eligius 4.2.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine-factory-65BHSli8.mjs","names":["forEach","when","addClass","addControllerToElement","addGlobalsToOperation","animate","animateWithClass","announceToScreenReader","breakForEach","broadcastEvent","calc","clearElement","clearOperationData","clearStorage","compareDate","concatenateStrings","continueForEach","SCHEME_PATTERN","FORBIDDEN_ATTRIBUTE_PATTERN","createElement","customFunction","endAction","endForEach","endWhen","extendController","filterArray","findInArray","formatDate","formatText","getAttributesFromElement","getControllerFromElement","getControllerInstance","getCurrentTime","getElementDimensions","getFocusedElement","getFormData","getImport","getQueryParams","getScrollPosition","getTextContent","httpDelete","httpPost","httpPut","invokeObjectMethod","isElementInViewport","loadFromStorage","loadJson","log","mapArray","math","otherwise","removeClass","removeControllerFromElement","removeElement","removePropertiesFromOperationData","reparentElement","replaceString","replaceText","requestAction","saveToStorage","scrollToElement","scrollToPosition","selectElement","setData","setElementAttributes","setElementContent","setFocus","setFormValue","setGlobalData","setOperationData","setStyle","setVariable","sortArray","splitString","startAction","substringText","toggleClass","toggleElement","toggleFormElement","validateForm","wait","DOMEventListenerController","KeyboardController","LabelController","LottieController","MutationObserverController","NavigationController","ProgressbarController","RoutingController","SubtitlesController","isClass","UNSAFE_KEYS","onceOriginals","isSeekable"],"sources":["../src/operation/helper/flow-control-names.ts","../src/operation/helper/flow-control-index.ts","../src/operation/helper/assert-safe-property-chain.ts","../src/operation/helper/chain-cache.ts","../src/util/guards/is-plain-object.ts","../src/operation/helper/deep-copy.ts","../src/operation/helper/globals.ts","../src/operation/helper/resolve-external-property-chain.ts","../src/operation/for-each.ts","../src/operation/helper/parse-operand.ts","../src/operation/helper/parse-expression.ts","../src/operation/helper/expression-cache.ts","../src/operation/helper/remove-operation-properties.ts","../src/operation/when.ts","../src/util/guards/is-promise.ts","../src/action/action.ts","../src/action/endable-action.ts","../src/action/timeline-action.ts","../src/adapters/engine-eventbus-adapter.ts","../src/util/keyboard-input-registry.ts","../src/adapters/engine-input-adapter.ts","../src/adapters/locale-eventbus-adapter.ts","../src/operation/add-class.ts","../src/operation/helper/get-element-data.ts","../src/operation/helper/attach-controller-to-element.ts","../src/operation/helper/merge-operation-data.ts","../src/operation/helper/internal-resolve.ts","../src/operation/add-controller-to-element.ts","../src/operation/add-globals-to-operation.ts","../src/operation/animate.ts","../src/operation/animate-with-class.ts","../src/operation/announce-to-screen-reader.ts","../src/operation/helper/loop-jump.ts","../src/operation/break-for-each.ts","../src/operation/helper/resolve-event-arguments.ts","../src/operation/broadcast-event.ts","../src/operation/helper/resolve-property-values.ts","../src/operation/calc.ts","../src/operation/helper/detach-controllers-within.ts","../src/operation/clear-element.ts","../src/operation/clear-operation-data.ts","../src/operation/clear-storage.ts","../src/operation/compare-date.ts","../src/operation/concatenate-strings.ts","../src/operation/continue-for-each.ts","../src/util/sanitize-html.ts","../src/operation/helper/assert-safe-attribute.ts","../src/operation/create-element.ts","../src/operation/helper/lookup-named-entry.ts","../src/util/guards/is-function.ts","../src/operation/custom-function.ts","../src/operation/end-action.ts","../src/operation/end-for-each.ts","../src/operation/end-when.ts","../src/operation/extend-controller.ts","../src/operation/filter-array.ts","../src/operation/find-in-array.ts","../src/operation/format-date.ts","../src/operation/format-text.ts","../src/operation/get-attributes-from-element.ts","../src/operation/get-controller-from-element.ts","../src/operation/get-controller-instance.ts","../src/operation/get-current-time.ts","../src/operation/helper/modify-dimensions.ts","../src/operation/get-element-dimensions.ts","../src/operation/get-focused-element.ts","../src/operation/get-form-data.ts","../src/operation/get-import.ts","../src/operation/get-query-params.ts","../src/operation/get-scroll-position.ts","../src/operation/get-text-content.ts","../src/operation/helper/read-json-body.ts","../src/operation/http-delete.ts","../src/operation/http-post.ts","../src/operation/http-put.ts","../src/operation/helper/get-property-chain-value.ts","../src/operation/invoke-object-method.ts","../src/operation/is-element-in-viewport.ts","../src/operation/load-from-storage.ts","../src/operation/load-json.ts","../src/operation/log.ts","../src/operation/map-array.ts","../src/util/guards/is-string.ts","../src/operation/math.ts","../src/operation/otherwise.ts","../src/operation/remove-class.ts","../src/operation/remove-controller-from-element.ts","../src/operation/remove-element.ts","../src/operation/remove-properties-from-operation-data.ts","../src/operation/reparent-element.ts","../src/operation/replace-string.ts","../src/operation/replace-text.ts","../src/operation/request-action.ts","../src/operation/save-to-storage.ts","../src/operation/scroll-to-element.ts","../src/operation/scroll-to-position.ts","../src/operation/select-element.ts","../src/operation/set-data.ts","../src/operation/set-element-attributes.ts","../src/operation/set-element-content.ts","../src/operation/set-focus.ts","../src/operation/set-form-value.ts","../src/operation/set-global-data.ts","../src/operation/set-operation-data.ts","../src/operation/set-style.ts","../src/operation/set-variable.ts","../src/operation/sort-array.ts","../src/operation/split-string.ts","../src/operation/start-action.ts","../src/operation/substring-text.ts","../src/operation/toggle-class.ts","../src/operation/toggle-element.ts","../src/operation/toggle-form-element.ts","../src/operation/validate-form.ts","../src/operation/wait.ts","../src/operation/metadata/add-class.ts","../src/operation/metadata/add-controller-to-element.ts","../src/operation/metadata/add-globals-to-operation.ts","../src/operation/metadata/animate-with-class.ts","../src/operation/metadata/animate.ts","../src/operation/metadata/announce-to-screen-reader.ts","../src/operation/metadata/break-for-each.ts","../src/operation/metadata/broadcast-event.ts","../src/operation/metadata/calc.ts","../src/operation/metadata/clear-element.ts","../src/operation/metadata/clear-operation-data.ts","../src/operation/metadata/clear-storage.ts","../src/operation/metadata/compare-date.ts","../src/operation/metadata/concatenate-strings.ts","../src/operation/metadata/continue-for-each.ts","../src/operation/metadata/create-element.ts","../src/operation/metadata/custom-function.ts","../src/operation/metadata/end-action.ts","../src/operation/metadata/end-for-each.ts","../src/operation/metadata/end-when.ts","../src/operation/metadata/extend-controller.ts","../src/operation/metadata/filter-array.ts","../src/operation/metadata/find-in-array.ts","../src/operation/metadata/for-each.ts","../src/operation/metadata/format-date.ts","../src/operation/metadata/format-text.ts","../src/operation/metadata/get-attributes-from-element.ts","../src/operation/metadata/get-controller-from-element.ts","../src/operation/metadata/get-controller-instance.ts","../src/operation/metadata/get-current-time.ts","../src/operation/metadata/get-element-dimensions.ts","../src/operation/metadata/get-focused-element.ts","../src/operation/metadata/get-form-data.ts","../src/operation/metadata/get-import.ts","../src/operation/metadata/get-query-params.ts","../src/operation/metadata/get-scroll-position.ts","../src/operation/metadata/get-text-content.ts","../src/operation/metadata/http-delete.ts","../src/operation/metadata/http-post.ts","../src/operation/metadata/http-put.ts","../src/operation/metadata/invoke-object-method.ts","../src/operation/metadata/is-element-in-viewport.ts","../src/operation/metadata/load-from-storage.ts","../src/operation/metadata/load-json.ts","../src/operation/metadata/log.ts","../src/operation/metadata/map-array.ts","../src/operation/metadata/math.ts","../src/operation/metadata/otherwise.ts","../src/operation/metadata/remove-class.ts","../src/operation/metadata/remove-controller-from-element.ts","../src/operation/metadata/remove-element.ts","../src/operation/metadata/remove-properties-from-operation-data.ts","../src/operation/metadata/reparent-element.ts","../src/operation/metadata/replace-string.ts","../src/operation/metadata/replace-text.ts","../src/operation/metadata/request-action.ts","../src/operation/metadata/save-to-storage.ts","../src/operation/metadata/scroll-to-element.ts","../src/operation/metadata/scroll-to-position.ts","../src/operation/metadata/select-element.ts","../src/operation/metadata/set-data.ts","../src/operation/metadata/set-element-attributes.ts","../src/operation/metadata/set-element-content.ts","../src/operation/metadata/set-focus.ts","../src/operation/metadata/set-form-value.ts","../src/operation/metadata/set-global-data.ts","../src/operation/metadata/set-operation-data.ts","../src/operation/metadata/set-style.ts","../src/operation/metadata/set-variable.ts","../src/operation/metadata/sort-array.ts","../src/operation/metadata/split-string.ts","../src/operation/metadata/start-action.ts","../src/operation/metadata/substring-text.ts","../src/operation/metadata/toggle-class.ts","../src/operation/metadata/toggle-element.ts","../src/operation/metadata/toggle-form-element.ts","../src/operation/metadata/validate-form.ts","../src/operation/metadata/wait.ts","../src/operation/metadata/when.ts","../src/operation/metadata/index.ts","../src/util/find-closest-names.ts","../src/controllers/metadata/dom-event-listener-controller.ts","../src/controllers/metadata/keyboard-controller.ts","../src/controllers/metadata/label-controller.ts","../src/controllers/metadata/lottie-controller.ts","../src/controllers/metadata/mutation-observer-controller.ts","../src/controllers/metadata/navigation-controller.ts","../src/controllers/metadata/progressbar-controller.ts","../src/controllers/metadata/routing-controller.ts","../src/controllers/metadata/subtitles-controller.ts","../src/controllers/metadata/index.ts","../src/configuration/timeline-provider-overrides.ts","../src/operation/helper/flow-control-structure.ts","../src/operation/helper/resolve-property-chain.ts","../src/util/guards/is-object.ts","../src/configuration/configuration-resolver.ts","../src/controllers/helper/controller-actions.ts","../src/controllers/dom-event-listener-controller.ts","../src/controllers/keyboard-controller.ts","../src/controllers/base-controller.ts","../src/controllers/label-controller.ts","../src/controllers/lottie-controller.ts","../src/controllers/mutation-observer-controller.ts","../src/controllers/helper/navigation-data.ts","../src/controllers/navigation-controller.ts","../src/controllers/progressbar-controller.ts","../src/controllers/routing-controller.ts","../src/controllers/subtitles-controller.ts","../src/eventbus/events/metadata/before-request-timeline-uri.ts","../src/eventbus/events/metadata/before-request-video-url.ts","../src/eventbus/events/metadata/dom-mutation.ts","../src/eventbus/events/metadata/engine-command-error.ts","../src/eventbus/events/metadata/engine-error.ts","../src/eventbus/events/metadata/highlight-navigation.ts","../src/eventbus/events/metadata/language-change.ts","../src/eventbus/events/metadata/navigate-to-video-url.ts","../src/eventbus/events/metadata/push-history-state.ts","../src/eventbus/events/metadata/request-current-language.ts","../src/eventbus/events/metadata/request-current-navigation.ts","../src/eventbus/events/metadata/request-current-timeline-position.ts","../src/eventbus/events/metadata/request-current-video-position.ts","../src/eventbus/events/metadata/request-label-collection.ts","../src/eventbus/events/metadata/request-label-collections.ts","../src/eventbus/events/metadata/request-timeline-cleanup.ts","../src/eventbus/events/metadata/request-timeline-uri.ts","../src/eventbus/events/metadata/request-translation.ts","../src/eventbus/events/metadata/request-video-cleanup.ts","../src/eventbus/events/metadata/request-video-url.ts","../src/eventbus/events/metadata/timeline-complete.ts","../src/eventbus/events/metadata/timeline-container-request.ts","../src/eventbus/events/metadata/timeline-current-timeline-change.ts","../src/eventbus/events/metadata/timeline-duration-request.ts","../src/eventbus/events/metadata/timeline-duration.ts","../src/eventbus/events/metadata/timeline-firstframe.ts","../src/eventbus/events/metadata/timeline-pause-request.ts","../src/eventbus/events/metadata/timeline-pause.ts","../src/eventbus/events/metadata/timeline-play-request.ts","../src/eventbus/events/metadata/timeline-play-toggle-request.ts","../src/eventbus/events/metadata/timeline-play.ts","../src/eventbus/events/metadata/timeline-request-current-timeline.ts","../src/eventbus/events/metadata/timeline-resize-request.ts","../src/eventbus/events/metadata/timeline-resize.ts","../src/eventbus/events/metadata/timeline-restart.ts","../src/eventbus/events/metadata/timeline-seek-request.ts","../src/eventbus/events/metadata/timeline-seek.ts","../src/eventbus/events/metadata/timeline-seeked.ts","../src/eventbus/events/metadata/timeline-stop-request.ts","../src/eventbus/events/metadata/timeline-stop.ts","../src/eventbus/events/metadata/timeline-time.ts","../src/eventbus/events/metadata/video-complete.ts","../src/eventbus/events/metadata/index.ts","../src/eventbus/actionregistry-eventbus-listener.ts","../src/eventbus/eventbus.ts","../src/eventbus/request-video-uri-interceptor.ts","../src/util/typed-event-emitter.ts","../src/eligius-engine.ts","../src/importer/registration-shape.ts","../src/importer/create-importer.ts","../src/timelineproviders/types.ts","../src/timelineproviders/position-sources/base-position-source.ts","../src/timelineproviders/position-sources/keyboard-step-source.ts","../src/util/animation-interval.ts","../src/timelineproviders/position-sources/raf-position-source.ts","../src/timelineproviders/position-sources/scroll-position-source.ts","../src/timelineproviders/position-sources/video-position-source.ts","../src/timelineproviders/container-providers/dom-container-provider.ts","../src/timelineproviders/playlist/simple-playlist.ts","../src/operation/metadata/parameter-types.ts","../src/engine-services.ts","../src/locale/locale-loader.ts","../src/locale/types.ts","../src/locale/locale-manager.ts","../src/engine-factory.ts"],"sourcesContent":["/**\n * System names of the control-flow operations, in one place so that the\n * operations and the flow-control scans can share them without importing\n * each other.\n */\nexport const whenSystemName = 'when';\nexport const otherwiseSystemName = 'otherwise';\nexport const endWhenSystemName = 'endWhen';\nexport const forEachSystemName = 'forEach';\nexport const endForEachSystemName = 'endForEach';\nexport const breakForEachSystemName = 'breakForEach';\nexport const continueForEachSystemName = 'continueForEach';\n","import type {IResolvedOperation} from '@configuration/types.ts';\nimport {\n endWhenSystemName,\n otherwiseSystemName,\n whenSystemName,\n} from '@operation/helper/flow-control-names.ts';\n\n/**\n * Forward scans over an operation list that find the end of a control-flow\n * block. They allocate nothing and are shared by `when`, `otherwise`,\n * `forEach` and the loop jumps, so every block boundary is found by one\n * algorithm.\n */\n\n/**\n * Finds the operation a false `when` continues at: the first `otherwise` or\n * `endWhen` at the same nesting depth after `start`. Only `when` and\n * `endWhen` change the depth.\n *\n * @param operations The operation list of the action\n * @param start The index the scan starts at (the operation after the `when`)\n * @returns The index of the `otherwise` or `endWhen`, or `operations.length`\n * when the block is not closed\n */\nexport function findNextFlowControlIndex(\n operations: readonly IResolvedOperation[],\n start: number\n): number {\n let depth = 0;\n for (let index = start; index < operations.length; index++) {\n const {systemName} = operations[index];\n if (systemName === whenSystemName) {\n depth++;\n } else if (systemName === endWhenSystemName) {\n if (depth === 0) {\n return index;\n }\n depth--;\n } else if (systemName === otherwiseSystemName && depth === 0) {\n return index;\n }\n }\n return operations.length;\n}\n\n/**\n * Finds the `close` operation that matches an `open` operation: the first\n * `close` at nesting depth zero after `start`, where every `open` seen on\n * the way opens one more level.\n *\n * @param operations The operation list of the action\n * @param start The index the scan starts at (the operation after the opener)\n * @param open The system name that opens a block, for example `when`\n * @param close The system name that closes it, for example `endWhen`\n * @returns The index of the matching `close`, or -1 when there is none\n */\nexport function findMatchingEndIndex(\n operations: readonly IResolvedOperation[],\n start: number,\n open: string,\n close: string\n): number {\n let depth = 0;\n for (let index = start; index < operations.length; index++) {\n const {systemName} = operations[index];\n if (systemName === open) {\n depth++;\n } else if (systemName === close) {\n if (depth === 0) {\n return index;\n }\n depth--;\n }\n }\n return -1;\n}\n","import type {IOperationScope} from '@operation/types.ts';\n\n/**\n * Property chain segments that lead to an object's prototype or constructor.\n * Reading or writing through them allows prototype pollution or reaching the\n * global `Function` constructor, so property chains may never contain them.\n */\nexport const forbiddenPropertyChainSegments: ReadonlySet<string> = new Set([\n '__proto__',\n 'prototype',\n 'constructor',\n]);\n\n/**\n * Returns true when the given segment is one of {@link forbiddenPropertyChainSegments}.\n */\nexport function isForbiddenPropertyChainSegment(segment: string): boolean {\n return forbiddenPropertyChainSegments.has(segment);\n}\n\n/**\n * Throws when any of the given segments is `__proto__`, `prototype` or `constructor`.\n *\n * A segment may carry a `+suffix` (as used by `getPropertyChainValue`); only the part\n * before the `+` is checked.\n *\n * @param segments The property chain segments to check.\n * @param propertyChain The chain as written in the configuration, used in the error message.\n * @param operationName The name of the operation resolving the chain, if known.\n * @throws When a forbidden segment is found. The message names the operation, the chain and the segment.\n */\nexport function assertSafePropertyChain(\n segments: readonly string[],\n propertyChain: string,\n operationName?: string\n): void {\n const forbidden = segments.find(segment =>\n isForbiddenPropertyChainSegment(segment.split('+')[0])\n );\n if (forbidden === undefined) {\n return;\n }\n\n const prefix = operationName\n ? `${operationName}: property chain`\n : 'Property chain';\n throw new Error(\n `${prefix} '${propertyChain}' contains forbidden segment '${forbidden.split('+')[0]}'. Property chains may not contain __proto__, prototype or constructor.`\n );\n}\n\n/**\n * Returns the system name of the operation the given scope is currently executing, if known.\n */\nexport function getCurrentOperationName(\n scope: IOperationScope | undefined\n): string | undefined {\n return scope?.operations?.[scope.currentIndex]?.systemName;\n}\n","import {isForbiddenPropertyChainSegment} from '@operation/helper/assert-safe-property-chain.ts';\n\n/**\n * Property chain parsing, shared by every helper that reads or writes a\n * chain, with a cache for the chains written in configuration.\n *\n * Before, every read of `$operationdata.items[2].label` split the text,\n * lower-cased the prefix, expanded the bracket index with a regular\n * expression, checked every segment for forbidden names and split the last\n * segment on `+`, on every execution. The chain text comes from the\n * configuration, so the parsed form is computed once and reused. Errors keep\n * their exact messages: they are built when they are thrown, from the parsed\n * chain and the name of the operation that is running.\n */\n\n/**\n * A property chain prepared for {@link walkChain}.\n */\nexport interface IParsedSegments {\n /** The segments after bracket expansion: `items[2].label` gives `['items', '2', 'label']` */\n segments: string[];\n /** `segments` joined with dots, as the error messages print the chain */\n chainText: string;\n /** The last segment without its `+suffix` */\n lastProperty: string;\n /** The text after the `+` of the last segment, or null when there is none */\n suffix: string | null;\n /** The first segment as written, before expansion */\n head: string;\n /** The first forbidden segment, with the chain text the error names */\n forbidden: {chainText: string; segment: string} | undefined;\n}\n\nexport type TChainPrefix = 'operationdata' | 'globaldata' | 'scope';\n\n/**\n * A parsed `$operationdata.`, `$globaldata.` or `$scope.` chain.\n */\nexport interface IParsedChain extends IParsedSegments {\n prefix: TChainPrefix;\n}\n\nconst bracketPattern = /\\[(\\d+)\\]/g;\n\n/**\n * Expands bracket indices into their own segments and drops empty segments,\n * so `items[2].label` and `items.2.label` resolve the same way.\n */\nexport function expandSegments(unexpanded: readonly string[]): string[] {\n const segments: string[] = [];\n for (const segment of unexpanded) {\n if (!segment.includes('[') && !segment.includes('.')) {\n if (segment.length > 0) {\n segments.push(segment);\n }\n continue;\n }\n for (const part of segment.replace(bracketPattern, '.$1').split('.')) {\n if (part.length > 0) {\n segments.push(part);\n }\n }\n }\n return segments;\n}\n\n/**\n * Returns the first segment whose name (before a `+suffix`) is forbidden.\n */\nexport function findForbiddenSegment(\n segments: readonly string[]\n): string | undefined {\n for (const segment of segments) {\n const name = segment.split('+')[0];\n if (isForbiddenPropertyChainSegment(name)) {\n return name;\n }\n }\n return undefined;\n}\n\n/**\n * Parses chain segments once.\n *\n * @param unexpanded The segments as written, split on dots\n * @param writtenChain The whole chain as written in the configuration. When\n * given, a forbidden segment found before expansion is reported with this\n * text; one found only after expansion is reported with the expanded chain.\n */\nexport function parseSegments(\n unexpanded: readonly string[],\n writtenChain?: string\n): IParsedSegments {\n let forbidden: IParsedSegments['forbidden'];\n if (writtenChain !== undefined) {\n const segment = findForbiddenSegment(unexpanded);\n if (segment !== undefined) {\n forbidden = {chainText: writtenChain, segment};\n }\n }\n const segments = expandSegments(unexpanded);\n const chainText = segments.join('.');\n if (forbidden === undefined) {\n const segment = findForbiddenSegment(segments);\n if (segment !== undefined) {\n forbidden = {chainText, segment};\n }\n }\n const last = segments.length > 0 ? segments[segments.length - 1] : '';\n const plus = last.indexOf('+');\n return {\n segments,\n chainText,\n lastProperty: plus >= 0 ? last.substring(0, plus) : last,\n suffix: plus >= 0 ? last.substring(plus + 1).split('+')[0] : null,\n head: unexpanded[0] ?? '',\n forbidden,\n };\n}\n\nfunction messagePrefix(operationName: string | undefined): string {\n return operationName ? `${operationName}: property chain` : 'Property chain';\n}\n\n/**\n * Throws when the parsed chain contains a forbidden segment.\n *\n * @throws Error naming the operation, the chain and the segment\n */\nexport function assertParsedChainSafe(\n parsed: IParsedSegments,\n operationName?: string\n): void {\n if (parsed.forbidden === undefined) {\n return;\n }\n throw new Error(\n `${messagePrefix(operationName)} '${parsed.forbidden.chainText}' contains forbidden segment '${parsed.forbidden.segment}'. Property chains may not contain __proto__, prototype or constructor.`\n );\n}\n\nfunction globalObjectError(\n operationName: string | undefined,\n parsed: IParsedSegments,\n index: number\n): Error {\n return new Error(\n `${messagePrefix(operationName)} '${parsed.chainText}' reaches the global object at '${parsed.segments\n .slice(0, index)\n .join('.')}'. Property chains may not access the global object.`\n );\n}\n\n/**\n * Returns true for the global object (`window`), including the window of another frame.\n */\nexport function isGlobalObject(value: unknown): boolean {\n return (\n value === globalThis ||\n (typeof value === 'object' &&\n value !== null &&\n Object.prototype.toString.call(value) === '[object Window]')\n );\n}\n\n/**\n * Reads a parsed chain from `sourceObject`.\n *\n * An empty chain returns `sourceObject`. Only null and undefined cannot be\n * indexed; `''`, `0` and `false` are valid intermediates. A `+suffix` on the\n * last segment is appended to the value; an empty suffix returns the value\n * as it is.\n *\n * @throws When an intermediate value is null or undefined (the message names\n * the part of the chain that did resolve), or when the chain passes through\n * or ends at the global object\n */\nexport function walkChain(\n parsed: IParsedSegments,\n sourceObject: Record<string, any>,\n operationName?: string\n): unknown {\n const {segments} = parsed;\n const count = segments.length;\n let current: any = sourceObject;\n for (let index = 0; index < count; index++) {\n if (current === null || current === undefined) {\n throw new Error(\n `${messagePrefix(operationName)} '${parsed.chainText}' cannot be resolved: '${segments\n .slice(0, index)\n .join('.')}' is ${current}.`\n );\n }\n if (index > 0 && isGlobalObject(current)) {\n throw globalObjectError(operationName, parsed, index);\n }\n current =\n current[index === count - 1 ? parsed.lastProperty : segments[index]];\n }\n if (count > 0 && isGlobalObject(current)) {\n throw globalObjectError(operationName, parsed, count);\n }\n return parsed.suffix ? `${current}${parsed.suffix}` : current;\n}\n\nconst prefixes: Record<string, TChainPrefix | undefined> = {\n '$operationdata.': 'operationdata',\n '$globaldata.': 'globaldata',\n '$scope.': 'scope',\n};\n\n/**\n * Returns the kind of external chain `value` is, or undefined when it is not\n * one. The prefix is matched without regard to case, like before.\n */\nexport function externalPrefixOf(value: string): TChainPrefix | undefined {\n if (value.charCodeAt(0) !== 36 /* $ */) {\n return undefined;\n }\n const dot = value.indexOf('.');\n if (dot < 0) {\n return undefined;\n }\n return prefixes[value.substring(0, dot + 1).toLocaleLowerCase()];\n}\n\n/**\n * The cache is cleared when it grows past this size, so chains built at\n * runtime cannot leak memory.\n */\nconst MAX_CACHED_CHAINS = 2000;\nconst parsedChains = new Map<string, IParsedChain>();\n\n/**\n * Returns the parsed form of an external property chain, parsing it on the\n * first use, or null when `value` is not an external chain.\n */\nexport function getParsedChain(value: string): IParsedChain | null {\n const cached = parsedChains.get(value);\n if (cached !== undefined) {\n return cached;\n }\n const prefix = externalPrefixOf(value);\n if (prefix === undefined) {\n return null;\n }\n const unexpanded = value.split('.');\n unexpanded.shift();\n const parsed: IParsedChain = {...parseSegments(unexpanded, value), prefix};\n if (parsedChains.size >= MAX_CACHED_CHAINS) {\n parsedChains.clear();\n }\n parsedChains.set(value, parsed);\n return parsed;\n}\n\n/**\n * Empties the chain cache. `EngineFactory` calls this when the last engine\n * is destroyed.\n */\nexport function clearChainCache(): void {\n parsedChains.clear();\n}\n","const functionToString = Function.prototype.toString;\n/** Source text of `Object`, the same in every realm */\nconst objectConstructorSource = functionToString.call(Object);\n\n/**\n * Returns true for plain data objects: object literals, parsed JSON objects\n * and `Object.create(null)` objects, also when they were created in another\n * realm (an iframe, a worker, the realm `fetch` parses JSON in). Returns false\n * for arrays, class instances, `Date`, `Map`, DOM nodes, jQuery objects and\n * objects that inherit from another object.\n *\n * @param value - Any value\n * @returns Whether `value` is a plain data object\n */\nexport function isPlainObject(\n value: unknown\n): value is Record<PropertyKey, unknown> {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype === null || prototype === Object.prototype) {\n return true;\n }\n // Another realm's Object.prototype: no prototype of its own, and its own\n // constructor is that realm's Object.\n if (Object.getPrototypeOf(prototype) !== null) {\n return false;\n }\n const objectConstructor = Object.hasOwn(prototype, 'constructor')\n ? prototype.constructor\n : undefined;\n return (\n typeof objectConstructor === 'function' &&\n functionToString.call(objectConstructor) === objectConstructorSource\n );\n}\n","import {isPlainObject} from '@util/guards/is-plain-object.ts';\n\nexport {isPlainObject};\n\nconst copyFunction =\n typeof structuredClone !== 'undefined'\n ? structuredClone\n : <T>(original: any) => JSON.parse(JSON.stringify(original)) as T;\n\n/**\n * Deep-copies plain data: arrays and plain objects are copied recursively (cycles are preserved),\n * Date, RegExp, Map, Set, Error, ArrayBuffer and typed arrays are cloned, and everything else\n * (functions, jQuery objects, DOM nodes, class instances) is kept by reference.\n *\n * An own `__proto__` key (as `JSON.parse` creates) stays an own data property of the copy.\n *\n * This runs for every execution of every operation with nested configured data, so it avoids\n * work on the common shapes: the cycle map is only created once a nested object or array\n * appears, and plain keys are assigned instead of defined.\n *\n * @param original The value to copy\n * @returns The copy, or the value itself when it is not copied\n */\nexport function deepCopy<T>(original: T): T {\n if (\n original === null ||\n typeof original !== 'object' ||\n isReferenceOnly(original)\n ) {\n return original;\n }\n return copyObject(original, {seen: null}) as T;\n}\n\ninterface ICopyContext {\n /**\n * Copies made so far, so that a cycle or a shared reference maps to one\n * copy. Created on the first nested object, because most configured data\n * is flat and never needs it.\n */\n seen: WeakMap<object, unknown> | null;\n}\n\n/**\n * Copies a child value of `parentValue`, whose copy is `parentCopy`.\n */\nfunction copyChild(\n child: unknown,\n parentValue: object,\n parentCopy: unknown,\n context: ICopyContext\n): unknown {\n // Primitives, functions, jQuery objects, DOM nodes: as-is.\n if (child === null || typeof child !== 'object' || isReferenceOnly(child)) {\n return child;\n }\n if (context.seen === null) {\n context.seen = new WeakMap();\n context.seen.set(parentValue, parentCopy);\n }\n return copyObject(child, context);\n}\n\n/**\n * Copies an object that is not reference-only.\n */\nfunction copyObject(value: object, context: ICopyContext): unknown {\n const {seen} = context;\n // Copies are always objects, so undefined means \"not seen\".\n const prior = seen?.get(value);\n if (prior !== undefined) {\n return prior;\n }\n\n if (Array.isArray(value)) {\n // Preallocated: the copy is filled index by index\n // oxlint-disable-next-line unicorn/no-new-array\n const copy: unknown[] = new Array(value.length);\n if (seen !== null) {\n seen.set(value, copy);\n }\n // forEach skips holes, so a sparse array stays sparse.\n value.forEach((item, index) => {\n copy[index] = copyChild(item, value, copy, context);\n });\n return copy;\n }\n\n if (isPlainObject(value)) {\n const copy: Record<string, unknown> = {};\n if (seen !== null) {\n seen.set(value, copy);\n }\n for (const key of Object.keys(value)) {\n const copied = copyChild(\n (value as Record<string, unknown>)[key],\n value,\n copy,\n context\n );\n if (key === '__proto__') {\n // defineProperty, so an own '__proto__' key (e.g. from JSON.parse) stays\n // a data property instead of replacing the copy's prototype.\n Object.defineProperty(copy, key, {\n value: copied,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n } else {\n copy[key] = copied;\n }\n }\n return copy;\n }\n\n if (!isStructuredCloneable(value)) {\n return value;\n }\n\n const copy = copyFunction(value);\n if (seen !== null) {\n seen.set(value, copy);\n }\n return copy;\n}\n\nfunction isReferenceOnly(value: object) {\n return (\n typeof (value as {jquery?: unknown}).jquery === 'string' ||\n (typeof Node !== 'undefined' && value instanceof Node)\n );\n}\n\nfunction isStructuredCloneable(value: object) {\n // Tags instead of instanceof, so values from another realm are recognised.\n return (\n cloneableTags.has(Object.prototype.toString.call(value)) ||\n ArrayBuffer.isView(value)\n );\n}\n\nconst cloneableTags = new Set([\n '[object Date]',\n '[object RegExp]',\n '[object Map]',\n '[object Set]',\n '[object Error]',\n '[object ArrayBuffer]',\n]);\n","import {isForbiddenPropertyChainSegment} from '@operation/helper/assert-safe-property-chain.ts';\nimport {deepCopy} from '@operation/helper/deep-copy.ts';\nexport type TGlobalCache = Record<string, any>;\n// No prototype, so a configured name can never read or replace inherited members.\nconst cache: TGlobalCache = Object.create(null);\n\nfunction _getGlobals(cache: TGlobalCache, name?: string): any {\n if (!name) {\n return cache;\n }\n const value = Object.hasOwn(cache, name) ? cache[name] : undefined;\n return value ? deepCopy(value) : value;\n}\n\nfunction _setGlobals(cache: TGlobalCache, newValues: TGlobalCache): void {\n Object.entries(newValues).forEach(([name, value]) => {\n assertSafeGlobalName(name, 'setGlobals');\n cache[name] = deepCopy(value);\n });\n}\n\nfunction _clearGlobals(cache: TGlobalCache): void {\n const keys = Object.keys(cache);\n keys.forEach(key => delete cache[key]);\n}\n\n/**\n * Throws when `name` is `__proto__`, `prototype` or `constructor`. Global names come from\n * configuration and are used as keys of the global store.\n *\n * @param name The global name to check.\n * @param operationName The operation or helper that uses the name, named in the error.\n * @throws When the name is forbidden.\n */\nexport function assertSafeGlobalName(name: string, operationName: string) {\n if (isForbiddenPropertyChainSegment(name)) {\n throw new Error(\n `${operationName}: global name '${name}' is not allowed. Names may not be __proto__, prototype or constructor.`\n );\n }\n}\n\n/**\n * Returns the global data store, or, given a name, a deep copy of the value stored under\n * that name (jQuery objects, DOM nodes, functions and class instances are returned by\n * reference, see `deepCopy`).\n *\n * Only own entries of the store are returned, so `getGlobals('constructor')` is `undefined`.\n */\nexport const getGlobals: (name?: string) => any = _getGlobals.bind(null, cache);\n\n/**\n * Stores deep copies of the given values in the global data store, so later in-place\n * changes to the operation data they came from do not change the store.\n *\n * @throws When a name is `__proto__`, `prototype` or `constructor`.\n */\nexport const setGlobals: (newValues: TGlobalCache) => void = _setGlobals.bind(\n null,\n cache\n);\n\n/**\n * Removes every value from the global data store that operations such as\n * `setGlobalData` and `addGlobalsToOperation` share.\n *\n * The store is shared by all engines on the page. `EngineFactory` clears it\n * when the last engine it created is destroyed; call this yourself to reset\n * it earlier, for example between tests.\n */\nexport const clearGlobals: () => void = _clearGlobals.bind(null, cache);\n","import {getCurrentOperationName} from '@operation/helper/assert-safe-property-chain.ts';\nimport {\n assertParsedChainSafe,\n externalPrefixOf,\n getParsedChain,\n walkChain,\n} from '@operation/helper/chain-cache.ts';\nimport {deepCopy} from '@operation/helper/deep-copy.ts';\nimport {getGlobals} from '@operation/helper/globals.ts';\nimport type {IOperationScope, TOperationData} from '@operation/types.ts';\n\n/**\n * Resolves operation and global data property chains.\n *\n * An operation data property chain is designated by a `operationdata.` suffix, followed by an arbitrary property chain.\n * For global data the suffix should be `globaldata.`\n *\n * If the propertyChainOrRegularObject is not a property chain, this value is returned instead.\n *\n * A `$globaldata` chain returns a deep copy of the global value (jQuery objects, DOM nodes,\n * functions and class instances stay references), the same as `getGlobals(name)`, so changing\n * the returned value in place never changes the shared global store. Write to the store with\n * `setGlobalData` or `setData` instead.\n *\n * The chain text is parsed once and cached (see `chain-cache.ts`); the value is read on every\n * call.\n */\nexport function resolveExternalPropertyChain(\n sourceObject: TOperationData,\n operationScope: IOperationScope,\n propertyChainOrRegularObject:\n | ExternalProperty\n | Record<string, any>\n | null\n | undefined\n) {\n if (\n propertyChainOrRegularObject === null ||\n propertyChainOrRegularObject === undefined\n ) {\n return null;\n }\n\n if (typeof propertyChainOrRegularObject !== 'string') {\n return propertyChainOrRegularObject;\n }\n\n const parsed = getParsedChain(propertyChainOrRegularObject);\n if (parsed === null) {\n return propertyChainOrRegularObject;\n }\n\n const operationName = getCurrentOperationName(operationScope);\n assertParsedChainSafe(parsed, operationName);\n switch (parsed.prefix) {\n case 'operationdata':\n return walkChain(parsed, sourceObject, operationName);\n case 'globaldata':\n return deepCopy(walkChain(parsed, getGlobals(), operationName));\n case 'scope':\n return walkChain(\n parsed,\n findDeclaringScope(parsed.head, operationScope) ?? operationScope,\n operationName\n );\n }\n}\n\n/**\n * Resolves a `$scope` property chain, walking up the parent scope chain.\n *\n * `forEach` and `when` execute in a child scope created by `Action._pushScope`,\n * which proxies only a few fields from its parent. A variable set with\n * `setVariable` lives on the scope that declares `variables` (the action's root\n * scope), not on the child scope an operation inside a loop or conditional runs\n * in.\n *\n * The chain is resolved against the nearest scope (the current one or an\n * ancestor) that declares the chain's head property, see\n * {@link findDeclaringScope}. `setVariable` and `setData` pick their write\n * target with the same rule, so reads and writes of `$scope.variables.*` always\n * meet on the same scope object.\n *\n * @param head The first segment of the chain as written, for example `variables`\n * @param scope The scope the operation runs in\n * @returns The nearest scope that has `head` as an own or inherited property, or undefined\n */\nexport function findDeclaringScope(\n head: string,\n scope: IOperationScope\n): IOperationScope | undefined {\n let current: IOperationScope | undefined = scope;\n while (current) {\n if (head in current) {\n return current;\n }\n current = current.parent;\n }\n return undefined;\n}\n\n/**\n * Returns the outermost scope of the given scope's parent chain: the\n * action's root scope.\n */\nexport function findRootScope(scope: IOperationScope): IOperationScope {\n let current = scope;\n while (current.parent) {\n current = current.parent;\n }\n return current;\n}\n\n/**\n * Returns true when the value is a `$operationdata.`, `$globaldata.` or\n * `$scope.` property chain. The prefix is matched without regard to case.\n */\nexport function isExternalProperty(\n value: ExternalProperty | Record<string, any>\n): value is ExternalProperty {\n return typeof value === 'string' && externalPrefixOf(value) !== undefined;\n}\n\nexport type ExternalProperty =\n | `$operationdata.${string}`\n | `$globaldata.${string}`\n | `$scope.${string}`;\n","// oxlint-disable no-unused-vars -- referenced by {@link} in the docs below\nimport type {breakForEach} from '@operation/break-for-each.ts';\nimport type {continueForEach} from '@operation/continue-for-each.ts';\n// oxlint-enable no-unused-vars\nimport {findMatchingEndIndex} from '@operation/helper/flow-control-index.ts';\nimport {\n endForEachSystemName,\n forEachSystemName,\n} from '@operation/helper/flow-control-names.ts';\nimport {\n type ExternalProperty,\n resolveExternalPropertyChain,\n} from '@operation/helper/resolve-external-property-chain.ts';\nimport type {IOperationScope, TOperation} from '@operation/types.ts';\n\nexport interface IForEachOperationData {\n /**\n * @type=ParameterType:array|ParameterType:string\n * @required\n */\n collection: unknown[] | string;\n}\n\n/**\n * This operation iterates over the given collection.\n *\n * Each iteration the current item from the specified collection is\n * assigned to the {@link IOperationScope.currentItem|currentItem} property on the {@link IOperationScope|operation scope}.\n *\n * At the start of the loop, the associated {@link endForEach} operation is determined and when\n * the last iteration is completed the flow control is set to the index of that operation.\n *\n * The {@link continueForEach|continue} and {@link breakForEach|break} operations can be used to control the\n * loop iterations.\n *\n * The collection is resolved once, when the loop starts, and the loop iterates over a snapshot\n * of it. Changing, replacing or removing the source collection inside the loop body does not\n * change the items or the number of iterations of the running loop.\n *\n * @category Control Flow\n */\nexport const forEach: TOperation<IForEachOperationData> = function (\n operationData: IForEachOperationData\n) {\n // First iteration of the loop\n if (this.loopIndex === undefined) {\n const resolvedCollection = resolveCollection(\n operationData.collection,\n operationData,\n this\n );\n this.loopEndIndex = findEndForEachIndex(this);\n if (resolvedCollection?.length) {\n this.loopIndex = 0;\n this.loopLength = resolvedCollection.length - 1;\n this.loopStartIndex = this.currentIndex;\n // A shallow copy, so changes to the source array inside the loop body do\n // not change the items of the running loop either.\n loopCollections.set(this, resolvedCollection.slice());\n } else {\n this.newIndex = this.loopEndIndex;\n\n delete this.loopIndex;\n delete this.loopLength;\n delete this.loopStartIndex;\n delete this.loopEndIndex;\n loopCollections.delete(this);\n }\n }\n\n const snapshot = loopCollections.get(this);\n if (snapshot && this.loopIndex !== undefined) {\n this.currentItem = snapshot[this.loopIndex];\n }\n\n return operationData;\n};\n\n/**\n * The collection each running loop iterates over, keyed by the loop's scope.\n */\nconst loopCollections = new WeakMap<IOperationScope, unknown[]>();\n\n/**\n * Forgets the collection snapshot of the loop that runs in the given scope.\n * Called when the loop finishes or breaks.\n *\n * @param scope The loop's scope.\n */\nexport function clearLoopCollection(scope: IOperationScope): void {\n loopCollections.delete(scope);\n}\n\nfunction resolveCollection(\n collection: IForEachOperationData['collection'],\n operationData: IForEachOperationData,\n scope: IOperationScope\n): unknown[] | null | undefined {\n const resolvedCollection =\n typeof collection === 'string'\n ? (resolveExternalPropertyChain(\n operationData,\n scope,\n collection as ExternalProperty\n ) as unknown[] | null | undefined)\n : collection;\n\n if (\n resolvedCollection !== null &&\n resolvedCollection !== undefined &&\n !Array.isArray(resolvedCollection)\n ) {\n throw new Error(\n 'forEach: Expected resolved collection property to be array type, string value was probably not resolved correctly'\n );\n }\n return resolvedCollection;\n}\n\nfunction findEndForEachIndex(scope: IOperationScope) {\n const index = findMatchingEndIndex(\n scope.operations,\n scope.currentIndex + 1,\n forEachSystemName,\n endForEachSystemName\n );\n return index > -1 ? index : scope.operations.length;\n}\n\nexport {endForEachSystemName, forEachSystemName};\n","import {\n type ExternalProperty,\n isExternalProperty,\n resolveExternalPropertyChain,\n} from '@operation/helper/resolve-external-property-chain.ts';\nimport type {IOperationScope, TOperationData} from '@operation/types.ts';\n\n/**\n * A parsed expression operand: either a literal value or a property chain that is\n * resolved when the expression is evaluated.\n */\nexport type TOperand =\n | {kind: 'literal'; value: string | number | boolean | null}\n | {kind: 'chain'; chain: ExternalProperty};\n\nconst numberPattern = /^[-+]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?$/;\nconst quotedPattern = /^'(.*)'$/s;\n// After the prefix: one or more segments separated by single dots, without\n// whitespace or quotes. Segments may use bracket indices and a '+suffix'.\nconst chainPattern =\n /^\\$(operationdata|globaldata|scope)\\.[^\\s.'\"]+(\\.[^\\s.'\"]+)*$/i;\n\nconst keywords: Record<string, boolean | null> = {\n true: true,\n false: false,\n null: null,\n};\n\n/**\n * Parses one operand of a condition expression. The tokenizer in `parse-expression.ts`\n * calls it for every operand it finds, so this function is the single definition of the\n * operand grammar.\n *\n * The operand grammar:\n * - a number: `100`, `-1.5`, `2e3` (the whole token must be numeric, so `10px` is invalid);\n * - a string in single quotes: `'John'`;\n * - the keywords `true`, `false` and `null`;\n * - a property chain starting with `$operationdata.`, `$globaldata.` or `$scope.` (the prefix\n * is case-insensitive), for example `$scope.variables.count`.\n *\n * @param token The operand text, already trimmed.\n * @param operationName The operation parsing the expression, named in the error.\n * @param expression The whole expression, quoted in the error.\n * @param position The 0-based position of the operand in the expression, named in the error\n * when given.\n * @returns The parsed operand.\n * @throws When the token matches none of the forms above.\n */\nexport function parseOperand(\n token: string,\n operationName: string,\n expression: string,\n position?: number\n): TOperand {\n const quoted = quotedPattern.exec(token);\n if (quoted) {\n return {kind: 'literal', value: quoted[1]};\n }\n if (Object.hasOwn(keywords, token)) {\n return {kind: 'literal', value: keywords[token]};\n }\n if (numberPattern.test(token)) {\n return {kind: 'literal', value: Number(token)};\n }\n if (\n isExternalProperty(token as ExternalProperty) &&\n chainPattern.test(token)\n ) {\n return {kind: 'chain', chain: token as ExternalProperty};\n }\n throw new Error(\n `${operationName}: unknown operand '${token}' in expression '${expression}'${position === undefined ? '' : ` at position ${position}`}. Use a number, a quoted string ('text'), true, false, null, or a property chain starting with $operationdata., $globaldata. or $scope.`\n );\n}\n\n/**\n * Returns the value of a parsed operand, resolving a property chain against the given\n * operation data and scope.\n *\n * @param operand The operand returned by {@link parseOperand}.\n * @param operationData The operation data `$operationdata` chains are resolved against.\n * @param scope The scope `$scope` chains are resolved against.\n * @returns The operand's value.\n */\nexport function resolveOperand(\n operand: TOperand,\n operationData: TOperationData,\n scope: IOperationScope\n): unknown {\n return operand.kind === 'literal'\n ? operand.value\n : resolveExternalPropertyChain(operationData, scope, operand.chain);\n}\n","import {\n parseOperand,\n resolveOperand,\n type TOperand,\n} from '@operation/helper/parse-operand.ts';\nimport type {IOperationScope, TOperationData} from '@operation/types.ts';\n\n/**\n * The comparison operators a condition expression supports.\n */\nexport type TComparisonOperator = '==' | '!=' | '>=' | '<=' | '>' | '<';\n\n/**\n * A node of a parsed condition expression, see {@link parseExpression}.\n */\nexport type TExpressionNode =\n | {kind: 'operand'; operand: TOperand}\n | {kind: 'not'; operand: TExpressionNode}\n | {kind: 'and' | 'or'; left: TExpressionNode; right: TExpressionNode}\n | {\n kind: 'comparison';\n operator: TComparisonOperator;\n left: TExpressionNode;\n right: TExpressionNode;\n };\n\ntype TSymbol = TComparisonOperator | '&&' | '||' | '!' | '(' | ')';\n\ntype TToken =\n | {type: 'symbol'; text: TSymbol; position: number}\n | {type: 'operand'; text: string; position: number; operand: TOperand};\n\n// Longest first, so '!=' is not read as '!' followed by '=', and '>=' not as '>' and '='.\nconst symbols: readonly TSymbol[] = [\n '&&',\n '||',\n '==',\n '!=',\n '>=',\n '<=',\n '>',\n '<',\n '!',\n '(',\n ')',\n];\n\nconst comparisonOperators: ReadonlySet<string> = new Set<TComparisonOperator>([\n '==',\n '!=',\n '>=',\n '<=',\n '>',\n '<',\n]);\n\n// Characters that end an unquoted operand.\nconst delimiterPattern = /[\\s()!=<>&|]/;\n\nfunction isDelimiter(char: string | undefined): boolean {\n return char === undefined || delimiterPattern.test(char);\n}\n\n/**\n * Parses a condition expression into a tree that {@link evaluateExpression} evaluates.\n *\n * The grammar, from lowest to highest precedence:\n *\n * ```\n * or := and ('||' and)*\n * and := comparison ('&&' comparison)*\n * comparison := unary (('==' | '!=' | '>=' | '<=' | '>' | '<') unary)?\n * unary := '!' unary | primary\n * primary := '(' or ')' | operand\n * ```\n *\n * Operands are parsed by {@link parseOperand}: numbers, single-quoted strings, `true`,\n * `false`, `null` and `$operationdata.`, `$globaldata.` or `$scope.` property chains.\n * Inside a quoted string, operators and parentheses are part of the text. A quote ends the\n * string only when it is followed by whitespace, an operator, a parenthesis or the end of the\n * expression, so an apostrophe inside the text (`'it's'`) needs no escaping.\n *\n * Comparisons do not chain (`1<x<3` is an error, write `1<x && x<3`). Arithmetic is not\n * supported. Nothing in the expression is executed as code.\n *\n * @param expression The expression text.\n * @param operationName The operation parsing the expression, named in the error messages.\n * @returns The root node of the parsed expression.\n * @throws When the expression is not a string or is empty, contains an unknown operand, an\n * unterminated string, an unknown or misplaced operator, or unbalanced parentheses. The message\n * names the operation, the problem, its position (0-based) and the expression.\n *\n * @example\n * parseExpression(\"$scope.variables.score>=5 && !$operationdata.skipped\", 'when');\n */\nexport function parseExpression(\n expression: string,\n operationName: string\n): TExpressionNode {\n if (typeof expression !== 'string') {\n throw new Error(\n `${operationName}: expression must be a string, received ${expression === null ? 'null' : typeof expression}.`\n );\n }\n\n const tokens = tokenize(expression, operationName);\n if (!tokens.length) {\n throw new Error(`${operationName}: empty expression '${expression}'.`);\n }\n\n let index = 0;\n\n const fail = (message: string, position: number, hint?: string): never => {\n throw new Error(\n `${operationName}: ${message} at position ${position} in expression '${expression}'.${hint ? ` ${hint}` : ''}`\n );\n };\n\n const unexpected = (token: TToken | undefined, hint?: string): never =>\n token\n ? fail(`unexpected '${token.text}'`, token.position, hint)\n : fail('unexpected end of expression', expression.length, hint);\n\n const peekSymbol = (): TSymbol | undefined => {\n const token = tokens[index];\n return token?.type === 'symbol' ? token.text : undefined;\n };\n\n const parseOr = (): TExpressionNode => {\n let left = parseAnd();\n while (peekSymbol() === '||') {\n index++;\n left = {kind: 'or', left, right: parseAnd()};\n }\n return left;\n };\n\n const parseAnd = (): TExpressionNode => {\n let left = parseComparison();\n while (peekSymbol() === '&&') {\n index++;\n left = {kind: 'and', left, right: parseComparison()};\n }\n return left;\n };\n\n const parseComparison = (): TExpressionNode => {\n const left = parseUnary();\n const operator = peekSymbol();\n if (operator && comparisonOperators.has(operator)) {\n index++;\n return {\n kind: 'comparison',\n operator: operator as TComparisonOperator,\n left,\n right: parseUnary(),\n };\n }\n return left;\n };\n\n const parseUnary = (): TExpressionNode => {\n if (peekSymbol() === '!') {\n index++;\n return {kind: 'not', operand: parseUnary()};\n }\n return parsePrimary();\n };\n\n const parsePrimary = (): TExpressionNode => {\n const token = tokens[index];\n if (token?.type === 'operand') {\n index++;\n return {kind: 'operand', operand: token.operand};\n }\n if (token?.text === '(') {\n index++;\n const node = parseOr();\n const closing = tokens[index];\n if (!closing) {\n return fail(\"missing ')' for the '('\", token.position);\n }\n if (closing.text !== ')') {\n return unexpected(closing, \"Expected ')' or an operator.\");\n }\n index++;\n return node;\n }\n return unexpected(token);\n };\n\n const root = parseOr();\n if (index < tokens.length) {\n const token = tokens[index];\n const hint =\n token.text === ')'\n ? \"It has no matching '('.\"\n : token.type === 'symbol' && comparisonOperators.has(token.text)\n ? 'Comparisons do not chain, combine them with && or use parentheses.'\n : 'Expected && or || between the parts of the condition.';\n unexpected(token, hint);\n }\n return root;\n}\n\n/**\n * Splits the expression into symbols and operands. Operands are parsed with\n * {@link parseOperand}, so the operand grammar has one source.\n */\nfunction tokenize(expression: string, operationName: string): TToken[] {\n const tokens: TToken[] = [];\n let i = 0;\n while (i < expression.length) {\n const char = expression[i];\n\n if (/\\s/.test(char)) {\n i++;\n continue;\n }\n\n const symbol = symbols.find(s => expression.startsWith(s, i));\n if (symbol) {\n tokens.push({type: 'symbol', text: symbol, position: i});\n i += symbol.length;\n continue;\n }\n\n if (char === '=' || char === '&' || char === '|') {\n throw new Error(\n `${operationName}: unexpected '${char}' at position ${i} in expression '${expression}'. Did you mean '${char}${char}'?`\n );\n }\n\n const end =\n char === \"'\" ? endOfString(expression, i) : endOfWord(expression, i);\n if (end < 0) {\n throw new Error(\n `${operationName}: unterminated string at position ${i} in expression '${expression}'.`\n );\n }\n\n const text = expression.substring(i, end);\n tokens.push({\n type: 'operand',\n text,\n position: i,\n operand: parseOperand(text, operationName, expression, i),\n });\n i = end;\n }\n return tokens;\n}\n\n/**\n * Returns the index after the quote that closes the string starting at `start`, or -1 when the\n * string is not closed. A quote closes the string only when a delimiter or the end follows it.\n */\nfunction endOfString(expression: string, start: number): number {\n for (let i = start + 1; i < expression.length; i++) {\n if (expression[i] === \"'\" && isDelimiter(expression[i + 1])) {\n return i + 1;\n }\n }\n return -1;\n}\n\nfunction endOfWord(expression: string, start: number): number {\n let i = start;\n while (i < expression.length && !isDelimiter(expression[i])) {\n i++;\n }\n return i;\n}\n\n/**\n * Evaluates a parsed condition expression.\n *\n * `&&` and `||` short-circuit: the right side is not resolved when the left side already\n * decides the result, so a property chain on the right that cannot be resolved is not read.\n * `&&`, `||` and `!` work on truthiness and produce `true` or `false`. A bare operand is\n * tested for truthiness. Comparisons work as before: `==` and `!=` compare strictly,\n * `<`, `<=`, `>` and `>=` use JavaScript ordering.\n *\n * @param node The expression returned by {@link parseExpression}.\n * @param operationData The operation data `$operationdata` chains are resolved against.\n * @param scope The scope `$scope` chains are resolved against.\n * @returns Whether the expression is true.\n * @throws When a property chain that is evaluated cannot be resolved or is not allowed.\n */\nexport function evaluateExpression(\n node: TExpressionNode,\n operationData: TOperationData,\n scope: IOperationScope\n): boolean {\n return Boolean(evaluateNode(node, operationData, scope));\n}\n\nfunction evaluateNode(\n node: TExpressionNode,\n operationData: TOperationData,\n scope: IOperationScope\n): unknown {\n switch (node.kind) {\n case 'operand':\n return resolveOperand(node.operand, operationData, scope);\n case 'not':\n return !evaluateNode(node.operand, operationData, scope);\n case 'and':\n return (\n Boolean(evaluateNode(node.left, operationData, scope)) &&\n Boolean(evaluateNode(node.right, operationData, scope))\n );\n case 'or':\n return (\n Boolean(evaluateNode(node.left, operationData, scope)) ||\n Boolean(evaluateNode(node.right, operationData, scope))\n );\n case 'comparison':\n return comparisons[node.operator](\n evaluateNode(node.left, operationData, scope),\n evaluateNode(node.right, operationData, scope)\n );\n }\n}\n\nconst comparisons: Record<\n TComparisonOperator,\n (left: any, right: any) => boolean\n> = {\n '==': (left, right) => left === right,\n '!=': (left, right) => left !== right,\n '>=': (left, right) => left >= right,\n '<=': (left, right) => left <= right,\n '>': (left, right) => left > right,\n '<': (left, right) => left < right,\n};\n","import {\n parseExpression,\n type TExpressionNode,\n} from '@operation/helper/parse-expression.ts';\n\n/**\n * Parsed condition expressions, keyed by operation name and expression text.\n *\n * A `when` operation parses its expression on every execution; the text comes\n * from the configuration, so the same handful of expressions is parsed again\n * and again. The parsed tree is never mutated, so it can be shared. Parse\n * errors are not cached: the operation throws them on every execution, as\n * before.\n */\nconst parsedExpressions = new Map<string, TExpressionNode>();\n\n/**\n * The cache is cleared when it grows past this size, so unbounded dynamic\n * expressions cannot leak memory.\n */\nconst MAX_CACHED_EXPRESSIONS = 1000;\n\n/**\n * Returns the parsed tree for `expression`, parsing it on the first use.\n *\n * @param expression The expression text, as `parseExpression` takes it\n * @param operationName The operation parsing the expression, named in error messages\n * @returns The parsed expression, shared between calls\n * @throws The `parseExpression` error for an invalid expression\n */\nexport function getParsedExpression(\n expression: string,\n operationName: string\n): TExpressionNode {\n if (typeof expression !== 'string') {\n return parseExpression(expression, operationName);\n }\n const key = `${operationName}\\u0000${expression}`;\n const cached = parsedExpressions.get(key);\n if (cached !== undefined) {\n return cached;\n }\n const parsed = parseExpression(expression, operationName);\n if (parsedExpressions.size >= MAX_CACHED_EXPRESSIONS) {\n parsedExpressions.clear();\n }\n parsedExpressions.set(key, parsed);\n return parsed;\n}\n\n/**\n * Empties the expression cache. `EngineFactory` calls this when the last\n * engine is destroyed.\n */\nexport function clearExpressionCache(): void {\n parsedExpressions.clear();\n}\n","/**\n * Removes specified properties from an operation data object.\n * This is a helper function to eliminate repetitive property deletion code across operations.\n *\n * @template T - The type of the operation data object\n * @template K - The keys to remove from the object (must be keys of T)\n * @param operationData - The operation data object to mutate\n * @param keys - The property keys to delete from the object\n * @returns The mutated operation data object with specified properties removed (typed as Omit<T, K>)\n *\n * @example\n * ```typescript\n * interface IMyOperationData {\n * selectedElement: JQuery;\n * animationDuration: number;\n * animationEasing: string;\n * }\n *\n * const data: IMyOperationData = {\n * selectedElement: $element,\n * animationDuration: 500,\n * animationEasing: 'ease-in'\n * };\n *\n * // Remove multiple properties at once\n * const result = removeProperties(data, 'animationDuration', 'animationEasing');\n * // result is typed as Omit<IMyOperationData, 'animationDuration' | 'animationEasing'>\n * // result = { selectedElement: $element }\n * ```\n */\nexport function removeProperties<T extends object, K extends keyof T>(\n operationData: T,\n ...keys: K[]\n): Omit<T, K> {\n for (const key of keys) {\n delete (operationData as any)[key];\n }\n return operationData as Omit<T, K>;\n}\n","import {getParsedExpression} from '@operation/helper/expression-cache.ts';\nimport {findNextFlowControlIndex} from '@operation/helper/flow-control-index.ts';\nimport {evaluateExpression} from '@operation/helper/parse-expression.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport {\n endWhenSystemName,\n otherwiseSystemName,\n whenSystemName,\n} from '@operation/helper/flow-control-names.ts';\n\n/**\n * A condition expression, see {@link when} for the grammar.\n */\ntype TExpression = string;\n\nexport interface IWhenOperationData {\n /**\n * @type=ParameterType:expression\n * @required\n * @erased\n */\n expression: TExpression;\n}\n\n/**\n * When the given expression evaluates to false, subsequent operations will be skipped\n * until an {@link endWhen} or {@link otherwise} operation is encountered.\n *\n * Practically, this means an `if` or `if`/`else` statement control flow implementation in a list of operations.\n *\n * The expression is passed in as a formatted string. An operand can be one of:\n *\n * 'constant': for a constant string (operators and parentheses inside the quotes are text)\n * 100: for a constant number (the whole operand must be numeric, `10px` is invalid)\n * true, false, null: for a boolean or null constant\n * $operationData.foo: for an operation data value\n * $globaldata.foo: for a global data value\n * $scope.loopIndex: for a scope value\n * $scope.variables.foo: for a variable set with `setVariable`\n *\n * Any other operand is an error, so a misspelled chain prefix fails instead of being compared\n * as a string.\n *\n * Operands are combined with these operators, from highest to lowest precedence:\n *\n * `!`: negation\n * `==`, `!=`, `>`, `<`, `>=`, `<=`: comparison (`==` and `!=` compare strictly, without type\n * conversion; comparisons do not chain, so write `0<$scope.loopIndex && $scope.loopIndex<5`)\n * `&&`: and\n * `||`: or\n *\n * Parentheses group. A bare operand is true when its value is truthy, so `'false'` and `'0'`\n * are true and `0`, `''`, `null` and a missing value are false. `!`, `&&` and `||` always\n * produce `true` or `false`. `!` binds tighter than a comparison: `!$operationdata.a==1`\n * compares `!$operationdata.a` with 1, write `!($operationdata.a==1)` to negate the comparison.\n * `&&` and `||` short-circuit: when the left side decides the result, the right side is not\n * resolved, so `$operationdata.user && $operationdata.user.name=='John'` does not fail when\n * `user` is missing.\n *\n * Arithmetic (`+`, `-`, `*`, `/`) is not supported: `-` is a valid character in a property\n * chain, so `$operationdata.a-1` would be ambiguous. Nothing in the expression is executed as\n * code, and property chains are resolved with the usual prototype-pollution and global-object\n * guards.\n *\n * @example\n * $scope.variables.foo=='bar'\n * @example\n * $operationdata.isValid==true\n * @example\n * $globalData.foo>$scope.variables.bar\n * @example\n * $operationData.foo!=100\n * @example\n * $scope.variables.position>=10 && $scope.variables.position<12\n * @example\n * ($scope.variables.answered && $scope.variables.score>=5) || $scope.variables.skipped\n * @example\n * !$operationdata.isHidden\n * @example\n * $operationdata.label=='a && b' || $operationdata.label=='(none)'\n *\n * @param operationData\n * @returns\n * @throws When the expression is not a string or is empty, an operand is not one of the forms\n * above, a string is not closed, an operator is unknown or misplaced, or parentheses do not\n * balance. The message names the problem, its 0-based position and the expression, for example\n * `when: unexpected ')' at position 4 in expression '1==1)'.`\n *\n * @category Control Flow\n */\nexport const when: TOperation<\n IWhenOperationData,\n Omit<IWhenOperationData, 'expression'>\n> = function (operationData: IWhenOperationData) {\n // The expression text comes from the configuration, so the parsed tree is\n // cached and shared between executions.\n const condition = getParsedExpression(operationData.expression, 'when');\n const evaluation = evaluateExpression(condition, operationData, this);\n\n removeProperties(operationData, 'expression');\n\n this.whenEvaluation = evaluation;\n\n if (!this.whenEvaluation) {\n // The `otherwise` or `endWhen` that belongs to this `when`, skipping\n // nested when/otherwise/endWhen blocks.\n this.newIndex = findNextFlowControlIndex(\n this.operations,\n this.currentIndex + 1\n );\n }\n\n return operationData;\n};\n","/**\n * Returns true for promises and other thenables.\n *\n * @param obj - Any value\n * @returns Whether `obj` is an object with a `then` method\n */\nexport function isPromise(obj: any): obj is Promise<unknown> {\n return (\n typeof obj === 'object' && obj !== null && typeof obj.then === 'function'\n );\n}\n","import type {IAction} from '@action/types.ts';\nimport type {IResolvedOperation} from '@configuration/types.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\nimport {endForEachSystemName, forEachSystemName} from '@operation/for-each.ts';\nimport {deepCopy} from '@operation/helper/deep-copy.ts';\nimport type {IOperationScope, TOperationData} from '@operation/types.ts';\nimport {endWhenSystemName, whenSystemName} from '@operation/when.ts';\nimport {isPlainObject} from '@util/guards/is-plain-object.ts';\nimport {isPromise} from '@util/guards/is-promise.ts';\nimport type {IEngineServices} from '@/engine-services.ts';\n\nexport class Action implements IAction {\n public id = '';\n /**\n * Scope stack used by {@link executeOperation} when it is called without an\n * explicit stack. `start()` and `end()` each create their own stack, so\n * overlapping executions of the same action never share scopes.\n *\n * @deprecated Calling {@link executeOperation} without a scope stack is\n * deprecated; this fallback will be removed in the next major version.\n */\n protected _scopeStack: IOperationScope[] = [];\n /**\n * The configured `forEach` operation data copied when a loop starts, keyed\n * by the loop's scope. Later iterations of the same loop merge this copy\n * again instead of deep-copying the collection on every iteration.\n */\n private _loopOperationData = new WeakMap<IOperationScope, TOperationData>();\n\n constructor(\n public name: string,\n public startOperations: IResolvedOperation[],\n protected eventbus: IEventbus,\n protected services: IEngineServices\n ) {}\n\n /**\n * Runs the start operations.\n *\n * A failure is not logged here: the returned promise rejects with the\n * error (annotated with the failing operation), and the caller reports it.\n * The engine reports it through its `error` event, the eventbus through\n * its `onHandlerError` option, and `init()` by rejecting.\n *\n * @param initOperationData - Operation data the first start operation receives\n * @returns The operation data of the last start operation\n */\n start(initOperationData?: TOperationData): Promise<TOperationData> {\n return this._runOperations(this.startOperations, initOperationData);\n }\n\n /**\n * Runs the given operations with a scope stack that belongs to this\n * execution only.\n *\n * @param operations - The operations to run\n * @param initOperationData - Operation data the first operation receives\n * @param onSettled - Called the moment the operations have completed or\n * failed, before the returned promise settles. Operations that complete\n * synchronously call it synchronously.\n * @returns The operation data of the last operation\n */\n protected _runOperations(\n operations: IResolvedOperation[],\n initOperationData?: TOperationData,\n onSettled?: () => void\n ): Promise<TOperationData> {\n const scopeStack = this._createScopeStack(operations);\n\n return new Promise<TOperationData>((resolve, reject) => {\n this.executeOperation(\n operations,\n 0,\n onSettled\n ? value => {\n onSettled();\n resolve(value);\n }\n : resolve,\n onSettled\n ? reason => {\n onSettled();\n reject(reason);\n }\n : reject,\n initOperationData,\n scopeStack\n );\n });\n }\n\n protected _createScopeStack(\n operations: IResolvedOperation[]\n ): IOperationScope[] {\n return [\n {\n currentIndex: -1,\n eventbus: this.eventbus,\n services: this.services,\n operations,\n },\n ];\n }\n\n /**\n * @deprecated Unused: `start()` and `end()` create a scope stack for each\n * execution. Will be removed in the next major version.\n */\n protected _initializeScopeStack() {\n this._scopeStack = this._createScopeStack(this.startOperations);\n }\n\n private _pushScope(\n scopeStack: IOperationScope[],\n parentScope: IOperationScope\n ): IOperationScope {\n const newScope = {\n get currentIndex() {\n return parentScope.currentIndex;\n },\n set currentIndex(value: number) {\n parentScope.currentIndex = value;\n },\n get eventbus() {\n return parentScope.eventbus;\n },\n get services() {\n return parentScope.services;\n },\n get operations() {\n return parentScope.operations;\n },\n parent: parentScope,\n };\n scopeStack.push(newScope);\n return newScope;\n }\n\n /**\n * Executes `operations` starting at `operationIndex`.\n *\n * Synchronous operations run in a loop, so the stack depth does not grow with\n * the number of executed operations (large `forEach` loops are safe). When an\n * operation returns a promise, execution continues once it resolves.\n */\n executeOperation(\n operations: IResolvedOperation[],\n operationIndex: number,\n resolve: (value?: any) => void,\n reject: (reason?: any) => void,\n previousOperationData: TOperationData | undefined = {},\n scopeStack: IOperationScope[] = this._scopeStack\n ): void {\n let index = operationIndex;\n let operationData: TOperationData = previousOperationData ?? {};\n // The operation being executed, used to annotate errors\n let failingOperation: IResolvedOperation | undefined;\n let failingIndex = operationIndex;\n\n try {\n while (true) {\n let scope = scopeStack[scopeStack.length - 1];\n if (scope.newIndex !== undefined) {\n index = scope.newIndex;\n delete scope.newIndex;\n }\n\n scope.currentIndex = index;\n\n if (index >= operations.length) {\n resolve(operationData);\n return;\n }\n\n const operationInfo = operations[index];\n failingOperation = operationInfo;\n failingIndex = index;\n const isLoopIteration =\n operationInfo.systemName === forEachSystemName &&\n scope.owner === operationInfo;\n const configuredData =\n (isLoopIteration ? this._loopOperationData.get(scope) : undefined) ??\n copyConfiguredOperationData(\n operationInfo.operationData,\n operationInfo.systemName\n );\n const mergedOperationData = Object.assign(\n operationData,\n configuredData\n );\n\n if (operationInfo.systemName === whenSystemName) {\n scope = this._pushScope(scopeStack, scope);\n } else if (\n operationInfo.systemName === forEachSystemName &&\n !isLoopIteration\n ) {\n scope = this._pushScope(scopeStack, scope);\n scope.owner = operationInfo;\n this._loopOperationData.set(scope, configuredData);\n }\n\n const operationResult = operationInfo.instance.call(\n scope,\n mergedOperationData\n );\n\n if (\n operationInfo.systemName === endWhenSystemName ||\n (operationInfo.systemName === endForEachSystemName &&\n scope.newIndex === undefined)\n ) {\n scopeStack.pop();\n }\n\n index++;\n\n if (isPromise(operationResult)) {\n const nextIndex = index;\n const asyncOperation = operationInfo;\n const asyncIndex = index - 1;\n // The rejection handler annotates only this operation's own failure;\n // later operations are annotated by the executeOperation call that\n // runs them.\n operationResult\n .then(\n promisedOperationResult =>\n this.executeOperation(\n operations,\n nextIndex,\n resolve,\n reject,\n promisedOperationResult as TOperationData,\n scopeStack\n ),\n (error: unknown) =>\n reject(withOperationContext(error, asyncOperation, asyncIndex))\n )\n .catch(reject);\n return;\n }\n\n operationData = (operationResult as TOperationData | undefined) ?? {};\n }\n } catch (error) {\n reject(\n failingOperation\n ? withOperationContext(error, failingOperation, failingIndex)\n : error\n );\n }\n }\n}\n\n/**\n * One operation on the path from the action the engine ran to the operation\n * that failed, see {@link IOperationErrorContext.operationPath}.\n */\nexport interface IOperationPathEntry {\n /** System name of the operation */\n systemName: string;\n /** Its index in the operation list of its action */\n index: number;\n}\n\n/**\n * An error that carries the operation it came from.\n *\n * `EligiusEngine` reads these properties to name the failing operation in its\n * `error` event.\n */\nexport interface IOperationErrorContext {\n /** System name of the innermost failing operation */\n operationSystemName?: string;\n /** Index of the innermost failing operation in its own action's list */\n operationIndex?: number;\n /**\n * The operations the error passed through, outermost first: every\n * `startAction` or `endAction` that called into another action, and\n * finally the failing operation itself (the same as `operationSystemName`\n * and `operationIndex`). Each entry's index is in the operation list of\n * the action the previous entry started.\n */\n operationPath?: IOperationPathEntry[];\n}\n\n/**\n * Adds the failing operation's system name and index to an error, unless an\n * inner action already did (the innermost operation is the most specific),\n * and prepends the operation to the error's path, so that every action frame\n * the error passes through adds exactly one entry, outermost first.\n * Non-Error values are wrapped in an Error that keeps their message.\n */\nfunction withOperationContext(\n error: unknown,\n operation: IResolvedOperation,\n index: number\n): Error & IOperationErrorContext {\n const annotated: Error & IOperationErrorContext =\n error instanceof Error ? error : new Error(String(error), {cause: error});\n if (annotated.operationSystemName === undefined) {\n annotated.operationSystemName = operation.systemName;\n annotated.operationIndex = index;\n }\n annotated.operationPath = [\n {systemName: operation.systemName, index},\n ...(annotated.operationPath ?? []),\n ];\n return annotated;\n}\n\nconst emptyOperationData: Readonly<TOperationData> = Object.freeze({});\n\n/**\n * Configured operation data already checked by {@link assertNoProtoKeys}.\n * Configured data is not changed after resolution, so each object is walked\n * once, not on every run of its operation.\n */\nconst checkedOperationData = new WeakSet<object>();\n\n/**\n * Throws when an own `__proto__` key occurs anywhere in the configured\n * operation data (JSON.parse creates one as a normal property). Merging with\n * Object.assign would run the `__proto__` setter at the top level, and\n * operations that assign or merge nested data could do the same below it.\n * Arrays and plain objects are walked; class instances, jQuery objects and\n * DOM nodes are not.\n *\n * @throws Error naming the operation and the path of the key\n */\nfunction assertNoProtoKeys(operationData: TOperationData, systemName: string) {\n if (checkedOperationData.has(operationData)) {\n return;\n }\n const visiting = new Set<object>();\n const walk = (value: unknown, path: string) => {\n if (value === null || typeof value !== 'object' || visiting.has(value)) {\n return;\n }\n if (Array.isArray(value)) {\n visiting.add(value);\n value.forEach((item, index) => {\n walk(item, `${path}[${index}]`);\n });\n return;\n }\n if (!isPlainObject(value)) {\n return;\n }\n visiting.add(value);\n if (Object.hasOwn(value, '__proto__')) {\n const at = path ? `${path}.__proto__` : '__proto__';\n throw new Error(\n `${systemName}: operation data must not contain a '__proto__' key (found at '${at}')`\n );\n }\n for (const key of Object.keys(value)) {\n walk(value[key], path ? `${path}.${key}` : key);\n }\n };\n walk(operationData, '');\n checkedOperationData.add(operationData);\n}\n\n/**\n * Returns the configured operation data in a form that is safe to merge into\n * the running operation data.\n *\n * Merging copies the top-level properties, so operations that delete or\n * reassign properties (such as `@erased` ones) never touch the configured\n * object. Only nested objects and arrays can be mutated through the merged\n * data, so a deep copy is made only when the configured data contains one.\n * Empty data and data holding only primitives and functions is returned as-is.\n *\n * @throws Error when the data contains a `__proto__` key at any depth\n */\nfunction copyConfiguredOperationData(\n operationData: TOperationData | undefined,\n systemName: string\n): TOperationData {\n if (!operationData) {\n return emptyOperationData;\n }\n assertNoProtoKeys(operationData, systemName);\n for (const key in operationData) {\n const value = operationData[key];\n if (\n typeof value === 'object' &&\n value !== null &&\n Object.hasOwn(operationData, key)\n ) {\n return deepCopy(operationData);\n }\n }\n return operationData;\n}\n","import {Action} from '@action/action.ts';\nimport type {IResolvedOperation} from '@configuration/types.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\nimport type {TOperationData} from '@operation/types.ts';\nimport type {IEngineServices} from '@/engine-services.ts';\n\nexport class EndableAction extends Action {\n constructor(\n name: string,\n startOperations: IResolvedOperation[],\n public endOperations: IResolvedOperation[],\n eventBus: IEventbus,\n services: IEngineServices\n ) {\n super(name, startOperations, eventBus, services);\n }\n\n /**\n * Runs the end operations.\n *\n * A failure is not logged here: the returned promise rejects with the\n * error (annotated with the failing operation), and the caller reports it.\n * The engine reports it through its `error` event.\n *\n * @param initOperationData - Operation data the first end operation receives\n * @returns The operation data of the last end operation\n */\n end(initOperationData?: TOperationData): Promise<TOperationData> {\n if (!this.endOperations.length) {\n return Promise.resolve(initOperationData ?? {});\n }\n\n return this._runOperations(this.endOperations, initOperationData);\n }\n}\n","import {EndableAction} from '@action/endable-action.ts';\nimport type {ITimelineAction} from '@action/types.ts';\nimport type {IResolvedOperation} from '@configuration/types.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\nimport type {TOperationData} from '@operation/types.ts';\nimport type {IEngineServices} from '@/engine-services.ts';\nimport type {IStrictDuration} from '../types.ts';\n\ntype TRun = () => Promise<TOperationData>;\n\nexport class TimelineAction extends EndableAction implements ITimelineAction {\n private _active: boolean = false;\n /** True while start or end operations of this action are running */\n private _running = false;\n /** Starts and ends called while operations were running, in call order */\n private _waiting: Array<() => void> = [];\n /**\n * Finishes the run that `_execute` is starting; handed to the operations\n * run (see `_runOperations`) so it is called the moment they settle.\n */\n private _finishPending: (() => void) | undefined;\n\n /**\n * True from the moment `start()` is called until `end()` is called, whether\n * or not the action has end operations. Both transitions happen\n * synchronously, so a second dispatch of the same start or end (a seek\n * while playing, a revisited key) is a no-op.\n */\n public get active() {\n return this._active;\n }\n\n constructor(\n name: string,\n startOperations: IResolvedOperation[],\n endOperations: IResolvedOperation[],\n public duration: IStrictDuration,\n eventBus: IEventbus,\n services: IEngineServices\n ) {\n super(name, startOperations, endOperations, eventBus, services);\n }\n\n /**\n * Starts the action, unless it is already active.\n *\n * `active` becomes true at once. When the operations of an earlier start\n * or end are still running (an asynchronous end at a loop wrap, a start\n * awaiting a fetch when its range is skipped), these start operations run\n * once those have finished, so the start and end operations of one action\n * never interleave. Otherwise they run right away.\n *\n * @param initOperationData - Operation data the first start operation receives\n * @returns The operation data of the last start operation\n */\n start(initOperationData?: TOperationData): Promise<TOperationData> {\n if (this._active) {\n return Promise.resolve({});\n }\n\n this._active = true;\n return this._sequence(() => super.start(initOperationData));\n }\n\n /**\n * Ends the action, unless it is not active.\n *\n * `active` becomes false at once. Like {@link start}, the end operations\n * wait for operations of this action that are still running.\n *\n * @param initOperationData - Operation data the first end operation receives\n * @returns The operation data of the last end operation\n */\n end(initOperationData?: TOperationData): Promise<TOperationData> {\n if (!this._active) {\n return Promise.resolve({});\n }\n\n this._active = false;\n return this._sequence(() => super.end(initOperationData));\n }\n\n private _sequence(run: TRun): Promise<TOperationData> {\n if (!this._running) {\n return this._execute(run);\n }\n return new Promise<TOperationData>((resolve, reject) => {\n this._waiting.push(() => {\n this._execute(run).then(resolve, reject);\n });\n });\n }\n\n /**\n * Runs `run`, marking the action as running until its operations settle.\n * Operations that complete synchronously finish the run synchronously, so\n * a start and end called back to back both run within the same call stack.\n */\n private _execute(run: TRun): Promise<TOperationData> {\n let finished = false;\n const finish = () => {\n if (finished) {\n return;\n }\n finished = true;\n this._running = false;\n this._waiting.shift()?.();\n };\n\n this._running = true;\n this._finishPending = finish;\n let result: Promise<TOperationData>;\n try {\n result = run();\n } catch (error) {\n result = Promise.reject(error);\n }\n if (this._finishPending === finish) {\n // No operations ran (an end without end operations)\n this._finishPending = undefined;\n finish();\n }\n return result;\n }\n\n protected override _runOperations(\n operations: IResolvedOperation[],\n initOperationData?: TOperationData,\n onSettled?: () => void\n ): Promise<TOperationData> {\n const finish = this._finishPending;\n this._finishPending = undefined;\n return super._runOperations(operations, initOperationData, () => {\n onSettled?.();\n finish?.();\n });\n }\n}\n","import type {EventName, IEventbus, TEventbusRemover} from '@eventbus/types.ts';\nimport type {\n EngineEvents,\n IEligiusEngine,\n IEngineEventSubscriptionOptions,\n} from '../types.ts';\nimport type {IAdapter} from './types.ts';\n\n/**\n * Bridges EligiusEngine to/from the eventbus.\n *\n * This adapter:\n * - Forwards engine events to eventbus broadcasts (the engine `error` event\n * becomes `engine-error`)\n * - Forwards eventbus commands to engine methods; a command that fails is\n * logged and broadcast as `engine-command-error` with the command name and\n * the error\n * - Handles eventbus state queries by reading engine properties\n */\nexport class EngineEventbusAdapter implements IAdapter {\n private _engineEventRemovers: Array<() => void> = [];\n private _eventbusRemovers: TEventbusRemover[] = [];\n private _connected = false;\n\n constructor(\n private _engine: IEligiusEngine,\n private _eventbus: IEventbus\n ) {}\n\n /**\n * Connect adapter - start listening and forwarding. Calling it again while\n * connected does nothing.\n */\n connect(): void {\n if (this._connected) {\n return;\n }\n this._connected = true;\n this._subscribeToEngineEvents();\n this._subscribeToEventbusEvents();\n }\n\n /**\n * Disconnect adapter - stop all listeners\n */\n disconnect(): void {\n this._connected = false;\n this._engineEventRemovers.forEach(remove => remove());\n this._engineEventRemovers = [];\n\n this._eventbusRemovers.forEach(remove => remove());\n this._eventbusRemovers = [];\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Engine Events → Eventbus Broadcasts\n // ─────────────────────────────────────────────────────────────────────────\n\n private _subscribeToEngineEvents(): void {\n this._onEngineEvent('start', () => {\n this._eventbus.broadcast('timeline-play', []);\n });\n\n this._onEngineEvent('pause', () => {\n this._eventbus.broadcast('timeline-pause', []);\n });\n\n this._onEngineEvent('stop', () => {\n this._eventbus.broadcast('timeline-stop', []);\n });\n\n this._onEngineEvent('time', (position: number) => {\n this._eventbus.broadcast('timeline-time', [position]);\n });\n\n this._onEngineEvent('duration', (duration: number) => {\n this._eventbus.broadcast('timeline-duration', [() => duration]);\n });\n\n this._onEngineEvent(\n 'seekStart',\n (target: number, current: number, duration: number) => {\n this._eventbus.broadcast('timeline-seek', [target, current, duration]);\n }\n );\n\n this._onEngineEvent(\n 'seekComplete',\n (position: number, duration: number) => {\n this._eventbus.broadcast('timeline-seeked', [position, duration]);\n }\n );\n\n this._onEngineEvent('timelineChange', (uri: string) => {\n this._eventbus.broadcast('timeline-current-timeline-change', [uri]);\n });\n\n this._onEngineEvent('timelineComplete', () => {\n this._eventbus.broadcast('timeline-complete', []);\n });\n\n this._onEngineEvent('timelineFirstFrame', () => {\n this._eventbus.broadcast('timeline-firstframe', []);\n });\n\n this._onEngineEvent('timelineRestart', () => {\n this._eventbus.broadcast('timeline-restart', []);\n });\n\n // Forward-only: the engine still logs errors nobody else subscribes to,\n // so they are not lost when nothing listens to engine-error.\n this._onEngineEvent(\n 'error',\n error => {\n this._eventbus.broadcast('engine-error', [error]);\n },\n {forwardOnly: true}\n );\n }\n\n private _onEngineEvent<K extends keyof EngineEvents>(\n event: K,\n handler: (...args: EngineEvents[K]) => void,\n options?: IEngineEventSubscriptionOptions\n ): void {\n const remover = options\n ? this._engine.on(event, handler, options)\n : this._engine.on(event, handler);\n this._engineEventRemovers.push(remover);\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Eventbus Commands → Engine Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * This adapter is the only place where eventbus commands reach the engine;\n * the engine itself does not subscribe to them.\n */\n private _subscribeToEventbusEvents(): void {\n // Playback commands\n this._onEventbusEvent('timeline-play-request', () => {\n this._handleRejection('start', this._engine.start());\n });\n\n this._onEventbusEvent('timeline-pause-request', () => {\n this._engine.pause();\n });\n\n this._onEventbusEvent('timeline-stop-request', () => {\n this._handleRejection('stop', this._engine.stop());\n });\n\n this._onEventbusEvent('timeline-seek-request', (position: number) => {\n this._handleRejection('seek', this._engine.seek(position));\n });\n\n this._onEventbusEvent('timeline-play-toggle-request', () => {\n if (this._engine.playState === 'playing') {\n this._engine.pause();\n } else {\n this._handleRejection('start', this._engine.start());\n }\n });\n\n // Timeline management\n this._onEventbusEvent(\n 'request-timeline-uri',\n (uri: string, position: number = 0) => {\n this._handleRejection(\n 'switchTimeline',\n this._engine.switchTimeline(uri, position)\n );\n }\n );\n\n // State queries - using onRequest for synchronous responses\n this._registerRequest('request-current-timeline-position', () => {\n return this._engine.position;\n });\n\n this._registerRequest('timeline-duration-request', () => {\n return this._engine.duration;\n });\n\n this._registerRequest('timeline-container-request', () => {\n return this._engine.container;\n });\n\n this._registerRequest('timeline-request-current-timeline', () => {\n return this._engine.currentTimelineUri;\n });\n }\n\n /**\n * Eventbus handlers cannot return the engine's promises to anyone, so\n * report a rejection here instead of leaving it unhandled: it is logged\n * and broadcast as `engine-command-error` (`[command, error]`), so the\n * application can react, for example to blocked autoplay.\n */\n private _handleRejection(command: string, result: unknown): void {\n if (result instanceof Promise) {\n result.catch(error => {\n console.error(\n `[EngineEventbusAdapter] engine.${command}() failed`,\n error\n );\n this._eventbus.broadcast('engine-command-error', [command, error]);\n });\n }\n }\n\n private _onEventbusEvent(\n eventName: EventName,\n handler: (...args: any[]) => void\n ): void {\n const remover = this._eventbus.on(eventName, handler);\n this._eventbusRemovers.push(remover);\n }\n\n private _registerRequest<T>(\n eventName: string,\n responder: (...args: any[]) => T\n ): void {\n const remover = this._eventbus.onRequest(eventName, responder);\n this._eventbusRemovers.push(remover);\n }\n}\n","import hotkeys from 'hotkeys-js';\n\n/**\n * Shared bookkeeping for the hotkeys-js handlers of the engine play toggle\n * (`EngineInputAdapter`) and of `KeyboardController`.\n *\n * hotkeys-js calls every handler bound to a key, so the handlers of one key\n * press agree through this registry on who handles it: the one engine that\n * handles a press while nothing has focus, and whether a KeyboardController\n * takes a key away from the play toggle of its own engine.\n */\n\n/**\n * Splits a hotkeys-js key description into its comma separated shortcuts,\n * the way hotkeys-js does.\n */\nexport function splitShortcuts(key: string): string[] {\n const keys = key.replace(/\\s/g, '').split(',');\n // An empty part after a trailing ',' means the comma key itself ('ctrl+,')\n const last = keys.lastIndexOf('');\n if (last >= 0) {\n keys.splice(last, 1);\n if (keys.length) {\n keys[keys.length - 1] += ',';\n }\n }\n return keys;\n}\n\n/**\n * Names hotkeys-js treats as the same key (they share a key code), mapped to\n * one of them.\n */\nconst keyAliases: Readonly<Record<string, string>> = {\n '⌫': 'backspace',\n '↩': 'enter',\n return: 'enter',\n escape: 'esc',\n arrowup: 'up',\n arrowdown: 'down',\n arrowleft: 'left',\n arrowright: 'right',\n delete: 'del',\n insert: 'ins',\n '⇪': 'capslock',\n '{': '[',\n '}': ']',\n '⇧': 'shift',\n '⌥': 'alt',\n option: 'alt',\n '⌃': 'ctrl',\n control: 'ctrl',\n '⌘': 'meta',\n cmd: 'meta',\n command: 'meta',\n};\n\nconst canonicalKey = (name: string): string => {\n const lower = name.toLowerCase();\n return keyAliases[lower] ?? lower;\n};\n\n/**\n * Returns one id for every spelling of a shortcut, so `'Space'` and\n * `'space'`, `'ArrowRight'` and `'right'`, `'cmd+s'` and `'command+s'` match.\n *\n * @param shortcut - One shortcut, such as `'shift+right'`\n */\nexport function shortcutId(shortcut: string): string {\n const parts = shortcut.replace(/\\s/g, '').split('+');\n const key = canonicalKey(parts.pop() ?? '');\n const modifiers = [...new Set(parts.map(canonicalKey))].sort();\n return [...modifiers, key].join('+');\n}\n\n/**\n * Returns the first part of a shortcut that hotkeys-js can't match, or\n * `undefined` when every part is valid. The last part must be a hotkeys-js\n * key name (case insensitive, which includes the `KeyboardEvent.key` names\n * of the arrow keys, `Enter`, `Escape`, `Home`, `F1` and so on) or a single\n * letter or digit. Any parts before it must be modifiers.\n *\n * @param shortcut - One shortcut, such as `'shift+right'`\n */\nexport function findInvalidKeyName(shortcut: string): string | undefined {\n const parts = shortcut.split('+');\n const key = parts.pop() ?? '';\n const invalidModifier = parts.find(\n part => !Object.hasOwn(hotkeys.modifier, part.toLowerCase())\n );\n if (invalidModifier !== undefined) {\n return invalidModifier;\n }\n const isKey =\n Object.hasOwn(hotkeys.keyMap, key.toLowerCase()) || /^[a-z0-9]$/i.test(key);\n return isKey ? undefined : key;\n}\n\n/**\n * The shortcut id of a hotkeys-js handler call, falling back to the first\n * shortcut when hotkeys-js passes no handler info.\n */\nexport function pressedShortcutId(\n hotkeysEvent: {key?: unknown} | undefined,\n shortcutIds: readonly string[]\n): string {\n return typeof hotkeysEvent?.key === 'string'\n ? shortcutId(hotkeysEvent.key)\n : shortcutIds[0];\n}\n\n/**\n * Returns the focused element of a key press, or `undefined` when nothing\n * has focus: the target is missing, the document, its body or its root\n * element.\n */\nexport function focusedElement(\n target: EventTarget | null | undefined\n): Element | undefined {\n const element = target as Element | null | undefined;\n if (!element || typeof element.closest !== 'function') {\n return undefined;\n }\n const {ownerDocument} = element;\n if (\n element === ownerDocument?.body ||\n element === ownerDocument?.documentElement\n ) {\n return undefined;\n }\n return element;\n}\n\n/**\n * A hotkeys-js handler that takes part in the key press election.\n */\nexport interface IKeyboardParticipant {\n /** `'controller'` takes a key away from the play toggle of its engine */\n readonly kind: 'playToggle' | 'controller';\n /** {@link shortcutId}s of the bound shortcuts */\n readonly shortcutIds: readonly string[];\n /** Whether it handles presses made while nothing has focus */\n readonly unfocused: boolean;\n /** Whether it can handle key presses right now */\n isReady(): boolean;\n /** The engine root element, if it is resolved */\n root(): Element | undefined;\n /** Whether it handles a press made while `element` has focus */\n acceptsFocus(element: Element): boolean;\n}\n\ninterface IKeyboardRegistry {\n /** Live participants in connection order */\n participants: Set<IKeyboardParticipant>;\n /** The engine root the user touched or focused last */\n lastInteractedRoot: Element | undefined;\n removeInteractionListeners: () => void;\n}\n\n/** Registries per document */\nconst registries = new Map<Document, IKeyboardRegistry>();\n\nfunction createRegistry(doc: Document): IKeyboardRegistry {\n const registry: IKeyboardRegistry = {\n participants: new Set(),\n lastInteractedRoot: undefined,\n removeInteractionListeners: () => {},\n };\n const onInteraction = (event: Event) => {\n const target = event.target as Node | null;\n if (!target) {\n return;\n }\n for (const candidate of registry.participants) {\n const root = candidate.root();\n if (root?.contains(target)) {\n registry.lastInteractedRoot = root;\n return;\n }\n }\n };\n const listenerOptions: AddEventListenerOptions = {\n capture: true,\n passive: true,\n };\n doc.addEventListener('pointerdown', onInteraction, listenerOptions);\n doc.addEventListener('focusin', onInteraction, listenerOptions);\n registry.removeInteractionListeners = () => {\n doc.removeEventListener('pointerdown', onInteraction, listenerOptions);\n doc.removeEventListener('focusin', onInteraction, listenerOptions);\n };\n return registry;\n}\n\n/**\n * Adds a participant to the registry of the document, creating the registry\n * and its interaction listeners for the first one.\n *\n * @returns A function that removes the participant again, and the registry\n * with its listeners after the last one\n */\nexport function joinKeyboardRegistry(\n doc: Document,\n participant: IKeyboardParticipant\n): () => void {\n let registry = registries.get(doc);\n if (!registry) {\n registry = createRegistry(doc);\n registries.set(doc, registry);\n }\n const joined = registry;\n joined.participants.add(participant);\n\n return () => {\n joined.participants.delete(participant);\n const root = joined.lastInteractedRoot;\n if (root && ![...joined.participants].some(p => p.root() === root)) {\n joined.lastInteractedRoot = undefined;\n }\n if (joined.participants.size === 0) {\n joined.removeInteractionListeners();\n if (registries.get(doc) === joined) {\n registries.delete(doc);\n }\n }\n };\n}\n\n/**\n * The participant whose engine handles a press of the shortcut made while\n * nothing has focus: among the ready participants that bind the shortcut and\n * handle unfocused presses, the first one inside the root the user last\n * clicked or focused inside, otherwise the first connected one.\n */\nfunction electParticipant(\n registry: IKeyboardRegistry,\n id: string\n): IKeyboardParticipant | undefined {\n const candidates = [...registry.participants].filter(\n p => p.unfocused && p.shortcutIds.includes(id) && p.isReady()\n );\n const {lastInteractedRoot} = registry;\n return (\n (lastInteractedRoot &&\n candidates.find(p => p.root() === lastInteractedRoot)) ||\n candidates[0]\n );\n}\n\n/**\n * Whether the participant handles this press of the shortcut. A press made\n * while nothing has focus goes to the participants of one engine root only;\n * see {@link IKeyboardParticipant.unfocused}.\n *\n * @param doc - The document the participant joined, if there is one\n * @param participant - The participant\n * @param event - The key press\n * @param id - The {@link shortcutId} of the pressed shortcut\n */\nexport function handlesKeyPress(\n doc: Document | undefined,\n participant: IKeyboardParticipant,\n event: KeyboardEvent,\n id: string\n): boolean {\n if (!participant.isReady()) {\n return false;\n }\n const element = focusedElement(event.target);\n if (element) {\n return participant.acceptsFocus(element);\n }\n const registry = doc && registries.get(doc);\n if (!participant.unfocused || !registry) {\n return false;\n }\n const elected = electParticipant(registry, id);\n if (elected === participant) {\n return true;\n }\n // The other participants of the elected engine handle the press too\n const root = participant.root();\n return root !== undefined && elected?.root() === root;\n}\n\n/**\n * Whether a KeyboardController of the engine with this root handles this\n * press of the shortcut, so the play toggle of that engine leaves it alone.\n */\nexport function isClaimedByController(\n doc: Document | undefined,\n root: Element | undefined,\n event: KeyboardEvent,\n id: string\n): boolean {\n const registry = doc && registries.get(doc);\n if (!registry || !root) {\n return false;\n }\n return [...registry.participants].some(\n p =>\n p.kind === 'controller' &&\n p.root() === root &&\n p.shortcutIds.includes(id) &&\n handlesKeyPress(doc, p, event, id)\n );\n}\n","import type {IEventbus, TEventbusRemover} from '@eventbus/types.ts';\nimport {\n handlesKeyPress,\n type IKeyboardParticipant,\n isClaimedByController,\n joinKeyboardRegistry,\n pressedShortcutId,\n shortcutId,\n splitShortcuts,\n} from '@util/keyboard-input-registry.ts';\nimport hotkeys, {type HotkeysEvent} from 'hotkeys-js';\nimport type {\n IEligiusEngine,\n IEngineInputOptions,\n TEngineInputScope,\n} from '../types.ts';\nimport type {IAdapter} from './types.ts';\n\n/**\n * Options for {@link EngineInputAdapter}: the {@link IEngineInputOptions}\n * plus the deprecated `playToggleHotkey` alias.\n */\nexport interface IEngineInputAdapterOptions extends IEngineInputOptions {\n /**\n * The hotkey that toggles playback (hotkeys-js syntax), or `false` for\n * none. Defaults to `'space'`. `playToggle` wins when both are set.\n *\n * @deprecated Use {@link IEngineInputOptions.playToggle}.\n */\n playToggleHotkey?: string | false;\n}\n\n/**\n * Elements whose own keyboard behaviour (activating a button, typing a\n * space) the play toggle hotkey must not take over.\n */\nconst interactiveSelector =\n 'button, a[href], input, select, textarea, summary, [contenteditable]:not([contenteditable=\"false\"]), [role=\"button\"], [role=\"link\"]';\n\nconst inputScopes: readonly TEngineInputScope[] = ['document', 'engineRoot'];\n\n/**\n * Handles external input sources (hotkeys, resize).\n *\n * This adapter:\n * - Registers the play toggle hotkey (space by default) in the hotkeys-js\n * `'all'` scope, so it works whatever scope a KeyboardStepSource sets.\n * It ignores buttons, links and form fields, and engines without an\n * active timeline, so the key keeps its normal behaviour there.\n * With `scope: 'document'` (the default) it handles presses while the\n * focus is inside the engine root, and presses while nothing has focus.\n * When several engines on a page could handle an unfocused press, only\n * one toggles: the engine the user last clicked or focused inside,\n * otherwise the first connected one. With `scope: 'engineRoot'` it only\n * handles presses while the focus is inside the engine root. A press that\n * a KeyboardController of the same engine handles is left to that\n * controller.\n * - Handles window resize events with debouncing, unless `resize` is\n * `false`.\n */\nexport class EngineInputAdapter implements IAdapter {\n private _removers: Array<TEventbusRemover | (() => void)> = [];\n private _resizeTimeout: ReturnType<typeof setTimeout> | undefined;\n private _resizeHandler: (() => void) | undefined;\n private _connected = false;\n private readonly _playToggleHotkey: string | false;\n private readonly _resize: boolean;\n private readonly _scope: TEngineInputScope;\n\n /**\n * @param _engine - The engine to control\n * @param _eventbus - The eventbus to broadcast `timeline-resize` on\n * @param _windowRef - The window to listen to for resizes\n * @param options - Optional settings; see {@link IEngineInputOptions}\n * @throws {Error} When `options.scope` is not `'document'` or\n * `'engineRoot'`\n */\n constructor(\n private _engine: IEligiusEngine,\n private _eventbus: IEventbus,\n private _windowRef: Window,\n options?: IEngineInputAdapterOptions\n ) {\n this._playToggleHotkey =\n options?.playToggle ?? options?.playToggleHotkey ?? 'space';\n this._resize = options?.resize ?? true;\n const scope = options?.scope ?? 'document';\n if (!inputScopes.includes(scope)) {\n throw new Error(\n `[EngineInputAdapter] Unknown input scope '${String(scope)}'. Use 'document' or 'engineRoot'.`\n );\n }\n this._scope = scope;\n }\n\n /**\n * Connect adapter - start listening to inputs. Calling it again while\n * connected does nothing.\n */\n connect(): void {\n if (this._connected) {\n return;\n }\n this._connected = true;\n this._registerHotkeys();\n if (this._resize) {\n this._registerResizeHandler();\n }\n }\n\n /**\n * Disconnect adapter - stop all listeners\n */\n disconnect(): void {\n this._connected = false;\n if (this._resizeTimeout) {\n clearTimeout(this._resizeTimeout);\n this._resizeTimeout = undefined;\n }\n\n this._removers.forEach(remove => remove());\n this._removers = [];\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Hotkey Handling\n // ─────────────────────────────────────────────────────────────────────────\n\n private _registerHotkeys(): void {\n const key = this._playToggleHotkey;\n if (key === false) {\n return;\n }\n const doc = this._document();\n const participant: IKeyboardParticipant = {\n kind: 'playToggle',\n shortcutIds: splitShortcuts(key).map(shortcutId),\n unfocused: this._scope === 'document',\n isReady: () => this._engine.duration !== undefined,\n root: () => this._root(),\n acceptsFocus: element =>\n !element.closest(interactiveSelector) &&\n (this._root()?.contains(element) ?? false),\n };\n if (doc) {\n this._removers.push(joinKeyboardRegistry(doc, participant));\n }\n\n const handler = (\n keyboardEvent: KeyboardEvent,\n hotkeysEvent: HotkeysEvent\n ): void | boolean =>\n this._handlePlayToggle(keyboardEvent, hotkeysEvent, doc, participant);\n // Bind in the 'all' scope explicitly, and unbind from it explicitly:\n // without a scope hotkeys.unbind() uses the *current* scope, which a\n // KeyboardStepSource may have changed.\n hotkeys(key, {scope: 'all'}, handler);\n this._removers.push(() => hotkeys.unbind(key, 'all', handler));\n }\n\n private _handlePlayToggle(\n keyboardEvent: KeyboardEvent,\n hotkeysEvent: HotkeysEvent | undefined,\n doc: Document | undefined,\n participant: IKeyboardParticipant\n ): void | boolean {\n const id = pressedShortcutId(hotkeysEvent, participant.shortcutIds);\n if (\n !handlesKeyPress(doc, participant, keyboardEvent, id) ||\n // A KeyboardController of this engine bound the same key\n isClaimedByController(doc, this._root(), keyboardEvent, id)\n ) {\n // Leave the key to the page (scrolling, a focused button, another\n // engine) or to the controller\n return;\n }\n\n keyboardEvent.preventDefault();\n\n if (this._engine.playState === 'playing') {\n this._engine.pause();\n } else {\n this._engine.start()?.catch(error => {\n console.error('[EngineInputAdapter] engine.start() failed', error);\n });\n }\n\n return false;\n }\n\n private _root(): Element | undefined {\n return this._engine.engineRoot?.[0];\n }\n\n private _document(): Document | undefined {\n return (\n this._windowRef.document ??\n (typeof document === 'undefined' ? undefined : document)\n );\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Resize Handling\n // ─────────────────────────────────────────────────────────────────────────\n\n private _registerResizeHandler(): void {\n this._resizeHandler = this._handleResize.bind(this);\n this._windowRef.addEventListener('resize', this._resizeHandler);\n this._removers.push(() => {\n if (this._resizeHandler) {\n this._windowRef.removeEventListener('resize', this._resizeHandler);\n }\n });\n }\n\n private _handleResize(): void {\n if (this._resizeTimeout) {\n clearTimeout(this._resizeTimeout);\n this._resizeTimeout = undefined;\n }\n\n this._resizeTimeout = setTimeout(() => {\n this._eventbus.broadcast('timeline-resize', []);\n }, 200);\n }\n}\n","/**\n * LocaleEventbusAdapter - Bridges LocaleManager to/from the eventbus\n * Feature: 005-rosetta-locale-manager\n *\n * This adapter:\n * - Forwards LocaleManager events to eventbus broadcasts\n * - Forwards eventbus language commands to LocaleManager methods\n * - Handles eventbus state queries by reading LocaleManager properties\n * - Updates DOM lang attribute when locale changes\n */\n\nimport type {IAdapter} from '@adapters/types.ts';\nimport type {EventName, IEventbus, TEventbusRemover} from '@eventbus/types.ts';\nimport type {\n ILocaleManager,\n LocaleEvents,\n TLanguageCode,\n} from '@locale/types.ts';\nimport type {IEligiusEngine} from '@/types.ts';\n\n/**\n * Bridges LocaleManager to/from the eventbus.\n *\n * Note: Requires engine reference to update DOM lang attribute on locale change.\n */\nexport class LocaleEventbusAdapter implements IAdapter {\n private _localeEventRemovers: Array<() => void> = [];\n private _eventbusRemovers: TEventbusRemover[] = [];\n /**\n * True while this adapter is broadcasting a LocaleManager change to the\n * eventbus. The eventbus handler ignores that broadcast, otherwise it would\n * call setLocale again and the two would feed each other forever.\n */\n private _forwardingToEventbus = false;\n /**\n * True while this adapter is applying an eventbus `language-change` command\n * to the LocaleManager. The resulting manager change is not rebroadcast,\n * because every eventbus listener already received the original command.\n */\n private _handlingEventbusCommand = false;\n private _connected = false;\n\n constructor(\n private _localeManager: ILocaleManager,\n private _eventbus: IEventbus,\n private _engine: IEligiusEngine\n ) {}\n\n /**\n * Connect adapter - start listening and forwarding. Calling it again while\n * connected does nothing.\n */\n connect(): void {\n if (this._connected) {\n return;\n }\n this._connected = true;\n this._subscribeToLocaleManagerEvents();\n this._subscribeToEventbusEvents();\n }\n\n /**\n * Disconnect adapter - stop all listeners\n */\n disconnect(): void {\n this._connected = false;\n this._localeEventRemovers.forEach(remove => remove());\n this._localeEventRemovers = [];\n\n this._eventbusRemovers.forEach(remove => remove());\n this._eventbusRemovers = [];\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // LocaleManager Events → Eventbus Broadcasts\n // ─────────────────────────────────────────────────────────────────────────\n\n private _subscribeToLocaleManagerEvents(): void {\n this._onLocaleEvent(\n 'change',\n (newLocale: TLanguageCode, _oldLocale: TLanguageCode) => {\n this._setRootElementLang(newLocale);\n\n if (this._handlingEventbusCommand) {\n // Change originated from the eventbus; listeners already have it.\n return;\n }\n\n this._forwardingToEventbus = true;\n try {\n this._eventbus.broadcast('language-change', [newLocale]);\n } finally {\n this._forwardingToEventbus = false;\n }\n }\n );\n }\n\n private _onLocaleEvent<K extends keyof LocaleEvents>(\n event: K,\n handler: (...args: LocaleEvents[K]) => void\n ): void {\n const remover = this._localeManager.on(event, handler);\n this._localeEventRemovers.push(remover);\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Eventbus Commands → LocaleManager Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n private _subscribeToEventbusEvents(): void {\n // Language change command\n this._onEventbusEvent('language-change', (language: TLanguageCode) => {\n if (this._forwardingToEventbus) {\n // This is our own rebroadcast of a LocaleManager change.\n return;\n }\n\n // Check if locale is available before switching\n if (!this._localeManager.availableLocales.includes(language)) {\n console.warn(\n `[LocaleEventbusAdapter] Locale '${language}' is not available. Available locales: ${this._localeManager.availableLocales.join(', ')}`\n );\n return;\n }\n\n this._handlingEventbusCommand = true;\n try {\n this._localeManager.setLocale(language);\n } finally {\n this._handlingEventbusCommand = false;\n }\n this._setRootElementLang(language);\n });\n\n // State queries - using onRequest for synchronous responses\n this._registerRequest('request-current-language', () => {\n return this._localeManager.locale;\n });\n\n // Translation request - exposes t() method via eventbus\n this._registerRequest(\n 'request-translation',\n (key: string | string[], params?: Record<string, unknown>) => {\n return this._localeManager.t(key, params);\n }\n );\n }\n\n private _onEventbusEvent(\n eventName: EventName,\n handler: (...args: any[]) => void\n ): void {\n const remover = this._eventbus.on(eventName, handler);\n this._eventbusRemovers.push(remover);\n }\n\n private _registerRequest<T>(\n eventName: string,\n responder: (...args: any[]) => T\n ): void {\n const remover = this._eventbus.onRequest(eventName, responder);\n this._eventbusRemovers.push(remover);\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // DOM Updates\n // ─────────────────────────────────────────────────────────────────────────\n\n private _setRootElementLang(locale: TLanguageCode): void {\n const lang = this._extractPrimaryLanguage(locale);\n this._engine.engineRoot.attr('lang', lang);\n }\n\n private _extractPrimaryLanguage(locale: TLanguageCode): string {\n return locale.split('-').shift() as string;\n }\n}\n","import type {TOperation} from '@operation/types.ts';\n\nexport interface IAddClassOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @type=ParameterType:className\n * @required\n * @erased\n */\n className: string;\n}\n\n/**\n * This operation adds the specified class name to the specified selected element.\n *\n * @category DOM\n */\nexport const addClass: TOperation<\n IAddClassOperationData,\n Omit<IAddClassOperationData, 'className'>\n> = operationData => {\n const {selectedElement, className} = operationData;\n delete (operationData as any).className;\n selectedElement.addClass(className);\n\n return operationData;\n};\n","import type {IController} from '@controllers/types.ts';\n\nconst controllersDataName = 'eligiusEngineControllers';\n\nfunction getElementData(\n name: string,\n element: JQuery\n): IController<any>[] | undefined {\n return element.data(name);\n}\n\nconst getElementControllers = getElementData.bind(null, controllersDataName);\n\nexport {controllersDataName, getElementControllers, getElementData};\n","import {\n controllersDataName,\n getElementControllers,\n} from '@operation/helper/get-element-data.ts';\n\nexport function attachControllerToElement(element: JQuery, controller: any) {\n if (!element.data(controllersDataName)) {\n element.data(controllersDataName, []);\n }\n const controllers = getElementControllers(element);\n if (controllers) {\n controllers.push(controller);\n }\n}\n","import type {TOperationData} from '@operation/types.ts';\n\nexport function mergeOperationData<T extends TOperationData>(\n operationData: T,\n newOperationData: TOperationData\n): T & TOperationData {\n return {...operationData, ...newOperationData};\n}\n","import {mergeOperationData} from '@operation/helper/merge-operation-data.ts';\nimport type {TOperationData} from '@operation/types.ts';\n\nexport function internalResolve<T extends TOperationData = TOperationData>(\n resolve: (data: T | PromiseLike<T>) => void,\n operationData: TOperationData,\n newOperationData?: TOperationData\n) {\n if (newOperationData) {\n resolve(mergeOperationData(operationData, newOperationData) as T);\n } else {\n resolve(operationData as T);\n }\n}\n","import type {IController} from '@controllers/types.ts';\nimport {attachControllerToElement} from '@operation/helper/attach-controller-to-element.ts';\nimport {getElementControllers} from '@operation/helper/get-element-data.ts';\nimport {internalResolve} from '@operation/helper/internal-resolve.ts';\nimport type {\n IOperationScope,\n TOperation,\n TOperationData,\n} from '@operation/types.ts';\n\nexport type IAddControllerToElementOperationData<\n T extends TOperationData = TOperationData,\n> = {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @dependency\n */\n controllerInstance: IController<T>;\n} & T;\n\nfunction unregisterController(\n element: JQuery,\n controller: IController<any>\n): void {\n const controllers = getElementControllers(element);\n const index = controllers?.indexOf(controller) ?? -1;\n if (index > -1) {\n controllers?.splice(index, 1);\n }\n}\n\n/**\n * This operation adds the specified controller instance to the given selected element.\n *\n * The controller is registered on the element only once `init` and a synchronous `attach`\n * have succeeded. When `attach` returns a promise, the controller is registered before\n * that promise settles (so detaching the element can still reach it) and is removed from\n * the element again when the promise rejects.\n *\n * @throws When the controller's `init` or `attach` throws, or the promise returned by `attach` rejects.\n *\n * @category Controller\n */\nexport const addControllerToElement: TOperation<IAddControllerToElementOperationData> =\n function <T extends TOperationData = TOperationData>(\n this: IOperationScope,\n operationData: IAddControllerToElementOperationData<T>\n ) {\n const {selectedElement, controllerInstance} = operationData;\n\n controllerInstance.init(operationData);\n\n const promise = controllerInstance.attach(this.eventbus, this.services);\n\n attachControllerToElement(selectedElement, controllerInstance);\n\n if (promise) {\n return new Promise((resolve, reject) => {\n promise.then(\n (newOperationData: TOperationData) => {\n internalResolve(resolve, operationData, newOperationData);\n },\n (error: unknown) => {\n unregisterController(selectedElement, controllerInstance);\n reject(error);\n }\n );\n });\n } else {\n return operationData;\n }\n };\n","import {assertSafeGlobalName, getGlobals} from '@operation/helper/globals.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IAddGlobalsToOperationData {\n /**\n * The names of the global properties that will be copied onto the current operation data\n *\n * @required\n * @erased\n */\n globalProperties: string[];\n}\n\n/**\n * This operation adds the specified global property names to the current operation data.\n * It finally removes the `globalProperties` property from the current operation data.\n *\n * Plain data is copied, so changing it does not change the global store. jQuery objects, DOM\n * nodes, functions and class instances (such as controllers) are added by reference.\n *\n * @throws When a name is `__proto__`, `prototype` or `constructor`.\n *\n * @category Data\n */\nexport const addGlobalsToOperation: TOperation<\n IAddGlobalsToOperationData,\n Omit<IAddGlobalsToOperationData, 'globalProperties'>\n> = (operationData: IAddGlobalsToOperationData) => {\n const {globalProperties} = operationData;\n\n const globalValues = globalProperties.reduce<Record<string, any>>(\n (prev, current) => {\n assertSafeGlobalName(current, 'addGlobalsToOperation');\n prev[current] = getGlobals(current);\n return prev;\n },\n {}\n );\n removeProperties(operationData, 'globalProperties');\n\n return Object.assign(operationData, globalValues);\n};\n","import {internalResolve} from '@operation/helper/internal-resolve.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IAnimateOperationData {\n /**\n * @type=ParameterType:string\n * @erased\n */\n animationEasing?: string;\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @required\n * @erased\n */\n animationProperties: Record<string, unknown>;\n /**\n * @type=ParameterType:number\n * @required\n * @erased\n */\n animationDuration: JQuery.Duration;\n}\n\n/**\n * This operation animates the specified selected element with the given [jQuery animation](https://api.jquery.com/animate/) properties, duration and easing.\n * It resolves after the animation completes, or immediately when the selected element set is empty.\n *\n * @param operationData\n * @returns\n *\n * @category Animation\n */\nexport const animate: TOperation<\n IAnimateOperationData,\n Omit<\n IAnimateOperationData,\n 'animationEasing' | 'animationProperties' | 'animationDuration'\n >\n> = (operationData: IAnimateOperationData) => {\n const {\n selectedElement,\n animationEasing,\n animationProperties,\n animationDuration,\n } = operationData;\n\n removeProperties(\n operationData,\n 'animationEasing',\n 'animationProperties',\n 'animationDuration'\n );\n\n const promise = new Promise<IAnimateOperationData>((resolve, reject) => {\n // jQuery never calls the complete callback for an empty set\n if (selectedElement.length === 0) {\n internalResolve(resolve, {}, operationData);\n return;\n }\n try {\n if (animationEasing) {\n selectedElement.animate(\n animationProperties,\n animationDuration,\n animationEasing,\n () => {\n internalResolve(resolve, {}, operationData);\n }\n );\n } else {\n selectedElement.animate(animationProperties, animationDuration, () => {\n internalResolve(resolve, {}, operationData);\n });\n }\n } catch (e) {\n reject(e);\n }\n });\n return promise;\n};\n","import {internalResolve} from '@operation/helper/internal-resolve.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IAnimateWithClassOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @type=ParameterType:className\n * @required\n * @erased\n */\n className: string;\n /**\n * When true (the default), the class is removed again after the animation ends\n *\n * @erased\n */\n removeClass?: boolean;\n /**\n * When true, the operation resolves on the first `animationend` event from the selected\n * element or any of its descendants. Use this for a class that only animates descendants.\n * When false (the default), only animations on the selected elements themselves are awaited.\n *\n * @erased\n */\n includeDescendants?: boolean;\n}\n\n/**\n * Extra time, in milliseconds, after the longest computed animation before the\n * operation settles anyway. Covers an `animationend` that never fires, for example\n * because the element was hidden or removed while animating.\n */\nconst FALLBACK_MARGIN_MS = 150;\n\nfunction parseCssList(value: string | undefined): string[] {\n return (value ?? '').split(',').map(part => part.trim());\n}\n\nfunction parseCssTime(value: string | undefined): number {\n if (!value) {\n return 0;\n }\n const amount = Number.parseFloat(value);\n if (Number.isNaN(amount)) {\n // 'auto' and other keywords resolve to 0s for time-based animations\n return 0;\n }\n return value.endsWith('ms') ? amount : amount * 1000;\n}\n\nfunction parseIterationCount(value: string | undefined): number {\n if (value === 'infinite') {\n return Number.POSITIVE_INFINITY;\n }\n const count = Number.parseFloat(value ?? '');\n return Number.isNaN(count) ? 1 : count;\n}\n\n/**\n * Returns the time in milliseconds until the element's longest running CSS animation\n * ends: 0 when it has no animation to wait for, Infinity for an infinite animation.\n */\nfunction getAnimationEndTime(element: Element): number {\n const view = element.ownerDocument?.defaultView;\n if (!view) {\n return 0;\n }\n const style = view.getComputedStyle(element);\n const names = parseCssList(style.animationName);\n const durations = parseCssList(style.animationDuration);\n const delays = parseCssList(style.animationDelay);\n const iterations = parseCssList(style.animationIterationCount);\n\n let endTime = 0;\n names.forEach((name, index) => {\n if (name === '' || name === 'none') {\n return;\n }\n const duration = parseCssTime(durations[index % durations.length]);\n const delay = parseCssTime(delays[index % delays.length]);\n const count = parseIterationCount(iterations[index % iterations.length]);\n const activeTime = duration === 0 ? 0 : duration * count;\n endTime = Math.max(endTime, delay + activeTime);\n });\n return endTime;\n}\n\n/**\n * This operation adds the specified class name to the specified selected element and assumes that this\n * class triggers an animation on the selected element. It then waits for this animation to complete\n * before it resolves.\n *\n * The class must put the animation on the selected element itself: `animationend` events that bubble up\n * from descendants are ignored, and with several selected elements the operation waits for all of them.\n * Set `includeDescendants` to true for a class that only animates descendants; the operation then resolves\n * on the first `animationend` from the element or its subtree.\n *\n * The operation resolves immediately when the selection is empty, or when the class gives none of the\n * selected elements a CSS animation (for example under `prefers-reduced-motion: reduce`). When an\n * `animationend` event never arrives, for example because the element was hidden or removed while\n * animating, it resolves shortly after the longest computed animation should have ended. An infinite\n * animation is waited for until it is ended by an `animationend` event.\n *\n * @category Animation\n */\nexport const animateWithClass: TOperation<\n IAnimateWithClassOperationData,\n Omit<\n IAnimateWithClassOperationData,\n 'className' | 'removeClass' | 'includeDescendants'\n >\n> = (operationData: IAnimateWithClassOperationData) => {\n const {selectedElement, className} = operationData;\n const removeClass = operationData.removeClass ?? true;\n const includeDescendants = operationData.includeDescendants ?? false;\n\n removeProperties(\n operationData,\n 'className',\n 'removeClass',\n 'includeDescendants'\n );\n\n return new Promise<\n Omit<\n IAnimateWithClassOperationData,\n 'className' | 'removeClass' | 'includeDescendants'\n >\n >((resolve, reject) => {\n // There is nothing that can fire animationend for an empty set\n if (selectedElement.length === 0) {\n internalResolve(resolve, {}, operationData);\n return;\n }\n\n let settled = false;\n let fallbackTimer: ReturnType<typeof setTimeout> | undefined;\n\n const finish = () => {\n if (settled) {\n return;\n }\n settled = true;\n if (fallbackTimer !== undefined) {\n clearTimeout(fallbackTimer);\n }\n selectedElement.off('animationend', handleAnimationEnd);\n if (removeClass) {\n selectedElement.removeClass(className);\n }\n internalResolve(resolve, {}, operationData);\n };\n\n const pending = new Set<Element>();\n\n function handleAnimationEnd(event: JQuery.TriggeredEvent) {\n if (includeDescendants) {\n finish();\n return;\n }\n // animationend bubbles: ignore events from descendants\n if (event.target !== event.currentTarget) {\n return;\n }\n pending.delete(event.currentTarget as Element);\n if (pending.size === 0) {\n finish();\n }\n }\n\n try {\n selectedElement.on('animationend', handleAnimationEnd);\n selectedElement.addClass(className);\n\n if (includeDescendants) {\n return;\n }\n\n let longestFinite = 0;\n let hasInfinite = false;\n selectedElement.each((_index, element) => {\n const endTime = getAnimationEndTime(element);\n if (endTime <= 0) {\n return;\n }\n pending.add(element);\n if (endTime === Number.POSITIVE_INFINITY) {\n hasInfinite = true;\n } else {\n longestFinite = Math.max(longestFinite, endTime);\n }\n });\n\n if (pending.size === 0) {\n finish();\n return;\n }\n\n if (!hasInfinite) {\n fallbackTimer = setTimeout(finish, longestFinite + FALLBACK_MARGIN_MS);\n }\n } catch (e) {\n settled = true;\n selectedElement.off('animationend', handleAnimationEnd);\n reject(e);\n }\n });\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IAnnounceToScreenReaderOperationData {\n /**\n * @required\n * @erased\n */\n message: string;\n /**\n * @optional\n * @erased\n */\n priority?: 'polite' | 'assertive';\n}\n\n/**\n * Delay between emptying the live region and writing the message. Screen readers\n * ignore content that is inserted together with a new live region, and setting the\n * same text twice causes no DOM change, so the message is written on a later task.\n */\nconst ANNOUNCE_DELAY_MS = 100;\n\n/**\n * Time after which an announced message is removed from the live region again.\n */\nconst ANNOUNCE_CLEAR_AFTER_MS = 5000;\n\ninterface IPendingAnnouncement {\n fill?: ReturnType<typeof setTimeout>;\n clear?: ReturnType<typeof setTimeout>;\n}\n\nconst pendingAnnouncements = new WeakMap<HTMLElement, IPendingAnnouncement>();\n\nfunction cancelPending(liveRegion: HTMLElement) {\n const pending = pendingAnnouncements.get(liveRegion);\n if (pending) {\n clearTimeout(pending.fill);\n clearTimeout(pending.clear);\n pendingAnnouncements.delete(liveRegion);\n }\n}\n\n/**\n * Announces a message to screen readers using an ARIA live region.\n *\n * The live region (`#aria-live-region`) is created empty on first use. The region is emptied\n * and the message is written 100 milliseconds later, so that a new region\n * and a message repeated verbatim are both announced. The message is removed again after 5 seconds.\n * A newer announcement replaces a pending one.\n *\n * The operation returns at once and does not wait for the message to be written.\n *\n * @throws When the message is empty.\n *\n * @category Accessibility\n */\nexport const announceToScreenReader: TOperation<\n IAnnounceToScreenReaderOperationData,\n Omit<IAnnounceToScreenReaderOperationData, 'message' | 'priority'>\n> = (operationData: IAnnounceToScreenReaderOperationData) => {\n const {message, priority = 'polite'} = operationData;\n\n if (!message || message.trim() === '') {\n throw new Error('announceToScreenReader: message is required');\n }\n\n // Create or get existing live region\n let liveRegion = document.getElementById('aria-live-region');\n if (!liveRegion) {\n liveRegion = document.createElement('div');\n liveRegion.id = 'aria-live-region';\n liveRegion.setAttribute('aria-live', priority);\n liveRegion.style.position = 'absolute';\n liveRegion.style.left = '-10000px';\n liveRegion.style.width = '1px';\n liveRegion.style.height = '1px';\n liveRegion.style.overflow = 'hidden';\n document.body.appendChild(liveRegion);\n } else {\n liveRegion.setAttribute('aria-live', priority);\n }\n\n cancelPending(liveRegion);\n liveRegion.textContent = '';\n\n const region = liveRegion;\n const pending: IPendingAnnouncement = {};\n pending.fill = setTimeout(() => {\n region.textContent = message;\n pending.clear = setTimeout(() => {\n region.textContent = '';\n pendingAnnouncements.delete(region);\n }, ANNOUNCE_CLEAR_AFTER_MS);\n }, ANNOUNCE_DELAY_MS);\n pendingAnnouncements.set(region, pending);\n\n removeProperties(operationData, 'message', 'priority');\n\n return operationData;\n};\n","import {clearLoopCollection} from '@operation/for-each.ts';\nimport {findMatchingEndIndex} from '@operation/helper/flow-control-index.ts';\nimport {\n endWhenSystemName,\n whenSystemName,\n} from '@operation/helper/flow-control-names.ts';\nimport type {IOperationScope} from '@operation/types.ts';\n\n/**\n * The kind of loop jump requested by `breakForEach` or `continueForEach`.\n */\nexport type TLoopJump = 'break' | 'continue';\n\n/**\n * Loop jumps that are still unwinding through enclosing `when` blocks, keyed by the\n * when-scope whose `endWhen` has to pass the jump on to its parent scope.\n */\nconst pendingLoopJumps = new WeakMap<IOperationScope, TLoopJump>();\n\n/**\n * Performs a `break` or `continue` for the nearest enclosing `forEach` loop.\n *\n * When the operation runs directly in the loop scope, the jump targets the loop's\n * `endForEach` immediately. When it runs inside one or more `when` blocks, each of\n * those blocks pushed its own scope, and `Action` only pops a when-scope when it\n * executes the matching `endWhen`. So instead of jumping straight to `endForEach`\n * (which would leave the when-scopes on the stack) the jump goes to the enclosing\n * `endWhen`, and `continuePendingLoopJump` passes it on from there, one\n * `when` block at a time, until it reaches the loop scope.\n *\n * Outside a loop this does nothing.\n */\nexport function requestLoopJump(scope: IOperationScope, jump: TLoopJump) {\n const loopScope = findLoopScope(scope);\n if (!loopScope) {\n return;\n }\n\n if (loopScope === scope) {\n applyLoopJump(loopScope, jump);\n return;\n }\n\n jumpToEnclosingEndWhen(scope, loopScope, jump);\n}\n\n/**\n * Called by `endWhen`. If a loop jump is unwinding through the when-scope that is\n * about to be popped, passes it on to the parent scope, which becomes the top of the\n * scope stack once `Action` pops this one.\n */\nexport function continuePendingLoopJump(scope: IOperationScope) {\n const jump = pendingLoopJumps.get(scope);\n if (!jump) {\n return;\n }\n pendingLoopJumps.delete(scope);\n\n const parent = scope.parent;\n if (!parent) {\n return;\n }\n\n if (isLoopScope(parent)) {\n applyLoopJump(parent, jump);\n return;\n }\n\n const loopScope = findLoopScope(parent);\n if (loopScope) {\n jumpToEnclosingEndWhen(parent, loopScope, jump);\n }\n}\n\nfunction jumpToEnclosingEndWhen(\n scope: IOperationScope,\n loopScope: IOperationScope,\n jump: TLoopJump\n) {\n const endWhenIndex = findEnclosingEndWhenIndex(scope);\n if (endWhenIndex === -1) {\n // Malformed block without an endWhen: nothing to unwind through, so jump\n // straight to the loop end from the current scope.\n applyLoopJump(loopScope, jump);\n scope.newIndex = loopScope.newIndex;\n delete loopScope.newIndex;\n return;\n }\n\n pendingLoopJumps.set(scope, jump);\n scope.newIndex = endWhenIndex;\n}\n\nfunction applyLoopJump(loopScope: IOperationScope, jump: TLoopJump) {\n loopScope.newIndex = loopScope.loopEndIndex;\n delete loopScope.currentItem;\n\n if (jump === 'break') {\n clearLoopCollection(loopScope);\n delete loopScope.loopIndex;\n delete loopScope.loopLength;\n delete loopScope.loopStartIndex;\n delete loopScope.loopEndIndex;\n }\n}\n\nfunction isLoopScope(scope: IOperationScope) {\n return scope.loopIndex !== undefined && scope.loopLength !== undefined;\n}\n\nfunction findLoopScope(scope: IOperationScope): IOperationScope | undefined {\n let current: IOperationScope | undefined = scope;\n while (current) {\n if (isLoopScope(current)) {\n return current;\n }\n current = current.parent;\n }\n return undefined;\n}\n\n/**\n * Returns the index of the `endWhen` that closes the `when` block the current\n * operation is in, skipping nested when/endWhen pairs, or -1 if there is none.\n */\nfunction findEnclosingEndWhenIndex(scope: IOperationScope) {\n return findMatchingEndIndex(\n scope.operations,\n scope.currentIndex + 1,\n whenSystemName,\n endWhenSystemName\n );\n}\n","// oxlint-disable no-unused-vars -- referenced by {@link} in the docs below\nimport type {endForEach} from '@operation/end-for-each.ts';\nimport type {forEach} from '@operation/for-each.ts';\n// oxlint-enable no-unused-vars\nimport {requestLoopJump} from '@operation/helper/loop-jump.ts';\nimport type {TOperation, TOperationData} from '@operation/types.ts';\n\n/**\n *\n * This operation should only be used within a loop, so between a {@link forEach} and {@link endForEach}\n * operation. This operation immediately moves to the loop end index, effectively stopping the loop.\n *\n * It can be placed inside a `when`/`otherwise`/`endWhen` block within the loop, to break conditionally.\n *\n * @category Control Flow\n */\nexport const breakForEach: TOperation<TOperationData> = function (\n operationData: TOperationData\n) {\n requestLoopJump(this, 'break');\n return operationData;\n};\n","import {resolveExternalPropertyChain} from '@operation/helper/resolve-external-property-chain.ts';\nimport type {IOperationScope, TOperationData} from '@operation/types.ts';\n\nexport function resolveEventArguments(\n operationData: TOperationData,\n operationScope: IOperationScope,\n eventArgs?: any[]\n) {\n if (!eventArgs) {\n return;\n }\n const resolve = resolveExternalPropertyChain.bind(\n null,\n operationData,\n operationScope\n );\n return eventArgs.map(resolve);\n}\n","import type {EventName} from '@eventbus/types.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport {resolveEventArguments} from '@operation/helper/resolve-event-arguments.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IBroadcastEventOperationData {\n /**\n * @required\n * @erased\n */\n eventArgs: unknown[];\n /**\n * @type=ParameterType:eventTopic\n * @erased\n */\n eventTopic?: string;\n /**\n * @type=ParameterType:eventName\n * @required\n * @erased\n */\n eventName: string;\n}\n\n/**\n * This operation broadcasts the given event through the eventbus, along with the\n * event arguments and optional event topic.\n *\n * @category Utility\n */\nexport const broadcastEvent: TOperation<\n IBroadcastEventOperationData,\n Omit<IBroadcastEventOperationData, 'eventArgs' | 'eventTopic' | 'eventName'>\n> = function (operationData: IBroadcastEventOperationData) {\n const {eventArgs, eventTopic, eventName} = operationData;\n\n removeProperties(operationData, 'eventArgs', 'eventTopic', 'eventName');\n\n const eventArguments = resolveEventArguments(operationData, this, eventArgs);\n if (eventTopic) {\n this.eventbus.broadcastForTopic(\n eventName as EventName,\n eventTopic,\n eventArguments as any\n );\n } else {\n this.eventbus.broadcast(eventName as EventName, eventArguments as any);\n }\n\n return operationData;\n};\n","import {deepCopy} from '@operation/helper/deep-copy.ts';\nimport type {ExternalProperty} from '@operation/helper/resolve-external-property-chain.ts';\nimport {\n isExternalProperty,\n resolveExternalPropertyChain,\n} from '@operation/helper/resolve-external-property-chain.ts';\nimport type {IOperationScope, TOperationData} from '@operation/types.ts';\nimport {isPlainObject} from '@util/guards/is-plain-object.ts';\n\ntype TResolver = (propertyChain: ExternalProperty) => unknown;\n\n/**\n * Resolves every `$operationdata.`, `$globaldata.` and `$scope.` property chain string in\n * `newProperties` and returns the result.\n *\n * Property chains are looked for in the top-level values of `newProperties` and, recursively,\n * inside plain objects and arrays. Class instances (actions, controllers, the eventbus, ...),\n * jQuery objects, DOM nodes and other non-plain objects are left untouched and never walked.\n *\n * - When `newProperties` is a separate object, a deep copy of it is resolved and returned;\n * `newProperties` itself is not changed.\n * - When `newProperties` is `operationData` itself, its top-level properties are replaced in\n * place and `operationData` is returned. Nested plain objects and arrays are never mutated:\n * one that contains a property chain is replaced by a resolved copy. So configured data and\n * objects shared with other operations stay as they were.\n *\n * @param operationData The operation data `$operationdata` chains are resolved against.\n * @param operationScope The scope `$scope` chains are resolved against.\n * @param newProperties The properties to resolve.\n * @returns The resolved properties.\n */\nexport function resolvePropertyValues<T extends TOperationData>(\n operationData: T,\n operationScope: IOperationScope,\n newProperties: Record<string, any>\n): T {\n const target =\n newProperties !== operationData ? deepCopy(newProperties) : newProperties;\n\n const resolve: TResolver = propertyChain =>\n resolveExternalPropertyChain(operationData, operationScope, propertyChain);\n\n const visiting = new Set<object>([target]);\n for (const key of Object.keys(target)) {\n const value = target[key];\n const resolved = resolveValue(value, resolve, visiting);\n if (resolved !== value) {\n target[key] = resolved;\n }\n }\n\n return target as T;\n}\n\n/**\n * Returns `value` with its property chains resolved. Plain objects and arrays that contain a\n * chain are copied (copy-on-write); everything else is returned as it is.\n */\nfunction resolveValue(\n value: unknown,\n resolve: TResolver,\n visiting: Set<object>\n): unknown {\n if (isExternalProperty(value as ExternalProperty)) {\n return resolve(value as ExternalProperty);\n }\n if (value === null || typeof value !== 'object') {\n return value;\n }\n const isArray = Array.isArray(value);\n if (!isArray && !isPlainObject(value)) {\n return value;\n }\n // Prevent recursive looping on cyclic data.\n if (visiting.has(value)) {\n return value;\n }\n\n visiting.add(value);\n try {\n if (isArray) {\n let copy: unknown[] | undefined;\n value.forEach((item, index) => {\n const resolved = resolveValue(item, resolve, visiting);\n if (resolved !== item) {\n copy ??= value.slice();\n copy[index] = resolved;\n }\n });\n return copy ?? value;\n }\n\n let copy: Record<string, unknown> | undefined;\n const source = value as Record<string, unknown>;\n for (const key of Object.keys(source)) {\n const item = source[key];\n const resolved = resolveValue(item, resolve, visiting);\n if (resolved !== item) {\n copy ??= copyPlainObject(source);\n copy[key] = resolved;\n }\n }\n return copy ?? value;\n } finally {\n visiting.delete(value);\n }\n}\n\nfunction copyPlainObject(source: Record<string, unknown>) {\n const copy: Record<string, unknown> = {};\n for (const key of Object.keys(source)) {\n // defineProperty, so an own '__proto__' key stays a data property.\n Object.defineProperty(copy, key, {\n value: source[key],\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n return copy;\n}\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport {resolvePropertyValues} from '@operation/helper/resolve-property-values.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport type TCalculationOperator = '+' | '-' | '*' | '/' | '%' | '**';\n\nexport interface ICalcOperationData {\n /**\n * The left operand\n * @type=ParameterType:number\n * @required\n * @erased\n */\n left: string | number;\n /**\n * The right operand\n * @type=ParameterType:number\n * @required\n * @erased\n */\n right: string | number;\n /**\n * @required\n * @erased\n */\n operator: TCalculationOperator;\n /**\n * @output\n */\n calculationResult?: number;\n}\n\nconst calcFunctions: Record<\n TCalculationOperator,\n (left: number, right: number) => number\n> = {\n '+': (left: number, right: number) => left + right,\n '-': (left: number, right: number) => left - right,\n '*': (left: number, right: number) => left * right,\n '/': (left: number, right: number) => left / right,\n '%': (left: number, right: number) => left % right,\n '**': (left: number, right: number) => left ** right,\n};\n\n/**\n * This operation calculates the given left and right hand operands using the specified operator.\n *\n * `left`, `right` and `operator` may be property chains (`$operationdata.`, `$globaldata.`,\n * `$scope.`). Only these three inputs are resolved; the rest of the operation data is left as\n * it is.\n *\n * @param operationData\n * @throws When the operator is not one of + - * / % **.\n *\n * @category Utility\n */\nexport const calc: TOperation<\n ICalcOperationData,\n Omit<ICalcOperationData, 'left' | 'right' | 'operator'>\n> = function (operationData: ICalcOperationData) {\n const {left, right, operator} = resolvePropertyValues(operationData, this, {\n left: operationData.left,\n right: operationData.right,\n operator: operationData.operator,\n });\n\n removeProperties(operationData, 'left', 'right', 'operator');\n\n if (typeof operator !== 'string' || !Object.hasOwn(calcFunctions, operator)) {\n throw new Error(\n `calc: unknown operator '${String(operator)}', expected one of ${Object.keys(calcFunctions).join(' ')}`\n );\n }\n\n operationData.calculationResult = calcFunctions[operator](+left, +right);\n\n return operationData;\n};\n","import type {IEventbus} from '@eventbus/types.ts';\nimport {getElementControllers} from '@operation/helper/get-element-data.ts';\nimport $ from 'jquery';\n\n/**\n * Detaches every controller that is still attached (by the\n * `addControllerToElement` operation) to `root` or to one of its descendants,\n * and removes it from its element. Controllers that were already removed with\n * `removeControllerFromElement` are not touched, so calling this again detaches\n * nothing twice.\n *\n * Every controller is attempted even when one of them throws.\n *\n * @param root - The element whose subtree is searched, root included\n * @param eventbus - The eventbus passed to each controller's `detach()`\n * @returns The errors thrown by `detach()` calls, empty when all succeeded\n */\nexport function detachControllersWithin(\n root: JQuery,\n eventbus: IEventbus\n): unknown[] {\n const errors: unknown[] = [];\n\n root\n .find('*')\n .addBack()\n .each((_index, element) => {\n // Elements without jQuery data cannot have controllers; skip them\n // without creating a data cache.\n if (!$.hasData(element)) {\n return;\n }\n const controllers = getElementControllers($(element));\n if (!controllers?.length) {\n return;\n }\n // Empty the stored list in place, so the element no longer holds them.\n controllers.splice(0).forEach(controller => {\n try {\n controller.detach(eventbus);\n } catch (error) {\n errors.push(error);\n }\n });\n });\n\n return errors;\n}\n","import {detachControllersWithin} from '@operation/helper/detach-controllers-within.ts';\nimport type {IOperationScope, TOperation} from '@operation/types.ts';\n\nexport interface IClearElementOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n}\n\n/**\n * This operation removes all of the children from the given selected element.\n *\n * Controllers attached to the removed children or their descendants (by `addControllerToElement`)\n * are detached first. Controllers on the selected element itself stay attached.\n *\n * @throws AggregateError When one or more controller `detach()` calls throw. The element is cleared anyway.\n *\n * @category DOM\n */\nexport const clearElement: TOperation<IClearElementOperationData> = function (\n this: IOperationScope,\n operationData: IClearElementOperationData\n) {\n const {selectedElement} = operationData;\n const errors = detachControllersWithin(\n selectedElement.children(),\n this.eventbus\n );\n selectedElement.empty();\n if (errors.length) {\n throw new AggregateError(\n errors,\n 'clearElement: detaching controllers of the removed children failed'\n );\n }\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IClearOperationDataOperationData {\n /**\n * @erased\n */\n properties?: string[];\n}\n\n/**\n * This operation removes all of the properties on the current operation date.\n * Or, if the `properties` property is set only removes the properties defined by that list.\n *\n * @category Data\n */\nexport const clearOperationData: TOperation<\n IClearOperationDataOperationData,\n Omit<IClearOperationDataOperationData, 'properties'>\n> = (operationData: IClearOperationDataOperationData) => {\n const {properties} = operationData;\n\n if (properties) {\n properties.forEach(name => {\n delete (operationData as any)[name];\n });\n removeProperties(operationData, 'properties');\n return operationData;\n }\n\n return {};\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport type StorageType = 'local' | 'session';\n\nexport interface IClearStorageOperationData {\n /**\n * @optional\n * @erased\n */\n key?: string;\n /**\n * @required\n * @erased\n */\n storageType: StorageType;\n}\n\n/**\n * Clears data from browser storage (localStorage or sessionStorage).\n *\n * If `key` is provided, removes only that key. If `key` is omitted, clears all storage.\n * A `key` that is present but empty, blank or not a string is rejected, so a value resolved\n * from missing data never wipes the whole storage.\n *\n * @throws When `key` is present but is not a non-empty string.\n *\n * @returns Operation data with storage properties erased\n *\n * @example\n * ```typescript\n * // Clear specific key\n * const result = clearStorage({\n * key: 'user-settings',\n * storageType: 'local'\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Clear all localStorage\n * const result = clearStorage({\n * storageType: 'local'\n * });\n * ```\n *\n * @category Data\n */\nexport const clearStorage: TOperation<\n IClearStorageOperationData,\n Omit<IClearStorageOperationData, 'key' | 'storageType'>\n> = (operationData: IClearStorageOperationData) => {\n const {key, storageType} = operationData;\n\n if (key !== undefined && (typeof key !== 'string' || key.trim() === '')) {\n throw new Error('clearStorage: key must be a non-empty string');\n }\n\n const storage = storageType === 'session' ? sessionStorage : localStorage;\n\n if (key === undefined) {\n storage.clear();\n } else {\n storage.removeItem(key);\n }\n\n removeProperties(operationData, 'key', 'storageType');\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface ICompareDateOperationData {\n /**\n * @required\n * @erased\n */\n date1: Date | string | number;\n /**\n * @required\n * @erased\n */\n date2: Date | string | number;\n /**\n * @output\n */\n comparison?: number;\n /**\n * @output\n */\n isEqual?: boolean;\n /**\n * @output\n */\n isBefore?: boolean;\n /**\n * @output\n */\n isAfter?: boolean;\n}\n\n/**\n * Compares two dates.\n * comparison: -1 (before), 0 (equal), 1 (after)\n *\n * @category Date\n */\nexport const compareDate: TOperation<\n ICompareDateOperationData,\n Omit<ICompareDateOperationData, 'date1' | 'date2'>\n> = (operationData: ICompareDateOperationData) => {\n const {date1, date2} = operationData;\n\n if (date1 == null || date1 === '' || date2 == null || date2 === '') {\n throw new Error('compareDate: both dates are required');\n }\n\n const dateObj1 = date1 instanceof Date ? date1 : new Date(date1);\n const dateObj2 = date2 instanceof Date ? date2 : new Date(date2);\n\n if (Number.isNaN(dateObj1.getTime()) || Number.isNaN(dateObj2.getTime())) {\n throw new Error('compareDate: invalid date');\n }\n\n const time1 = dateObj1.getTime();\n const time2 = dateObj2.getTime();\n\n operationData.comparison = time1 < time2 ? -1 : time1 > time2 ? 1 : 0;\n operationData.isEqual = time1 === time2;\n operationData.isBefore = time1 < time2;\n operationData.isAfter = time1 > time2;\n\n removeProperties(operationData, 'date1', 'date2');\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IConcatenateStringsOperationData {\n /**\n * @required\n * @erased\n */\n strings: string[];\n /**\n * @optional\n * @erased\n */\n separator?: string;\n /**\n * @output\n */\n result?: string;\n}\n\n/**\n * Concatenates multiple strings with an optional separator.\n *\n * @returns Operation data with `result` containing the concatenated string\n *\n * @example\n * ```typescript\n * const result = concatenateStrings({\n * strings: ['Hello', 'World'],\n * separator: ' '\n * });\n * // result.result = \"Hello World\"\n * ```\n *\n * @category String\n */\nexport const concatenateStrings: TOperation<\n IConcatenateStringsOperationData,\n Omit<IConcatenateStringsOperationData, 'strings' | 'separator'>\n> = (operationData: IConcatenateStringsOperationData) => {\n const {strings, separator = ''} = operationData;\n\n if (!Array.isArray(strings)) {\n throw new Error('concatenateStrings: strings must be an array');\n }\n\n operationData.result = strings.join(separator);\n\n removeProperties(operationData, 'strings', 'separator');\n\n return operationData;\n};\n","// oxlint-disable no-unused-vars -- referenced by {@link} in the docs below\nimport type {endForEach} from '@operation/end-for-each.ts';\nimport type {forEach} from '@operation/for-each.ts';\n// oxlint-enable no-unused-vars\nimport {requestLoopJump} from '@operation/helper/loop-jump.ts';\nimport type {TOperation, TOperationData} from '@operation/types.ts';\n\n/**\n *\n * This operation should only be used within a loop, so between a {@link forEach} and {@link endForEach}\n * operation. This operation immediately moves to the next loop index, effectively canceling the rest\n * of the operations in the current iteration.\n *\n * It can be placed inside a `when`/`otherwise`/`endWhen` block within the loop, to continue conditionally.\n *\n * @category Control Flow\n */\nexport const continueForEach: TOperation<TOperationData> = function (\n operationData: TOperationData\n) {\n requestLoopJump(this, 'continue');\n return operationData;\n};\n","const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n\n/**\n * Elements that {@link sanitizeHtml} keeps. Only inline formatting is\n * allowed, so translations and subtitles can carry line breaks, emphasis and\n * links, but nothing that loads resources, runs script or changes layout\n * beyond the text itself.\n */\nexport const ALLOWED_TAGS: ReadonlySet<string> = new Set([\n 'a',\n 'abbr',\n 'b',\n 'bdi',\n 'bdo',\n 'br',\n 'cite',\n 'code',\n 'del',\n 'dfn',\n 'em',\n 'i',\n 'ins',\n 'kbd',\n 'mark',\n 'q',\n 's',\n 'samp',\n 'small',\n 'span',\n 'strong',\n 'sub',\n 'sup',\n 'time',\n 'u',\n 'var',\n 'wbr',\n]);\n\n/**\n * Elements that {@link sanitizeHtml} removes together with everything inside\n * them, because their content is script, style, raw text or embedded content.\n * Any other element that is not in {@link ALLOWED_TAGS} is unwrapped: the\n * element goes, its (sanitized) children stay.\n */\nconst DROPPED_WITH_CONTENT: ReadonlySet<string> = new Set([\n 'applet',\n 'base',\n 'embed',\n 'frame',\n 'frameset',\n 'iframe',\n 'link',\n 'math',\n 'meta',\n 'noembed',\n 'noframes',\n 'noscript',\n 'object',\n 'plaintext',\n 'script',\n 'select',\n 'style',\n 'svg',\n 'template',\n 'textarea',\n 'title',\n 'xmp',\n]);\n\n/**\n * Attributes kept on every allowed element. `style` and `id` are left out on\n * purpose: `style` allows overlays and CSS based exfiltration, `id` allows DOM\n * clobbering.\n */\nconst GLOBAL_ATTRIBUTES: ReadonlySet<string> = new Set([\n 'class',\n 'dir',\n 'lang',\n 'title',\n]);\n\nconst TAG_ATTRIBUTES: Readonly<Record<string, ReadonlySet<string>>> = {\n a: new Set(['href', 'hreflang', 'target']),\n del: new Set(['cite', 'datetime']),\n ins: new Set(['cite', 'datetime']),\n q: new Set(['cite']),\n time: new Set(['datetime']),\n};\n\n/**\n * Attribute names whose value is a URL. Values written to these attributes\n * must pass {@link isSafeUrl}.\n */\nexport const URL_ATTRIBUTE_NAMES: ReadonlySet<string> = new Set([\n 'action',\n 'background',\n 'cite',\n 'data',\n 'formaction',\n 'href',\n 'poster',\n 'src',\n 'xlink:href',\n]);\n\nconst SAFE_SCHEMES: ReadonlySet<string> = new Set(['http', 'https', 'mailto']);\n\nconst SCHEME_PATTERN = /^([a-z][a-z0-9+.-]*):/i;\n\n/**\n * Strips what a browser's URL parser ignores before reading the scheme: ASCII\n * tab and newline anywhere, and leading or trailing C0 controls and spaces.\n * Without this, `java\\tscript:` or `\\u0000javascript:` would slip through.\n */\nfunction normalizeUrl(url: string): string {\n const withoutTabsAndNewlines = url.replace(/[\\t\\n\\r]/g, '');\n let start = 0;\n let end = withoutTabsAndNewlines.length;\n while (start < end && withoutTabsAndNewlines.charCodeAt(start) <= 0x20) {\n start++;\n }\n while (end > start && withoutTabsAndNewlines.charCodeAt(end - 1) <= 0x20) {\n end--;\n }\n return withoutTabsAndNewlines.slice(start, end);\n}\n\n/**\n * Returns true when the URL is relative (including fragment-only and\n * query-only URLs) or uses the http, https or mailto scheme. Every other\n * scheme, such as `javascript:`, `data:`, `vbscript:`, `file:` and `blob:`,\n * is unsafe.\n *\n * @param url An attribute value as the DOM returns it (entities decoded).\n * @returns Whether the URL may be written to an `href`-like attribute. A\n * value that is not a string is never safe.\n *\n * @example\n * isSafeUrl('https://example.com'); // true\n * isSafeUrl('#top'); // true\n * isSafeUrl(' JavaScript:alert(1)'); // false\n */\nexport function isSafeUrl(url: string): boolean {\n if (typeof url !== 'string') {\n return false;\n }\n const scheme = SCHEME_PATTERN.exec(normalizeUrl(url));\n return !scheme || SAFE_SCHEMES.has(scheme[1].toLowerCase());\n}\n\nfunction isAllowedAttribute(tagName: string, attributeName: string): boolean {\n return (\n GLOBAL_ATTRIBUTES.has(attributeName) ||\n TAG_ATTRIBUTES[tagName]?.has(attributeName) === true\n );\n}\n\nconst ELEMENT_NODE = 1;\nconst TEXT_NODE = 3;\n\n/**\n * Creates a clean copy of an allowed element: same tag, only the allowed\n * attributes, and no children (those are copied by the walk).\n */\nfunction copyAllowedElement(source: Element, doc: Document): Element {\n const tagName = source.localName;\n const copy = doc.createElement(tagName);\n for (const attribute of Array.from(source.attributes)) {\n const name = attribute.name.toLowerCase();\n if (\n isAllowedAttribute(tagName, name) &&\n (!URL_ATTRIBUTE_NAMES.has(name) || isSafeUrl(attribute.value))\n ) {\n copy.setAttribute(name, attribute.value);\n }\n }\n if (tagName === 'a' && copy.hasAttribute('target')) {\n // A link that opens another browsing context must not hand it a\n // reference back to this page.\n copy.setAttribute('rel', 'noopener noreferrer');\n }\n return copy;\n}\n\n/**\n * Sanitizes an HTML fragment against a small allowlist so it can be inserted\n * with `innerHTML` / jQuery `.html()`.\n *\n * - Elements in {@link ALLOWED_TAGS} (inline formatting such as `br`,\n * `strong`, `em`, `span`, `a`) are kept.\n * - `script`, `style`, `iframe`, `object`, `embed`, `svg`, `math`,\n * `template`, `noscript` and other raw-text or embedding elements are\n * removed together with their content. Elements outside the HTML\n * namespace are removed the same way.\n * - Every other element (for example `div`, `p`, `img`, `button`) is\n * unwrapped: the element goes, its sanitized text and children stay.\n * - Only `class`, `dir`, `lang` and `title` are kept on every element, plus\n * `href`, `hreflang` and `target` on `a`, `cite` on `q`/`del`/`ins`, and\n * `datetime` on `time`/`del`/`ins`. All `on*` handlers, `style`, `id` and\n * `data-*` attributes are removed.\n * - `href` and `cite` values are kept only when {@link isSafeUrl} accepts\n * them (http, https, mailto, relative and fragment URLs).\n * - Links with a `target` get `rel=\"noopener noreferrer\"`.\n * - Comments are removed.\n *\n * The input is parsed in a `<template>` element, whose content is inert: no\n * scripts run and no resources load while it is inspected. The result is\n * built as a fresh tree of copied text and allowed elements, so nothing of\n * the parsed input is reused.\n *\n * @param html The untrusted HTML fragment. `null` and `undefined` give an\n * empty string; any other value that is not a string is converted with\n * `String()` and then sanitized, so a node or object is never passed through.\n * @param doc The document used to parse the fragment. Defaults to the global\n * `document`.\n * @returns The sanitized HTML, always a string.\n *\n * @example\n * sanitizeHtml('Hi<br><strong>there</strong><img src=x onerror=alert(1)>');\n * // 'Hi<br><strong>there</strong>'\n */\nexport function sanitizeHtml(html: string, doc: Document = document): string {\n if (typeof html !== 'string') {\n if (html === null || html === undefined) {\n return '';\n }\n html = String(html);\n }\n if (!/[<&]/.test(html)) {\n return html;\n }\n\n const input = doc.createElement('template');\n input.innerHTML = html;\n const output = doc.createElement('template');\n const outputDoc = output.content.ownerDocument;\n\n // Iterative pre-order walk (children are pushed in reverse so they pop in\n // document order). Every node is appended to its output parent in\n // document order, an unwrapped element's children go to the unwrapped\n // element's own output parent, and deep nesting cannot overflow the stack.\n const pending: Array<[source: Node, target: Node]> = [];\n const pushChildren = (source: Node, target: Node) => {\n const children = source.childNodes;\n for (let i = children.length - 1; i >= 0; i--) {\n pending.push([children[i], target]);\n }\n };\n pushChildren(input.content, output.content);\n\n while (pending.length > 0) {\n const [source, target] = pending.pop()!;\n if (source.nodeType === TEXT_NODE) {\n target.appendChild(outputDoc.createTextNode(source.nodeValue ?? ''));\n continue;\n }\n if (source.nodeType !== ELEMENT_NODE) {\n continue;\n }\n\n const element = source as Element;\n const tagName = element.localName;\n if (\n element.namespaceURI !== HTML_NAMESPACE ||\n DROPPED_WITH_CONTENT.has(tagName)\n ) {\n continue;\n }\n\n if (ALLOWED_TAGS.has(tagName)) {\n const copy = target.appendChild(copyAllowedElement(element, outputDoc));\n pushChildren(element, copy);\n } else {\n pushChildren(element, target);\n }\n }\n\n return output.innerHTML;\n}\n","import {URL_ATTRIBUTE_NAMES} from '@util/sanitize-html.ts';\n\nconst FORBIDDEN_ATTRIBUTE_PATTERN = /^(on.*|srcdoc)$/i;\n\nconst SCRIPT_URL_PATTERN = /^(javascript|vbscript):/i;\n\n/**\n * Browsers ignore tabs and newlines anywhere in a URL and C0 controls and spaces around it,\n * so 'java\\tscript:' still runs. Removing every such character is stricter, which is fine here.\n */\nfunction withoutIgnoredUrlCharacters(url: string): string {\n return Array.from(url)\n .filter(char => char.charCodeAt(0) > 0x20)\n .join('');\n}\n\n/**\n * Throws when writing the attribute could run script: an event handler (`on*`) or `srcdoc`\n * attribute, or a URL attribute (such as `href`, `src` or `formaction`) whose value is a\n * `javascript:` or `vbscript:` URL.\n *\n * @param operationName The operation writing the attribute, named in the error.\n * @param name The attribute name.\n * @param value The attribute value. `undefined` and `null` are not checked, since they are\n * not written.\n * @throws When the attribute name or the URL value is refused. The value is not part of the\n * message, since it may be user data.\n */\nexport function assertSafeAttribute(\n operationName: string,\n name: string,\n value: unknown\n): void {\n const attributeName = String(name).trim().toLowerCase();\n if (FORBIDDEN_ATTRIBUTE_PATTERN.test(attributeName)) {\n throw new Error(\n `${operationName}: attribute '${name}' is not allowed. Event handler (on*) and srcdoc attributes are refused.`\n );\n }\n if (\n URL_ATTRIBUTE_NAMES.has(attributeName) &&\n value !== undefined &&\n value !== null &&\n // Stringified the way the DOM writes it, so a toString() returning a\n // script URL is caught too\n // oxlint-disable-next-line typescript/no-base-to-string\n SCRIPT_URL_PATTERN.test(withoutIgnoredUrlCharacters(String(value)))\n ) {\n throw new Error(\n `${operationName}: attribute '${name}' must not hold a javascript: or vbscript: URL.`\n );\n }\n}\n","import {assertSafeAttribute} from '@operation/helper/assert-safe-attribute.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport {resolvePropertyValues} from '@operation/helper/resolve-property-values.ts';\nimport type {IOperationScope, TOperation} from '@operation/types.ts';\nimport $ from 'jquery';\nimport type {RequireKeys} from '@/types.ts';\n\nexport type TTagNames = keyof HTMLElementTagNameMap;\n\nconst validElementName = /^[a-z][a-z0-9-]*$/i;\n\nexport interface ICreateElementOperationData<T extends TTagNames> {\n /**\n * @type=ParameterType:htmlElementName\n * @required\n * @erased\n */\n elementName: T;\n /**\n * @erased\n */\n text?: string;\n /**\n * @type=ParameterType:object\n * @erased\n */\n attributes?: Partial<HTMLElementTagNameMap[T]>;\n /**\n * @type=ParameterType:object\n * @output\n */\n template?: JQuery;\n}\n\n/**\n * This operation creates the DOM element described by the given elementName and attributes and assigns\n * the instance to the `template` property on the current operation data.\n *\n * The element is built with DOM APIs: attribute values are set with `.attr()` and `text` is set as\n * text content, so neither is parsed as HTML.\n *\n * Values may be resolved from user data, so nothing that runs script is created: `script`\n * elements, event handler (`on*`) and `srcdoc` attributes, and `javascript:` or `vbscript:`\n * URLs in URL attributes such as `href`, `src` and `formaction` are refused.\n *\n * @param operationData\n * @returns\n * @throws When `elementName` is not a valid element name or is `script`, or when an attribute\n * is refused (see above). The message names the operation.\n * @category DOM\n */\nexport const createElement: TOperation<\n ICreateElementOperationData<TTagNames>,\n Omit<\n RequireKeys<ICreateElementOperationData<TTagNames>, 'template'>,\n 'elementName' | 'text' | 'attributes'\n >\n> = function <T extends TTagNames>(\n this: IOperationScope,\n operationData: ICreateElementOperationData<T>\n) {\n // Resolve only this operation's own properties: other operation data is\n // passed on to later operations untouched.\n const {elementName, attributes, text} = resolvePropertyValues(\n operationData,\n this,\n {\n elementName: operationData.elementName,\n attributes: operationData.attributes,\n text: operationData.text,\n }\n ) as Pick<\n ICreateElementOperationData<T>,\n 'elementName' | 'attributes' | 'text'\n >;\n\n removeProperties(operationData, 'elementName', 'attributes', 'text');\n\n if (!validElementName.test(String(elementName))) {\n throw new Error(\n `createElement: invalid elementName '${String(elementName)}', expected a tag name such as 'div' or 'my-element'`\n );\n }\n\n if (String(elementName).toLowerCase() === 'script') {\n throw new Error(\n \"createElement: elementName 'script' is not allowed, configuration may not create scripts\"\n );\n }\n\n const entries = Object.entries(attributes ?? {}).filter(([_, value]) =>\n Boolean(value)\n );\n // Check every attribute before the element is created\n entries.forEach(([key, value]) => {\n assertSafeAttribute('createElement', key, value);\n });\n\n const template = $<HTMLElement>(document.createElement(elementName));\n\n entries.forEach(([key, value]) => {\n template.attr(key, String(value));\n });\n\n if (text) {\n template.text(text);\n }\n\n operationData.template = template;\n\n return operationData as RequireKeys<\n ICreateElementOperationData<TTagNames>,\n 'template'\n >;\n};\n","/**\n * Looks up the entry registered under `systemName` with `lookup` (one of the\n * engine services, such as `this.services.getAction`), and fails with an\n * error that names the calling operation when the lookup throws or answers\n * `undefined` or `null`.\n *\n * A message thrown by the lookup (such as the importer's \"did you mean\"\n * hint) is kept, and the original error becomes the `cause`.\n *\n * @param operationName - The name of the calling operation, used as the message prefix\n * @param systemName - The configured name to look up\n * @param lookup - Returns the entry for a name, or throws for an unknown one\n * @param noun - What is being looked up, for the message (for example `'controller'`)\n * @returns The registered entry, never `undefined` or `null`\n * @throws Error when the lookup throws or nothing is registered under `systemName`\n */\nexport function lookupNamedEntry(\n operationName: string,\n systemName: string,\n lookup: (systemName: string) => unknown,\n noun?: string\n): unknown {\n let entry: unknown;\n try {\n entry = lookup(systemName);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n const what = noun ? `${noun} '${systemName}'` : `'${systemName}'`;\n throw new Error(`${operationName}: could not retrieve ${what}. ${reason}`, {\n cause: error,\n });\n }\n\n if (entry === undefined || entry === null) {\n const nothing = noun ? `no ${noun}` : 'nothing';\n throw new Error(\n `${operationName}: ${nothing} registered for systemName '${systemName}'. Check the spelling, or make sure the resource importer provides it.`\n );\n }\n\n return entry;\n}\n","export function isFunction(value: any): value is (...arg: any) => any {\n return typeof value === 'function';\n}\n","import {internalResolve} from '@operation/helper/internal-resolve.ts';\nimport {lookupNamedEntry} from '@operation/helper/lookup-named-entry.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {IOperationScope, TOperation} from '@operation/types.ts';\nimport {isFunction} from '@util/guards/is-function.ts';\nimport {isPromise} from '@util/guards/is-promise.ts';\n\nexport interface ICustomFunctionOperationData {\n /**\n * @type=ParameterType:systemName\n * @erased\n * @required\n */\n systemName: string;\n}\n\n/**\n * This operation retrieves a custom function defined by the given system name\n * and invokes it with the current operation data and eventbus.\n *\n * The function is looked up with `this.services.getImport`, which answers from\n * the engine's resource importer. Register the function\n * with the `EligiusResourceImporter` constructor:\n * `new EligiusResourceImporter({functions: {myFunction}})`.\n *\n * The function is called with the current operation data as its argument, and with `this`\n * set to a view of the operation scope. Reading a property from `this` returns it from the\n * innermost scope that has it, so inside a `when` block in a loop `this.currentItem`,\n * `this.loopIndex` and `this.variables` return the loop's and the action's values, the same\n * as `$scope.` chains. Assigning to `this` (for example `this.newIndex`) writes to the scope the\n * operation runs in.\n *\n * @param operationData\n * @throws Error naming the operation and the `systemName` when nothing is\n * registered under that name (with the closest registered names when the\n * importer can suggest them), or when the registered value is not a function.\n *\n * @category Utility\n */\nexport const customFunction: TOperation<\n ICustomFunctionOperationData,\n Omit<ICustomFunctionOperationData, 'systemName'>\n> = function (operationData: ICustomFunctionOperationData) {\n const {systemName} = operationData;\n\n removeProperties(operationData, 'systemName');\n\n const func = lookupNamedEntry(\n 'customFunction',\n systemName,\n name => this.services.getImport(name),\n 'function'\n );\n\n if (!isFunction(func)) {\n throw new Error(\n `customFunction: systemName '${systemName}' does not resolve to a function.`\n );\n }\n\n const result = func.apply(createScopeView(this), [operationData]);\n // The function's return value is ignored, but a promise is awaited. Only a real\n // thenable takes that path; a synchronous function may return anything.\n if (result !== null && isPromise(result)) {\n return new Promise<ICustomFunctionOperationData>((resolve, reject) => {\n result.then(() => {\n internalResolve(resolve, {}, operationData);\n }, reject);\n });\n }\n\n return operationData;\n};\n\n/**\n * Returns a view of `scope` whose reads fall through to the parent scopes for properties the\n * scope itself does not have (the same rule `$scope.` chains use). Writes and deletes go to\n * `scope` itself.\n */\nfunction createScopeView(scope: IOperationScope): IOperationScope {\n if (!scope?.parent) {\n return scope;\n }\n return new Proxy(scope, {\n get(target, property) {\n let current: IOperationScope | undefined = target;\n while (current) {\n if (property in current) {\n return Reflect.get(current, property, current);\n }\n current = current.parent;\n }\n return undefined;\n },\n has(target, property) {\n let current: IOperationScope | undefined = target;\n while (current) {\n if (property in current) {\n return true;\n }\n current = current.parent;\n }\n return false;\n },\n });\n}\n","import type {IEndableAction} from '@action/types.ts';\nimport {internalResolve} from '@operation/helper/internal-resolve.ts';\nimport {mergeOperationData} from '@operation/helper/merge-operation-data.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IEndActionOperationData {\n /**\n * @dependency\n */\n actionInstance: IEndableAction;\n /**\n * @type=ParameterType:object\n * @erased\n */\n actionOperationData?: Record<string, unknown>;\n}\n\n/**\n * This operation invokes the {@link EndableAction}.end method on the specified action instance.\n *\n * The action receives its own copy of the current operation data merged with the action\n * operation data. Whatever the action's end operations add, change or remove in that copy stays\n * with the action: once it has completed, this operation continues with the operation data it\n * had before, without the `actionOperationData` property.\n *\n * @category Action\n */\nexport const endAction: TOperation<\n IEndActionOperationData,\n Omit<IEndActionOperationData, 'actionOperationData'>\n> = (operationData: IEndActionOperationData) => {\n const {actionOperationData = {}, ...callerOperationData} = operationData;\n\n return new Promise<Omit<IEndActionOperationData, 'actionOperationData'>>(\n (resolve, reject) => {\n const {actionInstance} = callerOperationData;\n if (!actionInstance) {\n reject(new Error('endAction: actionInstance is required'));\n return;\n }\n\n // The catch also rejects on errors thrown by the fulfilment handler, so the\n // returned promise always settles.\n actionInstance\n .end(mergeOperationData(callerOperationData, actionOperationData))\n .then(() => {\n internalResolve(resolve, {...callerOperationData});\n })\n .catch(reject);\n }\n );\n};\n","import {clearLoopCollection} from '@operation/for-each.ts';\nimport type {TOperation, TOperationData} from '@operation/types.ts';\n\n/**\n * This operation checks if the current loop should end or start the next iteration.\n *\n * @category Control Flow\n */\nexport const endForEach: TOperation<TOperationData> = function (\n operationData: TOperationData\n) {\n if (\n this.loopIndex !== undefined &&\n this.loopLength !== undefined &&\n this.loopIndex < this.loopLength\n ) {\n this.loopIndex = this.loopIndex + 1;\n this.newIndex = this.loopStartIndex;\n delete this.currentItem;\n } else {\n clearLoopCollection(this);\n }\n\n return operationData;\n};\n","import {continuePendingLoopJump} from '@operation/helper/loop-jump.ts';\nimport type {TOperation} from '@operation/types.ts';\n\n/**\n * This operation cleans up after the {@link when}/{@link otherwise}/{@link endWhen} control flow ends.\n *\n * @category Control Flow\n */\nexport const endWhen: TOperation<Record<string, unknown>> = function (\n operationData: Record<string, unknown>\n) {\n delete this.whenEvaluation;\n continuePendingLoopJump(this);\n return operationData;\n};\n","import type {IController} from '@controllers/types.ts';\nimport {isForbiddenPropertyChainSegment} from '@operation/helper/assert-safe-property-chain.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation, TOperationData} from '@operation/types.ts';\n\n/**\n * This operation extends the specified controller instance with the specified extension.\n */\nexport interface IExtendControllerOperationData {\n /**\n * @dependency\n */\n controllerInstance: IController<TOperationData>;\n /**\n * @erased\n * @required\n */\n controllerExtension: Record<PropertyKey, unknown>;\n}\n\n/**\n * Extends the current controller with given extension.\n *\n * The extension's own properties are copied onto the controller instance.\n *\n * @throws When the extension has a `__proto__`, `prototype` or `constructor` key, which would\n * replace the controller's prototype or shadow its class.\n *\n * @category Controller\n */\nexport const extendController: TOperation<\n IExtendControllerOperationData,\n Omit<IExtendControllerOperationData, 'controllerExtension'>\n> = (operationData: IExtendControllerOperationData) => {\n const {controllerInstance, controllerExtension} = operationData;\n\n removeProperties(operationData, 'controllerExtension');\n\n // A JSON-parsed extension can carry an own '__proto__' key; Object.assign would\n // pass it to the '__proto__' setter and swap the controller's prototype.\n const forbiddenKey = Object.keys(controllerExtension ?? {}).find(\n isForbiddenPropertyChainSegment\n );\n if (forbiddenKey !== undefined) {\n throw new Error(\n `extendController: controllerExtension must not contain a '${forbiddenKey}' key`\n );\n }\n\n operationData.controllerInstance = Object.assign(\n controllerInstance,\n controllerExtension\n );\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IFilterArrayOperationData {\n /**\n * @dependency\n */\n arrayData: any[];\n /**\n * @optional\n * @erased\n */\n filterProperty?: string;\n /**\n * @optional\n * @erased\n */\n filterValue?: any;\n /**\n * @optional\n * @erased\n */\n filterPredicate?: (item: any, index?: number) => boolean;\n /**\n * @output\n */\n filteredArray?: any[];\n}\n\n/**\n * Filters an array based on property equality or custom predicate function.\n *\n * Operates on arrayData passed from previous operations.\n * Supports two filtering modes:\n * 1. Property equality: `filterProperty` and `filterValue` to filter by property match\n * 2. Custom predicate: `filterPredicate` function for complex filtering logic\n *\n * @returns Operation data with `filteredArray` containing filtered results\n *\n * @example\n * ```typescript\n * // Filter by property equality\n * const result = filterArray({\n * arrayData: [{name: 'Alice', age: 25}, {name: 'Bob', age: 30}],\n * filterProperty: 'age',\n * filterValue: 25\n * });\n * // result.filteredArray = [{name: 'Alice', age: 25}]\n * ```\n *\n * @example\n * ```typescript\n * // Filter with custom predicate\n * const result = filterArray({\n * arrayData: [1, 2, 3, 4, 5],\n * filterPredicate: (item) => item % 2 === 0\n * });\n * // result.filteredArray = [2, 4]\n * ```\n *\n * @category Array\n */\nexport const filterArray: TOperation<\n IFilterArrayOperationData,\n Omit<\n IFilterArrayOperationData,\n 'filterProperty' | 'filterValue' | 'filterPredicate'\n >\n> = (operationData: IFilterArrayOperationData) => {\n const {arrayData, filterProperty, filterValue, filterPredicate} =\n operationData;\n\n if (!Array.isArray(arrayData)) {\n throw new Error('filterArray: arrayData is required and must be an array');\n }\n\n if (!filterPredicate && (!filterProperty || filterValue === undefined)) {\n throw new Error(\n 'filterArray: filterProperty/filterValue or filterPredicate is required'\n );\n }\n\n let filtered: any[];\n\n if (filterPredicate) {\n filtered = arrayData.filter(filterPredicate);\n } else {\n filtered = arrayData.filter(item => {\n if (typeof item === 'object' && item !== null) {\n return item[filterProperty!] === filterValue;\n }\n return false;\n });\n }\n\n operationData.filteredArray = filtered;\n\n removeProperties(\n operationData,\n 'filterProperty',\n 'filterValue',\n 'filterPredicate'\n );\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IFindInArrayOperationData {\n /**\n * @dependency\n */\n arrayData: any[];\n /**\n * @optional\n * @erased\n */\n findProperty?: string;\n /**\n * @optional\n * @erased\n */\n findValue?: any;\n /**\n * @optional\n * @erased\n */\n findPredicate?: (item: any, index?: number) => boolean;\n /**\n * @output\n */\n foundItem?: any;\n /**\n * @output\n */\n foundIndex?: number;\n}\n\n/**\n * Finds the first element in an array matching criteria.\n *\n * Operates on arrayData passed from previous operations.\n * Supports two search modes:\n * 1. Property equality: `findProperty` and `findValue` to find by property match\n * 2. Custom predicate: `findPredicate` function for complex search logic\n *\n * Returns `undefined` for `foundItem` and `-1` for `foundIndex` if no match found.\n *\n * @returns Operation data with `foundItem` (the matching element) and `foundIndex` (its position)\n *\n * @example\n * ```typescript\n * // Find by property equality\n * const result = findInArray({\n * arrayData: [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}],\n * findProperty: 'id',\n * findValue: 2\n * });\n * // result.foundItem = {id: 2, name: 'Bob'}\n * // result.foundIndex = 1\n * ```\n *\n * @example\n * ```typescript\n * // Find with custom predicate\n * const result = findInArray({\n * arrayData: [10, 25, 30, 45],\n * findPredicate: (item) => item > 30\n * });\n * // result.foundItem = 45\n * // result.foundIndex = 3\n * ```\n *\n * @category Array\n */\nexport const findInArray: TOperation<\n IFindInArrayOperationData,\n Omit<\n IFindInArrayOperationData,\n 'findProperty' | 'findValue' | 'findPredicate'\n >\n> = (operationData: IFindInArrayOperationData) => {\n const {arrayData, findProperty, findValue, findPredicate} = operationData;\n\n if (!Array.isArray(arrayData)) {\n throw new Error('findInArray: arrayData is required and must be an array');\n }\n\n if (!findPredicate && (!findProperty || findValue === undefined)) {\n throw new Error(\n 'findInArray: findProperty/findValue or findPredicate is required'\n );\n }\n\n let foundItem: any;\n let foundIndex = -1;\n\n if (findPredicate) {\n foundIndex = arrayData.findIndex(findPredicate);\n foundItem = foundIndex !== -1 ? arrayData[foundIndex] : undefined;\n } else {\n foundIndex = arrayData.findIndex(item => {\n if (typeof item === 'object' && item !== null) {\n return item[findProperty!] === findValue;\n }\n return item === findValue;\n });\n foundItem = foundIndex !== -1 ? arrayData[foundIndex] : undefined;\n }\n\n operationData.foundItem = foundItem;\n operationData.foundIndex = foundIndex;\n\n removeProperties(operationData, 'findProperty', 'findValue', 'findPredicate');\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IFormatDateOperationData {\n /**\n * @dependency\n */\n date: Date | string | number;\n /**\n * @required\n * @erased\n */\n format: string;\n /**\n * @output\n */\n formattedDate?: string;\n}\n\nconst FORMAT_TOKENS = /YYYY|MM|DD|HH|mm|ss/g;\n\n/**\n * Formats a date with a simple token pattern, in the local time zone.\n *\n * Supported tokens (every occurrence is replaced, other characters are kept as is):\n * - `YYYY`: four digit year\n * - `MM`: month, 01-12\n * - `DD`: day of the month, 01-31\n * - `HH`: hours, 00-23\n * - `mm`: minutes, 00-59\n * - `ss`: seconds, 00-59\n *\n * @throws When the date is missing or invalid.\n *\n * @example\n * ```typescript\n * formatDate({date: new Date(2024, 0, 5, 14, 5), format: 'HH:mm-HH:mm DD/MM/YYYY'});\n * // formattedDate = \"14:05-14:05 05/01/2024\"\n * ```\n *\n * @category Date\n */\nexport const formatDate: TOperation<\n IFormatDateOperationData,\n Omit<IFormatDateOperationData, 'format'>\n> = (operationData: IFormatDateOperationData) => {\n const {date, format} = operationData;\n\n if (date == null || date === '') {\n throw new Error('formatDate: date is required');\n }\n\n const dateObj = date instanceof Date ? date : new Date(date);\n\n if (Number.isNaN(dateObj.getTime())) {\n throw new Error('formatDate: invalid date');\n }\n\n const pad = (value: number) => String(value).padStart(2, '0');\n const tokens: Record<string, string> = {\n YYYY: String(dateObj.getFullYear()),\n MM: pad(dateObj.getMonth() + 1),\n DD: pad(dateObj.getDate()),\n HH: pad(dateObj.getHours()),\n mm: pad(dateObj.getMinutes()),\n ss: pad(dateObj.getSeconds()),\n };\n\n // One pass, so a replaced value is never matched again as a token\n operationData.formattedDate = format.replace(\n FORMAT_TOKENS,\n token => tokens[token]\n );\n\n removeProperties(operationData, 'format');\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport type TextTransformation =\n | 'uppercase'\n | 'lowercase'\n | 'capitalize'\n | 'titlecase'\n | 'trim';\n\nexport interface IFormatTextOperationData {\n /**\n * @dependency\n */\n textContent: string;\n /**\n * @required\n * @erased\n */\n transformation: TextTransformation;\n /**\n * @output\n */\n formattedText?: string;\n}\n\n/**\n * Transforms text using format operations: uppercase, lowercase, capitalize, titlecase, or trim.\n *\n * Operates on textContent passed from previous operations (e.g., getTextContent).\n *\n * Transformations:\n * - `uppercase`: Convert all characters to uppercase\n * - `lowercase`: Convert all characters to lowercase\n * - `capitalize`: Capitalize only the first letter\n * - `titlecase`: Capitalize first letter of each word\n * - `trim`: Remove leading and trailing whitespace\n *\n * @returns Operation data with `formattedText` containing the transformed text\n *\n * @example\n * ```typescript\n * // Convert to uppercase\n * const result = formatText({\n * textContent: 'hello',\n * transformation: 'uppercase'\n * });\n * // result.formattedText = \"HELLO\"\n * ```\n *\n * @example\n * ```typescript\n * // Title case\n * const result = formatText({\n * textContent: 'hello world',\n * transformation: 'titlecase'\n * });\n * // result.formattedText = \"Hello World\"\n * ```\n *\n * @category Text\n */\nexport const formatText: TOperation<\n IFormatTextOperationData,\n Omit<IFormatTextOperationData, 'transformation'>\n> = (operationData: IFormatTextOperationData) => {\n const {textContent, transformation} = operationData;\n\n if (textContent === undefined || textContent === null) {\n throw new Error('formatText: textContent is required');\n }\n\n let text = textContent;\n\n switch (transformation) {\n case 'uppercase':\n text = text.toUpperCase();\n break;\n case 'lowercase':\n text = text.toLowerCase();\n break;\n case 'capitalize':\n text = text.charAt(0).toUpperCase() + text.slice(1);\n break;\n case 'titlecase':\n // A letter starts a word unless a letter, digit or apostrophe precedes it\n text = text.replace(/(?<![\\p{L}\\p{N}'’])\\p{L}/gu, char =>\n char.toUpperCase()\n );\n break;\n case 'trim':\n text = text.trim();\n break;\n default:\n throw new Error(\n `formatText: unknown transformation type \"${String(transformation)}\"`\n );\n }\n\n operationData.formattedText = text;\n\n removeProperties(operationData, 'transformation');\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IGetAttributesFromElementOperationData {\n /**\n * The HTML element whose attributes will be retrieved\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * The specified attribute names that will be retrieved\n * @required\n * @erased\n */\n attributeNames: string[];\n /**\n * The retrieved attributes\n * @output\n */\n attributeValues?: Record<string, unknown>;\n}\n\n/**\n * This operation retrieves the values for the specified attribute names from the given selected element.\n *\n * @category DOM\n */\nexport const getAttributesFromElement: TOperation<\n IGetAttributesFromElementOperationData,\n Omit<IGetAttributesFromElementOperationData, 'attributeNames'>\n> = (operationData: IGetAttributesFromElementOperationData) => {\n const {selectedElement, attributeNames} = operationData;\n\n removeProperties(operationData, 'attributeNames');\n\n operationData.attributeValues = attributeNames.reduce(\n (acc, attrName) => {\n if (attrName !== 'value') {\n acc[attrName] = selectedElement.attr(attrName);\n } else {\n acc[attrName] = selectedElement.val();\n }\n return acc;\n },\n {} as Record<string, unknown>\n );\n\n return operationData;\n};\n","import type {IController} from '@controllers/types.ts';\nimport {getElementControllers} from '@operation/helper/get-element-data.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IGetControllerFromElementOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @type=ParameterType:controllerName\n * @required\n * @erased\n */\n controllerName: string;\n /**\n * @type=ParameterType:object\n * @output\n */\n controllerInstance?: IController<any>;\n}\n\n/**\n * This operation retrieves the controller instance with the specified name that is assigned to the given selected element.\n *\n * @param operationData\n * @returns\n *\n * @category Controller\n */\nexport const getControllerFromElement: TOperation<\n IGetControllerFromElementOperationData,\n Omit<IGetControllerFromElementOperationData, 'controllerName'>\n> = (operationData: IGetControllerFromElementOperationData) => {\n const {selectedElement, controllerName} = operationData;\n\n removeProperties(operationData, 'controllerName');\n\n const controllers = getElementControllers(selectedElement);\n const controller = controllers?.find(ctrl => ctrl.name === controllerName);\n\n if (!controller) {\n console.warn(\n `controller for name '${controllerName}' was not found on the given element`\n );\n }\n\n operationData.controllerInstance = controller;\n return operationData;\n};\n","import type * as controllers from '@controllers/index.ts';\nimport type {IController} from '@controllers/types.ts';\nimport {lookupNamedEntry} from '@operation/helper/lookup-named-entry.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation, TOperationData} from '@operation/types.ts';\n\ntype TSystemName = keyof typeof controllers;\nexport interface IGetControllerInstanceOperationData {\n /**\n * The name of a built-in controller, or of a controller registered on the\n * `EligiusResourceImporter`.\n *\n * @type=ParameterType:controllerName\n * @required\n * @erased\n */\n systemName: TSystemName | (string & {});\n /**\n * @type=ParameterType:object\n * @output\n */\n controllerInstance?: IController<TOperationData>;\n}\n\n/**\n * This operation retrieves an instance of the given controller name.\n * It assigns this instance to the `controllerInstance` property on the current operation data\n *\n * @throws Error naming getControllerInstance and the `systemName` when no controller is\n * registered under that name, or when creating it fails (for example because the name\n * belongs to something that is not a controller class). The importer's \"did you mean\"\n * hint is kept in the message and the original error is the `cause`.\n *\n * @category Controller\n */\nexport const getControllerInstance: TOperation<\n IGetControllerInstanceOperationData,\n Omit<IGetControllerInstanceOperationData, 'systemName'>\n> = function (operationData: IGetControllerInstanceOperationData) {\n const {systemName} = operationData;\n\n removeProperties(operationData, 'systemName');\n\n operationData.controllerInstance = lookupNamedEntry(\n 'getControllerInstance',\n systemName,\n name => this.services.createInstance(name),\n 'controller'\n ) as IController<TOperationData>;\n\n return operationData;\n};\n","import type {TOperation} from '@operation/types.ts';\n\nexport interface IGetCurrentTimeOperationData {\n /**\n * @output\n */\n timestamp?: number;\n /**\n * @output\n */\n date?: Date;\n}\n\n/**\n * Gets the current time as timestamp and Date object.\n *\n * @category Date\n */\nexport const getCurrentTime: TOperation<\n IGetCurrentTimeOperationData,\n IGetCurrentTimeOperationData\n> = (operationData: IGetCurrentTimeOperationData) => {\n const now = new Date();\n operationData.timestamp = now.getTime();\n operationData.date = now;\n return operationData;\n};\n","import type {IDimensions} from '../../types.ts';\n\n// h[ar=8-1]\nconst ratioModifierPattern = /^([hw])\\[ar=([^\\]]*)\\]$/;\nconst ratioPattern = /^\\d+(\\.\\d+)?$/;\n\nfunction _modifyDimensionsByRatio(\n ratioModifier: string,\n dimensions: IDimensions,\n modifier: string\n) {\n const modifiedDimensions = {...dimensions};\n const match = ratioModifierPattern.exec(ratioModifier);\n if (!match) {\n throw invalidModifier(\n modifier,\n `ratio modifier '${ratioModifier}' must look like 'h[ar=8-1]' or 'w[ar=8-1]'`\n );\n }\n const [, prefix, ratio] = match;\n const ratios = ratio.split('-');\n\n if (ratios.length !== 2 || !ratios.every(part => ratioPattern.test(part))) {\n throw invalidModifier(\n modifier,\n `expected two ratios, as in 'ar=8-1', but got 'ar=${ratio}'`\n );\n }\n\n if (prefix === 'h') {\n modifiedDimensions.height =\n (modifiedDimensions.width / +ratios[0]) * +ratios[1];\n } else if (prefix === 'w') {\n modifiedDimensions.width =\n (modifiedDimensions.height / +ratios[1]) * +ratios[0];\n }\n\n return modifiedDimensions;\n}\n\nfunction _getModifierSuffix(\n modifier: string //*100h%\n): [string | null, number, boolean] {\n const endIdx = 1;\n let suffix: string | null = modifier.substring(\n modifier.length - endIdx,\n modifier.length\n );\n\n if (suffix !== 'h' && suffix !== 'w' && suffix !== '%') {\n suffix = null;\n }\n\n const isPercent = suffix === '%';\n\n if (isPercent) {\n suffix = modifier.substring(\n modifier.length - endIdx,\n modifier.length - (endIdx + 1)\n );\n\n if (suffix !== 'h' && suffix !== 'w') {\n suffix = null;\n }\n }\n\n return [suffix, endIdx, isPercent];\n}\n\nfunction _modifyDimensions(\n dimensions: IDimensions,\n prefix: string,\n suffix: string | null,\n widthModifier: number,\n heightModifier: number\n) {\n const modifiedDimension = {...dimensions};\n switch (prefix) {\n case '+':\n switch (suffix) {\n case 'h':\n modifiedDimension.height += heightModifier;\n break;\n case 'w':\n modifiedDimension.width += widthModifier;\n break;\n default:\n modifiedDimension.height += heightModifier;\n modifiedDimension.width += widthModifier;\n }\n break;\n case '-':\n switch (suffix) {\n case 'h':\n modifiedDimension.height -= heightModifier;\n break;\n case 'w':\n modifiedDimension.width -= widthModifier;\n break;\n default:\n modifiedDimension.height -= heightModifier;\n modifiedDimension.width -= widthModifier;\n }\n break;\n case '/':\n switch (suffix) {\n case 'h':\n modifiedDimension.height /= heightModifier;\n break;\n case 'w':\n modifiedDimension.width /= widthModifier;\n break;\n default:\n modifiedDimension.height /= heightModifier;\n modifiedDimension.width /= widthModifier;\n }\n break;\n case '*':\n switch (suffix) {\n case 'h':\n modifiedDimension.height *= heightModifier;\n break;\n case 'w':\n modifiedDimension.width *= widthModifier;\n break;\n default:\n modifiedDimension.height *= heightModifier;\n modifiedDimension.width *= widthModifier;\n }\n break;\n }\n return modifiedDimension;\n}\n\nconst operators = ['+', '-', '/', '*'];\n\nfunction invalidModifier(modifier: string, reason: string) {\n return new Error(\n `modifyDimensions: invalid modifier '${modifier}': ${reason}.`\n );\n}\n\n/**\n * Modifies the given dimensions using the given modifier string.\n * The modifier string is formatted in the following way:\n *\n * <operator><amount><optional-side><optional-precentage>|<ratio-definition>\n *\n * Where the ratio modifier is formatted in the following way:\n * <side>[ar=<ratio-left>-<ratio-right>]\n *\n * For example, this modifier '+100h|w[ar=8-1]' will modifiy the dimensions like this:\n * it will add a value of 100 to the height and modify the width by a ration of 8 to 1 relative to the height.\n *\n * @param dimensions\n * @param modifier\n * @throws When the operator is not one of + - / *, the amount is not a number, or the ratio\n * modifier is malformed. The message names the modifier.\n */\nexport function modifyDimensions(dimensions: IDimensions, modifier: string) {\n const fullModifier = modifier;\n const clonedDimensions = {...dimensions};\n let ratioModifier: string | null = null;\n if (modifier.indexOf('|') > -1) {\n [modifier, ratioModifier] = modifier.split('|');\n }\n\n const prefix = modifier.substring(0, 1);\n if (!operators.includes(prefix)) {\n throw invalidModifier(\n fullModifier,\n `unknown operator '${prefix}', expected one of + - / *`\n );\n }\n const [suffix, endIdx, isPercent] = _getModifierSuffix(modifier);\n\n const value = parseInt(\n suffix !== null\n ? modifier.substring(1, modifier.length - (endIdx - 1))\n : modifier.substring(1),\n 10\n );\n if (Number.isNaN(value)) {\n throw invalidModifier(fullModifier, 'the amount is not a number');\n }\n\n let widthModifier = value;\n let heightModifier = value;\n if (isPercent) {\n widthModifier = (clonedDimensions.width / 100) * value;\n heightModifier = (clonedDimensions.height / 100) * value;\n }\n\n const modifiedDimension = _modifyDimensions(\n clonedDimensions,\n prefix,\n suffix,\n widthModifier,\n heightModifier\n );\n\n if (ratioModifier) {\n return _modifyDimensionsByRatio(\n ratioModifier,\n modifiedDimension,\n fullModifier\n );\n }\n\n return modifiedDimension;\n}\n","import {modifyDimensions} from '@operation/helper/modify-dimensions.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IGetElementDimensionsOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @type=ParameterType:dimensionsModifier\n * @erased\n */\n modifier?: string;\n /**\n * @type=ParameterType:object\n * @output\n */\n dimensions?: {width?: number; height?: number};\n}\n\n/**\n * This operation calculates the width and height of the given selected element.\n * It assigns this struct to the dimensions property on the current operation data.\n * Optionally the width and height can be modified using the given modifier string.\n *\n * The modifier string is formatted in the following way:\n *\n * <operator><amount><optional-side><optional-precentage>|<ratio-definition>\n *\n * Where the ratio modifier is formatted in the following way:\n * <side>[ar=<ratio-left>-<ratio-right>]\n *\n * For example, this modifier '+100h|w[ar=8-1]' will modifiy the dimensions like this:\n * it will add a value of 100 to the height and modify the width by a ratio of 8 to 1 relative to the height.\n *\n * @category DOM\n */\nexport const getElementDimensions: TOperation<\n IGetElementDimensionsOperationData,\n Omit<IGetElementDimensionsOperationData, 'modifier'>\n> = (operationData: IGetElementDimensionsOperationData) => {\n const {selectedElement, modifier} = operationData;\n\n removeProperties(operationData, 'modifier');\n\n let dimensions = {\n width: selectedElement.innerWidth() ?? 0,\n height: selectedElement.innerHeight() ?? 0,\n };\n\n if (dimensions.height === 0) {\n dimensions.height = dimensions.width;\n }\n\n if (modifier) {\n dimensions = modifyDimensions(dimensions, modifier);\n }\n\n operationData.dimensions = dimensions;\n return operationData;\n};\n","import type {TOperation} from '@operation/types.ts';\nimport $ from 'jquery';\n\nexport interface IGetFocusedElementOperationData {\n /**\n * @type=ParameterType:jQuery\n * @output\n */\n focusedElement?: JQuery;\n}\n\n/**\n * Gets the currently focused element.\n *\n * @category Focus\n */\nexport const getFocusedElement: TOperation<\n IGetFocusedElementOperationData,\n IGetFocusedElementOperationData\n> = (operationData: IGetFocusedElementOperationData) => {\n operationData.focusedElement = document.activeElement\n ? $(document.activeElement as HTMLElement)\n : $();\n return operationData;\n};\n","import type {TOperation} from '@operation/types.ts';\n\nexport interface IGetFormDataOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @output\n * @type=ParameterType:object\n */\n formData?: Record<string, any>;\n}\n\nfunction defineField(target: Record<string, any>, name: string, value: any) {\n Object.defineProperty(target, name, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * Extracts all input, select, and textarea values from form element into operation data.\n *\n * This operation reads form field values and returns them as an object with field names as keys.\n * Only processes form elements that are enabled and not hidden. Handles checkboxes, radio buttons,\n * select elements, textareas, and text inputs.\n *\n * @returns Operation data with `formData` object containing field values\n *\n * @example\n * ```typescript\n * // Given a form with fields: name=\"John\", email=\"john@example.com\"\n * const result = getFormData({selectedElement: $form});\n * // Returns: {selectedElement: $form, formData: {name: \"John\", email: \"john@example.com\"}}\n * ```\n *\n * @category Form\n */\nexport const getFormData: TOperation<\n IGetFormDataOperationData,\n IGetFormDataOperationData\n> = (operationData: IGetFormDataOperationData) => {\n const {selectedElement} = operationData;\n\n // Validate selectedElement exists\n if (!selectedElement || selectedElement.length === 0) {\n throw new Error('getFormData: selectedElement is required');\n }\n\n // Validate selectedElement is a form\n if (!selectedElement.is('form')) {\n throw new Error('getFormData: selectedElement must be a form element');\n }\n\n // Use jQuery's serializeArray to get form data\n const formArray = selectedElement.serializeArray();\n const formData: Record<string, any> = {};\n\n // Convert array format to object format. Only own keys count, and values are\n // defined rather than assigned, so field names like 'constructor' or '__proto__'\n // neither merge with inherited members nor replace the prototype.\n for (const field of formArray) {\n if (Object.hasOwn(formData, field.name)) {\n // Handle multiple values for same name (checkboxes)\n const existing = formData[field.name];\n if (Array.isArray(existing)) {\n existing.push(field.value);\n } else {\n defineField(formData, field.name, [existing, field.value]);\n }\n } else {\n defineField(formData, field.name, field.value);\n }\n }\n\n operationData.formData = formData;\n\n return operationData;\n};\n","import {lookupNamedEntry} from '@operation/helper/lookup-named-entry.ts';\nimport type {TOperation} from '@operation/types.ts';\nimport type {RequireKeys} from '@/types.ts';\n\nexport interface IGetImportOperationData {\n /**\n * @type=ParameterType:systemName\n * @required\n * @erased\n */\n systemName: string;\n /**\n * @output\n */\n importedInstance?: unknown;\n}\n\n/**\n * This operation retrieves the import specified by the given `systemName` and\n * assigns it to the `importedInstance` property on the current operaton date.\n *\n * The import is looked up with `this.services.getImport`, which answers from\n * the engine's resource importer. Functions, templates\n * and JSON registered with the `EligiusResourceImporter` constructor\n * (`new EligiusResourceImporter({json: {settings}})`) can be imported this\n * way, as can every built-in operation, controller and provider export.\n *\n * @param operationData\n * @throws Error naming the operation and the `systemName` when nothing is\n * registered under that name (with the closest registered names when the\n * importer can suggest them).\n *\n * @category Utility\n */\nexport const getImport: TOperation<\n IGetImportOperationData,\n Omit<RequireKeys<IGetImportOperationData, 'importedInstance'>, 'systemName'>\n> = function (operationData: IGetImportOperationData) {\n const {systemName} = operationData;\n\n delete (operationData as any).systemName;\n\n operationData.importedInstance = lookupNamedEntry(\n 'getImport',\n systemName,\n name => this.services.getImport(name)\n );\n\n return operationData as Omit<\n RequireKeys<IGetImportOperationData, 'importedInstance'>,\n 'systemName'\n >;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IGetQueryParamsOperationData {\n /**\n * The query params will be added as property/values to this object.\n * So, the query string `?foo=bar&bar=foo` will result in:\n * ```json\n * {\n * foo: \"bar\",\n * bar: \"foo\"\n * }\n * ```\n * This object will be assigned to the `queryParams` property.\n * @output\n */\n queryParams?: Record<string, string>;\n /**\n * The properties on this object will be assigned to the queryParams result\n * when the given property name is not part of the query string.\n *\n * @erased\n *\n */\n defaultValues?: Record<string, string>;\n}\n\n/**\n * This operation retrieves the current query parameters from the browser's address bar and places\n * them on the returned operation data.\n *\n * @category Utility\n */\nexport const getQueryParams: TOperation<\n IGetQueryParamsOperationData,\n Omit<IGetQueryParamsOperationData, 'defaultValues'>\n> = (operationData: IGetQueryParamsOperationData) => {\n const searchParams = new URLSearchParams(window.location.search);\n const queryParams = Object.fromEntries(searchParams.entries());\n\n const {defaultValues = {}} = operationData;\n\n removeProperties(operationData, 'defaultValues');\n\n operationData.queryParams = {\n ...defaultValues,\n ...queryParams,\n };\n\n return operationData;\n};\n","import type {TOperation} from '@operation/types.ts';\n\nexport interface IGetScrollPositionOperationData {\n /**\n * @output\n */\n scrollX?: number;\n /**\n * @output\n */\n scrollY?: number;\n}\n\n/**\n * Gets the current scroll position of the viewport.\n *\n * Returns x (horizontal) and y (vertical) scroll positions in pixels.\n * Uses cross-browser compatible methods to retrieve scroll position.\n *\n * @returns Operation data with `scrollX` and `scrollY` values\n *\n * @example\n * ```typescript\n * // Get current scroll position\n * const result = getScrollPosition({});\n * // result.scrollX = 150\n * // result.scrollY = 400\n * ```\n *\n * @category Scroll\n */\nexport const getScrollPosition: TOperation<\n IGetScrollPositionOperationData,\n IGetScrollPositionOperationData\n> = (operationData: IGetScrollPositionOperationData) => {\n // Cross-browser scroll position detection\n const scrollX =\n window.pageXOffset !== undefined\n ? window.pageXOffset\n : (window as any).scrollX !== undefined\n ? (window as any).scrollX\n : document.documentElement?.scrollLeft || 0;\n\n const scrollY =\n window.pageYOffset !== undefined\n ? window.pageYOffset\n : (window as any).scrollY !== undefined\n ? (window as any).scrollY\n : document.documentElement?.scrollTop || 0;\n\n operationData.scrollX = scrollX;\n operationData.scrollY = scrollY;\n\n return operationData;\n};\n","import type {TOperation} from '@operation/types.ts';\n\nexport interface IGetTextContentOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @output\n */\n textContent?: string;\n}\n\n/**\n * Extracts text content from element, stripping all HTML markup.\n *\n * Uses jQuery's `.text()` method which is XSS-safe and returns only the text content\n * without any HTML tags. Preserves whitespace and text from nested elements.\n *\n * @returns Operation data with `textContent` containing the extracted plain text\n *\n * @example\n * ```typescript\n * // Extract text from element with HTML\n * const result = getTextContent({selectedElement: $div});\n * // Given: <div>Hello <strong>World</strong>!</div>\n * // Returns: {textContent: \"Hello World!\"}\n * ```\n *\n * @category Text\n */\nexport const getTextContent: TOperation<\n IGetTextContentOperationData,\n IGetTextContentOperationData\n> = (operationData: IGetTextContentOperationData) => {\n const {selectedElement} = operationData;\n\n if (!selectedElement || selectedElement.length === 0) {\n throw new Error('getTextContent: selectedElement is required');\n }\n\n operationData.textContent = selectedElement.text();\n\n return operationData;\n};\n","/**\n * Reads a fetch response body as JSON for the HTTP operations.\n *\n * A 204 No Content or 205 Reset Content response, or an empty body, yields\n * `null` instead of a parse error.\n *\n * @param response - The fetch response to read\n * @param operationName - Name of the calling operation, used in error messages\n * @returns The parsed JSON value, or null when there is no body\n * @throws Error naming the operation when the body is not valid JSON\n */\nexport async function readJsonBody(\n response: Response,\n operationName: string\n): Promise<any> {\n if (response.status === 204 || response.status === 205) {\n return null;\n }\n const text = await response.text();\n if (text.trim() === '') {\n return null;\n }\n try {\n return JSON.parse(text);\n } catch (error) {\n throw new Error(\n `${operationName}: invalid JSON response: ${(error as Error).message}`,\n {cause: error}\n );\n }\n}\n","import {readJsonBody} from '@operation/helper/read-json-body.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IHttpDeleteOperationData {\n /**\n * @required\n * @erased\n */\n url: string;\n /**\n * @optional\n * @erased\n */\n headers?: Record<string, string>;\n /**\n * @output\n */\n response?: any;\n /**\n * @output\n */\n status?: number;\n}\n\n/**\n * Performs an HTTP DELETE request to the specified URL.\n *\n * @returns Operation data with `response` (parsed JSON, or `null` for non-JSON and empty bodies)\n * and `status` (HTTP status code)\n * @throws When the request fails, the server responds with an error status, or a JSON body is invalid.\n *\n * @example\n * ```typescript\n * const result = await httpDelete({\n * url: 'https://api.example.com/users/123',\n * headers: { 'Authorization': 'Bearer token' }\n * });\n * // result.response = {} or null\n * // result.status = 204\n * ```\n *\n * @category HTTP\n */\nexport const httpDelete: TOperation<\n IHttpDeleteOperationData,\n Omit<IHttpDeleteOperationData, 'url' | 'headers'>\n> = async (operationData: IHttpDeleteOperationData) => {\n const {url, headers = {}} = operationData;\n\n if (!url || url.trim() === '') {\n throw new Error('httpDelete: url is required');\n }\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'DELETE',\n headers,\n });\n } catch (error) {\n throw new Error(`httpDelete: ${(error as Error).message}`, {\n cause: error,\n });\n }\n\n operationData.status = response.status;\n\n if (!response.ok) {\n throw new Error(\n `httpDelete: HTTP error ${response.status} ${response.statusText}`\n );\n }\n\n // DELETE may return an empty body (204 No Content) or a non-JSON body\n const contentType = response.headers.get('content-type');\n operationData.response = contentType?.includes('application/json')\n ? await readJsonBody(response, 'httpDelete')\n : null;\n\n removeProperties(operationData, 'url', 'headers');\n\n return operationData;\n};\n","import {readJsonBody} from '@operation/helper/read-json-body.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IHttpPostOperationData {\n /**\n * @required\n * @erased\n */\n url: string;\n /**\n * @optional\n * @erased\n */\n body?: any;\n /**\n * @optional\n * @erased\n */\n headers?: Record<string, string>;\n /**\n * @output\n */\n response?: any;\n /**\n * @output\n */\n status?: number;\n}\n\n/**\n * Performs an HTTP POST request to the specified URL.\n *\n * The body is sent as JSON with `Content-Type: application/json`, unless the caller's headers set\n * another content type (header names are case-insensitive). With a non-JSON content type, a string\n * body is sent as is; other bodies are still JSON encoded.\n *\n * @returns Operation data with `response` (parsed JSON, or `null` for 204 No Content and empty bodies)\n * and `status` (HTTP status code)\n * @throws When the request fails, the server responds with an error status, or the body is not valid JSON.\n *\n * @example\n * ```typescript\n * const result = await httpPost({\n * url: 'https://api.example.com/users',\n * body: { name: 'John', email: 'john@example.com' },\n * headers: { 'Content-Type': 'application/json' }\n * });\n * // result.response = { id: 123, name: 'John', ... }\n * // result.status = 201\n * ```\n *\n * @category HTTP\n */\nexport const httpPost: TOperation<\n IHttpPostOperationData,\n Omit<IHttpPostOperationData, 'url' | 'body' | 'headers'>\n> = async (operationData: IHttpPostOperationData) => {\n const {url, body, headers = {}} = operationData;\n\n if (!url || url.trim() === '') {\n throw new Error('httpPost: url is required');\n }\n\n let response: Response;\n try {\n // Headers compares names case-insensitively, so a caller's 'content-type'\n // replaces the default instead of being sent as a second value\n const requestHeaders = new Headers(headers);\n if (!requestHeaders.has('Content-Type')) {\n requestHeaders.set('Content-Type', 'application/json');\n }\n const isJson = /json/i.test(requestHeaders.get('Content-Type') ?? '');\n response = await fetch(url, {\n method: 'POST',\n headers: requestHeaders,\n body: typeof body === 'string' && !isJson ? body : JSON.stringify(body),\n });\n } catch (error) {\n throw new Error(`httpPost: ${(error as Error).message}`, {cause: error});\n }\n\n operationData.status = response.status;\n\n if (!response.ok) {\n throw new Error(\n `httpPost: HTTP error ${response.status} ${response.statusText}`\n );\n }\n\n operationData.response = await readJsonBody(response, 'httpPost');\n\n removeProperties(operationData, 'url', 'body', 'headers');\n\n return operationData;\n};\n","import {readJsonBody} from '@operation/helper/read-json-body.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IHttpPutOperationData {\n /**\n * @required\n * @erased\n */\n url: string;\n /**\n * @optional\n * @erased\n */\n body?: any;\n /**\n * @optional\n * @erased\n */\n headers?: Record<string, string>;\n /**\n * @output\n */\n response?: any;\n /**\n * @output\n */\n status?: number;\n}\n\n/**\n * Performs an HTTP PUT request to the specified URL.\n *\n * The body is sent as JSON with `Content-Type: application/json`, unless the caller's headers set\n * another content type (header names are case-insensitive). With a non-JSON content type, a string\n * body is sent as is; other bodies are still JSON encoded.\n *\n * @returns Operation data with `response` (parsed JSON, or `null` for 204 No Content and empty bodies)\n * and `status` (HTTP status code)\n * @throws When the request fails, the server responds with an error status, or the body is not valid JSON.\n *\n * @example\n * ```typescript\n * const result = await httpPut({\n * url: 'https://api.example.com/users/123',\n * body: { name: 'John Updated', email: 'john.new@example.com' },\n * headers: { 'Content-Type': 'application/json' }\n * });\n * // result.response = { id: 123, name: 'John Updated', ... }\n * // result.status = 200\n * ```\n *\n * @category HTTP\n */\nexport const httpPut: TOperation<\n IHttpPutOperationData,\n Omit<IHttpPutOperationData, 'url' | 'body' | 'headers'>\n> = async (operationData: IHttpPutOperationData) => {\n const {url, body, headers = {}} = operationData;\n\n if (!url || url.trim() === '') {\n throw new Error('httpPut: url is required');\n }\n\n let response: Response;\n try {\n // Headers compares names case-insensitively, so a caller's 'content-type'\n // replaces the default instead of being sent as a second value\n const requestHeaders = new Headers(headers);\n if (!requestHeaders.has('Content-Type')) {\n requestHeaders.set('Content-Type', 'application/json');\n }\n const isJson = /json/i.test(requestHeaders.get('Content-Type') ?? '');\n response = await fetch(url, {\n method: 'PUT',\n headers: requestHeaders,\n body: typeof body === 'string' && !isJson ? body : JSON.stringify(body),\n });\n } catch (error) {\n throw new Error(`httpPut: ${(error as Error).message}`, {cause: error});\n }\n\n operationData.status = response.status;\n\n if (!response.ok) {\n throw new Error(\n `httpPut: HTTP error ${response.status} ${response.statusText}`\n );\n }\n\n operationData.response = await readJsonBody(response, 'httpPut');\n\n removeProperties(operationData, 'url', 'body', 'headers');\n\n return operationData;\n};\n","import {\n assertParsedChainSafe,\n parseSegments,\n walkChain,\n} from '@operation/helper/chain-cache.ts';\n\nexport {isGlobalObject} from '@operation/helper/chain-cache.ts';\n\n/**\n * Gets the value for the given property chain. A property chain is defined by a string array.\n *\n * For example, this property chain: `[mySource, subSource, element, value]` should be extracted from an object of this shape:\n * ```ts\n * const foo = {\n * mySource: {\n * subSource: {\n * element: {\n * value: 'bar'\n * }\n * }\n * }\n * }\n * ```\n *\n * The result of the invocation `getPropertyChainValue([mySource, subSource, element, value], foo)` would then yield the value `bar`.\n *\n * Chains containing a `__proto__`, `prototype` or `constructor` segment are rejected to\n * prevent prototype pollution and access to the `Function` constructor. Chains that pass\n * through or end at the global object (`window`), for example\n * `selectedElement.0.ownerDocument.defaultView`, are rejected too, so configuration cannot\n * reach `eval`, `Function`, timers or other globals.\n *\n * Bracket indices are expanded into their own segments, so `eventArgs[0]` resolves like\n * `eventArgs.0` and `items[2].label` like `items.2.label`. The parsing is shared with the\n * cached external chains, see `chain-cache.ts`.\n *\n * @param propertyChain The chain segments. Segments may use dot or bracket notation themselves.\n * @param sourceObject The object to resolve the chain against.\n * @param operationName The operation resolving the chain, named in the error messages.\n * @throws When an intermediate value is null or undefined (the message names the part of the\n * chain that did not resolve), when the chain contains a forbidden segment, or when it reaches\n * the global object.\n */\nexport function getPropertyChainValue(\n propertyChain: string[],\n sourceObject: Record<string, any>,\n operationName?: string\n) {\n const parsed = parseSegments(propertyChain);\n assertParsedChainSafe(parsed, operationName);\n return walkChain(parsed, sourceObject, operationName);\n}\n","import {isForbiddenPropertyChainSegment} from '@operation/helper/assert-safe-property-chain.ts';\nimport {isGlobalObject} from '@operation/helper/get-property-chain-value.ts';\nimport type {TOperation} from '@operation/types.ts';\nimport {isPromise} from '@util/guards/is-promise.ts';\nimport $ from 'jquery';\n\nexport interface IInvokeObjectMethodOperationData {\n /**\n *\n * The given object instance\n * @dependency\n *\n */\n instance: any;\n /**\n * The method name on the given object that will be invoked\n * @required\n * @erased\n */\n methodName: string;\n /**\n * Arguments that will be passed to the specified method\n * @erased\n */\n methodArguments?: unknown[];\n /**\n * If any, the results of the method invocation are assigned to the property\n * @output\n */\n methodResult?: unknown;\n}\n\n/**\n * This operation invokes the specified method on the given object with the given optional arguments\n * and assigns the result to the `methodResult` operationdata property. When the method returns a\n * promise, the operation waits for it and assigns the resolved value.\n *\n * The operation only calls application code: methods of controllers, of other instances of\n * application classes, and of plain objects. It refuses, and throws for:\n * - an `instance` that is a function, the global object (`window`), a document, a DOM node,\n * a jQuery object, or any other built-in or host object (arrays, maps, promises, `location`,\n * storage, ...);\n * - a method that is a built-in (native) function, such as `eval`, `Function`, `setTimeout`,\n * `setInterval`, `document.write`, `Reflect.apply` or a bound function, or a jQuery function;\n * - the method names `constructor`, `__proto__` and `prototype`;\n * - arguments that are such functions.\n *\n * These checks stop configuration from reaching the platform's code-executing functions through\n * this operation. They cannot vouch for what an application method does with its arguments, so\n * only expose methods that are safe to call with configured data.\n *\n * @param operationData\n * @throws When `instance` is missing or refused, when the method name or the method is refused,\n * or when the member is not a function. The message names the operation.\n *\n * @category Utility\n */\nexport const invokeObjectMethod: TOperation<\n IInvokeObjectMethodOperationData,\n Omit<IInvokeObjectMethodOperationData, 'methodName' | 'methodArguments'>\n> = (operationData: IInvokeObjectMethodOperationData) => {\n const {methodName, methodArguments, ...newOperationData} = operationData;\n\n delete (operationData as any).methodName;\n delete (operationData as any).methodArguments;\n\n if (typeof methodName !== 'string' || !methodName.length) {\n throw new Error('invokeObjectMethod: methodName is required');\n }\n if (isForbiddenPropertyChainSegment(methodName)) {\n throw new Error(\n `invokeObjectMethod: method name '${methodName}' is not allowed`\n );\n }\n\n const {instance} = operationData;\n if (instance === Function) {\n throw new Error(\n 'invokeObjectMethod: invoking methods on the Function constructor is not allowed'\n );\n }\n assertAllowedInstance(instance);\n\n const func = instance[methodName];\n if (typeof func !== 'function') {\n throw new Error(\n `invokeObjectMethod: '${methodName}' is not a function on the instance`\n );\n }\n if (isRefusedFunction(func)) {\n throw new Error(\n `invokeObjectMethod: method '${methodName}' is a built-in or library function and is not allowed`\n );\n }\n\n const args = methodArguments ?? [];\n if (!Array.isArray(args)) {\n throw new Error('invokeObjectMethod: methodArguments must be an array');\n }\n if (\n args.some(\n arg => typeof arg === 'function' && isRefusedFunction(arg as TAnyFunction)\n )\n ) {\n throw new Error(\n `invokeObjectMethod: the arguments for '${methodName}' contain a built-in or library function, which is not allowed`\n );\n }\n\n const result = func.apply(instance, args);\n if (isPromise(result)) {\n return result.then(resolved => {\n newOperationData.methodResult = resolved;\n return newOperationData;\n });\n }\n\n newOperationData.methodResult = result;\n return newOperationData;\n};\n\n/**\n * Accepts plain objects and instances of application classes; refuses everything else.\n */\nfunction assertAllowedInstance(instance: unknown): asserts instance is any {\n if (instance === null || instance === undefined) {\n throw new Error('invokeObjectMethod: instance is required');\n }\n if (typeof instance !== 'object') {\n throw new Error(\n `invokeObjectMethod: instance must be an object, not a ${typeof instance}`\n );\n }\n if (\n isGlobalObject(instance) ||\n typeof (instance as {jquery?: unknown}).jquery === 'string' ||\n // Host and built-in objects (Window, Document, elements, Location, Storage,\n // arrays, maps, promises, ...) carry their own tag; plain objects and\n // application class instances report '[object Object]'.\n Object.prototype.toString.call(instance) !== '[object Object]' ||\n hasBuiltInPrototype(instance)\n ) {\n throw new Error(\n 'invokeObjectMethod: instance must be a controller, an application class instance or a plain object; built-in, DOM and jQuery objects are not allowed'\n );\n }\n}\n\n/**\n * True when a prototype below `Object.prototype` belongs to a built-in constructor.\n */\nfunction hasBuiltInPrototype(instance: object) {\n let prototype = Object.getPrototypeOf(instance);\n while (prototype && prototype !== Object.prototype) {\n const ctor = Object.hasOwn(prototype, 'constructor')\n ? prototype.constructor\n : undefined;\n if (typeof ctor === 'function' && isNativeFunction(ctor)) {\n return true;\n }\n prototype = Object.getPrototypeOf(prototype);\n }\n return false;\n}\n\ntype TAnyFunction = (...args: never[]) => unknown;\n\nconst nativeCodePattern = /\\{\\s*\\[native code\\]\\s*\\}\\s*$/;\n\nfunction isNativeFunction(func: TAnyFunction) {\n try {\n return nativeCodePattern.test(Function.prototype.toString.call(func));\n } catch {\n // Exotic callables that cannot be inspected are refused.\n return true;\n }\n}\n\n/**\n * Functions that execute code given as a string, or navigate to a URL. Some\n * environments (such as jsdom) implement a few of them in JavaScript, so they are\n * refused by identity as well as by the native-function check.\n */\nfunction getCodeExecutingFunctions(): Set<unknown> {\n const global = globalThis as any;\n const doc = typeof document !== 'undefined' ? (document as any) : undefined;\n return new Set(\n [\n global.eval,\n global.Function,\n global.setTimeout,\n global.setInterval,\n global.setImmediate,\n global.execScript,\n global.open,\n global.Reflect?.apply,\n global.Reflect?.construct,\n doc?.write,\n doc?.writeln,\n doc?.open,\n global.Element?.prototype?.insertAdjacentHTML,\n global.Element?.prototype?.setAttribute,\n global.Element?.prototype?.setAttributeNS,\n global.Range?.prototype?.createContextualFragment,\n global.Location?.prototype?.assign,\n global.Location?.prototype?.replace,\n ].filter(fn => typeof fn === 'function')\n );\n}\n\nlet jQueryFunctions: WeakSet<TAnyFunction> | undefined;\n\n/**\n * jQuery turns HTML strings into DOM (running inline handlers and scripts), and its\n * functions do not check their receiver, so none of them may be called.\n */\nfunction getJQueryFunctions(): WeakSet<TAnyFunction> {\n if (!jQueryFunctions) {\n const functions = new WeakSet<TAnyFunction>([$]);\n for (const source of [$, $.fn]) {\n for (const key of Object.getOwnPropertyNames(source)) {\n const value = Object.getOwnPropertyDescriptor(source, key)?.value;\n if (typeof value === 'function') {\n functions.add(value);\n }\n }\n }\n jQueryFunctions = functions;\n }\n return jQueryFunctions;\n}\n\nfunction isRefusedFunction(func: TAnyFunction) {\n return (\n isNativeFunction(func) ||\n getCodeExecutingFunctions().has(func) ||\n getJQueryFunctions().has(func)\n );\n}\n","import type {TOperation} from '@operation/types.ts';\n\nexport interface IIsElementInViewportOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @output\n */\n isInViewport?: boolean;\n}\n\n/**\n * Checks if an element is currently visible within the viewport.\n *\n * Uses `getBoundingClientRect()` to determine if the element is within the viewport boundaries.\n *\n * @returns Operation data with `isInViewport` boolean indicating visibility\n *\n * @example\n * ```typescript\n * // Check if element is in view\n * const result = isElementInViewport({\n * selectedElement: $targetElement\n * });\n * // result.isInViewport = true or false\n * ```\n *\n * @category DOM\n */\nexport const isElementInViewport: TOperation<\n IIsElementInViewportOperationData,\n IIsElementInViewportOperationData\n> = (operationData: IIsElementInViewportOperationData) => {\n const {selectedElement} = operationData;\n\n if (!selectedElement || selectedElement.length === 0) {\n throw new Error('isElementInViewport: selectedElement is required');\n }\n\n const element = selectedElement[0];\n const rect = element.getBoundingClientRect();\n\n const isInViewport =\n rect.top >= 0 &&\n rect.left >= 0 &&\n rect.bottom <=\n (window.innerHeight || document.documentElement.clientHeight) &&\n rect.right <= (window.innerWidth || document.documentElement.clientWidth);\n\n operationData.isInViewport = isInViewport;\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport type StorageType = 'local' | 'session';\n\nexport interface ILoadFromStorageOperationData {\n /**\n * @required\n * @erased\n */\n key: string;\n /**\n * @required\n * @erased\n */\n storageType: StorageType;\n /**\n * @output\n */\n loadedValue?: any;\n}\n\n/**\n * Loads data from browser storage (localStorage or sessionStorage).\n *\n * Deserializes the stored JSON value. Returns `null` if key doesn't exist.\n * When `storageType` is omitted, localStorage is used.\n *\n * @returns Operation data with `loadedValue` containing the deserialized data\n * @throws When the key is empty, storageType is not 'local' or 'session', or the stored value is not valid JSON.\n *\n * @example\n * ```typescript\n * // Load user settings from localStorage\n * const result = loadFromStorage({\n * key: 'user-settings',\n * storageType: 'local'\n * });\n * // result.loadedValue = { theme: 'dark', language: 'en' }\n * ```\n *\n * @example\n * ```typescript\n * // Load session data\n * const result = loadFromStorage({\n * key: 'session-id',\n * storageType: 'session'\n * });\n * // result.loadedValue = 'abc123' or null if not found\n * ```\n *\n * @category Data\n */\nexport const loadFromStorage: TOperation<\n ILoadFromStorageOperationData,\n Omit<ILoadFromStorageOperationData, 'key' | 'storageType'>\n> = (operationData: ILoadFromStorageOperationData) => {\n const {key, storageType} = operationData;\n\n if (!key || key.trim() === '') {\n throw new Error('loadFromStorage: key is required');\n }\n\n // A missing storageType keeps the long-standing localStorage default; any other\n // value, such as a typo, must not silently read from the wrong storage\n if (\n storageType !== undefined &&\n storageType !== 'local' &&\n storageType !== 'session'\n ) {\n throw new Error(\n `loadFromStorage: storageType must be 'local' or 'session', got \"${String(storageType)}\"`\n );\n }\n\n const storage = storageType === 'session' ? sessionStorage : localStorage;\n const stored = storage.getItem(key);\n\n if (stored === null) {\n operationData.loadedValue = null;\n } else {\n try {\n operationData.loadedValue = JSON.parse(stored);\n } catch (error) {\n throw new Error(\n `loadFromStorage: failed to parse stored value for key \"${key}\"`,\n {cause: error}\n );\n }\n }\n\n removeProperties(operationData, 'key', 'storageType');\n\n return operationData;\n};\n","import {deepCopy} from '@operation/helper/deep-copy.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nconst jsonCache = new Map<string, unknown>();\n\nexport interface ILoadJSONOperationData {\n /**\n * The URL where the JSON will be retrieved from\n * @required\n * @erased\n */\n url: string;\n /**\n * If true, the results will be added to the cache and any subsequent call will use this cache\n * @erased\n */\n cache?: boolean;\n /**\n * The JSON retrieved from the given URL\n * @output\n */\n json?: any;\n}\n\nconst addToCache = (key: string, value: unknown) => {\n jsonCache.set(key, deepCopy(value));\n};\n\n/**\n * This operation loads a JSON file from the specified url and assigns it to the json\n * property on the current operation data.\n *\n * If the cache property is set to true and a cached value already exists, a copy of it is assigned\n * instead of re-retrieving it from the url. Mutating the returned json never changes the cache.\n *\n * The cache is shared by every engine. It is emptied when the last live engine created by\n * `EngineFactory` is destroyed; call {@link clearJsonCache} to empty it earlier.\n *\n * @throws When the url is empty, the request fails, the server responds with an error status, or the body is not valid JSON.\n *\n * @category Utility\n */\nexport const loadJson: TOperation<\n ILoadJSONOperationData,\n Omit<ILoadJSONOperationData, 'url' | 'cache'>\n> = async (operationData: ILoadJSONOperationData) => {\n const {url, cache} = operationData;\n\n if (typeof url !== 'string' || url.trim() === '') {\n throw new Error('loadJson: url is required');\n }\n\n removeProperties(operationData, 'url', 'cache');\n\n if (cache && jsonCache.has(url)) {\n operationData.json = deepCopy(jsonCache.get(url));\n return operationData;\n }\n\n let response: Response;\n try {\n response = await fetch(url);\n } catch (error) {\n throw new Error(`loadJson: ${url} failed: ${(error as Error).message}`, {\n cause: error,\n });\n }\n\n if (!response.ok) {\n throw new Error(\n `loadJson: ${url} responded ${response.status} ${response.statusText}`\n );\n }\n\n let json: unknown;\n try {\n json = await response.json();\n } catch (error) {\n throw new Error(\n `loadJson: ${url} returned invalid JSON: ${(error as Error).message}`,\n {cause: error}\n );\n }\n\n operationData.json = json;\n\n if (cache) {\n addToCache(url, json);\n }\n\n return operationData;\n};\n\n/**\n * Removes every response that {@link loadJson} cached with `cache: true`.\n *\n * `EngineFactory` calls it when the last live engine is destroyed. It is exported from the\n * package entry, not from the operations index, because it is not an operation.\n */\nexport const clearJsonCache = (): void => {\n jsonCache.clear();\n};\n","import {getGlobals} from '@operation/helper/globals.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface ILogOperationData {\n /**\n * @type=ParameterType:object|ParameterType:string|ParameterType:number|ParameterType:boolean|ParameterType:array\n * @erased\n */\n logValue?: any;\n /**\n * @erased\n */\n logName?: string;\n}\n\n/**\n * This operation logs the specified value, or, when no logValue property has been assigned\n * it will log the current operation data, global data and scope to the console\n *\n * @category Utility\n */\nexport const log: TOperation<\n ILogOperationData,\n Omit<ILogOperationData, 'logValue' | 'logName'>\n> = function (operationData: ILogOperationData) {\n if ('logValue' in operationData) {\n console.log(operationData.logName ?? 'logValue', operationData.logValue);\n removeProperties(operationData, 'logValue', 'logName');\n } else {\n const globalData = getGlobals();\n\n console.group('Operation info');\n console.log('scope', this);\n console.log('operationData', operationData);\n console.log('globalData', globalData);\n console.groupEnd();\n }\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IMapArrayOperationData {\n /**\n * @dependency\n */\n arrayData: any[];\n /**\n * @required\n * @erased\n */\n mapFunction: (item: any, index?: number) => any;\n /**\n * @output\n */\n mappedArray?: any[];\n}\n\n/**\n * Transforms each element of an array using a mapping function.\n *\n * Operates on arrayData passed from previous operations.\n * The mapFunction receives each item and optionally its index.\n *\n * @returns Operation data with `mappedArray` containing transformed elements\n *\n * @example\n * ```typescript\n * // Double each number\n * const result = mapArray({\n * arrayData: [1, 2, 3, 4],\n * mapFunction: (item) => item * 2\n * });\n * // result.mappedArray = [2, 4, 6, 8]\n * ```\n *\n * @example\n * ```typescript\n * // Extract property from objects\n * const result = mapArray({\n * arrayData: [{name: 'Alice', age: 25}, {name: 'Bob', age: 30}],\n * mapFunction: (item) => item.name\n * });\n * // result.mappedArray = ['Alice', 'Bob']\n * ```\n *\n * @example\n * ```typescript\n * // Use index in transformation\n * const result = mapArray({\n * arrayData: ['a', 'b', 'c'],\n * mapFunction: (item, index) => `${index}-${item}`\n * });\n * // result.mappedArray = ['0-a', '1-b', '2-c']\n * ```\n *\n * @category Array\n */\nexport const mapArray: TOperation<\n IMapArrayOperationData,\n Omit<IMapArrayOperationData, 'mapFunction'>\n> = (operationData: IMapArrayOperationData) => {\n const {arrayData, mapFunction} = operationData;\n\n if (!Array.isArray(arrayData)) {\n throw new Error('mapArray: arrayData is required and must be an array');\n }\n\n if (typeof mapFunction !== 'function') {\n throw new Error('mapArray: mapFunction is required and must be a function');\n }\n\n operationData.mappedArray = arrayData.map(mapFunction);\n\n removeProperties(operationData, 'mapFunction');\n\n return operationData;\n};\n","export function isString(value: any): value is string {\n return typeof value === 'string';\n}\n","import {resolvePropertyValues} from '@operation/helper/resolve-property-values.ts';\nimport type {TOperation} from '@operation/types.ts';\nimport {isFunction} from '@util/guards/is-function.ts';\nimport {isString} from '@util/guards/is-string.ts';\n\nexport type MathFunctionKeys = {\n [K in keyof Math]: Math[K] extends (...args: any) => any ? K : never;\n}[keyof Math];\n\n/** The names of the Math constants (`'PI'`, `'E'`, ...) */\nexport type MathNonFunctionKeys = Extract<\n {\n [K in keyof Math]: Math[K] extends (...args: any) => any ? never : K;\n }[keyof Math],\n string\n>;\n\nexport interface IMathOperationData {\n /**\n * Numbers, property chains, or names of Math constants\n * ({@link MathNonFunctionKeys}).\n *\n * @type=ParameterType:array\n * @required\n * @erased\n */\n args: (number | string)[];\n /**\n * @type=ParameterType:mathfunction\n * @required\n * @erased\n */\n functionName: MathFunctionKeys;\n /**\n * @output\n */\n mathResult?: number;\n}\n\n/**\n * This operation performs the given math function with the specified arguments.\n *\n * `args` and `functionName` may contain property chains (`$operationdata.`, `$globaldata.`,\n * `$scope.`). Only these two inputs are resolved; the rest of the operation data is left as it\n * is. Arguments that name a Math constant (such as `'PI'`) are replaced by its value.\n *\n * @throws When `functionName` is not a function of `Math`, or `args` is not an array.\n *\n * @category Utility\n */\nexport const math: TOperation<\n IMathOperationData,\n Omit<IMathOperationData, 'args' | 'functionName'>\n> = function (operationData: IMathOperationData) {\n const resolved = resolvePropertyValues(operationData, this, {\n args: operationData.args,\n functionName: operationData.functionName,\n });\n\n const {\n args: _args,\n functionName: _functionName,\n ...newOperationData\n } = operationData;\n const {functionName} = resolved;\n\n if (\n typeof functionName !== 'string' ||\n !Object.hasOwn(Math, functionName) ||\n !isFunction(Math[functionName as keyof Math])\n ) {\n throw new Error(`math: unknown function '${String(functionName)}'`);\n }\n if (!Array.isArray(resolved.args)) {\n throw new Error('math: args must be an array');\n }\n const args = resolveMathConstants(resolved.args);\n\n newOperationData.mathResult = (\n Math[functionName] as (...args: any[]) => any\n ).apply(null, args);\n\n return newOperationData;\n};\n\nfunction resolveMathConstants(args: any[]) {\n return args.map((arg: any) => {\n if (isMathProperty(arg)) {\n return Math[arg];\n }\n return arg;\n });\n}\n\nfunction isMathProperty(value: string | symbol): value is keyof Math {\n return (\n isString(value) &&\n Object.hasOwn(Math, value) &&\n !isFunction(Math[value as keyof Math])\n );\n}\n","import {findMatchingEndIndex} from '@operation/helper/flow-control-index.ts';\nimport {\n endWhenSystemName,\n whenSystemName,\n} from '@operation/helper/flow-control-names.ts';\nimport type {IOperationScope, TOperation} from '@operation/types.ts';\n\n/**\n * If the preceeding {@link when} operation evaluates to `true` subsequent operations will\n * be skipped until an {@link endWhen} operation is encountered.\n *\n * @category Control Flow\n */\nexport const otherwise: TOperation<Record<string, unknown>> = function (\n operationData: Record<string, unknown>\n) {\n if (this.whenEvaluation) {\n this.newIndex = findEndWhenIndex(this);\n }\n return operationData;\n};\n\nfunction findEndWhenIndex(scope: IOperationScope) {\n const endWhenIndex = findMatchingEndIndex(\n scope.operations,\n scope.currentIndex + 1,\n whenSystemName,\n endWhenSystemName\n );\n return endWhenIndex > -1 ? endWhenIndex : scope.operations.length;\n}\n","import type {TOperation} from '@operation/types.ts';\n\nexport interface IRemoveClassOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @type=ParameterType:className\n * @required\n * @erased\n */\n className: string;\n}\n\n/**\n * This operation removes the spcified class name from the given selected element.\n *\n * @param operationData\n * @returns\n * @category DOM\n */\nexport const removeClass: TOperation<\n IRemoveClassOperationData,\n Omit<IRemoveClassOperationData, 'className'>\n> = (operationData: IRemoveClassOperationData) => {\n const {selectedElement, className} = operationData;\n delete (operationData as any).className;\n selectedElement.removeClass(className);\n return operationData;\n};\n","import type {IController} from '@controllers/types.ts';\nimport {getElementControllers} from '@operation/helper/get-element-data.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IRemoveControllerFromElementOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @type=ParameterType:controllerName\n * @required\n * @erased\n */\n controllerName: string;\n}\n\n/**\n * This operation removes the controller with the specified name from the given selected element.\n *\n * @param operationData\n * @returns\n *\n * @category Controller\n */\nexport const removeControllerFromElement: TOperation<\n IRemoveControllerFromElementOperationData,\n Omit<IRemoveControllerFromElementOperationData, 'controllerName'>\n> = function (operationData: IRemoveControllerFromElementOperationData) {\n const {selectedElement, controllerName} = operationData;\n\n delete (operationData as any).controllerName;\n\n const controllers = getElementControllers(selectedElement);\n const controller = controllers?.find(\n (ctrl: IController<any>) => ctrl.name === controllerName\n );\n\n if (controller && controllers) {\n const idx = controllers.indexOf(controller);\n controllers.splice(idx, 1);\n controller.detach(this.eventbus);\n } else {\n console.warn(\n `controller for name '${controllerName}' was not found on the given element`\n );\n }\n\n return operationData;\n};\n","import {detachControllersWithin} from '@operation/helper/detach-controllers-within.ts';\nimport type {IOperationScope, TOperation} from '@operation/types.ts';\n\nexport interface IRemoveElementOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n}\n\n/**\n * This operation removes the given selected element from the DOM.\n *\n * Controllers attached to the element or its descendants (by `addControllerToElement`) are\n * detached first, so their eventbus and window listeners do not outlive the element.\n *\n * @throws AggregateError When one or more controller `detach()` calls throw. The element is removed anyway.\n *\n * @category DOM\n */\nexport const removeElement: TOperation<IRemoveElementOperationData> = function (\n this: IOperationScope,\n operationData: IRemoveElementOperationData\n) {\n const {selectedElement} = operationData;\n const errors = detachControllersWithin(selectedElement, this.eventbus);\n selectedElement.remove();\n if (errors.length) {\n throw new AggregateError(\n errors,\n 'removeElement: detaching controllers of the removed element failed'\n );\n }\n return operationData;\n};\n","import type {TOperation} from '@operation/types.ts';\n\nexport interface IRemovePropertiesFromOperationDataOperationData {\n /**\n * @required\n * @erased\n */\n propertyNames: string[];\n}\n\n/**\n * This operation removes the given list of properties from the current operation data.\n * It will also remove the property `propertyNames` from the result.\n *\n * @category Data\n */\nexport const removePropertiesFromOperationData: TOperation<\n IRemovePropertiesFromOperationDataOperationData,\n Omit<IRemovePropertiesFromOperationDataOperationData, 'propertyNames'>\n> = (operationData: IRemovePropertiesFromOperationDataOperationData) => {\n const {propertyNames} = operationData;\n if (propertyNames.indexOf('propertyNames') < 0) {\n propertyNames.push('propertyNames');\n }\n\n return Object.fromEntries(\n Object.entries(operationData).filter(\n ([name, _value]) => !propertyNames.includes(name)\n )\n );\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {IOperationScope, TOperation} from '@operation/types.ts';\n\nexport interface IReparentElementOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @type=ParameterType:selector\n * @required\n * @erased\n */\n newParentSelector: string;\n}\n\n/**\n * This operation moves the given selected element to the new parent that is defined\n * by the specified `newParentSelector`. jQuery data, event handlers and attached controllers\n * are preserved.\n *\n * The selector is resolved inside the engine root (the root itself included), the same way\n * `selectElement` resolves its selector, and must match exactly one element. HTML strings are\n * not accepted.\n *\n * @param operationData\n * @returns\n * @throws When the selector is empty or HTML, when the engine root is not available, or when the\n * selector matches no element or more than one element.\n *\n * @category DOM\n */\nexport const reparentElement: TOperation<\n IReparentElementOperationData,\n Omit<IReparentElementOperationData, 'newParentSelector'>\n> = function (\n this: IOperationScope,\n operationData: IReparentElementOperationData\n) {\n const {selectedElement, newParentSelector} = operationData;\n removeProperties(operationData, 'newParentSelector');\n\n if (typeof newParentSelector !== 'string' || !newParentSelector.trim()) {\n throw new Error('reparentElement: newParentSelector is required');\n }\n // jQuery would parse a string like '<div>' as HTML and create new nodes\n if (newParentSelector.trim().startsWith('<')) {\n throw new Error(\n 'reparentElement: newParentSelector must be a selector, not HTML'\n );\n }\n\n const root = this.services.getEngineRoot();\n if (!root?.length) {\n throw new Error('reparentElement: the engine root is not available');\n }\n\n const target = root\n .filter(newParentSelector)\n .add(root.find(newParentSelector));\n\n if (target.length === 0) {\n throw new Error(\n `reparentElement: '${newParentSelector}' matched no element inside the engine root`\n );\n }\n if (target.length > 1) {\n // appendTo would insert clones into every target but the last\n throw new Error(\n `reparentElement: '${newParentSelector}' matched ${target.length} elements, expected exactly one`\n );\n }\n\n // appendTo moves the existing node; .remove() would strip its jQuery data and handlers\n selectedElement.appendTo(target);\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IReplaceStringOperationData {\n /**\n * @dependency\n */\n textContent: string;\n /**\n * @required\n * @erased\n */\n pattern: string | RegExp;\n /**\n * @required\n * @erased\n */\n replacement: string;\n /**\n * @output\n */\n result?: string;\n}\n\n/**\n * Replaces occurrences of a pattern in a string (alias for replaceText for string context).\n *\n * Like replaceText, a string pattern replaces every occurrence and inserts the replacement\n * literally (`$&`, `$1` and similar are not expanded). A RegExp pattern follows\n * `String.prototype.replace`: only a global RegExp replaces every match, and `$` patterns\n * in the replacement are expanded. Unlike replaceText, the result is written to `result`\n * and `textContent` is left unchanged.\n *\n * @returns Operation data with `result` containing the replaced string\n * @throws When textContent is missing or the string pattern is empty.\n *\n * @example\n * ```typescript\n * const result = replaceString({\n * textContent: 'a-b-c',\n * pattern: '-',\n * replacement: '+'\n * });\n * // result.result = \"a+b+c\"\n * ```\n *\n * @category String\n */\nexport const replaceString: TOperation<\n IReplaceStringOperationData,\n Omit<IReplaceStringOperationData, 'pattern' | 'replacement'>\n> = (operationData: IReplaceStringOperationData) => {\n const {textContent, pattern, replacement} = operationData;\n\n if (textContent === undefined || textContent === null) {\n throw new Error('replaceString: textContent is required');\n }\n\n if (pattern instanceof RegExp) {\n operationData.result = textContent.replace(pattern, replacement);\n } else {\n if (pattern === '') {\n throw new Error('replaceString: pattern must not be empty');\n }\n operationData.result = textContent.split(pattern).join(replacement);\n }\n\n removeProperties(operationData, 'pattern', 'replacement');\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IReplaceTextOperationData {\n /**\n * @dependency\n */\n textContent: string;\n /**\n * @required\n * @erased\n */\n searchPattern: string | RegExp;\n /**\n * @required\n * @erased\n */\n replacement: string;\n /**\n * @output\n */\n replacementCount?: number;\n}\n\n/**\n * Finds and replaces text using literal string or regex pattern.\n *\n * Operates on textContent passed from previous operations (e.g., getTextContent).\n * Supports regex patterns with global flag for multiple replacements.\n * Updates textContent with replaced text and sets replacementCount.\n *\n * A string pattern replaces every occurrence and inserts the replacement literally.\n *\n * @returns Operation data with updated `textContent` and `replacementCount` indicating number of replacements made\n * @throws When textContent is missing or the string searchPattern is empty.\n *\n * @example\n * ```typescript\n * // Replace placeholder with value\n * const result = replaceText({\n * textContent: 'Hello {{name}}',\n * searchPattern: '{{name}}',\n * replacement: 'John'\n * });\n * // result.textContent = \"Hello John\"\n * // result.replacementCount = 1\n * ```\n *\n * @example\n * ```typescript\n * // Replace with regex pattern\n * const result = replaceText({\n * textContent: 'Test 123 and 456',\n * searchPattern: /\\d+/g,\n * replacement: 'NUM'\n * });\n * // result.textContent = \"Test NUM and NUM\"\n * // result.replacementCount = 2\n * ```\n *\n * @category Text\n */\nexport const replaceText: TOperation<\n IReplaceTextOperationData,\n Omit<IReplaceTextOperationData, 'searchPattern' | 'replacement'>\n> = (operationData: IReplaceTextOperationData) => {\n const {textContent, searchPattern, replacement} = operationData;\n\n if (textContent === undefined || textContent === null) {\n throw new Error('replaceText: textContent is required');\n }\n\n let newText: string;\n let count = 0;\n\n if (searchPattern instanceof RegExp) {\n // Count matches for regex. match() on a non-global regex returns the capture\n // groups as well, and replace() then replaces only the first match, so count 1.\n // A global match() starts from lastIndex 0, like replace() does.\n count = searchPattern.global\n ? (textContent.match(searchPattern)?.length ?? 0)\n : textContent.search(searchPattern) >= 0\n ? 1\n : 0;\n newText = textContent.replace(searchPattern, replacement);\n } else {\n if (searchPattern === '') {\n // split('') would insert the replacement between every character\n throw new Error('replaceText: searchPattern must not be empty');\n }\n // Count matches for string\n const parts = textContent.split(searchPattern);\n count = parts.length - 1;\n newText = parts.join(replacement);\n }\n\n operationData.textContent = newText;\n operationData.replacementCount = count;\n\n removeProperties(operationData, 'searchPattern', 'replacement');\n\n return operationData;\n};\n","import type {IAction} from '@action/types.ts';\nimport {lookupNamedEntry} from '@operation/helper/lookup-named-entry.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IRequestActionOperationData {\n /**\n * @type=ParameterType:actionName\n * @required\n * @erased\n */\n systemName: string;\n /**\n * @type=ParameterType:object\n * @output\n */\n actionInstance?: IAction;\n}\n\n/**\n * This operation requests an action instance with the specified name and assigns it\n * to the `actionInstance` property on the current operation data.\n *\n * @throws Error naming requestAction and the `systemName` when no action with that\n * name exists, so the misspelled name is reported here instead of by a later\n * `startAction` or `endAction`.\n *\n * @category Action\n */\nexport const requestAction: TOperation<\n IRequestActionOperationData,\n Omit<Required<IRequestActionOperationData>, 'systemName'>\n> = function (operationData: IRequestActionOperationData) {\n const {systemName} = operationData;\n\n removeProperties(operationData, 'systemName');\n\n operationData.actionInstance = lookupNamedEntry(\n 'requestAction',\n systemName,\n name => this.services.getAction(name),\n 'action'\n ) as IAction;\n\n return operationData as Required<IRequestActionOperationData>;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport type StorageType = 'local' | 'session';\n\nexport interface ISaveToStorageOperationData {\n /**\n * @required\n * @erased\n */\n key: string;\n /**\n * @required\n * @erased\n */\n value: any;\n /**\n * @required\n * @erased\n */\n storageType: StorageType;\n}\n\n/**\n * Saves data to browser storage (localStorage or sessionStorage).\n *\n * Serializes the value as JSON before storing. Supports any JSON-serializable data type.\n * Use `null` to store an empty value; `undefined` cannot be stored as JSON and is rejected.\n * When `storageType` is omitted, localStorage is used.\n *\n * @returns Operation data with storage properties erased\n * @throws When the key is empty, the value is undefined, or storageType is not 'local' or 'session'.\n *\n * @example\n * ```typescript\n * // Save user settings to localStorage\n * const result = saveToStorage({\n * key: 'user-settings',\n * value: { theme: 'dark', language: 'en' },\n * storageType: 'local'\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Save session data\n * const result = saveToStorage({\n * key: 'session-id',\n * value: 'abc123',\n * storageType: 'session'\n * });\n * ```\n *\n * @category Data\n */\nexport const saveToStorage: TOperation<\n ISaveToStorageOperationData,\n Omit<ISaveToStorageOperationData, 'key' | 'value' | 'storageType'>\n> = (operationData: ISaveToStorageOperationData) => {\n const {key, value, storageType} = operationData;\n\n if (!key || key.trim() === '') {\n throw new Error('saveToStorage: key is required');\n }\n\n // A missing storageType keeps the long-standing localStorage default; any other\n // value, such as a typo, must not silently write to persistent storage\n if (\n storageType !== undefined &&\n storageType !== 'local' &&\n storageType !== 'session'\n ) {\n throw new Error(\n `saveToStorage: storageType must be 'local' or 'session', got \"${String(storageType)}\"`\n );\n }\n\n // JSON.stringify(undefined) is undefined, which setItem would store as the\n // string 'undefined' that loadFromStorage cannot parse\n if (value === undefined) {\n throw new Error(`saveToStorage: value is required (key \"${key}\")`);\n }\n\n const storage = storageType === 'session' ? sessionStorage : localStorage;\n const serialized = JSON.stringify(value);\n storage.setItem(key, serialized);\n\n removeProperties(operationData, 'key', 'value', 'storageType');\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport type ScrollBehavior = 'auto' | 'smooth';\nexport type ScrollLogicalPosition = 'start' | 'center' | 'end' | 'nearest';\n\nexport interface IScrollToElementOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @optional\n * @erased\n */\n behavior?: ScrollBehavior;\n /**\n * @optional\n * @erased\n */\n block?: ScrollLogicalPosition;\n /**\n * @optional\n * @erased\n */\n inline?: ScrollLogicalPosition;\n}\n\n/**\n * Scrolls the viewport to bring the selected element into view.\n *\n * Uses the browser's `scrollIntoView` API with configurable behavior.\n *\n * @returns Operation data with scroll properties erased\n *\n * @example\n * ```typescript\n * // Smooth scroll to element at top of viewport\n * const result = scrollToElement({\n * selectedElement: $targetElement,\n * behavior: 'smooth',\n * block: 'start'\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Center element in viewport\n * const result = scrollToElement({\n * selectedElement: $targetElement,\n * behavior: 'smooth',\n * block: 'center'\n * });\n * ```\n *\n * @category Scroll\n */\nexport const scrollToElement: TOperation<\n IScrollToElementOperationData,\n Omit<IScrollToElementOperationData, 'behavior' | 'block' | 'inline'>\n> = (operationData: IScrollToElementOperationData) => {\n const {\n selectedElement,\n behavior = 'auto',\n block = 'start',\n inline = 'nearest',\n } = operationData;\n\n if (!selectedElement || selectedElement.length === 0) {\n throw new Error('scrollToElement: selectedElement is required');\n }\n\n const element = selectedElement[0];\n element.scrollIntoView({\n behavior,\n block,\n inline,\n });\n\n removeProperties(operationData, 'behavior', 'block', 'inline');\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport type ScrollBehavior = 'auto' | 'smooth';\n\nexport interface IScrollToPositionOperationData {\n /**\n * @required\n * @erased\n */\n x: number;\n /**\n * @required\n * @erased\n */\n y: number;\n /**\n * @optional\n * @erased\n */\n behavior?: ScrollBehavior;\n}\n\n/**\n * Scrolls the viewport to a specific x,y coordinate position.\n *\n * Uses the browser's `window.scrollTo` API with configurable behavior.\n *\n * @returns Operation data with scroll properties erased\n *\n * @example\n * ```typescript\n * // Smooth scroll to position\n * const result = scrollToPosition({\n * x: 0,\n * y: 500,\n * behavior: 'smooth'\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Instant scroll to top\n * const result = scrollToPosition({\n * x: 0,\n * y: 0\n * });\n * ```\n *\n * @category Scroll\n */\nexport const scrollToPosition: TOperation<\n IScrollToPositionOperationData,\n Omit<IScrollToPositionOperationData, 'x' | 'y' | 'behavior'>\n> = (operationData: IScrollToPositionOperationData) => {\n const {x, y, behavior = 'auto'} = operationData;\n\n if (typeof x !== 'number' || typeof y !== 'number') {\n throw new Error('scrollToPosition: x and y coordinates are required');\n }\n\n window.scrollTo({\n left: x,\n top: y,\n behavior,\n });\n\n removeProperties(operationData, 'x', 'y', 'behavior');\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport {\n type ExternalProperty,\n resolveExternalPropertyChain,\n} from '@operation/helper/resolve-external-property-chain.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nfunction findElementBySelector(root: JQuery, selector: string) {\n const element = root.find(selector);\n if (!element.length) {\n console.warn(`selector '${selector}' wasn't found!`);\n }\n return element;\n}\n\nexport interface ISelectElementOperationData {\n /**\n * @type=ParameterType:selector\n * @required\n * @erased\n */\n selector: string;\n /**\n * @erased\n */\n useSelectedElementAsRoot?: boolean;\n /**\n * @type=ParameterType:object\n * @output\n */\n selectedElement?: JQuery;\n}\n\n/**\n * This operation selects one or more elements using the specified selector.\n *\n * If `useSelectedElementAsRoot` is set to true and a valid DOM element is assigned\n * to the current operation data's `selectedElement` property\n * then the element will be looked for only in the descendant elements of this DOM element.\n *\n * @category DOM\n */\nexport const selectElement: TOperation<\n ISelectElementOperationData,\n Omit<ISelectElementOperationData, 'selector' | 'useSelectedElementAsRoot'>\n> = function (operationData: ISelectElementOperationData) {\n operationData.selector = resolveExternalPropertyChain(\n operationData,\n this,\n operationData.selector as ExternalProperty\n ) as string;\n\n const {selector, useSelectedElementAsRoot = false} = operationData;\n\n removeProperties(operationData, 'selector', 'useSelectedElementAsRoot');\n\n if (!selector) {\n throw new Error('selectElement: selector is either empty or not defined.');\n }\n\n if (useSelectedElementAsRoot && operationData.selectedElement) {\n const currentRoot = operationData.selectedElement;\n operationData.selectedElement = findElementBySelector(\n currentRoot,\n selector\n );\n return operationData;\n }\n\n operationData.selectedElement = findElementBySelector(\n this.services.getEngineRoot(),\n selector\n );\n\n return operationData;\n};\n","import {\n assertParsedChainSafe,\n findForbiddenSegment,\n type IParsedSegments,\n parseSegments,\n walkChain,\n} from '@operation/helper/chain-cache.ts';\nimport {getGlobals} from '@operation/helper/globals.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport {\n findDeclaringScope,\n resolveExternalPropertyChain,\n} from '@operation/helper/resolve-external-property-chain.ts';\nimport type {\n IOperationScope,\n TOperation,\n TOperationData,\n} from '@operation/types.ts';\n\nexport type TDataTarget =\n | `$scope.${string}`\n | `$operationdata.${string}`\n | `$globaldata.${string}`;\n\nexport interface ISetDataOperationData {\n /**\n * @required\n * @erased\n */\n properties: Record<TDataTarget, any>;\n}\n\n/**\n * This operation assigns the specified properties to the specified data targets.\n *\n * @example The various ways of assigning data\n * ```ts\n * setData({\n * '$operationdata.foo': '$scope.currentItem', // $scope.currentItem will be assigned to $operationdata.foo\n * '$globaldata.foo': '$scope.currentItem', // $scope.currentItem will be assigned to $globaldata.foo\n * '$scope.newIndex': 100, // The constant 100 will be assigned to $scope.newIndex\n * })\n * ```\n *\n * A `$scope` target with a property chain, such as `$scope.variables.total`, is written to the\n * nearest scope that declares the chain's first property, the same scope a `$scope` read\n * resolves from. Inside a `when` or `forEach` block this updates the action's variables.\n *\n * @throws When a target is not `$scope`, `$operationdata` or `$globaldata`, when it contains a\n * forbidden segment, or when the part before the written property does not resolve to an object.\n *\n * @category Data\n */\nexport const setData: TOperation<\n ISetDataOperationData,\n Omit<ISetDataOperationData, 'properties'>\n> = function (operationData: ISetDataOperationData) {\n const {properties} = operationData;\n removeProperties(operationData, 'properties');\n\n resolveTargets(properties, operationData, this);\n\n return operationData;\n};\n\n/**\n * A target key such as `$scope.variables.total`, parsed once. The target text\n * comes from the configuration, so the parsed form is cached.\n */\ninterface IParsedTarget {\n rootTarget: string;\n /** The chain before the written property */\n path: IParsedSegments;\n /** The first segment of `path` as written, for {@link findDeclaringScope} */\n head: string | undefined;\n pathLength: number;\n /** The property that is written */\n property: string;\n /** The target as printed in the \"does not resolve to an object\" message */\n targetText: string;\n /** A forbidden segment anywhere in the target, including the written property */\n forbiddenSegment: string | undefined;\n}\n\nconst MAX_CACHED_TARGETS = 2000;\nconst parsedTargets = new Map<string, IParsedTarget>();\n\nfunction parseTarget(item: string): IParsedTarget {\n const cached = parsedTargets.get(item);\n if (cached !== undefined) {\n return cached;\n }\n const path = item.split('.');\n const rootTarget = path.shift()?.toLowerCase().substring(1) ?? '';\n if (!isDataTarget(rootTarget)) {\n throw new Error(\n `Unrecognized target: ${rootTarget}, known targets are: ${knownTargets.join(\n ', '\n )}`\n );\n }\n // Guard every segment, including the property that is written, against\n // prototype pollution before anything is resolved or assigned.\n const forbiddenSegment = findForbiddenSegment(path);\n const property = path.pop() ?? '';\n const parsed: IParsedTarget = {\n rootTarget,\n path: parseSegments(path),\n head: path[0],\n pathLength: path.length,\n property,\n targetText: [`$${rootTarget}`, ...path].join('.'),\n forbiddenSegment,\n };\n if (parsedTargets.size >= MAX_CACHED_TARGETS) {\n parsedTargets.clear();\n }\n parsedTargets.set(item, parsed);\n return parsed;\n}\n\nfunction resolveTargets(\n data: Record<TDataTarget, any>,\n operationData: Record<string, any>,\n scope: IOperationScope\n) {\n for (const item of Object.keys(data)) {\n const target = parseTarget(item);\n if (target.forbiddenSegment !== undefined) {\n throw new Error(\n `setData: property chain '${item}' contains forbidden segment '${target.forbiddenSegment}'. Property chains may not contain __proto__, prototype or constructor.`\n );\n }\n const propertyValue = resolveExternalPropertyChain(\n operationData,\n scope,\n (data as any)[item]\n );\n\n let targetObject: TOperationData;\n if (target.rootTarget === 'scope') {\n // An empty path (such as '$scope.newIndex') writes to the current scope.\n targetObject =\n target.pathLength > 0\n ? (findDeclaringScope(target.head as string, scope) ?? scope)\n : scope;\n } else if (target.rootTarget === 'operationdata') {\n targetObject = operationData;\n } else {\n targetObject = getGlobals();\n }\n\n assertParsedChainSafe(target.path, 'setData');\n const propertyTarget = walkChain(\n target.path,\n targetObject,\n 'setData'\n ) as Record<string, any>;\n\n if (\n propertyTarget === null ||\n (typeof propertyTarget !== 'object' &&\n typeof propertyTarget !== 'function')\n ) {\n throw new Error(\n `setData: cannot write '${item}': '${target.targetText}' does not resolve to an object`\n );\n }\n\n propertyTarget[target.property] = propertyValue;\n }\n}\n\nconst knownTargets = ['scope', 'operationdata', 'globaldata'];\nfunction isDataTarget(value: string): value is TDataTarget {\n return knownTargets.includes(value);\n}\n","import {assertSafeAttribute} from '@operation/helper/assert-safe-attribute.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface ISetElementAttributesOperationData {\n /**\n * @required\n * @erased\n */\n attributes: Record<string, unknown>;\n /**\n * @dependency\n */\n selectedElement: JQuery;\n}\n\n/**\n * This operation sets the specified set of attributes on the given selected element.\n *\n * Event handler (`on*`) and `srcdoc` attributes, and `javascript:` or `vbscript:` URLs in URL\n * attributes such as `href`, `src` and `formaction`, are refused, the same as in `createElement`.\n *\n * @throws When an attribute is refused. No attribute is set then.\n *\n * @category DOM\n */\nexport const setElementAttributes: TOperation<\n ISetElementAttributesOperationData,\n Omit<ISetElementAttributesOperationData, 'attributes'>\n> = (operationData: ISetElementAttributesOperationData) => {\n const {attributes, selectedElement} = operationData;\n removeProperties(operationData, 'attributes');\n Object.entries(attributes ?? {}).forEach(([name, value]) => {\n assertSafeAttribute('setElementAttributes', name, value);\n });\n selectedElement.attr(attributes);\n return operationData;\n};\n","import {detachControllersWithin} from '@operation/helper/detach-controllers-within.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {IOperationScope, TOperation} from '@operation/types.ts';\n\nexport interface ISetElementContentOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @erased\n */\n template: string | JQuery.Node;\n /**\n * overwite = the contents of the selected element are replaced by the given template\n *\n * append = the new content will be inserted after the current content\n *\n * prepend = the new content will be inserted before the current content\n *\n * Defaults to overwrite.\n *\n * @erased\n */\n insertionType?: 'overwrite' | 'append' | 'prepend';\n}\n\n/**\n * This operation sets the specified content defined by the value assigned to the template property\n * to the given selected element.\n *\n * When the `insertionType` is set to `overwrite` the contents of the selected element are replaced\n * by the given template.\n * When set to `append` the new content will be inserted after the current content.\n * When set to `prepend` the new content will be inserted before the current content.\n *\n * With `overwrite`, controllers attached to the replaced content (by `addControllerToElement`) are\n * detached first. Controllers on the selected element itself stay attached.\n *\n * The template is inserted as HTML: a string template is parsed by jQuery, which also runs the\n * scripts and inline event handlers it contains. Only use string templates from the configuration\n * or the resource importer; build content from user data with `createElement`, whose `text` is\n * never parsed as HTML.\n *\n * @throws AggregateError When one or more controller `detach()` calls throw. The content is replaced anyway.\n * @throws When `insertionType` is not `overwrite`, `append` or `prepend`. Nothing is changed.\n *\n * @category DOM\n */\nexport const setElementContent: TOperation<\n ISetElementContentOperationData,\n Omit<ISetElementContentOperationData, 'template' | 'insertionType'>\n> = function (\n this: IOperationScope,\n operationData: ISetElementContentOperationData\n) {\n const {\n insertionType = 'overwrite',\n selectedElement,\n template,\n } = operationData;\n\n let detachErrors: unknown[] = [];\n\n switch (insertionType) {\n case 'overwrite':\n detachErrors = detachControllersWithin(\n selectedElement.children(),\n this.eventbus\n );\n selectedElement.html(template);\n break;\n case 'append':\n selectedElement.append(template);\n break;\n case 'prepend':\n selectedElement.prepend(template);\n break;\n default:\n // A misspelled insertionType would otherwise leave the element unchanged\n // without any sign of the mistake\n throw new Error(\n `setElementContent: unknown insertionType '${String(insertionType)}', expected 'overwrite', 'append' or 'prepend'`\n );\n }\n\n removeProperties(operationData, 'insertionType', 'template');\n\n if (detachErrors.length) {\n throw new AggregateError(\n detachErrors,\n 'setElementContent: detaching controllers of the replaced content failed'\n );\n }\n\n return operationData;\n};\n","import type {TOperation} from '@operation/types.ts';\n\nexport interface ISetFocusOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n}\n\n/**\n * Sets focus to the selected element.\n *\n * @category Focus\n */\nexport const setFocus: TOperation<\n ISetFocusOperationData,\n ISetFocusOperationData\n> = (operationData: ISetFocusOperationData) => {\n const {selectedElement} = operationData;\n\n if (!selectedElement || selectedElement.length === 0) {\n throw new Error('setFocus: selectedElement is required');\n }\n\n selectedElement[0].focus();\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface ISetFormValueOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @required\n * @erased\n */\n value: string | number | boolean;\n}\n\n/**\n * Sets the value of an input, select, or textarea element.\n *\n * Handles different input types appropriately:\n * - Text inputs, textareas, selects: sets value directly\n * - Checkboxes: sets checked property for boolean values\n * - Radio buttons: sets checked property for boolean values\n * - Number inputs: converts to string\n *\n * @example\n * ```typescript\n * // Set text input value\n * const result = setFormValue({selectedElement: $input, value: 'test@example.com'});\n * // Element value is now 'test@example.com'\n * ```\n *\n * @example\n * ```typescript\n * // Set checkbox checked state\n * const result = setFormValue({selectedElement: $checkbox, value: true});\n * // Checkbox is now checked\n * ```\n *\n * @category Form\n */\nexport const setFormValue: TOperation<\n ISetFormValueOperationData,\n Omit<ISetFormValueOperationData, 'value'>\n> = (operationData: ISetFormValueOperationData) => {\n const {selectedElement, value} = operationData;\n\n // Validate selectedElement exists\n if (!selectedElement || selectedElement.length === 0) {\n throw new Error('setFormValue: selectedElement is required');\n }\n\n // Handle checkboxes and radio buttons with boolean values\n if (\n typeof value === 'boolean' &&\n (selectedElement.is(':checkbox') || selectedElement.is(':radio'))\n ) {\n selectedElement.prop('checked', value);\n } else {\n // Handle all other inputs with val()\n selectedElement.val(value as any);\n }\n\n removeProperties(operationData, 'value');\n\n return operationData;\n};\n","import {setGlobals} from '@operation/helper/globals.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface ISetGlobalDataOperationData {\n /**\n * @required\n * @erased\n */\n propertyNames: string[];\n}\n\n/**\n * This operation copies the specified properties from the operationData to the global data.\n *\n * Plain data is stored as a deep copy, so changing the operation data afterwards does not change\n * the global data. jQuery objects, DOM nodes, functions and class instances (such as controllers)\n * are stored by reference.\n *\n * @throws When a property name is `__proto__`, `prototype` or `constructor`.\n *\n * @category Data\n */\nexport const setGlobalData: TOperation<\n ISetGlobalDataOperationData,\n Omit<ISetGlobalDataOperationData, 'propertyNames'>\n> = (operationData: ISetGlobalDataOperationData) => {\n const {propertyNames, ...newOperationData} = operationData;\n const newGlobals = Object.fromEntries(\n Object.entries(operationData).filter(([name, _value]) =>\n propertyNames.includes(name)\n )\n );\n\n setGlobals(newGlobals);\n\n return newOperationData;\n};\n","import {resolvePropertyValues} from '@operation/helper/resolve-property-values.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface ISetOperationData {\n /**\n * If set to true, the plucked properties replace the current operation data.\n * @erased\n */\n override?: boolean;\n /**\n * @required\n * @erased\n */\n properties: Record<string, any>;\n}\n\n/**\n * This operation assigns the specified properties to the current operation data.\n * When override is set to true the properties replace the current operation data entirely.\n *\n * @category Data\n */\nexport const setOperationData: TOperation<\n ISetOperationData,\n Omit<ISetOperationData, 'override' | 'properties'>\n> = function (operationData: ISetOperationData) {\n const {override = false, properties, ...newOperationData} = operationData;\n\n const resolvedProperties = resolvePropertyValues(\n newOperationData,\n this,\n properties\n );\n\n if (override) {\n return resolvedProperties;\n }\n\n return {\n ...newOperationData,\n ...resolvedProperties,\n };\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport {resolvePropertyValues} from '@operation/helper/resolve-property-values.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface ISetStyleOperationData {\n /**\n * @type=ParameterType:cssProperties\n * @required\n * @erased\n */\n properties: Record<string, any>;\n /**\n * @dependency\n */\n selectedElement: JQuery;\n}\n\n/**\n * This operation assigns the specified CSS style properties to the\n * given selected element.\n *\n * @category DOM\n */\nexport const setStyle: TOperation<\n ISetStyleOperationData,\n Omit<ISetStyleOperationData, 'properties'>\n> = function (operationData: ISetStyleOperationData) {\n const properties = resolvePropertyValues(\n operationData,\n this,\n operationData.properties\n );\n operationData.selectedElement.css(properties as JQuery.PlainObject);\n\n removeProperties(operationData, 'properties');\n\n return operationData;\n};\n","import {isForbiddenPropertyChainSegment} from '@operation/helper/assert-safe-property-chain.ts';\nimport {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport {\n findDeclaringScope,\n findRootScope,\n} from '@operation/helper/resolve-external-property-chain.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface ISetVariableOperationData {\n /**\n * @required\n * @erased\n */\n name: string;\n /**\n * @type=ParameterType:object|ParameterType:string|ParameterType:number|ParameterType:boolean|ParameterType:array\n * @required\n * @erased\n */\n value: any;\n}\n\n/**\n * This operation sets a variable with the specified name on the scope with the specified value.\n *\n * Variables belong to the action: a variable set inside a `when` or `forEach` block is the\n * same variable outside it, so it keeps its value after `endWhen` or `endForEach`, and\n * variables set before the block can be read and changed inside it. Read variables with\n * `$scope.variables.<name>`.\n *\n * @throws When the name is `__proto__`, `prototype` or `constructor`.\n *\n * @category Data\n */\nexport const setVariable: TOperation<\n ISetVariableOperationData,\n Omit<ISetVariableOperationData, 'name' | 'value'>\n> = function (operationData: ISetVariableOperationData) {\n const {name, value} = operationData;\n\n if (isForbiddenPropertyChainSegment(name)) {\n throw new Error(\n `setVariable: variable name '${name}' is not allowed. Names may not be __proto__, prototype or constructor.`\n );\n }\n\n // Write to the scope `$scope.variables` chains are read from, or create the\n // store on the action's root scope, so child scopes of when/forEach blocks\n // share the action's variables.\n const scope = findDeclaringScope('variables', this) ?? findRootScope(this);\n if (!scope.variables) {\n // No prototype, so a configured name never reads inherited members.\n scope.variables = Object.create(null) as Record<string, unknown>;\n }\n\n scope.variables[name] = value;\n\n removeProperties(operationData, 'name', 'value');\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport type SortOrder = 'asc' | 'desc';\n\nexport interface ISortArrayOperationData {\n /**\n * @dependency\n */\n arrayData: any[];\n /**\n * @optional\n * @erased\n */\n sortProperty?: string;\n /**\n * @optional\n * @erased\n */\n sortOrder?: SortOrder;\n /**\n * @optional\n * @erased\n */\n sortComparator?: (a: any, b: any) => number;\n /**\n * @output\n */\n sortedArray?: any[];\n}\n\n/**\n * Sorts an array by property, natural order, or custom comparator function.\n *\n * Operates on arrayData passed from previous operations.\n * Supports three sorting modes:\n * 1. Property sort: `sortProperty` and `sortOrder` to sort objects by property\n * 2. Natural sort: `sortOrder` alone for primitive arrays\n * 3. Custom comparator: `sortComparator` function for complex sorting logic\n *\n * @returns Operation data with `sortedArray` containing sorted results\n *\n * @example\n * ```typescript\n * // Sort objects by property\n * const result = sortArray({\n * arrayData: [{name: 'Bob', age: 30}, {name: 'Alice', age: 25}],\n * sortProperty: 'age',\n * sortOrder: 'asc'\n * });\n * // result.sortedArray = [{name: 'Alice', age: 25}, {name: 'Bob', age: 30}]\n * ```\n *\n * @example\n * ```typescript\n * // Sort primitives\n * const result = sortArray({\n * arrayData: [5, 2, 8, 1],\n * sortOrder: 'desc'\n * });\n * // result.sortedArray = [8, 5, 2, 1]\n * ```\n *\n * @example\n * ```typescript\n * // Custom comparator\n * const result = sortArray({\n * arrayData: ['apple', 'Banana', 'cherry'],\n * sortComparator: (a, b) => a.toLowerCase().localeCompare(b.toLowerCase())\n * });\n * ```\n *\n * @category Array\n */\nexport const sortArray: TOperation<\n ISortArrayOperationData,\n Omit<ISortArrayOperationData, 'sortProperty' | 'sortOrder' | 'sortComparator'>\n> = (operationData: ISortArrayOperationData) => {\n const {arrayData, sortProperty, sortOrder, sortComparator} = operationData;\n\n if (!Array.isArray(arrayData)) {\n throw new Error('sortArray: arrayData is required and must be an array');\n }\n\n // Create a copy to avoid mutating original\n const sorted = [...arrayData];\n\n if (sortComparator) {\n sorted.sort(sortComparator);\n } else if (sortProperty) {\n sorted.sort((a, b) => {\n const aVal = a[sortProperty];\n const bVal = b[sortProperty];\n\n if (aVal < bVal) return sortOrder === 'desc' ? 1 : -1;\n if (aVal > bVal) return sortOrder === 'desc' ? -1 : 1;\n return 0;\n });\n } else {\n // Natural sort for primitives\n sorted.sort((a, b) => {\n if (a < b) return sortOrder === 'desc' ? 1 : -1;\n if (a > b) return sortOrder === 'desc' ? -1 : 1;\n return 0;\n });\n }\n\n operationData.sortedArray = sorted;\n\n removeProperties(\n operationData,\n 'sortProperty',\n 'sortOrder',\n 'sortComparator'\n );\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface ISplitStringOperationData {\n /**\n * @dependency\n */\n textContent: string;\n /**\n * @required\n * @erased\n */\n delimiter: string | RegExp;\n /**\n * @optional\n * @erased\n */\n limit?: number;\n /**\n * @output\n */\n resultArray?: string[];\n}\n\n/**\n * Splits a string into an array by delimiter (string or regex).\n *\n * @returns Operation data with `resultArray` containing the split strings\n *\n * @example\n * ```typescript\n * const result = splitString({\n * textContent: 'apple,banana,cherry',\n * delimiter: ','\n * });\n * // result.resultArray = ['apple', 'banana', 'cherry']\n * ```\n *\n * @category String\n */\nexport const splitString: TOperation<\n ISplitStringOperationData,\n Omit<ISplitStringOperationData, 'delimiter' | 'limit'>\n> = (operationData: ISplitStringOperationData) => {\n const {textContent, delimiter, limit} = operationData;\n\n if (textContent === undefined || textContent === null) {\n throw new Error('splitString: textContent is required');\n }\n\n operationData.resultArray = textContent.split(delimiter, limit);\n\n removeProperties(operationData, 'delimiter', 'limit');\n\n return operationData;\n};\n","import type {IAction} from '@action/types.ts';\nimport {internalResolve} from '@operation/helper/internal-resolve.ts';\nimport {mergeOperationData} from '@operation/helper/merge-operation-data.ts';\nimport type {TOperation, TOperationData} from '@operation/types.ts';\n\nexport interface IStartActionOperationData {\n /**\n * @dependency\n */\n actionInstance: IAction;\n /**\n * @type=ParameterType:object\n * @erased\n */\n actionOperationData?: TOperationData;\n}\n\n/**\n * This operation starts the specified action instance using the given action operation data.\n *\n * The action receives its own copy of the current operation data merged with the action\n * operation data. Whatever the action's operations add, change or remove in that copy stays\n * with the action: once it has completed, this operation continues with the operation data it\n * had before, plus `actionInstance`, without the `actionOperationData` property.\n *\n * @category Action\n */\nexport const startAction: TOperation<\n IStartActionOperationData,\n Omit<IStartActionOperationData, 'actionOperationData'>\n> = (operationData: IStartActionOperationData) => {\n const {\n actionInstance,\n actionOperationData = {},\n ...callerOperationData\n } = operationData;\n\n return new Promise((resolve, reject) => {\n if (!actionInstance) {\n reject(new Error('startAction: actionInstance is required'));\n return;\n }\n\n // The catch also rejects on errors thrown by the fulfilment handler, so the\n // returned promise always settles.\n actionInstance\n .start(mergeOperationData(callerOperationData, actionOperationData))\n .then(() => {\n internalResolve(resolve, {...callerOperationData, actionInstance});\n })\n .catch(reject);\n });\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface ISubstringTextOperationData {\n /**\n * @dependency\n */\n textContent: string;\n /**\n * @required\n * @erased\n */\n start: number;\n /**\n * @optional\n * @erased\n */\n end?: number;\n /**\n * @output\n */\n substring?: string;\n}\n\n/**\n * Extracts a substring from text between start and end indices.\n *\n * @returns Operation data with `substring` containing the extracted text\n *\n * @example\n * ```typescript\n * const result = substringText({\n * textContent: 'Hello World',\n * start: 0,\n * end: 5\n * });\n * // result.substring = \"Hello\"\n * ```\n *\n * @category Text\n */\nexport const substringText: TOperation<\n ISubstringTextOperationData,\n Omit<ISubstringTextOperationData, 'start' | 'end'>\n> = (operationData: ISubstringTextOperationData) => {\n const {textContent, start, end} = operationData;\n\n if (textContent === undefined || textContent === null) {\n throw new Error('substringText: textContent is required');\n }\n\n if (typeof start !== 'number') {\n throw new Error('substringText: start must be a number');\n }\n\n operationData.substring = textContent.substring(start, end);\n\n removeProperties(operationData, 'start', 'end');\n\n return operationData;\n};\n","import type {TOperation} from '@operation/types.ts';\n\nexport interface IToggleClassOperationData {\n /**\n * The element on which the class will be toggled\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * The class that will be toggled\n * @type=ParameterType:className\n * @required\n * @erased\n */\n className: string;\n}\n\n/**\n * This operation toggles the specfied class name on the given selected element.\n *\n * Meaning, if the specified class name exists on the given element it will be removed,\n * otherwise it will be added.\n *\n * @category DOM\n */\nexport const toggleClass: TOperation<\n IToggleClassOperationData,\n Omit<IToggleClassOperationData, 'className'>\n> = (operationData: IToggleClassOperationData) => {\n const {selectedElement, className} = operationData;\n selectedElement.toggleClass(className);\n delete (operationData as any).className;\n return operationData;\n};\n","import type {TOperation} from '@operation/types.ts';\n\nexport interface IToggleElementOperationData {\n /**\n * The element whose visibility will be toggled\n * @dependency\n */\n selectedElement: JQuery;\n}\n\n/**\n * This operation toggles the visibility of the given selected element.\n *\n * Meaning, if the element is hidden, it will be made visible, otherwise\n * it will be hidden.\n *\n * @category DOM\n */\nexport const toggleElement: TOperation<IToggleElementOperationData> =\n function toggleElement(operationData: IToggleElementOperationData) {\n operationData.selectedElement.toggle();\n return operationData;\n };\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IToggleFormElementOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @required\n * @erased\n */\n enabled: boolean;\n}\n\n/**\n * Enables or disables form input elements (inputs, selects, textareas, buttons).\n *\n * Sets the `disabled` property on the element. When `enabled` is true, removes the disabled\n * attribute; when false, adds the disabled attribute.\n *\n * @example\n * ```typescript\n * // Disable an input field\n * toggleFormElement({selectedElement: $input, enabled: false});\n * // Input is now disabled\n * ```\n *\n * @example\n * ```typescript\n * // Enable a previously disabled button\n * toggleFormElement({selectedElement: $button, enabled: true});\n * // Button is now enabled\n * ```\n *\n * @category Form\n */\nexport const toggleFormElement: TOperation<\n IToggleFormElementOperationData,\n Omit<IToggleFormElementOperationData, 'enabled'>\n> = (operationData: IToggleFormElementOperationData) => {\n const {selectedElement, enabled} = operationData;\n\n if (!selectedElement || selectedElement.length === 0) {\n throw new Error('toggleFormElement: selectedElement is required');\n }\n\n // Set disabled property (disabled = !enabled)\n selectedElement.prop('disabled', !enabled);\n\n removeProperties(operationData, 'enabled');\n\n return operationData;\n};\n","import {removeProperties} from '@operation/helper/remove-operation-properties.ts';\nimport type {TOperation} from '@operation/types.ts';\nimport $ from 'jquery';\n\nexport interface IValidationRules {\n required?: boolean;\n minLength?: number;\n maxLength?: number;\n pattern?: string | RegExp;\n email?: boolean;\n}\n\nexport interface IValidateFormOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @erased\n */\n validationRules?: Record<string, IValidationRules>;\n /**\n * @output\n * @type=ParameterType:object\n */\n validationErrors?: Record<string, string>;\n /**\n * @output\n */\n isValid?: boolean;\n}\n\nconst emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\nfunction isCheckable(element: Element): element is HTMLInputElement {\n if (element.tagName !== 'INPUT') return false;\n const type = (element as HTMLInputElement).type;\n return type === 'checkbox' || type === 'radio';\n}\n\nfunction toRegExp(pattern: string | RegExp): RegExp {\n return typeof pattern === 'string' ? new RegExp(pattern) : pattern;\n}\n\nfunction matches(pattern: RegExp, value: string): boolean {\n // A global or sticky RegExp keeps lastIndex between test() calls\n pattern.lastIndex = 0;\n return pattern.test(value);\n}\n\n/**\n * Applies the rules to a single string value, returns the error message or undefined.\n */\nfunction validateValue(\n value: string,\n rules: IValidationRules\n): string | undefined {\n if (rules.required && value.trim() === '') {\n return 'This field is required';\n }\n if (rules.minLength && value.length < rules.minLength) {\n return `Must be at least ${rules.minLength} characters`;\n }\n if (rules.maxLength && value.length > rules.maxLength) {\n return `Must be no more than ${rules.maxLength} characters`;\n }\n if (rules.pattern && !matches(toRegExp(rules.pattern), value)) {\n return 'Invalid format';\n }\n if (rules.email && !emailRegex.test(value)) {\n return 'Must be a valid email address';\n }\n return undefined;\n}\n\n/**\n * Applies the rules to the values of a `<select multiple>`: required, minLength and\n * maxLength count the selected options, pattern and email apply to each of them.\n */\nfunction validateSelection(\n values: string[],\n rules: IValidationRules\n): string | undefined {\n if (rules.required && values.length === 0) {\n return 'This field is required';\n }\n if (rules.minLength && values.length < rules.minLength) {\n return `Select at least ${rules.minLength} options`;\n }\n if (rules.maxLength && values.length > rules.maxLength) {\n return `Select no more than ${rules.maxLength} options`;\n }\n if (rules.pattern) {\n const pattern = toRegExp(rules.pattern);\n if (values.some(value => !matches(pattern, value))) {\n return 'Invalid format';\n }\n }\n if (rules.email && values.some(value => !emailRegex.test(value))) {\n return 'Must be a valid email address';\n }\n return undefined;\n}\n\n/**\n * Validates form fields against HTML5 validation and custom rules.\n *\n * Uses HTML5 validation API (checkValidity()) for native validation, and supports\n * custom validation rules for: required, minLength, maxLength, pattern (regex), and email format.\n *\n * Checkboxes and radio buttons are validated once per name: `required` passes when at least one\n * of them is checked, and the string rules do not apply to them. For a `<select multiple>`,\n * `required`, `minLength` and `maxLength` count the selected options, and `pattern` and `email`\n * apply to each selected value.\n *\n * @returns Operation data with `validationErrors` object (field names → error messages) and `isValid` boolean\n *\n * @example\n * ```typescript\n * // Validate with HTML5 validation\n * const result = validateForm({selectedElement: $form});\n * // Returns: {isValid: true, validationErrors: {}}\n * ```\n *\n * @example\n * ```typescript\n * // Validate with custom rules\n * const result = validateForm({\n * selectedElement: $form,\n * validationRules: {\n * password: { required: true, minLength: 8 },\n * email: { email: true }\n * }\n * });\n * // Returns: {isValid: false, validationErrors: {password: \"Must be at least 8 characters\"}}\n * ```\n *\n * @category Form\n */\nexport const validateForm: TOperation<\n IValidateFormOperationData,\n Omit<IValidateFormOperationData, 'validationRules'>\n> = (operationData: IValidateFormOperationData) => {\n const {selectedElement, validationRules} = operationData;\n\n if (!selectedElement || selectedElement.length === 0) {\n throw new Error('validateForm: selectedElement is required');\n }\n\n if (!selectedElement.is('form')) {\n throw new Error('validateForm: selectedElement must be a form element');\n }\n\n const validationErrors: Record<string, string> = {};\n // defineProperty, so a field named '__proto__' becomes an own key instead of\n // replacing the result's prototype\n const setError = (name: string, message: string) => {\n Object.defineProperty(validationErrors, name, {\n value: message,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n };\n\n // Get all form inputs\n const inputs = selectedElement.find('input, select, textarea');\n // Checkbox and radio groups are validated once per name\n const handledGroups = new Set<string>();\n\n inputs.each((_, element) => {\n const $input = $(element);\n const name = $input.attr('name');\n\n if (!name) return; // Skip inputs without name attribute\n\n // Only own entries count, so a field named e.g. 'constructor' gets no inherited rules\n const rules =\n validationRules && Object.hasOwn(validationRules, name)\n ? validationRules[name]\n : undefined;\n\n if (isCheckable(element)) {\n if (handledGroups.has(name)) return;\n handledGroups.add(name);\n\n const group = inputs\n .toArray()\n .filter(\n other => isCheckable(other) && other.getAttribute('name') === name\n ) as HTMLInputElement[];\n\n const invalid = group.find(\n input => input.checkValidity && !input.checkValidity()\n );\n if (invalid) {\n setError(name, invalid.validationMessage || 'Invalid value');\n return;\n }\n\n // A checkbox or radio is filled in when one of its group is checked; its value\n // attribute ('on' by default) says nothing about that, so string rules do not apply\n if (rules?.required && !group.some(input => input.checked)) {\n setError(name, 'This field is required');\n }\n return;\n }\n\n // HTML5 validation first\n const inputElement = element as\n | HTMLInputElement\n | HTMLTextAreaElement\n | HTMLSelectElement;\n if (inputElement.checkValidity && !inputElement.checkValidity()) {\n setError(name, inputElement.validationMessage || 'Invalid value');\n return;\n }\n\n // Custom validation rules\n if (!rules) return;\n\n const raw = $input.val();\n const error = Array.isArray(raw)\n ? validateSelection(raw.map(String), rules)\n : validateValue(raw == null ? '' : String(raw), rules);\n if (error) {\n setError(name, error);\n }\n });\n\n operationData.validationErrors = validationErrors;\n operationData.isValid = Object.keys(validationErrors).length === 0;\n\n removeProperties(operationData, 'validationRules');\n\n return operationData;\n};\n","import {internalResolve} from '@operation/helper/internal-resolve.ts';\nimport type {TOperation} from '@operation/types.ts';\n\nexport interface IWaitOperationData {\n /**\n * The amount of milliseconds the operation will wait for.\n * @required\n * @erased\n */\n milliseconds: number;\n}\n\n/**\n * This operation waits for the specified amount of milliseconds.\n *\n * @category Utility\n */\nexport const wait: TOperation<\n IWaitOperationData,\n Omit<IWaitOperationData, 'milliseconds'>\n> = (operationData: IWaitOperationData) => {\n const {milliseconds, ...newOperationData} = operationData;\n\n return new Promise(resolve => {\n setTimeout(() => {\n internalResolve(resolve, newOperationData);\n }, milliseconds);\n });\n};\n","import type { IAddClassOperationData } from \"@operation/add-class.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function addClass(): IOperationMetadata<IAddClassOperationData> {\n return {\n description: `This operation adds the specified class name to the specified selected element.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n properties: {\n className: {\n type: 'ParameterType:className',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IAddControllerToElementOperationData } from \"@operation/add-controller-to-element.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { TOperationData } from \"@operation/types.ts\";\n\nexport function addControllerToElement(): IOperationMetadata<IAddControllerToElementOperationData<TOperationData>> {\n return {\n description: `This operation adds the specified controller instance to the given selected element.\n\nThe controller is registered on the element only once \\`init\\` and a synchronous \\`attach\\`\nhave succeeded. When \\`attach\\` returns a promise, the controller is registered before\nthat promise settles (so detaching the element can still reach it) and is removed from\nthe element again when the promise rejects.`,\n category: `Controller`,\n dependentProperties: ['selectedElement', 'controllerInstance'],\n };\n}\n","import type { IAddGlobalsToOperationData } from \"@operation/add-globals-to-operation.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function addGlobalsToOperation(): IOperationMetadata<IAddGlobalsToOperationData> {\n return {\n description: `This operation adds the specified global property names to the current operation data.\nIt finally removes the \\`globalProperties\\` property from the current operation data.\n\nPlain data is copied, so changing it does not change the global store. jQuery objects, DOM\nnodes, functions and class instances (such as controllers) are added by reference.`,\n category: `Data`,\n properties: {\n globalProperties: {\n type: 'ParameterType:array',\n itemType: 'ParameterType:string',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IAnimateWithClassOperationData } from \"@operation/animate-with-class.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function animateWithClass(): IOperationMetadata<IAnimateWithClassOperationData> {\n return {\n description: `This operation adds the specified class name to the specified selected element and assumes that this\nclass triggers an animation on the selected element. It then waits for this animation to complete\nbefore it resolves.\n\nThe class must put the animation on the selected element itself: \\`animationend\\` events that bubble up\nfrom descendants are ignored, and with several selected elements the operation waits for all of them.\nSet \\`includeDescendants\\` to true for a class that only animates descendants; the operation then resolves\non the first \\`animationend\\` from the element or its subtree.\n\nThe operation resolves immediately when the selection is empty, or when the class gives none of the\nselected elements a CSS animation (for example under \\`prefers-reduced-motion: reduce\\`). When an\n\\`animationend\\` event never arrives, for example because the element was hidden or removed while\nanimating, it resolves shortly after the longest computed animation should have ended. An infinite\nanimation is waited for until it is ended by an \\`animationend\\` event.`,\n category: `Animation`,\n dependentProperties: ['selectedElement'],\n properties: {\n className: {\n type: 'ParameterType:className',\n required: true,\n erased: true\n },\n removeClass: {\n type: 'ParameterType:boolean',\n erased: true\n },\n includeDescendants: {\n type: 'ParameterType:boolean',\n erased: true\n }\n },\n };\n}\n","import type { IAnimateOperationData } from \"@operation/animate.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function animate(): IOperationMetadata<IAnimateOperationData> {\n return {\n description: `This operation animates the specified selected element with the given [jQuery animation](https://api.jquery.com/animate/) properties, duration and easing.\nIt resolves after the animation completes, or immediately when the selected element set is empty.`,\n category: `Animation`,\n dependentProperties: ['selectedElement'],\n properties: {\n animationEasing: {\n type: 'ParameterType:string',\n erased: true\n },\n animationProperties: {\n type: 'ParameterType:object',\n required: true,\n erased: true\n },\n animationDuration: {\n type: 'ParameterType:number',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IAnnounceToScreenReaderOperationData } from \"@operation/announce-to-screen-reader.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function announceToScreenReader(): IOperationMetadata<IAnnounceToScreenReaderOperationData> {\n return {\n description: `Announces a message to screen readers using an ARIA live region.\n\nThe live region (\\`#aria-live-region\\`) is created empty on first use. The region is emptied\nand the message is written 100 milliseconds later, so that a new region\nand a message repeated verbatim are both announced. The message is removed again after 5 seconds.\nA newer announcement replaces a pending one.\n\nThe operation returns at once and does not wait for the message to be written.`,\n category: `Accessibility`,\n properties: {\n message: {\n type: 'ParameterType:string',\n required: true,\n erased: true\n },\n priority: {\n type: [\n { value: 'polite' },\n { value: 'assertive' }\n ],\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { TOperationData } from \"@operation/types.ts\";\n\nexport function breakForEach(): IOperationMetadata<TOperationData> {\n return {\n description: `This operation should only be used within a loop, so between a {@link forEach} and {@link endForEach}\noperation. This operation immediately moves to the loop end index, effectively stopping the loop.\n\nIt can be placed inside a \\`when\\`/\\`otherwise\\`/\\`endWhen\\` block within the loop, to break conditionally.`,\n category: `Control Flow`,\n };\n}\n","import type { IBroadcastEventOperationData } from \"@operation/broadcast-event.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function broadcastEvent(): IOperationMetadata<IBroadcastEventOperationData> {\n return {\n description: `This operation broadcasts the given event through the eventbus, along with the\nevent arguments and optional event topic.`,\n category: `Utility`,\n properties: {\n eventArgs: {\n type: 'ParameterType:array',\n required: true,\n erased: true\n },\n eventTopic: {\n type: 'ParameterType:eventTopic',\n erased: true\n },\n eventName: {\n type: 'ParameterType:eventName',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { ICalcOperationData } from \"@operation/calc.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function calc(): IOperationMetadata<ICalcOperationData> {\n return {\n description: `This operation calculates the given left and right hand operands using the specified operator.\n\n\\`left\\`, \\`right\\` and \\`operator\\` may be property chains (\\`$operationdata.\\`, \\`$globaldata.\\`,\n\\`$scope.\\`). Only these three inputs are resolved; the rest of the operation data is left as\nit is.`,\n category: `Utility`,\n properties: {\n left: {\n type: 'ParameterType:number',\n required: true,\n erased: true\n },\n right: {\n type: 'ParameterType:number',\n required: true,\n erased: true\n },\n operator: {\n type: [\n { value: '+' },\n { value: '-' },\n { value: '*' },\n { value: '/' },\n { value: '%' },\n { value: '**' }\n ],\n required: true,\n erased: true\n }\n },\n outputProperties: {\n calculationResult: {\n type: 'ParameterType:number'\n }\n }\n };\n}\n","import type { IClearElementOperationData } from \"@operation/clear-element.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function clearElement(): IOperationMetadata<IClearElementOperationData> {\n return {\n description: `This operation removes all of the children from the given selected element.\n\nControllers attached to the removed children or their descendants (by \\`addControllerToElement\\`)\nare detached first. Controllers on the selected element itself stay attached.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n };\n}\n","import type { IClearOperationDataOperationData } from \"@operation/clear-operation-data.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function clearOperationData(): IOperationMetadata<IClearOperationDataOperationData> {\n return {\n description: `This operation removes all of the properties on the current operation date.\nOr, if the \\`properties\\` property is set only removes the properties defined by that list.`,\n category: `Data`,\n properties: {\n properties: {\n type: 'ParameterType:array',\n itemType: 'ParameterType:string',\n erased: true\n }\n },\n };\n}\n","import type { IClearStorageOperationData } from \"@operation/clear-storage.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function clearStorage(): IOperationMetadata<IClearStorageOperationData> {\n return {\n description: `Clears data from browser storage (localStorage or sessionStorage).\n\nIf \\`key\\` is provided, removes only that key. If \\`key\\` is omitted, clears all storage.\nA \\`key\\` that is present but empty, blank or not a string is rejected, so a value resolved\nfrom missing data never wipes the whole storage.`,\n category: `Data`,\n properties: {\n key: {\n type: 'ParameterType:string',\n erased: true\n },\n storageType: {\n type: [\n { value: 'local' },\n { value: 'session' }\n ],\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { ICompareDateOperationData } from \"@operation/compare-date.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function compareDate(): IOperationMetadata<ICompareDateOperationData> {\n return {\n description: `Compares two dates.\ncomparison: -1 (before), 0 (equal), 1 (after)`,\n category: `Date`,\n properties: {\n date1: {\n type: 'ParameterType:string|ParameterType:number|ParameterType:Date',\n required: true,\n erased: true\n },\n date2: {\n type: 'ParameterType:string|ParameterType:number|ParameterType:Date',\n required: true,\n erased: true\n }\n },\n outputProperties: {\n comparison: {\n type: 'ParameterType:number'\n },\n isEqual: {\n type: 'ParameterType:boolean'\n },\n isBefore: {\n type: 'ParameterType:boolean'\n },\n isAfter: {\n type: 'ParameterType:boolean'\n }\n }\n };\n}\n","import type { IConcatenateStringsOperationData } from \"@operation/concatenate-strings.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function concatenateStrings(): IOperationMetadata<IConcatenateStringsOperationData> {\n return {\n description: `Concatenates multiple strings with an optional separator.`,\n category: `String`,\n properties: {\n strings: {\n type: 'ParameterType:array',\n itemType: 'ParameterType:string',\n required: true,\n erased: true\n },\n separator: {\n type: 'ParameterType:string',\n erased: true\n }\n },\n outputProperties: {\n result: {\n type: 'ParameterType:string'\n }\n }\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { TOperationData } from \"@operation/types.ts\";\n\nexport function continueForEach(): IOperationMetadata<TOperationData> {\n return {\n description: `This operation should only be used within a loop, so between a {@link forEach} and {@link endForEach}\noperation. This operation immediately moves to the next loop index, effectively canceling the rest\nof the operations in the current iteration.\n\nIt can be placed inside a \\`when\\`/\\`otherwise\\`/\\`endWhen\\` block within the loop, to continue conditionally.`,\n category: `Control Flow`,\n };\n}\n","import type { ICreateElementOperationData, TTagNames } from \"@operation/create-element.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function createElement(): IOperationMetadata<ICreateElementOperationData<TTagNames>> {\n return {\n description: `This operation creates the DOM element described by the given elementName and attributes and assigns\nthe instance to the \\`template\\` property on the current operation data.\n\nThe element is built with DOM APIs: attribute values are set with \\`.attr()\\` and \\`text\\` is set as\ntext content, so neither is parsed as HTML.\n\nValues may be resolved from user data, so nothing that runs script is created: \\`script\\`\nelements, event handler (\\`on*\\`) and \\`srcdoc\\` attributes, and \\`javascript:\\` or \\`vbscript:\\`\nURLs in URL attributes such as \\`href\\`, \\`src\\` and \\`formaction\\` are refused.`,\n category: `DOM`,\n properties: {\n elementName: {\n type: 'ParameterType:htmlElementName',\n required: true,\n erased: true\n },\n text: {\n type: 'ParameterType:string',\n erased: true\n },\n attributes: {\n type: 'ParameterType:object',\n erased: true\n }\n },\n outputProperties: {\n template: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { ICustomFunctionOperationData } from \"@operation/custom-function.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function customFunction(): IOperationMetadata<ICustomFunctionOperationData> {\n return {\n description: `This operation retrieves a custom function defined by the given system name\nand invokes it with the current operation data and eventbus.\n\nThe function is looked up with \\`this.services.getImport\\`, which answers from\nthe engine's resource importer. Register the function\nwith the \\`EligiusResourceImporter\\` constructor:\n\\`new EligiusResourceImporter({functions: {myFunction}})\\`.\n\nThe function is called with the current operation data as its argument, and with \\`this\\`\nset to a view of the operation scope. Reading a property from \\`this\\` returns it from the\ninnermost scope that has it, so inside a \\`when\\` block in a loop \\`this.currentItem\\`,\n\\`this.loopIndex\\` and \\`this.variables\\` return the loop's and the action's values, the same\nas \\`$scope.\\` chains. Assigning to \\`this\\` (for example \\`this.newIndex\\`) writes to the scope the\noperation runs in.`,\n category: `Utility`,\n properties: {\n systemName: {\n type: 'ParameterType:systemName',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IEndActionOperationData } from \"@operation/end-action.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function endAction(): IOperationMetadata<IEndActionOperationData> {\n return {\n description: `This operation invokes the {@link EndableAction}.end method on the specified action instance.\n\nThe action receives its own copy of the current operation data merged with the action\noperation data. Whatever the action's end operations add, change or remove in that copy stays\nwith the action: once it has completed, this operation continues with the operation data it\nhad before, without the \\`actionOperationData\\` property.`,\n category: `Action`,\n dependentProperties: ['actionInstance'],\n properties: {\n actionOperationData: {\n type: 'ParameterType:object',\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { TOperationData } from \"@operation/types.ts\";\n\nexport function endForEach(): IOperationMetadata<TOperationData> {\n return {\n description: `This operation checks if the current loop should end or start the next iteration.`,\n category: `Control Flow`,\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { TOperationData } from \"@operation/types.ts\";\n\nexport function endWhen(): IOperationMetadata<TOperationData> {\n return {\n description: `This operation cleans up after the {@link when}/{@link otherwise}/{@link endWhen} control flow ends.`,\n category: `Control Flow`,\n };\n}\n","import type { IExtendControllerOperationData } from \"@operation/extend-controller.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function extendController(): IOperationMetadata<IExtendControllerOperationData> {\n return {\n description: `Extends the current controller with given extension.\n\nThe extension's own properties are copied onto the controller instance.`,\n category: `Controller`,\n dependentProperties: ['controllerInstance'],\n properties: {\n controllerExtension: {\n type: 'ParameterType:object',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IFilterArrayOperationData } from \"@operation/filter-array.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function filterArray(): IOperationMetadata<IFilterArrayOperationData> {\n return {\n description: `Filters an array based on property equality or custom predicate function.\n\nOperates on arrayData passed from previous operations.\nSupports two filtering modes:\n1. Property equality: \\`filterProperty\\` and \\`filterValue\\` to filter by property match\n2. Custom predicate: \\`filterPredicate\\` function for complex filtering logic`,\n category: `Array`,\n dependentProperties: ['arrayData'],\n properties: {\n filterProperty: {\n type: 'ParameterType:string',\n erased: true\n },\n filterValue: {\n type: 'ParameterType:object',\n erased: true\n },\n filterPredicate: {\n type: 'ParameterType:function',\n erased: true\n }\n },\n outputProperties: {\n filteredArray: {\n type: 'ParameterType:array'\n }\n }\n };\n}\n","import type { IFindInArrayOperationData } from \"@operation/find-in-array.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function findInArray(): IOperationMetadata<IFindInArrayOperationData> {\n return {\n description: `Finds the first element in an array matching criteria.\n\nOperates on arrayData passed from previous operations.\nSupports two search modes:\n1. Property equality: \\`findProperty\\` and \\`findValue\\` to find by property match\n2. Custom predicate: \\`findPredicate\\` function for complex search logic\n\nReturns \\`undefined\\` for \\`foundItem\\` and \\`-1\\` for \\`foundIndex\\` if no match found.`,\n category: `Array`,\n dependentProperties: ['arrayData'],\n properties: {\n findProperty: {\n type: 'ParameterType:string',\n erased: true\n },\n findValue: {\n type: 'ParameterType:object',\n erased: true\n },\n findPredicate: {\n type: 'ParameterType:function',\n erased: true\n }\n },\n outputProperties: {\n foundItem: {\n type: 'ParameterType:object'\n },\n foundIndex: {\n type: 'ParameterType:number'\n }\n }\n };\n}\n","import type { IForEachOperationData } from \"@operation/for-each.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function forEach(): IOperationMetadata<IForEachOperationData> {\n return {\n description: `This operation iterates over the given collection.\n\nEach iteration the current item from the specified collection is\nassigned to the {@link IOperationScope.currentItem |currentItem} property on the {@link IOperationScope |operation scope}.\n\nAt the start of the loop, the associated {@link endForEach} operation is determined and when\nthe last iteration is completed the flow control is set to the index of that operation.\n\nThe {@link continueForEach |continue} and {@link breakForEach |break} operations can be used to control the\nloop iterations.\n\nThe collection is resolved once, when the loop starts, and the loop iterates over a snapshot\nof it. Changing, replacing or removing the source collection inside the loop body does not\nchange the items or the number of iterations of the running loop.`,\n category: `Control Flow`,\n properties: {\n collection: {\n type: 'ParameterType:array|ParameterType:string',\n required: true\n }\n },\n };\n}\n","import type { IFormatDateOperationData } from \"@operation/format-date.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function formatDate(): IOperationMetadata<IFormatDateOperationData> {\n return {\n description: `Formats a date with a simple token pattern, in the local time zone.\n\nSupported tokens (every occurrence is replaced, other characters are kept as is):\n- \\`YYYY\\`: four digit year\n- \\`MM\\`: month, 01-12\n- \\`DD\\`: day of the month, 01-31\n- \\`HH\\`: hours, 00-23\n- \\`mm\\`: minutes, 00-59\n- \\`ss\\`: seconds, 00-59`,\n category: `Date`,\n dependentProperties: ['date'],\n properties: {\n format: {\n type: 'ParameterType:string',\n required: true,\n erased: true\n }\n },\n outputProperties: {\n formattedDate: {\n type: 'ParameterType:string'\n }\n }\n };\n}\n","import type { IFormatTextOperationData } from \"@operation/format-text.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function formatText(): IOperationMetadata<IFormatTextOperationData> {\n return {\n description: `Transforms text using format operations: uppercase, lowercase, capitalize, titlecase, or trim.\n\nOperates on textContent passed from previous operations (e.g., getTextContent).\n\nTransformations:\n- \\`uppercase\\`: Convert all characters to uppercase\n- \\`lowercase\\`: Convert all characters to lowercase\n- \\`capitalize\\`: Capitalize only the first letter\n- \\`titlecase\\`: Capitalize first letter of each word\n- \\`trim\\`: Remove leading and trailing whitespace`,\n category: `Text`,\n dependentProperties: ['textContent'],\n properties: {\n transformation: {\n type: [\n { value: 'uppercase' },\n { value: 'lowercase' },\n { value: 'capitalize' },\n { value: 'titlecase' },\n { value: 'trim' }\n ],\n required: true,\n erased: true\n }\n },\n outputProperties: {\n formattedText: {\n type: 'ParameterType:string'\n }\n }\n };\n}\n","import type { IGetAttributesFromElementOperationData } from \"@operation/get-attributes-from-element.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function getAttributesFromElement(): IOperationMetadata<IGetAttributesFromElementOperationData> {\n return {\n description: `This operation retrieves the values for the specified attribute names from the given selected element.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n properties: {\n attributeNames: {\n type: 'ParameterType:array',\n itemType: 'ParameterType:string',\n required: true,\n erased: true\n }\n },\n outputProperties: {\n attributeValues: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { IGetControllerFromElementOperationData } from \"@operation/get-controller-from-element.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function getControllerFromElement(): IOperationMetadata<IGetControllerFromElementOperationData> {\n return {\n description: `This operation retrieves the controller instance with the specified name that is assigned to the given selected element.`,\n category: `Controller`,\n dependentProperties: ['selectedElement'],\n properties: {\n controllerName: {\n type: 'ParameterType:controllerName',\n required: true,\n erased: true\n }\n },\n outputProperties: {\n controllerInstance: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { IGetControllerInstanceOperationData } from \"@operation/get-controller-instance.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function getControllerInstance(): IOperationMetadata<IGetControllerInstanceOperationData> {\n return {\n description: `This operation retrieves an instance of the given controller name.\nIt assigns this instance to the \\`controllerInstance\\` property on the current operation data`,\n category: `Controller`,\n properties: {\n systemName: {\n type: 'ParameterType:controllerName',\n required: true,\n erased: true\n }\n },\n outputProperties: {\n controllerInstance: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { IGetCurrentTimeOperationData } from \"@operation/get-current-time.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function getCurrentTime(): IOperationMetadata<IGetCurrentTimeOperationData> {\n return {\n description: `Gets the current time as timestamp and Date object.`,\n category: `Date`,\n outputProperties: {\n timestamp: {\n type: 'ParameterType:number'\n },\n date: {\n type: 'ParameterType:Date'\n }\n }\n };\n}\n","import type { IGetElementDimensionsOperationData } from \"@operation/get-element-dimensions.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function getElementDimensions(): IOperationMetadata<IGetElementDimensionsOperationData> {\n return {\n description: `This operation calculates the width and height of the given selected element.\nIt assigns this struct to the dimensions property on the current operation data.\nOptionally the width and height can be modified using the given modifier string.\n\nThe modifier string is formatted in the following way:\n\n<operator><amount><optional-side><optional-precentage>|<ratio-definition>\n\nWhere the ratio modifier is formatted in the following way:\n<side>[ar=<ratio-left>-<ratio-right>]\n\nFor example, this modifier '+100h|w[ar=8-1]' will modifiy the dimensions like this:\nit will add a value of 100 to the height and modify the width by a ratio of 8 to 1 relative to the height.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n properties: {\n modifier: {\n type: 'ParameterType:dimensionsModifier',\n erased: true\n }\n },\n outputProperties: {\n dimensions: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { IGetFocusedElementOperationData } from \"@operation/get-focused-element.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function getFocusedElement(): IOperationMetadata<IGetFocusedElementOperationData> {\n return {\n description: `Gets the currently focused element.`,\n category: `Focus`,\n outputProperties: {\n focusedElement: {\n type: 'ParameterType:jQuery'\n }\n }\n };\n}\n","import type { IGetFormDataOperationData } from \"@operation/get-form-data.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function getFormData(): IOperationMetadata<IGetFormDataOperationData> {\n return {\n description: `Extracts all input, select, and textarea values from form element into operation data.\n\nThis operation reads form field values and returns them as an object with field names as keys.\nOnly processes form elements that are enabled and not hidden. Handles checkboxes, radio buttons,\nselect elements, textareas, and text inputs.`,\n category: `Form`,\n dependentProperties: ['selectedElement'],\n outputProperties: {\n formData: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { IGetImportOperationData } from \"@operation/get-import.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function getImport(): IOperationMetadata<IGetImportOperationData> {\n return {\n description: `This operation retrieves the import specified by the given \\`systemName\\` and\nassigns it to the \\`importedInstance\\` property on the current operaton date.\n\nThe import is looked up with \\`this.services.getImport\\`, which answers from\nthe engine's resource importer. Functions, templates\nand JSON registered with the \\`EligiusResourceImporter\\` constructor\n(\\`new EligiusResourceImporter({json: {settings}})\\`) can be imported this\nway, as can every built-in operation, controller and provider export.`,\n category: `Utility`,\n properties: {\n systemName: {\n type: 'ParameterType:systemName',\n required: true,\n erased: true\n }\n },\n outputProperties: {\n importedInstance: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { IGetQueryParamsOperationData } from \"@operation/get-query-params.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function getQueryParams(): IOperationMetadata<IGetQueryParamsOperationData> {\n return {\n description: `This operation retrieves the current query parameters from the browser's address bar and places\nthem on the returned operation data.`,\n category: `Utility`,\n properties: {\n defaultValues: {\n type: 'ParameterType:object',\n erased: true\n }\n },\n outputProperties: {\n queryParams: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { IGetScrollPositionOperationData } from \"@operation/get-scroll-position.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function getScrollPosition(): IOperationMetadata<IGetScrollPositionOperationData> {\n return {\n description: `Gets the current scroll position of the viewport.\n\nReturns x (horizontal) and y (vertical) scroll positions in pixels.\nUses cross-browser compatible methods to retrieve scroll position.`,\n category: `Scroll`,\n outputProperties: {\n scrollX: {\n type: 'ParameterType:number'\n },\n scrollY: {\n type: 'ParameterType:number'\n }\n }\n };\n}\n","import type { IGetTextContentOperationData } from \"@operation/get-text-content.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function getTextContent(): IOperationMetadata<IGetTextContentOperationData> {\n return {\n description: `Extracts text content from element, stripping all HTML markup.\n\nUses jQuery's \\`.text()\\` method which is XSS-safe and returns only the text content\nwithout any HTML tags. Preserves whitespace and text from nested elements.`,\n category: `Text`,\n dependentProperties: ['selectedElement'],\n outputProperties: {\n textContent: {\n type: 'ParameterType:string'\n }\n }\n };\n}\n","import type { IHttpDeleteOperationData } from \"@operation/http-delete.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function httpDelete(): IOperationMetadata<IHttpDeleteOperationData> {\n return {\n description: `Performs an HTTP DELETE request to the specified URL.`,\n category: `HTTP`,\n properties: {\n url: {\n type: 'ParameterType:string',\n required: true,\n erased: true\n },\n headers: {\n type: 'ParameterType:object',\n erased: true\n }\n },\n outputProperties: {\n response: {\n type: 'ParameterType:object'\n },\n status: {\n type: 'ParameterType:number'\n }\n }\n };\n}\n","import type { IHttpPostOperationData } from \"@operation/http-post.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function httpPost(): IOperationMetadata<IHttpPostOperationData> {\n return {\n description: `Performs an HTTP POST request to the specified URL.\n\nThe body is sent as JSON with \\`Content-Type: application/json\\`, unless the caller's headers set\nanother content type (header names are case-insensitive). With a non-JSON content type, a string\nbody is sent as is; other bodies are still JSON encoded.`,\n category: `HTTP`,\n properties: {\n url: {\n type: 'ParameterType:string',\n required: true,\n erased: true\n },\n body: {\n type: 'ParameterType:object',\n erased: true\n },\n headers: {\n type: 'ParameterType:object',\n erased: true\n }\n },\n outputProperties: {\n response: {\n type: 'ParameterType:object'\n },\n status: {\n type: 'ParameterType:number'\n }\n }\n };\n}\n","import type { IHttpPutOperationData } from \"@operation/http-put.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function httpPut(): IOperationMetadata<IHttpPutOperationData> {\n return {\n description: `Performs an HTTP PUT request to the specified URL.\n\nThe body is sent as JSON with \\`Content-Type: application/json\\`, unless the caller's headers set\nanother content type (header names are case-insensitive). With a non-JSON content type, a string\nbody is sent as is; other bodies are still JSON encoded.`,\n category: `HTTP`,\n properties: {\n url: {\n type: 'ParameterType:string',\n required: true,\n erased: true\n },\n body: {\n type: 'ParameterType:object',\n erased: true\n },\n headers: {\n type: 'ParameterType:object',\n erased: true\n }\n },\n outputProperties: {\n response: {\n type: 'ParameterType:object'\n },\n status: {\n type: 'ParameterType:number'\n }\n }\n };\n}\n","import type { IInvokeObjectMethodOperationData } from \"@operation/invoke-object-method.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function invokeObjectMethod(): IOperationMetadata<IInvokeObjectMethodOperationData> {\n return {\n description: `This operation invokes the specified method on the given object with the given optional arguments\nand assigns the result to the \\`methodResult\\` operationdata property. When the method returns a\npromise, the operation waits for it and assigns the resolved value.\n\nThe operation only calls application code: methods of controllers, of other instances of\napplication classes, and of plain objects. It refuses, and throws for:\n- an \\`instance\\` that is a function, the global object (\\`window\\`), a document, a DOM node,\n a jQuery object, or any other built-in or host object (arrays, maps, promises, \\`location\\`,\n storage, ...);\n- a method that is a built-in (native) function, such as \\`eval\\`, \\`Function\\`, \\`setTimeout\\`,\n \\`setInterval\\`, \\`document.write\\`, \\`Reflect.apply\\` or a bound function, or a jQuery function;\n- the method names \\`constructor\\`, \\`__proto__\\` and \\`prototype\\`;\n- arguments that are such functions.\n\nThese checks stop configuration from reaching the platform's code-executing functions through\nthis operation. They cannot vouch for what an application method does with its arguments, so\nonly expose methods that are safe to call with configured data.`,\n category: `Utility`,\n dependentProperties: ['instance'],\n properties: {\n methodName: {\n type: 'ParameterType:string',\n required: true,\n erased: true\n },\n methodArguments: {\n type: 'ParameterType:array',\n erased: true\n }\n },\n outputProperties: {\n methodResult: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { IIsElementInViewportOperationData } from \"@operation/is-element-in-viewport.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function isElementInViewport(): IOperationMetadata<IIsElementInViewportOperationData> {\n return {\n description: `Checks if an element is currently visible within the viewport.\n\nUses \\`getBoundingClientRect()\\` to determine if the element is within the viewport boundaries.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n outputProperties: {\n isInViewport: {\n type: 'ParameterType:boolean'\n }\n }\n };\n}\n","import type { ILoadFromStorageOperationData } from \"@operation/load-from-storage.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function loadFromStorage(): IOperationMetadata<ILoadFromStorageOperationData> {\n return {\n description: `Loads data from browser storage (localStorage or sessionStorage).\n\nDeserializes the stored JSON value. Returns \\`null\\` if key doesn't exist.\nWhen \\`storageType\\` is omitted, localStorage is used.`,\n category: `Data`,\n properties: {\n key: {\n type: 'ParameterType:string',\n required: true,\n erased: true\n },\n storageType: {\n type: [\n { value: 'local' },\n { value: 'session' }\n ],\n required: true,\n erased: true\n }\n },\n outputProperties: {\n loadedValue: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { ILoadJSONOperationData } from \"@operation/load-json.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function loadJson(): IOperationMetadata<ILoadJSONOperationData> {\n return {\n description: `This operation loads a JSON file from the specified url and assigns it to the json\nproperty on the current operation data.\n\nIf the cache property is set to true and a cached value already exists, a copy of it is assigned\ninstead of re-retrieving it from the url. Mutating the returned json never changes the cache.\n\nThe cache is shared by every engine. It is emptied when the last live engine created by\n\\`EngineFactory\\` is destroyed; call {@link clearJsonCache} to empty it earlier.`,\n category: `Utility`,\n properties: {\n url: {\n type: 'ParameterType:string',\n required: true,\n erased: true\n },\n cache: {\n type: 'ParameterType:boolean',\n erased: true\n }\n },\n outputProperties: {\n json: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { ILogOperationData } from \"@operation/log.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function log(): IOperationMetadata<ILogOperationData> {\n return {\n description: `This operation logs the specified value, or, when no logValue property has been assigned\nit will log the current operation data, global data and scope to the console`,\n category: `Utility`,\n properties: {\n logValue: {\n type: 'ParameterType:object|ParameterType:string|ParameterType:number|ParameterType:boolean|ParameterType:array',\n erased: true\n },\n logName: {\n type: 'ParameterType:string',\n erased: true\n }\n },\n };\n}\n","import type { IMapArrayOperationData } from \"@operation/map-array.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function mapArray(): IOperationMetadata<IMapArrayOperationData> {\n return {\n description: `Transforms each element of an array using a mapping function.\n\nOperates on arrayData passed from previous operations.\nThe mapFunction receives each item and optionally its index.`,\n category: `Array`,\n dependentProperties: ['arrayData'],\n properties: {\n mapFunction: {\n type: 'ParameterType:function',\n required: true,\n erased: true\n }\n },\n outputProperties: {\n mappedArray: {\n type: 'ParameterType:array'\n }\n }\n };\n}\n","import type { IMathOperationData } from \"@operation/math.ts\";\nimport type { IOperationMetadata } from \"@operation/metadata/types.ts\";\n\nexport function math(): IOperationMetadata<IMathOperationData> {\n return {\n description: `This operation performs the given math function with the specified arguments.\n\n\\`args\\` and \\`functionName\\` may contain property chains (\\`$operationdata.\\`, \\`$globaldata.\\`,\n\\`$scope.\\`). Only these two inputs are resolved; the rest of the operation data is left as it\nis. Arguments that name a Math constant (such as \\`'PI'\\`) are replaced by its value.`,\n category: `Utility`,\n properties: {\n args: {\n type: 'ParameterType:array',\n required: true,\n erased: true\n },\n functionName: {\n type: 'ParameterType:mathfunction',\n required: true,\n erased: true\n }\n },\n outputProperties: {\n mathResult: {\n type: 'ParameterType:number'\n }\n }\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { TOperationData } from \"@operation/types.ts\";\n\nexport function otherwise(): IOperationMetadata<TOperationData> {\n return {\n description: `If the preceeding {@link when} operation evaluates to \\`true\\` subsequent operations will\nbe skipped until an {@link endWhen} operation is encountered.`,\n category: `Control Flow`,\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IRemoveClassOperationData } from \"@operation/remove-class.ts\";\n\nexport function removeClass(): IOperationMetadata<IRemoveClassOperationData> {\n return {\n description: `This operation removes the spcified class name from the given selected element.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n properties: {\n className: {\n type: 'ParameterType:className',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IRemoveControllerFromElementOperationData } from \"@operation/remove-controller-from-element.ts\";\n\nexport function removeControllerFromElement(): IOperationMetadata<IRemoveControllerFromElementOperationData> {\n return {\n description: `This operation removes the controller with the specified name from the given selected element.`,\n category: `Controller`,\n dependentProperties: ['selectedElement'],\n properties: {\n controllerName: {\n type: 'ParameterType:controllerName',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IRemoveElementOperationData } from \"@operation/remove-element.ts\";\n\nexport function removeElement(): IOperationMetadata<IRemoveElementOperationData> {\n return {\n description: `This operation removes the given selected element from the DOM.\n\nControllers attached to the element or its descendants (by \\`addControllerToElement\\`) are\ndetached first, so their eventbus and window listeners do not outlive the element.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IRemovePropertiesFromOperationDataOperationData } from \"@operation/remove-properties-from-operation-data.ts\";\n\nexport function removePropertiesFromOperationData(): IOperationMetadata<IRemovePropertiesFromOperationDataOperationData> {\n return {\n description: `This operation removes the given list of properties from the current operation data.\nIt will also remove the property \\`propertyNames\\` from the result.`,\n category: `Data`,\n properties: {\n propertyNames: {\n type: 'ParameterType:array',\n itemType: 'ParameterType:string',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IReparentElementOperationData } from \"@operation/reparent-element.ts\";\n\nexport function reparentElement(): IOperationMetadata<IReparentElementOperationData> {\n return {\n description: `This operation moves the given selected element to the new parent that is defined\nby the specified \\`newParentSelector\\`. jQuery data, event handlers and attached controllers\nare preserved.\n\nThe selector is resolved inside the engine root (the root itself included), the same way\n\\`selectElement\\` resolves its selector, and must match exactly one element. HTML strings are\nnot accepted.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n properties: {\n newParentSelector: {\n type: 'ParameterType:selector',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IReplaceStringOperationData } from \"@operation/replace-string.ts\";\n\nexport function replaceString(): IOperationMetadata<IReplaceStringOperationData> {\n return {\n description: `Replaces occurrences of a pattern in a string (alias for replaceText for string context).\n\nLike replaceText, a string pattern replaces every occurrence and inserts the replacement\nliterally (\\`$&\\`, \\`$1\\` and similar are not expanded). A RegExp pattern follows\n\\`String.prototype.replace\\`: only a global RegExp replaces every match, and \\`$\\` patterns\nin the replacement are expanded. Unlike replaceText, the result is written to \\`result\\`\nand \\`textContent\\` is left unchanged.`,\n category: `String`,\n dependentProperties: ['textContent'],\n properties: {\n pattern: {\n type: 'ParameterType:string|ParameterType:RegExp',\n required: true,\n erased: true\n },\n replacement: {\n type: 'ParameterType:string',\n required: true,\n erased: true\n }\n },\n outputProperties: {\n result: {\n type: 'ParameterType:string'\n }\n }\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IReplaceTextOperationData } from \"@operation/replace-text.ts\";\n\nexport function replaceText(): IOperationMetadata<IReplaceTextOperationData> {\n return {\n description: `Finds and replaces text using literal string or regex pattern.\n\nOperates on textContent passed from previous operations (e.g., getTextContent).\nSupports regex patterns with global flag for multiple replacements.\nUpdates textContent with replaced text and sets replacementCount.\n\nA string pattern replaces every occurrence and inserts the replacement literally.`,\n category: `Text`,\n dependentProperties: ['textContent'],\n properties: {\n searchPattern: {\n type: 'ParameterType:string|ParameterType:RegExp',\n required: true,\n erased: true\n },\n replacement: {\n type: 'ParameterType:string',\n required: true,\n erased: true\n }\n },\n outputProperties: {\n replacementCount: {\n type: 'ParameterType:number'\n }\n }\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IRequestActionOperationData } from \"@operation/request-action.ts\";\n\nexport function requestAction(): IOperationMetadata<IRequestActionOperationData> {\n return {\n description: `This operation requests an action instance with the specified name and assigns it\nto the \\`actionInstance\\` property on the current operation data.`,\n category: `Action`,\n properties: {\n systemName: {\n type: 'ParameterType:actionName',\n required: true,\n erased: true\n }\n },\n outputProperties: {\n actionInstance: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISaveToStorageOperationData } from \"@operation/save-to-storage.ts\";\n\nexport function saveToStorage(): IOperationMetadata<ISaveToStorageOperationData> {\n return {\n description: `Saves data to browser storage (localStorage or sessionStorage).\n\nSerializes the value as JSON before storing. Supports any JSON-serializable data type.\nUse \\`null\\` to store an empty value; \\`undefined\\` cannot be stored as JSON and is rejected.\nWhen \\`storageType\\` is omitted, localStorage is used.`,\n category: `Data`,\n properties: {\n key: {\n type: 'ParameterType:string',\n required: true,\n erased: true\n },\n value: {\n type: 'ParameterType:object',\n required: true,\n erased: true\n },\n storageType: {\n type: [\n { value: 'local' },\n { value: 'session' }\n ],\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IScrollToElementOperationData } from \"@operation/scroll-to-element.ts\";\n\nexport function scrollToElement(): IOperationMetadata<IScrollToElementOperationData> {\n return {\n description: `Scrolls the viewport to bring the selected element into view.\n\nUses the browser's \\`scrollIntoView\\` API with configurable behavior.`,\n category: `Scroll`,\n dependentProperties: ['selectedElement'],\n properties: {\n behavior: {\n type: [\n { value: 'auto' },\n { value: 'smooth' }\n ],\n erased: true\n },\n block: {\n type: [\n { value: 'start' },\n { value: 'center' },\n { value: 'end' },\n { value: 'nearest' }\n ],\n erased: true\n },\n inline: {\n type: [\n { value: 'start' },\n { value: 'center' },\n { value: 'end' },\n { value: 'nearest' }\n ],\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IScrollToPositionOperationData } from \"@operation/scroll-to-position.ts\";\n\nexport function scrollToPosition(): IOperationMetadata<IScrollToPositionOperationData> {\n return {\n description: `Scrolls the viewport to a specific x,y coordinate position.\n\nUses the browser's \\`window.scrollTo\\` API with configurable behavior.`,\n category: `Scroll`,\n properties: {\n x: {\n type: 'ParameterType:number',\n required: true,\n erased: true\n },\n y: {\n type: 'ParameterType:number',\n required: true,\n erased: true\n },\n behavior: {\n type: [\n { value: 'auto' },\n { value: 'smooth' }\n ],\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISelectElementOperationData } from \"@operation/select-element.ts\";\n\nexport function selectElement(): IOperationMetadata<ISelectElementOperationData> {\n return {\n description: `This operation selects one or more elements using the specified selector.\n\nIf \\`useSelectedElementAsRoot\\` is set to true and a valid DOM element is assigned\nto the current operation data's \\`selectedElement\\` property\nthen the element will be looked for only in the descendant elements of this DOM element.`,\n category: `DOM`,\n properties: {\n selector: {\n type: 'ParameterType:selector',\n required: true,\n erased: true\n },\n useSelectedElementAsRoot: {\n type: 'ParameterType:boolean',\n erased: true\n }\n },\n outputProperties: {\n selectedElement: {\n type: 'ParameterType:object'\n }\n }\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISetDataOperationData } from \"@operation/set-data.ts\";\n\nexport function setData(): IOperationMetadata<ISetDataOperationData> {\n return {\n description: `This operation assigns the specified properties to the specified data targets.`,\n category: `Data`,\n properties: {\n properties: {\n type: 'ParameterType:object',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISetElementAttributesOperationData } from \"@operation/set-element-attributes.ts\";\n\nexport function setElementAttributes(): IOperationMetadata<ISetElementAttributesOperationData> {\n return {\n description: `This operation sets the specified set of attributes on the given selected element.\n\nEvent handler (\\`on*\\`) and \\`srcdoc\\` attributes, and \\`javascript:\\` or \\`vbscript:\\` URLs in URL\nattributes such as \\`href\\`, \\`src\\` and \\`formaction\\`, are refused, the same as in \\`createElement\\`.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n properties: {\n attributes: {\n type: 'ParameterType:object',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISetElementContentOperationData } from \"@operation/set-element-content.ts\";\n\nexport function setElementContent(): IOperationMetadata<ISetElementContentOperationData> {\n return {\n description: `This operation sets the specified content defined by the value assigned to the template property\nto the given selected element.\n\nWhen the \\`insertionType\\` is set to \\`overwrite\\` the contents of the selected element are replaced\nby the given template.\nWhen set to \\`append\\` the new content will be inserted after the current content.\nWhen set to \\`prepend\\` the new content will be inserted before the current content.\n\nWith \\`overwrite\\`, controllers attached to the replaced content (by \\`addControllerToElement\\`) are\ndetached first. Controllers on the selected element itself stay attached.\n\nThe template is inserted as HTML: a string template is parsed by jQuery, which also runs the\nscripts and inline event handlers it contains. Only use string templates from the configuration\nor the resource importer; build content from user data with \\`createElement\\`, whose \\`text\\` is\nnever parsed as HTML.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n properties: {\n template: {\n type: 'ParameterType:string|ParameterType:Element|ParameterType:Text|ParameterType:Comment|ParameterType:Document|ParameterType:DocumentFragment',\n erased: true\n },\n insertionType: {\n type: [\n { value: 'overwrite' },\n { value: 'append' },\n { value: 'prepend' }\n ],\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISetFocusOperationData } from \"@operation/set-focus.ts\";\n\nexport function setFocus(): IOperationMetadata<ISetFocusOperationData> {\n return {\n description: `Sets focus to the selected element.`,\n category: `Focus`,\n dependentProperties: ['selectedElement'],\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISetFormValueOperationData } from \"@operation/set-form-value.ts\";\n\nexport function setFormValue(): IOperationMetadata<ISetFormValueOperationData> {\n return {\n description: `Sets the value of an input, select, or textarea element.\n\nHandles different input types appropriately:\n- Text inputs, textareas, selects: sets value directly\n- Checkboxes: sets checked property for boolean values\n- Radio buttons: sets checked property for boolean values\n- Number inputs: converts to string`,\n category: `Form`,\n dependentProperties: ['selectedElement'],\n properties: {\n value: {\n type: 'ParameterType:string|ParameterType:number|ParameterType:boolean',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISetGlobalDataOperationData } from \"@operation/set-global-data.ts\";\n\nexport function setGlobalData(): IOperationMetadata<ISetGlobalDataOperationData> {\n return {\n description: `This operation copies the specified properties from the operationData to the global data.\n\nPlain data is stored as a deep copy, so changing the operation data afterwards does not change\nthe global data. jQuery objects, DOM nodes, functions and class instances (such as controllers)\nare stored by reference.`,\n category: `Data`,\n properties: {\n propertyNames: {\n type: 'ParameterType:array',\n itemType: 'ParameterType:string',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISetOperationData } from \"@operation/set-operation-data.ts\";\n\nexport function setOperationData(): IOperationMetadata<ISetOperationData> {\n return {\n description: `This operation assigns the specified properties to the current operation data.\nWhen override is set to true the properties replace the current operation data entirely.`,\n category: `Data`,\n properties: {\n override: {\n type: 'ParameterType:boolean',\n erased: true\n },\n properties: {\n type: 'ParameterType:object',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISetStyleOperationData } from \"@operation/set-style.ts\";\n\nexport function setStyle(): IOperationMetadata<ISetStyleOperationData> {\n return {\n description: `This operation assigns the specified CSS style properties to the\ngiven selected element.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n properties: {\n properties: {\n type: 'ParameterType:cssProperties',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISetVariableOperationData } from \"@operation/set-variable.ts\";\n\nexport function setVariable(): IOperationMetadata<ISetVariableOperationData> {\n return {\n description: `This operation sets a variable with the specified name on the scope with the specified value.\n\nVariables belong to the action: a variable set inside a \\`when\\` or \\`forEach\\` block is the\nsame variable outside it, so it keeps its value after \\`endWhen\\` or \\`endForEach\\`, and\nvariables set before the block can be read and changed inside it. Read variables with\n\\`$scope.variables.<name>\\`.`,\n category: `Data`,\n properties: {\n name: {\n type: 'ParameterType:string',\n required: true,\n erased: true\n },\n value: {\n type: 'ParameterType:object|ParameterType:string|ParameterType:number|ParameterType:boolean|ParameterType:array',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISortArrayOperationData } from \"@operation/sort-array.ts\";\n\nexport function sortArray(): IOperationMetadata<ISortArrayOperationData> {\n return {\n description: `Sorts an array by property, natural order, or custom comparator function.\n\nOperates on arrayData passed from previous operations.\nSupports three sorting modes:\n1. Property sort: \\`sortProperty\\` and \\`sortOrder\\` to sort objects by property\n2. Natural sort: \\`sortOrder\\` alone for primitive arrays\n3. Custom comparator: \\`sortComparator\\` function for complex sorting logic`,\n category: `Array`,\n dependentProperties: ['arrayData'],\n properties: {\n sortProperty: {\n type: 'ParameterType:string',\n erased: true\n },\n sortOrder: {\n type: [\n { value: 'asc' },\n { value: 'desc' }\n ],\n erased: true\n },\n sortComparator: {\n type: 'ParameterType:function',\n erased: true\n }\n },\n outputProperties: {\n sortedArray: {\n type: 'ParameterType:array'\n }\n }\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISplitStringOperationData } from \"@operation/split-string.ts\";\n\nexport function splitString(): IOperationMetadata<ISplitStringOperationData> {\n return {\n description: `Splits a string into an array by delimiter (string or regex).`,\n category: `String`,\n dependentProperties: ['textContent'],\n properties: {\n delimiter: {\n type: 'ParameterType:string|ParameterType:RegExp',\n required: true,\n erased: true\n },\n limit: {\n type: 'ParameterType:number',\n erased: true\n }\n },\n outputProperties: {\n resultArray: {\n type: 'ParameterType:array',\n itemType: 'ParameterType:string'\n }\n }\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IStartActionOperationData } from \"@operation/start-action.ts\";\n\nexport function startAction(): IOperationMetadata<IStartActionOperationData> {\n return {\n description: `This operation starts the specified action instance using the given action operation data.\n\nThe action receives its own copy of the current operation data merged with the action\noperation data. Whatever the action's operations add, change or remove in that copy stays\nwith the action: once it has completed, this operation continues with the operation data it\nhad before, plus \\`actionInstance\\`, without the \\`actionOperationData\\` property.`,\n category: `Action`,\n dependentProperties: ['actionInstance'],\n properties: {\n actionOperationData: {\n type: 'ParameterType:object',\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { ISubstringTextOperationData } from \"@operation/substring-text.ts\";\n\nexport function substringText(): IOperationMetadata<ISubstringTextOperationData> {\n return {\n description: `Extracts a substring from text between start and end indices.`,\n category: `Text`,\n dependentProperties: ['textContent'],\n properties: {\n start: {\n type: 'ParameterType:number',\n required: true,\n erased: true\n },\n end: {\n type: 'ParameterType:number',\n erased: true\n }\n },\n outputProperties: {\n substring: {\n type: 'ParameterType:string'\n }\n }\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IToggleClassOperationData } from \"@operation/toggle-class.ts\";\n\nexport function toggleClass(): IOperationMetadata<IToggleClassOperationData> {\n return {\n description: `This operation toggles the specfied class name on the given selected element.\n\nMeaning, if the specified class name exists on the given element it will be removed,\notherwise it will be added.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n properties: {\n className: {\n type: 'ParameterType:className',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IToggleElementOperationData } from \"@operation/toggle-element.ts\";\n\nexport function toggleElement(): IOperationMetadata<IToggleElementOperationData> {\n return {\n description: `This operation toggles the visibility of the given selected element.\n\nMeaning, if the element is hidden, it will be made visible, otherwise\nit will be hidden.`,\n category: `DOM`,\n dependentProperties: ['selectedElement'],\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IToggleFormElementOperationData } from \"@operation/toggle-form-element.ts\";\n\nexport function toggleFormElement(): IOperationMetadata<IToggleFormElementOperationData> {\n return {\n description: `Enables or disables form input elements (inputs, selects, textareas, buttons).\n\nSets the \\`disabled\\` property on the element. When \\`enabled\\` is true, removes the disabled\nattribute; when false, adds the disabled attribute.`,\n category: `Form`,\n dependentProperties: ['selectedElement'],\n properties: {\n enabled: {\n type: 'ParameterType:boolean',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IValidateFormOperationData } from \"@operation/validate-form.ts\";\n\nexport function validateForm(): IOperationMetadata<IValidateFormOperationData> {\n return {\n description: `Validates form fields against HTML5 validation and custom rules.\n\nUses HTML5 validation API (checkValidity()) for native validation, and supports\ncustom validation rules for: required, minLength, maxLength, pattern (regex), and email format.\n\nCheckboxes and radio buttons are validated once per name: \\`required\\` passes when at least one\nof them is checked, and the string rules do not apply to them. For a \\`<select multiple>\\`,\n\\`required\\`, \\`minLength\\` and \\`maxLength\\` count the selected options, and \\`pattern\\` and \\`email\\`\napply to each selected value.`,\n category: `Form`,\n dependentProperties: ['selectedElement'],\n properties: {\n validationRules: {\n type: 'ParameterType:object',\n erased: true\n }\n },\n outputProperties: {\n validationErrors: {\n type: 'ParameterType:object'\n },\n isValid: {\n type: 'ParameterType:boolean'\n }\n }\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IWaitOperationData } from \"@operation/wait.ts\";\n\nexport function wait(): IOperationMetadata<IWaitOperationData> {\n return {\n description: `This operation waits for the specified amount of milliseconds.`,\n category: `Utility`,\n properties: {\n milliseconds: {\n type: 'ParameterType:number',\n required: true,\n erased: true\n }\n },\n };\n}\n","import type { IOperationMetadata } from \"@operation/metadata/types.ts\";\nimport type { IWhenOperationData } from \"@operation/when.ts\";\n\nexport function when(): IOperationMetadata<IWhenOperationData> {\n return {\n description: `When the given expression evaluates to false, subsequent operations will be skipped\nuntil an {@link endWhen} or {@link otherwise} operation is encountered.\n\nPractically, this means an \\`if\\` or \\`if\\`/\\`else\\` statement control flow implementation in a list of operations.\n\nThe expression is passed in as a formatted string. An operand can be one of:\n\n'constant': for a constant string (operators and parentheses inside the quotes are text)\n100: for a constant number (the whole operand must be numeric, \\`10px\\` is invalid)\ntrue, false, null: for a boolean or null constant\n$operationData.foo: for an operation data value\n$globaldata.foo: for a global data value\n$scope.loopIndex: for a scope value\n$scope.variables.foo: for a variable set with \\`setVariable\\`\n\nAny other operand is an error, so a misspelled chain prefix fails instead of being compared\nas a string.\n\nOperands are combined with these operators, from highest to lowest precedence:\n\n\\`!\\`: negation\n\\`==\\`, \\`!=\\`, \\`>\\`, \\`<\\`, \\`>=\\`, \\`<=\\`: comparison (\\`==\\` and \\`!=\\` compare strictly, without type\nconversion; comparisons do not chain, so write \\`0<$scope.loopIndex && $scope.loopIndex<5\\`)\n\\`&&\\`: and\n\\`||\\`: or\n\nParentheses group. A bare operand is true when its value is truthy, so \\`'false'\\` and \\`'0'\\`\nare true and \\`0\\`, \\`''\\`, \\`null\\` and a missing value are false. \\`!\\`, \\`&&\\` and \\`||\\` always\nproduce \\`true\\` or \\`false\\`. \\`!\\` binds tighter than a comparison: \\`!$operationdata.a==1\\`\ncompares \\`!$operationdata.a\\` with 1, write \\`!($operationdata.a==1)\\` to negate the comparison.\n\\`&&\\` and \\`||\\` short-circuit: when the left side decides the result, the right side is not\nresolved, so \\`$operationdata.user && $operationdata.user.name=='John'\\` does not fail when\n\\`user\\` is missing.\n\nArithmetic (\\`+\\`, \\`-\\`, \\`*\\`, \\`/\\`) is not supported: \\`-\\` is a valid character in a property\nchain, so \\`$operationdata.a-1\\` would be ambiguous. Nothing in the expression is executed as\ncode, and property chains are resolved with the usual prototype-pollution and global-object\nguards.`,\n category: `Control Flow`,\n properties: {\n expression: {\n type: 'ParameterType:expression',\n required: true,\n erased: true\n }\n },\n };\n}\n","export { addClass } from \"@operation/metadata/add-class.ts\";\nexport { addControllerToElement } from \"@operation/metadata/add-controller-to-element.ts\";\nexport { addGlobalsToOperation } from \"@operation/metadata/add-globals-to-operation.ts\";\nexport { animateWithClass } from \"@operation/metadata/animate-with-class.ts\";\nexport { animate } from \"@operation/metadata/animate.ts\";\nexport { announceToScreenReader } from \"@operation/metadata/announce-to-screen-reader.ts\";\nexport { breakForEach } from \"@operation/metadata/break-for-each.ts\";\nexport { broadcastEvent } from \"@operation/metadata/broadcast-event.ts\";\nexport { calc } from \"@operation/metadata/calc.ts\";\nexport { clearElement } from \"@operation/metadata/clear-element.ts\";\nexport { clearOperationData } from \"@operation/metadata/clear-operation-data.ts\";\nexport { clearStorage } from \"@operation/metadata/clear-storage.ts\";\nexport { compareDate } from \"@operation/metadata/compare-date.ts\";\nexport { concatenateStrings } from \"@operation/metadata/concatenate-strings.ts\";\nexport { continueForEach } from \"@operation/metadata/continue-for-each.ts\";\nexport { createElement } from \"@operation/metadata/create-element.ts\";\nexport { customFunction } from \"@operation/metadata/custom-function.ts\";\nexport { endAction } from \"@operation/metadata/end-action.ts\";\nexport { endForEach } from \"@operation/metadata/end-for-each.ts\";\nexport { endWhen } from \"@operation/metadata/end-when.ts\";\nexport { extendController } from \"@operation/metadata/extend-controller.ts\";\nexport { filterArray } from \"@operation/metadata/filter-array.ts\";\nexport { findInArray } from \"@operation/metadata/find-in-array.ts\";\nexport { forEach } from \"@operation/metadata/for-each.ts\";\nexport { formatDate } from \"@operation/metadata/format-date.ts\";\nexport { formatText } from \"@operation/metadata/format-text.ts\";\nexport { getAttributesFromElement } from \"@operation/metadata/get-attributes-from-element.ts\";\nexport { getControllerFromElement } from \"@operation/metadata/get-controller-from-element.ts\";\nexport { getControllerInstance } from \"@operation/metadata/get-controller-instance.ts\";\nexport { getCurrentTime } from \"@operation/metadata/get-current-time.ts\";\nexport { getElementDimensions } from \"@operation/metadata/get-element-dimensions.ts\";\nexport { getFocusedElement } from \"@operation/metadata/get-focused-element.ts\";\nexport { getFormData } from \"@operation/metadata/get-form-data.ts\";\nexport { getImport } from \"@operation/metadata/get-import.ts\";\nexport { getQueryParams } from \"@operation/metadata/get-query-params.ts\";\nexport { getScrollPosition } from \"@operation/metadata/get-scroll-position.ts\";\nexport { getTextContent } from \"@operation/metadata/get-text-content.ts\";\nexport { httpDelete } from \"@operation/metadata/http-delete.ts\";\nexport { httpPost } from \"@operation/metadata/http-post.ts\";\nexport { httpPut } from \"@operation/metadata/http-put.ts\";\nexport { invokeObjectMethod } from \"@operation/metadata/invoke-object-method.ts\";\nexport { isElementInViewport } from \"@operation/metadata/is-element-in-viewport.ts\";\nexport { loadFromStorage } from \"@operation/metadata/load-from-storage.ts\";\nexport { loadJson } from \"@operation/metadata/load-json.ts\";\nexport { log } from \"@operation/metadata/log.ts\";\nexport { mapArray } from \"@operation/metadata/map-array.ts\";\nexport { math } from \"@operation/metadata/math.ts\";\nexport { otherwise } from \"@operation/metadata/otherwise.ts\";\nexport { removeClass } from \"@operation/metadata/remove-class.ts\";\nexport { removeControllerFromElement } from \"@operation/metadata/remove-controller-from-element.ts\";\nexport { removeElement } from \"@operation/metadata/remove-element.ts\";\nexport { removePropertiesFromOperationData } from \"@operation/metadata/remove-properties-from-operation-data.ts\";\nexport { reparentElement } from \"@operation/metadata/reparent-element.ts\";\nexport { replaceString } from \"@operation/metadata/replace-string.ts\";\nexport { replaceText } from \"@operation/metadata/replace-text.ts\";\nexport { requestAction } from \"@operation/metadata/request-action.ts\";\nexport { saveToStorage } from \"@operation/metadata/save-to-storage.ts\";\nexport { scrollToElement } from \"@operation/metadata/scroll-to-element.ts\";\nexport { scrollToPosition } from \"@operation/metadata/scroll-to-position.ts\";\nexport { selectElement } from \"@operation/metadata/select-element.ts\";\nexport { setData } from \"@operation/metadata/set-data.ts\";\nexport { setElementAttributes } from \"@operation/metadata/set-element-attributes.ts\";\nexport { setElementContent } from \"@operation/metadata/set-element-content.ts\";\nexport { setFocus } from \"@operation/metadata/set-focus.ts\";\nexport { setFormValue } from \"@operation/metadata/set-form-value.ts\";\nexport { setGlobalData } from \"@operation/metadata/set-global-data.ts\";\nexport { setOperationData } from \"@operation/metadata/set-operation-data.ts\";\nexport { setStyle } from \"@operation/metadata/set-style.ts\";\nexport { setVariable } from \"@operation/metadata/set-variable.ts\";\nexport { sortArray } from \"@operation/metadata/sort-array.ts\";\nexport { splitString } from \"@operation/metadata/split-string.ts\";\nexport { startAction } from \"@operation/metadata/start-action.ts\";\nexport { substringText } from \"@operation/metadata/substring-text.ts\";\nexport { toggleClass } from \"@operation/metadata/toggle-class.ts\";\nexport { toggleElement } from \"@operation/metadata/toggle-element.ts\";\nexport { toggleFormElement } from \"@operation/metadata/toggle-form-element.ts\";\nexport { validateForm } from \"@operation/metadata/validate-form.ts\";\nexport { wait } from \"@operation/metadata/wait.ts\";\nexport { when } from \"@operation/metadata/when.ts\";\nexport * from \"@operation/metadata/types.ts\";\n","/**\n * Returns the known names closest to `name`, for \"did you mean\" hints in error\n * messages. Matching ignores case and uses the Levenshtein edit distance; only\n * names within `max(2, floor(name.length / 3))` edits are returned, closest\n * first.\n *\n * @param name - The unknown name, as written in the configuration\n * @param knownNames - The names that are registered\n * @param max - The maximum number of suggestions to return\n * @returns Up to `max` known names, closest first; empty when none is close\n */\nexport function findClosestNames(\n name: string,\n knownNames: readonly string[],\n max = 3\n): string[] {\n const lowerName = name.toLowerCase();\n const maxDistance = Math.max(2, Math.floor(name.length / 3));\n\n return knownNames\n .map(knownName => ({\n knownName,\n distance: levenshtein(lowerName, knownName.toLowerCase()),\n }))\n .filter(({distance}) => distance <= maxDistance)\n .sort((a, b) => a.distance - b.distance)\n .slice(0, max)\n .map(({knownName}) => knownName);\n}\n\n/**\n * Formats suggestions from {@link findClosestNames} as a sentence.\n *\n * @param suggestions - The suggested names\n * @returns `Did you mean 'a', 'b'?`, or an empty string when there are no suggestions\n */\nexport function formatDidYouMean(suggestions: readonly string[]): string {\n if (!suggestions.length) {\n return '';\n }\n return `Did you mean ${suggestions.map(name => `'${name}'`).join(', ')}?`;\n}\n\nfunction levenshtein(a: string, b: string) {\n let previous = Array.from({length: b.length + 1}, (_, i) => i);\n for (let i = 1; i <= a.length; i++) {\n const current = [i];\n for (let j = 1; j <= b.length; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n current[j] = Math.min(\n previous[j] + 1,\n current[j - 1] + 1,\n previous[j - 1] + cost\n );\n }\n previous = current;\n }\n return previous[b.length];\n}\n","import type { IDOMEventListenerControllerOperationData } from \"@controllers/dom-event-listener-controller.ts\";\nimport type { IControllerMetadata } from \"@controllers/metadata/types.ts\";\n\nexport function DOMEventListenerController(): IControllerMetadata<IDOMEventListenerControllerOperationData> {\n return {\n description: `This controller attaches to the given selected element and adds a DOM event listener for the specified event name that\nexecutes the given actions with the given operation data.\n\nBy default the \\`start\\` operations of the specified actions are executed. To execute the \\`end\\` operations instead,\nprefix the action name with \\`end:\\`.\n\nThe actions receive a copy of \\`actionOperationData\\` plus \\`eventTarget\\` (the event's target) and, for key events,\n\\`eventKey\\` (the \\`KeyboardEvent.key\\`). They run in order, each receiving the operation data the previous one\nreturned. When an action fails, the\nremaining actions are skipped and the failure is reported through the eventbus's \\`reportError\\` (an error naming\nthis controller, the action and the DOM event, with the original error as \\`cause\\`), or logged with\n\\`console.error\\` when the eventbus has no \\`reportError\\`.`,\n dependentProperties: ['selectedElement'],\n properties: {\n eventName: {\n type: 'ParameterType:eventName',\n required: true,\n },\n actions: {\n type: 'ParameterType:array',\n itemType: 'ParameterType:string',\n },\n actionOperationData: {\n type: 'ParameterType:object',\n }\n },\n };\n}\n","import type { IKeyboardControllerOperationData } from \"@controllers/keyboard-controller.ts\";\nimport type { IControllerMetadata } from \"@controllers/metadata/types.ts\";\n\nexport function KeyboardController(): IControllerMetadata<IKeyboardControllerOperationData> {\n return {\n description: `This controller runs the given actions when one of the given keys is pressed.\n\nBy default the \\`start\\` operations of the specified actions are executed. To execute the \\`end\\` operations instead,\nprefix the action name with \\`end:\\`.\n\nThe actions receive a copy of \\`actionOperationData\\` plus \\`eventTarget\\` (the focused element, or the body when\nnothing has focus) and \\`eventKey\\` (the \\`KeyboardEvent.key\\`). They run in order, each receiving the operation data\nthe previous one returned. When an action fails, the remaining actions are skipped and the failure is reported\nthrough the eventbus's \\`reportError\\`, or logged with \\`console.error\\` when the eventbus has no \\`reportError\\`.\n\nWith \\`scope: 'document'\\` (the default) the keys work while the focus is inside the engine root, or while nothing\nhas focus. With \\`scope: 'element'\\` they only work while the focus is inside the selected element. Presses in\n\\`input\\`, \\`select\\`, \\`textarea\\` and contenteditable elements are ignored, so typing keeps working. A handled press\nhas its default action prevented (no scrolling for arrow keys and space); a held key runs the actions once, not\nagain for every key repeat.\n\nWhen the keys include the play toggle hotkey of the engine (space by default), or a key that the engine's\nKeyboardStepSource binds (the arrow keys, \\`shift+left\\`/\\`shift+right\\`, \\`home\\` and \\`end\\`), the controller wins: a\npress it handles runs its actions and does not toggle playback or step the timeline. A press it ignores (for\nexample outside the selected element with \\`scope: 'element'\\`) still does.\n\nThe keys are bound in the hotkeys-js \\`'all'\\` scope, so they work whatever scope a KeyboardStepSource sets. The\nhotkeys-js global \\`filter\\` still applies. Detaching removes only this controller's handler.`,\n dependentProperties: ['selectedElement'],\n properties: {\n keys: {\n type: 'ParameterType:string',\n required: true,\n },\n actions: {\n type: 'ParameterType:array',\n itemType: 'ParameterType:string',\n },\n actionOperationData: {\n type: 'ParameterType:object',\n },\n scope: {\n type: [\n { value: 'document' },\n { value: 'element' }\n ],\n }\n },\n };\n}\n","import type { ILabelControllerMetadata } from \"@controllers/label-controller.ts\";\nimport type { IControllerMetadata } from \"@controllers/metadata/types.ts\";\n\nexport function LabelController(): IControllerMetadata<ILabelControllerMetadata> {\n return {\n description: `This controller attaches to the given selected element and renders the text\nassociated with the given translation key.\n\nTranslations may contain simple inline markup. They are passed through\n\\`sanitizeHtml\\` before insertion, so \\`<br>\\`, \\`<strong>\\`, \\`<em>\\`,\n\\`<span>\\` and http(s)/mailto/relative links render, while scripts, event\nhandlers, \\`javascript:\\` URLs, images, iframes and SVG are removed.\n\nThe controller listens for the \\`language-change\\` event and re-renders the text\nwith the new language after such an event.\n\nUses the rosetta-based locale system via \\`request-translation\\` event.`,\n dependentProperties: ['selectedElement'],\n properties: {\n translationKey: {\n type: 'ParameterType:string',\n required: true,\n },\n attributeName: {\n type: 'ParameterType:string',\n }\n },\n };\n}\n","import type { ILottieControllerMetadata } from \"@controllers/lottie-controller.ts\";\nimport type { IControllerMetadata } from \"@controllers/metadata/types.ts\";\n\nexport function LottieController(): IControllerMetadata<ILottieControllerMetadata> {\n return {\n description: `This controller renders a [lottie-web](https://github.com/airbnb/lottie-web) animation inside the given selected element.\n\nThe url may encode freeze and end positions like this: my-url/filename[freeze=10,end=21].json\n\nlottie-web is an optional peer dependency. It is loaded with a dynamic\n\\`import()\\` the first time a LottieController attaches, so applications that\nnever use this controller do not need it installed.`,\n properties: {\n url: {\n type: 'ParameterType:url',\n }\n },\n };\n}\n","import type { IControllerMetadata } from \"@controllers/metadata/types.ts\";\nimport type { IMutationObserverControllerMetadata } from \"@controllers/mutation-observer-controller.ts\";\n\nexport function MutationObserverController(): IControllerMetadata<IMutationObserverControllerMetadata> {\n return {\n description: `Controller that observes DOM mutations on a selected element and broadcasts events.\n\nThis controller creates a MutationObserver to monitor DOM changes (attributes, child nodes,\ntext content) on a specified element. All detected mutations are broadcasted through the\nEligius eventbus, enabling reactive behavior in response to DOM changes.\n\nThe controller follows the standard Eligius lifecycle:\n- init(): Store configuration metadata\n- attach(): Create and start the MutationObserver\n- detach(): Disconnect the observer and clean up resources`,\n dependentProperties: ['selectedElement'],\n properties: {\n observeAttributes: {\n type: 'ParameterType:boolean',\n },\n observeChildList: {\n type: 'ParameterType:boolean',\n },\n observeCharacterData: {\n type: 'ParameterType:boolean',\n },\n observeSubtree: {\n type: 'ParameterType:boolean',\n },\n attributeOldValue: {\n type: 'ParameterType:boolean',\n },\n characterDataOldValue: {\n type: 'ParameterType:boolean',\n },\n attributeFilter: {\n type: 'ParameterType:array',\n itemType: 'ParameterType:string',\n }\n },\n };\n}\n","import type { IControllerMetadata } from \"@controllers/metadata/types.ts\";\nimport type { INavigationControllerOperationData } from \"@controllers/navigation-controller.ts\";\n\nexport function NavigationController(): IControllerMetadata<INavigationControllerOperationData> {\n return {\n description: `Renders a navigation menu in the selected element and keeps it in sync with\nthe active navigation entry.\n\nActivating a menu item (click, Enter or Space) navigates to its entry:\n- an entry with a \\`timelineUri\\` broadcasts \\`request-timeline-uri\\`\n [timelineUri, position], which the engine handles by switching timelines;\n- an entry without one broadcasts the legacy \\`request-video-url\\`\n [videoUrlIndex, position], which the engine does not handle.\n\nWith \\`autoNext\\`, the next entry is started when the active entry's timeline\ncompletes (\\`timeline-complete\\`) or, for legacy entries, on \\`video-complete\\`.\nWhen the engine switches to a timeline that an entry names\n(\\`timeline-current-timeline-change\\`), that entry becomes the active one.`,\n dependentProperties: ['selectedElement'],\n properties: {\n json: {\n type: 'ParameterType:object',\n required: true,\n }\n },\n };\n}\n","import type { IControllerMetadata } from \"@controllers/metadata/types.ts\";\nimport type { IProgressbarControllerOperationData } from \"@controllers/progressbar-controller.ts\";\n\nexport function ProgressbarController(): IControllerMetadata<IProgressbarControllerOperationData> {\n return {\n description: `This controller renders a progressbar that displays the progress of the current timeline in the given selected element.\n\nThe current progress as a percentage is rendered in the given text element.`,\n dependentProperties: ['selectedElement', 'textElement'],\n };\n}\n","import type { IControllerMetadata } from \"@controllers/metadata/types.ts\";\nimport type { IRoutingControllerOperationData } from \"@controllers/routing-controller.ts\";\n\nexport function RoutingController(): IControllerMetadata<IRoutingControllerOperationData> {\n return {\n description: `Keeps the browser history in sync with the navigation entries: each entry\ngets a \\`#/<id>/<position>\\` URL, and back/forward navigation requests the\nentry in the URL.\n\nRequests go to the engine as \\`request-timeline-uri\\` for entries with a\n\\`timelineUri\\`, and as the legacy \\`request-video-url\\` otherwise. Before the\nengine switches timelines (\\`before-request-timeline-uri\\`, or the legacy\n\\`before-request-video-url\\`), the current entry is saved with its position.\n\nThis is a work in progress, do not use this yet please....`,\n properties: {\n json: {\n type: 'ParameterType:object',\n required: true,\n }\n },\n };\n}\n","import type { IControllerMetadata } from \"@controllers/metadata/types.ts\";\nimport type { ISubtitlesControllerOperationData } from \"@controllers/subtitles-controller.ts\";\n\nexport function SubtitlesController(): IControllerMetadata<ISubtitlesControllerOperationData> {\n return {\n description: `This controller shows the subtitle whose duration contains the current\ntimeline position in the selected element, in the current language, and\nre-renders it after a \\`language-change\\` event.\n\nThe starting language is the locale's current language\n(\\`request-current-language\\`); the configured \\`language\\` is only used when\nnothing answers that request.\n\nSubtitle texts may contain simple inline markup. They are passed through\n\\`sanitizeHtml\\` before insertion, so \\`<br>\\`, \\`<i>\\`, \\`<em>\\`,\n\\`<strong>\\` and \\`<span>\\` render, while scripts, event handlers,\n\\`javascript:\\` URLs, images, iframes and SVG are removed.`,\n dependentProperties: ['selectedElement'],\n properties: {\n language: {\n type: 'ParameterType:languagecode',\n },\n subtitleData: {\n type: 'ParameterType:array',\n }\n },\n };\n}\n","export { DOMEventListenerController } from \"@controllers/metadata/dom-event-listener-controller.ts\";\nexport { KeyboardController } from \"@controllers/metadata/keyboard-controller.ts\";\nexport { LabelController } from \"@controllers/metadata/label-controller.ts\";\nexport { LottieController } from \"@controllers/metadata/lottie-controller.ts\";\nexport { MutationObserverController } from \"@controllers/metadata/mutation-observer-controller.ts\";\nexport { NavigationController } from \"@controllers/metadata/navigation-controller.ts\";\nexport { ProgressbarController } from \"@controllers/metadata/progressbar-controller.ts\";\nexport { RoutingController } from \"@controllers/metadata/routing-controller.ts\";\nexport { SubtitlesController } from \"@controllers/metadata/subtitles-controller.ts\";\nexport * from \"@controllers/metadata/types.ts\";\n","import type {\n IContainerProviderConfig,\n IPositionSourceConfig,\n ITimelineProviderSettings,\n} from '@configuration/types.ts';\n\n/**\n * The part of a timeline configuration that can override the provider\n * settings of its type.\n */\nexport interface ITimelineProviderOverrides {\n positionSource?: Partial<IPositionSourceConfig>;\n containerProvider?: Partial<IContainerProviderConfig>;\n}\n\ntype TProviderConfig = {systemName: string; [key: string]: unknown};\n\n/**\n * Merges a per-timeline override over the settings of the timeline's type.\n *\n * - Without an override the type's settings are returned as they are.\n * - An override that leaves out `systemName`, or names the same class as the\n * type's settings, is merged over them property by property (shallow).\n * - An override that names a different class replaces the type's settings,\n * so options meant for one class never reach another.\n *\n * @param base - The settings of the timeline's type, if any\n * @param override - The timeline's override, if any\n * @returns The effective settings, or undefined when neither is given\n */\nexport function mergeProviderConfig<T extends TProviderConfig>(\n base: T | undefined,\n override: Partial<T> | undefined\n): Partial<T> | undefined {\n if (!override) {\n return base;\n }\n if (!base) {\n return {...override};\n }\n if (\n override.systemName !== undefined &&\n override.systemName !== base.systemName\n ) {\n return {...override};\n }\n return {...base, ...override};\n}\n\n/**\n * The effective position source settings of a timeline: its\n * `positionSource` override merged over the settings of its type (see\n * {@link mergeProviderConfig}).\n */\nexport function effectivePositionSource(\n timeline: ITimelineProviderOverrides,\n typeSettings: ITimelineProviderSettings | undefined\n): Partial<IPositionSourceConfig> | undefined {\n return mergeProviderConfig(\n typeSettings?.positionSource,\n timeline.positionSource\n );\n}\n\n/**\n * The effective container provider settings of a timeline: its\n * `containerProvider` override merged over the `container` settings of its\n * type (see {@link mergeProviderConfig}).\n */\nexport function effectiveContainerProvider(\n timeline: ITimelineProviderOverrides,\n typeSettings: ITimelineProviderSettings | undefined\n): Partial<IContainerProviderConfig> | undefined {\n return mergeProviderConfig(\n typeSettings?.container,\n timeline.containerProvider\n );\n}\n\n/**\n * True when the timeline's `positionSource` override changes the settings\n * of its type, so the timeline needs a position source of its own.\n */\nexport function overridesPositionSource(\n timeline: ITimelineProviderOverrides,\n typeSettings: ITimelineProviderSettings | undefined\n): boolean {\n return (\n timeline.positionSource !== undefined &&\n !isSameProviderConfig(\n effectivePositionSource(timeline, typeSettings),\n typeSettings?.positionSource\n )\n );\n}\n\n/**\n * True when the timeline's `containerProvider` override changes the\n * `container` settings of its type.\n */\nexport function overridesContainerProvider(\n timeline: ITimelineProviderOverrides,\n typeSettings: ITimelineProviderSettings | undefined\n): boolean {\n return (\n timeline.containerProvider !== undefined &&\n !isSameProviderConfig(\n effectiveContainerProvider(timeline, typeSettings),\n typeSettings?.container\n )\n );\n}\n\n/**\n * A key that is equal for equal provider settings, whatever the order of\n * their properties.\n */\nexport function providerConfigKey(config: unknown): string {\n return JSON.stringify(sortKeys(config)) ?? 'undefined';\n}\n\nfunction isSameProviderConfig(a: unknown, b: unknown): boolean {\n return providerConfigKey(a) === providerConfigKey(b);\n}\n\nfunction sortKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortKeys);\n }\n if (value !== null && typeof value === 'object') {\n const source = value as Record<string, unknown>;\n return Object.keys(source)\n .sort()\n .reduce<Record<string, unknown>>((sorted, key) => {\n sorted[key] = sortKeys(source[key]);\n return sorted;\n }, {});\n }\n return value;\n}\n","import {\n breakForEachSystemName,\n continueForEachSystemName,\n endForEachSystemName,\n endWhenSystemName,\n forEachSystemName,\n otherwiseSystemName,\n whenSystemName,\n} from '@operation/helper/flow-control-names.ts';\n\n/**\n * A control-flow block that is not well formed, found by\n * {@link findFlowControlProblems}.\n */\nexport interface IFlowControlProblem {\n /** The index, in the operation list, of the operation the problem is reported at */\n index: number;\n /** What is wrong, naming the operations and their indices */\n message: string;\n}\n\ntype TOpener = typeof whenSystemName | typeof forEachSystemName;\n\ninterface IOpenBlock {\n name: TOpener;\n index: number;\n hasOtherwise: boolean;\n}\n\nconst closerOf: Record<TOpener, string> = {\n [whenSystemName]: endWhenSystemName,\n [forEachSystemName]: endForEachSystemName,\n};\n\n/**\n * Checks that the `when`/`otherwise`/`endWhen` and `forEach`/`endForEach`\n * blocks of an operation list are balanced and nested, and that\n * `breakForEach` and `continueForEach` sit inside a `forEach`.\n *\n * The interpreter does not check this. An `endWhen` that closes a `forEach`,\n * or an `endWhen` without a `when`, pops the wrong scope at runtime, and the\n * action then fails with a TypeError on the next operation, or runs with the\n * wrong scope. A block that is never closed runs to the end of the list.\n *\n * @param systemNames The system names of the operations, in order\n * @returns The problems in list order, empty when the blocks are well formed\n */\nexport function findFlowControlProblems(\n systemNames: readonly string[]\n): IFlowControlProblem[] {\n const problems: IFlowControlProblem[] = [];\n const stack: IOpenBlock[] = [];\n\n const close = (closer: string, expected: TOpener, index: number) => {\n const top = stack[stack.length - 1];\n if (!top) {\n problems.push({\n index,\n message: `${closer} at index ${index} has no open ${expected} to close.`,\n });\n return;\n }\n if (top.name !== expected) {\n problems.push({\n index,\n message: `${closer} at index ${index} closes the ${top.name} at index ${top.index}, which must be closed with ${closerOf[top.name]} first: blocks must nest.`,\n });\n }\n stack.pop();\n };\n\n systemNames.forEach((name, index) => {\n switch (name) {\n case whenSystemName:\n case forEachSystemName:\n stack.push({name, index, hasOtherwise: false});\n break;\n case otherwiseSystemName: {\n const top = stack[stack.length - 1];\n if (!top || top.name !== whenSystemName) {\n problems.push({\n index,\n message: top\n ? `otherwise at index ${index} is inside the forEach at index ${top.index}, not directly inside a when.`\n : `otherwise at index ${index} has no open when.`,\n });\n } else if (top.hasOtherwise) {\n problems.push({\n index,\n message: `otherwise at index ${index} is the second otherwise of the when at index ${top.index}.`,\n });\n } else {\n top.hasOtherwise = true;\n }\n break;\n }\n case endWhenSystemName:\n close(endWhenSystemName, whenSystemName, index);\n break;\n case endForEachSystemName:\n close(endForEachSystemName, forEachSystemName, index);\n break;\n case breakForEachSystemName:\n case continueForEachSystemName:\n if (!stack.some(block => block.name === forEachSystemName)) {\n problems.push({\n index,\n message: `${name} at index ${index} is not inside a forEach.`,\n });\n }\n break;\n default:\n break;\n }\n });\n\n for (const open of stack) {\n problems.push({\n index: open.index,\n message: `${open.name} at index ${open.index} is never closed with ${closerOf[open.name]}.`,\n });\n }\n\n return problems.sort((a, b) => a.index - b.index);\n}\n","import {getPropertyChainValue} from '@operation/helper/get-property-chain-value.ts';\n\n/**\n * Gets the value for the given property chain. A property chain is defined by a period delimited string.\n *\n * For example, this property chain: `mySource.subSource.element.value` should be extracted from an object of this shape:\n * ```ts\n * const foo = {\n * mySource: {\n * subSource: {\n * element: {\n * value: 'bar'\n * }\n * }\n * }\n * }\n * ```\n *\n * The result of the invocation `resolvePropertyChain('mySource.subSource.element.value', foo)` would then yield the value `bar`.\n *\n * Chains containing `__proto__`, `prototype` or `constructor` segments are rejected.\n *\n * @throws When the chain cannot be resolved or contains a forbidden segment.\n */\nexport function resolvePropertyChain(\n propertyChain: string,\n sourceObject: any,\n operationName?: string\n) {\n const properties = propertyChain.split('.');\n return getPropertyChainValue(properties, sourceObject, operationName);\n}\n","/**\n * Returns true for any non-null, non-array object: plain objects, but also\n * class instances, `Date`, `Map`, DOM nodes and jQuery objects.\n *\n * The narrowed type is a loose record. When the value must be a plain data\n * object (an object literal or parsed JSON), use `isPlainObject` instead.\n *\n * @param value - Any value\n * @returns Whether `value` is a non-null, non-array object\n */\nexport function isObject(\n value: unknown\n): value is Record<PropertyKey, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n","import {Action, EndableAction, TimelineAction} from '@action/index.ts';\nimport type {IAction} from '@action/types.ts';\nimport {\n effectiveContainerProvider,\n effectivePositionSource,\n} from '@configuration/timeline-provider-overrides.ts';\nimport type {\n IActionConfiguration,\n IEndableActionConfiguration,\n IEngineConfiguration,\n IEventActionConfiguration,\n IOperationConfiguration,\n IResolvedActionConfiguration,\n IResolvedEndableActionConfiguration,\n IResolvedEngineConfiguration,\n IResolvedOperation,\n IResolvedTimelineConfiguration,\n ITimelineActionConfiguration,\n ITimelineConfiguration,\n} from '@configuration/types.ts';\nimport type {ActionRegistryEventbusListener} from '@eventbus/index.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\nimport {deepCopy} from '@operation/helper/deep-copy.ts';\nimport {findFlowControlProblems} from '@operation/helper/flow-control-structure.ts';\nimport {resolvePropertyChain} from '@operation/helper/resolve-property-chain.ts';\nimport type {TOperationData} from '@operation/types.ts';\nimport {findClosestNames, formatDidYouMean} from '@util/find-closest-names.ts';\nimport {isFunction} from '@util/guards/is-function.ts';\nimport {isObject} from '@util/guards/is-object.ts';\nimport {isPlainObject} from '@util/guards/is-plain-object.ts';\nimport {isString} from '@util/guards/is-string.ts';\nimport {isDefined} from 'ts-is-present';\nimport type {IEngineServices} from '@/engine-services.ts';\nimport type {\n IConfigurationResolver,\n IConfigurationResolverOptions,\n IConfigurationWarning,\n IDuration,\n ISimpleResourceImporter,\n} from '../types.ts';\n\ntype TWarn = (warning: IConfigurationWarning) => void;\n\n/**\n * The default warning handler: writes the warning to the console.\n */\nfunction warnToConsole(warning: IConfigurationWarning): void {\n console.warn(\n `Eligius configuration warning at ${warning.path}: ${warning.message}`\n );\n}\n\n/**\n * Takes an `IEngineConfiguration` instance and return an `IResolvedEngineConfiguration`.\n * This means all system names within the configuration will be resolved to their associated instances.\n *\n * If the given configuration includes event actions, then those will be registered in the given\n * `ActionRegistryEventbusListener`. They are registered only after the whole configuration\n * has been accepted, so a configuration that `process` rejects leaves the listener untouched.\n *\n * Every error names the JSON path of the offending value.\n *\n * @throws When an operation's `systemName` does not resolve to an operation function (including\n * controller, timeline provider, custom function and class exports of the importer). The message\n * suggests the closest operation names the importer lists, which include the custom operations\n * registered with `EligiusResourceImporter`.\n * @throws When two actions (or an action and an event action) share the same name.\n * @throws When `actions`, `initActions`, `timelines`, an action's `startOperations` or\n * `endOperations`, or a timeline's `timelineActions` is not an array.\n * @throws When a timeline action has no valid `duration`, or when a timeline's `type` has no\n * entry in `timelineProviderSettings` and the timeline has no `positionSource` with a `systemName`\n * of its own.\n * @throws When a timeline's `positionSource` or `containerProvider` override is not an object,\n * names a `systemName` the importer does not provide, or leaves out a setting that the provider\n * requires (for example `selector` of `ScrollPositionSource`) once it is merged over the type's\n * settings.\n * @throws When a VideoPositionSource has an 'options' key, at timelineProviderSettings.<type>.positionSource\n * or at a timeline's positionSource override (also when the override inherits VideoPositionSource from its\n * type). 4.0.0 removed the video.js player options.\n * @throws When a `template:`, `json:` or `config:` placeholder cannot be resolved.\n *\n * Control-flow blocks that are not well formed (an `endWhen` without a `when`,\n * an `endWhen` that closes a `forEach`, a `when` that is never closed, a\n * `breakForEach` outside a `forEach`) are reported as warnings through\n * {@link IConfigurationResolverOptions.onWarning}, by default on the console.\n * The interpreter runs them as before: an operation list with such a block\n * fails at runtime, or runs with the wrong scope. They become errors in the\n * next major version. `eligius/lint` reports the same shapes as errors.\n */\nexport class ConfigurationResolver implements IConfigurationResolver {\n private readonly _warn: TWarn;\n\n /**\n * @param importer - Resolves system names to operations, controllers and providers\n * @param eventbus - The eventbus the resolved actions run on\n * @param services - The services of the engine the resolved actions run in\n * @param options - Optional. `onWarning` receives the configuration\n * warnings instead of the console.\n */\n constructor(\n private importer: ISimpleResourceImporter,\n private eventbus: IEventbus,\n private services: IEngineServices,\n options: IConfigurationResolverOptions = {}\n ) {\n this._warn = options.onWarning ?? warnToConsole;\n }\n\n process(\n configuration: IEngineConfiguration,\n actionRegistryListener?: ActionRegistryEventbusListener\n ): [Record<string, IAction>, IResolvedEngineConfiguration] {\n // Resolve the imported placeholders (template:, json:) first, so that a config:\n // placeholder always sees the resolved value, regardless of property order.\n const imported = new WeakSet<object>();\n resolvePlaceholders(\n configuration,\n configuration,\n this.importer,\n 'import',\n imported,\n ''\n );\n resolvePlaceholders(\n configuration,\n configuration,\n this.importer,\n 'config',\n imported,\n ''\n );\n\n if (\n !isObject(configuration.timelineProviderSettings) &&\n !(\n configuration.timelineProviderSettings === undefined &&\n everyTimelineHasOwnPositionSource(configuration.timelines)\n )\n ) {\n throw new Error(\n `Configuration incomplete: it needs to have at least one timeline provider setting at timelineProviderSettings, got ${describeValue(configuration.timelineProviderSettings)}.`\n );\n }\n\n const resolvedConfig: IResolvedEngineConfiguration = {\n id: configuration.id,\n engine: {...configuration.engine},\n timelineProviderSettings:\n deepCopy(configuration.timelineProviderSettings) ?? {},\n containerSelector: configuration.containerSelector,\n cssFiles: deepCopy(configuration.cssFiles),\n language: configuration.language,\n layoutTemplate: configuration.layoutTemplate,\n availableLanguages: deepCopy(configuration.availableLanguages),\n actions: resolveActions(\n configuration.actions,\n this.importer,\n this.eventbus,\n this.services,\n 'actions',\n this._warn\n ),\n initActions: resolveActions(\n configuration.initActions,\n this.importer,\n this.eventbus,\n this.services,\n 'initActions',\n this._warn\n ),\n timelineFlow: deepCopy(configuration.timelineFlow),\n timelines: resolveTimelines(\n configuration.timelines,\n this.importer,\n this.eventbus,\n this.services,\n this._warn\n ),\n };\n\n assertTimelineProviderSettings(configuration, this.importer);\n\n let eventActions: IEventActionRegistration[] = [];\n if (isDefined(configuration.eventActions)) {\n assertArray(configuration.eventActions, 'eventActions');\n if (actionRegistryListener) {\n eventActions = resolveEventActions(\n configuration.eventActions,\n this.importer,\n this.eventbus,\n this.services,\n this._warn\n );\n }\n }\n\n const actionsLookup = createActionsLookup([\n ...(resolvedConfig.actions as IAction[]).map(\n (action, index) => [action, `actions[${index}]`] as const\n ),\n ...eventActions.map(\n ({action}, index) => [action, `eventActions[${index}]`] as const\n ),\n ]);\n\n // Register only now that the configuration is accepted, so a rejected\n // configuration leaves no live event actions behind.\n for (const {action, eventName, eventTopic} of eventActions) {\n actionRegistryListener?.registerAction(action, eventName, eventTopic);\n }\n\n return [actionsLookup, resolvedConfig];\n }\n}\n\ninterface IEventActionRegistration {\n action: IAction;\n eventName: string;\n eventTopic?: string;\n}\n\n/**\n * Describes a value for an error message by its kind only, so configuration\n * data never ends up in a message.\n */\nfunction describeValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return 'an array';\n }\n switch (typeof value) {\n case 'undefined':\n return 'undefined';\n case 'object':\n return 'an object';\n case 'number':\n return Number.isFinite(value) ? String(value) : 'a non-finite number';\n case 'string':\n return 'a string';\n case 'boolean':\n return 'a boolean';\n default:\n return `a ${typeof value}`;\n }\n}\n\nfunction assertArray(value: unknown, path: string): asserts value is unknown[] {\n if (!Array.isArray(value)) {\n throw new Error(\n `Invalid configuration at ${path}: expected an array, got ${describeValue(value)}.`\n );\n }\n}\n\n/**\n * Every timeline needs a position source: from the provider settings of its\n * type, or from a `positionSource` override with a `systemName` of its own.\n * Otherwise the engine silently has no position source for it.\n *\n * Overrides are checked here so a mistake fails at resolution with its JSON\n * path, not at init or on the first switch to the timeline.\n */\nfunction assertTimelineProviderSettings(\n configuration: IEngineConfiguration,\n importer: ISimpleResourceImporter\n) {\n const settings = configuration.timelineProviderSettings ?? {};\n // Every type, including types no timeline uses, so the mistake fails fast\n for (const [type, typeSettings] of Object.entries(settings)) {\n if (isObject(typeSettings) && isObject(typeSettings.positionSource)) {\n assertNoVideoOptions(\n typeSettings.positionSource,\n typeSettings.positionSource.systemName,\n `timelineProviderSettings.${type}.positionSource`\n );\n }\n }\n configuration.timelines.forEach((timeline, index) => {\n const path = `timelines[${index}]`;\n const {type} = timeline;\n const typeSettings =\n Object.hasOwn(settings, type) && isObject(settings[type])\n ? settings[type]\n : undefined;\n\n assertProviderOverride(\n timeline.positionSource,\n `${path}.positionSource`,\n 'position source',\n importer\n );\n assertProviderOverride(\n timeline.containerProvider,\n `${path}.containerProvider`,\n 'container provider',\n importer\n );\n\n // Before the missing-settings checks, so an old override whose sources\n // sit inside 'options' gets the real reason\n if (isObject(timeline.positionSource)) {\n assertNoVideoOptions(\n timeline.positionSource,\n effectivePositionSource(timeline, typeSettings)?.systemName,\n `${path}.positionSource`\n );\n }\n\n if (!typeSettings && !isString(timeline.positionSource?.systemName)) {\n throw new Error(\n `Missing timeline provider settings at timelineProviderSettings.${type} for ${path} (type '${type}'). Add a provider for the '${type}' timeline type, or give ${path}.positionSource a systemName of its own.`\n );\n }\n\n if (isDefined(timeline.positionSource)) {\n assertMergedProviderSettings(\n effectivePositionSource(timeline, typeSettings),\n `${path}.positionSource`,\n `timelineProviderSettings.${type}.positionSource`,\n 'position source'\n );\n }\n if (isDefined(timeline.containerProvider)) {\n assertMergedProviderSettings(\n effectiveContainerProvider(timeline, typeSettings),\n `${path}.containerProvider`,\n `timelineProviderSettings.${type}.container`,\n 'container provider'\n );\n }\n });\n}\n\n/**\n * True when there are timelines and every one names its own position source,\n * so the configuration needs no `timelineProviderSettings`.\n */\nfunction everyTimelineHasOwnPositionSource(timelines: unknown): boolean {\n return (\n Array.isArray(timelines) &&\n timelines.length > 0 &&\n timelines.every(\n timeline =>\n isObject(timeline) &&\n isObject(timeline.positionSource) &&\n isString(timeline.positionSource.systemName)\n )\n );\n}\n\n/**\n * Settings that the built-in providers cannot work without. They are checked\n * for timelines that override their provider settings, after the merge.\n */\nconst REQUIRED_PROVIDER_SETTINGS: Record<string, readonly string[]> = {\n ScrollPositionSource: ['selector'],\n VideoPositionSource: ['selector', 'sources'],\n DomContainerProvider: ['selector'],\n};\n\n/**\n * VideoPositionSource took video.js player options under `options` until\n * 4.0.0 removed video.js. Other position sources may still take an\n * `options` key, so only the effective system name `VideoPositionSource` is\n * checked.\n *\n * @param positionSource - The settings object as written in the configuration\n * @param systemName - The effective system name (inherited for overrides without one)\n * @param path - JSON path of `positionSource`\n * @throws When a VideoPositionSource has an `options` key\n */\nfunction assertNoVideoOptions(\n positionSource: Record<PropertyKey, unknown>,\n systemName: unknown,\n path: string\n) {\n if (\n systemName !== 'VideoPositionSource' ||\n !Object.hasOwn(positionSource, 'options')\n ) {\n return;\n }\n throw new Error(\n `Invalid configuration at ${path}.options: VideoPositionSource no longer accepts 'options' (the video.js player options were removed in 4.0.0). Put 'sources' and 'poster' directly in ${path} and delete 'options'. See the 4.0.0 migration steps in CHANGELOG.md.`\n );\n}\n\n/**\n * Checks the shape of a per-timeline provider override and that its\n * `systemName`, when given, is provided by the importer.\n */\nfunction assertProviderOverride(\n override: unknown,\n path: string,\n kind: string,\n importer: ISimpleResourceImporter\n) {\n if (!isDefined(override)) {\n return;\n }\n if (!isObject(override)) {\n throw new Error(\n `Invalid configuration at ${path}: expected an object with ${kind} settings, got ${describeValue(override)}.`\n );\n }\n const {systemName} = override;\n if (!isDefined(systemName)) {\n return;\n }\n if (!isString(systemName)) {\n throw new Error(\n `Invalid configuration at ${path}.systemName: expected the name of a ${kind} class, got ${describeValue(systemName)}.`\n );\n }\n\n let entry: unknown;\n try {\n entry = importer.import(systemName)?.[systemName];\n } catch {\n entry = undefined;\n }\n if (!isFunction(entry)) {\n const didYouMean = formatDidYouMean(\n findClosestNames(\n systemName,\n getImporterNames(importer, 'getProviderNames')\n )\n );\n throw new Error(\n `Unknown ${kind} '${systemName}' at ${path}.systemName. ${\n didYouMean ||\n `Check the spelling, or make sure the ${kind} is available from the resource importer.`\n }`\n );\n }\n const isListedAs = (getterName: string) =>\n getImporterNames(importer, getterName).includes(systemName);\n if (\n !isListedAs('getProviderNames') &&\n (isListedAs('getOperationNames') || isListedAs('getControllerNames'))\n ) {\n throw new Error(\n `Unknown ${kind} '${systemName}' at ${path}.systemName: '${systemName}' is an operation or controller, not a ${kind}.`\n );\n }\n}\n\n/**\n * Checks the settings a timeline ends up with once its override is merged\n * over the settings of its type: a `systemName`, and the settings the\n * built-in provider of that name requires.\n */\nfunction assertMergedProviderSettings(\n merged: Record<string, unknown> | undefined,\n path: string,\n typePath: string,\n kind: string\n) {\n const systemName = merged?.systemName;\n if (!merged || !isString(systemName)) {\n throw new Error(\n `Missing systemName at ${path}.systemName: there are no settings at ${typePath} to merge the override over, so it has to name the ${kind} class.`\n );\n }\n const required = Object.hasOwn(REQUIRED_PROVIDER_SETTINGS, systemName)\n ? REQUIRED_PROVIDER_SETTINGS[systemName]\n : [];\n for (const key of required) {\n if (!hasRequiredSetting(merged, key)) {\n throw new Error(\n `Missing setting at ${path}.${key}: '${systemName}' requires '${key}', and neither ${path} nor ${typePath} provides it.`\n );\n }\n }\n}\n\nfunction hasRequiredSetting(\n settings: Record<string, unknown>,\n key: string\n): boolean {\n if (key === 'sources') {\n return isNonEmptyArray(settings.sources);\n }\n const value = settings[key];\n return isString(value) ? value.length > 0 : isDefined(value);\n}\n\nfunction isNonEmptyArray(value: unknown): boolean {\n return Array.isArray(value) && value.length > 0;\n}\n\nfunction createActionsLookup(\n actions: (readonly [IAction, string])[]\n): Record<string, IAction> {\n // Null prototype objects, so that an action named '__proto__' cannot alter the prototype\n const lookup: Record<string, IAction> = Object.create(null);\n const paths: Record<string, string> = Object.create(null);\n\n for (const [action, path] of actions) {\n if (Object.hasOwn(lookup, action.name)) {\n throw new Error(\n `Duplicate action name '${action.name}' at ${paths[action.name]}.name and ${path}.name. Action names must be unique across actions and eventActions, rename one of them.`\n );\n }\n lookup[action.name] = action;\n paths[action.name] = path;\n }\n\n return lookup;\n}\n\n/**\n * Creates the event actions without registering them.\n */\nfunction resolveEventActions(\n eventActionConfigurations: IEventActionConfiguration[],\n importer: ISimpleResourceImporter,\n eventbus: IEventbus,\n services: IEngineServices,\n warn: TWarn\n): IEventActionRegistration[] {\n const resolvedConfigs =\n eventActionConfigurations.map<IResolvedActionConfiguration>(\n (config, index) =>\n resolveActionConfiguration(\n config,\n importer,\n `eventActions[${index}]`,\n warn\n )\n );\n\n return resolvedConfigs.map((config, index) => {\n const {eventName, eventTopic} = eventActionConfigurations[index];\n return {\n action: new Action(\n config.name,\n config.startOperations,\n eventbus,\n services\n ),\n eventName,\n eventTopic,\n };\n });\n}\n\nfunction resolveTimelines(\n timelines: ITimelineConfiguration[],\n importer: ISimpleResourceImporter,\n eventbus: IEventbus,\n services: IEngineServices,\n warn: TWarn\n) {\n assertArray(timelines, 'timelines');\n return timelines.map<IResolvedTimelineConfiguration>(\n (config, timelineIndex) => {\n const path = `timelines[${timelineIndex}]`;\n assertArray(config.timelineActions, `${path}.timelineActions`);\n return {\n ...config,\n // Copies, so the resolved configuration does not share the overrides\n ...(isDefined(config.positionSource) && {\n positionSource: deepCopy(config.positionSource),\n }),\n ...(isDefined(config.containerProvider) && {\n containerProvider: deepCopy(config.containerProvider),\n }),\n timelineActions: config.timelineActions.map((actionConfig, index) =>\n resolveTimelineAction(\n importer,\n eventbus,\n services,\n actionConfig,\n `${path}.timelineActions[${index}]`,\n warn\n )\n ),\n };\n }\n );\n}\n\nfunction resolveOperation(\n importer: ISimpleResourceImporter,\n operationConfig: IOperationConfiguration<TOperationData>,\n path: string\n): IResolvedOperation {\n const {systemName} = operationConfig;\n let instance: unknown;\n try {\n instance = importer.import(systemName)?.[systemName];\n } catch (error) {\n // Importers may throw for unknown names (EligiusResourceImporter does);\n // report it like a missing entry so the message keeps the JSON path.\n throw new Error(createUnknownOperationMessage(importer, systemName, path), {\n cause: error,\n });\n }\n\n if (!isFunction(instance)) {\n throw new Error(createUnknownOperationMessage(importer, systemName, path));\n }\n\n // The importer also serves controllers, timeline providers and classes, which\n // are functions as well, but cannot be called as an operation.\n const notAnOperation = describeNonOperation(importer, systemName, instance);\n if (notAnOperation) {\n throw new Error(\n `Unknown operation '${systemName}' at ${path}.systemName. ${notAnOperation}`\n );\n }\n\n return {\n id: operationConfig.id,\n systemName,\n operationData: deepCopy(operationConfig.operationData) ?? {},\n instance,\n };\n}\n\n/**\n * Returns why the given importer export is not an operation, or `undefined`\n * when it may be one.\n */\nfunction describeNonOperation(\n importer: ISimpleResourceImporter,\n systemName: string,\n instance: (...args: any[]) => any\n): string | undefined {\n const isListedAs = (getterName: string) =>\n getImporterNames(importer, getterName).includes(systemName);\n\n if (!isListedAs('getOperationNames')) {\n if (isListedAs('getControllerNames')) {\n return `'${systemName}' is a controller, not an operation: attach it with the addControllerToElement operation.`;\n }\n if (isListedAs('getProviderNames')) {\n return `'${systemName}' is a timeline provider export, not an operation: configure it in timelineProviderSettings.`;\n }\n if (isListedAs('getFunctionNames')) {\n return `'${systemName}' is a custom function, not an operation: call it with the customFunction operation ({systemName: '${systemName}'}).`;\n }\n }\n if (isClass(instance)) {\n return `'${systemName}' is a class, not an operation function.`;\n }\n return undefined;\n}\n\nfunction isClass(value: (...args: any[]) => any): boolean {\n return /^class[\\s{]/.test(Function.prototype.toString.call(value));\n}\n\nfunction resolveOperations(\n importer: ISimpleResourceImporter,\n operationConfigs: IOperationConfiguration<TOperationData>[],\n path: string,\n warn: TWarn\n) {\n assertArray(operationConfigs, path);\n const resolved = operationConfigs.map((operationConfig, index) =>\n resolveOperation(importer, operationConfig, `${path}[${index}]`)\n );\n for (const problem of findFlowControlProblems(\n resolved.map(operation => operation.systemName)\n )) {\n warn({\n path: `${path}[${problem.index}].systemName`,\n message: `${problem.message} This will be a configuration error in the next major version.`,\n });\n }\n return resolved;\n}\n\nfunction createUnknownOperationMessage(\n importer: ISimpleResourceImporter,\n systemName: string,\n path: string\n) {\n const message = `Unknown operation '${systemName}' at ${path}.systemName.`;\n const knownNames = getImporterNames(importer, 'getOperationNames');\n const didYouMean = formatDidYouMean(\n findClosestNames(String(systemName), knownNames)\n );\n\n if (didYouMean) {\n return `${message} ${didYouMean}`;\n }\n return `${message} Check the spelling, or make sure the operation is available from the resource importer.`;\n}\n\n/**\n * Calls one of the optional `IResourceImporter` name getters, an empty list when\n * the importer does not have it.\n */\nfunction getImporterNames(\n importer: ISimpleResourceImporter,\n getterName: string\n): string[] {\n const getter = (importer as unknown as Record<string, unknown>)[getterName];\n if (isFunction(getter)) {\n const names = getter.call(importer);\n return Array.isArray(names) ? names : [];\n }\n return [];\n}\n\nfunction resolveActionConfiguration(\n config: IActionConfiguration,\n importer: ISimpleResourceImporter,\n path: string,\n warn: TWarn\n): IResolvedActionConfiguration {\n return {\n id: config.id,\n name: config.name,\n startOperations: resolveOperations(\n importer,\n config.startOperations,\n `${path}.startOperations`,\n warn\n ),\n };\n}\n\nfunction resolveEndableActionConfiguration(\n config: IEndableActionConfiguration,\n importer: ISimpleResourceImporter,\n path: string,\n warn: TWarn\n): IResolvedEndableActionConfiguration {\n const action = resolveActionConfiguration(config, importer, path, warn);\n\n return {\n ...action,\n endOperations: resolveOperations(\n importer,\n config.endOperations,\n `${path}.endOperations`,\n warn\n ),\n };\n}\n\n/**\n * Validates a timeline action duration: `start` is a number >= 0, `end` is\n * optional and, when given, not lower than `start`. An `end` of -1 marks an\n * open end, like a missing `end`.\n */\nfunction resolveDuration(duration: unknown, path: string): Required<IDuration> {\n if (!isObject(duration)) {\n throw new Error(\n `Invalid configuration at ${path}: expected {start: number, end?: number}, got ${describeValue(duration)}.`\n );\n }\n const {start, end} = duration;\n if (typeof start !== 'number' || !Number.isFinite(start) || start < 0) {\n throw new Error(\n `Invalid configuration at ${path}.start: expected a number >= 0, got ${describeValue(start)}.`\n );\n }\n if (!isDefined(end) || end === -1) {\n return {start, end: -1};\n }\n if (typeof end !== 'number' || !Number.isFinite(end)) {\n throw new Error(\n `Invalid configuration at ${path}.end: expected a number or no end, got ${describeValue(end)}.`\n );\n }\n if (end < start) {\n throw new Error(\n `Invalid configuration at ${path}.end: end (${end}) must not be lower than start (${start}).`\n );\n }\n return {start, end};\n}\n\nfunction resolveTimelineAction(\n importer: ISimpleResourceImporter,\n eventbus: IEventbus,\n services: IEngineServices,\n actionConfiguration: ITimelineActionConfiguration,\n path: string,\n warn: TWarn\n) {\n const duration = resolveDuration(\n actionConfiguration.duration,\n `${path}.duration`\n );\n const resolvedConfig = resolveEndableActionConfiguration(\n actionConfiguration,\n importer,\n path,\n warn\n );\n\n const {id, name, endOperations, startOperations} = resolvedConfig;\n const action = new TimelineAction(\n name,\n startOperations,\n endOperations,\n duration,\n eventbus,\n services\n );\n action.id = id;\n return action;\n}\n\nfunction resolveActions(\n actionConfigurations: IEndableActionConfiguration[],\n importer: ISimpleResourceImporter,\n eventbus: IEventbus,\n services: IEngineServices,\n path: string,\n warn: TWarn\n) {\n assertArray(actionConfigurations, path);\n const resolvedConfigs =\n actionConfigurations.map<IResolvedEndableActionConfiguration>(\n (config, index) => {\n return resolveEndableActionConfiguration(\n config,\n importer,\n `${path}[${index}]`,\n warn\n );\n }\n );\n\n return resolvedConfigs.map<EndableAction>(resolvedConfig => {\n const {name, endOperations, startOperations} = resolvedConfig;\n const action = new EndableAction(\n name,\n startOperations,\n endOperations,\n eventbus,\n services\n );\n action.id = resolvedConfig.id;\n return action;\n });\n}\n\n/**\n * `import` resolves the `template:` and `json:` placeholders, `config:` resolves the `config:` placeholders.\n */\ntype TPlaceholderPass = 'import' | 'config';\n\n/**\n * Walks arrays and plain data objects only. Class instances, jQuery objects and\n * other non-plain values (from the TypeScript API) are kept as they are.\n */\nfunction resolvePlaceholders(\n configFragment: Record<string, any> | any[],\n rootConfig: any,\n importer: ISimpleResourceImporter,\n pass: TPlaceholderPass,\n imported: WeakSet<object>,\n path: string\n) {\n if (!isDefined(configFragment) || imported.has(configFragment)) {\n return;\n }\n\n if (Array.isArray(configFragment)) {\n configFragment.forEach((_item, index) => {\n resolvePlaceholder(\n index,\n configFragment,\n rootConfig,\n importer,\n pass,\n imported,\n `${path}[${index}]`\n );\n });\n } else if (isPlainObject(configFragment)) {\n Object.keys(configFragment).forEach(key => {\n resolvePlaceholder(\n key,\n configFragment,\n rootConfig,\n importer,\n pass,\n imported,\n path ? `${path}.${key}` : key\n );\n });\n }\n}\n\nfunction resolvePlaceholder(\n key: PropertyKey,\n configFragment: any,\n rootConfig: any,\n importer: ISimpleResourceImporter,\n pass: TPlaceholderPass,\n imported: WeakSet<object>,\n path: string\n) {\n const configValue = configFragment[key];\n if (isString(configValue)) {\n if (pass === 'config') {\n if (configValue.startsWith('config:')) {\n configFragment[key] = resolveConfigPlaceholder(\n configValue,\n rootConfig,\n path\n );\n }\n } else if (configValue.startsWith('template:')) {\n const templateKey = configValue.substring(9, configValue.length);\n const template = importPlaceholder(\n importer,\n templateKey,\n configValue,\n path\n );\n configFragment[key] = template;\n } else if (configValue.startsWith('json:')) {\n const jsonKey = configValue.substring(5, configValue.length);\n // A copy, so the importer's own value is never rewritten when the\n // configuration is processed again\n const json = deepCopy(\n importPlaceholder(importer, jsonKey, configValue, path)\n );\n configFragment[key] = json;\n // Imported values are not walked for placeholders\n if (isPlainObject(json) || Array.isArray(json)) {\n imported.add(json);\n }\n }\n } else if (isPlainObject(configValue) || Array.isArray(configValue)) {\n resolvePlaceholders(\n configValue,\n rootConfig,\n importer,\n pass,\n imported,\n path\n );\n }\n}\n\n/**\n * Imports the value for a `template:` or `json:` placeholder. An importer that\n * throws for an unknown name gets its error wrapped, and an importer that returns\n * a record without an entry for the name is reported as an unknown name. Both\n * messages name the placeholder and its JSON path. An entry that is present but\n * `undefined` is accepted.\n */\nfunction importPlaceholder(\n importer: ISimpleResourceImporter,\n name: string,\n placeholder: string,\n path: string\n): unknown {\n let record: unknown;\n try {\n record = importer.import(name);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Unable to resolve placeholder '${placeholder}' at ${path}: ${reason}`,\n {cause: error}\n );\n }\n if (!isObject(record) || !Object.hasOwn(record, name)) {\n throw new Error(\n `Unable to resolve placeholder '${placeholder}' at ${path}: unknown name '${name}'.`\n );\n }\n return record[name];\n}\n\n/**\n * Resolves a `config:` placeholder against the root configuration. When the target\n * is itself a `config:` placeholder, that one is followed as well.\n *\n * @throws When the property chain cannot be resolved or yields `undefined`.\n */\nfunction resolveConfigPlaceholder(\n placeholder: string,\n rootConfig: any,\n path: string,\n visited: Set<string> = new Set()\n): any {\n if (visited.has(placeholder)) {\n throw new Error(\n `Circular config: placeholder '${placeholder}' at ${path} (chain: ${[...visited, placeholder].join(' -> ')})`\n );\n }\n visited.add(placeholder);\n\n const configProperty = placeholder.substring(7, placeholder.length);\n let value: unknown;\n try {\n value = resolvePropertyChain(configProperty, rootConfig);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Unable to resolve placeholder '${placeholder}' at ${path}: ${reason}`,\n {cause: error}\n );\n }\n if (value === undefined) {\n throw new Error(\n `Unable to resolve placeholder '${placeholder}' at ${path}: the configuration has no value at '${configProperty}'.`\n );\n }\n\n if (isString(value) && value.startsWith('config:')) {\n return resolveConfigPlaceholder(value, rootConfig, path, visited);\n }\n return value;\n}\n","import type {IEndableAction} from '@action/types.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\nimport type {TOperationData} from '@operation/types.ts';\nimport type {IEngineServices} from '@/engine-services.ts';\n\n/**\n * Helpers shared by the controllers that run configured actions in response\n * to an input (`DOMEventListenerController`, `KeyboardController`).\n */\n\n/**\n * An action to run, and whether its `start` (or `end`) operations run.\n */\nexport interface IControllerAction {\n start: boolean;\n action: IEndableAction;\n}\n\n/**\n * What makes a controller run its actions, used in error messages, such as\n * `{kind: 'DOM event', name: 'click'}`.\n */\nexport interface IControllerTrigger {\n kind: string;\n name: string;\n}\n\n/**\n * Splits off the `end:` prefix of an action name.\n *\n * @returns Whether the `start` operations run, and the action name\n */\nfunction parseActionName(actionName: string): [boolean, string] {\n return actionName.startsWith('end:')\n ? [false, actionName.substring('end:'.length)]\n : [true, actionName];\n}\n\n/**\n * Looks up the actions by name. A name prefixed with `end:` runs the `end`\n * operations of the action instead of its `start` operations.\n *\n * @param services - The engine services to look the actions up in\n * @param actionNames - The action names, optionally prefixed with `end:`\n * @param controllerName - The controller, named in error messages\n * @param trigger - What runs the actions, named in error messages\n * @returns The actions in the given order\n * @throws when an action name is unknown; the message names the controller,\n * the action and the trigger, and keeps the \"did you mean\" hint\n */\nexport function requestControllerActions(\n services: IEngineServices,\n actionNames: readonly string[],\n controllerName: string,\n trigger: IControllerTrigger\n): IControllerAction[] {\n return actionNames.map(actionName => {\n const [start, name] = parseActionName(actionName);\n const unknown = `${controllerName}: unknown action \"${name}\" for ${trigger.kind} \"${trigger.name}\"`;\n let action: IEndableAction | undefined;\n try {\n action = services.getAction(name) as IEndableAction;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(`${unknown}. ${reason}`, {cause: error});\n }\n if (!action) {\n throw new Error(unknown);\n }\n return {start, action};\n });\n}\n\n/**\n * Runs the actions one after another, merging each action's result into the\n * operation data for the next. A failing action stops the chain, since later\n * actions consume the earlier actions' output. The failure is reported\n * through the eventbus's `reportError` (an error naming the controller, the\n * action, the phase and the trigger, with the original error as `cause`), or\n * logged with `console.error` when the eventbus has no `reportError`. The\n * operation data is never logged.\n *\n * Never rejects, so an input handler leaves no floating rejection behind.\n *\n * @param actions - The actions to run\n * @param operationData - The operation data for the first action\n * @param controllerName - The controller, named in error messages\n * @param trigger - What runs the actions, named in error messages\n * @param eventbus - The eventbus to report failures through\n */\nexport async function runControllerActions(\n actions: readonly IControllerAction[],\n operationData: TOperationData,\n controllerName: string,\n trigger: IControllerTrigger,\n eventbus: IEventbus | null\n): Promise<void> {\n for (const {start, action} of actions) {\n try {\n const resultOperationData = start\n ? await action.start(operationData)\n : await action.end(operationData);\n Object.assign(operationData, resultOperationData);\n } catch (error) {\n const message = `${controllerName}: action '${action.name}' (${start ? 'start' : 'end'}) failed for ${trigger.kind} '${trigger.name}'`;\n if (eventbus && typeof eventbus.reportError === 'function') {\n eventbus.reportError(new Error(message, {cause: error}), {\n source: controllerName,\n });\n } else {\n console.error(message, error);\n }\n return;\n }\n }\n}\n","import {\n type IControllerAction,\n requestControllerActions,\n runControllerActions,\n} from '@controllers/helper/controller-actions.ts';\nimport type {IController} from '@controllers/types.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\nimport {deepCopy} from '@operation/helper/deep-copy.ts';\nimport type {TOperationData} from '@operation/types.ts';\nimport type {IEngineServices} from '@/engine-services.ts';\n\nexport interface IDOMEventListenerControllerOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @type=ParameterType:eventName\n * @required\n */\n eventName: string;\n actions: string[];\n /**\n * @type=ParameterType:object\n */\n actionOperationData?: TOperationData;\n}\n\n/**\n * This controller attaches to the given selected element and adds a DOM event listener for the specified event name that\n * executes the given actions with the given operation data.\n *\n * By default the `start` operations of the specified actions are executed. To execute the `end` operations instead,\n * prefix the action name with `end:`.\n *\n * The actions receive a copy of `actionOperationData` plus `eventTarget` (the event's target) and, for key events,\n * `eventKey` (the `KeyboardEvent.key`). They run in order, each receiving the operation data the previous one\n * returned. When an action fails, the\n * remaining actions are skipped and the failure is reported through the eventbus's `reportError` (an error naming\n * this controller, the action and the DOM event, with the original error as `cause`), or logged with\n * `console.error` when the eventbus has no `reportError`.\n */\nexport class DOMEventListenerController\n implements IController<IDOMEventListenerControllerOperationData>\n{\n operationData?: IDOMEventListenerControllerOperationData;\n actionInstanceInfos?: IControllerAction[];\n name = 'DOMEventListenerController';\n private _boundEventHandler: ((event: any) => void) | null = null;\n /** The eventbus passed to attach(), used to report failing actions */\n private _eventbus: IEventbus | null = null;\n\n init(operationData: IDOMEventListenerControllerOperationData) {\n this.operationData = {\n selectedElement: operationData.selectedElement,\n eventName: operationData.eventName,\n actions: operationData.actions.slice(),\n actionOperationData: deepCopy(operationData.actionOperationData),\n };\n }\n\n /**\n * Looks up the configured actions and starts listening for the DOM event.\n *\n * @param eventbus - The eventbus the actions report errors on\n * @param services - The engine services to look the actions up in\n * @throws when an action name is unknown; the message names the\n * controller, the action and the DOM event, and keeps the \"did you mean\"\n * hint\n */\n attach(eventbus: IEventbus, services: IEngineServices) {\n if (!this.operationData) {\n return;\n }\n\n const {selectedElement, actions, eventName} = this.operationData;\n if (!this.actionInstanceInfos) {\n this.actionInstanceInfos = requestControllerActions(\n services,\n actions,\n this.name,\n {kind: 'DOM event', name: eventName}\n );\n this._eventbus = eventbus;\n this._boundEventHandler = this._eventHandler.bind(this);\n selectedElement.on(eventName, this._boundEventHandler);\n }\n }\n\n private _eventHandler(event: any) {\n if (!this.operationData || !this.actionInstanceInfos) {\n return;\n }\n\n const actionOperationData = this.operationData.actionOperationData\n ? deepCopy(this.operationData.actionOperationData)\n : {};\n\n if (event?.target) {\n actionOperationData.eventTarget = event.target;\n }\n if (typeof event?.key === 'string') {\n actionOperationData.eventKey = event.key;\n }\n\n void runControllerActions(\n this.actionInstanceInfos,\n actionOperationData,\n this.name,\n {kind: 'DOM event', name: this.operationData.eventName},\n this._eventbus\n );\n }\n\n /**\n * Removes only the handler this controller registered, so other handlers for\n * the same event on the element keep working, and resets the action\n * instances so a later attach registers again.\n */\n detach(_eventbus: IEventbus) {\n if (this.operationData && this._boundEventHandler) {\n this.operationData.selectedElement.off(\n this.operationData.eventName,\n this._boundEventHandler\n );\n }\n this._boundEventHandler = null;\n this._eventbus = null;\n this.actionInstanceInfos = undefined;\n }\n}\n","import {\n type IControllerAction,\n type IControllerTrigger,\n requestControllerActions,\n runControllerActions,\n} from '@controllers/helper/controller-actions.ts';\nimport type {IController} from '@controllers/types.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\nimport {deepCopy} from '@operation/helper/deep-copy.ts';\nimport type {TOperationData} from '@operation/types.ts';\nimport {\n findInvalidKeyName,\n handlesKeyPress,\n type IKeyboardParticipant,\n joinKeyboardRegistry,\n pressedShortcutId,\n shortcutId,\n splitShortcuts,\n} from '@util/keyboard-input-registry.ts';\nimport hotkeys, {type HotkeysEvent, type KeyHandler} from 'hotkeys-js';\nimport type {IEngineServices} from '@/engine-services.ts';\n\n/**\n * Where a {@link KeyboardController} listens:\n * - `'document'`: while the focus is inside the engine root, or while\n * nothing has focus. With several engines on a page, a press while\n * nothing has focus runs the actions of one engine only: the engine the\n * user last clicked or focused inside, otherwise the first one that bound\n * the key.\n * - `'element'`: only while the focus is inside the selected element.\n */\nexport type TKeyboardControllerScope = 'document' | 'element';\n\nexport interface IKeyboardControllerOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * The keys that run the actions, in hotkeys-js syntax: comma separated\n * shortcuts such as `'right'`, `'shift+right'` or `'space, enter'`. Key\n * names are case insensitive. Accepted are the hotkeys-js names (`left`,\n * `up`, `right`, `down`, `space`, `enter`, `esc`, `tab`, `backspace`,\n * `del`, `ins`, `home`, `end`, `pageup`, `pagedown`, `f1` to `f19`,\n * `num_0` to `num_9`), the `KeyboardEvent.key` names of the same keys\n * (`ArrowLeft`, `ArrowUp`, `ArrowRight`, `ArrowDown`, `Enter`, `Escape`,\n * `Tab`, `Backspace`, `Delete`, `Insert`, `Home`, `End`, `PageUp`,\n * `PageDown`, `F1`), a single letter or digit, and the punctuation keys\n * `,` `.` `/` `;` `'` `[` `]` `-` `=`.\n * `' '` (the `KeyboardEvent.key` of the space bar) means `space`.\n * Modifiers: `shift`, `alt` (`option`), `ctrl` (`control`) and `meta`\n * (`cmd`, `command`).\n *\n * @type=ParameterType:string\n * @required\n */\n keys: string;\n actions: string[];\n /**\n * @type=ParameterType:object\n */\n actionOperationData?: TOperationData;\n /**\n * Defaults to `'document'`; see {@link TKeyboardControllerScope}.\n */\n scope?: TKeyboardControllerScope;\n}\n\n/**\n * Elements where a key press types, so it is left to the element.\n */\nconst editableSelector =\n 'input, select, textarea, [contenteditable]:not([contenteditable=\"false\"])';\n\nconst scopes: readonly TKeyboardControllerScope[] = ['document', 'element'];\n\n/**\n * This controller runs the given actions when one of the given keys is pressed.\n *\n * By default the `start` operations of the specified actions are executed. To execute the `end` operations instead,\n * prefix the action name with `end:`.\n *\n * The actions receive a copy of `actionOperationData` plus `eventTarget` (the focused element, or the body when\n * nothing has focus) and `eventKey` (the `KeyboardEvent.key`). They run in order, each receiving the operation data\n * the previous one returned. When an action fails, the remaining actions are skipped and the failure is reported\n * through the eventbus's `reportError`, or logged with `console.error` when the eventbus has no `reportError`.\n *\n * With `scope: 'document'` (the default) the keys work while the focus is inside the engine root, or while nothing\n * has focus. With `scope: 'element'` they only work while the focus is inside the selected element. Presses in\n * `input`, `select`, `textarea` and contenteditable elements are ignored, so typing keeps working. A handled press\n * has its default action prevented (no scrolling for arrow keys and space); a held key runs the actions once, not\n * again for every key repeat.\n *\n * When the keys include the play toggle hotkey of the engine (space by default), or a key that the engine's\n * KeyboardStepSource binds (the arrow keys, `shift+left`/`shift+right`, `home` and `end`), the controller wins: a\n * press it handles runs its actions and does not toggle playback or step the timeline. A press it ignores (for\n * example outside the selected element with `scope: 'element'`) still does.\n *\n * The keys are bound in the hotkeys-js `'all'` scope, so they work whatever scope a KeyboardStepSource sets. The\n * hotkeys-js global `filter` still applies. Detaching removes only this controller's handler.\n *\n * @example\n * ```json\n * {\"systemName\": \"addControllerToElement\", \"operationData\": {\"keys\": \"ArrowRight\", \"actions\": [\"NextChapter\"]}}\n * ```\n */\nexport class KeyboardController\n implements IController<IKeyboardControllerOperationData>\n{\n operationData?: IKeyboardControllerOperationData;\n actionInstanceInfos?: IControllerAction[];\n name = 'KeyboardController';\n private _handler: KeyHandler | null = null;\n private _leaveRegistry: (() => void) | null = null;\n /** The eventbus passed to attach(), used to report failing actions */\n private _eventbus: IEventbus | null = null;\n\n /**\n * @param operationData - The keys, actions and scope\n * @throws when `keys` is empty or names a key hotkeys-js can't match, or\n * when `scope` is not `'document'` or `'element'`\n */\n init(operationData: IKeyboardControllerOperationData) {\n const scope = operationData.scope ?? 'document';\n if (!scopes.includes(scope)) {\n throw new Error(\n `${this.name}: unknown scope '${String(scope)}'. Use 'document' or 'element'.`\n );\n }\n this.operationData = {\n selectedElement: operationData.selectedElement,\n keys: this._normalizeKeys(operationData.keys),\n actions: operationData.actions.slice(),\n actionOperationData: deepCopy(operationData.actionOperationData),\n scope,\n };\n }\n\n /**\n * Looks up the configured actions and starts listening for the keys.\n *\n * @param eventbus - The eventbus the actions report errors on\n * @param services - The engine services to look the actions and the engine\n * root up in\n * @throws when an action name is unknown; the message names the\n * controller, the action and the keys, and keeps the \"did you mean\" hint\n */\n attach(eventbus: IEventbus, services: IEngineServices) {\n if (!this.operationData || this.actionInstanceInfos) {\n return;\n }\n\n const {selectedElement, keys, actions, scope} = this.operationData;\n this.actionInstanceInfos = requestControllerActions(\n services,\n actions,\n this.name,\n this._trigger()\n );\n this._eventbus = eventbus;\n\n const element: Element | undefined = selectedElement[0];\n const root = this._engineRootElement(services) ?? element;\n const container = scope === 'element' ? element : root;\n const doc =\n element?.ownerDocument ??\n (typeof document === 'undefined' ? undefined : document);\n const participant: IKeyboardParticipant = {\n kind: 'controller',\n shortcutIds: splitShortcuts(keys).map(shortcutId),\n unfocused: scope === 'document',\n isReady: () => true,\n root: () => root,\n acceptsFocus: focused =>\n !focused.closest(editableSelector) &&\n (container?.contains(focused) ?? false),\n };\n if (doc) {\n this._leaveRegistry = joinKeyboardRegistry(doc, participant);\n }\n\n const handler = (event: KeyboardEvent, hotkeysEvent: HotkeysEvent) =>\n this._handleKey(event, hotkeysEvent, doc, participant);\n // Bind in the 'all' scope explicitly, and unbind from it explicitly:\n // without a scope hotkeys.unbind() uses the *current* scope, which a\n // KeyboardStepSource may have changed.\n hotkeys(keys, {scope: 'all'}, handler);\n this._handler = handler;\n }\n\n /**\n * Removes only the handler this controller bound, so other bindings of the\n * same keys keep working, and resets the action instances so a later\n * attach binds again.\n */\n detach(_eventbus: IEventbus) {\n if (this.operationData && this._handler) {\n hotkeys.unbind(this.operationData.keys, 'all', this._handler);\n }\n this._leaveRegistry?.();\n this._leaveRegistry = null;\n this._handler = null;\n this._eventbus = null;\n this.actionInstanceInfos = undefined;\n }\n\n private _handleKey(\n event: KeyboardEvent,\n hotkeysEvent: HotkeysEvent | undefined,\n doc: Document | undefined,\n participant: IKeyboardParticipant\n ) {\n if (!this.operationData || !this.actionInstanceInfos) {\n return;\n }\n const id = pressedShortcutId(hotkeysEvent, participant.shortcutIds);\n if (!handlesKeyPress(doc, participant, event, id)) {\n return;\n }\n event.preventDefault();\n if (event.repeat) {\n return;\n }\n\n const actionOperationData = this.operationData.actionOperationData\n ? deepCopy(this.operationData.actionOperationData)\n : {};\n actionOperationData.eventTarget = event.target;\n actionOperationData.eventKey = event.key;\n\n void runControllerActions(\n this.actionInstanceInfos,\n actionOperationData,\n this.name,\n this._trigger(),\n this._eventbus\n );\n }\n\n private _trigger(): IControllerTrigger {\n return {kind: 'key', name: this.operationData?.keys ?? ''};\n }\n\n private _engineRootElement(services: IEngineServices): Element | undefined {\n const root: Element | undefined = services.getEngineRoot()[0];\n return root && typeof root.contains === 'function' ? root : undefined;\n }\n\n /**\n * @returns The keys with `' '` replaced by `space`\n * @throws when the keys are empty or name a key hotkeys-js can't match\n */\n private _normalizeKeys(keys: unknown): string {\n if (typeof keys !== 'string' || keys.length === 0) {\n throw new Error(\n `${this.name}: 'keys' must be a non-empty string of hotkeys-js shortcuts, such as 'right' or 'shift+right, space'.`\n );\n }\n // ' ' is the KeyboardEvent.key of the space bar, hotkeys-js drops\n // whitespace\n const normalized = keys.trim() === '' ? 'space' : keys;\n for (const shortcut of splitShortcuts(normalized)) {\n const invalid = findInvalidKeyName(shortcut);\n if (invalid !== undefined) {\n throw new Error(\n `${this.name}: unknown key '${invalid}' in keys '${keys}'. Use hotkeys-js names such as 'right', 'space', 'enter' or 'shift+a', or KeyboardEvent.key names such as 'ArrowRight' or 'Escape'.`\n );\n }\n }\n return normalized;\n }\n}\n","import type {IController} from '@controllers/types.js';\nimport type {\n EventMap,\n EventName,\n IEventbus,\n TEventbusRemover,\n} from '@eventbus/types.js';\nimport type {TOperationData} from '@operation/types.js';\nimport type {IEngineServices} from '@/engine-services.ts';\n\n/**\n * Abstract base class for controllers providing standardized event listener management\n *\n * Benefits:\n * - Eliminates boilerplate event listener tracking code\n * - Automatic binding of event handlers to controller instance\n * - Handler arguments are type checked against the event's argument tuple\n * - Centralized cleanup preventing memory leaks\n * - An attached-state guard, so a second attach never duplicates listeners\n *\n * @example\n * ```typescript\n * class MyController extends BaseController<IMyOperationData> {\n * name = 'MyController';\n *\n * init(operationData: IMyOperationData): void {\n * this.operationData = operationData;\n * }\n *\n * attach(eventbus: IEventbus): void {\n * this.beginAttach(eventbus);\n * this.addListener(eventbus, 'timeline-time', this.handleTime);\n * // Handler automatically bound, cleanup tracked\n * }\n *\n * private handleTime(position: number): void {\n * // 'this' context preserved\n * }\n * }\n * ```\n */\nexport abstract class BaseController<T extends TOperationData>\n implements IController<T>\n{\n // Public properties (required by IController)\n public operationData: T | null = null;\n public abstract name: string;\n\n // Protected state\n protected eventListeners: TEventbusRemover[] = [];\n /** True between {@link BaseController.beginAttach} and the next detach. */\n protected isAttached = false;\n\n /**\n * Register event listener with automatic binding and cleanup tracking\n *\n * @param eventbus - The eventbus to register with\n * @param eventName - Name of the event to listen for\n * @param handler - Event handler function (will be bound to this controller).\n * Its parameters must match the event's argument tuple.\n */\n protected addListener<E extends EventName>(\n eventbus: IEventbus,\n eventName: E,\n handler: (this: this, ...args: EventMap[E]) => void\n ): void {\n const boundHandler = handler.bind(this) as (...args: EventMap[E]) => void;\n const remover = eventbus.on(eventName, boundHandler);\n this.eventListeners.push(remover);\n }\n\n /**\n * Call at the start of `attach`. When the controller is still attached, it\n * is detached first, so attaching twice replaces the previous attachment\n * instead of registering every listener (and any DOM it builds) twice.\n *\n * @param eventbus - The eventbus passed to `attach`\n */\n protected beginAttach(eventbus: IEventbus): void {\n if (this.isAttached) {\n this.detach(eventbus);\n }\n this.isAttached = true;\n }\n\n /**\n * Clean up all tracked event listeners\n * Prevents memory leaks by removing all registered handlers\n *\n * @param _eventbus - The eventbus (ignored, included for IController compatibility)\n */\n public detach(_eventbus: IEventbus): void {\n this.eventListeners.forEach(remover => remover());\n this.eventListeners = [];\n this.isAttached = false;\n }\n\n // Abstract methods (must be implemented by subclasses)\n public abstract init(operationData: T): void;\n public abstract attach(\n eventbus: IEventbus,\n services: IEngineServices\n ): Promise<any> | void;\n}\n","import {BaseController} from '@controllers/base-controller.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\nimport {\n isSafeUrl,\n sanitizeHtml,\n URL_ATTRIBUTE_NAMES,\n} from '@util/sanitize-html.ts';\n\nexport interface ILabelControllerMetadata {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * Translation key for rosetta-based locale system.\n * Example: 'nav.home', 'buttons.submit'\n * @required\n */\n translationKey: string;\n /**\n * By default the label is added to the inner HTML of the `selectedElement`,\n * after sanitizing: inline formatting such as `<br>`, `<strong>`, `<em>`\n * and links is kept, scripts, event handlers and other markup are removed.\n * If this property is set, the label is written as plain text to the\n * specified attribute of the `selectedElement` instead. Event handler\n * attributes (`on*`) and `srcdoc` are rejected, and URL attributes such as\n * `href` and `src` are only set when the translation is a safe URL.\n */\n attributeName?: string;\n}\n\n/**\n * Attribute names whose value the browser runs as script or renders as a\n * document. Translations are never written to them.\n */\nconst FORBIDDEN_ATTRIBUTE_PATTERN = /^(on.*|srcdoc)$/i;\n\n/**\n * This controller attaches to the given selected element and renders the text\n * associated with the given translation key.\n *\n * Translations may contain simple inline markup. They are passed through\n * `sanitizeHtml` before insertion, so `<br>`, `<strong>`, `<em>`,\n * `<span>` and http(s)/mailto/relative links render, while scripts, event\n * handlers, `javascript:` URLs, images, iframes and SVG are removed.\n *\n * The controller listens for the `language-change` event and re-renders the text\n * with the new language after such an event.\n *\n * Uses the rosetta-based locale system via `request-translation` event.\n */\nexport class LabelController extends BaseController<ILabelControllerMetadata> {\n name = 'LabelController';\n private _eventbus: IEventbus | null = null;\n\n /**\n * @throws Error when `attributeName` is an event handler attribute\n * (`on*`) or `srcdoc`.\n */\n init(operationData: ILabelControllerMetadata) {\n const {attributeName} = operationData;\n if (attributeName && FORBIDDEN_ATTRIBUTE_PATTERN.test(attributeName)) {\n throw new Error(\n `LabelController: attributeName \"${attributeName}\" cannot receive a translation, because the browser would run or render it as code. Use a text attribute such as \"title\" or \"aria-label\".`\n );\n }\n this.operationData = Object.assign({}, operationData);\n }\n\n /**\n * Sets the translation key and re-renders the label.\n */\n setTranslationKey(newKey: string) {\n if (this.operationData) {\n this.operationData.translationKey = newKey;\n this._setLabel();\n }\n }\n\n attach(eventbus: IEventbus) {\n if (!this.operationData) {\n return;\n }\n\n this.beginAttach(eventbus);\n this._eventbus = eventbus;\n this._setLabel();\n this.addListener(eventbus, 'language-change', this._handleLanguageChange);\n }\n\n private _setLabel() {\n if (!this._eventbus || !this.operationData?.translationKey) {\n return;\n }\n\n const text =\n this._eventbus.request<string>(\n 'request-translation',\n this.operationData.translationKey\n ) ?? '';\n this._applyText(text);\n }\n\n private _applyText(text: string) {\n if (!this.operationData) {\n return;\n }\n const {selectedElement, attributeName} = this.operationData;\n if (!attributeName) {\n selectedElement.html(sanitizeHtml(text));\n } else if (\n URL_ATTRIBUTE_NAMES.has(attributeName.toLowerCase()) &&\n !isSafeUrl(text)\n ) {\n selectedElement.removeAttr(attributeName);\n } else {\n selectedElement.attr(attributeName, text);\n }\n }\n\n detach(eventbus: IEventbus) {\n super.detach(eventbus);\n this._eventbus = null;\n }\n\n private _handleLanguageChange(_code: string) {\n this._setLabel();\n }\n}\n","import {BaseController} from '@controllers/base-controller.ts';\nimport type {\n ILottieAnimationItem,\n TLottieRendererConfig,\n} from '@controllers/types.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\n// lottie-web is an optional peer, so only the implementation below uses its\n// types. Public members use the structural types from controllers/types.ts,\n// which keeps lottie-web out of the published declarations.\nimport type {AnimationConfigWithData, LottiePlayer} from 'lottie-web';\nimport type {TLanguageCode} from '../types.ts';\n\nlet lottieLoader: Promise<LottiePlayer> | null = null;\n\n/**\n * Loads lottie-web, an optional peer dependency, on first use and caches it.\n * A failed load is not cached, so a later attach can try again.\n *\n * @returns the lottie player\n * @throws when lottie-web cannot be imported\n */\nfunction loadLottie(): Promise<LottiePlayer> {\n lottieLoader ??= import('lottie-web').then(\n module => {\n // Depending on the bundler's CommonJS interop, the player is the\n // module's default export or sits one `default` deeper\n const exported = module.default as LottiePlayer & {\n default?: LottiePlayer;\n };\n return exported.default ?? exported;\n },\n (error: unknown) => {\n lottieLoader = null;\n throw new Error(\n \"LottieController requires the optional peer dependency 'lottie-web'. Install it with: npm install lottie-web\",\n {cause: error}\n );\n }\n );\n return lottieLoader;\n}\n\nconst UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\n\nfunction isUnsafeKey(key: string): boolean {\n return UNSAFE_KEYS.has(key);\n}\n\nexport interface IInnerMetadata {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @type=ParameterType:string\n */\n renderer: TLottieRendererConfig;\n loop: boolean;\n autoplay: boolean;\n /**\n * The lottie animation data. Give either this or `json`; `json` wins when\n * both are set.\n *\n * @type=ParameterType:object\n */\n animationData: any;\n /**\n * The lottie animation data. Give either this or `animationData`.\n */\n json: any;\n /**\n * @type=ParameterType:array\n * @itemType=ParameterType:labelId\n */\n labelIds: string[];\n viewBox: string;\n /**\n * @deprecated Ignored: the fallback targeted Internet Explorer and legacy\n * Edge, which are no longer supported. Will be removed in the next major\n * version.\n */\n iefallback: any;\n}\n\nexport interface ILottieControllerMetadata extends IInnerMetadata {\n /**\n * The animation file name. It is not loaded; it is only read for freeze and\n * end markers, like `my-url/filename[freeze=10,end=21].json`.\n *\n * @type=ParameterType:url\n */\n url?: string;\n}\n\n/**\n * This controller renders a [lottie-web](https://github.com/airbnb/lottie-web) animation inside the given selected element.\n *\n * The url may encode freeze and end positions like this: my-url/filename[freeze=10,end=21].json\n *\n * lottie-web is an optional peer dependency. It is loaded with a dynamic\n * `import()` the first time a LottieController attaches, so applications that\n * never use this controller do not need it installed.\n */\nexport class LottieController extends BaseController<ILottieControllerMetadata> {\n name = 'LottieController';\n currentLanguage: TLanguageCode = 'nl-NL';\n /**\n * @deprecated Label collections come from a `request-label-collections`\n * responder, which nothing in Eligius provides since the labels array was\n * removed in 2.2.0. Use translation keys as label ids instead; they resolve\n * through `request-translation`. Will be removed in the next major version.\n */\n labelData: Record<string, Record<string, string>> = {};\n animationItem: ILottieAnimationItem | null = null;\n serializedData: string | null = null;\n /**\n * @deprecated Never used: see `iefallback`. Will be removed in the next\n * major version.\n */\n serializedIEData: string | null = null;\n freezePosition = -1;\n endPosition = -1;\n private _eventbus: IEventbus | null = null;\n private _lottie: LottiePlayer | null = null;\n /** Incremented by detach() so an attach still loading lottie-web gives up */\n private _attachGeneration = 0;\n\n /**\n * @throws when neither `json` nor `animationData` is given\n */\n init(operationData: ILottieControllerMetadata) {\n this.operationData = {...operationData};\n\n const animationData =\n this.operationData.json || this.operationData.animationData;\n if (!animationData) {\n throw new Error(\n `${this.name}: provide the animation as 'json' or 'animationData'`\n );\n }\n\n if (operationData.url?.includes('[')) {\n this._parseFilename(operationData.url);\n }\n\n this.serializedData = JSON.stringify(animationData);\n\n if (this.operationData.iefallback) {\n this.serializedIEData = JSON.stringify(this.operationData.iefallback);\n }\n }\n\n private _parseFilename(name: string) {\n const startIndex = name.indexOf('[') + 1;\n const endIndex = name.indexOf(']');\n const params = name.substring(startIndex, endIndex);\n\n const settings = params.split(',');\n\n settings.forEach(setting => {\n const values = setting.split('=');\n if (values[0] === 'freeze') {\n this.freezePosition = +values[1];\n } else if (values[0] === 'end') {\n this.endPosition = +values[1];\n }\n });\n }\n\n /**\n * Loads lottie-web (on first use), registers the language listener when\n * label ids are configured and creates the animation.\n *\n * If detach() is called before lottie-web has loaded, the attach is\n * abandoned: no listeners are registered and no animation is created.\n *\n * @param eventbus - The eventbus to request labels and language from\n * @returns a promise that resolves once the animation has been created\n * @throws when the optional peer dependency lottie-web cannot be loaded\n */\n async attach(eventbus: IEventbus): Promise<void> {\n if (!this.operationData) {\n return;\n }\n\n // A second attach (also one made while the first is still loading\n // lottie-web) detaches first, which makes the earlier attach give up.\n this.beginAttach(eventbus);\n const generation = this._attachGeneration;\n const lottie = await loadLottie();\n if (generation !== this._attachGeneration || !this.operationData) {\n return;\n }\n\n this._lottie = lottie;\n this._eventbus = eventbus;\n\n const {labelIds} = this.operationData;\n if (labelIds?.length) {\n this.currentLanguage =\n eventbus.request<TLanguageCode>('request-current-language') ?? 'en-US';\n this.addListener(eventbus, 'language-change', this._handleLanguageChange);\n // Deprecated path (see labelData): only a host-provided responder\n // answers this request\n const labelCollections =\n eventbus.request<any[]>(\n 'request-label-collections',\n this.operationData.labelIds\n ) ?? [];\n this._createTextDataLookup(labelCollections);\n }\n this._createAnimation();\n }\n\n /**\n * Removes the listeners and releases the lottie animation.\n *\n * When the url configured a freeze position and the animation does not loop,\n * the animation first plays out from the freeze position to the end position\n * (or its natural end) and is destroyed when it completes. Otherwise it is\n * destroyed immediately, since a looping animation never completes.\n */\n detach(eventbus: IEventbus) {\n super.detach(eventbus);\n this._attachGeneration++;\n this._eventbus = null;\n\n const animationItem = this.animationItem;\n if (!animationItem) {\n return;\n }\n\n if (this.freezePosition > -1 && !this.operationData?.loop) {\n const endPosition =\n this.endPosition > -1 ? this.endPosition : animationItem.timeCompleted;\n animationItem.addEventListener('complete', () => {\n animationItem.destroy();\n if (this.animationItem === animationItem) {\n this.animationItem = null;\n }\n });\n animationItem.playSegments([this.freezePosition, endPosition], true);\n } else {\n animationItem.destroy();\n this.animationItem = null;\n }\n }\n\n private _createAnimation() {\n if (!this.operationData || !this.serializedData || !this._lottie) {\n return;\n }\n\n this.animationItem?.destroy();\n let serialized = this.serializedData;\n\n const {labelIds} = this.operationData;\n if (labelIds?.length) {\n // O(n) regex-based replacement - single pass through string\n // Replaces all !!labelId!! patterns in one operation\n serialized = serialized.replace(/!!([^!]+)!!/g, (match, labelId) => {\n const text = this._resolveLabel(labelId);\n // The placeholder sits inside a JSON string literal, so escape the text\n return text === undefined ? match : JSON.stringify(text).slice(1, -1);\n });\n }\n const animationData = JSON.parse(serialized);\n\n const animationSettings: AnimationConfigWithData<'svg'> = {\n autoplay: this.operationData.autoplay,\n container: this.operationData.selectedElement[0],\n loop: this.operationData.loop,\n rendererSettings: this.operationData.renderer,\n animationData,\n };\n\n this.animationItem = this._lottie.loadAnimation(animationSettings);\n\n if (this.freezePosition > -1) {\n this.animationItem.playSegments([0, this.freezePosition], true);\n }\n if (this.operationData.viewBox) {\n this.operationData.selectedElement\n .find('svg')\n .attr('viewBox', this.operationData.viewBox);\n }\n }\n\n private _createTextDataLookup(data: any[]) {\n data.forEach((infos, index) => {\n const labelId = this.operationData?.labelIds[index];\n if (!labelId || isUnsafeKey(labelId) || !Array.isArray(infos)) {\n return;\n }\n if (!Object.hasOwn(this.labelData, labelId)) {\n this.labelData[labelId] = {};\n }\n const languageLookup = this.labelData[labelId];\n infos.forEach((d: any) => {\n if (typeof d?.code === 'string' && !isUnsafeKey(d.code)) {\n languageLookup[d.code] = d.label;\n }\n });\n });\n }\n\n /**\n * Resolves the text for a label id in the current language. Label collections\n * take precedence; otherwise the label id is looked up as a translation key\n * through the locale manager (`request-translation`).\n *\n * @returns the text, or undefined when no text is available\n */\n private _resolveLabel(labelId: string): string | undefined {\n if (Object.hasOwn(this.labelData, labelId)) {\n const languageLookup = this.labelData[labelId];\n if (Object.hasOwn(languageLookup, this.currentLanguage)) {\n return languageLookup[this.currentLanguage];\n }\n }\n\n if (!this.operationData?.labelIds.includes(labelId)) {\n return undefined;\n }\n\n const translation = this._eventbus?.request<string>(\n 'request-translation',\n labelId\n );\n return translation ? translation : undefined;\n }\n\n /**\n * Rebuilds the animation with the texts of the new language and moves it to\n * the frame the old one was at, playing or paused as before, so a language\n * switch does not restart it. Frames are counted from the start of the\n * current segment, which for the freeze segment is frame 0.\n */\n private _handleLanguageChange(code: TLanguageCode) {\n this.currentLanguage = code;\n const previous = this.animationItem;\n const frame = previous?.currentFrame;\n const wasPaused = previous?.isPaused;\n\n this._createAnimation();\n\n const item = this.animationItem;\n if (!item || item === previous || typeof frame !== 'number') {\n return;\n }\n if (wasPaused) {\n item.goToAndStop(frame, true);\n } else {\n item.goToAndPlay(frame, true);\n }\n }\n}\n","import {BaseController} from '@controllers/base-controller.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\n\n/**\n * Metadata configuration for MutationObserverController\n *\n * Configures what types of DOM mutations to observe and how to observe them.\n */\nexport interface IMutationObserverControllerMetadata {\n /**\n * jQuery-wrapped DOM element to observe for mutations\n * @dependency\n * @required\n */\n selectedElement: JQuery;\n\n /**\n * Observe changes to element attributes\n * @optional\n * @default true\n */\n observeAttributes?: boolean;\n\n /**\n * Observe additions and removals of child nodes\n * @optional\n * @default true\n */\n observeChildList?: boolean;\n\n /**\n * Observe changes to text content (character data)\n * @optional\n * @default true\n */\n observeCharacterData?: boolean;\n\n /**\n * Observe mutations in the entire subtree (all descendants)\n * @optional\n * @default false\n */\n observeSubtree?: boolean;\n\n /**\n * Record the previous value of attributes that change\n * Requires observeAttributes to be true\n * @optional\n * @default false\n */\n attributeOldValue?: boolean;\n\n /**\n * Record the previous value of text content that changes\n * Requires observeCharacterData to be true\n * @optional\n * @default false\n */\n characterDataOldValue?: boolean;\n\n /**\n * Array of specific attribute local names to observe\n * If omitted, all attribute changes are observed when observeAttributes is true\n * @optional\n */\n attributeFilter?: string[];\n}\n\n/**\n * Mutation event payload broadcasted through Eligius eventbus\n */\nexport interface IMutationEventPayload {\n /**\n * Array of mutation records from the MutationObserver callback\n */\n mutations: MutationRecord[];\n\n /**\n * Reference to the observed element (native DOM node)\n */\n target: Element;\n\n /**\n * Timestamp when the mutations were detected\n */\n timestamp: number;\n}\n\n/**\n * Controller that observes DOM mutations on a selected element and broadcasts events.\n *\n * This controller creates a MutationObserver to monitor DOM changes (attributes, child nodes,\n * text content) on a specified element. All detected mutations are broadcasted through the\n * Eligius eventbus, enabling reactive behavior in response to DOM changes.\n *\n * The controller follows the standard Eligius lifecycle:\n * - init(): Store configuration metadata\n * - attach(): Create and start the MutationObserver\n * - detach(): Disconnect the observer and clean up resources\n *\n * @example\n * ```typescript\n * // JSON configuration\n * {\n * \"systemName\": \"addControllerToElement\",\n * \"operationData\": {\n * \"controllerName\": \"MutationObserverController\",\n * \"observeAttributes\": true,\n * \"observeChildList\": true,\n * \"observeCharacterData\": false\n * }\n * }\n *\n * // Listen for mutations\n * eventbus.on('dom-mutation', (payload: IMutationEventPayload) => {\n * console.log('Mutations detected:', payload.mutations);\n * });\n * ```\n */\nexport class MutationObserverController extends BaseController<IMutationObserverControllerMetadata> {\n name = 'MutationObserverController';\n private observer: MutationObserver | null = null;\n\n /**\n * Initialize the controller with configuration metadata.\n *\n * @param operationData - Configuration for observation behavior\n * @throws when the options would make `MutationObserver.observe` throw:\n * nothing to observe, or an attribute or character data option without the\n * matching observe flag\n */\n init(operationData: IMutationObserverControllerMetadata): void {\n this.operationData = Object.assign({}, operationData);\n this._buildObserverOptions();\n }\n\n /**\n * Attach the controller and start observing mutations.\n * Creates MutationObserver instance and begins monitoring the target element.\n * Attaching again replaces the previous observer.\n *\n * @param eventbus - Eligius eventbus for broadcasting mutation events\n */\n attach(eventbus: IEventbus): void {\n if (!this.operationData) {\n return;\n }\n\n // Unwrap jQuery element to get native DOM node\n const nativeElement = this.operationData.selectedElement.get(0);\n if (!nativeElement) {\n return;\n }\n\n // Disconnects an observer left by a previous attach\n this.beginAttach(eventbus);\n\n // Build observer options from metadata\n const options = this._buildObserverOptions();\n\n // Create MutationObserver with bound callback\n this.observer = new MutationObserver(\n this._handleMutations.bind(this, eventbus, nativeElement)\n );\n\n // Start observing the target element\n this.observer.observe(nativeElement, options);\n }\n\n /**\n * Detach the controller and stop observing mutations.\n * Disconnects MutationObserver and cleans up resources.\n *\n * @param eventbus - Eligius eventbus (used by BaseController for cleanup)\n */\n detach(eventbus: IEventbus): void {\n // Disconnect and clean up observer\n if (this.observer) {\n this.observer.disconnect();\n this.observer = null;\n }\n\n // Call parent detach for event listener cleanup\n super.detach(eventbus);\n }\n\n /**\n * Build MutationObserverInit options from controller metadata.\n * Applies default values for optional configuration properties, and leaves\n * out `attributeFilter` when it is not configured.\n *\n * @returns MutationObserverInit options object\n * @throws when the combination of options is invalid\n * @private\n */\n private _buildObserverOptions(): MutationObserverInit {\n if (!this.operationData) {\n return {};\n }\n\n const {\n observeAttributes = true,\n observeChildList = true,\n observeCharacterData = true,\n observeSubtree = false,\n attributeOldValue = false,\n characterDataOldValue = false,\n attributeFilter,\n } = this.operationData;\n\n const fail = (message: string): never => {\n throw new Error(`${this.name}: ${message}`);\n };\n if (!observeAttributes && !observeChildList && !observeCharacterData) {\n fail(\n 'at least one of observeAttributes, observeChildList or observeCharacterData must be true'\n );\n }\n if (!observeAttributes && attributeFilter !== undefined) {\n fail('attributeFilter requires observeAttributes');\n }\n if (!observeAttributes && attributeOldValue) {\n fail('attributeOldValue requires observeAttributes');\n }\n if (!observeCharacterData && characterDataOldValue) {\n fail('characterDataOldValue requires observeCharacterData');\n }\n\n const options: MutationObserverInit = {\n attributes: observeAttributes,\n childList: observeChildList,\n characterData: observeCharacterData,\n subtree: observeSubtree,\n attributeOldValue,\n characterDataOldValue,\n };\n if (attributeFilter !== undefined) {\n options.attributeFilter = attributeFilter;\n }\n return options;\n }\n\n /**\n * Handle mutations detected by the MutationObserver.\n * Broadcasts mutation events through the eventbus with mutation details.\n *\n * @param eventbus - Eligius eventbus for broadcasting\n * @param target - The observed element\n * @param mutations - Array of mutation records from observer callback\n * @private\n */\n private _handleMutations(\n eventbus: IEventbus,\n target: Element,\n mutations: MutationRecord[]\n ): void {\n const payload: IMutationEventPayload = {\n mutations,\n target,\n timestamp: Date.now(),\n };\n\n eventbus.broadcast('dom-mutation', [payload]);\n }\n}\n","import type {IEventbus} from '@eventbus/types.ts';\nimport {deepCopy} from '@operation/helper/deep-copy.ts';\n\n/**\n * The navigation lookups shared by NavigationController and RoutingController.\n */\nexport interface INavigationData {\n /** The root entries, in `roots` order */\n roots: any[];\n /** Entries by `id` */\n navLookup: Record<string, any>;\n /** Entries by `videoUrlIndex` */\n navVidIdLookup: Record<string, any>;\n}\n\n/**\n * Builds the navigation entries from a navigation json\n * (`{navigationData: [...], roots: [...]}`).\n *\n * The json is copied first and never changed, so several controllers can be\n * initialised with the same json object. Every entry gets `previous` and\n * `next` links (`next` follows `nextId` when given, otherwise the next entry\n * in `navigationData`), and the `children` ids of every entry, at any depth,\n * are replaced by the entries they name.\n *\n * @param json - The navigation json\n * @param controllerName - Named in error messages\n * @returns the root entries and the lookups\n * @throws when the json has no `navigationData` array, or when `roots`,\n * `nextId` or `children` name an unknown navigation id\n */\nexport function buildNavigationData(\n json: any,\n controllerName: string\n): INavigationData {\n if (!Array.isArray(json?.navigationData)) {\n throw new Error(\n `${controllerName}: json.navigationData must be an array of navigation entries`\n );\n }\n\n const entries: any[] = deepCopy(json.navigationData);\n const navLookup: Record<string, any> = {};\n const navVidIdLookup: Record<string, any> = {};\n\n entries.forEach((nav, index) => {\n navLookup[nav.id] = nav;\n navVidIdLookup[nav.videoUrlIndex] = nav;\n nav.previous = entries[index - 1];\n });\n\n const find = (id: unknown, location: string) => {\n if (typeof id === 'string' && Object.hasOwn(navLookup, id)) {\n return navLookup[id];\n }\n throw new Error(\n `${controllerName}: unknown navigation id '${String(id)}' in ${location}`\n );\n };\n\n entries.forEach((nav, index) => {\n nav.next = nav.nextId\n ? find(nav.nextId, `nextId of '${nav.id}'`)\n : entries[index + 1];\n\n if (Array.isArray(nav.children)) {\n nav.children = nav.children.map((child: unknown) =>\n find(\n typeof child === 'object' && child !== null\n ? (child as {id?: unknown}).id\n : child,\n `children of '${nav.id}'`\n )\n );\n }\n });\n\n const rootIds: unknown[] = Array.isArray(json.roots) ? json.roots : [];\n const roots = rootIds.map(id => find(id, 'roots'));\n\n return {roots, navLookup, navVidIdLookup};\n}\n\n/**\n * Asks for the content of a navigation entry.\n *\n * An entry with a `timelineUri` is requested from the engine with\n * `request-timeline-uri` [timelineUri, position]. An entry without one falls\n * back to the legacy `request-video-url` [videoUrlIndex, position], which the\n * engine does not handle, so the host has to.\n *\n * @param eventbus - The eventbus to broadcast on\n * @param nav - The navigation entry\n * @param position - The start position in seconds\n * @param isHistoryRequest - Passed on as the third `request-video-url`\n * argument; the timeline request has no such argument\n */\nexport function requestNavigation(\n eventbus: IEventbus,\n nav: any,\n position: number,\n isHistoryRequest = false\n): void {\n if (typeof nav.timelineUri === 'string' && nav.timelineUri.length > 0) {\n eventbus.broadcast('request-timeline-uri', [nav.timelineUri, position]);\n } else if (isHistoryRequest) {\n eventbus.broadcast('request-video-url', [\n nav.videoUrlIndex,\n position,\n true,\n ]);\n } else {\n eventbus.broadcast('request-video-url', [nav.videoUrlIndex, position]);\n }\n}\n","import {BaseController} from '@controllers/base-controller.ts';\nimport {\n buildNavigationData,\n requestNavigation,\n} from '@controllers/helper/navigation-data.ts';\nimport type {LabelController} from '@controllers/label-controller.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\nimport $ from 'jquery';\nimport type {IEngineServices} from '@/engine-services.ts';\nimport type {TResultCallback} from '../types.ts';\n\nexport interface INavigationControllerOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * The navigation json: `{navigationData: [...], roots: [...]}`. Each entry\n * has an `id`, a `labelId`, a `videoUrlIndex` and optionally `visible`,\n * `children` (ids), `nextId`, `autoNext` and `timelineUri`. Give an entry a\n * `timelineUri` to let the engine switch to that timeline when the entry is\n * activated.\n *\n * @required\n */\n json: any;\n}\n\nconst CURRENT_CLASS = 'current-menu-item';\n\n/**\n * Renders a navigation menu in the selected element and keeps it in sync with\n * the active navigation entry.\n *\n * Activating a menu item (click, Enter or Space) navigates to its entry:\n * - an entry with a `timelineUri` broadcasts `request-timeline-uri`\n * [timelineUri, position], which the engine handles by switching timelines;\n * - an entry without one broadcasts the legacy `request-video-url`\n * [videoUrlIndex, position], which the engine does not handle.\n *\n * With `autoNext`, the next entry is started when the active entry's timeline\n * completes (`timeline-complete`) or, for legacy entries, on `video-complete`.\n * When the engine switches to a timeline that an entry names\n * (`timeline-current-timeline-change`), that entry becomes the active one.\n */\nexport class NavigationController extends BaseController<INavigationControllerOperationData> {\n name: string = 'NavigationController';\n navigation: any[] = [];\n navLookup: Record<string, any> = {};\n navVidIdLookup: Record<string, any> = {};\n ctrlLookup: Record<string, LabelController> = {};\n activeNavigationPoint: any = null;\n labelControllers: LabelController[] = [];\n eventbus: IEventbus | null = null;\n services: IEngineServices | null = null;\n container: JQuery | null = null;\n private _menuElement: JQuery | null = null;\n private _anchorLookup = new Map<any, JQuery>();\n private _highlightedAnchor: JQuery | null = null;\n private _navByTimelineUri = new Map<string, any>();\n\n /**\n * @throws when the json has no navigationData array or names an unknown\n * navigation id in roots, nextId or children\n */\n init(operationData: INavigationControllerOperationData) {\n this.operationData = operationData;\n this.container = operationData.selectedElement;\n const {roots, navLookup, navVidIdLookup} = buildNavigationData(\n operationData.json,\n this.name\n );\n this.navigation = roots;\n this.navLookup = navLookup;\n this.navVidIdLookup = navVidIdLookup;\n this._navByTimelineUri.clear();\n Object.values(navLookup).forEach(nav => {\n if (\n typeof nav.timelineUri === 'string' &&\n !this._navByTimelineUri.has(nav.timelineUri)\n ) {\n this._navByTimelineUri.set(nav.timelineUri, nav);\n }\n });\n }\n\n attach(eventbus: IEventbus, services: IEngineServices) {\n if (!this.container) {\n return;\n }\n\n this.beginAttach(eventbus);\n this.eventbus = eventbus;\n this.services = services;\n\n this.addListener(\n eventbus,\n 'navigate-to-video-url',\n this._handleNavigateVideoUrl\n );\n this.addListener(eventbus, 'highlight-navigation', this._highlightMenu);\n this.addListener(\n eventbus,\n 'request-current-navigation',\n this._handleRequestCurrentNavigation\n );\n this.addListener(eventbus, 'video-complete', this._handleVideoComplete);\n this.addListener(\n eventbus,\n 'timeline-complete',\n this._handleTimelineComplete\n );\n this.addListener(\n eventbus,\n 'timeline-current-timeline-change',\n this._handleTimelineChange\n );\n\n this._buildHtml(this.container, this.navigation);\n this._initHistory();\n }\n\n /**\n * Sets the active navigation point and the menu highlight from the URL hash,\n * falling back to the item with videoUrlIndex 0 when the hash is missing or\n * names an unknown navigation id.\n */\n private _initHistory() {\n const navId = this._getQueryVariable(0);\n const nav =\n navId && Object.hasOwn(this.navLookup, navId)\n ? this.navLookup[navId]\n : undefined;\n const videoIndex = nav?.videoUrlIndex ?? 0;\n this.activeNavigationPoint = this.navVidIdLookup[videoIndex] ?? null;\n this._highlightMenu(videoIndex);\n }\n\n private _getQueryVariable(variableIdx: number) {\n const href = window.location.href;\n const hashIndex = href.indexOf('#');\n if (hashIndex > -1) {\n const query = href.substring(hashIndex + 2);\n if (query) {\n const vars = query.split('/');\n return vars[variableIdx];\n }\n }\n return null;\n }\n\n private _handleRequestCurrentNavigation(\n resultCallback: TResultCallback<{navigationData: any; title: string} | null>\n ) {\n if (this.activeNavigationPoint) {\n const title =\n this.eventbus?.request<string>(\n 'request-translation',\n this.activeNavigationPoint.labelId\n ) ?? '';\n resultCallback({\n navigationData: this.activeNavigationPoint,\n title,\n });\n } else {\n resultCallback(null);\n }\n }\n\n detach(eventbus: IEventbus) {\n super.detach(eventbus);\n\n this.labelControllers.forEach(ctrl => {\n ctrl.detach(eventbus);\n });\n\n this.labelControllers.length = 0;\n this.ctrlLookup = {};\n\n // Removing the menu also unbinds its jQuery click and keydown handlers\n this._menuElement?.remove();\n this._menuElement = null;\n this._anchorLookup.clear();\n this._highlightedAnchor = null;\n\n this.eventbus = null;\n this.services = null;\n }\n\n private _pushCurrentState(position = -1) {\n if (!this.activeNavigationPoint) {\n return;\n }\n\n const title =\n this.eventbus?.request<string>(\n 'request-translation',\n this.activeNavigationPoint.labelId\n ) ?? '';\n\n const state = {\n navigationData: this.activeNavigationPoint,\n title,\n position: -1,\n };\n if (position > -1) {\n state.position = position;\n }\n this.eventbus?.broadcast('push-history-state', [state]);\n }\n\n private _buildHtml(parentElm: JQuery, data: any[]) {\n const ul = $('<ul/>');\n const ancestors = new Set<any>();\n data.forEach(nav => this._addNavElement(ul, nav, ancestors));\n parentElm.append(ul);\n this._menuElement = ul;\n }\n\n /**\n * Renders an entry and its children. `ancestors` holds the entries on the\n * current path, so a children list that refers back to an ancestor cannot\n * recurse forever.\n */\n private _addNavElement(parentElm: JQuery, data: any, ancestors: Set<any>) {\n if (!data?.visible || ancestors.has(data)) {\n return;\n }\n const li = $('<li/>');\n // Configuration values are only ever set as attribute values, never parsed\n // as HTML. The fragment href gives the anchor link semantics (focusable,\n // activated by Enter); the click handler prevents the navigation itself.\n const a = $('<a/>')\n .attr('href', `#/${data.id}`)\n .attr('id', `nav_${data.videoUrlIndex}`);\n this._anchorLookup.set(data, a);\n li.append(a);\n this._addLabel(a, data.labelId);\n this._addActivationHandlers(a, data);\n\n if (Array.isArray(data.children)) {\n const ul = $('<ul/>');\n ancestors.add(data);\n data.children.forEach((child: any) =>\n this._addNavElement(ul, child, ancestors)\n );\n ancestors.delete(data);\n li.append(ul);\n }\n\n parentElm.append(li);\n }\n\n /**\n * Activates the entry on click, which the browser also fires for Enter on a\n * focused link and for the default action of assistive technology, and on\n * Space, which links do not handle natively. Only one of click and mouseup\n * may be bound, since a mouse click fires both.\n */\n private _addActivationHandlers(anchor: JQuery, nav: any) {\n anchor.on('click', (event?: JQuery.TriggeredEvent) => {\n event?.preventDefault?.();\n this._navigateTo(nav);\n });\n anchor.on('keydown', (event?: JQuery.TriggeredEvent) => {\n if (event?.key === ' ' || event?.key === 'Spacebar') {\n event.preventDefault?.();\n this._navigateTo(nav);\n }\n });\n }\n\n private _handleNavigateVideoUrl(\n index: number,\n requestedVideoPosition: number = 0\n ) {\n const nav = this.navVidIdLookup[index];\n if (nav) {\n this._navigateTo(nav, requestedVideoPosition);\n } else {\n this.eventbus?.broadcast('request-video-url', [\n index,\n requestedVideoPosition,\n ]);\n }\n }\n\n /**\n * Highlights the entry, requests its content, makes it the active entry and\n * pushes a history state for it.\n */\n private _navigateTo(nav: any, position: number = 0) {\n this._highlightNav(nav);\n if (this.eventbus) {\n requestNavigation(this.eventbus, nav, position);\n }\n this.activeNavigationPoint = nav;\n this._pushCurrentState(position);\n }\n\n private _highlightMenu(index: number) {\n this._highlightNav(this.navVidIdLookup[index]);\n }\n\n private _highlightNav(nav: any) {\n const navElm = nav ? this._anchorLookup.get(nav) : undefined;\n\n if (navElm) {\n this._highlightedAnchor\n ?.removeClass(CURRENT_CLASS)\n .removeAttr('aria-current');\n navElm.addClass(CURRENT_CLASS).attr('aria-current', 'page');\n this._highlightedAnchor = navElm;\n }\n }\n\n /**\n * Legacy completion event for entries driven by `request-video-url`.\n */\n private _handleVideoComplete(index: number) {\n const navData = this.navVidIdLookup[index];\n if (navData?.autoNext && navData.next) {\n this._navigateTo(navData.next);\n } else {\n this.eventbus?.broadcast('request-video-cleanup', []);\n }\n }\n\n /**\n * Starts the next entry when the active entry's timeline completes. Legacy\n * entries without a `timelineUri` are left to `video-complete`, so a host\n * that bridges both events does not navigate twice.\n */\n private _handleTimelineComplete() {\n const nav = this.activeNavigationPoint;\n if (!nav?.timelineUri || !nav.autoNext || !nav.next) {\n return;\n }\n const currentUri = this.eventbus?.request<string>(\n 'timeline-request-current-timeline'\n );\n if (currentUri !== undefined && currentUri !== nav.timelineUri) {\n return;\n }\n this._navigateTo(nav.next);\n }\n\n /**\n * Keeps the active entry and the highlight in sync when the engine switches\n * timelines, whoever asked for the switch.\n */\n private _handleTimelineChange(timelineUri: string) {\n const nav = this._navByTimelineUri.get(timelineUri);\n if (nav) {\n this.activeNavigationPoint = nav;\n this._highlightNav(nav);\n }\n }\n\n private _addLabel(parentElm: JQuery, translationKey: string) {\n const data = {\n selectedElement: parentElm,\n translationKey,\n };\n const {eventbus, services} = this;\n if (!eventbus || !services) {\n return;\n }\n const instance =\n services.createInstance<LabelController>('LabelController');\n instance.init(data);\n instance.attach(eventbus);\n this.labelControllers.push(instance);\n this.ctrlLookup[translationKey] = instance;\n }\n}\n","import {BaseController} from '@controllers/base-controller.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\n\nexport interface IProgressbarControllerOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * @dependency\n */\n textElement: JQuery;\n}\n\n/**\n * This controller renders a progressbar that displays the progress of the current timeline in the given selected element.\n *\n * The current progress as a percentage is rendered in the given text element.\n */\nexport class ProgressbarController extends BaseController<IProgressbarControllerOperationData> {\n name: string = 'ProgressbarController';\n selectedElement: JQuery | null = null;\n textElement: JQuery | null = null;\n duration: number = 0;\n private _eventbus: IEventbus | null = null;\n /** The inline pointer-events value attach() replaced, restored on detach */\n private _previousPointerEvents: string | null = null;\n /** The last width and text written, so unchanged values are not rewritten */\n private _renderedWidth: string | null = null;\n private _renderedText: string | null = null;\n\n init(operationData: IProgressbarControllerOperationData) {\n this.operationData = operationData;\n this.selectedElement = operationData.selectedElement;\n this.textElement = operationData.textElement;\n }\n\n attach(eventbus: IEventbus) {\n this.beginAttach(eventbus);\n this.addListener(eventbus, 'timeline-time', this._positionUpdateHandler);\n this.addListener(eventbus, 'timeline-duration', this._durationHandler);\n\n this._eventbus = eventbus;\n // Read the current duration once; later changes (for example a timeline\n // switch) arrive through 'timeline-duration'.\n this._refreshDuration();\n\n if (this.selectedElement) {\n this._previousPointerEvents =\n (this.selectedElement[0] as HTMLElement | undefined)?.style\n ?.pointerEvents ?? '';\n this.selectedElement.css({'pointer-events': 'none'});\n }\n\n const container = this.selectedElement?.parent();\n\n if (container) {\n const clickHandler = this._clickHandler.bind(this, eventbus, container);\n container.on('click', clickHandler);\n this.eventListeners.push(() => container.off('click', clickHandler));\n }\n }\n\n detach(eventbus: IEventbus) {\n super.detach(eventbus);\n this._eventbus = null;\n if (this._previousPointerEvents !== null) {\n this.selectedElement?.css('pointer-events', this._previousPointerEvents);\n this._previousPointerEvents = null;\n }\n this._renderedWidth = null;\n this._renderedText = null;\n }\n\n /**\n * Requests the duration of the active timeline.\n */\n private _refreshDuration() {\n this.duration =\n this._eventbus?.request<number>('timeline-duration-request') ??\n this.duration;\n }\n\n /**\n * Stores the duration the engine reports when a timeline starts, which\n * changes when the engine switches timelines.\n */\n private _durationHandler(getDuration: (() => number) | undefined) {\n const duration = getDuration?.();\n if (typeof duration === 'number' && Number.isFinite(duration)) {\n this.duration = duration;\n }\n }\n\n private _positionUpdateHandler(position: number) {\n if (!(this.duration > 0)) {\n return;\n }\n const percentage = clamp((100 / this.duration) * position, 0, 100);\n // 'timeline-time' arrives every frame; only touch the DOM when the\n // rendered value changes. A 0.1% width step is at most a pixel or two.\n const width = `${Math.round(percentage * 10) / 10}%`;\n if (width !== this._renderedWidth) {\n this._renderedWidth = width;\n this.selectedElement?.css('width', width);\n }\n const text = `${Math.floor(percentage)}%`;\n if (text !== this._renderedText) {\n this._renderedText = text;\n this.textElement?.text(text);\n }\n }\n\n private _clickHandler(eventbus: IEventbus, container: JQuery, event: any) {\n // Measure against the container the handler is bound to, not event.target,\n // which may be a child such as the text element\n const rect = (\n container[0] as HTMLElement | undefined\n )?.getBoundingClientRect();\n if (!rect || !(rect.width > 0) || !(this.duration > 0)) {\n return;\n }\n\n const x = event.clientX - rect.left; //x position within the container.\n\n const percentage = clamp((100 / rect.width) * x, 0, 100);\n const position = (this.duration / 100) * percentage;\n\n // Round to the 0.1s action precision\n eventbus.broadcast('timeline-seek-request', [\n Math.round(position * 10) / 10,\n ]);\n }\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max);\n}\n","import {BaseController} from '@controllers/base-controller.ts';\nimport {\n buildNavigationData,\n requestNavigation,\n} from '@controllers/helper/navigation-data.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\n\nexport interface IRoutingControllerOperationData {\n /**\n * The navigation json, in the same format as NavigationController's. Give\n * an entry a `timelineUri` to let the engine switch to that timeline on\n * back/forward navigation.\n *\n * @required\n */\n json: any;\n}\n\n/**\n * Seconds subtracted from the current position when the current entry is\n * saved, so going back resumes slightly before the point where the user left.\n */\nconst REWIND_SECONDS = 3;\n\n/**\n * Keeps the browser history in sync with the navigation entries: each entry\n * gets a `#/<id>/<position>` URL, and back/forward navigation requests the\n * entry in the URL.\n *\n * Requests go to the engine as `request-timeline-uri` for entries with a\n * `timelineUri`, and as the legacy `request-video-url` otherwise. Before the\n * engine switches timelines (`before-request-timeline-uri`, or the legacy\n * `before-request-video-url`), the current entry is saved with its position.\n *\n * This is a work in progress, do not use this yet please....\n */\nexport class RoutingController extends BaseController<IRoutingControllerOperationData> {\n name = 'RoutingController';\n navLookup: Record<string, any> = {};\n navVidIdLookup: Record<string, any> = {};\n navigation: any = null;\n eventbus: IEventbus | null = null;\n private _popstateHandler: ((event: PopStateEvent) => void) | null = null;\n /** True while this controller requests an entry from the history */\n private _isHistoryRequest = false;\n\n /**\n * @throws when the json has no navigationData array or names an unknown\n * navigation id in roots, nextId or children\n */\n init(operationData: IRoutingControllerOperationData) {\n this.operationData = operationData;\n const {roots, navLookup, navVidIdLookup} = buildNavigationData(\n operationData.json,\n this.name\n );\n this.navigation = roots;\n this.navLookup = navLookup;\n this.navVidIdLookup = navVidIdLookup;\n }\n\n attach(eventbus: IEventbus) {\n this.beginAttach(eventbus);\n this.addListener(\n eventbus,\n 'before-request-video-url',\n this._handleBeforeRequestVideoUrl\n );\n this.addListener(\n eventbus,\n 'before-request-timeline-uri',\n this._handleBeforeRequestTimelineUri\n );\n this.addListener(\n eventbus,\n 'push-history-state',\n this._handlePushHistoryState\n );\n this.eventbus = eventbus;\n // Add a listener instead of assigning window.onpopstate, so a handler\n // installed by the host page (or another controller) is never replaced.\n if (this._popstateHandler) {\n window.removeEventListener('popstate', this._popstateHandler);\n }\n this._popstateHandler = this._handlePopstate.bind(this);\n window.addEventListener('popstate', this._popstateHandler);\n\n const navId = this._getQueryVariable(0);\n if (navId) {\n const nav = this._findNavigation(navId);\n if (nav) {\n this._requestFromHistory(\n nav,\n this._parsePosition(this._getQueryVariable(1))\n );\n }\n } else if (this.navigation?.length) {\n // Tag the current entry instead of adding one, so the first Back press\n // leaves the page.\n window.history.replaceState(\n {navigationId: this.navigation[0].id},\n '',\n `#/${this.navigation[0].id}`\n );\n }\n }\n\n /**\n * Requests the entry in the URL. A null state comes from a hash change (an\n * in-page link, an edited URL, or the entry before this controller added\n * state), so the URL is read. A state object without a navigation id belongs\n * to the host page and is ignored.\n */\n private _handlePopstate(event: PopStateEvent) {\n const state = event.state;\n let navId: unknown;\n let rawPosition: unknown;\n if (state === null || state === undefined) {\n navId = this._getQueryVariable(0) || undefined;\n rawPosition = this._getQueryVariable(1);\n } else if (typeof state?.navigationId === 'string') {\n navId = state.navigationId;\n rawPosition = state.position;\n } else {\n return;\n }\n\n const nav = this._findNavigation(navId);\n if (!nav) {\n return;\n }\n this.eventbus?.broadcast('highlight-navigation', [nav.videoUrlIndex]);\n this._requestFromHistory(nav, this._parsePosition(rawPosition));\n }\n\n /**\n * Requests an entry without saving the current one: the history already\n * has it.\n */\n private _requestFromHistory(nav: any, position: number) {\n if (!this.eventbus) {\n return;\n }\n this._isHistoryRequest = true;\n try {\n requestNavigation(this.eventbus, nav, position, true);\n } finally {\n this._isHistoryRequest = false;\n }\n }\n\n /**\n * Looks up a navigation entry by id (own properties only), falling back to\n * the first navigation entry for a missing or unknown id.\n */\n private _findNavigation(navId: unknown): any {\n if (typeof navId === 'string' && Object.hasOwn(this.navLookup, navId)) {\n return this.navLookup[navId];\n }\n return this.navigation?.[0];\n }\n\n /**\n * @returns the position as a finite, non-negative number, or 0\n */\n private _parsePosition(value: unknown): number {\n const position = Number.parseFloat(String(value));\n return Number.isFinite(position) && position >= 0 ? position : 0;\n }\n\n detach(eventbus: IEventbus) {\n super.detach(eventbus);\n if (this._popstateHandler) {\n window.removeEventListener('popstate', this._popstateHandler);\n }\n this._popstateHandler = null;\n this.eventbus = null;\n }\n\n private _handleBeforeRequestVideoUrl(\n _index: number,\n _requestedVideoPosition: number = 0,\n isHistoryRequest: boolean = false\n ) {\n if (!isHistoryRequest) {\n this._saveCurrentNavigation();\n }\n }\n\n /**\n * The interceptor passes on the `request-timeline-uri` arguments, which\n * have no history flag; requests this controller makes itself are skipped\n * through `_isHistoryRequest`.\n */\n private _handleBeforeRequestTimelineUri(_uri?: string, _position?: number) {\n if (!this._isHistoryRequest) {\n this._saveCurrentNavigation();\n }\n }\n\n private _saveCurrentNavigation() {\n const resultCallback = (item: any) => {\n this._pushState(item);\n };\n this.eventbus?.broadcast('request-current-navigation', [resultCallback]);\n }\n\n private _getQueryVariable(variableIdx: number) {\n const href = window.location.href;\n const hashIndex = href.indexOf('#');\n if (hashIndex > -1) {\n const query = href.substring(hashIndex + 2);\n if (query) {\n const vars = query.split('/');\n return vars[variableIdx];\n }\n }\n return '';\n }\n\n private _handlePushHistoryState(state: any) {\n this._pushState(state);\n }\n\n private _pushState(state: any) {\n if (!state?.navigationData?.visible) {\n return;\n }\n\n const navigationId = state.navigationData.id;\n const position = this._resolveStatePosition(state.position);\n const historyState =\n position === undefined ? {navigationId} : {navigationId, position};\n const url =\n position === undefined\n ? `#/${navigationId}`\n : `#/${navigationId}/${position}`;\n\n if (window.history.state?.navigationId === navigationId) {\n window.history.replaceState(historyState, state.title, url);\n } else {\n window.history.pushState(historyState, state.title, url);\n }\n window.document.title = state.title;\n }\n\n /**\n * A missing or negative position means \"where the timeline is now\": the\n * engine position minus a short rewind. When nothing reports a position,\n * the position is left out of the URL and the state.\n */\n private _resolveStatePosition(position: unknown): number | undefined {\n if (\n typeof position === 'number' &&\n Number.isFinite(position) &&\n position >= 0\n ) {\n return position;\n }\n\n let current = this.eventbus?.request<number>(\n 'request-current-timeline-position'\n );\n if (current === undefined) {\n // Legacy hosts answer through a callback broadcast\n this.eventbus?.broadcast('request-current-video-position', [\n (value: number) => {\n current = value;\n },\n ]);\n }\n return typeof current === 'number' && Number.isFinite(current)\n ? Math.max(0, current - REWIND_SECONDS)\n : undefined;\n }\n}\n","import {BaseController} from '@controllers/base-controller.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\nimport {sanitizeHtml} from '@util/sanitize-html.ts';\nimport type {\n IStrictDuration,\n ISubtitleCollection,\n TLanguageCode,\n} from '../types.ts';\n\nexport interface ISubtitlesControllerOperationData {\n /**\n * @dependency\n */\n selectedElement: JQuery;\n /**\n * The language to fall back to when the eventbus cannot tell the current\n * language (`request-current-language`).\n *\n * @type=ParameterType:languagecode\n */\n language: TLanguageCode;\n /**\n * One collection per language. Titles are matched by index across the\n * languages, so every collection needs the same number of titles.\n *\n * @type=ParameterType:array\n * @itemType=ParameterType:object\n */\n subtitleData: ISubtitleCollection[];\n}\n\ntype TTitleRange = IStrictDuration & {show: () => void};\n\n/**\n * This controller shows the subtitle whose duration contains the current\n * timeline position in the selected element, in the current language, and\n * re-renders it after a `language-change` event.\n *\n * The starting language is the locale's current language\n * (`request-current-language`); the configured `language` is only used when\n * nothing answers that request.\n *\n * Subtitle texts may contain simple inline markup. They are passed through\n * `sanitizeHtml` before insertion, so `<br>`, `<i>`, `<em>`,\n * `<strong>` and `<span>` render, while scripts, event handlers,\n * `javascript:` URLs, images, iframes and SVG are removed.\n */\nexport class SubtitlesController extends BaseController<ISubtitlesControllerOperationData> {\n /**\n * @deprecated Subtitles are looked up by range, not by exact position; this\n * lookup is no longer read and will be removed in the next major version.\n */\n actionLookup: Record<string, any> = {};\n currentLanguage: TLanguageCode | null = null;\n lastFunc: (() => void) | null = null;\n name = 'SubtitlesController';\n /**\n * @deprecated No longer read; will be removed in the next major version.\n */\n subtitleDurations: IStrictDuration[] | null = null;\n private _titleRanges: TTitleRange[] = [];\n /** True when no two ranges overlap, so the ranges are sorted by start */\n private _rangesDisjoint = true;\n /** Index of the last range a position was found in (or just after) */\n private _lastRangeIndex = -1;\n private _configuredLanguage: TLanguageCode | null = null;\n\n attach(eventbus: IEventbus) {\n this.beginAttach(eventbus);\n this.currentLanguage =\n eventbus.request<TLanguageCode>('request-current-language') ??\n this._configuredLanguage ??\n null;\n this.addListener(eventbus, 'timeline-time', this.onTimeHandler);\n this.addListener(eventbus, 'timeline-seeked', this.onSeekedHandler);\n this.addListener(eventbus, 'language-change', this.languageChangeHandler);\n }\n\n /**\n * Stops listening and removes the subtitle this controller is showing, since\n * no later time event would remove it.\n */\n detach(eventbus: IEventbus) {\n super.detach(eventbus);\n if (this.lastFunc) {\n this.removeTitle();\n }\n }\n\n languageChangeHandler(newLanguage: TLanguageCode) {\n this.currentLanguage = newLanguage;\n if (this.lastFunc) {\n this.lastFunc();\n }\n }\n\n removeTitle(container?: JQuery) {\n container?.empty();\n this.lastFunc = null;\n }\n\n /**\n * Shows the subtitle whose range contains the given position, or removes the\n * current subtitle when no range contains it.\n *\n * Positions arrive as fractional seconds, so the lookup is range based\n * (`start <= position < end`) rather than an exact key match.\n */\n onTimeHandler(position: number) {\n const func = this._findTitleFunc(position);\n if (func) {\n if (this.lastFunc !== func) {\n this.lastFunc = func;\n func();\n }\n } else if (this.lastFunc) {\n this.removeTitle();\n }\n }\n\n onSeekedHandler(position: number, _duration: number) {\n const func = this._findTitleFunc(position);\n if (func && this.lastFunc !== func) {\n this.lastFunc = func;\n func();\n } else if (!func) {\n this.removeTitle();\n }\n }\n\n /**\n * Playback almost always stays in the last range, moves into the gap after\n * it or into the next range, so those are checked first; other positions\n * (after a seek) are found with a binary search. Overlapping ranges fall\n * back to a linear search in configuration order, where the first range\n * containing the position wins.\n */\n private _findTitleFunc(position: number): (() => void) | undefined {\n const ranges = this._titleRanges;\n if (!this._rangesDisjoint) {\n return ranges.find(x => x.start <= position && position < x.end)?.show;\n }\n\n const last = this._lastRangeIndex;\n if (last >= 0 && last < ranges.length) {\n const lastRange = ranges[last];\n if (lastRange.start <= position) {\n if (position < lastRange.end) {\n return lastRange.show;\n }\n const next = ranges[last + 1];\n if (!next || position < next.start) {\n return undefined;\n }\n if (position < next.end) {\n this._lastRangeIndex = last + 1;\n return next.show;\n }\n }\n }\n\n // The last range that starts at or before the position\n let low = 0;\n let high = ranges.length - 1;\n let found = -1;\n while (low <= high) {\n const mid = (low + high) >> 1;\n if (ranges[mid].start <= position) {\n found = mid;\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n this._lastRangeIndex = found;\n return found >= 0 && position < ranges[found].end\n ? ranges[found].show\n : undefined;\n }\n\n setTitle(container: JQuery, titleLanguageLookup: Record<string, string>) {\n if (this.currentLanguage) {\n container.html(\n sanitizeHtml(titleLanguageLookup[this.currentLanguage] ?? '')\n );\n }\n }\n\n /**\n * Builds the subtitle ranges. Missing or empty subtitle data means there are\n * no subtitles.\n *\n * @returns the deprecated position lookup\n * @throws when a subtitle collection has no titles array, or a different\n * number of titles than the first collection\n */\n createActionLookup(\n operationData: ISubtitlesControllerOperationData,\n container: JQuery\n ) {\n const subtitleData = operationData.subtitleData;\n const subtitleTimeLookup: Record<number, () => void> = {};\n this._titleRanges = [];\n this._rangesDisjoint = true;\n this._lastRangeIndex = -1;\n\n if (!subtitleData?.length) {\n return subtitleTimeLookup;\n }\n this._validateSubtitleData(subtitleData);\n\n const titles = subtitleData[0].titles;\n const ranges: TTitleRange[] = [];\n for (let i = 0, ii = titles.length; i < ii; i++) {\n const titleLanguageLookup: Record<string, string> = {};\n\n for (let j = 0, jj = subtitleData.length; j < jj; j++) {\n const subs = subtitleData[j];\n titleLanguageLookup[subs.languageCode] = subs.titles[i].text;\n }\n\n const show = this.setTitle.bind(this, container, titleLanguageLookup);\n const {start, end} = titles[i].duration;\n ranges.push({start, end, show});\n\n subtitleTimeLookup[start] = show;\n subtitleTimeLookup[end] = this.removeTitle.bind(this, container);\n }\n\n const sorted = ranges.slice().sort((a, b) => a.start - b.start);\n this._rangesDisjoint = sorted.every(\n (range, index) => index === 0 || sorted[index - 1].end <= range.start\n );\n // Overlapping ranges keep configuration order for the linear search\n this._titleRanges = this._rangesDisjoint ? sorted : ranges;\n\n return subtitleTimeLookup;\n }\n\n private _validateSubtitleData(subtitleData: ISubtitleCollection[]) {\n const expected = subtitleData[0]?.titles?.length;\n subtitleData.forEach((subs, index) => {\n const titles = subs?.titles;\n if (!Array.isArray(titles)) {\n throw new Error(\n `SubtitlesController: subtitleData[${index}] (${subs?.languageCode}) has no titles array`\n );\n }\n if (titles.length !== expected) {\n throw new Error(\n `SubtitlesController: subtitleData[${index}] (${subs.languageCode}) has ${titles.length} titles, expected ${expected} (titles are matched by index across languages)`\n );\n }\n });\n }\n\n /**\n * @throws when the subtitle data is ragged (see createActionLookup)\n */\n init(operationData: ISubtitlesControllerOperationData) {\n const container = operationData.selectedElement;\n this.removeTitle = this.removeTitle.bind(this, container);\n this._configuredLanguage = operationData.language ?? null;\n this.currentLanguage = this._configuredLanguage;\n this.actionLookup = this.createActionLookup(operationData, container);\n this.subtitleDurations = operationData.subtitleData?.length\n ? operationData.subtitleData[0].titles.map(x => x.duration)\n : [];\n }\n}\n","import type { BeforeRequestTimelineUriEvent } from \"@eventbus/events/before-request-timeline-uri.ts\";\nimport type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\n\nexport function beforeRequestTimelineUri(): IEventMetadata<BeforeRequestTimelineUriEvent['args']> {\n return {\n description: `Event: before-request-timeline-uri\n\nBroadcast by \\`RequestVideoUriInterceptor\\` just before a\n\\`request-timeline-uri\\` event is handled, with the same arguments.`,\n category: `Timeline`,\n args: [\n {\n name: 'uri',\n type: 'string',\n description: 'The timeline URI that is about to be loaded'\n },\n {\n name: 'position',\n type: 'number',\n description: 'Optional start position (defaults to 0)',\n optional: true\n }]\n };\n}\n","import type { BeforeRequestVideoUrlEvent } from \"@eventbus/events/before-request-video-url.ts\";\nimport type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\n\nexport function beforeRequestVideoUrl(): IEventMetadata<BeforeRequestVideoUrlEvent['args']> {\n return {\n description: `Event: before-request-video-url`,\n category: `Navigation`,\n args: [\n {\n name: 'index',\n type: 'number',\n description: 'The video URL index'\n },\n {\n name: 'requestedVideoPosition',\n type: 'number',\n description: 'Optional video position to seek to',\n optional: true\n },\n {\n name: 'isHistoryRequest',\n type: 'boolean',\n description: 'Flag indicating if this is a history request',\n optional: true\n }]\n };\n}\n","import type { DomMutationEvent } from \"@eventbus/events/dom-mutation.ts\";\nimport type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\n\nexport function domMutation(): IEventMetadata<DomMutationEvent['args']> {\n return {\n description: `Event: dom-mutation`,\n category: `Controller`,\n args: [\n {\n name: 'payload',\n type: 'any',\n description: 'Mutation observer payload'\n }]\n };\n}\n","import type { EngineCommandErrorEvent } from \"@eventbus/events/engine-command-error.ts\";\nimport type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\n\nexport function engineCommandError(): IEventMetadata<EngineCommandErrorEvent['args']> {\n return {\n description: `Event: engine-command-error\nBroadcast by EngineEventbusAdapter when an engine command that an eventbus\nevent triggered fails, for example \\`engine.start()\\` after a\n\\`timeline-play-request\\` when the browser blocks autoplay. The failure is\nalso logged with \\`console.error\\`.`,\n category: `Engine`,\n args: [\n {\n name: 'command',\n type: 'string',\n description: 'The engine method that failed: `\\'start\\'`, `\\'stop\\'`, `\\'seek\\'` or `\\'switchTimeline\\'`'\n },\n {\n name: 'error',\n type: 'unknown',\n description: 'The value the engine\\'s promise rejected with'\n }]\n };\n}\n","import type { EngineErrorEvent } from \"@eventbus/events/engine-error.ts\";\nimport type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\n\nexport function engineError(): IEventMetadata<EngineErrorEvent['args']> {\n return {\n description: `Event: engine-error\nBroadcast when a timeline action that the engine started or ended on its\nown fails. The error names the action, the phase (start or end) and, when\nknown, the failing operation (\\`operationSystemName\\`, \\`operationIndex\\`) and\nthe path to it through called actions (\\`operationPath\\`, outermost first).`,\n category: `Engine`,\n args: [\n {\n name: 'error',\n type: 'IEngineActionError',\n description: 'The error, with the original error as its `cause`'\n }]\n };\n}\n","import type { HighlightNavigationEvent } from \"@eventbus/events/highlight-navigation.ts\";\nimport type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\n\nexport function highlightNavigation(): IEventMetadata<HighlightNavigationEvent['args']> {\n return {\n description: `Event: highlight-navigation`,\n category: `Navigation`,\n args: [\n {\n name: 'videoUrlIndex',\n type: 'number',\n description: 'The index of the video URL to highlight'\n }]\n };\n}\n","import type { LanguageChangeEvent } from \"@eventbus/events/language-change.ts\";\nimport type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\n\nexport function languageChange(): IEventMetadata<LanguageChangeEvent['args']> {\n return {\n description: `Event: language-change`,\n category: `Language Manager`,\n args: [\n {\n name: 'language',\n type: 'TLanguageCode',\n description: 'The new language code'\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { NavigateToVideoUrlEvent } from \"@eventbus/events/navigate-to-video-url.ts\";\n\nexport function navigateToVideoUrl(): IEventMetadata<NavigateToVideoUrlEvent['args']> {\n return {\n description: `Event: navigate-to-video-url`,\n category: `Navigation`,\n args: [\n {\n name: 'index',\n type: 'number',\n description: 'The video URL index to navigate to'\n },\n {\n name: 'requestedVideoPosition',\n type: 'number',\n description: 'Optional video position to seek to',\n optional: true\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { PushHistoryStateEvent } from \"@eventbus/events/push-history-state.ts\";\n\nexport function pushHistoryState(): IEventMetadata<PushHistoryStateEvent['args']> {\n return {\n description: `Event: push-history-state`,\n category: `Navigation`,\n args: [\n {\n name: 'state',\n type: 'any',\n description: 'The history state to push'\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RequestCurrentLanguageEvent } from \"@eventbus/events/request-current-language.ts\";\n\nexport function requestCurrentLanguage(): IEventMetadata<RequestCurrentLanguageEvent['args']> {\n return {\n description: `Request: request-current-language\nAnswered through \\`eventbus.request('request-current-language')\\` by\nLocaleEventbusAdapter with the active locale.`,\n category: `Engine Request`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RequestCurrentNavigationEvent } from \"@eventbus/events/request-current-navigation.ts\";\n\nexport function requestCurrentNavigation(): IEventMetadata<RequestCurrentNavigationEvent['args']> {\n return {\n description: `Event: request-current-navigation`,\n category: `Navigation`,\n args: [\n {\n name: 'callback',\n type: '(navigation: any) => void',\n description: 'Callback that receives the current navigation data'\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RequestCurrentTimelinePositionEvent } from \"@eventbus/events/request-current-timeline-position.ts\";\n\nexport function requestCurrentTimelinePosition(): IEventMetadata<RequestCurrentTimelinePositionEvent['args']> {\n return {\n description: `Request: request-current-timeline-position\nAnswered through \\`eventbus.request('request-current-timeline-position')\\` by\nEngineEventbusAdapter with the position of the current timeline. The engine\nalso answers the legacy form, a broadcast whose last argument is a\ncallback that receives the value.`,\n category: `Engine Request`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RequestCurrentVideoPositionEvent } from \"@eventbus/events/request-current-video-position.ts\";\n\nexport function requestCurrentVideoPosition(): IEventMetadata<RequestCurrentVideoPositionEvent['args']> {\n return {\n description: `Event: request-current-video-position`,\n category: `Navigation`,\n args: [\n {\n name: 'callback',\n type: '(position: number) => void',\n description: 'Callback that receives the current video position'\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RequestLabelCollectionEvent } from \"@eventbus/events/request-label-collection.ts\";\n\nexport function requestLabelCollection(): IEventMetadata<RequestLabelCollectionEvent['args']> {\n return {\n description: `Event: request-label-collection`,\n category: `Engine Request`,\n args: [\n {\n name: 'language',\n type: 'string',\n description: 'The language code'\n },\n {\n name: 'callback',\n type: '(collection: any) => void',\n description: 'Callback that receives the label collection'\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RequestLabelCollectionsEvent } from \"@eventbus/events/request-label-collections.ts\";\n\nexport function requestLabelCollections(): IEventMetadata<RequestLabelCollectionsEvent['args']> {\n return {\n description: `Event: request-label-collections`,\n category: `Engine Request`,\n args: [\n {\n name: 'labelIds',\n type: 'string[]',\n description: 'Array of label IDs to retrieve'\n },\n {\n name: 'callback',\n type: '(collections: any) => void',\n description: 'Callback that receives the label collections'\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RequestTimelineCleanupEvent } from \"@eventbus/events/request-timeline-cleanup.ts\";\n\nexport function requestTimelineCleanup(): IEventMetadata<RequestTimelineCleanupEvent['args']> {\n return {\n description: `Event: request-timeline-cleanup`,\n category: `Engine Request`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RequestTimelineUriEvent } from \"@eventbus/events/request-timeline-uri.ts\";\n\nexport function requestTimelineUri(): IEventMetadata<RequestTimelineUriEvent['args']> {\n return {\n description: `Event: request-timeline-uri`,\n category: `Engine Request`,\n args: [\n {\n name: 'uri',\n type: 'string',\n description: 'The timeline URI to load'\n },\n {\n name: 'position',\n type: 'number',\n description: 'Optional start position (defaults to 0)',\n optional: true\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RequestTranslationEvent } from \"@eventbus/events/request-translation.ts\";\n\nexport function requestTranslation(): IEventMetadata<RequestTranslationEvent['args']> {\n return {\n description: `Request: request-translation\nAnswered through \\`eventbus.request('request-translation', key, params)\\` by\nLocaleEventbusAdapter with the translation for the key in the active\nlocale, see \\`ILocaleManager.t\\`.`,\n category: `Engine Request`,\n args: [\n {\n name: 'key',\n type: 'string | string[]',\n description: 'Dot-notation translation key, or its segments'\n },\n {\n name: 'params',\n type: 'Record<string, unknown>',\n description: 'Optional values for the placeholders in the translation',\n optional: true\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RequestVideoCleanupEvent } from \"@eventbus/events/request-video-cleanup.ts\";\n\nexport function requestVideoCleanup(): IEventMetadata<RequestVideoCleanupEvent['args']> {\n return {\n description: `Event: request-video-cleanup`,\n category: `Navigation`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RequestVideoUrlEvent } from \"@eventbus/events/request-video-url.ts\";\n\nexport function requestVideoUrl(): IEventMetadata<RequestVideoUrlEvent['args']> {\n return {\n description: `Event: request-video-url`,\n category: `Navigation`,\n args: [\n {\n name: 'videoUrlIndex',\n type: 'number',\n description: 'The index of the video URL'\n },\n {\n name: 'requestedVideoPosition',\n type: 'number',\n description: 'Optional video position to seek to',\n optional: true\n },\n {\n name: 'fromRouting',\n type: 'boolean',\n description: 'Optional flag indicating if request came from routing',\n optional: true\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { CompleteEvent } from \"@eventbus/events/timeline-complete.ts\";\n\nexport function timelineComplete(): IEventMetadata<CompleteEvent['args']> {\n return {\n description: `Event: timeline-complete`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { ContainerRequestEvent } from \"@eventbus/events/timeline-container-request.ts\";\n\nexport function timelineContainerRequest(): IEventMetadata<ContainerRequestEvent['args']> {\n return {\n description: `Request: timeline-container-request\nAnswered through \\`eventbus.request('timeline-container-request')\\` by\nEngineEventbusAdapter with the DOM container of the current timeline. The\nengine also answers the legacy form, a broadcast whose last argument is a\ncallback that receives the value.`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { CurrentTimelineChangeEvent } from \"@eventbus/events/timeline-current-timeline-change.ts\";\n\nexport function timelineCurrentTimelineChange(): IEventMetadata<CurrentTimelineChangeEvent['args']> {\n return {\n description: `Event: timeline-current-timeline-change`,\n category: `Timeline`,\n args: [\n {\n name: 'timelineUri',\n type: 'string',\n description: 'The URI of the new current timeline'\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { DurationRequestEvent } from \"@eventbus/events/timeline-duration-request.ts\";\n\nexport function timelineDurationRequest(): IEventMetadata<DurationRequestEvent['args']> {\n return {\n description: `Request: timeline-duration-request\nAnswered through \\`eventbus.request('timeline-duration-request')\\` by\nEngineEventbusAdapter with the duration of the current timeline. The engine\nalso answers the legacy form, a broadcast whose last argument is a\ncallback that receives the value.`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { DurationEvent } from \"@eventbus/events/timeline-duration.ts\";\n\nexport function timelineDuration(): IEventMetadata<DurationEvent['args']> {\n return {\n description: `Event: timeline-duration`,\n category: `Timeline`,\n args: [\n {\n name: 'getDuration',\n type: '(() => number) | undefined',\n description: 'Function that returns the timeline duration'\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { FirstFrameEvent } from \"@eventbus/events/timeline-firstframe.ts\";\n\nexport function timelineFirstframe(): IEventMetadata<FirstFrameEvent['args']> {\n return {\n description: `Event: timeline-firstframe`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { PauseRequestEvent } from \"@eventbus/events/timeline-pause-request.ts\";\n\nexport function timelinePauseRequest(): IEventMetadata<PauseRequestEvent['args']> {\n return {\n description: `Event: timeline-pause-request`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { PauseEvent } from \"@eventbus/events/timeline-pause.ts\";\n\nexport function timelinePause(): IEventMetadata<PauseEvent['args']> {\n return {\n description: `Event: timeline-pause`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { PlayRequestEvent } from \"@eventbus/events/timeline-play-request.ts\";\n\nexport function timelinePlayRequest(): IEventMetadata<PlayRequestEvent['args']> {\n return {\n description: `Event: timeline-play-request`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { PlayToggleRequestEvent } from \"@eventbus/events/timeline-play-toggle-request.ts\";\n\nexport function timelinePlayToggleRequest(): IEventMetadata<PlayToggleRequestEvent['args']> {\n return {\n description: `Event: timeline-play-toggle-request`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { PlayEvent } from \"@eventbus/events/timeline-play.ts\";\n\nexport function timelinePlay(): IEventMetadata<PlayEvent['args']> {\n return {\n description: `Event: timeline-play`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RequestCurrentTimelineEvent } from \"@eventbus/events/timeline-request-current-timeline.ts\";\n\nexport function timelineRequestCurrentTimeline(): IEventMetadata<RequestCurrentTimelineEvent['args']> {\n return {\n description: `Request: timeline-request-current-timeline\nAnswered through \\`eventbus.request('timeline-request-current-timeline')\\` by\nEngineEventbusAdapter with the URI of the current timeline. The engine also\nanswers the legacy form, a broadcast whose last argument is a callback that\nreceives the value.`,\n category: `Engine Request`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { ResizeRequestEvent } from \"@eventbus/events/timeline-resize-request.ts\";\n\nexport function timelineResizeRequest(): IEventMetadata<ResizeRequestEvent['args']> {\n return {\n description: `Event: timeline-resize-request`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { ResizeEvent } from \"@eventbus/events/timeline-resize.ts\";\n\nexport function timelineResize(): IEventMetadata<ResizeEvent['args']> {\n return {\n description: `Event: timeline-resize`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { RestartEvent } from \"@eventbus/events/timeline-restart.ts\";\n\nexport function timelineRestart(): IEventMetadata<RestartEvent['args']> {\n return {\n description: `Event: timeline-restart`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { SeekRequestEvent } from \"@eventbus/events/timeline-seek-request.ts\";\n\nexport function timelineSeekRequest(): IEventMetadata<SeekRequestEvent['args']> {\n return {\n description: `Event: timeline-seek-request`,\n category: `Timeline`,\n args: [\n {\n name: 'position',\n type: 'number',\n description: 'The timeline position to seek to'\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { SeekEvent } from \"@eventbus/events/timeline-seek.ts\";\n\nexport function timelineSeek(): IEventMetadata<SeekEvent['args']> {\n return {\n description: `Event: timeline-seek`,\n category: `Timeline`,\n args: [\n {\n name: 'seekPosition',\n type: 'number',\n description: 'The position to seek to'\n },\n {\n name: 'currentPosition',\n type: 'number',\n description: 'The current position'\n },\n {\n name: 'duration',\n type: 'number',\n description: 'The timeline duration'\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { SeekedEvent } from \"@eventbus/events/timeline-seeked.ts\";\n\nexport function timelineSeeked(): IEventMetadata<SeekedEvent['args']> {\n return {\n description: `Event: timeline-seeked`,\n category: `Timeline`,\n args: [\n {\n name: 'position',\n type: 'number',\n description: 'The new timeline position after seeking'\n },\n {\n name: 'duration',\n type: 'number',\n description: 'The timeline duration'\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { StopRequestEvent } from \"@eventbus/events/timeline-stop-request.ts\";\n\nexport function timelineStopRequest(): IEventMetadata<StopRequestEvent['args']> {\n return {\n description: `Event: timeline-stop-request`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { StopEvent } from \"@eventbus/events/timeline-stop.ts\";\n\nexport function timelineStop(): IEventMetadata<StopEvent['args']> {\n return {\n description: `Event: timeline-stop`,\n category: `Timeline`,\n args: []\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { TimeEvent } from \"@eventbus/events/timeline-time.ts\";\n\nexport function timelineTime(): IEventMetadata<TimeEvent['args']> {\n return {\n description: `Event: timeline-time`,\n category: `Timeline`,\n args: [\n {\n name: 'position',\n type: 'number',\n description: 'The current timeline position'\n }]\n };\n}\n","import type { IEventMetadata } from \"@eventbus/events/metadata/types.ts\";\nimport type { VideoCompleteEvent } from \"@eventbus/events/video-complete.ts\";\n\nexport function videoComplete(): IEventMetadata<VideoCompleteEvent['args']> {\n return {\n description: `Event: video-complete`,\n category: `Navigation`,\n args: [\n {\n name: 'index',\n type: 'number',\n description: 'The video URL index that completed'\n }]\n };\n}\n","export { beforeRequestTimelineUri } from \"@eventbus/events/metadata/before-request-timeline-uri.ts\";\nexport { beforeRequestVideoUrl } from \"@eventbus/events/metadata/before-request-video-url.ts\";\nexport { domMutation } from \"@eventbus/events/metadata/dom-mutation.ts\";\nexport { engineCommandError } from \"@eventbus/events/metadata/engine-command-error.ts\";\nexport { engineError } from \"@eventbus/events/metadata/engine-error.ts\";\nexport { highlightNavigation } from \"@eventbus/events/metadata/highlight-navigation.ts\";\nexport { languageChange } from \"@eventbus/events/metadata/language-change.ts\";\nexport { navigateToVideoUrl } from \"@eventbus/events/metadata/navigate-to-video-url.ts\";\nexport { pushHistoryState } from \"@eventbus/events/metadata/push-history-state.ts\";\nexport { requestCurrentLanguage } from \"@eventbus/events/metadata/request-current-language.ts\";\nexport { requestCurrentNavigation } from \"@eventbus/events/metadata/request-current-navigation.ts\";\nexport { requestCurrentTimelinePosition } from \"@eventbus/events/metadata/request-current-timeline-position.ts\";\nexport { requestCurrentVideoPosition } from \"@eventbus/events/metadata/request-current-video-position.ts\";\nexport { requestLabelCollection } from \"@eventbus/events/metadata/request-label-collection.ts\";\nexport { requestLabelCollections } from \"@eventbus/events/metadata/request-label-collections.ts\";\nexport { requestTimelineCleanup } from \"@eventbus/events/metadata/request-timeline-cleanup.ts\";\nexport { requestTimelineUri } from \"@eventbus/events/metadata/request-timeline-uri.ts\";\nexport { requestTranslation } from \"@eventbus/events/metadata/request-translation.ts\";\nexport { requestVideoCleanup } from \"@eventbus/events/metadata/request-video-cleanup.ts\";\nexport { requestVideoUrl } from \"@eventbus/events/metadata/request-video-url.ts\";\nexport { timelineComplete } from \"@eventbus/events/metadata/timeline-complete.ts\";\nexport { timelineContainerRequest } from \"@eventbus/events/metadata/timeline-container-request.ts\";\nexport { timelineCurrentTimelineChange } from \"@eventbus/events/metadata/timeline-current-timeline-change.ts\";\nexport { timelineDurationRequest } from \"@eventbus/events/metadata/timeline-duration-request.ts\";\nexport { timelineDuration } from \"@eventbus/events/metadata/timeline-duration.ts\";\nexport { timelineFirstframe } from \"@eventbus/events/metadata/timeline-firstframe.ts\";\nexport { timelinePauseRequest } from \"@eventbus/events/metadata/timeline-pause-request.ts\";\nexport { timelinePause } from \"@eventbus/events/metadata/timeline-pause.ts\";\nexport { timelinePlayRequest } from \"@eventbus/events/metadata/timeline-play-request.ts\";\nexport { timelinePlayToggleRequest } from \"@eventbus/events/metadata/timeline-play-toggle-request.ts\";\nexport { timelinePlay } from \"@eventbus/events/metadata/timeline-play.ts\";\nexport { timelineRequestCurrentTimeline } from \"@eventbus/events/metadata/timeline-request-current-timeline.ts\";\nexport { timelineResizeRequest } from \"@eventbus/events/metadata/timeline-resize-request.ts\";\nexport { timelineResize } from \"@eventbus/events/metadata/timeline-resize.ts\";\nexport { timelineRestart } from \"@eventbus/events/metadata/timeline-restart.ts\";\nexport { timelineSeekRequest } from \"@eventbus/events/metadata/timeline-seek-request.ts\";\nexport { timelineSeek } from \"@eventbus/events/metadata/timeline-seek.ts\";\nexport { timelineSeeked } from \"@eventbus/events/metadata/timeline-seeked.ts\";\nexport { timelineStopRequest } from \"@eventbus/events/metadata/timeline-stop-request.ts\";\nexport { timelineStop } from \"@eventbus/events/metadata/timeline-stop.ts\";\nexport { timelineTime } from \"@eventbus/events/metadata/timeline-time.ts\";\nexport { videoComplete } from \"@eventbus/events/metadata/video-complete.ts\";\nexport * from \"@eventbus/events/metadata/types.ts\";\n","import type {IAction} from '@action/types.ts';\nimport type {IEventbusListener} from '@eventbus/types.ts';\n\n/**\n * The `IEventbusListener` first registers a number of actions that are then\n * executed when the specified event is broadcast.\n */\nexport class ActionRegistryEventbusListener implements IEventbusListener {\n private _actionRegistry = new Map<string, IAction[]>();\n\n registerAction(\n action: IAction,\n eventName: string,\n eventTopic?: string\n ): void {\n if (eventTopic?.length) {\n eventName = `${eventName}:${eventTopic}`;\n }\n if (!this._actionRegistry.has(eventName)) {\n this._actionRegistry.set(eventName, []);\n }\n this._actionRegistry.get(eventName)?.push(action);\n }\n\n /**\n * Starts every action registered for the event.\n *\n * @returns A promise that settles once all started actions have finished,\n * or undefined when no action is registered. It rejects with the failing\n * action's error, or with an AggregateError when several fail. The Eventbus\n * watches this promise and reports a rejection like any handler error.\n */\n handleEvent(\n eventName: string,\n eventTopic: string | undefined,\n args: any[]\n ): Promise<void> | undefined {\n if (eventTopic) {\n eventName = `${eventName}:${eventTopic}`;\n }\n const actions = this._actionRegistry.get(eventName);\n if (!actions?.length) {\n return undefined;\n }\n\n // Each action gets its own operation data: Action merges into and\n // mutates the object it is given, so sharing one would leak state\n // (selectedElement, variables, ...) from one action into the next.\n const runs = actions.map(action =>\n action.start({eventArgs: Array.isArray(args) ? [...args] : args})\n );\n\n return Promise.allSettled(runs).then(results => {\n const errors = results\n .filter(\n (result): result is PromiseRejectedResult =>\n result.status === 'rejected'\n )\n .map(result => result.reason);\n if (errors.length === 1) {\n throw errors[0];\n }\n if (errors.length > 1) {\n throw new AggregateError(\n errors,\n `${errors.length} event actions failed for '${eventName}'`\n );\n }\n });\n }\n}\n","import type {\n IEventbus,\n IEventbusErrorContext,\n IEventbusErrorReport,\n IEventbusInterceptor,\n IEventbusListener,\n IEventbusOptions,\n RequestMap,\n RequestName,\n TEventbusErrorHandler,\n TEventbusErrorSource,\n TEventbusRemover,\n TEventHandler,\n TRequestResponder,\n TTypedRequestResponder,\n} from '@eventbus/types.ts';\nimport {isPromise} from '@util/guards/is-promise.ts';\n\n/**\n * Maps each once() decorator to the handler it wraps, so off() can remove a\n * once() registration by the original function.\n */\nconst onceOriginals = new WeakMap<TEventHandler, TEventHandler>();\n\n/**\n * Central event bus for pub/sub communication and synchronous request/response queries.\n *\n * The eventbus supports:\n * - **Pub/Sub**: `on()`, `once()`, `off()`, `broadcast()`, `broadcastForTopic()`\n * - **Request/Response**: `onRequest()`, `request()`, `requestForTopic()` for synchronous queries\n * - **Interceptors**: Transform event arguments before handlers receive them\n * - **Listeners**: Global event observers for logging/debugging\n *\n * @example Pub/Sub pattern\n * ```ts\n * const remover = eventbus.on('timeline-play', () => console.log('Playing'));\n * eventbus.broadcast('timeline-play', []);\n * remover(); // Unsubscribe\n * ```\n *\n * @example Request/Response pattern\n * ```ts\n * eventbus.onRequest('request-translation', (key) => translations[key]);\n * const label = eventbus.request<string>('request-translation', 'nav.home');\n * ```\n *\n * Broadcasts isolate errors: a handler, listener or interceptor that throws, or\n * returns a promise that rejects, is reported and the others still run. Request\n * responders are not isolated; their errors reach the requester.\n *\n * @example Observing handler errors\n * ```ts\n * const eventbus = new Eventbus({\n * onHandlerError: (error, {eventName, eventTopic, source}) =>\n * myLogger.warn(`${source} failed for ${eventName}`, error),\n * });\n * ```\n */\nexport class Eventbus implements IEventbus {\n private eventHandlers = new Map<string, TEventHandler[]>();\n private eventInterceptors = new Map<string, IEventbusInterceptor[]>();\n private eventListeners: IEventbusListener[] = [];\n private requestResponders = new Map<string, TRequestResponder[]>();\n private readonly onHandlerError: TEventbusErrorHandler | undefined;\n\n /**\n * @param options - Optional settings. `onHandlerError` observes errors raised\n * by handlers, listeners and interceptors during a broadcast. It survives\n * {@link Eventbus.clear}.\n */\n constructor(options?: IEventbusOptions) {\n this.onHandlerError = options?.onHandlerError;\n this.clear();\n }\n\n /**\n * Clears all handlers, listeners, interceptors, and request responders.\n */\n clear() {\n this.eventHandlers = new Map<string, TEventHandler[]>();\n this.eventListeners = [];\n this.eventInterceptors = new Map<string, IEventbusInterceptor[]>();\n this.requestResponders = new Map<string, TRequestResponder[]>();\n }\n\n _getEventInterceptors(\n eventName: string,\n eventTopic?: string\n ): IEventbusInterceptor[] {\n if (eventTopic) {\n eventName = `${eventName}:${eventTopic}`;\n }\n if (!this.eventInterceptors.has(eventName)) {\n this.eventInterceptors.set(eventName, []);\n }\n return this.eventInterceptors.get(eventName) as IEventbusInterceptor[];\n }\n\n _getEventHandlers(eventName: string, eventTopic?: string): TEventHandler[] {\n if (eventTopic) {\n eventName = `${eventName}:${eventTopic}`;\n }\n if (!this.eventHandlers.has(eventName)) {\n this.eventHandlers.set(eventName, []);\n }\n return this.eventHandlers.get(eventName) as TEventHandler[];\n }\n\n on(\n eventName: string,\n eventHandler: TEventHandler,\n eventTopic?: string\n ): TEventbusRemover {\n this._getEventHandlers(eventName, eventTopic).push(eventHandler);\n return () => {\n this.off(eventName, eventHandler, eventTopic);\n };\n }\n\n once(\n eventName: string,\n eventHandler: TEventHandler,\n eventTopic?: string\n ): TEventbusRemover {\n // Remove the decorator before calling the handler, so a handler that\n // rebroadcasts the event or throws cannot make it fire more than once.\n // The flag covers a broadcast that already took a snapshot including it.\n let called = false;\n const eventHandlerDecorator = (...args: any[]) => {\n if (called) {\n return;\n }\n called = true;\n this.off(eventName, eventHandlerDecorator, eventTopic);\n // Return the result so a rejected promise from an async handler reaches\n // the dispatcher and gets reported.\n return eventHandler(...args);\n };\n // Lets off(eventName, eventHandler) find the decorator.\n onceOriginals.set(eventHandlerDecorator, eventHandler);\n this.on(eventName, eventHandlerDecorator, eventTopic);\n return () => {\n this.off(eventName, eventHandlerDecorator, eventTopic);\n };\n }\n\n /**\n * Removes one registration of the handler. A handler registered with\n * {@link Eventbus.once} can be removed by passing the original function. An\n * exact registration (through `on()`) is preferred over a `once()` one.\n */\n off(\n eventName: string,\n eventHandler: TEventHandler,\n eventTopic?: string\n ): void {\n const handlers = this._getEventHandlers(eventName, eventTopic);\n let idx = handlers.indexOf(eventHandler);\n if (idx === -1) {\n idx = handlers.findIndex(h => onceOriginals.get(h) === eventHandler);\n }\n if (idx > -1) {\n handlers.splice(idx, 1);\n }\n }\n\n broadcast(eventName: string, args: any[]): void {\n this._callHandlers(eventName, undefined, args);\n }\n\n broadcastForTopic(eventName: string, eventTopic: string, args: any[]): void {\n this._callHandlers(eventName, eventTopic, args);\n }\n\n registerEventlistener(eventbusListener: IEventbusListener): TEventbusRemover {\n this.eventListeners.push(eventbusListener);\n return () => {\n const index = this.eventListeners.indexOf(eventbusListener);\n if (index > -1) {\n this.eventListeners.splice(index, 1);\n }\n };\n }\n\n registerInterceptor(\n eventName: string,\n interceptor: IEventbusInterceptor,\n eventTopic?: string\n ): TEventbusRemover {\n const interceptors = this._getEventInterceptors(eventName, eventTopic);\n interceptors.push(interceptor);\n return () => {\n const index = interceptors.indexOf(interceptor);\n if (index > -1) {\n interceptors.splice(index, 1);\n }\n };\n }\n\n onRequest<K extends RequestName>(\n eventName: K,\n responder: TTypedRequestResponder<K>,\n eventTopic?: string\n ): TEventbusRemover;\n onRequest<T>(\n eventName: string,\n responder: TRequestResponder<T>,\n eventTopic?: string\n ): TEventbusRemover;\n onRequest(\n eventName: string,\n responder: TRequestResponder,\n eventTopic?: string\n ): TEventbusRemover {\n const responders = this._getRequestResponders(eventName, eventTopic);\n responders.push(responder);\n return () => {\n const index = responders.indexOf(responder);\n if (index > -1) {\n responders.splice(index, 1);\n }\n };\n }\n\n request<K extends RequestName>(\n eventName: K,\n ...args: RequestMap[K]['args']\n ): RequestMap[K]['returns'] | undefined;\n request<T>(eventName: string, ...args: unknown[]): T | undefined;\n request(eventName: string, ...args: unknown[]): unknown {\n return this._callResponder(eventName, undefined, args);\n }\n\n requestForTopic<K extends RequestName>(\n eventName: K,\n eventTopic: string,\n ...args: RequestMap[K]['args']\n ): RequestMap[K]['returns'] | undefined;\n requestForTopic<T>(\n eventName: string,\n eventTopic: string,\n ...args: unknown[]\n ): T | undefined;\n requestForTopic(\n eventName: string,\n eventTopic: string,\n ...args: unknown[]\n ): unknown {\n return this._callResponder(eventName, eventTopic, args);\n }\n\n private _getRequestResponders(\n eventName: string,\n eventTopic?: string\n ): TRequestResponder[] {\n if (eventTopic) {\n eventName = `${eventName}:${eventTopic}`;\n }\n if (!this.requestResponders.has(eventName)) {\n this.requestResponders.set(eventName, []);\n }\n return this.requestResponders.get(eventName) as TRequestResponder[];\n }\n\n private _callResponder<T>(\n eventName: string,\n eventTopic: string | undefined,\n args: unknown[]\n ): T | undefined {\n const responders = this._getRequestResponders(eventName, eventTopic);\n if (responders.length === 0) {\n return undefined;\n }\n // First responder wins\n return responders[0](...args) as T;\n }\n\n _callHandlers(\n eventName: string,\n eventTopic: string | undefined,\n args: any = []\n ): void {\n const handlers = this._getEventHandlers(eventName, eventTopic);\n\n if (handlers) {\n // Iterate snapshots: an interceptor, listener or handler that removes\n // itself (or an earlier one) during dispatch would otherwise make the\n // loop skip the entry that moves into the freed slot. Handlers added\n // during dispatch wait for the next broadcast.\n const interceptors = this._getEventInterceptors(\n eventName,\n eventTopic\n ).slice();\n const listeners = this.eventListeners.slice();\n const snapshot = handlers.slice();\n\n // Each interceptor, listener and handler is isolated: one that throws is\n // reported and the rest still run, so a faulty controller cannot abort\n // dispatch or throw into the engine code that broadcast the event.\n for (const interceptor of interceptors) {\n try {\n args = interceptor.intercept(args);\n } catch (error) {\n this._reportError(error, eventName, eventTopic, 'interceptor');\n }\n }\n\n for (const listener of listeners) {\n try {\n this._watchResult(\n listener.handleEvent(eventName, eventTopic, args),\n eventName,\n eventTopic,\n 'listener'\n );\n } catch (error) {\n this._reportError(error, eventName, eventTopic, 'listener');\n }\n }\n\n const hasArgs = args?.length > 0;\n for (const handler of snapshot) {\n // Skip a handler that an earlier one removed, or that clear() dropped,\n // during this dispatch: its owner may already be detached.\n if (!this._getEventHandlers(eventName, eventTopic).includes(handler)) {\n continue;\n }\n try {\n this._watchResult(\n hasArgs ? handler(...args) : handler(),\n eventName,\n eventTopic,\n 'handler'\n );\n } catch (error) {\n this._reportError(error, eventName, eventTopic, 'handler');\n }\n }\n }\n }\n\n /**\n * Handlers are typed to return void, but async ones return a promise that\n * nobody awaits. Report its rejection like a synchronous throw.\n */\n private _watchResult(\n result: unknown,\n eventName: string,\n eventTopic: string | undefined,\n source: TEventbusErrorSource\n ): void {\n if (result && isPromise(result)) {\n result.then(undefined, error =>\n this._reportError(error, eventName, eventTopic, source)\n );\n }\n }\n\n /**\n * Reports an error a component caught, the same way as a failing handler:\n * `console.error` naming the source, then the `onHandlerError` option with\n * source `'reported'`. Never throws.\n *\n * @param error - The caught error\n * @param context - The reporting component and, if any, the event it was\n * handling\n */\n reportError(error: unknown, context: IEventbusErrorReport): void {\n const {source, eventName} = context;\n const event = eventName ? ` for \"${eventName}\"` : '';\n console.error(`Error reported by ${source}${event}:`, error);\n this._notifyErrorHook(\n error,\n {\n eventName: eventName ?? '',\n eventTopic: undefined,\n source: 'reported',\n reporter: source,\n },\n `${source}${event}`\n );\n }\n\n /**\n * Logs the error with the event name and topic, never the event arguments\n * (they can carry configuration or user data), then passes it to the\n * `onHandlerError` option.\n */\n private _reportError(\n error: unknown,\n eventName: string,\n eventTopic: string | undefined,\n source: TEventbusErrorSource\n ): void {\n const topic = eventTopic ? ` (topic \"${eventTopic}\")` : '';\n console.error(\n `Error in eventbus ${source} for \"${eventName}\"${topic}:`,\n error\n );\n this._notifyErrorHook(\n error,\n {eventName, eventTopic, source},\n `\"${eventName}\"${topic}`\n );\n }\n\n private _notifyErrorHook(\n error: unknown,\n context: IEventbusErrorContext,\n description: string\n ): void {\n if (!this.onHandlerError) {\n return;\n }\n try {\n this.onHandlerError(error, context);\n } catch (hookError) {\n console.error(\n `Error in eventbus onHandlerError for ${description}:`,\n hookError\n );\n }\n }\n}\n","import type {EventMap} from '@eventbus/events/types.ts';\nimport type {IEventbus, IEventbusInterceptor} from '@eventbus/types.ts';\n\n/**\n * Intercepts `request-timeline-uri` and broadcasts\n * `before-request-timeline-uri` with a copy of the same arguments, then\n * passes the arguments on unchanged.\n */\nexport class RequestVideoUriInterceptor implements IEventbusInterceptor {\n constructor(private eventbus: IEventbus) {}\n\n intercept(\n args: EventMap['request-timeline-uri']\n ): EventMap['request-timeline-uri'] {\n this.eventbus.broadcast(\n 'before-request-timeline-uri',\n args.slice() as EventMap['before-request-timeline-uri']\n );\n return args;\n }\n}\n","import {isPromise} from '@util/guards/is-promise.ts';\n\n/**\n * Handler function for a specific event\n */\nexport type EventHandler<T extends unknown[]> = (...args: T) => void;\n\n/**\n * Maps each once() wrapper to the handler it wraps, so off() can remove a\n * once() registration by the original function.\n */\nconst onceOriginals = new WeakMap<EventHandler<any[]>, EventHandler<any[]>>();\n\n/**\n * Interface for a type-safe event emitter\n * @typeParam T - Event map object where keys are event names and values are argument tuples\n *\n * Note: Use `type` aliases (not `interface`) for your event maps to avoid\n * \"Index signature is missing\" errors. TypeScript treats them differently.\n */\nexport interface ITypedEventEmitter<T extends Record<keyof T, unknown[]>> {\n /**\n * Subscribe to an event\n * @param event - Event name\n * @param handler - Event handler\n * @returns Unsubscribe function\n */\n on<K extends keyof T>(event: K, handler: EventHandler<T[K]>): () => void;\n\n /**\n * Subscribe to an event for one-time execution\n * @param event - Event name\n * @param handler - Event handler\n * @returns Unsubscribe function\n */\n once<K extends keyof T>(event: K, handler: EventHandler<T[K]>): () => void;\n\n /**\n * Unsubscribe from an event\n * @param event - Event name\n * @param handler - Event handler to remove\n */\n off<K extends keyof T>(event: K, handler: EventHandler<T[K]>): void;\n\n /**\n * Emit an event to all subscribers\n * @param event - Event name\n * @param args - Event arguments\n */\n emit<K extends keyof T>(event: K, ...args: T[K]): void;\n\n /**\n * Remove all listeners for a specific event or all events\n * @param event - Optional event name. If not provided, removes all listeners.\n */\n removeAllListeners(event?: keyof T): void;\n}\n\n/**\n * Type-safe event emitter implementation\n *\n * Features:\n * - Generic type parameter for event map\n * - Handler execution order preserved (registration order)\n * - Errors in handlers caught and logged (don't break other handlers)\n * - Copy handlers array during emit (safe removal during iteration); a\n * handler removed during an emit is not called by that emit\n *\n * @example\n * ```typescript\n * interface MyEvents {\n * start: [];\n * data: [value: string];\n * progress: [current: number, total: number];\n * }\n *\n * const emitter = new TypedEventEmitter<MyEvents>();\n *\n * const unsubscribe = emitter.on('data', (value) => {\n * console.log('Received:', value);\n * });\n *\n * emitter.emit('data', 'hello');\n * unsubscribe();\n * ```\n */\nexport class TypedEventEmitter<T extends Record<keyof T, unknown[]>>\n implements ITypedEventEmitter<T>\n{\n private handlers: Map<keyof T, Array<EventHandler<T[keyof T]>>> = new Map();\n\n /**\n * Subscribe to an event\n * @param event - Event name\n * @param handler - Event handler\n * @returns Unsubscribe function\n */\n on<K extends keyof T>(event: K, handler: EventHandler<T[K]>): () => void {\n if (!this.handlers.has(event)) {\n this.handlers.set(event, []);\n }\n\n const eventHandlers = this.handlers.get(event)!;\n eventHandlers.push(handler as EventHandler<T[keyof T]>);\n\n return () => this.off(event, handler);\n }\n\n /**\n * Subscribe to an event for one-time execution\n * @param event - Event name\n * @param handler - Event handler\n * @returns Unsubscribe function\n */\n once<K extends keyof T>(event: K, handler: EventHandler<T[K]>): () => void {\n const onceHandler: EventHandler<T[K]> = (...args) => {\n this.off(event, onceHandler);\n // Return the result so emit() can report a rejected async handler.\n return handler(...args);\n };\n onceOriginals.set(\n onceHandler as EventHandler<any[]>,\n handler as EventHandler<any[]>\n );\n\n return this.on(event, onceHandler);\n }\n\n /**\n * Unsubscribe from an event. Removes one registration of the handler; a\n * handler registered with {@link TypedEventEmitter.once} can be removed by\n * passing the original function. An exact registration (through `on()`) is\n * preferred over a `once()` one.\n *\n * @param event - Event name\n * @param handler - Event handler to remove\n */\n off<K extends keyof T>(event: K, handler: EventHandler<T[K]>): void {\n const eventHandlers = this.handlers.get(event);\n if (!eventHandlers) {\n return;\n }\n\n let index = eventHandlers.indexOf(handler as EventHandler<T[keyof T]>);\n if (index === -1) {\n index = eventHandlers.findIndex(\n h => onceOriginals.get(h as EventHandler<any[]>) === handler\n );\n }\n if (index !== -1) {\n eventHandlers.splice(index, 1);\n }\n }\n\n /**\n * Emit an event to all subscribers\n *\n * Features:\n * - Copies handlers array to allow safe removal during iteration\n * - Isolates errors - one failing handler doesn't break others\n * - Logs errors to console for debugging, including rejections of promises\n * returned by async handlers (they are not awaited)\n *\n * @param event - Event name\n * @param args - Event arguments\n */\n emit<K extends keyof T>(event: K, ...args: T[K]): void {\n const eventHandlers = this.handlers.get(event);\n if (!eventHandlers || eventHandlers.length === 0) {\n return;\n }\n\n // Copy array to allow safe removal during iteration\n const handlersCopy = [...eventHandlers];\n\n for (const handler of handlersCopy) {\n // Skip a handler removed during this emit, by an earlier handler or by a\n // nested emit that ran a once() handler.\n if (!this.handlers.get(event)?.includes(handler)) {\n continue;\n }\n try {\n // Handlers are typed to return void, but async ones return a promise.\n const result: unknown = handler(...(args as T[keyof T]));\n if (result && isPromise(result)) {\n result.then(undefined, error => this._logError(event, error));\n }\n } catch (error) {\n this._logError(event, error);\n }\n }\n }\n\n private _logError(event: keyof T, error: unknown): void {\n console.error(`Error in event handler for \"${String(event)}\":`, error);\n }\n\n /**\n * Remove all listeners for a specific event or all events\n * @param event - Optional event name. If not provided, removes all listeners.\n */\n removeAllListeners(event?: keyof T): void {\n if (event !== undefined) {\n this.handlers.delete(event);\n } else {\n this.handlers.clear();\n }\n }\n}\n","import type {IAction, IEndableAction, ITimelineAction} from '@action/types.ts';\nimport type {\n IResolvedEngineConfiguration,\n IResolvedTimelineConfiguration,\n} from '@configuration/types.ts';\nimport type {\n EventName,\n IEventbus,\n TEventbusRemover,\n TEventHandler,\n} from '@eventbus/types.ts';\nimport {detachControllersWithin} from '@operation/helper/detach-controllers-within.ts';\nimport type {\n IContainerProvider,\n IPlaylist,\n IPositionSource,\n ISeekable,\n} from '@timelineproviders/types.ts';\nimport {findClosestNames, formatDidYouMean} from '@util/find-closest-names.ts';\nimport {TypedEventEmitter} from '@util/typed-event-emitter.ts';\nimport $ from 'jquery';\nimport type {ILocaleManager} from './locale/types.ts';\nimport type {\n EngineEvents,\n IEligiusEngine,\n IEligiusEngineOptions,\n IEngineActionError,\n IEngineEventSubscriptionOptions,\n IOperationPathEntry,\n ITimelineProviderInfo,\n TActionPhase,\n TimelineTypes,\n TResultCallback,\n} from './types.ts';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Errors\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Error emitted through the engine's `error` event when a timeline action that\n * the engine started or ended on its own fails.\n *\n * The original error is kept as `cause`. When it carries\n * `operationSystemName` and `operationIndex` properties, they are copied, and\n * the message names the operation.\n *\n * @example\n * ```typescript\n * engine.on('error', error => {\n * reportToMonitoring(error.message, error.cause);\n * });\n * // error.message: \"Error in action start 'ShowTitle': ...\"\n * ```\n */\nexport class EngineActionError extends Error implements IEngineActionError {\n readonly actionName: string;\n readonly actionId: string;\n readonly phase: TActionPhase;\n readonly operationSystemName?: string;\n readonly operationIndex?: number;\n readonly operationPath?: readonly IOperationPathEntry[];\n readonly cause: unknown;\n\n /**\n * @param action - The failing action\n * @param phase - Whether its start or its end operations failed\n * @param cause - The original error\n */\n constructor(\n action: Pick<IAction, 'id' | 'name'>,\n phase: TActionPhase,\n cause: unknown\n ) {\n const {operationSystemName, operationIndex, operationPath} =\n readOperationContext(cause);\n const operation =\n operationSystemName === undefined\n ? ''\n : ` at operation '${operationSystemName}'${\n operationIndex === undefined ? '' : ` (index ${operationIndex})`\n }`;\n // For a failure inside a called action, name the calls that led there\n const callers =\n operationPath && operationPath.length > 1\n ? `, reached through ${operationPath\n .slice(0, -1)\n .map(entry => `'${entry.systemName}' (index ${entry.index})`)\n .join(' > ')}`\n : '';\n super(\n `Error in action ${phase} '${action.name}'${operation}${callers}: ${describeCause(cause)}`\n );\n this.name = 'EngineActionError';\n this.actionName = action.name;\n this.actionId = action.id;\n this.phase = phase;\n this.operationSystemName = operationSystemName;\n this.operationIndex = operationIndex;\n this.operationPath = operationPath;\n this.cause = cause;\n }\n}\n\nfunction readOperationContext(cause: unknown): {\n operationSystemName?: string;\n operationIndex?: number;\n operationPath?: readonly IOperationPathEntry[];\n} {\n if (cause === null || typeof cause !== 'object') {\n return {};\n }\n const {operationSystemName, operationIndex, operationPath} = cause as Record<\n string,\n unknown\n >;\n return {\n operationSystemName:\n typeof operationSystemName === 'string' ? operationSystemName : undefined,\n operationIndex:\n typeof operationIndex === 'number' ? operationIndex : undefined,\n operationPath: readOperationPath(operationPath),\n };\n}\n\n/**\n * A frozen copy of a well-formed operation path, or undefined for anything\n * else, so the engine error never shares or trusts the cause's array.\n */\nfunction readOperationPath(\n value: unknown\n): readonly IOperationPathEntry[] | undefined {\n if (!Array.isArray(value) || value.length === 0) {\n return undefined;\n }\n const entries: IOperationPathEntry[] = [];\n for (const entry of value) {\n if (\n entry === null ||\n typeof entry !== 'object' ||\n typeof entry.systemName !== 'string' ||\n typeof entry.index !== 'number'\n ) {\n return undefined;\n }\n entries.push(\n Object.freeze({systemName: entry.systemName, index: entry.index})\n );\n }\n return Object.freeze(entries);\n}\n\nfunction describeCause(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Type Guards\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Type guard to check if a position source supports seeking.\n */\nfunction isSeekable(\n source: IPositionSource\n): source is IPositionSource & ISeekable {\n return 'seek' in source && typeof (source as ISeekable).seek === 'function';\n}\n\n/**\n * Maps position source state to engine play state.\n */\nfunction mapSourceStateToPlayState(\n sourceState: IPositionSource['state']\n): 'playing' | 'paused' | 'stopped' {\n switch (sourceState) {\n case 'active':\n return 'playing';\n case 'suspended':\n return 'paused';\n case 'inactive':\n return 'stopped';\n }\n}\n\ntype ActionMethod =\n | (IEndableAction['start'] & ActionMethodMetadata)\n | (IEndableAction['end'] & ActionMethodMetadata);\n\ninterface ActionMethodMetadata {\n id: string;\n isStart: boolean;\n startPosition?: number;\n}\n\n/**\n * A start or end of a timeline action at a position on the timeline.\n */\ninterface IScheduledActionEvent {\n position: number;\n isStart: boolean;\n /**\n * Order among events at the same position: ends (0) before starts (1), so an\n * action ending at 5 is ended before one starting at 5 is started. The end\n * of a zero-length action (2) comes after its own start.\n */\n order: 0 | 1 | 2;\n action: ITimelineAction;\n}\n\n/**\n * A start that a position update, seek or switch decided on but has not run\n * yet, because it waits for ends to finish.\n */\ninterface IPendingStart {\n action: ITimelineAction;\n /** A later update passed its end before the start could run */\n endAfterStart: boolean;\n}\n\nconst noop = () => {};\nconst resolved: Promise<void> = Promise.resolve();\n\n/**\n * A position source that asks the engine to switch to the previous or next\n * timeline, like KeyboardStepSource in `timeline-switch` mode.\n */\ninterface ITimelineChangeRequester {\n onTimelineChangeRequest(\n callback: (direction: 'prev' | 'next') => void\n ): (() => void) | void;\n}\n\n/**\n * A position source that binds keys and leaves the keys that a\n * KeyboardController of its engine handles to that controller, like\n * KeyboardStepSource.\n */\ninterface IEngineRootReceiver {\n setEngineRoot(getRoot: () => Element | undefined): void;\n}\n\n/**\n * `actionId` of the error the engine emits when a timeline switch that a\n * position source requested fails.\n */\nconst TIMELINE_CHANGE_REQUEST_ID = 'timeline-change-request';\n\ninterface ISignal {\n promise: Promise<void>;\n resolve: () => void;\n}\n\nfunction createSignal(): ISignal {\n let resolve: () => void = noop;\n const promise = new Promise<void>(settle => {\n resolve = settle;\n });\n return {promise, resolve};\n}\n\n/** The part of a seek that other commands wait for, see `seek()` */\ninterface ISeekStep {\n source: IPositionSource;\n duration: number;\n /** Settles when the seek's starts have begun */\n reconciled: Promise<void>;\n}\n\n/**\n * The end of an action's range. The configuration marks an open-ended range\n * with a negative end; it is read as Infinity without changing the action.\n */\nfunction actionEnd(action: ITimelineAction): number {\n const {end} = action.duration;\n return end < 0 ? Infinity : end;\n}\n\n/**\n * Whether the action is in effect at the given position. Ranges are\n * half-open, `[start, end)`, so an action is ended exactly when the playhead\n * reaches its end, which matches what the position callback does.\n */\nfunction coversPosition(action: ITimelineAction, position: number) {\n return action.duration.start <= position && position < actionEnd(action);\n}\n\n/**\n * Index of the first event whose position is greater than `position`.\n */\nfunction upperBound(events: IScheduledActionEvent[], position: number) {\n let low = 0;\n let high = events.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (events[middle].position <= position) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n return low;\n}\n\nfunction invoke<T>(task: () => Promise<T>): Promise<T> {\n try {\n return task();\n } catch (error) {\n return Promise.reject(error);\n }\n}\n\n/**\n * The Eligius timeline engine with explicit, testable API.\n *\n * This engine is responsible for starting and stopping the given timeline provider\n * and triggering the actions associated with positions along the timeline.\n *\n * The engine reports its state through its own event emitter (see\n * {@link EngineEvents}). Mapping those events to eventbus broadcasts, and\n * eventbus commands such as `timeline-play-request` to engine calls, is done\n * by {@link EngineEventbusAdapter}, which {@link EngineFactory.createEngine}\n * connects. An engine constructed directly needs that adapter connected to be\n * driven through the eventbus.\n *\n * Transport commands are serialised: `init()`, `start()`, `seek()`,\n * `switchTimeline()` and the action cleanup of `stop()` run one after the\n * other, in call order; a command called while another one runs waits for\n * it. A later `seek()`, `stop()` or `destroy()` supersedes a `seek()` that\n * has not finished. A later `pause()`, `stop()` or `destroy()` cancels a\n * `start()` that has not activated the timeline yet, and keeps a pending\n * `switchTimeline()` from starting playback. `pause()` and the synchronous\n * part of `stop()` take effect at once. After `destroy()`, pending commands\n * do nothing more and new ones are ignored; a pending `init()` rejects.\n */\nexport class EligiusEngine implements IEligiusEngine {\n /**\n * Per timeline URI, every start and end of its timeline actions, sorted once\n * by position. Position updates process the slice between the previous and\n * the current position with a binary search, so tick cost does not depend on\n * the number of actions.\n */\n private _timelineSchedules: Map<string, IScheduledActionEvent[]> = new Map();\n private _timelineLookupCache: Map<string, IResolvedTimelineConfiguration> =\n new Map();\n private _eventbusRemovers: TEventbusRemover[] = [];\n private _currentTimelineUri: string = '';\n\n // Decomposed timeline provider components\n private _activePositionSource: IPositionSource | undefined = undefined;\n private _activeContainerProvider: IContainerProvider | undefined = undefined;\n private _activePlaylist: IPlaylist | undefined = undefined;\n /** The engine root, looked up once when the layout is created */\n private _engineRoot: JQuery<HTMLElement> | undefined = undefined;\n\n /** Position sources whose callbacks are registered */\n private _wiredSources: Set<IPositionSource> = new Set();\n /** Removes registrations on sources that destroy() must undo */\n private _sourceRemovers: Array<() => void> = [];\n /** Position sources whose init() succeeded */\n private _preparedSources: Set<IPositionSource> = new Set();\n /** Container providers whose init() succeeded */\n private _preparedContainers: Set<IContainerProvider> = new Set();\n /**\n * Sources and container providers whose init() has not settled yet.\n * destroy() leaves them alone; they are destroyed when init() settles.\n */\n private _initializing: Set<object> = new Set();\n /** Init actions whose start resolved, in start order */\n private _startedInitActions: Set<IEndableAction> = new Set();\n\n private _lastPosition: number = -1;\n /**\n * Set just before a source is activated. The first position it reports is\n * then reconciled like a seek instead of dispatched as an interval from the\n * previous position: a scroll container scrolled while its timeline was not\n * playing would otherwise start and end every action between the previous\n * position and its offset.\n */\n private _reconcileNextPosition = false;\n /** Position updates are ignored while a seek is in progress */\n private _seekDepth = 0;\n /** Settles when the last scheduled transport command has settled */\n private _transportTail: Promise<void> = resolved;\n /** Transport commands scheduled and not settled yet */\n private _transportPending = 0;\n /**\n * Incremented by seek(), stop() and destroy() (see `_bumpPositionToken`).\n * A seek that sees another value after an await has been superseded.\n */\n private _positionToken = 0;\n /** Resolved and replaced whenever `_positionToken` changes */\n private _positionTokenChanged: ISignal = createSignal();\n /**\n * Incremented by start(), pause(), stop() and destroy(). A pending start()\n * or switchTimeline() only starts playback while it is unchanged.\n */\n private _playToken = 0;\n private _initCalled = false;\n private _destroyed = false;\n private _destroyPromise: Promise<void> | undefined = undefined;\n /**\n * Starts waiting for ends to settle. Seeking, stopping, switching, cleanup\n * and destroy clear it, which cancels them.\n */\n private _pendingStarts: Map<ITimelineAction, IPendingStart> = new Map();\n /**\n * Settles when the last batch of starts that waited for ends has run.\n * Later batches wait for it, so starts run in timeline order. Undefined\n * when no batch is waiting.\n */\n private _startGate: Promise<void> | undefined = undefined;\n /** Live `error` subscriptions, to log errors nobody listens to */\n private _errorSubscriptions: Set<object> = new Set();\n private _emitter = new TypedEventEmitter<EngineEvents>();\n /** See {@link IEligiusEngineOptions.maxCatchUp} */\n private readonly _maxCatchUp: number;\n\n // ─────────────────────────────────────────────────────────────────────────\n // STATE (synchronous reads) - IEligiusEngine interface\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Current timeline position in seconds (supports fractional values); 0\n * when no timeline is active (before init() and after destroy())\n */\n get position(): number {\n return this._activePositionSource?.getPosition() ?? 0;\n }\n\n /** Timeline duration in seconds, undefined if not yet available */\n get duration(): number | undefined {\n return this._activePositionSource?.getDuration();\n }\n\n /** Current playback state (derived from position source state) */\n get playState(): 'playing' | 'paused' | 'stopped' {\n if (!this._activePositionSource) {\n return 'stopped';\n }\n return mapSourceStateToPlayState(this._activePositionSource.state);\n }\n\n /** URI of the currently active timeline */\n get currentTimelineUri(): string {\n return this._currentTimelineUri;\n }\n\n /** Container element for the active timeline provider */\n get container(): JQuery<HTMLElement> | undefined {\n return this._activeContainerProvider?.getContainer();\n }\n\n /**\n * Root element of the engine (container selector). From init() until\n * destroy() the same jQuery instance is returned.\n */\n get engineRoot(): JQuery<HTMLElement> {\n return this._engineRoot ?? $(this.configuration.containerSelector);\n }\n\n /**\n * @param configuration - The resolved engine configuration\n * @param eventbus - The eventbus, used for the callback-style state queries\n * @param timelineProviders - Timeline providers per timeline type\n * @param localeManager - The locale manager, destroyed with the engine\n * @param timelineProvidersByUri - Optional timeline providers per timeline\n * URI. When a timeline's URI has an entry it is used instead of the\n * provider for its type, so timelines of the same type can each have their\n * own position source (and duration).\n * @param localesReady - Optional promise that settles when externally\n * referenced (`$ref`) locales have been loaded into the locale manager.\n * {@link init} waits for it before running init actions, so labels can be\n * translated, and rejects if loading failed.\n * @param options - Optional engine options\n * @throws Error when an option is invalid\n */\n constructor(\n private configuration: IResolvedEngineConfiguration,\n private eventbus: IEventbus,\n private timelineProviders: Record<TimelineTypes, ITimelineProviderInfo>,\n private localeManager: ILocaleManager,\n private timelineProvidersByUri?: Record<string, ITimelineProviderInfo>,\n private localesReady?: Promise<void>,\n options?: IEligiusEngineOptions\n ) {\n const maxCatchUp = options?.maxCatchUp ?? Infinity;\n if (typeof maxCatchUp !== 'number' || !(maxCatchUp > 0)) {\n throw new Error(\n `EligiusEngine: options.maxCatchUp must be a positive number of seconds, got ${String(maxCatchUp)}`\n );\n }\n this._maxCatchUp = maxCatchUp;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // EVENTS - IEligiusEngine interface\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Subscribe to engine events.\n *\n * Errors of timeline actions that the engine starts or ends on its own are\n * reported through the `error` event; while it has no subscribers they are\n * logged with `console.error` instead. A subscription made with\n * `{forwardOnly: true}` (EngineEventbusAdapter makes one to broadcast\n * `engine-error`) does not count as a subscriber.\n *\n * @param event - Event name\n * @param handler - Event handler\n * @param options - Optional subscription options\n * @returns Unsubscribe function\n */\n on<K extends keyof EngineEvents>(\n event: K,\n handler: (...args: EngineEvents[K]) => void,\n options?: IEngineEventSubscriptionOptions\n ): () => void {\n const unsubscribe = this._emitter.on(event, handler);\n if (event !== 'error' || options?.forwardOnly) {\n return unsubscribe;\n }\n\n const subscription = {};\n this._errorSubscriptions.add(subscription);\n return () => {\n this._errorSubscriptions.delete(subscription);\n unsubscribe();\n };\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // PLAYBACK COMMANDS - IEligiusEngine interface\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Start playback.\n *\n * Waits for transport commands called earlier (for example the action\n * cleanup of `stop()`). Emits `start` once the timeline plays; not when it\n * already did, or when `pause()`, `stop()` or `destroy()` came first.\n *\n * @throws If autoplay is blocked (video provider)\n */\n start(): Promise<void> {\n if (this._destroyed) {\n return resolved;\n }\n const token = ++this._playToken;\n return this._schedule(() => this._start(token));\n }\n\n private async _start(token: number): Promise<void> {\n const source = this._activePositionSource;\n if (\n !source ||\n this._destroyed ||\n token !== this._playToken ||\n source.state === 'active'\n ) {\n return;\n }\n\n this._reconcileNextPosition = true;\n await source.activate();\n // activate() also resolves when pause/stop/destroy superseded it\n if (\n !this._destroyed &&\n source === this._activePositionSource &&\n this.playState === 'playing'\n ) {\n this._emitter.emit('start');\n }\n }\n\n /**\n * Pause playback. Emits `pause` when the timeline was playing. A `start()`\n * that has not activated the timeline yet is cancelled.\n */\n pause(): void {\n const source = this._activePositionSource;\n if (!source || this._destroyed) {\n return;\n }\n\n this._playToken++;\n if (source.state !== 'active') {\n return;\n }\n source.suspend();\n this._emitter.emit('pause');\n }\n\n /**\n * Stop playback and reset to the beginning.\n *\n * The position source is deactivated and the 'stop' event is emitted\n * synchronously; a pending `start()` or `seek()` is cancelled. The active\n * timeline actions are then ended, after transport commands called\n * earlier; the returned promise resolves when their end operations have\n * finished, or earlier when a later `seek()` or `stop()` takes over.\n * A `start()` called after `stop()` waits for it. Errors in end\n * operations are reported through the `error` event, not rethrown.\n */\n stop(): Promise<void> {\n const source = this._activePositionSource;\n if (!source || this._destroyed) {\n return resolved;\n }\n\n this._playToken++;\n const token = this._bumpPositionToken();\n source.deactivate();\n this._lastPosition = -1;\n this._cancelPendingStarts();\n this._emitter.emit('stop');\n\n return this._schedule(() =>\n this._waitUnlessSuperseded(this._endActiveActionsReporting(), token)\n );\n }\n\n /**\n * Seek to a specific position.\n *\n * Ends the active actions that do not cover the position and, once those\n * ends have finished, starts the ones that do. The returned promise\n * resolves when the starts have begun; it does not wait for start\n * operations to finish. Failing actions are reported through the `error`\n * event. Other commands only wait for the source to seek, not for the\n * end operations. A later `seek()` or `stop()` supersedes this one: it\n * then resolves with the position at that moment without emitting\n * `seekComplete`, and its starts that had not run yet are dropped. When a\n * `switchTimeline()` replaces the timeline before the seek's starts have\n * begun, it resolves with the new timeline's position, also without\n * emitting `seekComplete`.\n *\n * @param position - Target position in seconds\n * @returns Actual position after seek\n */\n seek(position: number): Promise<number> {\n if (this._destroyed || !Number.isFinite(position) || position < 0) {\n return Promise.resolve(this.position);\n }\n const source = this._activePositionSource;\n if (source && position > source.getDuration()) {\n return Promise.resolve(source.getPosition());\n }\n\n const token = this._bumpPositionToken();\n // Starts still waiting (including those of a seek this one supersedes)\n // are replaced by this seek's reconciliation.\n this._cancelPendingStarts();\n return this._schedule(() =>\n this._seekSourceAndReconcile(position, token)\n ).then(async step => {\n if (!step) {\n return this.position;\n }\n await this._waitUnlessSuperseded(step.reconciled, token);\n if (!this._destroyed && step.source !== this._activePositionSource) {\n // A switchTimeline() took over: the seeked timeline is gone.\n return this.position;\n }\n const finalPosition = step.source.getPosition();\n if (!this._isSuperseded(token)) {\n this._emitter.emit('seekComplete', finalPosition, step.duration);\n this._emitter.emit('time', finalPosition);\n }\n return finalPosition;\n });\n }\n\n /**\n * The part of a seek that other transport commands wait for: seeking the\n * source and deciding which actions to end and start. Resolves with the\n * reconciliation still running, or undefined when the seek did not happen.\n */\n private async _seekSourceAndReconcile(\n position: number,\n token: number\n ): Promise<ISeekStep | undefined> {\n const source = this._activePositionSource;\n if (!source || this._isSuperseded(token)) {\n return undefined;\n }\n const currentPosition = source.getPosition();\n const duration = source.getDuration();\n if (position > duration) {\n return undefined;\n }\n\n this._emitter.emit('seekStart', position, currentPosition, duration);\n this._cancelPendingStarts();\n\n await this._seekSource(source, position);\n if (this._isSuperseded(token)) {\n return undefined;\n }\n // The seek target is reconciled below; the position update the source\n // emits for it (now, or when it resumes) must not dispatch actions again.\n this._lastPosition = position;\n const reconciled = this._reconcileActions(\n this._currentTimelineUri,\n position\n );\n return {source, duration, reconciled};\n }\n\n private _isSuperseded(positionToken: number) {\n return this._destroyed || positionToken !== this._positionToken;\n }\n\n /**\n * Increments the position token, which supersedes running seeks and\n * releases the waits of `_waitUnlessSuperseded`.\n *\n * @returns The new token\n */\n private _bumpPositionToken(): number {\n this._positionToken++;\n const changed = this._positionTokenChanged;\n this._positionTokenChanged = createSignal();\n changed.resolve();\n return this._positionToken;\n }\n\n /**\n * Waits for `work`, unless the position token changes first (a later\n * seek, stop or destroy), so a slow or hung end operation cannot hold up\n * the commands that follow.\n */\n private _waitUnlessSuperseded(\n work: Promise<void>,\n token: number\n ): Promise<void> {\n if (this._isSuperseded(token)) {\n return resolved;\n }\n return Promise.race([work, this._positionTokenChanged.promise]);\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // TIMELINE MANAGEMENT - IEligiusEngine interface\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Switch to a different timeline.\n *\n * First initialises the new timeline's position source and container\n * provider on first use. If that fails, the current timeline is left as it\n * was and the promise rejects, so a later call retries. Then it ends the\n * active actions of the current timeline, activates the new timeline,\n * seeks it to `position`, emits `timelineChange`, starts the actions that\n * cover that position and starts playback (unless `pause()` or `stop()`\n * was called after this call). The returned promise resolves when\n * playback has started; it does not wait for start operations to finish.\n * Failing actions are reported through the `error` event. Concurrent\n * calls are processed one after the other. Switching to the current\n * timeline does nothing.\n *\n * @param uri - Timeline URI to switch to\n * @param position - Optional starting position\n * @throws Error (rejects) when the engine is not initialised or no timeline\n * has the URI\n */\n switchTimeline(uri: string, position: number = 0): Promise<void> {\n if (this._destroyed) {\n return resolved;\n }\n if (!this._initCalled) {\n return Promise.reject(\n new Error(\n `EligiusEngine.switchTimeline('${uri}'): the engine is not initialised, call init() first`\n )\n );\n }\n const timelineConfig = this._timelineLookupCache.get(uri);\n if (!timelineConfig) {\n return Promise.reject(this._unknownTimelineError(uri));\n }\n\n const playToken = this._playToken;\n return this._schedule(() =>\n this._switchTimeline(timelineConfig, position, playToken)\n );\n }\n\n private _unknownTimelineError(uri: string) {\n const known = [...this._timelineLookupCache.keys()];\n const suggestion = formatDidYouMean(findClosestNames(uri, known));\n return new Error(\n `EligiusEngine.switchTimeline('${uri}'): unknown timeline URI. ${\n suggestion ? `${suggestion} ` : ''\n }Known timelines: ${known.map(name => `'${name}'`).join(', ')}`\n );\n }\n\n private async _switchTimeline(\n timelineConfig: IResolvedTimelineConfiguration,\n position: number,\n playToken: number\n ): Promise<void> {\n const previousSource = this._activePositionSource;\n if (\n this._destroyed ||\n !previousSource ||\n this._currentTimelineUri === timelineConfig.uri\n ) {\n return;\n }\n\n const providerInfo = this._getProviderInfo(timelineConfig);\n if (!providerInfo?.positionSource) {\n throw new Error(\n `EligiusEngine.switchTimeline('${timelineConfig.uri}'): no timeline provider configured for type '${timelineConfig.type}'`\n );\n }\n const source = providerInfo.positionSource;\n const {playlist} = providerInfo;\n if (playlist?.hasItem && !playlist.hasItem(timelineConfig.uri)) {\n throw new Error(\n `EligiusEngine.switchTimeline('${timelineConfig.uri}'): the timeline's playlist has no item '${timelineConfig.uri}'`\n );\n }\n\n // Initialise first: when that fails (a video that does not load) the\n // current timeline keeps running and a later switch retries.\n await this._prepareProvider(providerInfo);\n if (this._destroyed) {\n return;\n }\n\n const previousUri = this._currentTimelineUri;\n previousSource.deactivate();\n this._lastPosition = -1;\n this._cancelPendingStarts();\n await this._waitUnlessSuperseded(\n this._endActiveActionsReporting(previousUri),\n this._positionToken\n );\n if (this._destroyed) {\n return;\n }\n\n this._activePositionSource = source;\n this._activeContainerProvider = providerInfo.containerProvider;\n this._activePlaylist = providerInfo.playlist;\n this._currentTimelineUri = timelineConfig.uri;\n source.loop = timelineConfig.loop;\n this._activePlaylist?.selectItem(timelineConfig.uri);\n\n let target = source.getPosition();\n if (position > 0 && Number.isFinite(position) && isSeekable(source)) {\n const duration = source.getDuration();\n target =\n Number.isFinite(duration) && duration > 0\n ? Math.min(position, duration)\n : position;\n await this._seekSource(source, target);\n if (this._destroyed) {\n return;\n }\n }\n\n // The new timeline is active now, so listeners that query the engine get\n // its source, container, duration and position.\n this._emitter.emit('timelineChange', timelineConfig.uri);\n\n // Start the actions covering the start position here, so the position\n // update that activation emits does not dispatch them a second time.\n this._lastPosition = target;\n await this._reconcileActions(timelineConfig.uri, target);\n\n if (this._destroyed || playToken !== this._playToken) {\n return;\n }\n this._reconcileNextPosition = true;\n await source.activate();\n }\n\n /**\n * Initializes the engine by creating the HTML layout and the first time line\n * by executing its initActions.\n *\n * @returns The position source of the first timeline\n * @throws Error when the container selector matches nothing (synchronously)\n * @throws Error (rejects) when there are no timelines or no provider for the\n * first timeline, when its source fails to initialise, an init action\n * fails or external locales fail to load, and when the engine is destroyed\n * before init completes\n */\n init(): Promise<IPositionSource> {\n if (this._destroyed) {\n return Promise.reject(\n new Error('EligiusEngine.init(): the engine has been destroyed')\n );\n }\n\n this._createLayoutTemplate();\n\n this._removeEventbusListeners();\n this._addEventbusListeners();\n\n const {timelines} = this.configuration;\n\n this._currentTimelineUri = timelines?.[0]?.uri ?? '';\n\n this._createTimelineLookup();\n this._initCalled = true;\n\n return this._schedule(() => this._initialize());\n }\n\n private async _initialize(): Promise<IPositionSource> {\n if (this.localesReady) {\n await this.localesReady;\n this._throwIfDestroyed('init()');\n }\n return this._initializeTimelineProvider();\n }\n\n private _throwIfDestroyed(method: string) {\n if (this._destroyed) {\n throw new Error(\n `EligiusEngine.${method}: the engine was destroyed before it completed`\n );\n }\n }\n\n private _createLayoutTemplate() {\n const {containerSelector} = this.configuration;\n const container = $(containerSelector);\n\n if (!container?.length) {\n throw new Error(`Container selector not found: ${containerSelector}`);\n }\n this._engineRoot = container;\n\n const {layoutTemplate} = this.configuration;\n\n if (layoutTemplate?.length) {\n // html() drops the jQuery data of the replaced elements, so controllers\n // still attached to them would stay subscribed to the eventbus.\n const errors = detachControllersWithin(\n container.children(),\n this.eventbus\n );\n errors.forEach(error => {\n console.error(\n 'EligiusEngine.init(): detaching a controller from the replaced layout failed',\n error\n );\n });\n container.html(layoutTemplate);\n } else {\n console.warn('layoutTemplate is empty, unable to create layout');\n }\n }\n\n private async _initializeTimelineProvider(): Promise<IPositionSource> {\n if (!this.configuration.timelines?.length) {\n throw new Error('No timelines present');\n }\n\n const firstTimeline = this.configuration.timelines[0];\n const providerSettings = this._getProviderInfo(firstTimeline);\n\n if (!providerSettings) {\n throw new Error(\n `No timeline provider configured for type ${firstTimeline.type}`\n );\n }\n\n if (!providerSettings.positionSource) {\n throw new Error('NO ACTIVE POSITION SOURCE');\n }\n\n this._lastPosition = -1;\n await this._prepareProvider(providerSettings);\n this._throwIfDestroyed('init()');\n this._activePositionSource = providerSettings.positionSource;\n this._activeContainerProvider = providerSettings.containerProvider;\n this._activePlaylist = providerSettings.playlist;\n providerSettings.positionSource.loop = firstTimeline.loop;\n\n for (const action of this.configuration.initActions ?? []) {\n await action.start();\n if (this._destroyed) {\n // destroy() only ended the init actions that had started before\n await this._runActionMethod(action, 'end');\n this._throwIfDestroyed('init()');\n }\n this._startedInitActions.add(action);\n }\n this._emitter.emit('initialized');\n return providerSettings.positionSource;\n }\n\n private _getProviderInfo(\n timeline: IResolvedTimelineConfiguration\n ): ITimelineProviderInfo | undefined {\n return (\n this.timelineProvidersByUri?.[timeline.uri] ??\n this.timelineProviders?.[timeline.type]\n );\n }\n\n /**\n * Initialises the provider's position source and container provider the\n * first time they are used, registering the engine callbacks on the\n * source. A failed init is not remembered, so the next use retries it.\n */\n private async _prepareProvider(providerInfo: ITimelineProviderInfo) {\n await this._prepareSource(providerInfo.positionSource);\n if (this._destroyed) {\n return;\n }\n await this._prepareContainer(\n providerInfo.containerProvider,\n providerInfo.positionSource\n );\n }\n\n private async _prepareSource(source: IPositionSource) {\n if (this._preparedSources.has(source)) {\n return;\n }\n this._wireSource(source);\n await this._initializeComponent(source, () => source.init());\n if (!this._destroyed) {\n this._preparedSources.add(source);\n }\n }\n\n /**\n * Registers the engine callbacks on a source, once per source.\n */\n private _wireSource(source: IPositionSource) {\n if (this._wiredSources.has(source)) {\n return;\n }\n this._wiredSources.add(source);\n\n // Sources stay registered after a switch, so every callback ignores\n // events from sources that are not the active one.\n source.onPosition(position => {\n if (source === this._activePositionSource) {\n this._onTimeHandler(position);\n }\n });\n source.onBoundaryReached(boundary => {\n if (source !== this._activePositionSource) {\n return;\n }\n if (boundary === 'end') {\n this._onCompleteCallback();\n } else if (boundary === 'start') {\n this._onRestartCallback();\n }\n });\n source.onActivated(() => {\n if (source === this._activePositionSource) {\n this._onFirstFrameCallback();\n }\n });\n this._wireTimelineChangeRequests(source);\n this._wireEngineRoot(source);\n }\n\n /**\n * Sources that bind keys (KeyboardStepSource) get the engine root, so they\n * leave a key to a KeyboardController of this engine that handles it.\n */\n private _wireEngineRoot(source: IPositionSource) {\n const receiver = source as Partial<IEngineRootReceiver>;\n if (typeof receiver.setEngineRoot === 'function') {\n receiver.setEngineRoot(() => this._engineRoot?.[0]);\n }\n }\n\n /**\n * Sources that ask for timeline changes (KeyboardStepSource in\n * `timeline-switch` mode) switch to the previous or next configured\n * timeline, from its start. Requests at the first or the last timeline do\n * nothing. A failed switch is reported through the `error` event.\n */\n private _wireTimelineChangeRequests(source: IPositionSource) {\n const requester = source as Partial<ITimelineChangeRequester>;\n if (\n typeof requester.onTimelineChangeRequest !== 'function' ||\n (this.configuration.timelines?.length ?? 0) < 2\n ) {\n // With a single timeline Up/Down keep their default behaviour.\n return;\n }\n const remover = requester.onTimelineChangeRequest(direction => {\n if (this._destroyed || source !== this._activePositionSource) {\n return;\n }\n const uris = (this.configuration.timelines ?? []).map(\n timeline => timeline.uri\n );\n const index = uris.indexOf(this._currentTimelineUri);\n const target = index + (direction === 'next' ? 1 : -1);\n if (index === -1 || target < 0 || target >= uris.length) {\n return;\n }\n const uri = uris[target];\n this.switchTimeline(uri, 0).catch(error => {\n this._reportActionError(\n {id: TIMELINE_CHANGE_REQUEST_ID, name: `switchTimeline('${uri}')`},\n 'start',\n error\n );\n });\n });\n if (typeof remover === 'function') {\n this._sourceRemovers.push(remover);\n }\n }\n\n private async _prepareContainer(\n containerProvider: IContainerProvider | undefined,\n source: IPositionSource\n ) {\n if (\n !containerProvider ||\n (containerProvider as unknown) === source ||\n this._preparedContainers.has(containerProvider)\n ) {\n return;\n }\n await this._initializeComponent(containerProvider, async () => {\n await containerProvider.init?.();\n });\n if (!this._destroyed) {\n this._preparedContainers.add(containerProvider);\n }\n }\n\n /**\n * Runs a component's init(). When the engine was destroyed meanwhile,\n * destroy() skipped the component, so it is destroyed here.\n */\n private async _initializeComponent(\n component: {destroy?(): void},\n init: () => Promise<void>\n ) {\n this._initializing.add(component);\n try {\n await init();\n } finally {\n this._initializing.delete(component);\n if (this._destroyed) {\n try {\n component.destroy?.();\n } catch (error) {\n console.error(\n 'EligiusEngine: destroying a component that finished initialising after destroy() failed',\n error\n );\n }\n }\n }\n }\n\n private _onCompleteCallback() {\n // playState is now derived from position source state\n this._emitter.emit('timelineComplete');\n }\n\n private _onFirstFrameCallback() {\n this._emitter.emit('timelineFirstFrame');\n\n const duration = this._activePositionSource?.getDuration();\n if (duration !== undefined) {\n this._emitter.emit('duration', duration);\n }\n }\n\n private _onRestartCallback() {\n this._emitter.emit('timelineRestart');\n }\n\n /**\n * Cleans up all the necessary parts that the engine initialized.\n * - It stops the active position source and cancels pending commands.\n * - It ends the currently active timeline actions and the init actions\n * that started.\n * - It detaches the controllers still attached to elements inside the\n * engine root (those that no end operation removed).\n * - It removes all its eventbus listeners.\n * - It destroys all of its position sources and container providers.\n * - It empties the HTML element indicated by the containerSelector configuration property.\n *\n * Every step runs even when an earlier one fails. Errors are rethrown at\n * the end (an AggregateError when there is more than one). Calling it\n * again returns the same promise; the teardown runs once.\n */\n destroy(): Promise<void> {\n this._destroyPromise ??= this._destroy();\n return this._destroyPromise;\n }\n\n private async _destroy() {\n // Pending commands check this after every await and do nothing more.\n this._destroyed = true;\n this._playToken++;\n this._bumpPositionToken();\n\n const errors: unknown[] = [];\n const attempt = (step: () => void) => {\n try {\n step();\n } catch (error) {\n errors.push(error);\n }\n };\n\n // Stop the clock first, so no tick starts actions while others end.\n const activeSource = this._activePositionSource;\n attempt(() => activeSource?.deactivate());\n this._cancelPendingStarts();\n\n await this._endActionsSettled(\n this._getActiveActions(this._getTimelineActionsForCurrentTimeline()),\n errors\n );\n const initActions = [...this._startedInitActions].reverse();\n this._startedInitActions.clear();\n await this._endActionsSettled(initActions, errors);\n\n // After the end operations, so a removeControllerFromElement in them\n // still finds its controller.\n attempt(() => {\n errors.push(\n ...detachControllersWithin(\n $(this.configuration.containerSelector),\n this.eventbus\n )\n );\n });\n\n attempt(() => this.localeManager.destroy());\n\n const sourceRemovers = this._sourceRemovers.splice(0);\n sourceRemovers.forEach(remove => {\n attempt(remove);\n });\n\n this._activePositionSource = undefined;\n this._activeContainerProvider = undefined;\n this._activePlaylist = undefined;\n attempt(() => this._removeEventbusListeners());\n\n // Components still initialising are destroyed when their init settles.\n const providers = this._allProviderInfos();\n const sources = new Set(providers.map(info => info.positionSource));\n sources.forEach(source => {\n if (source && !this._initializing.has(source)) {\n attempt(() => source.destroy());\n }\n });\n new Set(providers.map(info => info.containerProvider)).forEach(\n containerProvider => {\n if (\n containerProvider &&\n !sources.has(containerProvider as unknown as IPositionSource) &&\n !this._initializing.has(containerProvider)\n ) {\n attempt(() => containerProvider.destroy?.());\n }\n }\n );\n this._preparedSources.clear();\n this._preparedContainers.clear();\n\n attempt(() => {\n const {containerSelector} = this.configuration;\n $(containerSelector).empty();\n });\n this._engineRoot = undefined;\n\n attempt(() => this._emitter.emit('destroyed'));\n this._emitter.removeAllListeners();\n this._errorSubscriptions.clear();\n\n if (errors.length === 1) {\n throw errors[0];\n }\n if (errors.length > 1) {\n throw new AggregateError(errors, 'Errors while destroying the engine');\n }\n }\n\n private _allProviderInfos(): ITimelineProviderInfo[] {\n return [\n ...Object.values(this.timelineProviders ?? {}),\n ...Object.values(this.timelineProvidersByUri ?? {}),\n ].filter(Boolean) as ITimelineProviderInfo[];\n }\n\n private async _endActionsSettled(\n actions: IEndableAction[],\n errors: unknown[]\n ) {\n for (const action of actions) {\n try {\n await action.end();\n } catch (error) {\n errors.push(error);\n }\n }\n }\n\n /**\n * Runs `task` once the transport commands scheduled before it have\n * settled. When none is pending it runs right away, synchronously up to\n * its first await, so `start()` on an idle engine activates the source\n * before it returns.\n */\n private _schedule<T>(task: () => Promise<T>): Promise<T> {\n const previous = this._transportTail;\n const idle = this._transportPending === 0;\n let release: () => void = noop;\n this._transportTail = new Promise<void>(resolve => {\n release = resolve;\n });\n this._transportPending++;\n\n const run = idle ? invoke(task) : previous.then(task);\n const settle = () => {\n this._transportPending--;\n release();\n };\n run.then(settle, settle);\n return run;\n }\n\n private _addEventListener(\n eventName: string,\n eventHandler: TEventHandler,\n eventTopic?: string\n ) {\n this._eventbusRemovers.push(\n this.eventbus.on(eventName as EventName, eventHandler, eventTopic)\n );\n }\n\n private _removeEventbusListeners() {\n const removers = this._eventbusRemovers;\n this._eventbusRemovers = [];\n removers.forEach(remover => remover());\n }\n\n /**\n * Registers the callback-style eventbus queries (`broadcast(name,\n * [resultCallback])`). Playback commands (`timeline-play-request` and so\n * on) and state broadcasts are owned by EngineEventbusAdapter.\n */\n private _addEventbusListeners() {\n this._addEventListener(\n 'request-current-timeline-position',\n this._handleRequestTimelinePosition.bind(this)\n );\n this._addEventListener(\n 'request-timeline-cleanup',\n this._handleTimelineComplete.bind(this)\n );\n this._addEventListener(\n 'timeline-request-current-timeline',\n this._requestCurrentTimeline.bind(this)\n );\n this._addEventListener(\n 'timeline-container-request',\n this._containerRequest.bind(this)\n );\n this._addEventListener(\n 'timeline-duration-request',\n this._durationRequest.bind(this)\n );\n }\n\n private _durationRequest(callBack: TResultCallback<number | undefined>) {\n callBack(this.duration);\n }\n\n private _containerRequest(\n callBack: TResultCallback<JQuery<HTMLElement> | undefined>\n ) {\n callBack(this.container);\n }\n\n private _createTimelineLookup() {\n this._timelineSchedules = new Map();\n this._timelineLookupCache = new Map();\n\n if (!this.configuration.timelines) {\n return;\n }\n\n this.configuration.timelines.forEach(timelineInfo => {\n // Populate timeline lookup cache for O(1) access\n this._timelineLookupCache.set(timelineInfo.uri, timelineInfo);\n this._timelineSchedules.set(\n timelineInfo.uri,\n EligiusEngine._createSchedule(timelineInfo.timelineActions)\n );\n });\n }\n\n /**\n * Builds the sorted start and end events of a timeline. The actions are\n * only read; an open-ended range (negative end) gets no end event.\n */\n private static _createSchedule(\n timelineActions: ITimelineAction[]\n ): IScheduledActionEvent[] {\n const events: IScheduledActionEvent[] = [];\n\n timelineActions.forEach(action => {\n const {start} = action.duration;\n const end = actionEnd(action);\n\n events.push({position: start, isStart: true, order: 1, action});\n if (Number.isFinite(end)) {\n events.push({\n position: end,\n isStart: false,\n order: end === start ? 2 : 0,\n action,\n });\n }\n });\n\n // Array.prototype.sort is stable, so starts at the same position keep\n // their configuration order.\n return events.sort((a, b) => {\n if (a.position !== b.position) {\n return a.position - b.position;\n }\n if (a.order !== b.order) {\n return a.order - b.order;\n }\n return a.isStart\n ? 0\n : sortActionsHighestStartPositionFirst(a.action, b.action);\n });\n }\n\n /**\n * @deprecated Left over from the removed per-position dispatch; the engine\n * does not use it. Will be removed in the next major version.\n */\n static sortTimelines(timelines: Record<number, ActionMethod[]>[]) {\n timelines.forEach(timelineActions => {\n Object.keys(timelineActions).forEach(key => {\n const numericKey = Number(key);\n timelineActions[numericKey] = EligiusEngine.sortActionsPerPosition(\n timelineActions[numericKey]\n );\n });\n });\n }\n\n /**\n * @deprecated Left over from the removed per-position dispatch; the engine\n * does not use it. Will be removed in the next major version.\n */\n static sortActionsPerPosition(actions: ActionMethod[]) {\n const [startMethods, endMethods] = actions.reduce(\n (acc, item) => {\n if (item.isStart) {\n acc[0].push(item);\n } else {\n acc[1].push(item);\n }\n return acc;\n },\n [[], []] as [ActionMethod[], ActionMethod[]]\n );\n return [\n ...endMethods.sort(sortActionMethodsHighestStartPositionFirst),\n ...startMethods,\n ];\n }\n\n private _getActiveActions(allActions: ITimelineAction[]) {\n const actions = allActions.filter(action => action.active);\n return actions.sort(sortActionsHighestStartPositionFirst);\n }\n\n /**\n * Answers with {@link position}, like the `request()` responder of\n * EngineEventbusAdapter does: 0 when no timeline is active.\n */\n private _handleRequestTimelinePosition(\n resultCallback: TResultCallback<number>\n ) {\n resultCallback(this.position);\n }\n\n private _handleTimelineComplete() {\n this._cancelPendingStarts();\n void this._endActiveActionsReporting();\n }\n\n /**\n * Ends every active action of the given timeline (the current one by\n * default), highest start position first, reporting failures through the\n * `error` event. The returned promise never rejects.\n */\n private async _endActiveActionsReporting(\n uri: string = this._currentTimelineUri\n ): Promise<void> {\n const actions = this._getActiveActions(this._getTimelineActionsForUri(uri));\n for (const action of actions) {\n await this._runActionMethod(action, 'end');\n }\n }\n\n /**\n * Calls the start or end of an action that the engine dispatches on its\n * own, routing a failure to the `error` event. The returned promise never\n * rejects.\n */\n private _runActionMethod(\n action: IEndableAction,\n phase: TActionPhase\n ): Promise<void> {\n try {\n return Promise.resolve(action[phase]()).then(noop, error =>\n this._reportActionError(action, phase, error)\n );\n } catch (error) {\n this._reportActionError(action, phase, error);\n return resolved;\n }\n }\n\n /**\n * Emits the failure through the `error` event; while nothing but\n * forward-only subscriptions listen, it is also logged with its cause, so\n * the original stack is kept.\n */\n private _reportActionError(\n action: Pick<IAction, 'id' | 'name'>,\n phase: TActionPhase,\n cause: unknown\n ) {\n const error = new EngineActionError(action, phase, cause);\n this._emitter.emit('error', error);\n if (this._errorSubscriptions.size === 0) {\n console.error(error.message, cause);\n }\n }\n\n private _getTimelineActionsForCurrentTimeline() {\n return this._getTimelineActionsForUri(this._currentTimelineUri);\n }\n\n private _requestCurrentTimeline(resultCallback: TResultCallback<string>) {\n resultCallback(this._currentTimelineUri);\n }\n\n private _getTimelineActionsForUri(uri: string): ITimelineAction[] {\n const info = this._timelineLookupCache.get(uri);\n return info?.timelineActions ?? [];\n }\n\n /**\n * Seeks the source (when it is seekable) without dispatching the position\n * updates it emits while seeking; the caller reconciles the actions.\n */\n private async _seekSource(source: IPositionSource, position: number) {\n if (!isSeekable(source)) {\n return;\n }\n\n this._seekDepth++;\n try {\n await source.seek(position);\n } finally {\n this._seekDepth--;\n }\n }\n\n private _onTimeHandler(position: number) {\n if (Number.isNaN(position) || this._seekDepth > 0) {\n return;\n }\n if (this._reconcileNextPosition) {\n this._reconcileNextPosition = false;\n if (this._lastPosition !== position) {\n this._lastPosition = position;\n void this._reconcileActions(this._currentTimelineUri, position);\n this._emitter.emit('time', position);\n }\n return;\n }\n if (this._lastPosition === position) {\n return;\n }\n\n const previousPosition = this._lastPosition;\n this._lastPosition = position;\n this._dispatchActionsBetween(previousPosition, position);\n this._emitter.emit('time', position);\n }\n\n /**\n * Dispatches the timeline actions whose start or end lies between the\n * previous and the current position.\n *\n * Moving forward, every start and end in `(from, to]` is processed in\n * position order, so skipped frames and coarse sources (video timeupdate,\n * scroll, keyboard steps) never miss an action. A forward jump larger than\n * `maxCatchUp` is reconciled like a seek instead. Moving backward, the\n * actions whose range no longer covers the position are ended and the ones\n * that cover it again are started, like a seek. Actions track their own\n * `active` state, so revisiting a key never runs a start or end twice.\n *\n * All ends run before any start: when the update ends actions, or starts\n * of an earlier update are still waiting, its starts wait (as pending\n * starts) until those have run. An action whose start and end both lie in\n * the update (a skipped or zero-length range) is ended right after it is\n * started; TimelineAction runs its end operations once its start\n * operations have finished. Nothing is awaited here, and nothing is\n * allocated when the update crosses no start or end. Failures are reported\n * through the `error` event.\n */\n private _dispatchActionsBetween(from: number, to: number) {\n const events = this._timelineSchedules.get(this._currentTimelineUri);\n if (!events?.length) {\n return;\n }\n\n const forward = to > from;\n const low = upperBound(events, forward ? from : to);\n const high = upperBound(events, forward ? to : from);\n if (low === high) {\n return;\n }\n\n if (forward && to - from > this._maxCatchUp) {\n void this._reconcileActions(this._currentTimelineUri, to);\n return;\n }\n\n const pending = this._pendingStarts;\n const ends: ITimelineAction[] = [];\n const starts: IPendingStart[] = [];\n\n if (forward) {\n for (let i = low; i < high; i++) {\n const {action, isStart} = events[i];\n if (isStart) {\n if (!action.active && !pending.has(action)) {\n this._addPendingStart(action, starts);\n }\n } else if (action.active) {\n ends.push(action);\n } else {\n const start = pending.get(action);\n if (start) {\n start.endAfterStart = true;\n }\n }\n }\n } else {\n const toStart: ITimelineAction[] = [];\n for (let i = high - 1; i >= low; i--) {\n const {action, isStart} = events[i];\n if (isStart) {\n if (action.active) {\n ends.push(action);\n } else {\n // Back before its start: a start that is still waiting is dropped.\n pending.delete(action);\n }\n } else if (!action.active && action.duration.start <= to) {\n const start = pending.get(action);\n if (start) {\n start.endAfterStart = false;\n } else {\n toStart.push(action);\n }\n }\n }\n toStart\n .sort((a, b) => a.duration.start - b.duration.start)\n .forEach(action => this._addPendingStart(action, starts));\n }\n\n void this._runEndsThenStarts(ends, starts);\n }\n\n private _addPendingStart(action: ITimelineAction, starts: IPendingStart[]) {\n const start: IPendingStart = {action, endAfterStart: false};\n this._pendingStarts.set(action, start);\n starts.push(start);\n }\n\n /**\n * Ends the given actions, and runs the given pending starts once those\n * ends and every earlier batch of waiting starts have settled; right away\n * when there is nothing to wait for. The returned promise settles when the\n * starts have been run (not when their operations finish) and never\n * rejects.\n */\n private _runEndsThenStarts(\n ends: ITimelineAction[],\n starts: IPendingStart[]\n ): Promise<void> {\n const waitFor: Promise<void>[] = [];\n for (const action of ends) {\n waitFor.push(this._runActionMethod(action, 'end'));\n }\n if (starts.length && this._startGate) {\n waitFor.push(this._startGate);\n }\n if (!waitFor.length) {\n this._runPendingStarts(starts);\n return resolved;\n }\n\n const settled = Promise.all(waitFor).then(noop);\n if (!starts.length) {\n return settled;\n }\n const gate: Promise<void> = settled.then(() => {\n if (this._startGate === gate) {\n this._startGate = undefined;\n }\n this._runPendingStarts(starts);\n });\n this._startGate = gate;\n return gate;\n }\n\n /**\n * Cancels the starts that are waiting for ends, and the ordering of later\n * starts behind them.\n */\n private _cancelPendingStarts() {\n this._pendingStarts.clear();\n this._startGate = undefined;\n }\n\n /**\n * Runs the given pending starts that are still pending; seeking, stopping,\n * switching, cleanup, destroy or a later update may have cancelled them.\n */\n private _runPendingStarts(starts: IPendingStart[]) {\n for (const start of starts) {\n const {action} = start;\n if (this._pendingStarts.get(action) !== start) {\n continue;\n }\n this._pendingStarts.delete(action);\n void this._runActionMethod(action, 'start');\n if (start.endAfterStart) {\n void this._runActionMethod(action, 'end');\n }\n }\n }\n\n /**\n * Brings the actions of a timeline in line with a position: ends the active\n * actions that do not cover it and, once those ends have finished, starts\n * the inactive ones that do. The `active` flags change synchronously, so\n * position updates that arrive meanwhile see the reconciled state. The\n * returned promise settles once the starts have begun and never rejects;\n * failures are reported through the `error` event.\n */\n private _reconcileActions(uri: string, position: number): Promise<void> {\n const timelineActions = this._getTimelineActionsForUri(uri);\n const ends = this._getActiveActions(timelineActions).filter(\n action => !coversPosition(action, position)\n );\n const starts: IPendingStart[] = [];\n for (const action of timelineActions) {\n const pending = this._pendingStarts.get(action);\n if (pending) {\n pending.endAfterStart = !coversPosition(action, position);\n } else if (!action.active && coversPosition(action, position)) {\n this._addPendingStart(action, starts);\n }\n }\n return this._runEndsThenStarts(ends, starts);\n }\n}\n\nconst sortActionsHighestStartPositionFirst = (\n a: ITimelineAction,\n b: ITimelineAction\n) => b.duration.start - a.duration.start;\n\nconst sortActionMethodsHighestStartPositionFirst = (\n a: ActionMethod,\n b: ActionMethod\n) => {\n if (a.startPosition === undefined || b.startPosition === undefined) {\n return 0;\n }\n return b.startPosition - a.startPosition;\n};\n","import type {TRegisteredResourceKind} from '../types.ts';\n\n/**\n * Shape checks shared by `EligiusResourceImporter` and `createImporter`, so\n * both reject a resource of the wrong shape with the same message.\n */\n\n/**\n * The kinds a resource importer can provide: the registrable kinds plus the\n * engine and timeline provider classes that only `createImporter` takes.\n */\nexport type TImporterResourceKind =\n | TRegisteredResourceKind\n | 'engine'\n | 'provider';\n\n/**\n * Returns why `value` cannot be provided as a `kind`, or `undefined` when it\n * can. Operations are checked the way the configuration resolver checks\n * them: a function that is not a class.\n */\nexport function checkShape(\n kind: TImporterResourceKind,\n value: unknown\n): string | undefined {\n switch (kind) {\n case 'operation':\n case 'function':\n if (typeof value !== 'function') {\n return `must be a function, got ${describeKind(value)}.`;\n }\n if (isClass(value)) {\n return kind === 'operation'\n ? 'is a class, an operation must be a function. Register controllers under registrations.controllers.'\n : 'is a class, a custom function must be a plain function.';\n }\n return undefined;\n case 'controller':\n if (typeof value !== 'function' || !isClass(value)) {\n return `must be a controller class, got ${describeKind(value)}.`;\n }\n for (const method of ['init', 'attach', 'detach']) {\n if (typeof value.prototype?.[method] !== 'function') {\n return `must implement IController: it has no '${method}' method.`;\n }\n }\n return undefined;\n case 'engine':\n case 'provider':\n return typeof value === 'function'\n ? undefined\n : `must be a class, got ${describeKind(value)}.`;\n case 'template':\n return typeof value === 'string'\n ? undefined\n : `must be a string, got ${describeKind(value)}.`;\n case 'json':\n switch (typeof value) {\n case 'undefined':\n case 'function':\n case 'symbol':\n case 'bigint':\n return `must be JSON data, got ${describeKind(value)}.`;\n default:\n return undefined;\n }\n }\n}\n\nexport function isClass(value: unknown): boolean {\n return (\n typeof value === 'function' &&\n /^class[\\s{]/.test(Function.prototype.toString.call(value))\n );\n}\n\n/**\n * Describes a value by its kind only, so registered data never ends up in a\n * message.\n */\nexport function describeKind(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return 'an array';\n }\n if (typeof value === 'function') {\n return isClass(value) ? 'a class' : 'a function';\n }\n const type = typeof value;\n return type === 'undefined'\n ? 'undefined'\n : `${/^[aeiou]/.test(type) ? 'an' : 'a'} ${type}`;\n}\n","import {findClosestNames, formatDidYouMean} from '@util/find-closest-names.ts';\nimport {EligiusEngine} from '../eligius-engine.ts';\nimport type {IImporterResources, IResourceImporter} from '../types.ts';\nimport {\n checkShape,\n describeKind,\n type TImporterResourceKind,\n} from './registration-shape.ts';\n\ninterface IProvidedResource {\n kind: TImporterResourceKind;\n value: unknown;\n}\n\nconst RESOURCE_KINDS: ReadonlyArray<\n readonly [keyof IImporterResources, TImporterResourceKind]\n> = [\n ['engines', 'engine'],\n ['operations', 'operation'],\n ['controllers', 'controller'],\n ['providers', 'provider'],\n ['functions', 'function'],\n ['templates', 'template'],\n ['json', 'json'],\n];\n\n/**\n * Creates a resource importer that provides exactly the resources it is\n * given, keyed by system name.\n *\n * Unlike {@link EligiusResourceImporter}, which provides every operation,\n * controller and timeline provider of Eligius, this importer only references\n * the resources you name. A bundler can then drop every operation and\n * controller a presentation does not use, which makes the bundle noticeably\n * smaller. See the README section \"Smaller bundles\".\n *\n * The maps follow the same rules as the `EligiusResourceImporter`\n * registrations: operations and functions must be functions, not classes;\n * controllers must be classes implementing `IController`; templates must be\n * strings; JSON must be JSON data. Engines, position sources, container\n * providers and playlists are given as classes. Every name must be unique\n * across all the maps. There are no built-in names, so nothing is shadowed and\n * `override` does not exist here.\n *\n * `engines` defaults to `{EligiusEngine}`.\n *\n * @param resources - The resources to provide, see {@link IImporterResources}\n * @returns An importer for the `EngineFactory`\n * @throws Error when a value has the wrong shape for its map, or when a name\n * appears in more than one map. The message names the map and the name.\n *\n * @example\n * ```ts\n * import {\n * addClass,\n * createImporter,\n * DomContainerProvider,\n * EngineFactory,\n * RafPositionSource,\n * selectElement,\n * SimplePlaylist,\n * } from 'eligius/runtime';\n *\n * const importer = createImporter({\n * operations: {selectElement, addClass, trackEvent},\n * providers: {RafPositionSource, DomContainerProvider, SimplePlaylist},\n * functions: {formatPrice},\n * });\n * const factory = new EngineFactory(importer, window);\n * ```\n */\nexport function createImporter(\n resources: IImporterResources\n): IResourceImporter {\n if (resources === null || typeof resources !== 'object') {\n throw new Error(\n `createImporter: the resources must be an object, got ${describeKind(resources)}.`\n );\n }\n\n const provided = new Map<string, IProvidedResource>();\n\n for (const [mapName, kind] of RESOURCE_KINDS) {\n const map =\n mapName === 'engines'\n ? (resources.engines ?? {EligiusEngine})\n : resources[mapName];\n if (map === undefined) {\n continue;\n }\n if (map === null || typeof map !== 'object' || Array.isArray(map)) {\n throw new Error(\n `createImporter: resources.${mapName} must be an object of names to values, got ${describeKind(map)}.`\n );\n }\n\n for (const name of Object.keys(map)) {\n const value = (map as Record<string, unknown>)[name];\n const shapeError = checkShape(kind, value);\n if (shapeError) {\n throw new Error(\n `createImporter: resources.${mapName}.${name} ${shapeError}`\n );\n }\n const earlier = provided.get(name);\n if (earlier) {\n throw new Error(\n `createImporter: '${name}' is provided more than once (as ${article(earlier.kind)} and as ${article(kind)}). Every name must be unique, rename one of them.`\n );\n }\n provided.set(name, {kind, value});\n }\n }\n\n const namesOf = (kind: TImporterResourceKind): string[] => {\n const names: string[] = [];\n for (const [name, resource] of provided) {\n if (resource.kind === kind) {\n names.push(name);\n }\n }\n return names;\n };\n\n return {\n getOperationNames: () => namesOf('operation'),\n getControllerNames: () => namesOf('controller'),\n getProviderNames: () => namesOf('provider'),\n getFunctionNames: () => namesOf('function'),\n import(name: string): Record<string, any> {\n const resource = provided.get(name);\n if (resource === undefined) {\n throw new Error(createUnknownNameMessage(name, [...provided.keys()]));\n }\n return {[name]: resource.value};\n },\n };\n}\n\nfunction article(kind: TImporterResourceKind): string {\n return `${/^[aeiou]/.test(kind) ? 'an' : 'a'} ${kind}`;\n}\n\nfunction createUnknownNameMessage(name: string, knownNames: string[]): string {\n const message = `createImporter: unknown system name '${name}'.`;\n const didYouMean = formatDidYouMean(\n findClosestNames(String(name), knownNames)\n );\n if (didYouMean) {\n return `${message} ${didYouMean}`;\n }\n return `${message} Check the spelling, or add it to the resources passed to createImporter.`;\n}\n","/**\n * Position source state.\n * - `active`: Source is emitting position updates\n * - `suspended`: Source is paused, position preserved\n * - `inactive`: Source is stopped, position reset to initial state\n */\nexport type TSourceState = 'active' | 'suspended' | 'inactive';\n\n/**\n * Boundary type for position source events.\n * - `start`: Position reached the beginning (e.g., after reverse or loop)\n * - `end`: Position reached the end of duration\n */\nexport type TBoundary = 'start' | 'end';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// IPositionSource\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Core interface for timeline position sources.\n *\n * A position source provides the current position within a timeline and emits\n * position updates. The source of position can vary: elapsed time (RAF),\n * media playback (video), scroll position, mouse position, external data, etc.\n *\n * @example\n * ```typescript\n * // RAF-based position source\n * const source = new RafPositionSource(config);\n * await source.init();\n *\n * source.onPosition((position) => {\n * console.log(`Current position: ${position}`);\n * });\n *\n * source.onBoundaryReached((boundary) => {\n * if (boundary === 'end') console.log('Reached end');\n * });\n *\n * await source.activate();\n * ```\n */\nexport interface IPositionSource {\n // ───────────────────────────────────────────────────────────────────────────\n // STATE\n // ───────────────────────────────────────────────────────────────────────────\n\n /** Current state of the position source */\n readonly state: TSourceState;\n\n /**\n * Whether to loop when reaching the end boundary.\n *\n * When `true`, the source resets to position 0 and continues.\n * When `false`, the source emits `'end'` boundary and deactivates.\n *\n * For sources where looping is not applicable (e.g., mouse position),\n * this property has no effect.\n */\n loop: boolean;\n\n // ───────────────────────────────────────────────────────────────────────────\n // LIFECYCLE\n // ───────────────────────────────────────────────────────────────────────────\n\n /**\n * Initialize the position source.\n *\n * Performs any async setup required before the source can be activated.\n * For example: loading media, binding event listeners, establishing connections.\n *\n * @throws If initialization fails (e.g., media load error, connection refused)\n */\n init(): Promise<void>;\n\n /**\n * Destroy the position source and release all resources.\n *\n * After calling destroy, the source cannot be reused.\n * Removes event listeners, closes connections, clears timers.\n */\n destroy(): void;\n\n // ───────────────────────────────────────────────────────────────────────────\n // TRANSPORT\n // ───────────────────────────────────────────────────────────────────────────\n\n /**\n * Activate the position source to begin emitting position updates.\n *\n * Transitions state from `inactive` or `suspended` to `active`.\n *\n * @throws (rejects) If activation fails (e.g., autoplay blocked, permission\n * denied), and after {@link destroy} has been called: a destroyed source\n * cannot be activated again\n */\n activate(): Promise<void>;\n\n /**\n * Suspend the position source, preserving current position.\n *\n * Transitions state from `active` to `suspended`.\n * Position updates stop but position is preserved for later resumption.\n */\n suspend(): void;\n\n /**\n * Deactivate the position source and reset to initial state.\n *\n * Transitions state to `inactive`.\n * Position is reset (typically to 0).\n */\n deactivate(): void;\n\n // ───────────────────────────────────────────────────────────────────────────\n // POSITION\n // ───────────────────────────────────────────────────────────────────────────\n\n /**\n * Get the current position.\n *\n * @returns Current position in seconds (or source-specific units)\n */\n getPosition(): number;\n\n /**\n * Get the total duration.\n *\n * @returns Duration in seconds (or source-specific units), or `Infinity` for unbounded sources\n */\n getDuration(): number;\n\n // ───────────────────────────────────────────────────────────────────────────\n // EVENTS\n // ───────────────────────────────────────────────────────────────────────────\n\n /**\n * Register a callback for position updates.\n *\n * Called whenever the position changes while the source is active.\n * Frequency depends on the source type (e.g., RAF tick, video timeupdate).\n *\n * @param callback - Function receiving the current position\n * @returns A function that unregisters the callback. The built-in implementations always return one; custom implementations written for earlier versions may return nothing, so callers must handle `undefined`.\n */\n onPosition(callback: (position: number) => void): (() => void) | void;\n\n /**\n * Register a callback for boundary events.\n *\n * Called when position reaches a boundary (start or end).\n * For looping sources, `'end'` is emitted before reset.\n *\n * @param callback - Function receiving the boundary type\n * @returns A function that unregisters the callback. The built-in implementations always return one; custom implementations written for earlier versions may return nothing, so callers must handle `undefined`.\n */\n onBoundaryReached(\n callback: (boundary: TBoundary) => void\n ): (() => void) | void;\n\n /**\n * Register a callback for when the source becomes active.\n *\n * Called once each time the source transitions to the `active` state.\n * This is equivalent to \"first frame\" semantics - for RAF sources it's\n * the first tick, for video sources it's when playback actually starts.\n *\n * @param callback - Function called when source becomes active\n * @returns A function that unregisters the callback. The built-in implementations always return one; custom implementations written for earlier versions may return nothing, so callers must handle `undefined`.\n */\n onActivated(callback: () => void): (() => void) | void;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// ISeekable\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Interface for position sources that support seeking to arbitrary positions.\n *\n * Not all position sources are seekable. For example:\n * - Seekable: RAF, video, scroll (programmatic), step-based\n * - Not seekable: mouse position, external WebSocket, live streams\n *\n * @example\n * ```typescript\n * if (isSeekable(source)) {\n * const actualPosition = await source.seek(30.5);\n * console.log(`Seeked to: ${actualPosition}`);\n * }\n * ```\n */\nexport interface ISeekable {\n /**\n * Seek to a specific position.\n *\n * @param position - Target position in seconds (or source-specific units)\n * @returns Actual position after seek (may differ from requested if clamped)\n */\n seek(position: number): Promise<number>;\n}\n\n/**\n * Type guard to check if a position source is seekable.\n *\n * @param source - Position source to check\n * @returns `true` if source implements ISeekable\n */\nexport function isSeekable(\n source: IPositionSource\n): source is IPositionSource & ISeekable {\n return 'seek' in source && typeof (source as ISeekable).seek === 'function';\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// IPlaylist\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Interface for managing a collection of timeline items.\n *\n * A playlist allows switching between multiple timeline configurations\n * (e.g., multiple videos, multiple animation sequences).\n *\n * @typeParam TItem - Type of playlist items (default: unknown)\n *\n * @example\n * ```typescript\n * playlist.onItemChange((item) => {\n * console.log(`Switched to: ${item.uri}`);\n * });\n *\n * playlist.selectItem('chapter-2');\n * ```\n */\nexport interface IPlaylist<TItem = unknown> {\n /** Currently active playlist item */\n readonly currentItem: TItem;\n\n /** All items in the playlist */\n readonly items: readonly TItem[];\n\n /**\n * Select a playlist item by identifier.\n *\n * @param identifier - Unique identifier for the item (e.g., URI, ID)\n * @throws If no item matches the identifier\n */\n selectItem(identifier: string): void;\n\n /**\n * Optional: whether an item with the given identifier exists, without\n * changing the selection. When a playlist implements it, the engine checks\n * the timeline URI with it before a timeline switch deactivates the\n * current timeline, so an unknown identifier cannot stop a switch halfway.\n *\n * @param identifier - Identifier to look up\n * @returns true when `selectItem(identifier)` would succeed\n */\n hasItem?(identifier: string): boolean;\n\n /**\n * Register a callback for item changes.\n *\n * Called whenever the current item changes via `selectItem()`.\n *\n * @param callback - Function receiving the new current item\n * @returns A function that unregisters the callback. The built-in implementations always return one; custom implementations written for earlier versions may return nothing, so callers must handle `undefined`.\n */\n onItemChange(callback: (item: TItem) => void): (() => void) | void;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// IContainerProvider\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Interface for providing the DOM container where content is rendered.\n *\n * The container is where operations render their output (elements, animations, etc.).\n * For some sources (video), the container is intrinsic. For others (WebSocket),\n * the container is a separate concern configured independently.\n *\n * @example\n * ```typescript\n * containerProvider.onContainerReady(() => {\n * const $container = containerProvider.getContainer();\n * $container?.append('<div class=\"content\">Loaded!</div>');\n * });\n * ```\n */\nexport interface IContainerProvider {\n /**\n * Optional asynchronous initialisation, for example resolving the container\n * element. The engine awaits it before the provider's timeline is first\n * activated.\n *\n * @throws If the container cannot be resolved\n */\n init?(): Promise<void>;\n\n /**\n * Optional cleanup. The engine calls it once when it is destroyed.\n */\n destroy?(): void;\n\n /**\n * Get the container element.\n *\n * @returns jQuery-wrapped container element, or `undefined` if not available\n */\n getContainer(): JQuery<HTMLElement> | undefined;\n\n /**\n * Register a callback for when the container is ready.\n *\n * Called once when the container becomes available and ready for content.\n * For video sources, this corresponds to the first frame.\n * For DOM containers, this is called after the element is found/created.\n *\n * @param callback - Function called when container is ready\n */\n onContainerReady(callback: () => void): void;\n}\n","import type {\n IPositionSource,\n TBoundary,\n TSourceState,\n} from '@timelineproviders/types.ts';\n\n/**\n * Abstract base class for position sources.\n *\n * Provides shared state management, lifecycle handling, and callback\n * registration for concrete position source implementations.\n *\n * Subclasses must implement:\n * - `doInit()` - Source-specific initialization\n * - `doDestroy()` - Source-specific cleanup\n * - `startTicking()` - Start emitting position updates\n * - `stopTicking()` - Stop emitting position updates\n *\n * @example\n * ```typescript\n * class MyPositionSource extends BasePositionSource {\n * protected doInit(): Promise<void> {\n * // Initialize resources\n * return Promise.resolve();\n * }\n *\n * protected doDestroy(): void {\n * // Clean up resources\n * }\n *\n * protected startTicking(): void {\n * // Start position updates\n * }\n *\n * protected stopTicking(): void {\n * // Stop position updates\n * }\n * }\n * ```\n */\nexport abstract class BasePositionSource implements IPositionSource {\n // ─────────────────────────────────────────────────────────────────────────\n // State\n // ─────────────────────────────────────────────────────────────────────────\n\n private _state: TSourceState = 'inactive';\n private _position = 0;\n private readonly _duration: number;\n private _loop = false;\n private _destroyed = false;\n /**\n * Incremented by every activate(), suspend(), deactivate() and destroy().\n * An asynchronous activation only applies its outcome while the token it\n * took is still current, so a stale start cannot overwrite a newer one.\n */\n private _activationToken = 0;\n\n // ─────────────────────────────────────────────────────────────────────────\n // Callbacks\n // ─────────────────────────────────────────────────────────────────────────\n\n private _positionCallbacks: Array<(position: number) => void> = [];\n private _boundaryCallbacks: Array<(boundary: TBoundary) => void> = [];\n private _activatedCallbacks: Array<() => void> = [];\n\n // ─────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Create a new position source.\n *\n * @param duration - Total duration in seconds (or `Infinity` for unbounded)\n */\n constructor(duration: number) {\n this._duration = duration;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // IPositionSource - State\n // ─────────────────────────────────────────────────────────────────────────\n\n get state(): TSourceState {\n return this._state;\n }\n\n get loop(): boolean {\n return this._loop;\n }\n\n set loop(value: boolean) {\n this._loop = value;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // IPositionSource - Lifecycle\n // ─────────────────────────────────────────────────────────────────────────\n\n async init(): Promise<void> {\n await this.doInit();\n }\n\n /**\n * Release the source.\n *\n * Destroy is terminal: afterwards `activate()` rejects, the built-in\n * sources ignore `seek()`, and every registered callback is dropped so the\n * source no longer keeps its consumers alive. A pending asynchronous\n * activation is superseded and will not call the activated callbacks.\n */\n destroy(): void {\n this._activationToken++;\n if (this._state === 'active') {\n this.stopTicking();\n }\n this._state = 'inactive';\n this._position = 0;\n this._destroyed = true;\n this._positionCallbacks = [];\n this._boundaryCallbacks = [];\n this._activatedCallbacks = [];\n this.doDestroy();\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // IPositionSource - Transport\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Start emitting positions.\n *\n * When `startTicking()` is asynchronous, its outcome only applies while no\n * later `activate()`, `suspend()`, `deactivate()` or `destroy()` has\n * superseded this call. A superseded activation resolves without touching\n * the state or calling the activated callbacks, even when its start failed.\n *\n * @throws when the source has been destroyed, or when a current (not\n * superseded) asynchronous start fails\n */\n async activate(): Promise<void> {\n if (this._destroyed) {\n throw new Error(\n `${this.constructor.name}: cannot activate a destroyed position source`\n );\n }\n\n if (this._state === 'active') {\n // Already active, no-op\n return;\n }\n\n const previousState = this._state;\n const token = ++this._activationToken;\n this._state = 'active';\n const started = this.startTicking();\n\n if (started) {\n // Asynchronous start (e.g. media playback). Activation only counts once\n // it has succeeded.\n try {\n await started;\n } catch (error) {\n if (token !== this._activationToken) {\n // Superseded while starting: the newer call owns the state\n return;\n }\n this._state = previousState;\n throw error;\n }\n\n if (token !== this._activationToken) {\n return;\n }\n }\n\n // Emit activated callbacks (first frame semantics)\n for (const callback of [...this._activatedCallbacks]) {\n this._invoke(callback, 'activated');\n }\n }\n\n suspend(): void {\n if (this._state !== 'active') {\n // Can only suspend from active state\n return;\n }\n\n this._activationToken++;\n this._state = 'suspended';\n this.stopTicking();\n // Position is preserved\n }\n\n deactivate(): void {\n if (this._state === 'inactive') {\n // Already inactive, no-op\n return;\n }\n\n this._activationToken++;\n if (this._state === 'active') {\n this.stopTicking();\n }\n\n this._state = 'inactive';\n this._position = 0;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // IPositionSource - Position\n // ─────────────────────────────────────────────────────────────────────────\n\n getPosition(): number {\n return this._position;\n }\n\n getDuration(): number {\n return this._duration;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // IPositionSource - Events\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Register a position callback.\n *\n * @param callback - Called with each new position while active\n * @returns A function that unregisters the callback\n */\n onPosition(callback: (position: number) => void): () => void {\n this._positionCallbacks.push(callback);\n return () => {\n this._positionCallbacks = this._positionCallbacks.filter(\n registered => registered !== callback\n );\n };\n }\n\n /**\n * Register a boundary callback.\n *\n * @param callback - Called with 'start' or 'end' when a boundary is reached\n * @returns A function that unregisters the callback\n */\n onBoundaryReached(callback: (boundary: TBoundary) => void): () => void {\n this._boundaryCallbacks.push(callback);\n return () => {\n this._boundaryCallbacks = this._boundaryCallbacks.filter(\n registered => registered !== callback\n );\n };\n }\n\n /**\n * Register an activation callback.\n *\n * @param callback - Called each time an activation succeeds\n * @returns A function that unregisters the callback\n */\n onActivated(callback: () => void): () => void {\n this._activatedCallbacks.push(callback);\n return () => {\n this._activatedCallbacks = this._activatedCallbacks.filter(\n registered => registered !== callback\n );\n };\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Protected - For Subclasses\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Whether `destroy()` has been called. Subclasses use it to ignore\n * transport calls such as `seek()` on a destroyed source.\n */\n protected get isDestroyed(): boolean {\n return this._destroyed;\n }\n\n /**\n * Set the current position and emit to callbacks.\n *\n * Only emits if the source is active. A callback that throws is logged and\n * stops neither the other callbacks nor the caller (for example a RAF\n * tick), so one failing consumer cannot freeze the clock.\n *\n * @param position - New position value\n */\n protected setPosition(position: number): void {\n this._position = position;\n if (this._state === 'active') {\n for (const callback of [...this._positionCallbacks]) {\n this._invoke(() => callback(position), 'position');\n }\n }\n }\n\n /**\n * Emit a boundary event to all registered callbacks.\n *\n * A callback that throws is logged and does not stop the others.\n *\n * @param boundary - The boundary type ('start' or 'end')\n */\n protected emitBoundary(boundary: TBoundary): void {\n for (const callback of [...this._boundaryCallbacks]) {\n this._invoke(() => callback(boundary), 'boundary');\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Abstract - Must Implement\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Perform source-specific initialization.\n *\n * Called by `init()`. Override to load resources, bind listeners, etc.\n */\n protected abstract doInit(): Promise<void>;\n\n /**\n * Perform source-specific cleanup.\n *\n * Called by `destroy()`. Override to release resources, unbind listeners, etc.\n */\n protected abstract doDestroy(): void;\n\n /**\n * Start emitting position updates.\n *\n * Called when transitioning to `active` state.\n * Override to start timers, begin listening to events, etc.\n *\n * May return a promise when starting is asynchronous (for example media\n * playback). `activate()` then waits for it: if it rejects, the state\n * reverts to its previous value, the activated callbacks are not called,\n * and `activate()` rethrows the error. When a later transition supersedes\n * the activation before the promise settles, the outcome is ignored.\n */\n protected abstract startTicking(): void | Promise<void>;\n\n /**\n * Stop emitting position updates.\n *\n * Called when transitioning from `active` to `suspended` or `inactive`.\n * Override to stop timers, pause listening, etc.\n */\n protected abstract stopTicking(): void;\n\n // ─────────────────────────────────────────────────────────────────────────\n // Private\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Run one consumer callback, isolating its failure from the source.\n */\n private _invoke(callback: () => void, kind: string): void {\n try {\n callback();\n } catch (error) {\n console.error(\n `${this.constructor.name}: error in ${kind} callback:`,\n error\n );\n }\n }\n}\n","import {BasePositionSource} from '@timelineproviders/position-sources/base-position-source.ts';\nimport type {ISeekable} from '@timelineproviders/types.ts';\nimport {\n isClaimedByController,\n shortcutId,\n} from '@util/keyboard-input-registry.ts';\nimport hotkeys from 'hotkeys-js';\n\n/**\n * Vertical axis mode for keyboard navigation.\n *\n * - `timeline-switch`: Up/Down arrows emit timeline change requests\n * - `chapter-navigation`: Up/Down arrows jump between markers\n * - `disabled`: Up/Down arrows do nothing\n */\nexport type TVerticalMode =\n | 'timeline-switch'\n | 'chapter-navigation'\n | 'disabled';\n\n/**\n * Configuration for KeyboardStepSource.\n */\nexport interface KeyboardStepSourceConfig {\n /**\n * Total duration in seconds.\n */\n duration: number;\n\n /**\n * Vertical axis behavior.\n */\n verticalMode: TVerticalMode;\n\n /**\n * Step size for Left/Right arrows in seconds.\n * @default 1\n */\n stepSize?: number;\n\n /**\n * Large step size for Shift+Left/Right arrows in seconds.\n * @default 10\n */\n largeStepSize?: number;\n\n /**\n * Marker positions for chapter navigation mode (in seconds).\n * Will be auto-sorted ascending on init.\n */\n markers?: number[];\n\n /**\n * Target element to scope keyboard bindings.\n * Can be an HTMLElement or a CSS selector string. A selector that matches\n * no element makes `init()` reject.\n * If not provided, bindings are global (document).\n */\n targetElement?: HTMLElement | string;\n\n /**\n * Whether navigation wraps at boundaries.\n * @default true\n */\n wrapNavigation?: boolean;\n}\n\n/**\n * Key bindings used by KeyboardStepSource.\n */\nconst KEY_BINDINGS = {\n stepForward: 'right',\n stepBackward: 'left',\n largeStepForward: 'shift+right',\n largeStepBackward: 'shift+left',\n jumpToStart: 'home',\n jumpToEnd: 'end',\n verticalPrev: 'up',\n verticalNext: 'down',\n} as const;\n\n/**\n * Convert seconds to integer milliseconds, the unit steps are computed in so\n * that repeated fractional steps do not accumulate float error.\n */\nconst toMs = (seconds: number): number => Math.round(seconds * 1000);\n\n/**\n * Keyboard-based position source for stepping through a timeline.\n *\n * Key handlers are bound in the hotkeys-js `'all'` scope, so they work\n * whatever scope the host application has set, and they are removed one by\n * one on suspend, deactivate and destroy. The source never changes the\n * global hotkeys-js scope.\n *\n * A key that a KeyboardController of the owning engine handles is left to\n * that controller: the press runs the controller's actions and does not step\n * the timeline. The engine tells the source its root through\n * {@link KeyboardStepSource.setEngineRoot}.\n *\n * Supports:\n * - Left/Right arrows: step by `stepSize` (default 1s)\n * - Shift+Left/Right: large step by `largeStepSize` (default 10s)\n * - Home/End: jump to start/end\n * - Up/Down: configurable (timeline switch, chapter navigation, or disabled)\n *\n * @example\n * ```typescript\n * const source = new KeyboardStepSource({\n * duration: 60,\n * verticalMode: 'chapter-navigation',\n * markers: [0, 10, 20, 30, 40, 50],\n * });\n *\n * await source.init();\n *\n * source.onPosition((position) => {\n * console.log(`Position: ${position}s`);\n * });\n *\n * source.onMarkerJump((index, position) => {\n * console.log(`Jumped to marker ${index} at ${position}s`);\n * });\n *\n * await source.activate();\n * ```\n */\nexport class KeyboardStepSource\n extends BasePositionSource\n implements ISeekable\n{\n // ─────────────────────────────────────────────────────────────────────────\n // Configuration\n // ─────────────────────────────────────────────────────────────────────────\n\n private readonly _stepSize: number;\n private readonly _largeStepSize: number;\n private readonly _verticalMode: TVerticalMode;\n private readonly _wrapNavigation: boolean;\n private _markers: number[];\n private readonly _targetElementConfig?: HTMLElement | string;\n private _targetElement?: HTMLElement;\n /** Returns the root element of the owning engine, see setEngineRoot() */\n private _getEngineRoot: (() => Element | undefined) | undefined;\n /** Handlers currently bound in hotkeys-js, for exact removal. */\n private _bindings: Array<{\n key: string;\n method: (event: KeyboardEvent) => void;\n }> = [];\n\n // ─────────────────────────────────────────────────────────────────────────\n // Callbacks\n // ─────────────────────────────────────────────────────────────────────────\n\n private _timelineChangeCallbacks: Array<\n (direction: 'prev' | 'next') => void\n > = [];\n private _markerJumpCallbacks: Array<\n (markerIndex: number, position: number) => void\n > = [];\n\n // ─────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Create a new keyboard-based position source.\n *\n * @param config - Configuration options\n */\n constructor(config: KeyboardStepSourceConfig) {\n super(config.duration);\n this._stepSize = config.stepSize ?? 1;\n this._largeStepSize = config.largeStepSize ?? 10;\n this._verticalMode = config.verticalMode;\n this._wrapNavigation = config.wrapNavigation ?? true;\n this._markers = config.markers ? [...config.markers] : [];\n this._targetElementConfig = config.targetElement;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // BasePositionSource Implementation\n // ─────────────────────────────────────────────────────────────────────────\n\n protected doInit(): Promise<void> {\n // Sort markers ascending\n this._markers.sort((a, b) => a - b);\n\n // Resolve target element if string selector provided. A selector that\n // matches nothing fails fast instead of silently binding the keys on the\n // whole document.\n if (typeof this._targetElementConfig === 'string') {\n const element = document.querySelector(this._targetElementConfig);\n if (!(element instanceof HTMLElement)) {\n return Promise.reject(\n new Error(\n `KeyboardStepSource: target element not found for selector '${this._targetElementConfig}'`\n )\n );\n }\n this._targetElement = element;\n } else if (this._targetElementConfig instanceof HTMLElement) {\n this._targetElement = this._targetElementConfig;\n }\n\n return Promise.resolve();\n }\n\n protected doDestroy(): void {\n this._unbindKeys();\n this._timelineChangeCallbacks = [];\n this._markerJumpCallbacks = [];\n }\n\n protected startTicking(): void {\n this._bindKeys();\n }\n\n protected stopTicking(): void {\n this._unbindKeys();\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // ISeekable Implementation\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Seek to a specific position.\n *\n * Position is clamped to the valid range [0, duration].\n *\n * @param position - Target position in seconds\n * @returns Actual position after seek (may be clamped)\n */\n async seek(position: number): Promise<number> {\n if (this.isDestroyed) {\n return this.getPosition();\n }\n const clampedPosition = Math.max(0, Math.min(position, this.getDuration()));\n this.setPosition(clampedPosition);\n return clampedPosition;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Additional Callbacks\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Register callback for timeline change requests (timeline-switch mode).\n *\n * EligiusEngine registers one when the configuration has more than one\n * timeline: Up switches to the previous configured timeline and Down to the\n * next, from its start (nothing happens at the first or last timeline).\n * Until a callback is registered, Up/Down keep their default browser\n * behaviour (page scroll).\n *\n * @param callback - Called with 'prev' or 'next' when Up/Down is pressed\n * @returns A function that unregisters the callback\n */\n onTimelineChangeRequest(\n callback: (direction: 'prev' | 'next') => void\n ): () => void {\n this._timelineChangeCallbacks.push(callback);\n return () => {\n this._timelineChangeCallbacks = this._timelineChangeCallbacks.filter(\n registered => registered !== callback\n );\n };\n }\n\n /**\n * Tells the source the root element of the engine that owns it, so a key\n * press that a KeyboardController of that engine handles is left to the\n * controller instead of stepping the timeline. EligiusEngine calls this\n * for every source it wires; a source without an engine root handles\n * every press of its keys.\n *\n * @param getRoot - Returns the engine root, or `undefined` before the\n * engine is initialised\n */\n setEngineRoot(getRoot: () => Element | undefined): void {\n this._getEngineRoot = getRoot;\n }\n\n /**\n * Register callback for marker jumps (chapter-navigation mode).\n *\n * @param callback - Called with marker index and position when jumping\n * @returns A function that unregisters the callback\n */\n onMarkerJump(\n callback: (markerIndex: number, position: number) => void\n ): () => void {\n this._markerJumpCallbacks.push(callback);\n return () => {\n this._markerJumpCallbacks = this._markerJumpCallbacks.filter(\n registered => registered !== callback\n );\n };\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Private Methods - Key Binding\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Bind all keyboard handlers.\n */\n private _bindKeys(): void {\n // Never bind twice (each binding is removed by its exact method)\n this._unbindKeys();\n\n // Horizontal navigation\n this._bind(KEY_BINDINGS.stepForward, () => this._handleStepForward());\n this._bind(KEY_BINDINGS.stepBackward, () => this._handleStepBackward());\n this._bind(KEY_BINDINGS.largeStepForward, () =>\n this._handleLargeStepForward()\n );\n this._bind(KEY_BINDINGS.largeStepBackward, () =>\n this._handleLargeStepBackward()\n );\n\n // Jump to start/end\n this._bind(KEY_BINDINGS.jumpToStart, () => this._handleJumpToStart());\n this._bind(KEY_BINDINGS.jumpToEnd, () => this._handleJumpToEnd());\n\n // Vertical navigation (only if mode is not disabled)\n if (this._verticalMode !== 'disabled') {\n this._bind(\n KEY_BINDINGS.verticalPrev,\n () => this._handleVerticalPrev(),\n () => this._handlesVerticalKeys()\n );\n this._bind(\n KEY_BINDINGS.verticalNext,\n () => this._handleVerticalNext(),\n () => this._handlesVerticalKeys()\n );\n }\n }\n\n /**\n * Bind one key in the hotkeys-js `'all'` scope, which fires whatever the\n * current global scope is, without changing that scope.\n *\n * @param key - hotkeys-js key description\n * @param action - Navigation to run\n * @param handles - Whether the source handles the key right now; when it\n * returns false the key keeps its default browser behaviour\n */\n private _bind(\n key: string,\n action: () => void,\n handles: () => boolean = () => true\n ): void {\n const id = shortcutId(key);\n const method = (event: KeyboardEvent) => {\n if (\n this.state !== 'active' ||\n !handles() ||\n // A KeyboardController of the owning engine bound the same key\n isClaimedByController(\n typeof document === 'undefined' ? undefined : document,\n this._getEngineRoot?.(),\n event,\n id\n )\n ) {\n return;\n }\n event.preventDefault();\n action();\n };\n const options: {scope: string; element?: HTMLElement} = {scope: 'all'};\n if (this._targetElement) {\n options.element = this._targetElement;\n }\n hotkeys(key, options, method);\n this._bindings.push({key, method});\n }\n\n /**\n * Unbind this source's keyboard handlers, leaving every other hotkeys-js\n * handler and the global scope untouched.\n */\n private _unbindKeys(): void {\n for (const {key, method} of this._bindings) {\n hotkeys.unbind(key, 'all', method);\n }\n this._bindings = [];\n }\n\n /**\n * Whether Up/Down do anything: always in chapter-navigation mode, and in\n * timeline-switch mode only when someone listens for change requests.\n */\n private _handlesVerticalKeys(): boolean {\n return (\n this._verticalMode !== 'timeline-switch' ||\n this._timelineChangeCallbacks.length > 0\n );\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Private Methods - Navigation Handlers\n // ─────────────────────────────────────────────────────────────────────────\n\n private _handleStepForward(): void {\n this._stepForward(this._stepSize);\n }\n\n private _handleStepBackward(): void {\n this._stepBackward(this._stepSize);\n }\n\n private _handleLargeStepForward(): void {\n this._stepForward(this._largeStepSize);\n }\n\n private _handleLargeStepBackward(): void {\n this._stepBackward(this._largeStepSize);\n }\n\n /**\n * Step forward by the given amount.\n *\n * Stepping past the end wraps to 0 and emits `'start'` when wrapping is on,\n * otherwise it clamps to the duration. Arriving at the duration emits\n * `'end'` once.\n */\n private _stepForward(step: number): void {\n // Integer milliseconds, so ten 0.1 s steps land exactly on 1 s\n const currentMs = toMs(this.getPosition());\n const duration = this.getDuration();\n const durationMs = toMs(duration);\n let newMs = currentMs + toMs(step);\n\n if (newMs > durationMs) {\n if (this._wrapNavigation) {\n this.setPosition(0);\n this.emitBoundary('start');\n return;\n }\n newMs = durationMs;\n }\n\n if (newMs === currentMs) {\n // Already at the end\n return;\n }\n\n if (newMs === durationMs) {\n this.setPosition(duration);\n this.emitBoundary('end');\n } else {\n this.setPosition(newMs / 1000);\n }\n }\n\n /**\n * Step backward by the given amount.\n *\n * Stepping before the start wraps to the duration when wrapping is on,\n * otherwise it clamps to 0. A backward wrap is navigation, not completion,\n * so it emits no boundary (the engine treats `'end'` as timeline complete).\n */\n private _stepBackward(step: number): void {\n const currentPosition = this.getPosition();\n const currentMs = toMs(currentPosition);\n const newMs = currentMs - toMs(step);\n\n let newPosition: number;\n if (newMs < 0) {\n newPosition = this._wrapNavigation ? this.getDuration() : 0;\n } else {\n newPosition = newMs / 1000;\n }\n\n if (newPosition !== currentPosition) {\n this.setPosition(newPosition);\n }\n }\n\n private _handleJumpToStart(): void {\n this.setPosition(0);\n this.emitBoundary('start');\n }\n\n private _handleJumpToEnd(): void {\n this.setPosition(this.getDuration());\n this.emitBoundary('end');\n }\n\n private _handleVerticalPrev(): void {\n if (this._verticalMode === 'timeline-switch') {\n this._emitTimelineChange('prev');\n } else if (this._verticalMode === 'chapter-navigation') {\n this._jumpToPreviousMarker();\n }\n }\n\n private _handleVerticalNext(): void {\n if (this._verticalMode === 'timeline-switch') {\n this._emitTimelineChange('next');\n } else if (this._verticalMode === 'chapter-navigation') {\n this._jumpToNextMarker();\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Private Methods - Timeline Switch\n // ─────────────────────────────────────────────────────────────────────────\n\n private _emitTimelineChange(direction: 'prev' | 'next'): void {\n for (const callback of this._timelineChangeCallbacks) {\n callback(direction);\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Private Methods - Chapter Navigation\n // ─────────────────────────────────────────────────────────────────────────\n\n private _jumpToPreviousMarker(): void {\n if (this._markers.length === 0) return;\n\n const currentPosition = this.getPosition();\n const currentMarkerIndex = this._findCurrentMarkerIndex(currentPosition);\n\n let targetIndex: number;\n\n if (currentMarkerIndex === -1) {\n // Before the first marker - there is no previous marker\n if (this._wrapNavigation) {\n targetIndex = this._markers.length - 1;\n } else {\n return;\n }\n } else if (this._markers[currentMarkerIndex] === currentPosition) {\n // Exactly on a marker - go to previous marker\n if (currentMarkerIndex === 0) {\n if (this._wrapNavigation) {\n targetIndex = this._markers.length - 1;\n } else {\n return; // Already at first marker\n }\n } else {\n targetIndex = currentMarkerIndex - 1;\n }\n } else {\n // Between markers - go to the start of current section (marker at currentMarkerIndex)\n targetIndex = currentMarkerIndex;\n }\n\n const targetPosition = this._markers[targetIndex];\n this.setPosition(targetPosition);\n this._emitMarkerJump(targetIndex, targetPosition);\n }\n\n private _jumpToNextMarker(): void {\n if (this._markers.length === 0) return;\n\n const currentPosition = this.getPosition();\n const currentMarkerIndex = this._findCurrentMarkerIndex(currentPosition);\n\n let targetIndex: number;\n\n if (currentMarkerIndex >= this._markers.length - 1) {\n // At or after last marker\n if (this._wrapNavigation) {\n targetIndex = 0;\n } else {\n // Already at last marker, do nothing\n return;\n }\n } else {\n targetIndex = currentMarkerIndex + 1;\n }\n\n const targetPosition = this._markers[targetIndex];\n this.setPosition(targetPosition);\n this._emitMarkerJump(targetIndex, targetPosition);\n }\n\n /**\n * Find the index of the current or previous marker.\n *\n * If position matches a marker exactly, returns that marker's index.\n * Otherwise, returns the index of the marker before the current position.\n * Returns -1 if there are no markers or the position is before the first\n * marker.\n */\n private _findCurrentMarkerIndex(position: number): number {\n for (let i = this._markers.length - 1; i >= 0; i--) {\n if (position >= this._markers[i]) {\n return i;\n }\n }\n\n return -1;\n }\n\n private _emitMarkerJump(markerIndex: number, position: number): void {\n for (const callback of this._markerJumpCallbacks) {\n callback(markerIndex, position);\n }\n }\n}\n","// https://gist.github.com/jakearchibald/cb03f15670817001b1157e62a076fe95\n/**\n * Calls `callback` roughly every `ms` milliseconds, aligned to animation\n * frames, until `signal` is aborted.\n *\n * The callback receives the time elapsed in milliseconds since this interval\n * was started, not the absolute animation frame timestamp. Consumers can\n * therefore treat the value as \"time since start\" regardless of how long the\n * page has been open.\n *\n * Frames are scheduled on the grid `start + k * ms`. A frame's timestamp can\n * land a little before or after its grid point (timer truncation, frame begin\n * time, scheduling latency), so the scheduler treats a frame as belonging to\n * the nearest grid point: `Math.round(elapsed / ms)`. Consumers that convert\n * elapsed time into a tick count must use the same rounding, otherwise a\n * slightly early frame is counted as the previous tick and the scheduler\n * skips ahead past the one that was never reported.\n *\n * Aborting the signal cancels the pending timer and animation frame at once,\n * so nothing keeps running after the owner is destroyed. A callback that\n * throws does not stop the interval: the next frame is still scheduled and\n * the error is rethrown to the frame's caller.\n *\n * @param ms - Interval length in milliseconds\n * @param signal - Aborting this signal stops the interval\n * @param callback - Receives elapsed milliseconds since start\n */\nexport function animationInterval(\n ms: number,\n signal: AbortSignal,\n callback: (elapsed: number) => void\n): void {\n if (signal.aborted) {\n return;\n }\n\n // Prefer currentTime, as it'll better sync animations queued in the\n // same frame, but if it isn't supported, performance.now() is fine.\n const currentTime = document?.timeline?.currentTime;\n const start = currentTime ? Number(currentTime) : performance.now();\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let frameId: number | undefined;\n\n const frame = (time: number) => {\n if (signal.aborted) return;\n try {\n callback(time - start);\n } finally {\n scheduleFrame(time);\n }\n };\n\n const scheduleFrame = (time: number) => {\n if (signal.aborted) return;\n const elapsed = time - start;\n const roundedElapsed = Math.round(elapsed / ms) * ms;\n const targetNext = start + roundedElapsed + ms;\n const delay = targetNext - performance.now();\n timeoutId = setTimeout(() => {\n timeoutId = undefined;\n if (signal.aborted) return;\n let ran = false;\n const id = requestAnimationFrame(time => {\n ran = true;\n frameId = undefined;\n frame(time);\n });\n // A frame that already ran synchronously has nothing left to cancel\n if (!ran) {\n frameId = id;\n }\n }, delay);\n };\n\n signal.addEventListener(\n 'abort',\n () => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n }\n if (frameId !== undefined) {\n if (typeof cancelAnimationFrame === 'function') {\n cancelAnimationFrame(frameId);\n }\n frameId = undefined;\n }\n },\n {once: true}\n );\n\n scheduleFrame(start);\n}\n","import {BasePositionSource} from '@timelineproviders/position-sources/base-position-source.ts';\nimport type {ISeekable} from '@timelineproviders/types.ts';\nimport {animationInterval} from '@util/animation-interval.ts';\n\n/**\n * Configuration for RafPositionSource.\n */\nexport interface RafPositionSourceConfig {\n /**\n * Total duration in seconds.\n */\n duration: number;\n\n /**\n * Interval between position ticks in milliseconds.\n *\n * The default of 100 ms matches the 0.1 s precision at which actions are\n * keyed. A larger interval emits fewer position updates, but actions then\n * start and end up to one interval late, and a duration that is not a\n * multiple of the interval is reported on the tick after it.\n *\n * @default 100 (0.1 second)\n */\n tickInterval?: number;\n}\n\n/**\n * Default interval between position ticks, in milliseconds.\n */\nconst DEFAULT_TICK_INTERVAL = 100;\n\n/**\n * RequestAnimationFrame-based position source.\n *\n * Uses the `animationInterval` utility to emit position updates at a regular\n * interval (default: 100 ms). Position values are elapsed seconds, quantised\n * to the tick interval.\n *\n * Implements both `IPositionSource` (via `BasePositionSource`) and `ISeekable`.\n *\n * @example\n * ```typescript\n * const source = new RafPositionSource({ duration: 60 });\n * await source.init();\n *\n * source.onPosition((position) => {\n * console.log(`Position: ${position}s`);\n * });\n *\n * source.onBoundaryReached((boundary) => {\n * if (boundary === 'end') {\n * console.log('Timeline complete');\n * }\n * });\n *\n * await source.activate();\n *\n * // Seek to 30 seconds\n * await source.seek(30);\n * ```\n */\nexport class RafPositionSource extends BasePositionSource implements ISeekable {\n // ─────────────────────────────────────────────────────────────────────────\n // State\n // ─────────────────────────────────────────────────────────────────────────\n\n private readonly _tickInterval: number;\n private _abortController: AbortController | null = null;\n /**\n * Position (in seconds) the source had when the current ticking session\n * started. Each tick adds the session's elapsed time to this value, so\n * resuming after suspend or seeking continues from the right place.\n */\n private _sessionStartPosition = 0;\n /**\n * Elapsed time (in milliseconds, as reported by animationInterval) at which\n * the current loop iteration began. Set to the wrap tick's grid point on\n * loop wrap.\n */\n private _sessionElapsedOffset = 0;\n\n // ─────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Create a new RAF-based position source.\n *\n * @param config - Configuration options\n */\n constructor(config: RafPositionSourceConfig) {\n super(config.duration);\n this._tickInterval = config.tickInterval ?? DEFAULT_TICK_INTERVAL;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // BasePositionSource Implementation\n // ─────────────────────────────────────────────────────────────────────────\n\n protected doInit(): Promise<void> {\n // RAF-based source requires no async initialization\n return Promise.resolve();\n }\n\n protected doDestroy(): void {\n this._abortTicking();\n }\n\n protected startTicking(): void {\n // Emit initial position immediately\n this.setPosition(this.getPosition());\n this._startSession();\n }\n\n protected stopTicking(): void {\n this._abortTicking();\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // ISeekable Implementation\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Seek to a specific position.\n *\n * Position is clamped to the valid range [0, duration].\n *\n * @param position - Target position in seconds\n * @returns Actual position after seek (may be clamped)\n */\n async seek(position: number): Promise<number> {\n if (this.isDestroyed) {\n return this.getPosition();\n }\n\n // Clamp position to valid range\n const clampedPosition = Math.max(0, Math.min(position, this.getDuration()));\n\n // Update position (setPosition will emit callback if active)\n this.setPosition(clampedPosition);\n\n // While ticking, restart the session so the clock is anchored to the new\n // position instead of the next tick overwriting it.\n if (this.state === 'active') {\n this._abortTicking();\n this._startSession();\n }\n\n return clampedPosition;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Start a ticking session anchored at the current position.\n */\n private _startSession(): void {\n this._sessionStartPosition = this.getPosition();\n this._sessionElapsedOffset = 0;\n\n // Create new abort controller for this ticking session\n this._abortController = new AbortController();\n\n // Start the animation interval\n animationInterval(\n this._tickInterval,\n this._abortController.signal,\n this._onTick.bind(this)\n );\n }\n\n /**\n * Handle a tick from animationInterval.\n *\n * The elapsed parameter is the time since the current ticking session\n * started. Position is the session start position plus the elapsed time,\n * rounded to the nearest tick.\n *\n * Rounding (not flooring) is required: animationInterval aligns its\n * schedule with `Math.round(elapsed / ms)`, and a frame's timestamp can\n * land slightly before the boundary it was scheduled for. Flooring would\n * report such a frame as the previous tick while the scheduler moves on to\n * the tick after next, so one position would be skipped.\n *\n * @param elapsed - Elapsed time in milliseconds from animationInterval\n */\n private _onTick(elapsed: number): void {\n // Skip if not active (safety check)\n if (this.state !== 'active') {\n return;\n }\n\n // Round the elapsed time to the nearest tick boundary in milliseconds,\n // add the session start position, then convert to seconds. Working in\n // integer milliseconds avoids float drift such as 0.1 + 0.2.\n const elapsedThisIteration = elapsed - this._sessionElapsedOffset;\n const ticksElapsed = Math.round(elapsedThisIteration / this._tickInterval);\n const positionMs =\n Math.round(this._sessionStartPosition * 1000) +\n ticksElapsed * this._tickInterval;\n const newPosition = positionMs / 1000;\n const duration = this.getDuration();\n\n // Check if we've reached or exceeded the end\n if (newPosition >= duration) {\n // Report the final position while still active, so actions keyed at\n // the duration run before the end boundary (and also when looping).\n this.setPosition(duration);\n this.emitBoundary('end');\n\n if (this.loop) {\n // Next iteration starts at 0 from this tick onwards. Anchor it to\n // the scheduler's tick grid, not to this frame's jittered timestamp,\n // or every tick of the next iteration inherits this frame's jitter.\n this._sessionElapsedOffset =\n Math.round(elapsed / this._tickInterval) * this._tickInterval;\n this._sessionStartPosition = 0;\n // Reset to start and emit start boundary\n this.setPosition(0);\n this.emitBoundary('start');\n } else {\n this.deactivate();\n }\n } else {\n // Normal position update\n this.setPosition(newPosition);\n }\n }\n\n /**\n * Abort the current ticking session.\n */\n private _abortTicking(): void {\n if (this._abortController) {\n this._abortController.abort();\n this._abortController = null;\n }\n }\n}\n","import {BasePositionSource} from '@timelineproviders/position-sources/base-position-source.ts';\nimport type {ISeekable} from '@timelineproviders/types.ts';\nimport $ from 'jquery';\n\n/**\n * Configuration for ScrollPositionSource.\n */\nexport interface ScrollPositionSourceConfig {\n /**\n * CSS selector for the scrollable container element.\n */\n selector: string;\n\n /**\n * Duration in seconds that the scroll represents.\n * Position is calculated as: (scrollTop / scrollableHeight) * duration\n */\n duration: number;\n}\n\n/**\n * Scroll-based position source.\n *\n * Maps scroll position to a timeline position. The position is calculated\n * as a percentage of the scroll progress multiplied by the configured duration.\n *\n * Implements `IPositionSource` and `ISeekable`.\n *\n * @example\n * ```typescript\n * const source = new ScrollPositionSource({\n * selector: '#scroll-container',\n * duration: 100, // 100 seconds timeline\n * });\n *\n * await source.init();\n *\n * source.onPosition((position) => {\n * console.log(`Scroll at ${position}s of 100s`);\n * });\n *\n * source.onBoundaryReached((boundary) => {\n * if (boundary === 'end') {\n * console.log('Scrolled to bottom');\n * }\n * });\n *\n * await source.activate();\n * ```\n */\nexport class ScrollPositionSource\n extends BasePositionSource\n implements ISeekable\n{\n // ─────────────────────────────────────────────────────────────────────────\n // State\n // ─────────────────────────────────────────────────────────────────────────\n\n private readonly _config: ScrollPositionSourceConfig;\n private _element: HTMLElement | null = null;\n private _boundScrollHandler: ((event: Event) => void) | null = null;\n private _lastPosition = 0;\n private _wasAtStart = true;\n /**\n * The last programmatic scroll: the scrollTop the browser settled on and\n * the exact position it was made for. While the element stays at that\n * offset, the source reports the exact position instead of recomputing it\n * from a pixel-snapped scrollTop, so a seek or loop reset is not followed\n * by a slightly different position from its own scroll event.\n */\n private _programmaticScroll: {scrollTop: number; position: number} | null =\n null;\n\n // ─────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Create a new scroll-based position source.\n *\n * @param config - Configuration options\n */\n constructor(config: ScrollPositionSourceConfig) {\n super(config.duration);\n this._config = config;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // BasePositionSource Implementation\n // ─────────────────────────────────────────────────────────────────────────\n\n protected doInit(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const $element = $(this._config.selector);\n\n if ($element.length === 0) {\n reject(new Error(`Element not found: ${this._config.selector}`));\n return;\n }\n\n this._element = $element.get(0) as HTMLElement;\n resolve();\n });\n }\n\n protected doDestroy(): void {\n if (this._element && this._boundScrollHandler) {\n this._element.removeEventListener('scroll', this._boundScrollHandler, {\n passive: true,\n } as EventListenerOptions);\n this._boundScrollHandler = null;\n }\n this._element = null;\n }\n\n protected startTicking(): void {\n if (!this._element) {\n return;\n }\n\n this._boundScrollHandler = this._handleScroll.bind(this);\n this._element.addEventListener('scroll', this._boundScrollHandler, {\n passive: true,\n });\n\n // Sync with the current scroll offset (restored scroll, a scroll while\n // inactive, a seek while inactive, or a stop/start cycle) instead of\n // waiting for the next event.\n const position = this._currentPosition();\n this._lastPosition = position;\n this._wasAtStart = position === 0;\n this.setPosition(position);\n }\n\n protected stopTicking(): void {\n if (this._element && this._boundScrollHandler) {\n this._element.removeEventListener('scroll', this._boundScrollHandler, {\n passive: true,\n } as EventListenerOptions);\n this._boundScrollHandler = null;\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // ISeekable Implementation\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Seek to a specific position by programmatically scrolling.\n *\n * Position is clamped to the valid range [0, duration]. The scroll is\n * instant (never smooth, even under CSS `scroll-behavior: smooth`), so the\n * target position is reported synchronously in every state and the\n * browser's follow-up scroll event repeats it instead of sweeping through\n * intermediate positions. Seeking while inactive moves the scroll offset\n * too, so a later `activate()` starts at the requested position. Seeking\n * to the same position twice has no further effect.\n *\n * @param position - Target position in seconds (0 to duration)\n * @returns The clamped target position\n */\n async seek(position: number): Promise<number> {\n if (!this._element || this.isDestroyed) {\n return this.getPosition();\n }\n\n const duration = this._config.duration;\n const clampedPosition = Math.max(0, Math.min(position, duration));\n\n this._scrollInstantlyTo(clampedPosition);\n this.setPosition(clampedPosition);\n\n return clampedPosition;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Handle scroll events and update position.\n */\n private _handleScroll(_event: Event): void {\n if (this.state !== 'active' || !this._element) {\n return;\n }\n\n const position = this._currentPosition();\n const duration = this._config.duration;\n\n // Store last position for boundary detection\n const previousPosition = this._lastPosition;\n this._lastPosition = position;\n\n // Update position\n this.setPosition(position);\n\n // Check for end boundary\n if (position >= duration && previousPosition < duration) {\n this.emitBoundary('end');\n\n if (this.loop && this.state === 'active') {\n // Restart is a jump, not a backward scrub: report 0 and the start\n // boundary now, then move the offset instantly so no intermediate\n // positions replay the timeline's actions in reverse\n this.setPosition(0);\n this.emitBoundary('start');\n this._scrollInstantlyTo(0);\n return;\n }\n }\n\n // Check for start boundary (only if we were not already at start)\n if (position === 0 && previousPosition > 0 && !this._wasAtStart) {\n this.emitBoundary('start');\n }\n\n this._wasAtStart = position === 0;\n }\n\n /**\n * Scroll instantly to the offset for `position` and remember it, so the\n * resulting scroll event and a later activation report exactly `position`.\n *\n * The boundary bookkeeping is updated before scrolling, so a scroll event\n * delivered synchronously by the browser sees the new position as current.\n */\n private _scrollInstantlyTo(position: number): void {\n const element = this._element;\n if (!element) {\n return;\n }\n\n this._lastPosition = position;\n this._wasAtStart = position === 0;\n\n const duration = this._config.duration;\n const top =\n duration > 0 ? (position * this._getScrollableHeight()) / duration : 0;\n element.scrollTo({top, behavior: 'instant'});\n this._programmaticScroll = {scrollTop: element.scrollTop, position};\n }\n\n /**\n * The position for the current scroll offset: the exact position of the\n * last programmatic scroll while the element is still at that offset,\n * otherwise the position calculated from the offset.\n */\n private _currentPosition(): number {\n const programmatic = this._programmaticScroll;\n if (programmatic && this._element) {\n if (this._element.scrollTop === programmatic.scrollTop) {\n return programmatic.position;\n }\n this._programmaticScroll = null;\n }\n return this._calculatePosition();\n }\n\n /**\n * Calculate position from scroll percentage, clamped to [0, duration].\n *\n * scrollTop is fractional under browser zoom or high-DPI scaling and can\n * stop just short of the integer maximum, so anything within 1px of the\n * bottom counts as the end.\n */\n private _calculatePosition(): number {\n if (!this._element) {\n return 0;\n }\n\n const scrollTop = this._element.scrollTop;\n const scrollableHeight = this._getScrollableHeight();\n const duration = this._config.duration;\n\n if (scrollableHeight <= 0) {\n return 0;\n }\n\n if (scrollableHeight - scrollTop < 1) {\n return duration;\n }\n\n const position = (scrollTop / scrollableHeight) * duration;\n return Math.max(0, Math.min(position, duration));\n }\n\n /**\n * Get the scrollable height (total scroll distance).\n */\n private _getScrollableHeight(): number {\n if (!this._element) {\n return 0;\n }\n\n return this._element.scrollHeight - this._element.clientHeight;\n }\n}\n","import {BasePositionSource} from '@timelineproviders/position-sources/base-position-source.ts';\nimport type {IContainerProvider, ISeekable} from '@timelineproviders/types.ts';\nimport $ from 'jquery';\n\n/**\n * Media source configuration for VideoPositionSource.\n */\nexport interface VideoSource {\n /**\n * URL of the media file.\n */\n src: string;\n\n /**\n * MIME type of the media (for example 'video/mp4', 'video/webm' or\n * 'audio/mpeg'). Written as the `type` attribute of the `<source>`\n * element; a source whose type the browser reports it cannot play is\n * left out without being requested.\n */\n type: string;\n}\n\n/**\n * Configuration for VideoPositionSource.\n */\nexport interface VideoPositionSourceConfig {\n /**\n * CSS selector for the container the video element is appended to. When\n * it matches several elements, the first one is used.\n */\n selector: string;\n\n /**\n * Media sources, in order of preference. Each becomes a `<source>` child\n * of the video element; the browser plays the first one it supports and\n * falls back to the next when one fails. Browser-playable media files\n * only (video or audio, for example MP4, WebM or MP3); HLS (.m3u8) and\n * DASH (.mpd) play only where the browser supports them natively.\n * Required: `init()` rejects when this is not a non-empty array.\n */\n sources: VideoSource[];\n\n /**\n * Optional poster image URL, shown until the first frame is available.\n */\n poster?: string;\n\n /**\n * Milliseconds `init()` waits for a source to become playable\n * (`canplay`) before it rejects. Guards against media the browser accepts\n * but never finishes loading or reports as failed. `0` disables the limit.\n *\n * @default 30000\n */\n loadTimeout?: number;\n}\n\n/** CSS class of the video element the source creates. */\nconst VIDEO_ELEMENT_CLASS = 'eligius-video';\n\n/** HTMLMediaElement constants, without reading a global of one realm. */\nconst HAVE_NOTHING = 0;\nconst NETWORK_NO_SOURCE = 3;\n\n/** Default of {@link VideoPositionSourceConfig.loadTimeout}. */\nconst DEFAULT_LOAD_TIMEOUT_MS = 30_000;\n\nconst OPTIONS_REMOVED_MESSAGE =\n \"VideoPositionSource: 'options' is no longer supported (the video.js player options were removed in 4.0.0). Put 'sources' and 'poster' directly in the position source settings and delete 'options'.\";\n\ntype TRemoveListener = () => void;\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\nfunction createSourceElement(\n doc: Document,\n {src, type}: VideoSource\n): HTMLSourceElement {\n const element = doc.createElement('source');\n element.src = src;\n // Without a type the browser sniffs the media; never write type=\"undefined\"\n if (isNonEmptyString(type)) {\n element.type = type;\n }\n return element;\n}\n\n/**\n * jsdom has no `error` property at all, so read it defensively.\n */\nfunction describeMediaError(error: MediaError | null | undefined): string {\n if (error?.message) {\n return `: ${error.message}`;\n }\n return error?.code !== undefined ? `: MediaError code ${error.code}` : '';\n}\n\n/**\n * Position source driven by a native HTML `<video>` element.\n *\n * `init()` creates `<video id=\"video-…\" class=\"eligius-video\" preload=\"auto\"\n * playsinline>` with one `<source>` child per playable entry of `sources`,\n * and appends it to the first element matching `selector`. The element has\n * no controls and no styling: size it with CSS on `.eligius-video`. Host\n * code can reach it as `container.querySelector('video.eligius-video')`.\n *\n * Only browser-playable media files are supported (video or audio); there\n * is no HLS or DASH player. `init()` resolves on the first `canplay` and\n * rejects when no source can be played, on a media error, when no source\n * becomes playable within `loadTimeout` (30 s by default), when the\n * container or the sources are missing, when an entry has no `src`, or when\n * the removed `options` key is present. `getContainer()` returns the\n * selector's element. Browser autoplay policies may reject `activate()`\n * with a `NotAllowedError`.\n *\n * Implements `IPositionSource`, `ISeekable`, and `IContainerProvider`.\n *\n * @example\n * ```typescript\n * const source = new VideoPositionSource({\n * selector: '#video-container',\n * sources: [\n * { src: 'video.mp4', type: 'video/mp4' },\n * { src: 'video.webm', type: 'video/webm' },\n * ],\n * });\n *\n * await source.init();\n *\n * source.onPosition((position) => {\n * console.log(`Video at ${position}s`);\n * });\n *\n * source.onContainerReady(() => {\n * console.log('Video ready for display');\n * });\n *\n * await source.activate();\n * ```\n */\nexport class VideoPositionSource\n extends BasePositionSource\n implements ISeekable, IContainerProvider\n{\n // ─────────────────────────────────────────────────────────────────────────\n // State\n // ─────────────────────────────────────────────────────────────────────────\n\n private readonly _config: VideoPositionSourceConfig;\n private readonly _videoElementId: string;\n private _video: HTMLVideoElement | null = null;\n /** Only the appended (playable) source elements, in document order */\n private _sourceElements: HTMLSourceElement[] = [];\n private _initPromise: Promise<void> | null = null;\n private _pendingInit: {\n resolve: () => void;\n reject: (error: unknown) => void;\n } | null = null;\n /** timeupdate, ended, playing and seek listeners */\n private readonly _listeners = new Set<TRemoveListener>();\n /** canplay and the capture-phase error listener of a pending init */\n private readonly _initListeners = new Set<TRemoveListener>();\n private readonly _containerReadyCallbacks: Array<() => void> = [];\n private _containerReady = false;\n private readonly _pendingSeeks = new Set<(position: number) => void>();\n\n // ─────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Create a new video position source.\n *\n * @param config - Configuration options\n */\n constructor(config: VideoPositionSourceConfig) {\n // Duration starts at 0 and comes from the media once it is loaded\n super(0);\n this._config = config;\n this._videoElementId = `video-${crypto.randomUUID?.() ?? Math.random().toString(36).slice(2)}`;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // BasePositionSource Implementation\n // ─────────────────────────────────────────────────────────────────────────\n\n protected doInit(): Promise<void> {\n // A pending or completed init is shared; a failed one is forgotten so\n // the engine's retry on next use starts clean\n this._initPromise ??= this._load().catch((error: unknown) => {\n this._initPromise = null;\n throw error;\n });\n return this._initPromise;\n }\n\n protected doDestroy(): void {\n // Reject a pending init (this also removes the init listeners)\n this._settleInit(\n new Error('VideoPositionSource: destroyed before init completed')\n );\n // A later init() must reach _load() and be refused\n this._initPromise = null;\n // Settle seeks, remove listeners, release the media\n this._teardown();\n // Drop the consumers' container-ready callbacks\n this._containerReadyCallbacks.length = 0;\n }\n\n protected async startTicking(): Promise<void> {\n // Position comes from 'timeupdate'; only playback needs starting.\n // play() rejects when the browser blocks autoplay (NotAllowedError);\n // activate() then reverts the state and rethrows. Awaiting undefined\n // (an environment whose play() returns no promise) is fine.\n await this._video?.play();\n }\n\n protected stopTicking(): void {\n this._video?.pause();\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // ISeekable Implementation\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Seek to a specific position in the media.\n *\n * Resolves on 'seeked' with the position the media landed on. A seek\n * that cannot complete also settles, with the media's current time: on a\n * media 'error' (also at a `<source>`), when the media is reset\n * ('emptied', for example by a new load), or when the source is\n * destroyed. Callers awaiting the seek (such as the engine, which ignores\n * position updates while seeking) are therefore never left waiting.\n *\n * Seeks that the media would never complete settle at once:\n * - before `init()` or after `destroy()`: with `getPosition()`;\n * - after a fatal media error, or when nothing is seekable: with the\n * media's current time;\n * - before the media metadata is loaded: with the requested position,\n * which the element keeps as the position playback starts from.\n *\n * @param position - Target position in seconds\n * @returns Actual position after seek\n */\n async seek(position: number): Promise<number> {\n const video = this._video;\n if (!video || this.isDestroyed) {\n return this.getPosition();\n }\n if (video.error) {\n // A fatal media error was already reported; no 'seeked', 'error' or\n // 'emptied' will follow\n return video.currentTime;\n }\n if (video.readyState === HAVE_NOTHING) {\n // No metadata: the element keeps the value as its default playback\n // start position, the getter returns it, and the real seek runs when\n // the metadata arrives\n video.currentTime = position;\n this.setPosition(position);\n return position;\n }\n if (video.seekable.length === 0) {\n // The HTML seek algorithm returns without firing 'seeked' when there\n // are no seekable ranges\n return video.currentTime;\n }\n\n return new Promise<number>(resolve => {\n let settled = false;\n const removers: TRemoveListener[] = [];\n const settle = (actualPosition: number) => {\n if (settled) {\n return;\n }\n settled = true;\n this._pendingSeeks.delete(settle);\n for (const remove of removers) {\n remove();\n }\n resolve(actualPosition);\n };\n\n const onSeeked = () => {\n const actualPosition = video.currentTime;\n this.setPosition(actualPosition);\n settle(actualPosition);\n };\n\n // The seek will never complete: settle with wherever the media is\n const onAborted = () => settle(video.currentTime);\n\n // Settled by destroy() if it comes first\n this._pendingSeeks.add(settle);\n removers.push(\n this._listen(video, 'seeked', onSeeked),\n // Capture, like init: also sees errors at <source> children\n this._listen(video, 'error', onAborted, true),\n this._listen(video, 'emptied', onAborted)\n );\n\n // After the listeners, in case 'seeked' fires synchronously\n video.currentTime = position;\n });\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // IContainerProvider Implementation\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Get the container element.\n *\n * @returns jQuery-wrapped container element\n */\n getContainer(): JQuery<HTMLElement> | undefined {\n return $(this._config.selector);\n }\n\n /**\n * Register a callback for when the container is ready.\n *\n * The container is ready once playback has started for the first time. If\n * it is already ready, the callback is invoked immediately.\n *\n * @param callback - Function called when container is ready\n */\n onContainerReady(callback: () => void): void {\n if (this._containerReady) {\n callback();\n return;\n }\n this._containerReadyCallbacks.push(callback);\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Overrides\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Get the media duration.\n *\n * @returns Duration in seconds from the media: 0 until its metadata is\n * loaded, `Infinity` for unbounded media\n */\n override getDuration(): number {\n const duration = this._video?.duration;\n // NaN until metadata is loaded; Infinity for unbounded media is kept\n return duration === undefined || Number.isNaN(duration) ? 0 : duration;\n }\n\n /**\n * Deactivate the source and reset position.\n *\n * Overrides base to also reset the media's currentTime.\n */\n override deactivate(): void {\n if (this.state === 'inactive') {\n return;\n }\n // Bumps the activation token, pauses once when active, sets inactive\n // and position 0\n super.deactivate();\n if (this._video) {\n this._video.currentTime = 0;\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Validate the configuration, create the video element with its sources\n * and start loading. Resolves on 'canplay', rejects when no source can be\n * played or on a media error.\n */\n private _load(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (this.isDestroyed) {\n reject(\n new Error(\n 'VideoPositionSource: cannot init a destroyed position source'\n )\n );\n return;\n }\n // Before the sources check, so old configurations get the real reason\n if (Object.hasOwn(this._config, 'options')) {\n reject(new Error(OPTIONS_REMOVED_MESSAGE));\n return;\n }\n // Inside the executor: an invalid selector makes jQuery throw, which\n // becomes a rejection\n const container = $(this._config.selector).get(0);\n if (!container) {\n reject(\n new Error(\n `VideoPositionSource: container not found for selector '${this._config.selector}'`\n )\n );\n return;\n }\n // Without a source the media element never fires 'canplay' or\n // 'error', so init would never settle\n const {sources} = this._config;\n if (!Array.isArray(sources) || sources.length === 0) {\n reject(\n new Error(\n \"VideoPositionSource: 'sources' is required (an array of {src, type})\"\n )\n );\n return;\n }\n const loadTimeout = this._config.loadTimeout ?? DEFAULT_LOAD_TIMEOUT_MS;\n if (\n typeof loadTimeout !== 'number' ||\n !Number.isFinite(loadTimeout) ||\n loadTimeout < 0\n ) {\n reject(\n new Error(\n \"VideoPositionSource: 'loadTimeout' must be a finite number of milliseconds, 0 or more (0 disables the limit)\"\n )\n );\n return;\n }\n const invalid = sources.findIndex(\n source => !isNonEmptyString(source?.src)\n );\n if (invalid !== -1) {\n reject(\n new Error(\n `VideoPositionSource: sources[${invalid}].src must be a non-empty string`\n )\n );\n return;\n }\n\n const doc = container.ownerDocument;\n const video = this._createVideoElement(doc);\n // The browser skips a type it cannot play without requesting it;\n // leaving those out makes the last <source> the real last candidate\n const playable = sources.filter(\n ({type}) => !isNonEmptyString(type) || video.canPlayType(type) !== ''\n );\n if (playable.length === 0) {\n reject(\n new Error(\n `VideoPositionSource: failed to load video (${this._sourceList()}): none of the sources has a type this browser can play`\n )\n );\n return;\n }\n\n this._pendingInit = {resolve, reject};\n this._video = video;\n this._sourceElements = playable.map(source =>\n createSourceElement(doc, source)\n );\n // Listeners before any <source> is attached\n this._attachListeners(video);\n if (loadTimeout > 0) {\n this._startLoadTimer(video, loadTimeout);\n }\n for (const element of this._sourceElements) {\n video.appendChild(element);\n }\n // In the DOM before loading starts. appendChild on the first match,\n // not jQuery append, so nothing is cloned into other matches.\n container.appendChild(video);\n video.load();\n });\n }\n\n private _sourceList(): string {\n return this._config.sources.map(source => source.src).join(', ');\n }\n\n /**\n * Create the video element (DOM APIs, so `src` and `poster` need no\n * escaping).\n */\n private _createVideoElement(doc: Document): HTMLVideoElement {\n const video = doc.createElement('video');\n video.id = this._videoElementId;\n video.className = VIDEO_ELEMENT_CLASS;\n video.preload = 'auto';\n video.controls = false;\n video.autoplay = false;\n // iOS plays inline instead of switching to fullscreen\n video.playsInline = true;\n // Never set video.loop: the source loops itself so the 'end' and\n // 'start' boundaries fire. video.muted is not set: playback starts\n // unmuted, as in 3.x.\n if (this._config.poster !== undefined) {\n video.poster = this._config.poster;\n }\n return video;\n }\n\n /**\n * Add an event listener and record its remover in `group`. The only\n * place that calls addEventListener.\n */\n private _listen(\n target: EventTarget,\n type: string,\n handler: (event: Event) => void,\n capture = false,\n group: Set<TRemoveListener> = this._listeners\n ): TRemoveListener {\n target.addEventListener(type, handler, capture);\n const remove = () => {\n // Same capture flag, or the removal is a no-op\n target.removeEventListener(type, handler, capture);\n group.delete(remove);\n };\n group.add(remove);\n return remove;\n }\n\n /**\n * Attach the media listeners. Each handler first checks that its element\n * is still the current one, so nothing from an old element can drive a\n * new attempt.\n */\n private _attachListeners(video: HTMLVideoElement): void {\n const current = () => this._video === video;\n this._listen(video, 'timeupdate', () => {\n if (current()) {\n this._handleTimeUpdate();\n }\n });\n this._listen(video, 'ended', () => {\n if (current()) {\n this._handleEnded();\n }\n });\n const removePlaying = this._listen(video, 'playing', () => {\n removePlaying();\n if (current()) {\n this._notifyContainerReady();\n }\n });\n this._listen(\n video,\n 'canplay',\n () => {\n if (current()) {\n this._settleInit();\n }\n },\n false,\n this._initListeners\n );\n // 'error' does not bubble. A failed <source> fires it at the <source>,\n // not at the video, and leaves video.error null. A capture listener on\n // the video sees both.\n this._listen(\n video,\n 'error',\n event => {\n if (current()) {\n this._handleInitError(event, video);\n }\n },\n true,\n this._initListeners\n );\n }\n\n /**\n * Reject the pending init when no source has become playable within\n * `ms`. The timer is an init listener, so settling or tearing down init\n * clears it.\n */\n private _startLoadTimer(video: HTMLVideoElement, ms: number): void {\n const timer = setTimeout(() => {\n if (this._video === video) {\n this._failInit(\n new Error(\n `VideoPositionSource: failed to load video (${this._sourceList()}): no source became playable within ${ms} ms`\n )\n );\n }\n }, ms);\n const clear = () => {\n clearTimeout(timer);\n this._initListeners.delete(clear);\n };\n this._initListeners.add(clear);\n }\n\n private _handleInitError(event: Event, video: HTMLVideoElement): void {\n let detail: string;\n if (event.target === video) {\n detail = describeMediaError(video.error);\n } else if (\n event.target === this._sourceElements.at(-1) ||\n // Some browsers fire no error at the remaining non-viable sources;\n // NETWORK_NO_SOURCE means no candidate is left (no sources are added\n // later)\n video.networkState === NETWORK_NO_SOURCE\n ) {\n detail = ': none of the sources could be played';\n } else {\n // An earlier <source> failed and the browser tries the next one\n return;\n }\n this._failInit(\n new Error(\n `VideoPositionSource: failed to load video (${this._sourceList()})${detail}`\n )\n );\n }\n\n /**\n * Settle the pending init promise once: resolve without an error, reject\n * with one. Removes the init listeners either way.\n */\n private _settleInit(error?: unknown): void {\n const pending = this._pendingInit;\n if (!pending) {\n return;\n }\n this._pendingInit = null;\n for (const remove of [...this._initListeners]) {\n remove();\n }\n if (error === undefined) {\n pending.resolve();\n } else {\n pending.reject(error);\n }\n }\n\n /**\n * Reject the pending init and remove the element, so no element or\n * listener survives a failed init.\n */\n private _failInit(error: Error): void {\n this._settleInit(error);\n this._teardown();\n }\n\n /**\n * Settle pending seeks, remove every listener and release the media\n * element.\n */\n private _teardown(): void {\n const video = this._video;\n // Settle pending seeks with the media time, before the listeners go\n const position = video?.currentTime ?? this.getPosition();\n for (const settleSeek of [...this._pendingSeeks]) {\n settleSeek(position);\n }\n // Remove every remaining listener, so nothing below can call back\n for (const remove of [...this._listeners, ...this._initListeners]) {\n remove();\n }\n this._video = null;\n this._sourceElements = [];\n if (!video) {\n return;\n }\n // Release the media. The <source> children must go before load(),\n // otherwise load() selects them again.\n video.pause();\n for (const source of [...video.querySelectorAll('source')]) {\n source.remove();\n }\n video.removeAttribute('src');\n // Aborts the download and frees the decoder\n video.load();\n video.remove();\n }\n\n /**\n * Handle the media's timeupdate event.\n */\n private _handleTimeUpdate(): void {\n if (this.state !== 'active' || !this._video) {\n return;\n }\n this.setPosition(this._video.currentTime);\n }\n\n /**\n * Handle the media's ended event.\n */\n private _handleEnded(): void {\n if (this.state !== 'active') {\n return;\n }\n\n this.emitBoundary('end');\n\n if (!this.loop) {\n // No-op when a boundary listener already stopped or destroyed it\n this.deactivate();\n return;\n }\n if (this.state !== 'active') {\n // An 'end' listener paused, stopped or destroyed the source\n return;\n }\n\n if (this._video) {\n this._video.currentTime = 0;\n }\n this.setPosition(0);\n this.emitBoundary('start');\n if (this.state !== 'active') {\n // A 'start' listener paused it\n return;\n }\n\n // Nobody awaits this replay, so handle its rejection here\n this._video?.play()?.catch(() => {});\n }\n\n /**\n * Notify all container ready callbacks.\n */\n private _notifyContainerReady(): void {\n this._containerReady = true;\n const callbacks = [...this._containerReadyCallbacks];\n this._containerReadyCallbacks.length = 0;\n for (const callback of callbacks) {\n callback();\n }\n }\n}\n","import type {IContainerProvider} from '@timelineproviders/types.ts';\nimport $ from 'jquery';\n\n/**\n * Configuration for DomContainerProvider.\n */\nexport interface DomContainerProviderConfig {\n /**\n * CSS selector for the container element.\n */\n selector: string;\n}\n\n/**\n * DOM selector-based container provider.\n *\n * Provides access to a DOM container element via a CSS selector.\n * Implements `IContainerProvider` for use with position sources that\n * don't have an intrinsic container (e.g., RAF-based sources, WebSocket sources).\n *\n * @example\n * ```typescript\n * const containerProvider = new DomContainerProvider({\n * selector: '#timeline-container',\n * });\n *\n * containerProvider.onContainerReady(() => {\n * const $container = containerProvider.getContainer();\n * $container?.append('<div class=\"content\">Ready!</div>');\n * });\n *\n * await containerProvider.init();\n * ```\n */\nexport class DomContainerProvider implements IContainerProvider {\n // ─────────────────────────────────────────────────────────────────────────\n // State\n // ─────────────────────────────────────────────────────────────────────────\n\n private readonly _config: DomContainerProviderConfig;\n private _container: JQuery<HTMLElement> | undefined;\n private _isReady = false;\n private _isDestroyed = false;\n private readonly _readyCallbacks: Array<() => void> = [];\n\n // ─────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Create a new DOM container provider.\n *\n * @param config - Configuration options\n */\n constructor(config: DomContainerProviderConfig) {\n this._config = config;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Initialize the container provider.\n *\n * Looks up the container element using the configured selector.\n *\n * @throws Error if the element is not found\n */\n async init(): Promise<void> {\n if (this._isReady) {\n return;\n }\n\n const $element = $(this._config.selector);\n\n if ($element.length === 0) {\n throw new Error(`Container element not found: ${this._config.selector}`);\n }\n\n this._container = $element;\n this._isReady = true;\n\n // Notify all ready callbacks\n this._notifyReady();\n }\n\n /**\n * Destroy the container provider and release resources.\n */\n destroy(): void {\n this._container = undefined;\n this._isReady = false;\n this._isDestroyed = true;\n this._readyCallbacks.length = 0;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // IContainerProvider Implementation\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Get the container element.\n *\n * @returns jQuery-wrapped container element, or `undefined` if not initialized\n */\n getContainer(): JQuery<HTMLElement> | undefined {\n return this._container;\n }\n\n /**\n * Register a callback for when the container is ready.\n *\n * If the container is already ready, the callback is invoked immediately.\n *\n * @param callback - Function called when container is ready\n */\n onContainerReady(callback: () => void): void {\n if (this._isDestroyed) {\n return;\n }\n\n if (this._isReady) {\n callback();\n } else {\n this._readyCallbacks.push(callback);\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Notify all registered ready callbacks.\n */\n private _notifyReady(): void {\n for (const callback of this._readyCallbacks) {\n callback();\n }\n }\n}\n","import type {IPlaylist} from '@timelineproviders/types.ts';\n\n/**\n * Configuration for SimplePlaylist.\n *\n * @typeParam TItem - Type of playlist items\n */\nexport interface SimplePlaylistConfig<TItem> {\n /**\n * Array of items in the playlist.\n * Must contain at least one item.\n */\n items: TItem[];\n\n /**\n * Key of the item to use as identifier for `selectItem()`.\n * The value at this key is coerced to a string for comparison.\n */\n identifierKey: keyof TItem;\n}\n\n/**\n * Simple playlist implementation.\n *\n * Manages a collection of timeline items and allows switching between them.\n * Implements `IPlaylist<TItem>` for use with timeline providers that\n * support multiple content sources.\n *\n * Nothing in the engine subscribes to `onItemChange`, and the built-in\n * position sources cannot change their media, so a playlist only has an\n * effect through callbacks the host registers. When the engine switches\n * timelines it calls `selectItem()` with the timeline URI, so key the\n * playlist by timeline URI (`identifierKey` pointing at a property that\n * holds it); use `hasItem()` to check an identifier without the throw.\n *\n * @typeParam TItem - Type of playlist items\n *\n * @example\n * ```typescript\n * interface VideoItem {\n * id: string;\n * uri: string;\n * title: string;\n * }\n *\n * const playlist = new SimplePlaylist<VideoItem>({\n * items: [\n * { id: 'intro', uri: '/videos/intro.mp4', title: 'Introduction' },\n * { id: 'ch1', uri: '/videos/chapter-1.mp4', title: 'Chapter 1' },\n * ],\n * identifierKey: 'id',\n * });\n *\n * playlist.onItemChange((item) => {\n * console.log(`Now playing: ${item.title}`);\n * });\n *\n * playlist.selectItem('ch1');\n * ```\n */\nexport class SimplePlaylist<TItem = unknown> implements IPlaylist<TItem> {\n // ─────────────────────────────────────────────────────────────────────────\n // State\n // ─────────────────────────────────────────────────────────────────────────\n\n private readonly _items: readonly TItem[];\n private readonly _identifierKey: keyof TItem;\n private _currentIndex = 0;\n private readonly _changeCallbacks: Array<(item: TItem) => void> = [];\n\n // ─────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Create a new simple playlist.\n *\n * @param config - Configuration options\n * @throws Error if items array is empty\n */\n constructor(config: SimplePlaylistConfig<TItem>) {\n if (!config.items || config.items.length === 0) {\n throw new Error('Playlist must have at least one item');\n }\n\n this._items = Object.freeze([...config.items]);\n this._identifierKey = config.identifierKey;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // IPlaylist Implementation\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Get the currently active item.\n */\n get currentItem(): TItem {\n return this._items[this._currentIndex];\n }\n\n /**\n * Get all items in the playlist.\n *\n * Returns a readonly array to prevent external modification.\n */\n get items(): readonly TItem[] {\n return this._items;\n }\n\n /**\n * Select an item by identifier.\n *\n * Looks up the item using the configured identifier key and switches\n * to it if found. Triggers item change callbacks if the selection changes.\n *\n * @param identifier - Unique identifier for the item\n * @throws Error if no item matches the identifier\n */\n selectItem(identifier: string): void {\n const index = this._indexOf(identifier);\n\n if (index === -1) {\n throw new Error(`Playlist item not found: ${identifier}`);\n }\n\n // Only notify if actually changing\n if (index !== this._currentIndex) {\n this._currentIndex = index;\n this._notifyChange();\n }\n }\n\n /**\n * Whether an item with the given identifier exists. Does not change the\n * selection.\n *\n * @param identifier - Identifier to look up\n * @returns true when `selectItem(identifier)` would succeed\n */\n hasItem(identifier: string): boolean {\n return this._indexOf(identifier) !== -1;\n }\n\n /**\n * Register a callback for item changes.\n *\n * Called whenever the current item changes via `selectItem()`.\n *\n * @param callback - Function receiving the new current item\n * @returns A function that unregisters the callback\n */\n onItemChange(callback: (item: TItem) => void): () => void {\n this._changeCallbacks.push(callback);\n return () => {\n const index = this._changeCallbacks.indexOf(callback);\n if (index !== -1) {\n this._changeCallbacks.splice(index, 1);\n }\n };\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n private _indexOf(identifier: string): number {\n return this._items.findIndex(\n item => String(item[this._identifierKey]) === identifier\n );\n }\n\n /**\n * Notify all registered change callbacks.\n */\n private _notifyChange(): void {\n const currentItem = this.currentItem;\n for (const callback of [...this._changeCallbacks]) {\n callback(currentItem);\n }\n }\n}\n","/**\n * Every parameter type the operation and controller metadata may use. The\n * metadata generator fails on a type name that is not in this list.\n *\n * `RegExp` and the DOM node types (`Element`, `Text`, `Comment`, `Document`,\n * `DocumentFragment`) are the names the generator emits for `string | RegExp`\n * and `string | JQuery.Node` properties.\n *\n * Kept out of `types.ts`: the generated metadata index re-exports `types.ts`\n * into the `metadata` namespace, whose consumers expect only metadata\n * functions there.\n */\nexport const PARAMETER_TYPES = [\n 'ParameterType:htmlElementName',\n 'ParameterType:className',\n 'ParameterType:selector',\n 'ParameterType:string',\n 'ParameterType:number',\n 'ParameterType:object',\n 'ParameterType:boolean',\n 'ParameterType:array',\n 'ParameterType:eventTopic',\n 'ParameterType:eventName',\n 'ParameterType:systemName',\n 'ParameterType:actionName',\n 'ParameterType:controllerName',\n 'ParameterType:dimensions',\n 'ParameterType:dimensionsModifier',\n 'ParameterType:url',\n 'ParameterType:htmlContent',\n 'ParameterType:labelId',\n 'ParameterType:ImagePath',\n 'ParameterType:QuadrantPosition',\n 'ParameterType:jQuery',\n 'ParameterType:expression',\n 'ParameterType:mathfunction',\n 'ParameterType:cssProperties',\n 'ParameterType:function',\n 'ParameterType:Date',\n 'ParameterType:languagecode',\n 'ParameterType:RegExp',\n 'ParameterType:Element',\n 'ParameterType:Text',\n 'ParameterType:Comment',\n 'ParameterType:Document',\n 'ParameterType:DocumentFragment',\n] as const;\n","import type {IAction} from '@action/types.ts';\nimport type {IEventbus} from '@eventbus/types.ts';\nimport {findClosestNames, formatDidYouMean} from '@util/find-closest-names.ts';\nimport type {IEligiusEngine, ISimpleResourceImporter} from './types.ts';\n\n/**\n * Engine internals that actions, operations and controllers look up by name.\n *\n * Every engine has its own services object. Operations reach it as\n * `this.services` (see `IOperationScope`), controllers receive it in\n * `attach(eventbus, services)`. Because it belongs to one engine, a lookup\n * always answers for that engine, also when several engines share an\n * eventbus.\n */\nexport interface IEngineServices {\n /**\n * Returns the configured action (from `actions` or `eventActions`) with\n * this name.\n *\n * @param systemName - The action name\n * @returns The action\n * @throws Error for an unknown name, with a \"did you mean\" hint\n */\n getAction(systemName: string): IAction;\n /**\n * Returns what the resource importer provides under this name: a custom\n * function, registered JSON or template, or any built-in export.\n *\n * @param systemName - The registered name\n * @returns The registered entry; registered JSON may be `0`, `''` or `false`\n * @throws Error when nothing is registered under the name (the importer's\n * \"did you mean\" hint is kept)\n */\n getImport(systemName: string): unknown;\n /**\n * Creates a new instance of the class the resource importer provides under\n * this name (a controller, for example), constructed with the engine's\n * eventbus.\n *\n * @param systemName - The registered class name\n * @returns The new instance\n * @throws Error when nothing is registered under the name, or when it is not\n * a class\n */\n createInstance<T = unknown>(systemName: string): T;\n /**\n * Returns the engine's root element (its container selector). From\n * `engine.init()` until `engine.destroy()` this is the same jQuery instance.\n *\n * @returns The engine root\n */\n getEngineRoot(): JQuery<HTMLElement>;\n}\n\n/**\n * The services of one engine, created by `EngineFactory.createEngine`.\n *\n * The configuration resolver hands it to every action it creates, before the\n * action lookup and the engine exist; the factory supplies both once they do\n * ({@link setActions}, {@link setEngine}). After {@link dispose} every lookup\n * throws, so a destroyed engine's actions cannot reach its resources.\n */\nexport class EngineServices implements IEngineServices {\n private _actions: Record<string, IAction> | undefined;\n private _engine: Pick<IEligiusEngine, 'engineRoot'> | undefined;\n private _disposed = false;\n\n /**\n * @param importer - Provides the registered functions, classes and data\n * @param eventbus - The engine's eventbus, passed to created instances\n */\n constructor(\n private readonly importer: ISimpleResourceImporter,\n private readonly eventbus: IEventbus\n ) {}\n\n /**\n * Supplies the resolved actions that {@link getAction} looks up.\n *\n * @param actions - The action lookup, by name\n */\n setActions(actions: Record<string, IAction>): void {\n this._actions = actions;\n }\n\n /**\n * Supplies the engine whose root {@link getEngineRoot} returns.\n *\n * @param engine - The engine these services belong to\n */\n setEngine(engine: Pick<IEligiusEngine, 'engineRoot'>): void {\n this._engine = engine;\n }\n\n /**\n * Releases the actions and the engine. Every lookup throws afterwards.\n */\n dispose(): void {\n this._disposed = true;\n this._actions = undefined;\n this._engine = undefined;\n }\n\n getAction(systemName: string): IAction {\n const actions = this._require(this._actions, 'the actions are');\n if (Object.hasOwn(actions, systemName)) {\n return actions[systemName];\n }\n throw new Error(unknownActionMessage(systemName, Object.keys(actions)));\n }\n\n getImport(systemName: string): unknown {\n this._assertLive();\n return importSystemEntry(this.importer, systemName);\n }\n\n createInstance<T = unknown>(systemName: string): T {\n const ctor = this.getImport(systemName) as new (eventbus: IEventbus) => T;\n return new ctor(this.eventbus);\n }\n\n getEngineRoot(): JQuery<HTMLElement> {\n return this._require(this._engine, 'the engine is').engineRoot;\n }\n\n private _assertLive(): void {\n if (this._disposed) {\n throw new Error('EngineServices: the engine was destroyed');\n }\n }\n\n private _require<T>(value: T | undefined, what: string): T {\n this._assertLive();\n if (value === undefined) {\n throw new Error(\n `EngineServices: ${what} not available yet; EngineFactory supplies it once the engine is created`\n );\n }\n return value;\n }\n}\n\n/**\n * Creates services for a context that has no engine, such as linting or a\n * scope made by `createDefaultScope`. Every lookup throws an error naming\n * that context.\n *\n * @param context - Who created the services, for the error message\n * @returns Services whose every lookup throws\n */\nexport function createUnavailableServices(context: string): IEngineServices {\n const unavailable = (): never => {\n throw new Error(\n `${context}: engine services are not available here (no engine)`\n );\n };\n return {\n getAction: unavailable,\n getImport: unavailable,\n createInstance: unavailable,\n getEngineRoot: unavailable,\n };\n}\n\n/**\n * Returns the entry the importer provides under `systemName`.\n *\n * @param importer - The resource importer\n * @param systemName - The registered name\n * @returns The entry; registered JSON and templates may be `0`, `''` or `false`\n * @throws Error when the importer throws or provides nothing under the name\n */\nexport function importSystemEntry(\n importer: ISimpleResourceImporter,\n systemName: string\n): any {\n const module = importer.import(systemName);\n const entry = module?.[systemName];\n if (entry === undefined) {\n throw new Error(\n `Failed to import '${systemName}': module does not export '${systemName}'`\n );\n }\n return entry;\n}\n\nfunction unknownActionMessage(name: string, knownNames: string[]): string {\n const suggestion = formatDidYouMean(findClosestNames(name, knownNames));\n return `Unknown action '${name}'. ${\n suggestion || 'Check the action name in the configuration.'\n }`;\n}\n","/**\n * LocaleLoader - External locale file loading with $ref resolution\n * Feature: 005-rosetta-locale-manager\n *\n * Handles loading external JSON locale files referenced via $ref syntax.\n * Supports caching, parallel loading, and circular reference detection.\n */\n\nimport {deepCopy} from '@operation/helper/deep-copy.ts';\nimport type {\n ILocaleLoader,\n ILocaleLoaderOptions,\n ILocaleLoadResult,\n ILocaleReference,\n TLanguageCode,\n TLocaleData,\n} from './types.ts';\n\nconst SCHEME_PATTERN = /^[a-zA-Z][a-zA-Z\\d+.-]*:/;\n\nfunction hasScheme(url: string): boolean {\n return SCHEME_PATTERN.test(url);\n}\n\nfunction isRootRelative(url: string): boolean {\n return url.startsWith('/');\n}\n\n/**\n * Removes `.` segments and resolves `..` segments, so that one file always\n * gets the same URL however a reference spells it.\n *\n * URLs with a scheme go through `new URL()`. Other URLs stay relative (or\n * root-relative): `..` that would climb above the start of a relative path is\n * kept, `..` above the root of a root-relative path is dropped, and a leading\n * `./` is kept so the URL passed to fetch keeps its original form. The query\n * string and hash are left untouched.\n */\nfunction normaliseUrl(url: string): string {\n if (hasScheme(url)) {\n try {\n return new URL(url).href;\n } catch {\n return url;\n }\n }\n\n const suffixIndex = url.search(/[?#]/);\n const path = suffixIndex === -1 ? url : url.slice(0, suffixIndex);\n const suffix = suffixIndex === -1 ? '' : url.slice(suffixIndex);\n\n let prefix = '';\n let rest = path;\n if (rest.startsWith('//')) {\n // Protocol-relative: keep the host, normalise the path after it.\n const hostEnd = rest.indexOf('/', 2);\n if (hostEnd === -1) {\n return url;\n }\n prefix = rest.slice(0, hostEnd + 1);\n rest = rest.slice(hostEnd + 1);\n } else if (isRootRelative(rest)) {\n prefix = '/';\n rest = rest.slice(1);\n } else if (rest.startsWith('./')) {\n prefix = './';\n }\n const rooted = prefix !== '' && prefix !== './';\n\n const output: string[] = [];\n for (const segment of rest.split('/')) {\n if (segment === '.') {\n continue;\n }\n if (segment === '..') {\n if (output.length > 0 && output[output.length - 1] !== '..') {\n output.pop();\n } else if (!rooted) {\n output.push('..');\n }\n continue;\n }\n output.push(segment);\n }\n\n let normalised = output.join('/');\n if (prefix === './' && normalised.startsWith('..')) {\n prefix = '';\n }\n normalised = `${prefix}${normalised}`;\n return `${normalised}${suffix}`;\n}\n\n/**\n * The key under which a normalised URL is cached and tracked for cycles.\n * `./a.json` and `a.json` name the same file.\n */\nfunction toKey(url: string): string {\n return url.startsWith('./') ? url.slice(2) : url;\n}\n\nfunction describeJsonType(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n return Array.isArray(value) ? 'array' : typeof value;\n}\n\n/**\n * Applies the loader's timeout and abort signal to one fetch.\n */\ninterface IFetchGuard {\n /** Second argument for fetch, or undefined when no signal is needed. */\n init: RequestInit | undefined;\n /** Settles with `promise`, or rejects as soon as the fetch is aborted. */\n race<T>(promise: Promise<T>): Promise<T>;\n /** Clears the timer and the abort listener. */\n dispose(): void;\n}\n\nconst UNGUARDED: IFetchGuard = {\n init: undefined,\n race: promise => promise,\n dispose: () => {},\n};\n\n/**\n * LocaleLoader loads external locale files referenced via $ref syntax.\n *\n * Features:\n * - Fetches JSON locale files from URLs\n * - Caches results to avoid redundant fetches\n * - Detects circular references\n * - Supports baseUrl for relative path resolution\n * - Normalises `./` and `../` segments, so cycle detection and the cache see\n * one URL per file\n * - Optional per-file timeout and abort signal\n */\nexport class LocaleLoader implements ILocaleLoader {\n private readonly _fetch: typeof globalThis.fetch;\n private readonly _baseUrl: string;\n private readonly _timeoutMs: number | undefined;\n private readonly _signal: AbortSignal | undefined;\n private readonly _cache: Map<string, TLocaleData>;\n private readonly _loading: Map<string, Promise<TLocaleData>>;\n\n /**\n * Creates a new LocaleLoader instance.\n *\n * @param options - Configuration options\n * @throws If `timeoutMs` is given and is not a positive finite number\n */\n constructor(options: ILocaleLoaderOptions = {}) {\n const {timeoutMs} = options;\n if (\n timeoutMs !== undefined &&\n !(Number.isFinite(timeoutMs) && timeoutMs > 0)\n ) {\n throw new Error(\n `[LocaleLoader] timeoutMs must be a positive finite number, got ${timeoutMs}`\n );\n }\n // Bind the default: browsers throw 'Illegal invocation' when fetch is\n // called with a receiver other than the global object.\n this._fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this._baseUrl = options.baseUrl ?? '';\n this._timeoutMs = timeoutMs;\n this._signal = options.signal;\n this._cache = new Map();\n this._loading = new Map();\n }\n\n /**\n * Loads a single locale from an external reference.\n *\n * @param locale - The locale code\n * @param reference - The external reference to load\n * @returns The loaded locale data\n * @throws If a file cannot be loaded, does not contain a JSON object, times\n * out or is aborted, or if a circular reference is detected\n */\n async load(\n locale: TLanguageCode,\n reference: ILocaleReference\n ): Promise<ILocaleLoadResult> {\n // Use per-load-chain visited paths to detect circular refs\n const visitedPaths = new Set<string>();\n return this._loadWithVisited(locale, reference, visitedPaths);\n }\n\n /**\n * Internal load method with visited path tracking.\n */\n private async _loadWithVisited(\n locale: TLanguageCode,\n reference: ILocaleReference,\n visitedPaths: Set<string>\n ): Promise<ILocaleLoadResult> {\n const url = this._resolveUrl(reference.$ref);\n const key = toKey(url);\n\n // Check for circular reference within this load chain\n if (visitedPaths.has(key)) {\n throw new Error(\n `[LocaleLoader] Circular reference detected: ${url} has already been visited`\n );\n }\n\n visitedPaths.add(key);\n\n // Resolve nested refs on a copy so the cached data is never mutated\n const data = deepCopy(await this._fetchWithCache(url));\n\n // Check for nested $ref in loaded data (recursive references)\n await this._resolveNestedRefs(data, url, visitedPaths);\n\n return {locale, data};\n }\n\n /**\n * Loads multiple locales in parallel.\n *\n * @param entries - Map of locale codes to references\n * @returns Array of loaded locale data\n */\n async loadAll(\n entries: Map<TLanguageCode, ILocaleReference>\n ): Promise<ILocaleLoadResult[]> {\n // Each load gets its own visitedPaths set for circular detection\n // Cache handles deduplication of same URLs across different locales\n const promises: Promise<ILocaleLoadResult>[] = [];\n\n for (const [locale, reference] of entries) {\n promises.push(this.load(locale, reference));\n }\n\n return Promise.all(promises);\n }\n\n /**\n * Fetches URL with caching to avoid redundant requests.\n */\n private async _fetchWithCache(url: string): Promise<TLocaleData> {\n const key = toKey(url);\n\n // Return from cache if available\n if (this._cache.has(key)) {\n return this._cache.get(key)!;\n }\n\n // Return existing promise if already loading\n if (this._loading.has(key)) {\n return this._loading.get(key)!;\n }\n\n // Start new fetch\n const promise = this._doFetch(url);\n this._loading.set(key, promise);\n\n try {\n const data = await promise;\n this._cache.set(key, data);\n return data;\n } finally {\n this._loading.delete(key);\n }\n }\n\n /**\n * Performs the actual fetch request.\n */\n private async _doFetch(url: string): Promise<TLocaleData> {\n const guard = this._createFetchGuard(url);\n try {\n const response = await guard.race(\n guard.init ? this._fetch(url, guard.init) : this._fetch(url)\n );\n\n if (!response.ok) {\n throw new Error(\n `[LocaleLoader] Failed to load locale file '${url}': ${response.status} ${response.statusText}`\n );\n }\n\n const data: unknown = await guard.race(response.json());\n if (data === null || typeof data !== 'object' || Array.isArray(data)) {\n throw new Error(\n `[LocaleLoader] Locale file '${url}' must contain a JSON object, got ${describeJsonType(data)}`\n );\n }\n return data as TLocaleData;\n } catch (error) {\n if (error instanceof Error && error.message.includes('[LocaleLoader]')) {\n throw error;\n }\n throw new Error(\n `[LocaleLoader] Failed to load locale file '${url}': ${error instanceof Error ? error.message : String(error)}`\n );\n } finally {\n guard.dispose();\n }\n }\n\n /**\n * Builds the abort signal for one fetch from the `timeoutMs` and `signal`\n * options. The fetch is also raced against the abort, so a custom fetch\n * that ignores the signal cannot keep the load pending.\n */\n private _createFetchGuard(url: string): IFetchGuard {\n const timeoutMs = this._timeoutMs;\n const external = this._signal;\n if (timeoutMs === undefined && !external) {\n return UNGUARDED;\n }\n\n const controller = new AbortController();\n let rejectAborted: (error: Error) => void = () => {};\n const aborted = new Promise<never>((_, reject) => {\n rejectAborted = reject;\n });\n // The fetch may finish first, leaving this promise unobserved.\n aborted.catch(() => {});\n\n const abortWith = (error: Error) => {\n rejectAborted(error);\n controller.abort(error);\n };\n const onExternalAbort = () =>\n abortWith(\n new Error(`[LocaleLoader] Loading locale file '${url}' was aborted`)\n );\n\n if (external?.aborted) {\n onExternalAbort();\n } else {\n external?.addEventListener('abort', onExternalAbort, {once: true});\n }\n\n const timer =\n timeoutMs === undefined\n ? undefined\n : setTimeout(\n () =>\n abortWith(\n new Error(\n `[LocaleLoader] Timed out loading locale file '${url}' after ${timeoutMs} ms`\n )\n ),\n timeoutMs\n );\n\n return {\n init: {signal: controller.signal},\n race: promise => Promise.race([promise, aborted]),\n dispose: () => {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n external?.removeEventListener('abort', onExternalAbort);\n },\n };\n }\n\n /**\n * Resolves a potentially relative URL using the baseUrl, then normalises it.\n */\n private _resolveUrl(ref: string): string {\n if (!this._baseUrl || hasScheme(ref) || isRootRelative(ref)) {\n return normaliseUrl(ref);\n }\n\n // Combine baseUrl and ref\n const base = this._baseUrl.endsWith('/')\n ? this._baseUrl\n : `${this._baseUrl}/`;\n return normaliseUrl(`${base}${ref}`);\n }\n\n /**\n * Recursively resolves nested $ref references in loaded data.\n */\n private async _resolveNestedRefs(\n data: TLocaleData,\n parentUrl: string,\n visitedPaths: Set<string>\n ): Promise<void> {\n for (const key of Object.keys(data)) {\n const value = data[key];\n\n if (this._isReference(value)) {\n const nestedUrl = this._resolveRelativeToParent(value.$ref, parentUrl);\n const nestedKey = toKey(nestedUrl);\n\n // visitedPaths holds only the ancestors of the current branch, so a\n // file referenced from two places (a diamond) is not a cycle.\n if (visitedPaths.has(nestedKey)) {\n throw new Error(\n `[LocaleLoader] Circular reference detected: ${nestedUrl} has already been visited (referenced from ${parentUrl})`\n );\n }\n\n visitedPaths.add(nestedKey);\n try {\n const nestedData = deepCopy(await this._fetchWithCache(nestedUrl));\n await this._resolveNestedRefs(nestedData, nestedUrl, visitedPaths);\n\n // Replace the $ref with actual data\n data[key] = nestedData;\n } finally {\n visitedPaths.delete(nestedKey);\n }\n } else if (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value)\n ) {\n // Recurse into nested objects\n await this._resolveNestedRefs(\n value as TLocaleData,\n parentUrl,\n visitedPaths\n );\n }\n }\n }\n\n /**\n * Type guard for reference objects.\n */\n private _isReference(value: unknown): value is ILocaleReference {\n return (\n typeof value === 'object' &&\n value !== null &&\n '$ref' in value &&\n typeof (value as ILocaleReference).$ref === 'string'\n );\n }\n\n /**\n * Resolves a relative path relative to a parent URL, then normalises it.\n */\n private _resolveRelativeToParent(ref: string, parentUrl: string): string {\n // If ref is absolute, it does not depend on the parent\n if (hasScheme(ref) || isRootRelative(ref)) {\n return normaliseUrl(ref);\n }\n\n // Get directory of parent URL\n const lastSlash = parentUrl.lastIndexOf('/');\n if (lastSlash === -1) {\n return normaliseUrl(ref);\n }\n\n const parentDir = parentUrl.substring(0, lastSlash + 1);\n return normaliseUrl(`${parentDir}${ref}`);\n }\n}\n","/**\n * Locale Types\n * Feature: 005-rosetta-locale-manager\n *\n * These types define the public API for the locale management system.\n */\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * IETF language tag format (e.g., 'en-US', 'nl-NL')\n */\nexport type TLanguageCode = `${Lowercase<string>}-${Uppercase<string>}`;\n\n/**\n * Recursive interface for nested translation data.\n * Compatible with rosetta's expected format.\n * Uses interface to support recursive definition.\n */\nexport interface TLocaleData {\n [key: string]:\n | string\n | ((params: Record<string, unknown>) => string)\n | TLocaleData;\n}\n\n/**\n * Valid values in locale data:\n * - string: Simple translation text (may contain {{interpolation}})\n * - function: Dynamic translation that receives params\n * - nested object: Nested translation keys\n */\nexport type TLocaleValue = TLocaleData[keyof TLocaleData];\n\n// =============================================================================\n// Configuration Types\n// =============================================================================\n\n/**\n * External locale file reference using JSON Reference syntax.\n * The loader resolves these to TLocaleData at initialization.\n */\nexport interface ILocaleReference {\n /** URL or relative path to JSON locale file */\n $ref: string;\n}\n\n/**\n * Type guard for ILocaleReference\n */\nexport function isLocaleReference(\n value: TLocaleData | ILocaleReference\n): value is ILocaleReference {\n return (\n typeof value === 'object' &&\n value !== null &&\n '$ref' in value &&\n typeof (value as ILocaleReference).$ref === 'string'\n );\n}\n\n/**\n * A single locale entry can be inline data or an external reference.\n */\nexport type TLocaleEntry = TLocaleData | ILocaleReference;\n\n/**\n * Top-level configuration object for all locales.\n * Keys are language codes, values are inline data or external references.\n */\nexport interface ILocalesConfiguration {\n [locale: TLanguageCode]: TLocaleEntry;\n}\n\n// =============================================================================\n// LocaleManager Types\n// =============================================================================\n\n/**\n * Options for LocaleManager initialization.\n */\nexport interface ILocaleManagerOptions {\n /** Default locale to use at startup */\n defaultLocale: TLanguageCode;\n /** Enable debug mode (logs missing translation keys) */\n debug?: boolean;\n}\n\n/**\n * Events emitted by LocaleManager.\n */\nexport type LocaleEvents = {\n /** Emitted when locale changes: [newLocale, previousLocale] */\n change: [locale: TLanguageCode, previousLocale: TLanguageCode];\n};\n\n/**\n * Main LocaleManager interface.\n * Wraps rosetta with type safety and event emission.\n */\nexport interface ILocaleManager {\n // =========================================================================\n // State (read-only)\n // =========================================================================\n\n /** Current active locale */\n readonly locale: TLanguageCode;\n\n /** List of all loaded locale codes */\n readonly availableLocales: ReadonlyArray<TLanguageCode>;\n\n // =========================================================================\n // Translation\n // =========================================================================\n\n /**\n * Get translated string for key.\n *\n * @param key - Dot-notation key (e.g., 'nav.home') or array (['nav', 'home'])\n * @param params - Optional interpolation parameters\n * @param locale - Optional locale override (defaults to current locale)\n * @returns Translated string, or an empty string if the key does not name a\n * string translation: it is missing, only inherited (such as\n * `constructor`), names a namespace rather than a leaf, or names a function\n * translation that returned a non-string. Debug mode logs a warning for\n * each of these.\n */\n t(\n key: string | string[],\n params?: Record<string, unknown>,\n locale?: TLanguageCode\n ): string;\n\n // =========================================================================\n // Locale Management\n // =========================================================================\n\n /**\n * Change the active locale.\n * Emits 'change' event if locale differs from current.\n * Falls back to default locale if requested locale is unavailable.\n *\n * @param locale - New locale to activate\n */\n setLocale(locale: TLanguageCode): void;\n\n /**\n * Load or merge locale data.\n * Can be called after initialization to add translations.\n *\n * @param locale - Locale code to load data for\n * @param data - Translation data to merge\n */\n loadLocale(locale: TLanguageCode, data: TLocaleData): void;\n\n // =========================================================================\n // Events\n // =========================================================================\n\n /**\n * Subscribe to locale events.\n *\n * Handlers are isolated: one that throws is logged with `console.error`\n * and the others still run, so `setLocale()` does not throw because of a\n * handler. A handler added while an event is being emitted is first called\n * for the next event.\n *\n * @param event - Event name ('change')\n * @param handler - Event handler function\n * @returns Unsubscribe function\n */\n on<K extends keyof LocaleEvents>(\n event: K,\n handler: (...args: LocaleEvents[K]) => void\n ): () => void;\n\n // =========================================================================\n // Lifecycle\n // =========================================================================\n\n /**\n * Clean up resources and remove all listeners.\n */\n destroy(): void;\n}\n\n// =============================================================================\n// LocaleLoader Types\n// =============================================================================\n\n/**\n * Options for LocaleLoader.\n */\nexport interface ILocaleLoaderOptions {\n /** Base URL for resolving relative paths */\n baseUrl?: string;\n /** Custom fetch function (for testing or SSR) */\n fetch?: typeof globalThis.fetch;\n /**\n * Maximum time in milliseconds to wait for each locale file, including\n * reading its body. A file that takes longer makes the load reject with\n * `[LocaleLoader] Timed out loading locale file '<url>' after <n> ms`.\n * Must be a positive finite number. No timeout when omitted.\n */\n timeoutMs?: number;\n /**\n * Aborts all pending and future fetches of this loader when the signal\n * fires, for example when the engine is destroyed while locales are still\n * loading. Pending loads reject with\n * `[LocaleLoader] Loading locale file '<url>' was aborted`.\n *\n * @example\n * ```ts\n * const controller = new AbortController();\n * const loader = new LocaleLoader({signal: controller.signal, timeoutMs: 10000});\n * const loading = loader.load('en-US', {$ref: './locales/en-US.json'});\n * controller.abort(); // loading rejects\n * ```\n */\n signal?: AbortSignal;\n}\n\n/**\n * Result of loading a locale file.\n */\nexport interface ILocaleLoadResult {\n locale: TLanguageCode;\n data: TLocaleData;\n}\n\n/**\n * LocaleLoader interface for resolving external locale references.\n */\nexport interface ILocaleLoader {\n /**\n * Load a single locale from external reference.\n *\n * @param locale - Locale code\n * @param reference - External reference to resolve\n * @returns Resolved locale data\n * @throws If file cannot be loaded or parsed\n */\n load(\n locale: TLanguageCode,\n reference: ILocaleReference\n ): Promise<ILocaleLoadResult>;\n\n /**\n * Load multiple locales in parallel.\n *\n * @param entries - Map of locale codes to references\n * @returns Array of resolved locale data\n */\n loadAll(\n entries: Map<TLanguageCode, ILocaleReference>\n ): Promise<ILocaleLoadResult[]>;\n}\n","/**\n * LocaleManager - Core locale management class wrapping rosetta\n * Feature: 005-rosetta-locale-manager\n *\n * Provides translation retrieval, locale switching, and event emission\n * for the Eligius timeline engine.\n */\n\nimport rosetta from 'rosetta';\nimport {\n type ILocaleManager,\n type ILocaleManagerOptions,\n isLocaleReference,\n type LocaleEvents,\n type TLanguageCode,\n type TLocaleData,\n} from './types.ts';\n\nconst UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\n\n/** Returned by {@link resolveOwnPath} when the path does not exist. */\nconst MISSING: unique symbol = Symbol('missing');\n\n/**\n * Walks `path` from `root` over own properties only, so inherited members\n * such as `constructor` or `toString` never count as present.\n */\nfunction resolveOwnPath(root: unknown, path: readonly string[]): unknown {\n let current = root;\n for (const segment of path) {\n if (\n current === null ||\n typeof current !== 'object' ||\n !Object.hasOwn(current, segment)\n ) {\n return MISSING;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\nfunction toKeyPath(key: string | string[]): string[] {\n return Array.isArray(key) ? key : key.split('.');\n}\n\nfunction keyToString(key: string | string[]): string {\n return Array.isArray(key) ? key.join('.') : key;\n}\n\n/** Matches rosetta's (templite) placeholder syntax: `{{ name }}`, `{{a.b}}`. */\nconst PLACEHOLDER_PATTERN = /\\{\\{(.*?)\\}\\}/g;\n\nfunction isPlainDataObject(value: unknown): value is TLocaleData {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Recursively merges `source` into a copy of `target`. Neither argument is\n * mutated. Keys that could pollute prototypes are skipped.\n */\nfunction mergeLocaleData(\n target: TLocaleData | undefined,\n source: TLocaleData\n): TLocaleData {\n const result: TLocaleData = {...target};\n for (const key of Object.keys(source)) {\n if (UNSAFE_KEYS.has(key)) {\n continue;\n }\n const sourceValue = source[key];\n const targetValue = result[key];\n result[key] =\n isPlainDataObject(sourceValue) && isPlainDataObject(targetValue)\n ? mergeLocaleData(targetValue, sourceValue)\n : sourceValue;\n }\n return result;\n}\n\n/**\n * LocaleManager wraps the rosetta library to provide translation management\n * with event-based locale switching support.\n */\nexport class LocaleManager implements ILocaleManager {\n private readonly _rosetta: ReturnType<typeof rosetta>;\n private readonly _listeners: Map<\n keyof LocaleEvents,\n Set<(...args: LocaleEvents[keyof LocaleEvents]) => void>\n >;\n private _locale: TLanguageCode;\n private readonly _defaultLocale: TLanguageCode;\n private _availableLocales: Set<TLanguageCode>;\n private readonly _debug: boolean;\n /** Raw locale data for debug mode variable checking (rosetta interpolates on access) */\n private readonly _rawLocaleData: Map<TLanguageCode, TLocaleData>;\n\n /**\n * Creates a new LocaleManager instance.\n *\n * @param options - Configuration options for the locale manager\n */\n constructor(options: ILocaleManagerOptions) {\n this._rosetta = rosetta();\n this._listeners = new Map();\n this._locale = options.defaultLocale;\n this._defaultLocale = options.defaultLocale;\n this._availableLocales = new Set();\n this._debug = options.debug ?? false;\n this._rawLocaleData = new Map();\n\n // Set initial locale in rosetta\n this._rosetta.locale(this._locale);\n }\n\n /**\n * Gets the current locale.\n */\n get locale(): TLanguageCode {\n return this._locale;\n }\n\n /**\n * Gets the list of available locales.\n */\n get availableLocales(): ReadonlyArray<TLanguageCode> {\n return Array.from(this._availableLocales);\n }\n\n /**\n * Loads translation data for a specific locale. Data loaded for a locale\n * that already has translations is deep-merged into the existing data.\n *\n * @param locale - The locale code (e.g., 'en-US', 'nl-NL')\n * @param data - The translation data object\n * @throws If `data` is an unresolved external reference (`{$ref: ...}`);\n * resolve it with `LocaleLoader` first.\n */\n loadLocale(locale: TLanguageCode, data: TLocaleData): void {\n if (isLocaleReference(data)) {\n throw new Error(\n `[LocaleManager] Locale '${locale}' is an unresolved external reference ($ref: '${data.$ref}'). Resolve it with LocaleLoader before calling loadLocale.`\n );\n }\n\n const merged = mergeLocaleData(\n this._rosetta.table(locale) as TLocaleData | undefined,\n data\n );\n this._rosetta.set(locale, merged);\n this._availableLocales.add(locale);\n\n // Store raw data for debug mode variable checking\n if (this._debug) {\n this._rawLocaleData.set(\n locale,\n mergeLocaleData(this._rawLocaleData.get(locale), data)\n );\n console.log(`[LocaleManager] Loaded locale: ${locale}`);\n }\n }\n\n /**\n * Retrieves a translation for the given key.\n *\n * The key must name a leaf translation: a string, or a function that\n * returns a string. Every other case returns an empty string (and logs a\n * warning in debug mode):\n * - the key does not exist as own properties of the locale data (inherited\n * members such as `constructor` or `toString` do not count);\n * - the key names a namespace (a nested object) rather than a leaf;\n * - a function translation returns something other than a string.\n *\n * @param key - The translation key (string or array of strings for nested keys)\n * @param params - Optional parameters for interpolation\n * @param locale - Optional locale override (uses current locale if not specified)\n * @returns The translated string, or an empty string if the key does not\n * name a string translation\n * @throws Whatever a function translation throws\n *\n * @example\n * ```ts\n * localeManager.loadLocale('en-US', {nav: {home: 'Home'}});\n * localeManager.t('nav.home'); // 'Home'\n * localeManager.t('nav'); // '' (namespace, not a leaf)\n * ```\n */\n t(\n key: string | string[],\n params?: Record<string, unknown>,\n locale?: TLanguageCode\n ): string {\n const targetLocale = locale ?? this._locale;\n const keyPath = toKeyPath(key);\n\n // rosetta walks inherited properties too, so check the path first.\n if (\n resolveOwnPath(this._rosetta.table(targetLocale), keyPath) === MISSING\n ) {\n this._warnMissingTranslation(key);\n return '';\n }\n\n // In debug mode, check for missing interpolation variables before rosetta interpolates\n if (this._debug && params) {\n this._checkMissingInterpolationVars(key, params, targetLocale);\n }\n\n // Pass the locale to rosetta instead of switching its global locale, so a\n // throwing function translation cannot leave rosetta on the override.\n const result: unknown = this._rosetta.t(key, params, targetLocale);\n\n if (result === undefined || result === null || result === '') {\n this._warnMissingTranslation(key);\n return '';\n }\n\n if (typeof result !== 'string') {\n if (this._debug) {\n console.warn(\n `[LocaleManager] Translation key '${keyToString(key)}' does not name a string translation: it names a namespace, or a function translation returned a ${typeof result}. Returning an empty string.`\n );\n }\n return '';\n }\n\n return result;\n }\n\n private _warnMissingTranslation(key: string | string[]): void {\n if (this._debug) {\n console.warn(\n `[LocaleManager] Missing translation for key: ${keyToString(key)}`\n );\n }\n }\n\n /**\n * Checks for missing interpolation variables in debug mode.\n *\n * Uses rosetta's placeholder syntax: `{{name}}`, `{{ name }}` and dot paths\n * such as `{{user.name}}`. A placeholder is reported when its path does not\n * resolve, over own properties of `params`, to a value other than\n * `undefined` or `null`.\n */\n private _checkMissingInterpolationVars(\n key: string | string[],\n params: Record<string, unknown>,\n locale: TLanguageCode\n ): void {\n // Get raw translation from stored data (rosetta interpolates on access)\n const rawTranslation = this._getRawTranslation(key, locale);\n if (typeof rawTranslation !== 'string') {\n return;\n }\n\n const missingVars = new Set<string>();\n for (const match of rawTranslation.matchAll(PLACEHOLDER_PATTERN)) {\n const name = match[1].trim();\n if (name === '') {\n continue;\n }\n const value = resolveOwnPath(params, name.split('.'));\n if (value === MISSING || value === undefined || value === null) {\n missingVars.add(name);\n }\n }\n\n if (missingVars.size > 0) {\n console.warn(\n `[LocaleManager] Missing interpolation variable(s) for key '${keyToString(key)}': ${[...missingVars].join(', ')}`\n );\n }\n }\n\n /**\n * Gets raw translation value from stored locale data (without interpolation).\n */\n private _getRawTranslation(\n key: string | string[],\n locale: TLanguageCode\n ): unknown {\n const value = resolveOwnPath(\n this._rawLocaleData.get(locale),\n toKeyPath(key)\n );\n return value === MISSING ? undefined : value;\n }\n\n /**\n * Sets the current locale and emits a change event.\n *\n * If the requested locale has not been loaded (and at least one locale\n * has), a warning is logged and the default locale is used instead.\n *\n * Setting the locale that is already current (after any fallback) is a\n * no-op: no event is emitted, so listeners that react by switching the\n * locale again cannot cause a loop.\n *\n * @param locale - The new locale to set\n */\n setLocale(locale: TLanguageCode): void {\n const previousLocale = this._locale;\n if (\n this._availableLocales.size > 0 &&\n !this._availableLocales.has(locale)\n ) {\n console.warn(\n `[LocaleManager] Locale '${locale}' is not available, falling back to default locale '${this._defaultLocale}'. Available locales: ${this.availableLocales.join(', ')}`\n );\n locale = this._defaultLocale;\n }\n if (locale === previousLocale) {\n return;\n }\n this._locale = locale;\n this._rosetta.locale(locale);\n\n this._emit('change', locale, previousLocale);\n\n if (this._debug) {\n console.log(\n `[LocaleManager] Locale changed: ${previousLocale} -> ${locale}`\n );\n }\n }\n\n /**\n * Subscribes to a locale event.\n *\n * @param event - The event name to subscribe to\n * @param handler - The event handler function\n * @returns An unsubscribe function\n */\n on<K extends keyof LocaleEvents>(\n event: K,\n handler: (...args: LocaleEvents[K]) => void\n ): () => void {\n if (!this._listeners.has(event)) {\n this._listeners.set(event, new Set());\n }\n\n const handlers = this._listeners.get(event)!;\n handlers.add(\n handler as (...args: LocaleEvents[keyof LocaleEvents]) => void\n );\n\n // Return unsubscribe function\n return () => {\n handlers.delete(\n handler as (...args: LocaleEvents[keyof LocaleEvents]) => void\n );\n };\n }\n\n /**\n * Destroys the LocaleManager, cleaning up all listeners and data.\n */\n destroy(): void {\n this._listeners.clear();\n this._availableLocales.clear();\n this._rawLocaleData.clear();\n\n if (this._debug) {\n console.log('[LocaleManager] Destroyed');\n }\n }\n\n /**\n * Emits an event to all registered listeners.\n *\n * Iterates a snapshot, so a handler added during the emit is not called for\n * this event. Each handler is isolated: one that throws is logged (with the\n * event name, never the locale data) and the rest still run.\n *\n * @param event - The event name\n * @param args - The event arguments\n */\n private _emit<K extends keyof LocaleEvents>(\n event: K,\n ...args: LocaleEvents[K]\n ): void {\n const handlers = this._listeners.get(event);\n if (!handlers) {\n return;\n }\n for (const handler of [...handlers]) {\n try {\n (handler as (...args: LocaleEvents[K]) => void)(...args);\n } catch (error) {\n console.error(\n `[LocaleManager] Error in '${String(event)}' event handler:`,\n error\n );\n }\n }\n }\n}\n","import {\n EngineEventbusAdapter,\n EngineInputAdapter,\n type IAdapter,\n LocaleEventbusAdapter,\n} from '@adapters/index.ts';\nimport {ConfigurationResolver} from '@configuration/configuration-resolver.ts';\nimport {\n effectiveContainerProvider,\n effectivePositionSource,\n overridesContainerProvider,\n overridesPositionSource,\n providerConfigKey,\n} from '@configuration/timeline-provider-overrides.ts';\nimport type {\n IEngineConfiguration,\n IPositionSourceConfig,\n IResolvedEngineConfiguration,\n IResolvedTimelineConfiguration,\n ITimelineProviderSettings,\n} from '@configuration/types.ts';\nimport {\n ActionRegistryEventbusListener,\n Eventbus,\n type IEventbus,\n RequestVideoUriInterceptor,\n type TEventbusRemover,\n} from '@eventbus/index.ts';\nimport {clearChainCache} from '@operation/helper/chain-cache.ts';\nimport {clearExpressionCache} from '@operation/helper/expression-cache.ts';\nimport {clearGlobals} from '@operation/helper/globals.ts';\nimport {clearJsonCache} from '@operation/load-json.ts';\nimport type {\n IContainerProvider,\n IPlaylist,\n IPositionSource,\n} from '@timelineproviders/types.ts';\nimport {EngineServices, importSystemEntry} from '@/engine-services.ts';\nimport {LocaleLoader} from './locale/locale-loader.ts';\nimport {LocaleManager} from './locale/locale-manager.ts';\nimport {\n type ILocaleReference,\n type ILocalesConfiguration,\n isLocaleReference,\n type TLanguageCode,\n} from './locale/types.ts';\nimport type {\n IEligiusEngine,\n IEngineFactory,\n IEngineFactoryOptions,\n IEngineFactoryResult,\n ISimpleResourceImporter,\n ITimelineProviderInfo,\n TimelineTypes,\n} from './types.ts';\n\n/**\n * Number of engines created by any factory whose destroy() has not run yet.\n * The global data store (see globals.ts) and the loadJson cache are\n * module-wide, so they are cleared only when this drops to zero.\n */\nlet liveEngineCount = 0;\n\n/**\n * How long one external (`$ref`) locale file may take to load before\n * engine.init() rejects, in milliseconds.\n */\nconst LOCALE_LOAD_TIMEOUT_MS = 30000;\n\n/**\n * The EngineFactory is used to create and initialize an {@link IEligiusEngine} instance.\n *\n * It prepares a resolved configuration and creates the engine based on the class defined in the configuration.\n *\n * @example Loading a configuration and creating an IEligiusEngine instance\n * ```ts\n * import { IEngineConfiguration, EngineFactory, EligiusResourceImporter } from 'eligius';\n * import * as engineConfig from './my-eligius-config.json';\n *\n * const factory = new EngineFactory(new EligiusResourceImporter(), window);\n *\n * const { engine } = factory.createEngine((engineConfig as unknown) as IEngineConfiguration);\n *\n * engine.init().then(()=> {console.log('Eligius engine ready for business');});\n * ```\n */\nexport class EngineFactory implements IEngineFactory {\n /** The eventbus from the options, shared by every engine; see `options` */\n private _sharedEventbus: IEventbus | undefined;\n /**\n * Every eventbus registration the factory made that is still in place.\n * An engine's destroy() removes its own; factory.destroy() the rest.\n */\n private _eventRemovers: Set<TEventbusRemover> = new Set();\n /** Live engines on the shared eventbus */\n private _liveSharedEngines = 0;\n private _importer: ISimpleResourceImporter;\n private _windowRef: Window;\n private _options: IEngineFactoryOptions | undefined;\n\n /**\n * @param importer - Resolves system names (engine, operations, controllers,\n * providers) to their implementations\n * @param windowRef - The window the engines run in\n * @param options - Optional settings. Without `options.eventbus` every\n * engine gets its own eventbus; see {@link IEngineFactoryOptions.eventbus}.\n */\n constructor(\n importer: ISimpleResourceImporter,\n windowRef: Window,\n options?: IEngineFactoryOptions\n ) {\n this._importer = importer;\n this._windowRef = windowRef;\n this._options = options;\n this._sharedEventbus = options?.eventbus;\n }\n\n /**\n * Destroys the factory and cleans up all registered request handlers.\n */\n destroy() {\n const removers = [...this._eventRemovers];\n this._eventRemovers.clear();\n removers.forEach(remove => remove());\n }\n\n private _importSystemEntry(systemName: string): any {\n return importSystemEntry(this._importer, systemName);\n }\n\n /**\n * Creates a fully wired engine with adapters and event handlers.\n *\n * This method:\n * - Resolves the configuration\n * - Creates timeline providers\n * - Instantiates the engine and locale manager\n * - Creates and connects adapters for eventbus integration\n *\n * Unless the factory was given an eventbus, the engine gets an eventbus of\n * its own, so several live engines from one factory do not answer each\n * other's requests or react to each other's commands. When this method\n * throws, nothing it registered is left on the eventbus and pending\n * external locale loads are aborted.\n *\n * External (`$ref`) locales are loaded with a 30 second timeout per file.\n * Destroying the engine (through the returned `destroy()` or\n * `engine.destroy()`) aborts loads that are still pending, disconnects the\n * adapters and removes the engine's eventbus registrations.\n *\n * Each engine gets its own {@link EngineServices}: its actions and\n * operations look up actions, imports and the engine root there, never on\n * the eventbus, so they always resolve against their own engine.\n *\n * @param configuration - The engine configuration\n * @returns Engine result with engine, locale manager, eventbus, and destroy function\n * @throws Error when the configuration cannot be resolved or a provider\n * cannot be created\n */\n createEngine(configuration: IEngineConfiguration): IEngineFactoryResult {\n const {systemName} = configuration.engine;\n const EngineClass = this._importSystemEntry(systemName);\n\n const ownsEventbus = !this._sharedEventbus;\n const eventbus = this._sharedEventbus ?? new Eventbus();\n if (!ownsEventbus && this._liveSharedEngines > 0) {\n console.warn(\n '[EngineFactory] Creating a second live engine on a shared eventbus: requests such as request-current-timeline-position are answered by the first engine and commands reach both. Use a factory without options.eventbus to give each engine its own eventbus.'\n );\n }\n const services = new EngineServices(this._importer, eventbus);\n\n // Registrations that belong to this engine. The returned destroy() removes\n // them; they are also tracked factory-wide, so factory.destroy() still\n // removes them if the engine is never destroyed.\n const engineRemovers: TEventbusRemover[] = [];\n const addEngineRemover = (remover: TEventbusRemover) => {\n engineRemovers.push(remover);\n this._eventRemovers.add(remover);\n };\n // Aborts this engine's pending external locale loads.\n const localeLoads = new AbortController();\n const removeEngineRegistrations = () => {\n const removers = engineRemovers.splice(0);\n removers.forEach(remove => {\n this._eventRemovers.delete(remove);\n remove();\n });\n if (ownsEventbus) {\n eventbus.clear();\n }\n };\n\n let engineInstance: IEligiusEngine;\n let localeManager: LocaleManager;\n let adapters: IAdapter[] = [];\n let released = false;\n // Undoes what a successful createEngine set up, once, whether the engine\n // is destroyed through the returned destroy() or engine.destroy().\n const releaseEngine = () => {\n if (released) {\n return;\n }\n released = true;\n adapters.forEach(adapter => adapter.disconnect());\n removeEngineRegistrations();\n services.dispose();\n liveEngineCount--;\n if (!ownsEventbus) {\n this._liveSharedEngines--;\n }\n // The global data store is shared by every engine on the page,\n // so only clear it once no engine is left to use it.\n if (liveEngineCount === 0) {\n clearGlobals();\n clearJsonCache();\n clearExpressionCache();\n clearChainCache();\n }\n };\n let engineInputAdapter: EngineInputAdapter;\n try {\n // Resolve first: it throws on unknown names and duplicate actions, and\n // nothing is registered on the eventbus yet.\n const actionRegistryListener = configuration.eventActions?.length\n ? new ActionRegistryEventbusListener()\n : undefined;\n const resolver = new ConfigurationResolver(\n this._importer,\n eventbus,\n services\n );\n const [actionLookup, resolvedConfiguration] = resolver.process(\n configuration,\n actionRegistryListener\n );\n services.setActions(actionLookup);\n\n const timelineProviders = this._createTimelineProviders(\n resolvedConfiguration\n );\n const timelineProvidersByUri = this.createTimelineProvidersByUri(\n resolvedConfiguration,\n timelineProviders\n );\n\n if (actionRegistryListener) {\n addEngineRemover(\n eventbus.registerEventlistener(actionRegistryListener)\n );\n }\n addEngineRemover(\n eventbus.registerInterceptor(\n 'request-timeline-uri',\n new RequestVideoUriInterceptor(eventbus)\n )\n );\n\n // Initialize locale manager with locales from configuration\n const {language, locales} = configuration;\n localeManager = new LocaleManager({\n defaultLocale: language as TLanguageCode,\n });\n\n // Load inline locales now; external ($ref) locales load in the\n // background and engine.init() waits for them.\n const localesReady = this._loadLocales(\n localeManager,\n locales,\n localeLoads.signal\n );\n\n engineInstance = new EngineClass(\n resolvedConfiguration,\n eventbus,\n timelineProviders,\n localeManager,\n timelineProvidersByUri,\n localesReady,\n this._options?.engineOptions\n );\n services.setEngine(engineInstance);\n\n // Create and connect adapters\n engineInputAdapter = new EngineInputAdapter(\n engineInstance,\n eventbus,\n this._windowRef,\n {\n playToggleHotkey: this._options?.playToggleHotkey,\n ...this._options?.input,\n }\n );\n adapters = [\n new EngineEventbusAdapter(engineInstance, eventbus),\n new LocaleEventbusAdapter(localeManager, eventbus, engineInstance),\n engineInputAdapter,\n ];\n adapters.forEach(adapter => adapter.connect());\n // Also when the engine is destroyed without the returned destroy().\n // The key bindings go too, so a destroyed engine keeps no hotkey. The\n // rest is released once the other 'destroyed' listeners have run.\n engineInstance.on('destroyed', () => {\n localeLoads.abort();\n engineInputAdapter.disconnect();\n queueMicrotask(releaseEngine);\n });\n } catch (error) {\n localeLoads.abort();\n adapters.forEach(adapter => adapter.disconnect());\n removeEngineRegistrations();\n services.dispose();\n throw error;\n }\n\n liveEngineCount++;\n if (!ownsEventbus) {\n this._liveSharedEngines++;\n }\n\n let destroyPromise: Promise<void> | undefined;\n const destroyEngine = async () => {\n // Stop external input first, so no key press restarts playback.\n engineInputAdapter.disconnect();\n // A pending locale load must not resume after destroy.\n localeLoads.abort();\n\n try {\n // Destroy the engine while the eventbus adapters and the services\n // are still live: end operations may need request responders (for\n // example 'request-translation') and the engine root.\n // engineInstance.destroy() also destroys the localeManager.\n await engineInstance.destroy();\n } finally {\n releaseEngine();\n }\n };\n\n // Return the factory result\n return {\n engine: engineInstance,\n localeManager,\n eventbus,\n services,\n destroy: () => {\n // Calling it again returns the first call's promise.\n destroyPromise ??= destroyEngine();\n return destroyPromise;\n },\n };\n }\n\n /**\n * Loads the configured locales into the locale manager.\n *\n * Inline locale data is loaded synchronously. Entries that reference an\n * external file (`{$ref: '...'}`) are fetched with {@link LocaleLoader},\n * with a timeout per file and `signal` to abort them.\n *\n * @param localeManager - The manager to load the locales into\n * @param locales - The configured locales\n * @param signal - Aborts the external loads; once aborted, nothing more is\n * loaded into the manager\n * @returns A promise that settles when the external locales are loaded, or\n * undefined when there are none. It rejects with an error naming the locale\n * that failed.\n */\n private _loadLocales(\n localeManager: LocaleManager,\n locales: ILocalesConfiguration | undefined,\n signal: AbortSignal\n ): Promise<void> | undefined {\n if (!locales) {\n return undefined;\n }\n\n const references = new Map<TLanguageCode, ILocaleReference>();\n for (const [locale, entry] of Object.entries(locales)) {\n if (isLocaleReference(entry)) {\n references.set(locale as TLanguageCode, entry);\n } else {\n localeManager.loadLocale(locale as TLanguageCode, entry);\n }\n }\n\n if (references.size === 0) {\n return undefined;\n }\n\n const loader = new LocaleLoader({\n timeoutMs: LOCALE_LOAD_TIMEOUT_MS,\n signal,\n });\n const loads = [...references].map(([locale, reference]) =>\n loader.load(locale, reference).then(\n result => {\n if (signal.aborted) {\n throw new Error(\n `[EngineFactory] Loading locale '${locale}' was aborted because the engine was destroyed`\n );\n }\n localeManager.loadLocale(result.locale, result.data);\n },\n (error: unknown) => {\n const message =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `[EngineFactory] Failed to load locale '${locale}' from '${reference.$ref}': ${message}`,\n {cause: error}\n );\n }\n )\n );\n const ready = Promise.all(loads).then(() => undefined);\n // An engine that is never initialised must not cause an unhandled\n // rejection; init() still receives the rejection through `ready`.\n ready.catch(() => {});\n return ready;\n }\n\n private _createTimelineProviders(\n configuration: IResolvedEngineConfiguration\n ): Record<TimelineTypes, ITimelineProviderInfo> {\n // Delegate to the new config-driven method\n return this.createTimelineProvidersForConfig(configuration);\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Config-Driven Factory Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Creates a position source for a specific timeline based on configuration.\n *\n * The position source class is resolved dynamically via the resource importer\n * using the `systemName` property from the configuration.\n *\n * @param timeline - The resolved timeline configuration\n * @param settings - The timeline provider settings containing position source config\n * @returns A configured position source\n * @throws Error if the position source class cannot be resolved\n */\n createPositionSourceForTimeline(\n timeline: IResolvedEngineConfiguration['timelines'][number],\n settings: ITimelineProviderSettings\n ): IPositionSource {\n const config = settings.positionSource;\n const {systemName, ...options} = config;\n\n const PositionSourceClass = this._importSystemEntry(systemName);\n\n // Merge timeline-specific values with config options\n const constructorConfig = {\n ...options,\n duration: timeline.duration,\n };\n\n return new PositionSourceClass(constructorConfig);\n }\n\n /**\n * Creates a container provider based on timeline provider settings.\n *\n * The container provider class is resolved dynamically via the resource importer\n * using the `systemName` property from the configuration.\n *\n * @param settings - The timeline provider settings\n * @returns A container provider, or undefined if not configured\n * @throws Error if the container provider class cannot be resolved\n */\n createContainerProviderForTimeline(\n settings: ITimelineProviderSettings\n ): IContainerProvider | undefined {\n if (!settings.container) {\n return undefined;\n }\n\n const {systemName, ...options} = settings.container;\n const ContainerProviderClass = this._importSystemEntry(systemName);\n\n return new ContainerProviderClass(options);\n }\n\n /**\n * Creates a playlist based on timeline provider settings.\n *\n * The playlist class is resolved dynamically via the resource importer\n * using the `systemName` property from the configuration.\n *\n * @param settings - The timeline provider settings\n * @returns A playlist, or undefined if not configured\n * @throws Error if the playlist class cannot be resolved\n */\n createPlaylistForTimeline(\n settings: ITimelineProviderSettings\n ): IPlaylist | undefined {\n if (!settings.playlist) {\n return undefined;\n }\n\n const {systemName, ...options} = settings.playlist;\n const PlaylistClass = this._importSystemEntry(systemName);\n\n return new PlaylistClass(options);\n }\n\n /**\n * Assembles a complete ITimelineProviderInfo from timeline and settings.\n *\n * This is the main entry point for creating provider info with the new\n * configuration-driven architecture.\n *\n * @param timeline - The resolved timeline configuration\n * @param settings - The timeline provider settings\n * @returns A complete timeline provider info with all components\n */\n createTimelineProviderInfo(\n timeline: IResolvedEngineConfiguration['timelines'][number],\n settings: ITimelineProviderSettings\n ): ITimelineProviderInfo {\n return {\n positionSource: this.createPositionSourceForTimeline(timeline, settings),\n containerProvider: this.createContainerProviderForTimeline(settings),\n playlist: this.createPlaylistForTimeline(settings),\n };\n }\n\n /**\n * Creates timeline providers for all configured timeline types using the new\n * configuration-driven architecture.\n *\n * This method iterates over timelineProviderSettings and creates a\n * ITimelineProviderInfo for each configured timeline type by:\n * 1. Finding the first timeline that matches the type, skipping timelines\n * whose `positionSource` override changes the type's settings (when\n * every timeline of the type has one, the first timeline is used)\n * 2. Using the timeline's duration for the position source\n * 3. Assembling components from the settings\n *\n * @param configuration - The resolved engine configuration\n * @returns A record of timeline types to their provider info\n * @throws Error if a provider setting has no matching timeline in config\n */\n createTimelineProvidersForConfig(\n configuration: IResolvedEngineConfiguration\n ): Record<TimelineTypes, ITimelineProviderInfo> {\n const {timelineProviderSettings, timelines} = configuration;\n\n const result = Object.entries(timelineProviderSettings ?? {}).reduce<\n Record<TimelineTypes, ITimelineProviderInfo>\n >(\n (acc, [timelineType, settings]) => {\n if (!settings) {\n return acc;\n }\n\n // The first timeline of this type that uses the type's position\n // source settings unchanged\n const matchingTimeline = representativeTimeline(\n timelines,\n timelineType as TimelineTypes,\n settings\n );\n if (!matchingTimeline) {\n throw new Error(\n `Timeline provider settings for '${timelineType}' has no matching timeline in configuration`\n );\n }\n\n acc[timelineType as TimelineTypes] = this.createTimelineProviderInfo(\n matchingTimeline,\n settings\n );\n return acc;\n },\n {} as Record<TimelineTypes, ITimelineProviderInfo>\n );\n\n return result;\n }\n\n /**\n * Creates the timeline provider for every timeline, keyed by timeline URI.\n *\n * The first timeline of each type reuses the provider created for that type\n * by {@link createTimelineProvidersForConfig}. Every other timeline gets its\n * own position source, constructed with its own duration, and shares the\n * type's container provider and playlist.\n *\n * A timeline whose `positionSource` or `containerProvider` override changes\n * the settings of its type gets that component built from the merged\n * settings (see `ITimelineConfiguration.positionSource`). The\n * components it does not override, and the playlist, come from its type.\n *\n * Position sources that render their own DOM container (they implement\n * `IContainerProvider`, like VideoPositionSource) take their duration from\n * the media rather than from the timeline. They are shared by all timelines\n * of a type with the same effective settings, so switching timelines does\n * not create a second video element; a timeline whose override changes the\n * video settings gets a video element of its own. Overridden container\n * providers are shared the same way.\n *\n * @param configuration - The resolved engine configuration\n * @param providersByType - The providers created per timeline type\n * @returns A record of timeline URIs to their provider info\n * @throws Error when a position source or container provider cannot be\n * imported, or an overridden position source has no `systemName`\n */\n createTimelineProvidersByUri(\n configuration: IResolvedEngineConfiguration,\n providersByType: Record<TimelineTypes, ITimelineProviderInfo>\n ): Record<string, ITimelineProviderInfo> {\n const {timelineProviderSettings, timelines} = configuration;\n const result: Record<string, ITimelineProviderInfo> = {};\n const sharedSources = new Map<string, IPositionSource>();\n const sharedContainers = new Map<string, IContainerProvider | undefined>();\n\n timelines?.forEach(timeline => {\n const typeProvider: ITimelineProviderInfo | undefined =\n providersByType[timeline.type];\n const settings = timelineProviderSettings?.[timeline.type];\n const ownSource = overridesPositionSource(timeline, settings);\n const ownContainer = overridesContainerProvider(timeline, settings);\n\n const typeInfo =\n !ownSource && typeProvider && settings\n ? this._typeProviderInfo(timeline, timelines, settings, typeProvider)\n : undefined;\n if (!ownSource && !ownContainer) {\n if (typeInfo) {\n result[timeline.uri] = typeInfo;\n }\n return;\n }\n\n const positionSource = ownSource\n ? this._overriddenPositionSource(timeline, settings, sharedSources)\n : typeInfo?.positionSource;\n if (!positionSource) {\n return;\n }\n\n result[timeline.uri] = {\n positionSource,\n containerProvider: ownContainer\n ? this._overriddenContainerProvider(\n timeline,\n settings,\n sharedContainers\n )\n : typeProvider?.containerProvider,\n playlist: typeProvider?.playlist,\n };\n });\n\n return result;\n }\n\n /**\n * The provider of a timeline that uses the settings of its type: the type\n * provider itself for the timeline it was created for and for sources with\n * their own container, otherwise a new position source with the timeline's\n * duration next to the type's container provider and playlist.\n */\n private _typeProviderInfo(\n timeline: IResolvedTimelineConfiguration,\n timelines: IResolvedTimelineConfiguration[],\n settings: ITimelineProviderSettings,\n typeProvider: ITimelineProviderInfo\n ): ITimelineProviderInfo {\n if (\n representativeTimeline(timelines, timeline.type, settings) === timeline ||\n hasIntrinsicContainer(typeProvider.positionSource)\n ) {\n return typeProvider;\n }\n return {\n positionSource: this.createPositionSourceForTimeline(timeline, settings),\n containerProvider: typeProvider.containerProvider,\n playlist: typeProvider.playlist,\n };\n }\n\n /**\n * Creates the position source of a timeline from its override merged over\n * the type's settings. Sources with their own container are shared by the\n * timelines of a type with the same merged settings.\n */\n private _overriddenPositionSource(\n timeline: IResolvedTimelineConfiguration,\n settings: ITimelineProviderSettings | undefined,\n sharedSources: Map<string, IPositionSource>\n ): IPositionSource {\n const config = effectivePositionSource(timeline, settings);\n if (!config || typeof config.systemName !== 'string') {\n throw new Error(\n `Timeline '${timeline.uri}' has a positionSource override without a systemName, and there are no timelineProviderSettings.${timeline.type} to merge it over.`\n );\n }\n const timelineSettings: ITimelineProviderSettings = {\n positionSource: config as IPositionSourceConfig,\n };\n const SourceClass = this._importSystemEntry(config.systemName);\n if (!isIntrinsicContainerClass(SourceClass)) {\n return this.createPositionSourceForTimeline(timeline, timelineSettings);\n }\n\n const key = `${timeline.type}:${providerConfigKey(config)}`;\n let source = sharedSources.get(key);\n if (!source) {\n source = this.createPositionSourceForTimeline(timeline, timelineSettings);\n sharedSources.set(key, source);\n }\n return source;\n }\n\n /**\n * Creates the container provider of a timeline from its override merged\n * over the type's settings, shared by the timelines of a type with the\n * same merged settings.\n */\n private _overriddenContainerProvider(\n timeline: IResolvedTimelineConfiguration,\n settings: ITimelineProviderSettings | undefined,\n sharedContainers: Map<string, IContainerProvider | undefined>\n ): IContainerProvider | undefined {\n const config = effectiveContainerProvider(timeline, settings);\n const key = `${timeline.type}:${providerConfigKey(config)}`;\n if (!sharedContainers.has(key)) {\n sharedContainers.set(\n key,\n this.createContainerProviderForTimeline({\n container: config,\n } as ITimelineProviderSettings)\n );\n }\n return sharedContainers.get(key);\n }\n}\n\nfunction hasIntrinsicContainer(source: IPositionSource): boolean {\n const candidate = source as Partial<IContainerProvider>;\n return (\n typeof candidate.getContainer === 'function' &&\n typeof candidate.onContainerReady === 'function'\n );\n}\n\n/**\n * Whether instances of the position source class render their own container,\n * judged from its prototype so no instance is needed.\n */\nfunction isIntrinsicContainerClass(SourceClass: unknown): boolean {\n const prototype = (SourceClass as {prototype?: unknown})?.prototype;\n return (\n typeof prototype === 'object' &&\n prototype !== null &&\n hasIntrinsicContainer(prototype as IPositionSource)\n );\n}\n\n/**\n * The timeline the provider of a type is created for: the first timeline of\n * the type that uses the type's position source settings unchanged, or the\n * first timeline of the type when every one of them overrides them.\n */\nfunction representativeTimeline(\n timelines: IResolvedTimelineConfiguration[],\n type: TimelineTypes,\n settings: ITimelineProviderSettings\n): IResolvedTimelineConfiguration | undefined {\n const ofType = timelines.filter(t => t.type === type);\n return (\n ofType.find(t => !overridesPositionSource(t, settings)) ?? ofType.at(0)\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAKA,MAAa,iBAAiB;AAC9B,MAAa,sBAAsB;AACnC,MAAa,oBAAoB;AACjC,MAAa,oBAAoB;AACjC,MAAa,uBAAuB;AACpC,MAAa,yBAAyB;AACtC,MAAa,4BAA4B;;;;;;;;;;;;;;;;;;;ACazC,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