eligius 4.0.0 → 4.1.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.
package/dist/lint.mjs ADDED
@@ -0,0 +1,4406 @@
1
+
2
+ import { t as __exportAll } from "./rolldown-runtime-CGzGPw9x.mjs";
3
+ import { isDefined } from "ts-is-present";
4
+
5
+ // src/operation/helper/flow-control-names.ts
6
+ /**
7
+ * System names of the control-flow operations, in one place so that the
8
+ * operations and the flow-control scans can share them without importing
9
+ * each other.
10
+ */
11
+ const whenSystemName = "when";
12
+ const otherwiseSystemName = "otherwise";
13
+ const endWhenSystemName = "endWhen";
14
+ const forEachSystemName = "forEach";
15
+ const endForEachSystemName = "endForEach";
16
+ const breakForEachSystemName = "breakForEach";
17
+ const continueForEachSystemName = "continueForEach";
18
+
19
+ // src/operation/helper/assert-safe-property-chain.ts
20
+ /**
21
+ * Property chain segments that lead to an object's prototype or constructor.
22
+ * Reading or writing through them allows prototype pollution or reaching the
23
+ * global `Function` constructor, so property chains may never contain them.
24
+ */
25
+ const forbiddenPropertyChainSegments = /* @__PURE__ */ new Set([
26
+ "__proto__",
27
+ "prototype",
28
+ "constructor"
29
+ ]);
30
+ /**
31
+ * Returns true when the given segment is one of {@link forbiddenPropertyChainSegments}.
32
+ */
33
+ function isForbiddenPropertyChainSegment(segment) {
34
+ return forbiddenPropertyChainSegments.has(segment);
35
+ }
36
+
37
+ // src/operation/helper/chain-cache.ts
38
+ const bracketPattern = /\[(\d+)\]/g;
39
+ /**
40
+ * Expands bracket indices into their own segments and drops empty segments,
41
+ * so `items[2].label` and `items.2.label` resolve the same way.
42
+ */
43
+ function expandSegments(unexpanded) {
44
+ const segments = [];
45
+ for (const segment of unexpanded) {
46
+ if (!segment.includes("[") && !segment.includes(".")) {
47
+ if (segment.length > 0) segments.push(segment);
48
+ continue;
49
+ }
50
+ for (const part of segment.replace(bracketPattern, ".$1").split(".")) if (part.length > 0) segments.push(part);
51
+ }
52
+ return segments;
53
+ }
54
+ /**
55
+ * Returns the first segment whose name (before a `+suffix`) is forbidden.
56
+ */
57
+ function findForbiddenSegment(segments) {
58
+ for (const segment of segments) {
59
+ const name = segment.split("+")[0];
60
+ if (isForbiddenPropertyChainSegment(name)) return name;
61
+ }
62
+ }
63
+ /**
64
+ * Parses chain segments once.
65
+ *
66
+ * @param unexpanded The segments as written, split on dots
67
+ * @param writtenChain The whole chain as written in the configuration. When
68
+ * given, a forbidden segment found before expansion is reported with this
69
+ * text; one found only after expansion is reported with the expanded chain.
70
+ */
71
+ function parseSegments(unexpanded, writtenChain) {
72
+ let forbidden;
73
+ if (writtenChain !== void 0) {
74
+ const segment = findForbiddenSegment(unexpanded);
75
+ if (segment !== void 0) forbidden = {
76
+ chainText: writtenChain,
77
+ segment
78
+ };
79
+ }
80
+ const segments = expandSegments(unexpanded);
81
+ const chainText = segments.join(".");
82
+ if (forbidden === void 0) {
83
+ const segment = findForbiddenSegment(segments);
84
+ if (segment !== void 0) forbidden = {
85
+ chainText,
86
+ segment
87
+ };
88
+ }
89
+ const last = segments.length > 0 ? segments[segments.length - 1] : "";
90
+ const plus = last.indexOf("+");
91
+ return {
92
+ segments,
93
+ chainText,
94
+ lastProperty: plus >= 0 ? last.substring(0, plus) : last,
95
+ suffix: plus >= 0 ? last.substring(plus + 1).split("+")[0] : null,
96
+ head: unexpanded[0] ?? "",
97
+ forbidden
98
+ };
99
+ }
100
+ function messagePrefix(operationName) {
101
+ return operationName ? `${operationName}: property chain` : "Property chain";
102
+ }
103
+ /**
104
+ * Throws when the parsed chain contains a forbidden segment.
105
+ *
106
+ * @throws Error naming the operation, the chain and the segment
107
+ */
108
+ function assertParsedChainSafe(parsed, operationName) {
109
+ if (parsed.forbidden === void 0) return;
110
+ throw new Error(`${messagePrefix(operationName)} '${parsed.forbidden.chainText}' contains forbidden segment '${parsed.forbidden.segment}'. Property chains may not contain __proto__, prototype or constructor.`);
111
+ }
112
+ function globalObjectError(operationName, parsed, index) {
113
+ return /* @__PURE__ */ new Error(`${messagePrefix(operationName)} '${parsed.chainText}' reaches the global object at '${parsed.segments.slice(0, index).join(".")}'. Property chains may not access the global object.`);
114
+ }
115
+ /**
116
+ * Returns true for the global object (`window`), including the window of another frame.
117
+ */
118
+ function isGlobalObject(value) {
119
+ return value === globalThis || typeof value === "object" && value !== null && Object.prototype.toString.call(value) === "[object Window]";
120
+ }
121
+ /**
122
+ * Reads a parsed chain from `sourceObject`.
123
+ *
124
+ * An empty chain returns `sourceObject`. Only null and undefined cannot be
125
+ * indexed; `''`, `0` and `false` are valid intermediates. A `+suffix` on the
126
+ * last segment is appended to the value; an empty suffix returns the value
127
+ * as it is.
128
+ *
129
+ * @throws When an intermediate value is null or undefined (the message names
130
+ * the part of the chain that did resolve), or when the chain passes through
131
+ * or ends at the global object
132
+ */
133
+ function walkChain(parsed, sourceObject, operationName) {
134
+ const { segments } = parsed;
135
+ const count = segments.length;
136
+ let current = sourceObject;
137
+ for (let index = 0; index < count; index++) {
138
+ if (current === null || current === void 0) throw new Error(`${messagePrefix(operationName)} '${parsed.chainText}' cannot be resolved: '${segments.slice(0, index).join(".")}' is ${current}.`);
139
+ if (index > 0 && isGlobalObject(current)) throw globalObjectError(operationName, parsed, index);
140
+ current = current[index === count - 1 ? parsed.lastProperty : segments[index]];
141
+ }
142
+ if (count > 0 && isGlobalObject(current)) throw globalObjectError(operationName, parsed, count);
143
+ return parsed.suffix ? `${current}${parsed.suffix}` : current;
144
+ }
145
+ const prefixes = {
146
+ "$operationdata.": "operationdata",
147
+ "$globaldata.": "globaldata",
148
+ "$scope.": "scope"
149
+ };
150
+ /**
151
+ * Returns the kind of external chain `value` is, or undefined when it is not
152
+ * one. The prefix is matched without regard to case, like before.
153
+ */
154
+ function externalPrefixOf(value) {
155
+ if (value.charCodeAt(0) !== 36) return;
156
+ const dot = value.indexOf(".");
157
+ if (dot < 0) return;
158
+ return prefixes[value.substring(0, dot + 1).toLocaleLowerCase()];
159
+ }
160
+ /**
161
+ * The cache is cleared when it grows past this size, so chains built at
162
+ * runtime cannot leak memory.
163
+ */
164
+ const MAX_CACHED_CHAINS = 2e3;
165
+ const parsedChains = /* @__PURE__ */ new Map();
166
+ /**
167
+ * Returns the parsed form of an external property chain, parsing it on the
168
+ * first use, or null when `value` is not an external chain.
169
+ */
170
+ function getParsedChain(value) {
171
+ const cached = parsedChains.get(value);
172
+ if (cached !== void 0) return cached;
173
+ const prefix = externalPrefixOf(value);
174
+ if (prefix === void 0) return null;
175
+ const unexpanded = value.split(".");
176
+ unexpanded.shift();
177
+ const parsed = {
178
+ ...parseSegments(unexpanded, value),
179
+ prefix
180
+ };
181
+ if (parsedChains.size >= MAX_CACHED_CHAINS) parsedChains.clear();
182
+ parsedChains.set(value, parsed);
183
+ return parsed;
184
+ }
185
+
186
+ // src/util/guards/is-plain-object.ts
187
+ const functionToString = Function.prototype.toString;
188
+ /** Source text of `Object`, the same in every realm */
189
+ const objectConstructorSource = functionToString.call(Object);
190
+ /**
191
+ * Returns true for plain data objects: object literals, parsed JSON objects
192
+ * and `Object.create(null)` objects, also when they were created in another
193
+ * realm (an iframe, a worker, the realm `fetch` parses JSON in). Returns false
194
+ * for arrays, class instances, `Date`, `Map`, DOM nodes, jQuery objects and
195
+ * objects that inherit from another object.
196
+ *
197
+ * @param value - Any value
198
+ * @returns Whether `value` is a plain data object
199
+ */
200
+ function isPlainObject(value) {
201
+ if (value === null || typeof value !== "object") return false;
202
+ const prototype = Object.getPrototypeOf(value);
203
+ if (prototype === null || prototype === Object.prototype) return true;
204
+ if (Object.getPrototypeOf(prototype) !== null) return false;
205
+ const objectConstructor = Object.hasOwn(prototype, "constructor") ? prototype.constructor : void 0;
206
+ return typeof objectConstructor === "function" && functionToString.call(objectConstructor) === objectConstructorSource;
207
+ }
208
+
209
+ // src/operation/helper/deep-copy.ts
210
+ const copyFunction = typeof structuredClone !== "undefined" ? structuredClone : (original) => JSON.parse(JSON.stringify(original));
211
+ /**
212
+ * Deep-copies plain data: arrays and plain objects are copied recursively (cycles are preserved),
213
+ * Date, RegExp, Map, Set, Error, ArrayBuffer and typed arrays are cloned, and everything else
214
+ * (functions, jQuery objects, DOM nodes, class instances) is kept by reference.
215
+ *
216
+ * An own `__proto__` key (as `JSON.parse` creates) stays an own data property of the copy.
217
+ *
218
+ * This runs for every execution of every operation with nested configured data, so it avoids
219
+ * work on the common shapes: the cycle map is only created once a nested object or array
220
+ * appears, and plain keys are assigned instead of defined.
221
+ *
222
+ * @param original The value to copy
223
+ * @returns The copy, or the value itself when it is not copied
224
+ */
225
+ function deepCopy(original) {
226
+ if (original === null || typeof original !== "object" || isReferenceOnly(original)) return original;
227
+ return copyObject(original, { seen: null });
228
+ }
229
+ /**
230
+ * Copies a child value of `parentValue`, whose copy is `parentCopy`.
231
+ */
232
+ function copyChild(child, parentValue, parentCopy, context) {
233
+ if (child === null || typeof child !== "object" || isReferenceOnly(child)) return child;
234
+ if (context.seen === null) {
235
+ context.seen = /* @__PURE__ */ new WeakMap();
236
+ context.seen.set(parentValue, parentCopy);
237
+ }
238
+ return copyObject(child, context);
239
+ }
240
+ /**
241
+ * Copies an object that is not reference-only.
242
+ */
243
+ function copyObject(value, context) {
244
+ const { seen } = context;
245
+ const prior = seen?.get(value);
246
+ if (prior !== void 0) return prior;
247
+ if (Array.isArray(value)) {
248
+ const copy = new Array(value.length);
249
+ if (seen !== null) seen.set(value, copy);
250
+ value.forEach((item, index) => {
251
+ copy[index] = copyChild(item, value, copy, context);
252
+ });
253
+ return copy;
254
+ }
255
+ if (isPlainObject(value)) {
256
+ const copy = {};
257
+ if (seen !== null) seen.set(value, copy);
258
+ for (const key of Object.keys(value)) {
259
+ const copied = copyChild(value[key], value, copy, context);
260
+ if (key === "__proto__") Object.defineProperty(copy, key, {
261
+ value: copied,
262
+ writable: true,
263
+ enumerable: true,
264
+ configurable: true
265
+ });
266
+ else copy[key] = copied;
267
+ }
268
+ return copy;
269
+ }
270
+ if (!isStructuredCloneable(value)) return value;
271
+ const copy = copyFunction(value);
272
+ if (seen !== null) seen.set(value, copy);
273
+ return copy;
274
+ }
275
+ function isReferenceOnly(value) {
276
+ return typeof value.jquery === "string" || typeof Node !== "undefined" && value instanceof Node;
277
+ }
278
+ function isStructuredCloneable(value) {
279
+ return cloneableTags.has(Object.prototype.toString.call(value)) || ArrayBuffer.isView(value);
280
+ }
281
+ const cloneableTags = /* @__PURE__ */ new Set([
282
+ "[object Date]",
283
+ "[object RegExp]",
284
+ "[object Map]",
285
+ "[object Set]",
286
+ "[object Error]",
287
+ "[object ArrayBuffer]"
288
+ ]);
289
+
290
+ // src/operation/helper/resolve-external-property-chain.ts
291
+ /**
292
+ * Returns true when the value is a `$operationdata.`, `$globaldata.` or
293
+ * `$scope.` property chain. The prefix is matched without regard to case.
294
+ */
295
+ function isExternalProperty(value) {
296
+ return typeof value === "string" && externalPrefixOf(value) !== void 0;
297
+ }
298
+
299
+ // src/operation/helper/parse-operand.ts
300
+ const numberPattern = /^[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$/;
301
+ const quotedPattern = /^'(.*)'$/s;
302
+ const chainPattern = /^\$(operationdata|globaldata|scope)\.[^\s.'"]+(\.[^\s.'"]+)*$/i;
303
+ const keywords = {
304
+ true: true,
305
+ false: false,
306
+ null: null
307
+ };
308
+ /**
309
+ * Parses one operand of a condition expression. The tokenizer in `parse-expression.ts`
310
+ * calls it for every operand it finds, so this function is the single definition of the
311
+ * operand grammar.
312
+ *
313
+ * The operand grammar:
314
+ * - a number: `100`, `-1.5`, `2e3` (the whole token must be numeric, so `10px` is invalid);
315
+ * - a string in single quotes: `'John'`;
316
+ * - the keywords `true`, `false` and `null`;
317
+ * - a property chain starting with `$operationdata.`, `$globaldata.` or `$scope.` (the prefix
318
+ * is case-insensitive), for example `$scope.variables.count`.
319
+ *
320
+ * @param token The operand text, already trimmed.
321
+ * @param operationName The operation parsing the expression, named in the error.
322
+ * @param expression The whole expression, quoted in the error.
323
+ * @param position The 0-based position of the operand in the expression, named in the error
324
+ * when given.
325
+ * @returns The parsed operand.
326
+ * @throws When the token matches none of the forms above.
327
+ */
328
+ function parseOperand(token, operationName, expression, position) {
329
+ const quoted = quotedPattern.exec(token);
330
+ if (quoted) return {
331
+ kind: "literal",
332
+ value: quoted[1]
333
+ };
334
+ if (Object.hasOwn(keywords, token)) return {
335
+ kind: "literal",
336
+ value: keywords[token]
337
+ };
338
+ if (numberPattern.test(token)) return {
339
+ kind: "literal",
340
+ value: Number(token)
341
+ };
342
+ if (isExternalProperty(token) && chainPattern.test(token)) return {
343
+ kind: "chain",
344
+ chain: token
345
+ };
346
+ throw new Error(`${operationName}: unknown operand '${token}' in expression '${expression}'${position === void 0 ? "" : ` at position ${position}`}. Use a number, a quoted string ('text'), true, false, null, or a property chain starting with $operationdata., $globaldata. or $scope.`);
347
+ }
348
+
349
+ // src/operation/helper/parse-expression.ts
350
+ const symbols = [
351
+ "&&",
352
+ "||",
353
+ "==",
354
+ "!=",
355
+ ">=",
356
+ "<=",
357
+ ">",
358
+ "<",
359
+ "!",
360
+ "(",
361
+ ")"
362
+ ];
363
+ const comparisonOperators = /* @__PURE__ */ new Set([
364
+ "==",
365
+ "!=",
366
+ ">=",
367
+ "<=",
368
+ ">",
369
+ "<"
370
+ ]);
371
+ const delimiterPattern = /[\s()!=<>&|]/;
372
+ function isDelimiter(char) {
373
+ return char === void 0 || delimiterPattern.test(char);
374
+ }
375
+ /**
376
+ * Parses a condition expression into a tree that {@link evaluateExpression} evaluates.
377
+ *
378
+ * The grammar, from lowest to highest precedence:
379
+ *
380
+ * ```
381
+ * or := and ('||' and)*
382
+ * and := comparison ('&&' comparison)*
383
+ * comparison := unary (('==' | '!=' | '>=' | '<=' | '>' | '<') unary)?
384
+ * unary := '!' unary | primary
385
+ * primary := '(' or ')' | operand
386
+ * ```
387
+ *
388
+ * Operands are parsed by {@link parseOperand}: numbers, single-quoted strings, `true`,
389
+ * `false`, `null` and `$operationdata.`, `$globaldata.` or `$scope.` property chains.
390
+ * Inside a quoted string, operators and parentheses are part of the text. A quote ends the
391
+ * string only when it is followed by whitespace, an operator, a parenthesis or the end of the
392
+ * expression, so an apostrophe inside the text (`'it's'`) needs no escaping.
393
+ *
394
+ * Comparisons do not chain (`1<x<3` is an error, write `1<x && x<3`). Arithmetic is not
395
+ * supported. Nothing in the expression is executed as code.
396
+ *
397
+ * @param expression The expression text.
398
+ * @param operationName The operation parsing the expression, named in the error messages.
399
+ * @returns The root node of the parsed expression.
400
+ * @throws When the expression is not a string or is empty, contains an unknown operand, an
401
+ * unterminated string, an unknown or misplaced operator, or unbalanced parentheses. The message
402
+ * names the operation, the problem, its position (0-based) and the expression.
403
+ *
404
+ * @example
405
+ * parseExpression("$scope.variables.score>=5 && !$operationdata.skipped", 'when');
406
+ */
407
+ function parseExpression(expression, operationName) {
408
+ if (typeof expression !== "string") throw new Error(`${operationName}: expression must be a string, received ${expression === null ? "null" : typeof expression}.`);
409
+ const tokens = tokenize(expression, operationName);
410
+ if (!tokens.length) throw new Error(`${operationName}: empty expression '${expression}'.`);
411
+ let index = 0;
412
+ const fail = (message, position, hint) => {
413
+ throw new Error(`${operationName}: ${message} at position ${position} in expression '${expression}'.${hint ? ` ${hint}` : ""}`);
414
+ };
415
+ const unexpected = (token, hint) => token ? fail(`unexpected '${token.text}'`, token.position, hint) : fail("unexpected end of expression", expression.length, hint);
416
+ const peekSymbol = () => {
417
+ const token = tokens[index];
418
+ return token?.type === "symbol" ? token.text : void 0;
419
+ };
420
+ const parseOr = () => {
421
+ let left = parseAnd();
422
+ while (peekSymbol() === "||") {
423
+ index++;
424
+ left = {
425
+ kind: "or",
426
+ left,
427
+ right: parseAnd()
428
+ };
429
+ }
430
+ return left;
431
+ };
432
+ const parseAnd = () => {
433
+ let left = parseComparison();
434
+ while (peekSymbol() === "&&") {
435
+ index++;
436
+ left = {
437
+ kind: "and",
438
+ left,
439
+ right: parseComparison()
440
+ };
441
+ }
442
+ return left;
443
+ };
444
+ const parseComparison = () => {
445
+ const left = parseUnary();
446
+ const operator = peekSymbol();
447
+ if (operator && comparisonOperators.has(operator)) {
448
+ index++;
449
+ return {
450
+ kind: "comparison",
451
+ operator,
452
+ left,
453
+ right: parseUnary()
454
+ };
455
+ }
456
+ return left;
457
+ };
458
+ const parseUnary = () => {
459
+ if (peekSymbol() === "!") {
460
+ index++;
461
+ return {
462
+ kind: "not",
463
+ operand: parseUnary()
464
+ };
465
+ }
466
+ return parsePrimary();
467
+ };
468
+ const parsePrimary = () => {
469
+ const token = tokens[index];
470
+ if (token?.type === "operand") {
471
+ index++;
472
+ return {
473
+ kind: "operand",
474
+ operand: token.operand
475
+ };
476
+ }
477
+ if (token?.text === "(") {
478
+ index++;
479
+ const node = parseOr();
480
+ const closing = tokens[index];
481
+ if (!closing) return fail("missing ')' for the '('", token.position);
482
+ if (closing.text !== ")") return unexpected(closing, "Expected ')' or an operator.");
483
+ index++;
484
+ return node;
485
+ }
486
+ return unexpected(token);
487
+ };
488
+ const root = parseOr();
489
+ if (index < tokens.length) {
490
+ const token = tokens[index];
491
+ unexpected(token, token.text === ")" ? "It has no matching '('." : token.type === "symbol" && comparisonOperators.has(token.text) ? "Comparisons do not chain, combine them with && or use parentheses." : "Expected && or || between the parts of the condition.");
492
+ }
493
+ return root;
494
+ }
495
+ /**
496
+ * Splits the expression into symbols and operands. Operands are parsed with
497
+ * {@link parseOperand}, so the operand grammar has one source.
498
+ */
499
+ function tokenize(expression, operationName) {
500
+ const tokens = [];
501
+ let i = 0;
502
+ while (i < expression.length) {
503
+ const char = expression[i];
504
+ if (/\s/.test(char)) {
505
+ i++;
506
+ continue;
507
+ }
508
+ const symbol = symbols.find((s) => expression.startsWith(s, i));
509
+ if (symbol) {
510
+ tokens.push({
511
+ type: "symbol",
512
+ text: symbol,
513
+ position: i
514
+ });
515
+ i += symbol.length;
516
+ continue;
517
+ }
518
+ if (char === "=" || char === "&" || char === "|") throw new Error(`${operationName}: unexpected '${char}' at position ${i} in expression '${expression}'. Did you mean '${char}${char}'?`);
519
+ const end = char === "'" ? endOfString(expression, i) : endOfWord(expression, i);
520
+ if (end < 0) throw new Error(`${operationName}: unterminated string at position ${i} in expression '${expression}'.`);
521
+ const text = expression.substring(i, end);
522
+ tokens.push({
523
+ type: "operand",
524
+ text,
525
+ position: i,
526
+ operand: parseOperand(text, operationName, expression, i)
527
+ });
528
+ i = end;
529
+ }
530
+ return tokens;
531
+ }
532
+ /**
533
+ * Returns the index after the quote that closes the string starting at `start`, or -1 when the
534
+ * string is not closed. A quote closes the string only when a delimiter or the end follows it.
535
+ */
536
+ function endOfString(expression, start) {
537
+ for (let i = start + 1; i < expression.length; i++) if (expression[i] === "'" && isDelimiter(expression[i + 1])) return i + 1;
538
+ return -1;
539
+ }
540
+ function endOfWord(expression, start) {
541
+ let i = start;
542
+ while (i < expression.length && !isDelimiter(expression[i])) i++;
543
+ return i;
544
+ }
545
+
546
+ // src/util/guards/is-promise.ts
547
+ /**
548
+ * Returns true for promises and other thenables.
549
+ *
550
+ * @param obj - Any value
551
+ * @returns Whether `obj` is an object with a `then` method
552
+ */
553
+ function isPromise(obj) {
554
+ return typeof obj === "object" && obj !== null && typeof obj.then === "function";
555
+ }
556
+
557
+ // src/action/action.ts
558
+ var Action = class {
559
+ name;
560
+ startOperations;
561
+ eventbus;
562
+ id = "";
563
+ /**
564
+ * Scope stack used by {@link executeOperation} when it is called without an
565
+ * explicit stack. `start()` and `end()` each create their own stack, so
566
+ * overlapping executions of the same action never share scopes.
567
+ *
568
+ * @deprecated Calling {@link executeOperation} without a scope stack is
569
+ * deprecated; this fallback will be removed in the next major version.
570
+ */
571
+ _scopeStack = [];
572
+ /**
573
+ * The configured `forEach` operation data copied when a loop starts, keyed
574
+ * by the loop's scope. Later iterations of the same loop merge this copy
575
+ * again instead of deep-copying the collection on every iteration.
576
+ */
577
+ _loopOperationData = /* @__PURE__ */ new WeakMap();
578
+ constructor(name, startOperations, eventbus) {
579
+ this.name = name;
580
+ this.startOperations = startOperations;
581
+ this.eventbus = eventbus;
582
+ }
583
+ /**
584
+ * Runs the start operations.
585
+ *
586
+ * A failure is not logged here: the returned promise rejects with the
587
+ * error (annotated with the failing operation), and the caller reports it.
588
+ * The engine reports it through its `error` event, the eventbus through
589
+ * its `onHandlerError` option, and `init()` by rejecting.
590
+ *
591
+ * @param initOperationData - Operation data the first start operation receives
592
+ * @returns The operation data of the last start operation
593
+ */
594
+ start(initOperationData) {
595
+ return this._runOperations(this.startOperations, initOperationData);
596
+ }
597
+ /**
598
+ * Runs the given operations with a scope stack that belongs to this
599
+ * execution only.
600
+ *
601
+ * @param operations - The operations to run
602
+ * @param initOperationData - Operation data the first operation receives
603
+ * @param onSettled - Called the moment the operations have completed or
604
+ * failed, before the returned promise settles. Operations that complete
605
+ * synchronously call it synchronously.
606
+ * @returns The operation data of the last operation
607
+ */
608
+ _runOperations(operations, initOperationData, onSettled) {
609
+ const scopeStack = this._createScopeStack(operations);
610
+ return new Promise((resolve, reject) => {
611
+ this.executeOperation(operations, 0, onSettled ? (value) => {
612
+ onSettled();
613
+ resolve(value);
614
+ } : resolve, onSettled ? (reason) => {
615
+ onSettled();
616
+ reject(reason);
617
+ } : reject, initOperationData, scopeStack);
618
+ });
619
+ }
620
+ _createScopeStack(operations) {
621
+ return [{
622
+ currentIndex: -1,
623
+ eventbus: this.eventbus,
624
+ operations
625
+ }];
626
+ }
627
+ /**
628
+ * @deprecated Unused: `start()` and `end()` create a scope stack for each
629
+ * execution. Will be removed in the next major version.
630
+ */
631
+ _initializeScopeStack() {
632
+ this._scopeStack = this._createScopeStack(this.startOperations);
633
+ }
634
+ _pushScope(scopeStack, parentScope) {
635
+ const newScope = {
636
+ get currentIndex() {
637
+ return parentScope.currentIndex;
638
+ },
639
+ set currentIndex(value) {
640
+ parentScope.currentIndex = value;
641
+ },
642
+ get eventbus() {
643
+ return parentScope.eventbus;
644
+ },
645
+ get operations() {
646
+ return parentScope.operations;
647
+ },
648
+ parent: parentScope
649
+ };
650
+ scopeStack.push(newScope);
651
+ return newScope;
652
+ }
653
+ /**
654
+ * Executes `operations` starting at `operationIndex`.
655
+ *
656
+ * Synchronous operations run in a loop, so the stack depth does not grow with
657
+ * the number of executed operations (large `forEach` loops are safe). When an
658
+ * operation returns a promise, execution continues once it resolves.
659
+ */
660
+ executeOperation(operations, operationIndex, resolve, reject, previousOperationData = {}, scopeStack = this._scopeStack) {
661
+ let index = operationIndex;
662
+ let operationData = previousOperationData ?? {};
663
+ let failingOperation;
664
+ let failingIndex = operationIndex;
665
+ try {
666
+ while (true) {
667
+ let scope = scopeStack[scopeStack.length - 1];
668
+ if (scope.newIndex !== void 0) {
669
+ index = scope.newIndex;
670
+ delete scope.newIndex;
671
+ }
672
+ scope.currentIndex = index;
673
+ if (index >= operations.length) {
674
+ resolve(operationData);
675
+ return;
676
+ }
677
+ const operationInfo = operations[index];
678
+ failingOperation = operationInfo;
679
+ failingIndex = index;
680
+ const isLoopIteration = operationInfo.systemName === "forEach" && scope.owner === operationInfo;
681
+ const configuredData = (isLoopIteration ? this._loopOperationData.get(scope) : void 0) ?? copyConfiguredOperationData(operationInfo.operationData, operationInfo.systemName);
682
+ const mergedOperationData = Object.assign(operationData, configuredData);
683
+ if (operationInfo.systemName === "when") scope = this._pushScope(scopeStack, scope);
684
+ else if (operationInfo.systemName === "forEach" && !isLoopIteration) {
685
+ scope = this._pushScope(scopeStack, scope);
686
+ scope.owner = operationInfo;
687
+ this._loopOperationData.set(scope, configuredData);
688
+ }
689
+ const operationResult = operationInfo.instance.call(scope, mergedOperationData);
690
+ if (operationInfo.systemName === "endWhen" || operationInfo.systemName === "endForEach" && scope.newIndex === void 0) scopeStack.pop();
691
+ index++;
692
+ if (isPromise(operationResult)) {
693
+ const nextIndex = index;
694
+ const asyncOperation = operationInfo;
695
+ const asyncIndex = index - 1;
696
+ operationResult.then((promisedOperationResult) => this.executeOperation(operations, nextIndex, resolve, reject, promisedOperationResult, scopeStack), (error) => reject(withOperationContext(error, asyncOperation, asyncIndex))).catch(reject);
697
+ return;
698
+ }
699
+ operationData = operationResult ?? {};
700
+ }
701
+ } catch (error) {
702
+ reject(failingOperation ? withOperationContext(error, failingOperation, failingIndex) : error);
703
+ }
704
+ }
705
+ };
706
+ /**
707
+ * Adds the failing operation's system name and index to an error, unless an
708
+ * inner action already did (the innermost operation is the most specific).
709
+ * Non-Error values are wrapped in an Error that keeps their message.
710
+ */
711
+ function withOperationContext(error, operation, index) {
712
+ const annotated = error instanceof Error ? error : new Error(String(error), { cause: error });
713
+ if (annotated.operationSystemName === void 0) {
714
+ annotated.operationSystemName = operation.systemName;
715
+ annotated.operationIndex = index;
716
+ }
717
+ return annotated;
718
+ }
719
+ const emptyOperationData = Object.freeze({});
720
+ /**
721
+ * Configured operation data already checked by {@link assertNoProtoKeys}.
722
+ * Configured data is not changed after resolution, so each object is walked
723
+ * once, not on every run of its operation.
724
+ */
725
+ const checkedOperationData = /* @__PURE__ */ new WeakSet();
726
+ /**
727
+ * Throws when an own `__proto__` key occurs anywhere in the configured
728
+ * operation data (JSON.parse creates one as a normal property). Merging with
729
+ * Object.assign would run the `__proto__` setter at the top level, and
730
+ * operations that assign or merge nested data could do the same below it.
731
+ * Arrays and plain objects are walked; class instances, jQuery objects and
732
+ * DOM nodes are not.
733
+ *
734
+ * @throws Error naming the operation and the path of the key
735
+ */
736
+ function assertNoProtoKeys(operationData, systemName) {
737
+ if (checkedOperationData.has(operationData)) return;
738
+ const visiting = /* @__PURE__ */ new Set();
739
+ const walk = (value, path) => {
740
+ if (value === null || typeof value !== "object" || visiting.has(value)) return;
741
+ if (Array.isArray(value)) {
742
+ visiting.add(value);
743
+ value.forEach((item, index) => {
744
+ walk(item, `${path}[${index}]`);
745
+ });
746
+ return;
747
+ }
748
+ if (!isPlainObject(value)) return;
749
+ visiting.add(value);
750
+ if (Object.hasOwn(value, "__proto__")) {
751
+ const at = path ? `${path}.__proto__` : "__proto__";
752
+ throw new Error(`${systemName}: operation data must not contain a '__proto__' key (found at '${at}')`);
753
+ }
754
+ for (const key of Object.keys(value)) walk(value[key], path ? `${path}.${key}` : key);
755
+ };
756
+ walk(operationData, "");
757
+ checkedOperationData.add(operationData);
758
+ }
759
+ /**
760
+ * Returns the configured operation data in a form that is safe to merge into
761
+ * the running operation data.
762
+ *
763
+ * Merging copies the top-level properties, so operations that delete or
764
+ * reassign properties (such as `@erased` ones) never touch the configured
765
+ * object. Only nested objects and arrays can be mutated through the merged
766
+ * data, so a deep copy is made only when the configured data contains one.
767
+ * Empty data and data holding only primitives and functions is returned as-is.
768
+ *
769
+ * @throws Error when the data contains a `__proto__` key at any depth
770
+ */
771
+ function copyConfiguredOperationData(operationData, systemName) {
772
+ if (!operationData) return emptyOperationData;
773
+ assertNoProtoKeys(operationData, systemName);
774
+ for (const key in operationData) {
775
+ const value = operationData[key];
776
+ if (typeof value === "object" && value !== null && Object.hasOwn(operationData, key)) return deepCopy(operationData);
777
+ }
778
+ return operationData;
779
+ }
780
+
781
+ // src/action/endable-action.ts
782
+ var EndableAction = class extends Action {
783
+ endOperations;
784
+ constructor(name, startOperations, endOperations, eventBus) {
785
+ super(name, startOperations, eventBus);
786
+ this.endOperations = endOperations;
787
+ }
788
+ /**
789
+ * Runs the end operations.
790
+ *
791
+ * A failure is not logged here: the returned promise rejects with the
792
+ * error (annotated with the failing operation), and the caller reports it.
793
+ * The engine reports it through its `error` event.
794
+ *
795
+ * @param initOperationData - Operation data the first end operation receives
796
+ * @returns The operation data of the last end operation
797
+ */
798
+ end(initOperationData) {
799
+ if (!this.endOperations.length) return Promise.resolve(initOperationData ?? {});
800
+ return this._runOperations(this.endOperations, initOperationData);
801
+ }
802
+ };
803
+
804
+ // src/action/timeline-action.ts
805
+ var TimelineAction = class extends EndableAction {
806
+ duration;
807
+ _active = false;
808
+ /** True while start or end operations of this action are running */
809
+ _running = false;
810
+ /** Starts and ends called while operations were running, in call order */
811
+ _waiting = [];
812
+ /**
813
+ * Finishes the run that `_execute` is starting; handed to the operations
814
+ * run (see `_runOperations`) so it is called the moment they settle.
815
+ */
816
+ _finishPending;
817
+ /**
818
+ * True from the moment `start()` is called until `end()` is called, whether
819
+ * or not the action has end operations. Both transitions happen
820
+ * synchronously, so a second dispatch of the same start or end (a seek
821
+ * while playing, a revisited key) is a no-op.
822
+ */
823
+ get active() {
824
+ return this._active;
825
+ }
826
+ constructor(name, startOperations, endOperations, duration, eventBus) {
827
+ super(name, startOperations, endOperations, eventBus);
828
+ this.duration = duration;
829
+ }
830
+ /**
831
+ * Starts the action, unless it is already active.
832
+ *
833
+ * `active` becomes true at once. When the operations of an earlier start
834
+ * or end are still running (an asynchronous end at a loop wrap, a start
835
+ * awaiting a fetch when its range is skipped), these start operations run
836
+ * once those have finished, so the start and end operations of one action
837
+ * never interleave. Otherwise they run right away.
838
+ *
839
+ * @param initOperationData - Operation data the first start operation receives
840
+ * @returns The operation data of the last start operation
841
+ */
842
+ start(initOperationData) {
843
+ if (this._active) return Promise.resolve({});
844
+ this._active = true;
845
+ return this._sequence(() => super.start(initOperationData));
846
+ }
847
+ /**
848
+ * Ends the action, unless it is not active.
849
+ *
850
+ * `active` becomes false at once. Like {@link start}, the end operations
851
+ * wait for operations of this action that are still running.
852
+ *
853
+ * @param initOperationData - Operation data the first end operation receives
854
+ * @returns The operation data of the last end operation
855
+ */
856
+ end(initOperationData) {
857
+ if (!this._active) return Promise.resolve({});
858
+ this._active = false;
859
+ return this._sequence(() => super.end(initOperationData));
860
+ }
861
+ _sequence(run) {
862
+ if (!this._running) return this._execute(run);
863
+ return new Promise((resolve, reject) => {
864
+ this._waiting.push(() => {
865
+ this._execute(run).then(resolve, reject);
866
+ });
867
+ });
868
+ }
869
+ /**
870
+ * Runs `run`, marking the action as running until its operations settle.
871
+ * Operations that complete synchronously finish the run synchronously, so
872
+ * a start and end called back to back both run within the same call stack.
873
+ */
874
+ _execute(run) {
875
+ let finished = false;
876
+ const finish = () => {
877
+ if (finished) return;
878
+ finished = true;
879
+ this._running = false;
880
+ this._waiting.shift()?.();
881
+ };
882
+ this._running = true;
883
+ this._finishPending = finish;
884
+ let result;
885
+ try {
886
+ result = run();
887
+ } catch (error) {
888
+ result = Promise.reject(error);
889
+ }
890
+ if (this._finishPending === finish) {
891
+ this._finishPending = void 0;
892
+ finish();
893
+ }
894
+ return result;
895
+ }
896
+ _runOperations(operations, initOperationData, onSettled) {
897
+ const finish = this._finishPending;
898
+ this._finishPending = void 0;
899
+ return super._runOperations(operations, initOperationData, () => {
900
+ onSettled?.();
901
+ finish?.();
902
+ });
903
+ }
904
+ };
905
+
906
+ // src/configuration/timeline-provider-overrides.ts
907
+ /**
908
+ * Merges a per-timeline override over the settings of the timeline's type.
909
+ *
910
+ * - Without an override the type's settings are returned as they are.
911
+ * - An override that leaves out `systemName`, or names the same class as the
912
+ * type's settings, is merged over them property by property (shallow).
913
+ * - An override that names a different class replaces the type's settings,
914
+ * so options meant for one class never reach another.
915
+ *
916
+ * @param base - The settings of the timeline's type, if any
917
+ * @param override - The timeline's override, if any
918
+ * @returns The effective settings, or undefined when neither is given
919
+ */
920
+ function mergeProviderConfig(base, override) {
921
+ if (!override) return base;
922
+ if (!base) return { ...override };
923
+ if (override.systemName !== void 0 && override.systemName !== base.systemName) return { ...override };
924
+ return {
925
+ ...base,
926
+ ...override
927
+ };
928
+ }
929
+ /**
930
+ * The effective position source settings of a timeline: its
931
+ * `positionSource` override merged over the settings of its type (see
932
+ * {@link mergeProviderConfig}).
933
+ */
934
+ function effectivePositionSource(timeline, typeSettings) {
935
+ return mergeProviderConfig(typeSettings?.positionSource, timeline.positionSource);
936
+ }
937
+ /**
938
+ * The effective container provider settings of a timeline: its
939
+ * `containerProvider` override merged over the `container` settings of its
940
+ * type (see {@link mergeProviderConfig}).
941
+ */
942
+ function effectiveContainerProvider(timeline, typeSettings) {
943
+ return mergeProviderConfig(typeSettings?.container, timeline.containerProvider);
944
+ }
945
+
946
+ // src/operation/helper/flow-control-structure.ts
947
+ const closerOf = {
948
+ [whenSystemName]: endWhenSystemName,
949
+ [forEachSystemName]: endForEachSystemName
950
+ };
951
+ /**
952
+ * Checks that the `when`/`otherwise`/`endWhen` and `forEach`/`endForEach`
953
+ * blocks of an operation list are balanced and nested, and that
954
+ * `breakForEach` and `continueForEach` sit inside a `forEach`.
955
+ *
956
+ * The interpreter does not check this. An `endWhen` that closes a `forEach`,
957
+ * or an `endWhen` without a `when`, pops the wrong scope at runtime, and the
958
+ * action then fails with a TypeError on the next operation, or runs with the
959
+ * wrong scope. A block that is never closed runs to the end of the list.
960
+ *
961
+ * @param systemNames The system names of the operations, in order
962
+ * @returns The problems in list order, empty when the blocks are well formed
963
+ */
964
+ function findFlowControlProblems(systemNames) {
965
+ const problems = [];
966
+ const stack = [];
967
+ const close = (closer, expected, index) => {
968
+ const top = stack[stack.length - 1];
969
+ if (!top) {
970
+ problems.push({
971
+ index,
972
+ message: `${closer} at index ${index} has no open ${expected} to close.`
973
+ });
974
+ return;
975
+ }
976
+ if (top.name !== expected) problems.push({
977
+ index,
978
+ 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.`
979
+ });
980
+ stack.pop();
981
+ };
982
+ systemNames.forEach((name, index) => {
983
+ switch (name) {
984
+ case whenSystemName:
985
+ case forEachSystemName:
986
+ stack.push({
987
+ name,
988
+ index,
989
+ hasOtherwise: false
990
+ });
991
+ break;
992
+ case otherwiseSystemName: {
993
+ const top = stack[stack.length - 1];
994
+ if (!top || top.name !== "when") problems.push({
995
+ index,
996
+ message: top ? `otherwise at index ${index} is inside the forEach at index ${top.index}, not directly inside a when.` : `otherwise at index ${index} has no open when.`
997
+ });
998
+ else if (top.hasOtherwise) problems.push({
999
+ index,
1000
+ message: `otherwise at index ${index} is the second otherwise of the when at index ${top.index}.`
1001
+ });
1002
+ else top.hasOtherwise = true;
1003
+ break;
1004
+ }
1005
+ case endWhenSystemName:
1006
+ close(endWhenSystemName, whenSystemName, index);
1007
+ break;
1008
+ case endForEachSystemName:
1009
+ close(endForEachSystemName, forEachSystemName, index);
1010
+ break;
1011
+ case breakForEachSystemName:
1012
+ case continueForEachSystemName: if (!stack.some((block) => block.name === "forEach")) problems.push({
1013
+ index,
1014
+ message: `${name} at index ${index} is not inside a forEach.`
1015
+ });
1016
+ }
1017
+ });
1018
+ for (const open of stack) problems.push({
1019
+ index: open.index,
1020
+ message: `${open.name} at index ${open.index} is never closed with ${closerOf[open.name]}.`
1021
+ });
1022
+ return problems.sort((a, b) => a.index - b.index);
1023
+ }
1024
+
1025
+ // src/operation/helper/get-property-chain-value.ts
1026
+ /**
1027
+ * Gets the value for the given property chain. A property chain is defined by a string array.
1028
+ *
1029
+ * For example, this property chain: `[mySource, subSource, element, value]` should be extracted from an object of this shape:
1030
+ * ```ts
1031
+ * const foo = {
1032
+ * mySource: {
1033
+ * subSource: {
1034
+ * element: {
1035
+ * value: 'bar'
1036
+ * }
1037
+ * }
1038
+ * }
1039
+ * }
1040
+ * ```
1041
+ *
1042
+ * The result of the invocation `getPropertyChainValue([mySource, subSource, element, value], foo)` would then yield the value `bar`.
1043
+ *
1044
+ * Chains containing a `__proto__`, `prototype` or `constructor` segment are rejected to
1045
+ * prevent prototype pollution and access to the `Function` constructor. Chains that pass
1046
+ * through or end at the global object (`window`), for example
1047
+ * `selectedElement.0.ownerDocument.defaultView`, are rejected too, so configuration cannot
1048
+ * reach `eval`, `Function`, timers or other globals.
1049
+ *
1050
+ * Bracket indices are expanded into their own segments, so `eventArgs[0]` resolves like
1051
+ * `eventArgs.0` and `items[2].label` like `items.2.label`. The parsing is shared with the
1052
+ * cached external chains, see `chain-cache.ts`.
1053
+ *
1054
+ * @param propertyChain The chain segments. Segments may use dot or bracket notation themselves.
1055
+ * @param sourceObject The object to resolve the chain against.
1056
+ * @param operationName The operation resolving the chain, named in the error messages.
1057
+ * @throws When an intermediate value is null or undefined (the message names the part of the
1058
+ * chain that did not resolve), when the chain contains a forbidden segment, or when it reaches
1059
+ * the global object.
1060
+ */
1061
+ function getPropertyChainValue(propertyChain, sourceObject, operationName) {
1062
+ const parsed = parseSegments(propertyChain);
1063
+ assertParsedChainSafe(parsed, operationName);
1064
+ return walkChain(parsed, sourceObject, operationName);
1065
+ }
1066
+
1067
+ // src/operation/helper/resolve-property-chain.ts
1068
+ /**
1069
+ * Gets the value for the given property chain. A property chain is defined by a period delimited string.
1070
+ *
1071
+ * For example, this property chain: `mySource.subSource.element.value` should be extracted from an object of this shape:
1072
+ * ```ts
1073
+ * const foo = {
1074
+ * mySource: {
1075
+ * subSource: {
1076
+ * element: {
1077
+ * value: 'bar'
1078
+ * }
1079
+ * }
1080
+ * }
1081
+ * }
1082
+ * ```
1083
+ *
1084
+ * The result of the invocation `resolvePropertyChain('mySource.subSource.element.value', foo)` would then yield the value `bar`.
1085
+ *
1086
+ * Chains containing `__proto__`, `prototype` or `constructor` segments are rejected.
1087
+ *
1088
+ * @throws When the chain cannot be resolved or contains a forbidden segment.
1089
+ */
1090
+ function resolvePropertyChain(propertyChain, sourceObject, operationName) {
1091
+ const properties = propertyChain.split(".");
1092
+ return getPropertyChainValue(properties, sourceObject, operationName);
1093
+ }
1094
+
1095
+ // src/util/find-closest-names.ts
1096
+ /**
1097
+ * Returns the known names closest to `name`, for "did you mean" hints in error
1098
+ * messages. Matching ignores case and uses the Levenshtein edit distance; only
1099
+ * names within `max(2, floor(name.length / 3))` edits are returned, closest
1100
+ * first.
1101
+ *
1102
+ * @param name - The unknown name, as written in the configuration
1103
+ * @param knownNames - The names that are registered
1104
+ * @param max - The maximum number of suggestions to return
1105
+ * @returns Up to `max` known names, closest first; empty when none is close
1106
+ */
1107
+ function findClosestNames(name, knownNames, max = 3) {
1108
+ const lowerName = name.toLowerCase();
1109
+ const maxDistance = Math.max(2, Math.floor(name.length / 3));
1110
+ return knownNames.map((knownName) => ({
1111
+ knownName,
1112
+ distance: levenshtein(lowerName, knownName.toLowerCase())
1113
+ })).filter(({ distance }) => distance <= maxDistance).sort((a, b) => a.distance - b.distance).slice(0, max).map(({ knownName }) => knownName);
1114
+ }
1115
+ /**
1116
+ * Formats suggestions from {@link findClosestNames} as a sentence.
1117
+ *
1118
+ * @param suggestions - The suggested names
1119
+ * @returns `Did you mean 'a', 'b'?`, or an empty string when there are no suggestions
1120
+ */
1121
+ function formatDidYouMean(suggestions) {
1122
+ if (!suggestions.length) return "";
1123
+ return `Did you mean ${suggestions.map((name) => `'${name}'`).join(", ")}?`;
1124
+ }
1125
+ function levenshtein(a, b) {
1126
+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
1127
+ for (let i = 1; i <= a.length; i++) {
1128
+ const current = [i];
1129
+ for (let j = 1; j <= b.length; j++) {
1130
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
1131
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
1132
+ }
1133
+ previous = current;
1134
+ }
1135
+ return previous[b.length];
1136
+ }
1137
+
1138
+ // src/util/guards/is-function.ts
1139
+ function isFunction(value) {
1140
+ return typeof value === "function";
1141
+ }
1142
+
1143
+ // src/util/guards/is-object.ts
1144
+ /**
1145
+ * Returns true for any non-null, non-array object: plain objects, but also
1146
+ * class instances, `Date`, `Map`, DOM nodes and jQuery objects.
1147
+ *
1148
+ * The narrowed type is a loose record. When the value must be a plain data
1149
+ * object (an object literal or parsed JSON), use `isPlainObject` instead.
1150
+ *
1151
+ * @param value - Any value
1152
+ * @returns Whether `value` is a non-null, non-array object
1153
+ */
1154
+ function isObject(value) {
1155
+ return !!value && typeof value === "object" && !Array.isArray(value);
1156
+ }
1157
+
1158
+ // src/util/guards/is-string.ts
1159
+ function isString(value) {
1160
+ return typeof value === "string";
1161
+ }
1162
+
1163
+ // src/configuration/configuration-resolver.ts
1164
+ /**
1165
+ * The default warning handler: writes the warning to the console.
1166
+ */
1167
+ function warnToConsole(warning) {
1168
+ console.warn(`Eligius configuration warning at ${warning.path}: ${warning.message}`);
1169
+ }
1170
+ /**
1171
+ * Takes an `IEngineConfiguration` instance and return an `IResolvedEngineConfiguration`.
1172
+ * This means all system names within the configuration will be resolved to their associated instances.
1173
+ *
1174
+ * If the given configuration includes event actions, then those will be registered in the given
1175
+ * `ActionRegistryEventbusListener`. They are registered only after the whole configuration
1176
+ * has been accepted, so a configuration that `process` rejects leaves the listener untouched.
1177
+ *
1178
+ * Every error names the JSON path of the offending value.
1179
+ *
1180
+ * @throws When an operation's `systemName` does not resolve to an operation function (including
1181
+ * controller, timeline provider, custom function and class exports of the importer). The message
1182
+ * suggests the closest operation names the importer lists, which include the custom operations
1183
+ * registered with `EligiusResourceImporter`.
1184
+ * @throws When two actions (or an action and an event action) share the same name.
1185
+ * @throws When `actions`, `initActions`, `timelines`, an action's `startOperations` or
1186
+ * `endOperations`, or a timeline's `timelineActions` is not an array.
1187
+ * @throws When a timeline action has no valid `duration`, or when a timeline's `type` has no
1188
+ * entry in `timelineProviderSettings` and the timeline has no `positionSource` with a `systemName`
1189
+ * of its own.
1190
+ * @throws When a timeline's `positionSource` or `containerProvider` override is not an object,
1191
+ * names a `systemName` the importer does not provide, or leaves out a setting that the provider
1192
+ * requires (for example `selector` of `ScrollPositionSource`) once it is merged over the type's
1193
+ * settings.
1194
+ * @throws When a VideoPositionSource has an 'options' key, at timelineProviderSettings.<type>.positionSource
1195
+ * or at a timeline's positionSource override (also when the override inherits VideoPositionSource from its
1196
+ * type). 4.0.0 removed the video.js player options.
1197
+ * @throws When a `template:`, `json:` or `config:` placeholder cannot be resolved.
1198
+ *
1199
+ * Control-flow blocks that are not well formed (an `endWhen` without a `when`,
1200
+ * an `endWhen` that closes a `forEach`, a `when` that is never closed, a
1201
+ * `breakForEach` outside a `forEach`) are reported as warnings through
1202
+ * {@link IConfigurationResolverOptions.onWarning}, by default on the console.
1203
+ * The interpreter runs them as before: an operation list with such a block
1204
+ * fails at runtime, or runs with the wrong scope. They become errors in the
1205
+ * next major version. `eligius/lint` reports the same shapes as errors.
1206
+ */
1207
+ var ConfigurationResolver = class {
1208
+ importer;
1209
+ eventbus;
1210
+ _warn;
1211
+ /**
1212
+ * @param importer - Resolves system names to operations, controllers and providers
1213
+ * @param eventbus - The eventbus the resolved actions run on
1214
+ * @param options - Optional. `onWarning` receives the configuration
1215
+ * warnings instead of the console.
1216
+ */
1217
+ constructor(importer, eventbus, options = {}) {
1218
+ this.importer = importer;
1219
+ this.eventbus = eventbus;
1220
+ this._warn = options.onWarning ?? warnToConsole;
1221
+ }
1222
+ process(configuration, actionRegistryListener) {
1223
+ const imported = /* @__PURE__ */ new WeakSet();
1224
+ resolvePlaceholders(configuration, configuration, this.importer, "import", imported, "");
1225
+ resolvePlaceholders(configuration, configuration, this.importer, "config", imported, "");
1226
+ if (!isObject(configuration.timelineProviderSettings) && !(configuration.timelineProviderSettings === void 0 && everyTimelineHasOwnPositionSource(configuration.timelines))) throw new Error(`Configuration incomplete: it needs to have at least one timeline provider setting at timelineProviderSettings, got ${describeValue(configuration.timelineProviderSettings)}.`);
1227
+ const resolvedConfig = {
1228
+ id: configuration.id,
1229
+ engine: { ...configuration.engine },
1230
+ timelineProviderSettings: deepCopy(configuration.timelineProviderSettings) ?? {},
1231
+ containerSelector: configuration.containerSelector,
1232
+ cssFiles: deepCopy(configuration.cssFiles),
1233
+ language: configuration.language,
1234
+ layoutTemplate: configuration.layoutTemplate,
1235
+ availableLanguages: deepCopy(configuration.availableLanguages),
1236
+ actions: resolveActions(configuration.actions, this.importer, this.eventbus, "actions", this._warn),
1237
+ initActions: resolveActions(configuration.initActions, this.importer, this.eventbus, "initActions", this._warn),
1238
+ timelineFlow: deepCopy(configuration.timelineFlow),
1239
+ timelines: resolveTimelines(configuration.timelines, this.importer, this.eventbus, this._warn)
1240
+ };
1241
+ assertTimelineProviderSettings(configuration, this.importer);
1242
+ let eventActions = [];
1243
+ if (isDefined(configuration.eventActions)) {
1244
+ assertArray(configuration.eventActions, "eventActions");
1245
+ if (actionRegistryListener) eventActions = resolveEventActions(configuration.eventActions, this.importer, this.eventbus, this._warn);
1246
+ }
1247
+ const actionsLookup = createActionsLookup([...resolvedConfig.actions.map((action, index) => [action, `actions[${index}]`]), ...eventActions.map(({ action }, index) => [action, `eventActions[${index}]`])]);
1248
+ for (const { action, eventName, eventTopic } of eventActions) actionRegistryListener?.registerAction(action, eventName, eventTopic);
1249
+ return [actionsLookup, resolvedConfig];
1250
+ }
1251
+ };
1252
+ /**
1253
+ * Describes a value for an error message by its kind only, so configuration
1254
+ * data never ends up in a message.
1255
+ */
1256
+ function describeValue(value) {
1257
+ if (value === null) return "null";
1258
+ if (Array.isArray(value)) return "an array";
1259
+ switch (typeof value) {
1260
+ case "undefined": return "undefined";
1261
+ case "object": return "an object";
1262
+ case "number": return Number.isFinite(value) ? String(value) : "a non-finite number";
1263
+ case "string": return "a string";
1264
+ case "boolean": return "a boolean";
1265
+ default: return `a ${typeof value}`;
1266
+ }
1267
+ }
1268
+ function assertArray(value, path) {
1269
+ if (!Array.isArray(value)) throw new Error(`Invalid configuration at ${path}: expected an array, got ${describeValue(value)}.`);
1270
+ }
1271
+ /**
1272
+ * Every timeline needs a position source: from the provider settings of its
1273
+ * type, or from a `positionSource` override with a `systemName` of its own.
1274
+ * Otherwise the engine silently has no position source for it.
1275
+ *
1276
+ * Overrides are checked here so a mistake fails at resolution with its JSON
1277
+ * path, not at init or on the first switch to the timeline.
1278
+ */
1279
+ function assertTimelineProviderSettings(configuration, importer) {
1280
+ const settings = configuration.timelineProviderSettings ?? {};
1281
+ for (const [type, typeSettings] of Object.entries(settings)) if (isObject(typeSettings) && isObject(typeSettings.positionSource)) assertNoVideoOptions(typeSettings.positionSource, typeSettings.positionSource.systemName, `timelineProviderSettings.${type}.positionSource`);
1282
+ configuration.timelines.forEach((timeline, index) => {
1283
+ const path = `timelines[${index}]`;
1284
+ const { type } = timeline;
1285
+ const typeSettings = Object.hasOwn(settings, type) && isObject(settings[type]) ? settings[type] : void 0;
1286
+ assertProviderOverride(timeline.positionSource, `${path}.positionSource`, "position source", importer);
1287
+ assertProviderOverride(timeline.containerProvider, `${path}.containerProvider`, "container provider", importer);
1288
+ if (isObject(timeline.positionSource)) assertNoVideoOptions(timeline.positionSource, effectivePositionSource(timeline, typeSettings)?.systemName, `${path}.positionSource`);
1289
+ if (!typeSettings && !isString(timeline.positionSource?.systemName)) throw new Error(`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.`);
1290
+ if (isDefined(timeline.positionSource)) assertMergedProviderSettings(effectivePositionSource(timeline, typeSettings), `${path}.positionSource`, `timelineProviderSettings.${type}.positionSource`, "position source");
1291
+ if (isDefined(timeline.containerProvider)) assertMergedProviderSettings(effectiveContainerProvider(timeline, typeSettings), `${path}.containerProvider`, `timelineProviderSettings.${type}.container`, "container provider");
1292
+ });
1293
+ }
1294
+ /**
1295
+ * True when there are timelines and every one names its own position source,
1296
+ * so the configuration needs no `timelineProviderSettings`.
1297
+ */
1298
+ function everyTimelineHasOwnPositionSource(timelines) {
1299
+ return Array.isArray(timelines) && timelines.length > 0 && timelines.every((timeline) => isObject(timeline) && isObject(timeline.positionSource) && isString(timeline.positionSource.systemName));
1300
+ }
1301
+ /**
1302
+ * Settings that the built-in providers cannot work without. They are checked
1303
+ * for timelines that override their provider settings, after the merge.
1304
+ */
1305
+ const REQUIRED_PROVIDER_SETTINGS = {
1306
+ ScrollPositionSource: ["selector"],
1307
+ VideoPositionSource: ["selector", "sources"],
1308
+ DomContainerProvider: ["selector"]
1309
+ };
1310
+ /**
1311
+ * VideoPositionSource took video.js player options under `options` until
1312
+ * 4.0.0 removed video.js. Other position sources may still take an
1313
+ * `options` key, so only the effective system name `VideoPositionSource` is
1314
+ * checked.
1315
+ *
1316
+ * @param positionSource - The settings object as written in the configuration
1317
+ * @param systemName - The effective system name (inherited for overrides without one)
1318
+ * @param path - JSON path of `positionSource`
1319
+ * @throws When a VideoPositionSource has an `options` key
1320
+ */
1321
+ function assertNoVideoOptions(positionSource, systemName, path) {
1322
+ if (systemName !== "VideoPositionSource" || !Object.hasOwn(positionSource, "options")) return;
1323
+ throw new Error(`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.`);
1324
+ }
1325
+ /**
1326
+ * Checks the shape of a per-timeline provider override and that its
1327
+ * `systemName`, when given, is provided by the importer.
1328
+ */
1329
+ function assertProviderOverride(override, path, kind, importer) {
1330
+ if (!isDefined(override)) return;
1331
+ if (!isObject(override)) throw new Error(`Invalid configuration at ${path}: expected an object with ${kind} settings, got ${describeValue(override)}.`);
1332
+ const { systemName } = override;
1333
+ if (!isDefined(systemName)) return;
1334
+ if (!isString(systemName)) throw new Error(`Invalid configuration at ${path}.systemName: expected the name of a ${kind} class, got ${describeValue(systemName)}.`);
1335
+ let entry;
1336
+ try {
1337
+ entry = importer.import(systemName)?.[systemName];
1338
+ } catch {
1339
+ entry = void 0;
1340
+ }
1341
+ if (!isFunction(entry)) {
1342
+ const didYouMean = formatDidYouMean(findClosestNames(systemName, getImporterNames(importer, "getProviderNames")));
1343
+ throw new Error(`Unknown ${kind} '${systemName}' at ${path}.systemName. ${didYouMean || `Check the spelling, or make sure the ${kind} is available from the resource importer.`}`);
1344
+ }
1345
+ const isListedAs = (getterName) => getImporterNames(importer, getterName).includes(systemName);
1346
+ if (!isListedAs("getProviderNames") && (isListedAs("getOperationNames") || isListedAs("getControllerNames"))) throw new Error(`Unknown ${kind} '${systemName}' at ${path}.systemName: '${systemName}' is an operation or controller, not a ${kind}.`);
1347
+ }
1348
+ /**
1349
+ * Checks the settings a timeline ends up with once its override is merged
1350
+ * over the settings of its type: a `systemName`, and the settings the
1351
+ * built-in provider of that name requires.
1352
+ */
1353
+ function assertMergedProviderSettings(merged, path, typePath, kind) {
1354
+ const systemName = merged?.systemName;
1355
+ if (!merged || !isString(systemName)) throw new Error(`Missing systemName at ${path}.systemName: there are no settings at ${typePath} to merge the override over, so it has to name the ${kind} class.`);
1356
+ const required = Object.hasOwn(REQUIRED_PROVIDER_SETTINGS, systemName) ? REQUIRED_PROVIDER_SETTINGS[systemName] : [];
1357
+ for (const key of required) if (!hasRequiredSetting(merged, key)) throw new Error(`Missing setting at ${path}.${key}: '${systemName}' requires '${key}', and neither ${path} nor ${typePath} provides it.`);
1358
+ }
1359
+ function hasRequiredSetting(settings, key) {
1360
+ if (key === "sources") return isNonEmptyArray(settings.sources);
1361
+ const value = settings[key];
1362
+ return isString(value) ? value.length > 0 : isDefined(value);
1363
+ }
1364
+ function isNonEmptyArray(value) {
1365
+ return Array.isArray(value) && value.length > 0;
1366
+ }
1367
+ function createActionsLookup(actions) {
1368
+ const lookup = Object.create(null);
1369
+ const paths = Object.create(null);
1370
+ for (const [action, path] of actions) {
1371
+ if (Object.hasOwn(lookup, action.name)) throw new Error(`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.`);
1372
+ lookup[action.name] = action;
1373
+ paths[action.name] = path;
1374
+ }
1375
+ return lookup;
1376
+ }
1377
+ /**
1378
+ * Creates the event actions without registering them.
1379
+ */
1380
+ function resolveEventActions(eventActionConfigurations, importer, eventbus, warn) {
1381
+ return eventActionConfigurations.map((config, index) => resolveActionConfiguration(config, importer, `eventActions[${index}]`, warn)).map((config, index) => {
1382
+ const { eventName, eventTopic } = eventActionConfigurations[index];
1383
+ return {
1384
+ action: new Action(config.name, config.startOperations, eventbus),
1385
+ eventName,
1386
+ eventTopic
1387
+ };
1388
+ });
1389
+ }
1390
+ function resolveTimelines(timelines, importer, eventbus, warn) {
1391
+ assertArray(timelines, "timelines");
1392
+ return timelines.map((config, timelineIndex) => {
1393
+ const path = `timelines[${timelineIndex}]`;
1394
+ assertArray(config.timelineActions, `${path}.timelineActions`);
1395
+ return {
1396
+ ...config,
1397
+ ...isDefined(config.positionSource) && { positionSource: deepCopy(config.positionSource) },
1398
+ ...isDefined(config.containerProvider) && { containerProvider: deepCopy(config.containerProvider) },
1399
+ timelineActions: config.timelineActions.map((actionConfig, index) => resolveTimelineAction(importer, eventbus, actionConfig, `${path}.timelineActions[${index}]`, warn))
1400
+ };
1401
+ });
1402
+ }
1403
+ function resolveOperation(importer, operationConfig, path) {
1404
+ const { systemName } = operationConfig;
1405
+ let instance;
1406
+ try {
1407
+ instance = importer.import(systemName)?.[systemName];
1408
+ } catch (error) {
1409
+ throw new Error(createUnknownOperationMessage(importer, systemName, path), { cause: error });
1410
+ }
1411
+ if (!isFunction(instance)) throw new Error(createUnknownOperationMessage(importer, systemName, path));
1412
+ const notAnOperation = describeNonOperation(importer, systemName, instance);
1413
+ if (notAnOperation) throw new Error(`Unknown operation '${systemName}' at ${path}.systemName. ${notAnOperation}`);
1414
+ return {
1415
+ id: operationConfig.id,
1416
+ systemName,
1417
+ operationData: deepCopy(operationConfig.operationData) ?? {},
1418
+ instance
1419
+ };
1420
+ }
1421
+ /**
1422
+ * Returns why the given importer export is not an operation, or `undefined`
1423
+ * when it may be one.
1424
+ */
1425
+ function describeNonOperation(importer, systemName, instance) {
1426
+ const isListedAs = (getterName) => getImporterNames(importer, getterName).includes(systemName);
1427
+ if (!isListedAs("getOperationNames")) {
1428
+ if (isListedAs("getControllerNames")) return `'${systemName}' is a controller, not an operation: attach it with the addControllerToElement operation.`;
1429
+ if (isListedAs("getProviderNames")) return `'${systemName}' is a timeline provider export, not an operation: configure it in timelineProviderSettings.`;
1430
+ if (isListedAs("getFunctionNames")) return `'${systemName}' is a custom function, not an operation: call it with the customFunction operation ({systemName: '${systemName}'}).`;
1431
+ }
1432
+ if (isClass(instance)) return `'${systemName}' is a class, not an operation function.`;
1433
+ }
1434
+ function isClass(value) {
1435
+ return /^class[\s{]/.test(Function.prototype.toString.call(value));
1436
+ }
1437
+ function resolveOperations(importer, operationConfigs, path, warn) {
1438
+ assertArray(operationConfigs, path);
1439
+ const resolved = operationConfigs.map((operationConfig, index) => resolveOperation(importer, operationConfig, `${path}[${index}]`));
1440
+ for (const problem of findFlowControlProblems(resolved.map((operation) => operation.systemName))) warn({
1441
+ path: `${path}[${problem.index}].systemName`,
1442
+ message: `${problem.message} This will be a configuration error in the next major version.`
1443
+ });
1444
+ return resolved;
1445
+ }
1446
+ function createUnknownOperationMessage(importer, systemName, path) {
1447
+ const message = `Unknown operation '${systemName}' at ${path}.systemName.`;
1448
+ const knownNames = getImporterNames(importer, "getOperationNames");
1449
+ const didYouMean = formatDidYouMean(findClosestNames(String(systemName), knownNames));
1450
+ if (didYouMean) return `${message} ${didYouMean}`;
1451
+ return `${message} Check the spelling, or make sure the operation is available from the resource importer.`;
1452
+ }
1453
+ /**
1454
+ * Calls one of the optional `IResourceImporter` name getters, an empty list when
1455
+ * the importer does not have it.
1456
+ */
1457
+ function getImporterNames(importer, getterName) {
1458
+ const getter = importer[getterName];
1459
+ if (isFunction(getter)) {
1460
+ const names = getter.call(importer);
1461
+ return Array.isArray(names) ? names : [];
1462
+ }
1463
+ return [];
1464
+ }
1465
+ function resolveActionConfiguration(config, importer, path, warn) {
1466
+ return {
1467
+ id: config.id,
1468
+ name: config.name,
1469
+ startOperations: resolveOperations(importer, config.startOperations, `${path}.startOperations`, warn)
1470
+ };
1471
+ }
1472
+ function resolveEndableActionConfiguration(config, importer, path, warn) {
1473
+ return {
1474
+ ...resolveActionConfiguration(config, importer, path, warn),
1475
+ endOperations: resolveOperations(importer, config.endOperations, `${path}.endOperations`, warn)
1476
+ };
1477
+ }
1478
+ /**
1479
+ * Validates a timeline action duration: `start` is a number >= 0, `end` is
1480
+ * optional and, when given, not lower than `start`. An `end` of -1 marks an
1481
+ * open end, like a missing `end`.
1482
+ */
1483
+ function resolveDuration(duration, path) {
1484
+ if (!isObject(duration)) throw new Error(`Invalid configuration at ${path}: expected {start: number, end?: number}, got ${describeValue(duration)}.`);
1485
+ const { start, end } = duration;
1486
+ if (typeof start !== "number" || !Number.isFinite(start) || start < 0) throw new Error(`Invalid configuration at ${path}.start: expected a number >= 0, got ${describeValue(start)}.`);
1487
+ if (!isDefined(end) || end === -1) return {
1488
+ start,
1489
+ end: -1
1490
+ };
1491
+ if (typeof end !== "number" || !Number.isFinite(end)) throw new Error(`Invalid configuration at ${path}.end: expected a number or no end, got ${describeValue(end)}.`);
1492
+ if (end < start) throw new Error(`Invalid configuration at ${path}.end: end (${end}) must not be lower than start (${start}).`);
1493
+ return {
1494
+ start,
1495
+ end
1496
+ };
1497
+ }
1498
+ function resolveTimelineAction(importer, eventbus, actionConfiguration, path, warn) {
1499
+ const duration = resolveDuration(actionConfiguration.duration, `${path}.duration`);
1500
+ const { id, name, endOperations, startOperations } = resolveEndableActionConfiguration(actionConfiguration, importer, path, warn);
1501
+ const action = new TimelineAction(name, startOperations, endOperations, duration, eventbus);
1502
+ action.id = id;
1503
+ return action;
1504
+ }
1505
+ function resolveActions(actionConfigurations, importer, eventbus, path, warn) {
1506
+ assertArray(actionConfigurations, path);
1507
+ return actionConfigurations.map((config, index) => {
1508
+ return resolveEndableActionConfiguration(config, importer, `${path}[${index}]`, warn);
1509
+ }).map((resolvedConfig) => {
1510
+ const { name, endOperations, startOperations } = resolvedConfig;
1511
+ const action = new EndableAction(name, startOperations, endOperations, eventbus);
1512
+ action.id = resolvedConfig.id;
1513
+ return action;
1514
+ });
1515
+ }
1516
+ /**
1517
+ * Walks arrays and plain data objects only. Class instances, jQuery objects and
1518
+ * other non-plain values (from the TypeScript API) are kept as they are.
1519
+ */
1520
+ function resolvePlaceholders(configFragment, rootConfig, importer, pass, imported, path) {
1521
+ if (!isDefined(configFragment) || imported.has(configFragment)) return;
1522
+ if (Array.isArray(configFragment)) configFragment.forEach((_item, index) => {
1523
+ resolvePlaceholder(index, configFragment, rootConfig, importer, pass, imported, `${path}[${index}]`);
1524
+ });
1525
+ else if (isPlainObject(configFragment)) Object.keys(configFragment).forEach((key) => {
1526
+ resolvePlaceholder(key, configFragment, rootConfig, importer, pass, imported, path ? `${path}.${key}` : key);
1527
+ });
1528
+ }
1529
+ function resolvePlaceholder(key, configFragment, rootConfig, importer, pass, imported, path) {
1530
+ const configValue = configFragment[key];
1531
+ if (isString(configValue)) {
1532
+ if (pass === "config") {
1533
+ if (configValue.startsWith("config:")) configFragment[key] = resolveConfigPlaceholder(configValue, rootConfig, path);
1534
+ } else if (configValue.startsWith("template:")) configFragment[key] = importPlaceholder(importer, configValue.substring(9, configValue.length), configValue, path);
1535
+ else if (configValue.startsWith("json:")) {
1536
+ const jsonKey = configValue.substring(5, configValue.length);
1537
+ const json = deepCopy(importPlaceholder(importer, jsonKey, configValue, path));
1538
+ configFragment[key] = json;
1539
+ if (isPlainObject(json) || Array.isArray(json)) imported.add(json);
1540
+ }
1541
+ } else if (isPlainObject(configValue) || Array.isArray(configValue)) resolvePlaceholders(configValue, rootConfig, importer, pass, imported, path);
1542
+ }
1543
+ /**
1544
+ * Imports the value for a `template:` or `json:` placeholder. An importer that
1545
+ * throws for an unknown name gets its error wrapped, and an importer that returns
1546
+ * a record without an entry for the name is reported as an unknown name. Both
1547
+ * messages name the placeholder and its JSON path. An entry that is present but
1548
+ * `undefined` is accepted.
1549
+ */
1550
+ function importPlaceholder(importer, name, placeholder, path) {
1551
+ let record;
1552
+ try {
1553
+ record = importer.import(name);
1554
+ } catch (error) {
1555
+ const reason = error instanceof Error ? error.message : String(error);
1556
+ throw new Error(`Unable to resolve placeholder '${placeholder}' at ${path}: ${reason}`, { cause: error });
1557
+ }
1558
+ if (!isObject(record) || !Object.hasOwn(record, name)) throw new Error(`Unable to resolve placeholder '${placeholder}' at ${path}: unknown name '${name}'.`);
1559
+ return record[name];
1560
+ }
1561
+ /**
1562
+ * Resolves a `config:` placeholder against the root configuration. When the target
1563
+ * is itself a `config:` placeholder, that one is followed as well.
1564
+ *
1565
+ * @throws When the property chain cannot be resolved or yields `undefined`.
1566
+ */
1567
+ function resolveConfigPlaceholder(placeholder, rootConfig, path, visited = /* @__PURE__ */ new Set()) {
1568
+ if (visited.has(placeholder)) throw new Error(`Circular config: placeholder '${placeholder}' at ${path} (chain: ${[...visited, placeholder].join(" -> ")})`);
1569
+ visited.add(placeholder);
1570
+ const configProperty = placeholder.substring(7, placeholder.length);
1571
+ let value;
1572
+ try {
1573
+ value = resolvePropertyChain(configProperty, rootConfig);
1574
+ } catch (error) {
1575
+ const reason = error instanceof Error ? error.message : String(error);
1576
+ throw new Error(`Unable to resolve placeholder '${placeholder}' at ${path}: ${reason}`, { cause: error });
1577
+ }
1578
+ if (value === void 0) throw new Error(`Unable to resolve placeholder '${placeholder}' at ${path}: the configuration has no value at '${configProperty}'.`);
1579
+ if (isString(value) && value.startsWith("config:")) return resolveConfigPlaceholder(value, rootConfig, path, visited);
1580
+ return value;
1581
+ }
1582
+
1583
+ // src/eventbus/actionregistry-eventbus-listener.ts
1584
+ /**
1585
+ * The `IEventbusListener` first registers a number of actions that are then
1586
+ * executed when the specified event is broadcast.
1587
+ */
1588
+ var ActionRegistryEventbusListener = class {
1589
+ _actionRegistry = /* @__PURE__ */ new Map();
1590
+ registerAction(action, eventName, eventTopic) {
1591
+ if (eventTopic?.length) eventName = `${eventName}:${eventTopic}`;
1592
+ if (!this._actionRegistry.has(eventName)) this._actionRegistry.set(eventName, []);
1593
+ this._actionRegistry.get(eventName)?.push(action);
1594
+ }
1595
+ /**
1596
+ * Starts every action registered for the event.
1597
+ *
1598
+ * @returns A promise that settles once all started actions have finished,
1599
+ * or undefined when no action is registered. It rejects with the failing
1600
+ * action's error, or with an AggregateError when several fail. The Eventbus
1601
+ * watches this promise and reports a rejection like any handler error.
1602
+ */
1603
+ handleEvent(eventName, eventTopic, args) {
1604
+ if (eventTopic) eventName = `${eventName}:${eventTopic}`;
1605
+ const actions = this._actionRegistry.get(eventName);
1606
+ if (!actions?.length) return;
1607
+ const runs = actions.map((action) => action.start({ eventArgs: Array.isArray(args) ? [...args] : args }));
1608
+ return Promise.allSettled(runs).then((results) => {
1609
+ const errors = results.filter((result) => result.status === "rejected").map((result) => result.reason);
1610
+ if (errors.length === 1) throw errors[0];
1611
+ if (errors.length > 1) throw new AggregateError(errors, `${errors.length} event actions failed for '${eventName}'`);
1612
+ });
1613
+ }
1614
+ };
1615
+
1616
+ // src/eventbus/eventbus.ts
1617
+ /**
1618
+ * Maps each once() decorator to the handler it wraps, so off() can remove a
1619
+ * once() registration by the original function.
1620
+ */
1621
+ const onceOriginals = /* @__PURE__ */ new WeakMap();
1622
+ /**
1623
+ * Central event bus for pub/sub communication and synchronous request/response queries.
1624
+ *
1625
+ * The eventbus supports:
1626
+ * - **Pub/Sub**: `on()`, `once()`, `off()`, `broadcast()`, `broadcastForTopic()`
1627
+ * - **Request/Response**: `onRequest()`, `request()`, `requestForTopic()` for synchronous queries
1628
+ * - **Interceptors**: Transform event arguments before handlers receive them
1629
+ * - **Listeners**: Global event observers for logging/debugging
1630
+ *
1631
+ * @example Pub/Sub pattern
1632
+ * ```ts
1633
+ * const remover = eventbus.on('timeline-play', () => console.log('Playing'));
1634
+ * eventbus.broadcast('timeline-play', []);
1635
+ * remover(); // Unsubscribe
1636
+ * ```
1637
+ *
1638
+ * @example Request/Response pattern
1639
+ * ```ts
1640
+ * eventbus.onRequest('request-instance', (name) => new MyClass(name));
1641
+ * const instance = eventbus.request<MyClass>('request-instance', 'test');
1642
+ * ```
1643
+ *
1644
+ * Broadcasts isolate errors: a handler, listener or interceptor that throws, or
1645
+ * returns a promise that rejects, is reported and the others still run. Request
1646
+ * responders are not isolated; their errors reach the requester.
1647
+ *
1648
+ * @example Observing handler errors
1649
+ * ```ts
1650
+ * const eventbus = new Eventbus({
1651
+ * onHandlerError: (error, {eventName, eventTopic, source}) =>
1652
+ * myLogger.warn(`${source} failed for ${eventName}`, error),
1653
+ * });
1654
+ * ```
1655
+ */
1656
+ var Eventbus = class {
1657
+ eventHandlers = /* @__PURE__ */ new Map();
1658
+ eventInterceptors = /* @__PURE__ */ new Map();
1659
+ eventListeners = [];
1660
+ requestResponders = /* @__PURE__ */ new Map();
1661
+ onHandlerError;
1662
+ /**
1663
+ * @param options - Optional settings. `onHandlerError` observes errors raised
1664
+ * by handlers, listeners and interceptors during a broadcast. It survives
1665
+ * {@link Eventbus.clear}.
1666
+ */
1667
+ constructor(options) {
1668
+ this.onHandlerError = options?.onHandlerError;
1669
+ this.clear();
1670
+ }
1671
+ /**
1672
+ * Clears all handlers, listeners, interceptors, and request responders.
1673
+ */
1674
+ clear() {
1675
+ this.eventHandlers = /* @__PURE__ */ new Map();
1676
+ this.eventListeners = [];
1677
+ this.eventInterceptors = /* @__PURE__ */ new Map();
1678
+ this.requestResponders = /* @__PURE__ */ new Map();
1679
+ }
1680
+ _getEventInterceptors(eventName, eventTopic) {
1681
+ if (eventTopic) eventName = `${eventName}:${eventTopic}`;
1682
+ if (!this.eventInterceptors.has(eventName)) this.eventInterceptors.set(eventName, []);
1683
+ return this.eventInterceptors.get(eventName);
1684
+ }
1685
+ _getEventHandlers(eventName, eventTopic) {
1686
+ if (eventTopic) eventName = `${eventName}:${eventTopic}`;
1687
+ if (!this.eventHandlers.has(eventName)) this.eventHandlers.set(eventName, []);
1688
+ return this.eventHandlers.get(eventName);
1689
+ }
1690
+ on(eventName, eventHandler, eventTopic) {
1691
+ this._getEventHandlers(eventName, eventTopic).push(eventHandler);
1692
+ return () => {
1693
+ this.off(eventName, eventHandler, eventTopic);
1694
+ };
1695
+ }
1696
+ once(eventName, eventHandler, eventTopic) {
1697
+ let called = false;
1698
+ const eventHandlerDecorator = (...args) => {
1699
+ if (called) return;
1700
+ called = true;
1701
+ this.off(eventName, eventHandlerDecorator, eventTopic);
1702
+ return eventHandler(...args);
1703
+ };
1704
+ onceOriginals.set(eventHandlerDecorator, eventHandler);
1705
+ this.on(eventName, eventHandlerDecorator, eventTopic);
1706
+ return () => {
1707
+ this.off(eventName, eventHandlerDecorator, eventTopic);
1708
+ };
1709
+ }
1710
+ /**
1711
+ * Removes one registration of the handler. A handler registered with
1712
+ * {@link Eventbus.once} can be removed by passing the original function. An
1713
+ * exact registration (through `on()`) is preferred over a `once()` one.
1714
+ */
1715
+ off(eventName, eventHandler, eventTopic) {
1716
+ const handlers = this._getEventHandlers(eventName, eventTopic);
1717
+ let idx = handlers.indexOf(eventHandler);
1718
+ if (idx === -1) idx = handlers.findIndex((h) => onceOriginals.get(h) === eventHandler);
1719
+ if (idx > -1) handlers.splice(idx, 1);
1720
+ }
1721
+ broadcast(eventName, args) {
1722
+ this._callHandlers(eventName, void 0, args);
1723
+ }
1724
+ broadcastForTopic(eventName, eventTopic, args) {
1725
+ this._callHandlers(eventName, eventTopic, args);
1726
+ }
1727
+ registerEventlistener(eventbusListener) {
1728
+ this.eventListeners.push(eventbusListener);
1729
+ return () => {
1730
+ const index = this.eventListeners.indexOf(eventbusListener);
1731
+ if (index > -1) this.eventListeners.splice(index, 1);
1732
+ };
1733
+ }
1734
+ registerInterceptor(eventName, interceptor, eventTopic) {
1735
+ const interceptors = this._getEventInterceptors(eventName, eventTopic);
1736
+ interceptors.push(interceptor);
1737
+ return () => {
1738
+ const index = interceptors.indexOf(interceptor);
1739
+ if (index > -1) interceptors.splice(index, 1);
1740
+ };
1741
+ }
1742
+ onRequest(eventName, responder, eventTopic) {
1743
+ const responders = this._getRequestResponders(eventName, eventTopic);
1744
+ responders.push(responder);
1745
+ return () => {
1746
+ const index = responders.indexOf(responder);
1747
+ if (index > -1) responders.splice(index, 1);
1748
+ };
1749
+ }
1750
+ request(eventName, ...args) {
1751
+ return this._callResponder(eventName, void 0, args);
1752
+ }
1753
+ requestForTopic(eventName, eventTopic, ...args) {
1754
+ return this._callResponder(eventName, eventTopic, args);
1755
+ }
1756
+ _getRequestResponders(eventName, eventTopic) {
1757
+ if (eventTopic) eventName = `${eventName}:${eventTopic}`;
1758
+ if (!this.requestResponders.has(eventName)) this.requestResponders.set(eventName, []);
1759
+ return this.requestResponders.get(eventName);
1760
+ }
1761
+ _callResponder(eventName, eventTopic, args) {
1762
+ const responders = this._getRequestResponders(eventName, eventTopic);
1763
+ if (responders.length === 0) return;
1764
+ return responders[0](...args);
1765
+ }
1766
+ _callHandlers(eventName, eventTopic, args = []) {
1767
+ const handlers = this._getEventHandlers(eventName, eventTopic);
1768
+ if (handlers) {
1769
+ const interceptors = this._getEventInterceptors(eventName, eventTopic).slice();
1770
+ const listeners = this.eventListeners.slice();
1771
+ const snapshot = handlers.slice();
1772
+ for (const interceptor of interceptors) try {
1773
+ args = interceptor.intercept(args);
1774
+ } catch (error) {
1775
+ this._reportError(error, eventName, eventTopic, "interceptor");
1776
+ }
1777
+ for (const listener of listeners) try {
1778
+ this._watchResult(listener.handleEvent(eventName, eventTopic, args), eventName, eventTopic, "listener");
1779
+ } catch (error) {
1780
+ this._reportError(error, eventName, eventTopic, "listener");
1781
+ }
1782
+ const hasArgs = args?.length > 0;
1783
+ for (const handler of snapshot) {
1784
+ if (!this._getEventHandlers(eventName, eventTopic).includes(handler)) continue;
1785
+ try {
1786
+ this._watchResult(hasArgs ? handler(...args) : handler(), eventName, eventTopic, "handler");
1787
+ } catch (error) {
1788
+ this._reportError(error, eventName, eventTopic, "handler");
1789
+ }
1790
+ }
1791
+ }
1792
+ }
1793
+ /**
1794
+ * Handlers are typed to return void, but async ones return a promise that
1795
+ * nobody awaits. Report its rejection like a synchronous throw.
1796
+ */
1797
+ _watchResult(result, eventName, eventTopic, source) {
1798
+ if (result && isPromise(result)) result.then(void 0, (error) => this._reportError(error, eventName, eventTopic, source));
1799
+ }
1800
+ /**
1801
+ * Reports an error a component caught, the same way as a failing handler:
1802
+ * `console.error` naming the source, then the `onHandlerError` option with
1803
+ * source `'reported'`. Never throws.
1804
+ *
1805
+ * @param error - The caught error
1806
+ * @param context - The reporting component and, if any, the event it was
1807
+ * handling
1808
+ */
1809
+ reportError(error, context) {
1810
+ const { source, eventName } = context;
1811
+ const event = eventName ? ` for "${eventName}"` : "";
1812
+ console.error(`Error reported by ${source}${event}:`, error);
1813
+ this._notifyErrorHook(error, {
1814
+ eventName: eventName ?? "",
1815
+ eventTopic: void 0,
1816
+ source: "reported",
1817
+ reporter: source
1818
+ }, `${source}${event}`);
1819
+ }
1820
+ /**
1821
+ * Logs the error with the event name and topic, never the event arguments
1822
+ * (they can carry configuration or user data), then passes it to the
1823
+ * `onHandlerError` option.
1824
+ */
1825
+ _reportError(error, eventName, eventTopic, source) {
1826
+ const topic = eventTopic ? ` (topic "${eventTopic}")` : "";
1827
+ console.error(`Error in eventbus ${source} for "${eventName}"${topic}:`, error);
1828
+ this._notifyErrorHook(error, {
1829
+ eventName,
1830
+ eventTopic,
1831
+ source
1832
+ }, `"${eventName}"${topic}`);
1833
+ }
1834
+ _notifyErrorHook(error, context, description) {
1835
+ if (!this.onHandlerError) return;
1836
+ try {
1837
+ this.onHandlerError(error, context);
1838
+ } catch (hookError) {
1839
+ console.error(`Error in eventbus onHandlerError for ${description}:`, hookError);
1840
+ }
1841
+ }
1842
+ };
1843
+
1844
+ // src/controllers/metadata/dom-event-listener-controller.ts
1845
+ function DOMEventListenerController() {
1846
+ return {
1847
+ description: `This controller attaches to the given selected element and adds a DOM event listener for the specified event name that
1848
+ executes the given actions with the given operation data.
1849
+
1850
+ By default the \`start\` operations of the specified actions are executed. To execute the \`end\` operations instead,
1851
+ prefix the action name with \`end:\`.
1852
+
1853
+ The actions receive a copy of \`actionOperationData\` plus \`eventTarget\` (the event's target) and, for key events,
1854
+ \`eventKey\` (the \`KeyboardEvent.key\`). They run in order, each receiving the operation data the previous one
1855
+ returned. When an action fails, the
1856
+ remaining actions are skipped and the failure is reported through the eventbus's \`reportError\` (an error naming
1857
+ this controller, the action and the DOM event, with the original error as \`cause\`), or logged with
1858
+ \`console.error\` when the eventbus has no \`reportError\`.`,
1859
+ dependentProperties: ["selectedElement"],
1860
+ properties: {
1861
+ eventName: {
1862
+ type: "ParameterType:eventName",
1863
+ required: true
1864
+ },
1865
+ actions: {
1866
+ type: "ParameterType:array",
1867
+ itemType: "ParameterType:string"
1868
+ },
1869
+ actionOperationData: { type: "ParameterType:object" }
1870
+ }
1871
+ };
1872
+ }
1873
+
1874
+ // src/controllers/metadata/keyboard-controller.ts
1875
+ function KeyboardController() {
1876
+ return {
1877
+ description: `This controller runs the given actions when one of the given keys is pressed.
1878
+
1879
+ By default the \`start\` operations of the specified actions are executed. To execute the \`end\` operations instead,
1880
+ prefix the action name with \`end:\`.
1881
+
1882
+ The actions receive a copy of \`actionOperationData\` plus \`eventTarget\` (the focused element, or the body when
1883
+ nothing has focus) and \`eventKey\` (the \`KeyboardEvent.key\`). They run in order, each receiving the operation data
1884
+ the previous one returned. When an action fails, the remaining actions are skipped and the failure is reported
1885
+ through the eventbus's \`reportError\`, or logged with \`console.error\` when the eventbus has no \`reportError\`.
1886
+
1887
+ With \`scope: 'document'\` (the default) the keys work while the focus is inside the engine root, or while nothing
1888
+ has focus. With \`scope: 'element'\` they only work while the focus is inside the selected element. Presses in
1889
+ \`input\`, \`select\`, \`textarea\` and contenteditable elements are ignored, so typing keeps working. A handled press
1890
+ has its default action prevented (no scrolling for arrow keys and space); a held key runs the actions once, not
1891
+ again for every key repeat.
1892
+
1893
+ When the keys include the play toggle hotkey of the engine (space by default), or a key that the engine's
1894
+ KeyboardStepSource binds (the arrow keys, \`shift+left\`/\`shift+right\`, \`home\` and \`end\`), the controller wins: a
1895
+ press it handles runs its actions and does not toggle playback or step the timeline. A press it ignores (for
1896
+ example outside the selected element with \`scope: 'element'\`) still does.
1897
+
1898
+ The keys are bound in the hotkeys-js \`'all'\` scope, so they work whatever scope a KeyboardStepSource sets. The
1899
+ hotkeys-js global \`filter\` still applies. Detaching removes only this controller's handler.`,
1900
+ dependentProperties: ["selectedElement"],
1901
+ properties: {
1902
+ keys: {
1903
+ type: "ParameterType:string",
1904
+ required: true
1905
+ },
1906
+ actions: {
1907
+ type: "ParameterType:array",
1908
+ itemType: "ParameterType:string"
1909
+ },
1910
+ actionOperationData: { type: "ParameterType:object" },
1911
+ scope: { type: [{ value: "document" }, { value: "element" }] }
1912
+ }
1913
+ };
1914
+ }
1915
+
1916
+ // src/controllers/metadata/label-controller.ts
1917
+ function LabelController() {
1918
+ return {
1919
+ description: `This controller attaches to the given selected element and renders the text
1920
+ associated with the given translation key.
1921
+
1922
+ Translations may contain simple inline markup. They are passed through
1923
+ \`sanitizeHtml\` before insertion, so \`<br>\`, \`<strong>\`, \`<em>\`,
1924
+ \`<span>\` and http(s)/mailto/relative links render, while scripts, event
1925
+ handlers, \`javascript:\` URLs, images, iframes and SVG are removed.
1926
+
1927
+ The controller listens for the \`language-change\` event and re-renders the text
1928
+ with the new language after such an event.
1929
+
1930
+ Uses the rosetta-based locale system via \`request-translation\` event.`,
1931
+ dependentProperties: ["selectedElement"],
1932
+ properties: {
1933
+ translationKey: {
1934
+ type: "ParameterType:string",
1935
+ required: true
1936
+ },
1937
+ attributeName: { type: "ParameterType:string" }
1938
+ }
1939
+ };
1940
+ }
1941
+
1942
+ // src/controllers/metadata/lottie-controller.ts
1943
+ function LottieController() {
1944
+ return {
1945
+ description: `This controller renders a [lottie-web](https://github.com/airbnb/lottie-web) animation inside the given selected element.
1946
+
1947
+ The url may encode freeze and end positions like this: my-url/filename[freeze=10,end=21].json
1948
+
1949
+ lottie-web is an optional peer dependency. It is loaded with a dynamic
1950
+ \`import()\` the first time a LottieController attaches, so applications that
1951
+ never use this controller do not need it installed.`,
1952
+ properties: { url: { type: "ParameterType:url" } }
1953
+ };
1954
+ }
1955
+
1956
+ // src/controllers/metadata/mutation-observer-controller.ts
1957
+ function MutationObserverController() {
1958
+ return {
1959
+ description: `Controller that observes DOM mutations on a selected element and broadcasts events.
1960
+
1961
+ This controller creates a MutationObserver to monitor DOM changes (attributes, child nodes,
1962
+ text content) on a specified element. All detected mutations are broadcasted through the
1963
+ Eligius eventbus, enabling reactive behavior in response to DOM changes.
1964
+
1965
+ The controller follows the standard Eligius lifecycle:
1966
+ - init(): Store configuration metadata
1967
+ - attach(): Create and start the MutationObserver
1968
+ - detach(): Disconnect the observer and clean up resources`,
1969
+ dependentProperties: ["selectedElement"],
1970
+ properties: {
1971
+ observeAttributes: { type: "ParameterType:boolean" },
1972
+ observeChildList: { type: "ParameterType:boolean" },
1973
+ observeCharacterData: { type: "ParameterType:boolean" },
1974
+ observeSubtree: { type: "ParameterType:boolean" },
1975
+ attributeOldValue: { type: "ParameterType:boolean" },
1976
+ characterDataOldValue: { type: "ParameterType:boolean" },
1977
+ attributeFilter: {
1978
+ type: "ParameterType:array",
1979
+ itemType: "ParameterType:string"
1980
+ }
1981
+ }
1982
+ };
1983
+ }
1984
+
1985
+ // src/controllers/metadata/navigation-controller.ts
1986
+ function NavigationController() {
1987
+ return {
1988
+ description: `Renders a navigation menu in the selected element and keeps it in sync with
1989
+ the active navigation entry.
1990
+
1991
+ Activating a menu item (click, Enter or Space) navigates to its entry:
1992
+ - an entry with a \`timelineUri\` broadcasts \`request-timeline-uri\`
1993
+ [timelineUri, position], which the engine handles by switching timelines;
1994
+ - an entry without one broadcasts the legacy \`request-video-url\`
1995
+ [videoUrlIndex, position], which the engine does not handle.
1996
+
1997
+ With \`autoNext\`, the next entry is started when the active entry's timeline
1998
+ completes (\`timeline-complete\`) or, for legacy entries, on \`video-complete\`.
1999
+ When the engine switches to a timeline that an entry names
2000
+ (\`timeline-current-timeline-change\`), that entry becomes the active one.`,
2001
+ dependentProperties: ["selectedElement"],
2002
+ properties: { json: {
2003
+ type: "ParameterType:object",
2004
+ required: true
2005
+ } }
2006
+ };
2007
+ }
2008
+
2009
+ // src/controllers/metadata/progressbar-controller.ts
2010
+ function ProgressbarController() {
2011
+ return {
2012
+ description: `This controller renders a progressbar that displays the progress of the current timeline in the given selected element.
2013
+
2014
+ The current progress as a percentage is rendered in the given text element.`,
2015
+ dependentProperties: ["selectedElement", "textElement"]
2016
+ };
2017
+ }
2018
+
2019
+ // src/controllers/metadata/routing-controller.ts
2020
+ function RoutingController() {
2021
+ return {
2022
+ description: `Keeps the browser history in sync with the navigation entries: each entry
2023
+ gets a \`#/<id>/<position>\` URL, and back/forward navigation requests the
2024
+ entry in the URL.
2025
+
2026
+ Requests go to the engine as \`request-timeline-uri\` for entries with a
2027
+ \`timelineUri\`, and as the legacy \`request-video-url\` otherwise. Before the
2028
+ engine switches timelines (\`before-request-timeline-uri\`, or the legacy
2029
+ \`before-request-video-url\`), the current entry is saved with its position.
2030
+
2031
+ This is a work in progress, do not use this yet please....`,
2032
+ properties: { json: {
2033
+ type: "ParameterType:object",
2034
+ required: true
2035
+ } }
2036
+ };
2037
+ }
2038
+
2039
+ // src/controllers/metadata/subtitles-controller.ts
2040
+ function SubtitlesController() {
2041
+ return {
2042
+ description: `This controller shows the subtitle whose duration contains the current
2043
+ timeline position in the selected element, in the current language, and
2044
+ re-renders it after a \`language-change\` event.
2045
+
2046
+ The starting language is the locale's current language
2047
+ (\`request-current-language\`); the configured \`language\` is only used when
2048
+ nothing answers that request.
2049
+
2050
+ Subtitle texts may contain simple inline markup. They are passed through
2051
+ \`sanitizeHtml\` before insertion, so \`<br>\`, \`<i>\`, \`<em>\`,
2052
+ \`<strong>\` and \`<span>\` render, while scripts, event handlers,
2053
+ \`javascript:\` URLs, images, iframes and SVG are removed.`,
2054
+ dependentProperties: ["selectedElement"],
2055
+ properties: {
2056
+ language: { type: "ParameterType:languagecode" },
2057
+ subtitleData: { type: "ParameterType:array" }
2058
+ }
2059
+ };
2060
+ }
2061
+
2062
+ // src/controllers/metadata/index.ts
2063
+ var metadata_exports$1 = /* @__PURE__ */ __exportAll({
2064
+ DOMEventListenerController: () => DOMEventListenerController,
2065
+ KeyboardController: () => KeyboardController,
2066
+ LabelController: () => LabelController,
2067
+ LottieController: () => LottieController,
2068
+ MutationObserverController: () => MutationObserverController,
2069
+ NavigationController: () => NavigationController,
2070
+ ProgressbarController: () => ProgressbarController,
2071
+ RoutingController: () => RoutingController,
2072
+ SubtitlesController: () => SubtitlesController
2073
+ });
2074
+
2075
+ // src/operation/metadata/add-class.ts
2076
+ function addClass() {
2077
+ return {
2078
+ description: `This operation adds the specified class name to the specified selected element.`,
2079
+ category: `DOM`,
2080
+ dependentProperties: ["selectedElement"],
2081
+ properties: { className: {
2082
+ type: "ParameterType:className",
2083
+ required: true,
2084
+ erased: true
2085
+ } }
2086
+ };
2087
+ }
2088
+
2089
+ // src/operation/metadata/add-controller-to-element.ts
2090
+ function addControllerToElement() {
2091
+ return {
2092
+ description: `This operation adds the specified controller instance to the given selected element.
2093
+
2094
+ The controller is registered on the element only once \`init\` and a synchronous \`attach\`
2095
+ have succeeded. When \`attach\` returns a promise, the controller is registered before
2096
+ that promise settles (so detaching the element can still reach it) and is removed from
2097
+ the element again when the promise rejects.`,
2098
+ category: `Controller`,
2099
+ dependentProperties: ["selectedElement", "controllerInstance"]
2100
+ };
2101
+ }
2102
+
2103
+ // src/operation/metadata/add-globals-to-operation.ts
2104
+ function addGlobalsToOperation() {
2105
+ return {
2106
+ description: `This operation adds the specified global property names to the current operation data.
2107
+ It finally removes the \`globalProperties\` property from the current operation data.
2108
+
2109
+ Plain data is copied, so changing it does not change the global store. jQuery objects, DOM
2110
+ nodes, functions and class instances (such as controllers) are added by reference.`,
2111
+ category: `Data`,
2112
+ properties: { globalProperties: {
2113
+ type: "ParameterType:array",
2114
+ itemType: "ParameterType:string",
2115
+ required: true,
2116
+ erased: true
2117
+ } }
2118
+ };
2119
+ }
2120
+
2121
+ // src/operation/metadata/animate-with-class.ts
2122
+ function animateWithClass() {
2123
+ return {
2124
+ description: `This operation adds the specified class name to the specified selected element and assumes that this
2125
+ class triggers an animation on the selected element. It then waits for this animation to complete
2126
+ before it resolves.
2127
+
2128
+ The class must put the animation on the selected element itself: \`animationend\` events that bubble up
2129
+ from descendants are ignored, and with several selected elements the operation waits for all of them.
2130
+ Set \`includeDescendants\` to true for a class that only animates descendants; the operation then resolves
2131
+ on the first \`animationend\` from the element or its subtree.
2132
+
2133
+ The operation resolves immediately when the selection is empty, or when the class gives none of the
2134
+ selected elements a CSS animation (for example under \`prefers-reduced-motion: reduce\`). When an
2135
+ \`animationend\` event never arrives, for example because the element was hidden or removed while
2136
+ animating, it resolves shortly after the longest computed animation should have ended. An infinite
2137
+ animation is waited for until it is ended by an \`animationend\` event.`,
2138
+ category: `Animation`,
2139
+ dependentProperties: ["selectedElement"],
2140
+ properties: {
2141
+ className: {
2142
+ type: "ParameterType:className",
2143
+ required: true,
2144
+ erased: true
2145
+ },
2146
+ removeClass: {
2147
+ type: "ParameterType:boolean",
2148
+ erased: true
2149
+ },
2150
+ includeDescendants: {
2151
+ type: "ParameterType:boolean",
2152
+ erased: true
2153
+ }
2154
+ }
2155
+ };
2156
+ }
2157
+
2158
+ // src/operation/metadata/animate.ts
2159
+ function animate() {
2160
+ return {
2161
+ description: `This operation animates the specified selected element with the given [jQuery animation](https://api.jquery.com/animate/) properties, duration and easing.
2162
+ It resolves after the animation completes, or immediately when the selected element set is empty.`,
2163
+ category: `Animation`,
2164
+ dependentProperties: ["selectedElement"],
2165
+ properties: {
2166
+ animationEasing: {
2167
+ type: "ParameterType:string",
2168
+ erased: true
2169
+ },
2170
+ animationProperties: {
2171
+ type: "ParameterType:object",
2172
+ required: true,
2173
+ erased: true
2174
+ },
2175
+ animationDuration: {
2176
+ type: "ParameterType:number",
2177
+ required: true,
2178
+ erased: true
2179
+ }
2180
+ }
2181
+ };
2182
+ }
2183
+
2184
+ // src/operation/metadata/announce-to-screen-reader.ts
2185
+ function announceToScreenReader() {
2186
+ return {
2187
+ description: `Announces a message to screen readers using an ARIA live region.
2188
+
2189
+ The live region (\`#aria-live-region\`) is created empty on first use. The region is emptied
2190
+ and the message is written 100 milliseconds later, so that a new region
2191
+ and a message repeated verbatim are both announced. The message is removed again after 5 seconds.
2192
+ A newer announcement replaces a pending one.
2193
+
2194
+ The operation returns at once and does not wait for the message to be written.`,
2195
+ category: `Accessibility`,
2196
+ properties: {
2197
+ message: {
2198
+ type: "ParameterType:string",
2199
+ required: true,
2200
+ erased: true
2201
+ },
2202
+ priority: {
2203
+ type: [{ value: "polite" }, { value: "assertive" }],
2204
+ erased: true
2205
+ }
2206
+ }
2207
+ };
2208
+ }
2209
+
2210
+ // src/operation/metadata/break-for-each.ts
2211
+ function breakForEach() {
2212
+ return {
2213
+ description: `This operation should only be used within a loop, so between a {@link forEach} and {@link endForEach}
2214
+ operation. This operation immediately moves to the loop end index, effectively stopping the loop.
2215
+
2216
+ It can be placed inside a \`when\`/\`otherwise\`/\`endWhen\` block within the loop, to break conditionally.`,
2217
+ category: `Control Flow`
2218
+ };
2219
+ }
2220
+
2221
+ // src/operation/metadata/broadcast-event.ts
2222
+ function broadcastEvent() {
2223
+ return {
2224
+ description: `This operation broadcasts the given event through the eventbus, along with the
2225
+ event arguments and optional event topic.`,
2226
+ category: `Utility`,
2227
+ properties: {
2228
+ eventArgs: {
2229
+ type: "ParameterType:array",
2230
+ required: true,
2231
+ erased: true
2232
+ },
2233
+ eventTopic: {
2234
+ type: "ParameterType:eventTopic",
2235
+ erased: true
2236
+ },
2237
+ eventName: {
2238
+ type: "ParameterType:eventName",
2239
+ required: true,
2240
+ erased: true
2241
+ }
2242
+ }
2243
+ };
2244
+ }
2245
+
2246
+ // src/operation/metadata/calc.ts
2247
+ function calc() {
2248
+ return {
2249
+ description: `This operation calculates the given left and right hand operands using the specified operator.
2250
+
2251
+ \`left\`, \`right\` and \`operator\` may be property chains (\`$operationdata.\`, \`$globaldata.\`,
2252
+ \`$scope.\`). Only these three inputs are resolved; the rest of the operation data is left as
2253
+ it is.`,
2254
+ category: `Utility`,
2255
+ properties: {
2256
+ left: {
2257
+ type: "ParameterType:number",
2258
+ required: true,
2259
+ erased: true
2260
+ },
2261
+ right: {
2262
+ type: "ParameterType:number",
2263
+ required: true,
2264
+ erased: true
2265
+ },
2266
+ operator: {
2267
+ type: [
2268
+ { value: "+" },
2269
+ { value: "-" },
2270
+ { value: "*" },
2271
+ { value: "/" },
2272
+ { value: "%" },
2273
+ { value: "**" }
2274
+ ],
2275
+ required: true,
2276
+ erased: true
2277
+ }
2278
+ },
2279
+ outputProperties: { calculationResult: { type: "ParameterType:number" } }
2280
+ };
2281
+ }
2282
+
2283
+ // src/operation/metadata/clear-element.ts
2284
+ function clearElement() {
2285
+ return {
2286
+ description: `This operation removes all of the children from the given selected element.
2287
+
2288
+ Controllers attached to the removed children or their descendants (by \`addControllerToElement\`)
2289
+ are detached first. Controllers on the selected element itself stay attached.`,
2290
+ category: `DOM`,
2291
+ dependentProperties: ["selectedElement"]
2292
+ };
2293
+ }
2294
+
2295
+ // src/operation/metadata/clear-operation-data.ts
2296
+ function clearOperationData() {
2297
+ return {
2298
+ description: `This operation removes all of the properties on the current operation date.
2299
+ Or, if the \`properties\` property is set only removes the properties defined by that list.`,
2300
+ category: `Data`,
2301
+ properties: { properties: {
2302
+ type: "ParameterType:array",
2303
+ itemType: "ParameterType:string",
2304
+ erased: true
2305
+ } }
2306
+ };
2307
+ }
2308
+
2309
+ // src/operation/metadata/clear-storage.ts
2310
+ function clearStorage() {
2311
+ return {
2312
+ description: `Clears data from browser storage (localStorage or sessionStorage).
2313
+
2314
+ If \`key\` is provided, removes only that key. If \`key\` is omitted, clears all storage.
2315
+ A \`key\` that is present but empty, blank or not a string is rejected, so a value resolved
2316
+ from missing data never wipes the whole storage.`,
2317
+ category: `Data`,
2318
+ properties: {
2319
+ key: {
2320
+ type: "ParameterType:string",
2321
+ erased: true
2322
+ },
2323
+ storageType: {
2324
+ type: [{ value: "local" }, { value: "session" }],
2325
+ required: true,
2326
+ erased: true
2327
+ }
2328
+ }
2329
+ };
2330
+ }
2331
+
2332
+ // src/operation/metadata/compare-date.ts
2333
+ function compareDate() {
2334
+ return {
2335
+ description: `Compares two dates.
2336
+ comparison: -1 (before), 0 (equal), 1 (after)`,
2337
+ category: `Date`,
2338
+ properties: {
2339
+ date1: {
2340
+ type: "ParameterType:string|ParameterType:number|ParameterType:Date",
2341
+ required: true,
2342
+ erased: true
2343
+ },
2344
+ date2: {
2345
+ type: "ParameterType:string|ParameterType:number|ParameterType:Date",
2346
+ required: true,
2347
+ erased: true
2348
+ }
2349
+ },
2350
+ outputProperties: {
2351
+ comparison: { type: "ParameterType:number" },
2352
+ isEqual: { type: "ParameterType:boolean" },
2353
+ isBefore: { type: "ParameterType:boolean" },
2354
+ isAfter: { type: "ParameterType:boolean" }
2355
+ }
2356
+ };
2357
+ }
2358
+
2359
+ // src/operation/metadata/concatenate-strings.ts
2360
+ function concatenateStrings() {
2361
+ return {
2362
+ description: `Concatenates multiple strings with an optional separator.`,
2363
+ category: `String`,
2364
+ properties: {
2365
+ strings: {
2366
+ type: "ParameterType:array",
2367
+ itemType: "ParameterType:string",
2368
+ required: true,
2369
+ erased: true
2370
+ },
2371
+ separator: {
2372
+ type: "ParameterType:string",
2373
+ erased: true
2374
+ }
2375
+ },
2376
+ outputProperties: { result: { type: "ParameterType:string" } }
2377
+ };
2378
+ }
2379
+
2380
+ // src/operation/metadata/continue-for-each.ts
2381
+ function continueForEach() {
2382
+ return {
2383
+ description: `This operation should only be used within a loop, so between a {@link forEach} and {@link endForEach}
2384
+ operation. This operation immediately moves to the next loop index, effectively canceling the rest
2385
+ of the operations in the current iteration.
2386
+
2387
+ It can be placed inside a \`when\`/\`otherwise\`/\`endWhen\` block within the loop, to continue conditionally.`,
2388
+ category: `Control Flow`
2389
+ };
2390
+ }
2391
+
2392
+ // src/operation/metadata/create-element.ts
2393
+ function createElement() {
2394
+ return {
2395
+ description: `This operation creates the DOM element described by the given elementName and attributes and assigns
2396
+ the instance to the \`template\` property on the current operation data.
2397
+
2398
+ The element is built with DOM APIs: attribute values are set with \`.attr()\` and \`text\` is set as
2399
+ text content, so neither is parsed as HTML.
2400
+
2401
+ Values may be resolved from user data, so nothing that runs script is created: \`script\`
2402
+ elements, event handler (\`on*\`) and \`srcdoc\` attributes, and \`javascript:\` or \`vbscript:\`
2403
+ URLs in URL attributes such as \`href\`, \`src\` and \`formaction\` are refused.`,
2404
+ category: `DOM`,
2405
+ properties: {
2406
+ elementName: {
2407
+ type: "ParameterType:htmlElementName",
2408
+ required: true,
2409
+ erased: true
2410
+ },
2411
+ text: {
2412
+ type: "ParameterType:string",
2413
+ erased: true
2414
+ },
2415
+ attributes: {
2416
+ type: "ParameterType:object",
2417
+ erased: true
2418
+ }
2419
+ },
2420
+ outputProperties: { template: { type: "ParameterType:object" } }
2421
+ };
2422
+ }
2423
+
2424
+ // src/operation/metadata/custom-function.ts
2425
+ function customFunction() {
2426
+ return {
2427
+ description: `This operation retrieves a custom function defined by the given system name
2428
+ and invokes it with the current operation data and eventbus.
2429
+
2430
+ The function is looked up with the \`request-function\` event, which the
2431
+ \`EngineFactory\` answers from its resource importer. Register the function
2432
+ with the \`EligiusResourceImporter\` constructor:
2433
+ \`new EligiusResourceImporter({functions: {myFunction}})\`.
2434
+
2435
+ The function is called with the current operation data as its argument, and with \`this\`
2436
+ set to a view of the operation scope. Reading a property from \`this\` returns it from the
2437
+ innermost scope that has it, so inside a \`when\` block in a loop \`this.currentItem\`,
2438
+ \`this.loopIndex\` and \`this.variables\` return the loop's and the action's values, the same
2439
+ as \`$scope.\` chains. Assigning to \`this\` (for example \`this.newIndex\`) writes to the scope the
2440
+ operation runs in.`,
2441
+ category: `Utility`,
2442
+ properties: { systemName: {
2443
+ type: "ParameterType:systemName",
2444
+ required: true,
2445
+ erased: true
2446
+ } }
2447
+ };
2448
+ }
2449
+
2450
+ // src/operation/metadata/end-action.ts
2451
+ function endAction() {
2452
+ return {
2453
+ description: `This operation invokes the {@link EndableAction}.end method on the specified action instance.
2454
+
2455
+ The action receives its own copy of the current operation data merged with the action
2456
+ operation data. Whatever the action's end operations add, change or remove in that copy stays
2457
+ with the action: once it has completed, this operation continues with the operation data it
2458
+ had before, without the \`actionOperationData\` property.`,
2459
+ category: `Action`,
2460
+ dependentProperties: ["actionInstance"],
2461
+ properties: { actionOperationData: {
2462
+ type: "ParameterType:object",
2463
+ erased: true
2464
+ } }
2465
+ };
2466
+ }
2467
+
2468
+ // src/operation/metadata/end-for-each.ts
2469
+ function endForEach() {
2470
+ return {
2471
+ description: `This operation checks if the current loop should end or start the next iteration.`,
2472
+ category: `Control Flow`
2473
+ };
2474
+ }
2475
+
2476
+ // src/operation/metadata/end-when.ts
2477
+ function endWhen() {
2478
+ return {
2479
+ description: `This operation cleans up after the {@link when}/{@link otherwise}/{@link endWhen} control flow ends.`,
2480
+ category: `Control Flow`
2481
+ };
2482
+ }
2483
+
2484
+ // src/operation/metadata/extend-controller.ts
2485
+ function extendController() {
2486
+ return {
2487
+ description: `Extends the current controller with given extension.
2488
+
2489
+ The extension's own properties are copied onto the controller instance.`,
2490
+ category: `Controller`,
2491
+ dependentProperties: ["controllerInstance"],
2492
+ properties: { controllerExtension: {
2493
+ type: "ParameterType:object",
2494
+ required: true,
2495
+ erased: true
2496
+ } }
2497
+ };
2498
+ }
2499
+
2500
+ // src/operation/metadata/filter-array.ts
2501
+ function filterArray() {
2502
+ return {
2503
+ description: `Filters an array based on property equality or custom predicate function.
2504
+
2505
+ Operates on arrayData passed from previous operations.
2506
+ Supports two filtering modes:
2507
+ 1. Property equality: \`filterProperty\` and \`filterValue\` to filter by property match
2508
+ 2. Custom predicate: \`filterPredicate\` function for complex filtering logic`,
2509
+ category: `Array`,
2510
+ dependentProperties: ["arrayData"],
2511
+ properties: {
2512
+ filterProperty: {
2513
+ type: "ParameterType:string",
2514
+ erased: true
2515
+ },
2516
+ filterValue: {
2517
+ type: "ParameterType:object",
2518
+ erased: true
2519
+ },
2520
+ filterPredicate: {
2521
+ type: "ParameterType:function",
2522
+ erased: true
2523
+ }
2524
+ },
2525
+ outputProperties: { filteredArray: { type: "ParameterType:array" } }
2526
+ };
2527
+ }
2528
+
2529
+ // src/operation/metadata/find-in-array.ts
2530
+ function findInArray() {
2531
+ return {
2532
+ description: `Finds the first element in an array matching criteria.
2533
+
2534
+ Operates on arrayData passed from previous operations.
2535
+ Supports two search modes:
2536
+ 1. Property equality: \`findProperty\` and \`findValue\` to find by property match
2537
+ 2. Custom predicate: \`findPredicate\` function for complex search logic
2538
+
2539
+ Returns \`undefined\` for \`foundItem\` and \`-1\` for \`foundIndex\` if no match found.`,
2540
+ category: `Array`,
2541
+ dependentProperties: ["arrayData"],
2542
+ properties: {
2543
+ findProperty: {
2544
+ type: "ParameterType:string",
2545
+ erased: true
2546
+ },
2547
+ findValue: {
2548
+ type: "ParameterType:object",
2549
+ erased: true
2550
+ },
2551
+ findPredicate: {
2552
+ type: "ParameterType:function",
2553
+ erased: true
2554
+ }
2555
+ },
2556
+ outputProperties: {
2557
+ foundItem: { type: "ParameterType:object" },
2558
+ foundIndex: { type: "ParameterType:number" }
2559
+ }
2560
+ };
2561
+ }
2562
+
2563
+ // src/operation/metadata/for-each.ts
2564
+ function forEach() {
2565
+ return {
2566
+ description: `This operation iterates over the given collection.
2567
+
2568
+ Each iteration the current item from the specified collection is
2569
+ assigned to the {@link IOperationScope.currentItem |currentItem} property on the {@link IOperationScope |operation scope}.
2570
+
2571
+ At the start of the loop, the associated {@link endForEach} operation is determined and when
2572
+ the last iteration is completed the flow control is set to the index of that operation.
2573
+
2574
+ The {@link continueForEach |continue} and {@link breakForEach |break} operations can be used to control the
2575
+ loop iterations.
2576
+
2577
+ The collection is resolved once, when the loop starts, and the loop iterates over a snapshot
2578
+ of it. Changing, replacing or removing the source collection inside the loop body does not
2579
+ change the items or the number of iterations of the running loop.`,
2580
+ category: `Control Flow`,
2581
+ properties: { collection: {
2582
+ type: "ParameterType:array|ParameterType:string",
2583
+ required: true
2584
+ } }
2585
+ };
2586
+ }
2587
+
2588
+ // src/operation/metadata/format-date.ts
2589
+ function formatDate() {
2590
+ return {
2591
+ description: `Formats a date with a simple token pattern, in the local time zone.
2592
+
2593
+ Supported tokens (every occurrence is replaced, other characters are kept as is):
2594
+ - \`YYYY\`: four digit year
2595
+ - \`MM\`: month, 01-12
2596
+ - \`DD\`: day of the month, 01-31
2597
+ - \`HH\`: hours, 00-23
2598
+ - \`mm\`: minutes, 00-59
2599
+ - \`ss\`: seconds, 00-59`,
2600
+ category: `Date`,
2601
+ dependentProperties: ["date"],
2602
+ properties: { format: {
2603
+ type: "ParameterType:string",
2604
+ required: true,
2605
+ erased: true
2606
+ } },
2607
+ outputProperties: { formattedDate: { type: "ParameterType:string" } }
2608
+ };
2609
+ }
2610
+
2611
+ // src/operation/metadata/format-text.ts
2612
+ function formatText() {
2613
+ return {
2614
+ description: `Transforms text using format operations: uppercase, lowercase, capitalize, titlecase, or trim.
2615
+
2616
+ Operates on textContent passed from previous operations (e.g., getTextContent).
2617
+
2618
+ Transformations:
2619
+ - \`uppercase\`: Convert all characters to uppercase
2620
+ - \`lowercase\`: Convert all characters to lowercase
2621
+ - \`capitalize\`: Capitalize only the first letter
2622
+ - \`titlecase\`: Capitalize first letter of each word
2623
+ - \`trim\`: Remove leading and trailing whitespace`,
2624
+ category: `Text`,
2625
+ dependentProperties: ["textContent"],
2626
+ properties: { transformation: {
2627
+ type: [
2628
+ { value: "uppercase" },
2629
+ { value: "lowercase" },
2630
+ { value: "capitalize" },
2631
+ { value: "titlecase" },
2632
+ { value: "trim" }
2633
+ ],
2634
+ required: true,
2635
+ erased: true
2636
+ } },
2637
+ outputProperties: { formattedText: { type: "ParameterType:string" } }
2638
+ };
2639
+ }
2640
+
2641
+ // src/operation/metadata/get-attributes-from-element.ts
2642
+ function getAttributesFromElement() {
2643
+ return {
2644
+ description: `This operation retrieves the values for the specified attribute names from the given selected element.`,
2645
+ category: `DOM`,
2646
+ dependentProperties: ["selectedElement"],
2647
+ properties: { attributeNames: {
2648
+ type: "ParameterType:array",
2649
+ itemType: "ParameterType:string",
2650
+ required: true,
2651
+ erased: true
2652
+ } },
2653
+ outputProperties: { attributeValues: { type: "ParameterType:object" } }
2654
+ };
2655
+ }
2656
+
2657
+ // src/operation/metadata/get-controller-from-element.ts
2658
+ function getControllerFromElement() {
2659
+ return {
2660
+ description: `This operation retrieves the controller instance with the specified name that is assigned to the given selected element.`,
2661
+ category: `Controller`,
2662
+ dependentProperties: ["selectedElement"],
2663
+ properties: { controllerName: {
2664
+ type: "ParameterType:controllerName",
2665
+ required: true,
2666
+ erased: true
2667
+ } },
2668
+ outputProperties: { controllerInstance: { type: "ParameterType:object" } }
2669
+ };
2670
+ }
2671
+
2672
+ // src/operation/metadata/get-controller-instance.ts
2673
+ function getControllerInstance() {
2674
+ return {
2675
+ description: `This operation retrieves an instance of the given controller name.
2676
+ It assigns this instance to the \`controllerInstance\` property on the current operation data`,
2677
+ category: `Controller`,
2678
+ properties: { systemName: {
2679
+ type: "ParameterType:controllerName",
2680
+ required: true,
2681
+ erased: true
2682
+ } },
2683
+ outputProperties: { controllerInstance: { type: "ParameterType:object" } }
2684
+ };
2685
+ }
2686
+
2687
+ // src/operation/metadata/get-current-time.ts
2688
+ function getCurrentTime() {
2689
+ return {
2690
+ description: `Gets the current time as timestamp and Date object.`,
2691
+ category: `Date`,
2692
+ outputProperties: {
2693
+ timestamp: { type: "ParameterType:number" },
2694
+ date: { type: "ParameterType:Date" }
2695
+ }
2696
+ };
2697
+ }
2698
+
2699
+ // src/operation/metadata/get-element-dimensions.ts
2700
+ function getElementDimensions() {
2701
+ return {
2702
+ description: `This operation calculates the width and height of the given selected element.
2703
+ It assigns this struct to the dimensions property on the current operation data.
2704
+ Optionally the width and height can be modified using the given modifier string.
2705
+
2706
+ The modifier string is formatted in the following way:
2707
+
2708
+ <operator><amount><optional-side><optional-precentage>|<ratio-definition>
2709
+
2710
+ Where the ratio modifier is formatted in the following way:
2711
+ <side>[ar=<ratio-left>-<ratio-right>]
2712
+
2713
+ For example, this modifier '+100h|w[ar=8-1]' will modifiy the dimensions like this:
2714
+ 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.`,
2715
+ category: `DOM`,
2716
+ dependentProperties: ["selectedElement"],
2717
+ properties: { modifier: {
2718
+ type: "ParameterType:dimensionsModifier",
2719
+ erased: true
2720
+ } },
2721
+ outputProperties: { dimensions: { type: "ParameterType:object" } }
2722
+ };
2723
+ }
2724
+
2725
+ // src/operation/metadata/get-focused-element.ts
2726
+ function getFocusedElement() {
2727
+ return {
2728
+ description: `Gets the currently focused element.`,
2729
+ category: `Focus`,
2730
+ outputProperties: { focusedElement: { type: "ParameterType:jQuery" } }
2731
+ };
2732
+ }
2733
+
2734
+ // src/operation/metadata/get-form-data.ts
2735
+ function getFormData() {
2736
+ return {
2737
+ description: `Extracts all input, select, and textarea values from form element into operation data.
2738
+
2739
+ This operation reads form field values and returns them as an object with field names as keys.
2740
+ Only processes form elements that are enabled and not hidden. Handles checkboxes, radio buttons,
2741
+ select elements, textareas, and text inputs.`,
2742
+ category: `Form`,
2743
+ dependentProperties: ["selectedElement"],
2744
+ outputProperties: { formData: { type: "ParameterType:object" } }
2745
+ };
2746
+ }
2747
+
2748
+ // src/operation/metadata/get-import.ts
2749
+ function getImport() {
2750
+ return {
2751
+ description: `This operation retrieves the import specified by the given \`systemName\` and
2752
+ assigns it to the \`importedInstance\` property on the current operaton date.
2753
+
2754
+ The import is looked up with the \`request-function\` event, which the
2755
+ \`EngineFactory\` answers from its resource importer. Functions, templates
2756
+ and JSON registered with the \`EligiusResourceImporter\` constructor
2757
+ (\`new EligiusResourceImporter({json: {settings}})\`) can be imported this
2758
+ way, as can every built-in operation, controller and provider export.`,
2759
+ category: `Utility`,
2760
+ properties: { systemName: {
2761
+ type: "ParameterType:systemName",
2762
+ required: true,
2763
+ erased: true
2764
+ } },
2765
+ outputProperties: { importedInstance: { type: "ParameterType:object" } }
2766
+ };
2767
+ }
2768
+
2769
+ // src/operation/metadata/get-query-params.ts
2770
+ function getQueryParams() {
2771
+ return {
2772
+ description: `This operation retrieves the current query parameters from the browser's address bar and places
2773
+ them on the returned operation data.`,
2774
+ category: `Utility`,
2775
+ properties: { defaultValues: {
2776
+ type: "ParameterType:object",
2777
+ erased: true
2778
+ } },
2779
+ outputProperties: { queryParams: { type: "ParameterType:object" } }
2780
+ };
2781
+ }
2782
+
2783
+ // src/operation/metadata/get-scroll-position.ts
2784
+ function getScrollPosition() {
2785
+ return {
2786
+ description: `Gets the current scroll position of the viewport.
2787
+
2788
+ Returns x (horizontal) and y (vertical) scroll positions in pixels.
2789
+ Uses cross-browser compatible methods to retrieve scroll position.`,
2790
+ category: `Scroll`,
2791
+ outputProperties: {
2792
+ scrollX: { type: "ParameterType:number" },
2793
+ scrollY: { type: "ParameterType:number" }
2794
+ }
2795
+ };
2796
+ }
2797
+
2798
+ // src/operation/metadata/get-text-content.ts
2799
+ function getTextContent() {
2800
+ return {
2801
+ description: `Extracts text content from element, stripping all HTML markup.
2802
+
2803
+ Uses jQuery's \`.text()\` method which is XSS-safe and returns only the text content
2804
+ without any HTML tags. Preserves whitespace and text from nested elements.`,
2805
+ category: `Text`,
2806
+ dependentProperties: ["selectedElement"],
2807
+ outputProperties: { textContent: { type: "ParameterType:string" } }
2808
+ };
2809
+ }
2810
+
2811
+ // src/operation/metadata/http-delete.ts
2812
+ function httpDelete() {
2813
+ return {
2814
+ description: `Performs an HTTP DELETE request to the specified URL.`,
2815
+ category: `HTTP`,
2816
+ properties: {
2817
+ url: {
2818
+ type: "ParameterType:string",
2819
+ required: true,
2820
+ erased: true
2821
+ },
2822
+ headers: {
2823
+ type: "ParameterType:object",
2824
+ erased: true
2825
+ }
2826
+ },
2827
+ outputProperties: {
2828
+ response: { type: "ParameterType:object" },
2829
+ status: { type: "ParameterType:number" }
2830
+ }
2831
+ };
2832
+ }
2833
+
2834
+ // src/operation/metadata/http-post.ts
2835
+ function httpPost() {
2836
+ return {
2837
+ description: `Performs an HTTP POST request to the specified URL.
2838
+
2839
+ The body is sent as JSON with \`Content-Type: application/json\`, unless the caller's headers set
2840
+ another content type (header names are case-insensitive). With a non-JSON content type, a string
2841
+ body is sent as is; other bodies are still JSON encoded.`,
2842
+ category: `HTTP`,
2843
+ properties: {
2844
+ url: {
2845
+ type: "ParameterType:string",
2846
+ required: true,
2847
+ erased: true
2848
+ },
2849
+ body: {
2850
+ type: "ParameterType:object",
2851
+ erased: true
2852
+ },
2853
+ headers: {
2854
+ type: "ParameterType:object",
2855
+ erased: true
2856
+ }
2857
+ },
2858
+ outputProperties: {
2859
+ response: { type: "ParameterType:object" },
2860
+ status: { type: "ParameterType:number" }
2861
+ }
2862
+ };
2863
+ }
2864
+
2865
+ // src/operation/metadata/http-put.ts
2866
+ function httpPut() {
2867
+ return {
2868
+ description: `Performs an HTTP PUT request to the specified URL.
2869
+
2870
+ The body is sent as JSON with \`Content-Type: application/json\`, unless the caller's headers set
2871
+ another content type (header names are case-insensitive). With a non-JSON content type, a string
2872
+ body is sent as is; other bodies are still JSON encoded.`,
2873
+ category: `HTTP`,
2874
+ properties: {
2875
+ url: {
2876
+ type: "ParameterType:string",
2877
+ required: true,
2878
+ erased: true
2879
+ },
2880
+ body: {
2881
+ type: "ParameterType:object",
2882
+ erased: true
2883
+ },
2884
+ headers: {
2885
+ type: "ParameterType:object",
2886
+ erased: true
2887
+ }
2888
+ },
2889
+ outputProperties: {
2890
+ response: { type: "ParameterType:object" },
2891
+ status: { type: "ParameterType:number" }
2892
+ }
2893
+ };
2894
+ }
2895
+
2896
+ // src/operation/metadata/invoke-object-method.ts
2897
+ function invokeObjectMethod() {
2898
+ return {
2899
+ description: `This operation invokes the specified method on the given object with the given optional arguments
2900
+ and assigns the result to the \`methodResult\` operationdata property. When the method returns a
2901
+ promise, the operation waits for it and assigns the resolved value.
2902
+
2903
+ The operation only calls application code: methods of controllers, of other instances of
2904
+ application classes, and of plain objects. It refuses, and throws for:
2905
+ - an \`instance\` that is a function, the global object (\`window\`), a document, a DOM node,
2906
+ a jQuery object, or any other built-in or host object (arrays, maps, promises, \`location\`,
2907
+ storage, ...);
2908
+ - a method that is a built-in (native) function, such as \`eval\`, \`Function\`, \`setTimeout\`,
2909
+ \`setInterval\`, \`document.write\`, \`Reflect.apply\` or a bound function, or a jQuery function;
2910
+ - the method names \`constructor\`, \`__proto__\` and \`prototype\`;
2911
+ - arguments that are such functions.
2912
+
2913
+ These checks stop configuration from reaching the platform's code-executing functions through
2914
+ this operation. They cannot vouch for what an application method does with its arguments, so
2915
+ only expose methods that are safe to call with configured data.`,
2916
+ category: `Utility`,
2917
+ dependentProperties: ["instance"],
2918
+ properties: {
2919
+ methodName: {
2920
+ type: "ParameterType:string",
2921
+ required: true,
2922
+ erased: true
2923
+ },
2924
+ methodArguments: {
2925
+ type: "ParameterType:array",
2926
+ erased: true
2927
+ }
2928
+ },
2929
+ outputProperties: { methodResult: { type: "ParameterType:object" } }
2930
+ };
2931
+ }
2932
+
2933
+ // src/operation/metadata/is-element-in-viewport.ts
2934
+ function isElementInViewport() {
2935
+ return {
2936
+ description: `Checks if an element is currently visible within the viewport.
2937
+
2938
+ Uses \`getBoundingClientRect()\` to determine if the element is within the viewport boundaries.`,
2939
+ category: `DOM`,
2940
+ dependentProperties: ["selectedElement"],
2941
+ outputProperties: { isInViewport: { type: "ParameterType:boolean" } }
2942
+ };
2943
+ }
2944
+
2945
+ // src/operation/metadata/load-from-storage.ts
2946
+ function loadFromStorage() {
2947
+ return {
2948
+ description: `Loads data from browser storage (localStorage or sessionStorage).
2949
+
2950
+ Deserializes the stored JSON value. Returns \`null\` if key doesn't exist.
2951
+ When \`storageType\` is omitted, localStorage is used.`,
2952
+ category: `Data`,
2953
+ properties: {
2954
+ key: {
2955
+ type: "ParameterType:string",
2956
+ required: true,
2957
+ erased: true
2958
+ },
2959
+ storageType: {
2960
+ type: [{ value: "local" }, { value: "session" }],
2961
+ required: true,
2962
+ erased: true
2963
+ }
2964
+ },
2965
+ outputProperties: { loadedValue: { type: "ParameterType:object" } }
2966
+ };
2967
+ }
2968
+
2969
+ // src/operation/metadata/load-json.ts
2970
+ function loadJson() {
2971
+ return {
2972
+ description: `This operation loads a JSON file from the specified url and assigns it to the json
2973
+ property on the current operation data.
2974
+
2975
+ If the cache property is set to true and a cached value already exists, a copy of it is assigned
2976
+ instead of re-retrieving it from the url. Mutating the returned json never changes the cache.
2977
+
2978
+ The cache is shared by every engine. It is emptied when the last live engine created by
2979
+ \`EngineFactory\` is destroyed; call {@link clearJsonCache} to empty it earlier.`,
2980
+ category: `Utility`,
2981
+ properties: {
2982
+ url: {
2983
+ type: "ParameterType:string",
2984
+ required: true,
2985
+ erased: true
2986
+ },
2987
+ cache: {
2988
+ type: "ParameterType:boolean",
2989
+ erased: true
2990
+ }
2991
+ },
2992
+ outputProperties: { json: { type: "ParameterType:object" } }
2993
+ };
2994
+ }
2995
+
2996
+ // src/operation/metadata/log.ts
2997
+ function log() {
2998
+ return {
2999
+ description: `This operation logs the specified value, or, when no logValue property has been assigned
3000
+ it will log the current operation data, global data and scope to the console`,
3001
+ category: `Utility`,
3002
+ properties: {
3003
+ logValue: {
3004
+ type: "ParameterType:object|ParameterType:string|ParameterType:number|ParameterType:boolean|ParameterType:array",
3005
+ erased: true
3006
+ },
3007
+ logName: {
3008
+ type: "ParameterType:string",
3009
+ erased: true
3010
+ }
3011
+ }
3012
+ };
3013
+ }
3014
+
3015
+ // src/operation/metadata/map-array.ts
3016
+ function mapArray() {
3017
+ return {
3018
+ description: `Transforms each element of an array using a mapping function.
3019
+
3020
+ Operates on arrayData passed from previous operations.
3021
+ The mapFunction receives each item and optionally its index.`,
3022
+ category: `Array`,
3023
+ dependentProperties: ["arrayData"],
3024
+ properties: { mapFunction: {
3025
+ type: "ParameterType:function",
3026
+ required: true,
3027
+ erased: true
3028
+ } },
3029
+ outputProperties: { mappedArray: { type: "ParameterType:array" } }
3030
+ };
3031
+ }
3032
+
3033
+ // src/operation/metadata/math.ts
3034
+ function math() {
3035
+ return {
3036
+ description: `This operation performs the given math function with the specified arguments.
3037
+
3038
+ \`args\` and \`functionName\` may contain property chains (\`$operationdata.\`, \`$globaldata.\`,
3039
+ \`$scope.\`). Only these two inputs are resolved; the rest of the operation data is left as it
3040
+ is. Arguments that name a Math constant (such as \`'PI'\`) are replaced by its value.`,
3041
+ category: `Utility`,
3042
+ properties: {
3043
+ args: {
3044
+ type: "ParameterType:array",
3045
+ required: true,
3046
+ erased: true
3047
+ },
3048
+ functionName: {
3049
+ type: "ParameterType:mathfunction",
3050
+ required: true,
3051
+ erased: true
3052
+ }
3053
+ },
3054
+ outputProperties: { mathResult: { type: "ParameterType:number" } }
3055
+ };
3056
+ }
3057
+
3058
+ // src/operation/metadata/otherwise.ts
3059
+ function otherwise() {
3060
+ return {
3061
+ description: `If the preceeding {@link when} operation evaluates to \`true\` subsequent operations will
3062
+ be skipped until an {@link endWhen} operation is encountered.`,
3063
+ category: `Control Flow`
3064
+ };
3065
+ }
3066
+
3067
+ // src/operation/metadata/remove-class.ts
3068
+ function removeClass() {
3069
+ return {
3070
+ description: `This operation removes the spcified class name from the given selected element.`,
3071
+ category: `DOM`,
3072
+ dependentProperties: ["selectedElement"],
3073
+ properties: { className: {
3074
+ type: "ParameterType:className",
3075
+ required: true,
3076
+ erased: true
3077
+ } }
3078
+ };
3079
+ }
3080
+
3081
+ // src/operation/metadata/remove-controller-from-element.ts
3082
+ function removeControllerFromElement() {
3083
+ return {
3084
+ description: `This operation removes the controller with the specified name from the given selected element.`,
3085
+ category: `Controller`,
3086
+ dependentProperties: ["selectedElement"],
3087
+ properties: { controllerName: {
3088
+ type: "ParameterType:controllerName",
3089
+ required: true,
3090
+ erased: true
3091
+ } }
3092
+ };
3093
+ }
3094
+
3095
+ // src/operation/metadata/remove-element.ts
3096
+ function removeElement() {
3097
+ return {
3098
+ description: `This operation removes the given selected element from the DOM.
3099
+
3100
+ Controllers attached to the element or its descendants (by \`addControllerToElement\`) are
3101
+ detached first, so their eventbus and window listeners do not outlive the element.`,
3102
+ category: `DOM`,
3103
+ dependentProperties: ["selectedElement"]
3104
+ };
3105
+ }
3106
+
3107
+ // src/operation/metadata/remove-properties-from-operation-data.ts
3108
+ function removePropertiesFromOperationData() {
3109
+ return {
3110
+ description: `This operation removes the given list of properties from the current operation data.
3111
+ It will also remove the property \`propertyNames\` from the result.`,
3112
+ category: `Data`,
3113
+ properties: { propertyNames: {
3114
+ type: "ParameterType:array",
3115
+ itemType: "ParameterType:string",
3116
+ required: true,
3117
+ erased: true
3118
+ } }
3119
+ };
3120
+ }
3121
+
3122
+ // src/operation/metadata/reparent-element.ts
3123
+ function reparentElement() {
3124
+ return {
3125
+ description: `This operation moves the given selected element to the new parent that is defined
3126
+ by the specified \`newParentSelector\`. jQuery data, event handlers and attached controllers
3127
+ are preserved.
3128
+
3129
+ The selector is resolved inside the engine root (the root itself included), the same way
3130
+ \`selectElement\` resolves its selector, and must match exactly one element. HTML strings are
3131
+ not accepted.`,
3132
+ category: `DOM`,
3133
+ dependentProperties: ["selectedElement"],
3134
+ properties: { newParentSelector: {
3135
+ type: "ParameterType:selector",
3136
+ required: true,
3137
+ erased: true
3138
+ } }
3139
+ };
3140
+ }
3141
+
3142
+ // src/operation/metadata/replace-string.ts
3143
+ function replaceString() {
3144
+ return {
3145
+ description: `Replaces occurrences of a pattern in a string (alias for replaceText for string context).
3146
+
3147
+ Like replaceText, a string pattern replaces every occurrence and inserts the replacement
3148
+ literally (\`$&\`, \`$1\` and similar are not expanded). A RegExp pattern follows
3149
+ \`String.prototype.replace\`: only a global RegExp replaces every match, and \`$\` patterns
3150
+ in the replacement are expanded. Unlike replaceText, the result is written to \`result\`
3151
+ and \`textContent\` is left unchanged.`,
3152
+ category: `String`,
3153
+ dependentProperties: ["textContent"],
3154
+ properties: {
3155
+ pattern: {
3156
+ type: "ParameterType:string|ParameterType:RegExp",
3157
+ required: true,
3158
+ erased: true
3159
+ },
3160
+ replacement: {
3161
+ type: "ParameterType:string",
3162
+ required: true,
3163
+ erased: true
3164
+ }
3165
+ },
3166
+ outputProperties: { result: { type: "ParameterType:string" } }
3167
+ };
3168
+ }
3169
+
3170
+ // src/operation/metadata/replace-text.ts
3171
+ function replaceText() {
3172
+ return {
3173
+ description: `Finds and replaces text using literal string or regex pattern.
3174
+
3175
+ Operates on textContent passed from previous operations (e.g., getTextContent).
3176
+ Supports regex patterns with global flag for multiple replacements.
3177
+ Updates textContent with replaced text and sets replacementCount.
3178
+
3179
+ A string pattern replaces every occurrence and inserts the replacement literally.`,
3180
+ category: `Text`,
3181
+ dependentProperties: ["textContent"],
3182
+ properties: {
3183
+ searchPattern: {
3184
+ type: "ParameterType:string|ParameterType:RegExp",
3185
+ required: true,
3186
+ erased: true
3187
+ },
3188
+ replacement: {
3189
+ type: "ParameterType:string",
3190
+ required: true,
3191
+ erased: true
3192
+ }
3193
+ },
3194
+ outputProperties: { replacementCount: { type: "ParameterType:number" } }
3195
+ };
3196
+ }
3197
+
3198
+ // src/operation/metadata/request-action.ts
3199
+ function requestAction() {
3200
+ return {
3201
+ description: `This operation requests an action instance with the specified name and assigns it
3202
+ to the \`actionInstance\` property on the current operation data.`,
3203
+ category: `Action`,
3204
+ properties: { systemName: {
3205
+ type: "ParameterType:actionName",
3206
+ required: true,
3207
+ erased: true
3208
+ } },
3209
+ outputProperties: { actionInstance: { type: "ParameterType:object" } }
3210
+ };
3211
+ }
3212
+
3213
+ // src/operation/metadata/save-to-storage.ts
3214
+ function saveToStorage() {
3215
+ return {
3216
+ description: `Saves data to browser storage (localStorage or sessionStorage).
3217
+
3218
+ Serializes the value as JSON before storing. Supports any JSON-serializable data type.
3219
+ Use \`null\` to store an empty value; \`undefined\` cannot be stored as JSON and is rejected.
3220
+ When \`storageType\` is omitted, localStorage is used.`,
3221
+ category: `Data`,
3222
+ properties: {
3223
+ key: {
3224
+ type: "ParameterType:string",
3225
+ required: true,
3226
+ erased: true
3227
+ },
3228
+ value: {
3229
+ type: "ParameterType:object",
3230
+ required: true,
3231
+ erased: true
3232
+ },
3233
+ storageType: {
3234
+ type: [{ value: "local" }, { value: "session" }],
3235
+ required: true,
3236
+ erased: true
3237
+ }
3238
+ }
3239
+ };
3240
+ }
3241
+
3242
+ // src/operation/metadata/scroll-to-element.ts
3243
+ function scrollToElement() {
3244
+ return {
3245
+ description: `Scrolls the viewport to bring the selected element into view.
3246
+
3247
+ Uses the browser's \`scrollIntoView\` API with configurable behavior.`,
3248
+ category: `Scroll`,
3249
+ dependentProperties: ["selectedElement"],
3250
+ properties: {
3251
+ behavior: {
3252
+ type: [{ value: "auto" }, { value: "smooth" }],
3253
+ erased: true
3254
+ },
3255
+ block: {
3256
+ type: [
3257
+ { value: "start" },
3258
+ { value: "center" },
3259
+ { value: "end" },
3260
+ { value: "nearest" }
3261
+ ],
3262
+ erased: true
3263
+ },
3264
+ inline: {
3265
+ type: [
3266
+ { value: "start" },
3267
+ { value: "center" },
3268
+ { value: "end" },
3269
+ { value: "nearest" }
3270
+ ],
3271
+ erased: true
3272
+ }
3273
+ }
3274
+ };
3275
+ }
3276
+
3277
+ // src/operation/metadata/scroll-to-position.ts
3278
+ function scrollToPosition() {
3279
+ return {
3280
+ description: `Scrolls the viewport to a specific x,y coordinate position.
3281
+
3282
+ Uses the browser's \`window.scrollTo\` API with configurable behavior.`,
3283
+ category: `Scroll`,
3284
+ properties: {
3285
+ x: {
3286
+ type: "ParameterType:number",
3287
+ required: true,
3288
+ erased: true
3289
+ },
3290
+ y: {
3291
+ type: "ParameterType:number",
3292
+ required: true,
3293
+ erased: true
3294
+ },
3295
+ behavior: {
3296
+ type: [{ value: "auto" }, { value: "smooth" }],
3297
+ erased: true
3298
+ }
3299
+ }
3300
+ };
3301
+ }
3302
+
3303
+ // src/operation/metadata/select-element.ts
3304
+ function selectElement() {
3305
+ return {
3306
+ description: `This operation selects one or more elements using the specified selector.
3307
+
3308
+ If \`useSelectedElementAsRoot\` is set to true and a valid DOM element is assigned
3309
+ to the current operation data's \`selectedElement\` property
3310
+ then the element will be looked for only in the descendant elements of this DOM element.`,
3311
+ category: `DOM`,
3312
+ properties: {
3313
+ selector: {
3314
+ type: "ParameterType:selector",
3315
+ required: true,
3316
+ erased: true
3317
+ },
3318
+ useSelectedElementAsRoot: {
3319
+ type: "ParameterType:boolean",
3320
+ erased: true
3321
+ }
3322
+ },
3323
+ outputProperties: { selectedElement: { type: "ParameterType:object" } }
3324
+ };
3325
+ }
3326
+
3327
+ // src/operation/metadata/set-data.ts
3328
+ function setData() {
3329
+ return {
3330
+ description: `This operation assigns the specified properties to the specified data targets.`,
3331
+ category: `Data`,
3332
+ properties: { properties: {
3333
+ type: "ParameterType:object",
3334
+ required: true,
3335
+ erased: true
3336
+ } }
3337
+ };
3338
+ }
3339
+
3340
+ // src/operation/metadata/set-element-attributes.ts
3341
+ function setElementAttributes() {
3342
+ return {
3343
+ description: `This operation sets the specified set of attributes on the given selected element.
3344
+
3345
+ Event handler (\`on*\`) and \`srcdoc\` attributes, and \`javascript:\` or \`vbscript:\` URLs in URL
3346
+ attributes such as \`href\`, \`src\` and \`formaction\`, are refused, the same as in \`createElement\`.`,
3347
+ category: `DOM`,
3348
+ dependentProperties: ["selectedElement"],
3349
+ properties: { attributes: {
3350
+ type: "ParameterType:object",
3351
+ required: true,
3352
+ erased: true
3353
+ } }
3354
+ };
3355
+ }
3356
+
3357
+ // src/operation/metadata/set-element-content.ts
3358
+ function setElementContent() {
3359
+ return {
3360
+ description: `This operation sets the specified content defined by the value assigned to the template property
3361
+ to the given selected element.
3362
+
3363
+ When the \`insertionType\` is set to \`overwrite\` the contents of the selected element are replaced
3364
+ by the given template.
3365
+ When set to \`append\` the new content will be inserted after the current content.
3366
+ When set to \`prepend\` the new content will be inserted before the current content.
3367
+
3368
+ With \`overwrite\`, controllers attached to the replaced content (by \`addControllerToElement\`) are
3369
+ detached first. Controllers on the selected element itself stay attached.
3370
+
3371
+ The template is inserted as HTML: a string template is parsed by jQuery, which also runs the
3372
+ scripts and inline event handlers it contains. Only use string templates from the configuration
3373
+ or the resource importer; build content from user data with \`createElement\`, whose \`text\` is
3374
+ never parsed as HTML.`,
3375
+ category: `DOM`,
3376
+ dependentProperties: ["selectedElement"],
3377
+ properties: {
3378
+ template: {
3379
+ type: "ParameterType:string|ParameterType:Element|ParameterType:Text|ParameterType:Comment|ParameterType:Document|ParameterType:DocumentFragment",
3380
+ erased: true
3381
+ },
3382
+ insertionType: {
3383
+ type: [
3384
+ { value: "overwrite" },
3385
+ { value: "append" },
3386
+ { value: "prepend" }
3387
+ ],
3388
+ erased: true
3389
+ }
3390
+ }
3391
+ };
3392
+ }
3393
+
3394
+ // src/operation/metadata/set-focus.ts
3395
+ function setFocus() {
3396
+ return {
3397
+ description: `Sets focus to the selected element.`,
3398
+ category: `Focus`,
3399
+ dependentProperties: ["selectedElement"]
3400
+ };
3401
+ }
3402
+
3403
+ // src/operation/metadata/set-form-value.ts
3404
+ function setFormValue() {
3405
+ return {
3406
+ description: `Sets the value of an input, select, or textarea element.
3407
+
3408
+ Handles different input types appropriately:
3409
+ - Text inputs, textareas, selects: sets value directly
3410
+ - Checkboxes: sets checked property for boolean values
3411
+ - Radio buttons: sets checked property for boolean values
3412
+ - Number inputs: converts to string`,
3413
+ category: `Form`,
3414
+ dependentProperties: ["selectedElement"],
3415
+ properties: { value: {
3416
+ type: "ParameterType:string|ParameterType:number|ParameterType:boolean",
3417
+ required: true,
3418
+ erased: true
3419
+ } }
3420
+ };
3421
+ }
3422
+
3423
+ // src/operation/metadata/set-global-data.ts
3424
+ function setGlobalData() {
3425
+ return {
3426
+ description: `This operation copies the specified properties from the operationData to the global data.
3427
+
3428
+ Plain data is stored as a deep copy, so changing the operation data afterwards does not change
3429
+ the global data. jQuery objects, DOM nodes, functions and class instances (such as controllers)
3430
+ are stored by reference.`,
3431
+ category: `Data`,
3432
+ properties: { propertyNames: {
3433
+ type: "ParameterType:array",
3434
+ itemType: "ParameterType:string",
3435
+ required: true,
3436
+ erased: true
3437
+ } }
3438
+ };
3439
+ }
3440
+
3441
+ // src/operation/metadata/set-operation-data.ts
3442
+ function setOperationData() {
3443
+ return {
3444
+ description: `This operation assigns the specified properties to the current operation data.
3445
+ When override is set to true the properties replace the current operation data entirely.`,
3446
+ category: `Data`,
3447
+ properties: {
3448
+ override: {
3449
+ type: "ParameterType:boolean",
3450
+ erased: true
3451
+ },
3452
+ properties: {
3453
+ type: "ParameterType:object",
3454
+ required: true,
3455
+ erased: true
3456
+ }
3457
+ }
3458
+ };
3459
+ }
3460
+
3461
+ // src/operation/metadata/set-style.ts
3462
+ function setStyle() {
3463
+ return {
3464
+ description: `This operation assigns the specified CSS style properties to the
3465
+ given selected element.`,
3466
+ category: `DOM`,
3467
+ dependentProperties: ["selectedElement"],
3468
+ properties: { properties: {
3469
+ type: "ParameterType:cssProperties",
3470
+ required: true,
3471
+ erased: true
3472
+ } }
3473
+ };
3474
+ }
3475
+
3476
+ // src/operation/metadata/set-variable.ts
3477
+ function setVariable() {
3478
+ return {
3479
+ description: `This operation sets a variable with the specified name on the scope with the specified value.
3480
+
3481
+ Variables belong to the action: a variable set inside a \`when\` or \`forEach\` block is the
3482
+ same variable outside it, so it keeps its value after \`endWhen\` or \`endForEach\`, and
3483
+ variables set before the block can be read and changed inside it. Read variables with
3484
+ \`$scope.variables.<name>\`.`,
3485
+ category: `Data`,
3486
+ properties: {
3487
+ name: {
3488
+ type: "ParameterType:string",
3489
+ required: true,
3490
+ erased: true
3491
+ },
3492
+ value: {
3493
+ type: "ParameterType:object|ParameterType:string|ParameterType:number|ParameterType:boolean|ParameterType:array",
3494
+ required: true,
3495
+ erased: true
3496
+ }
3497
+ }
3498
+ };
3499
+ }
3500
+
3501
+ // src/operation/metadata/sort-array.ts
3502
+ function sortArray() {
3503
+ return {
3504
+ description: `Sorts an array by property, natural order, or custom comparator function.
3505
+
3506
+ Operates on arrayData passed from previous operations.
3507
+ Supports three sorting modes:
3508
+ 1. Property sort: \`sortProperty\` and \`sortOrder\` to sort objects by property
3509
+ 2. Natural sort: \`sortOrder\` alone for primitive arrays
3510
+ 3. Custom comparator: \`sortComparator\` function for complex sorting logic`,
3511
+ category: `Array`,
3512
+ dependentProperties: ["arrayData"],
3513
+ properties: {
3514
+ sortProperty: {
3515
+ type: "ParameterType:string",
3516
+ erased: true
3517
+ },
3518
+ sortOrder: {
3519
+ type: [{ value: "asc" }, { value: "desc" }],
3520
+ erased: true
3521
+ },
3522
+ sortComparator: {
3523
+ type: "ParameterType:function",
3524
+ erased: true
3525
+ }
3526
+ },
3527
+ outputProperties: { sortedArray: { type: "ParameterType:array" } }
3528
+ };
3529
+ }
3530
+
3531
+ // src/operation/metadata/split-string.ts
3532
+ function splitString() {
3533
+ return {
3534
+ description: `Splits a string into an array by delimiter (string or regex).`,
3535
+ category: `String`,
3536
+ dependentProperties: ["textContent"],
3537
+ properties: {
3538
+ delimiter: {
3539
+ type: "ParameterType:string|ParameterType:RegExp",
3540
+ required: true,
3541
+ erased: true
3542
+ },
3543
+ limit: {
3544
+ type: "ParameterType:number",
3545
+ erased: true
3546
+ }
3547
+ },
3548
+ outputProperties: { resultArray: {
3549
+ type: "ParameterType:array",
3550
+ itemType: "ParameterType:string"
3551
+ } }
3552
+ };
3553
+ }
3554
+
3555
+ // src/operation/metadata/start-action.ts
3556
+ function startAction() {
3557
+ return {
3558
+ description: `This operation starts the specified action instance using the given action operation data.
3559
+
3560
+ The action receives its own copy of the current operation data merged with the action
3561
+ operation data. Whatever the action's operations add, change or remove in that copy stays
3562
+ with the action: once it has completed, this operation continues with the operation data it
3563
+ had before, plus \`actionInstance\`, without the \`actionOperationData\` property.`,
3564
+ category: `Action`,
3565
+ dependentProperties: ["actionInstance"],
3566
+ properties: { actionOperationData: {
3567
+ type: "ParameterType:object",
3568
+ erased: true
3569
+ } }
3570
+ };
3571
+ }
3572
+
3573
+ // src/operation/metadata/substring-text.ts
3574
+ function substringText() {
3575
+ return {
3576
+ description: `Extracts a substring from text between start and end indices.`,
3577
+ category: `Text`,
3578
+ dependentProperties: ["textContent"],
3579
+ properties: {
3580
+ start: {
3581
+ type: "ParameterType:number",
3582
+ required: true,
3583
+ erased: true
3584
+ },
3585
+ end: {
3586
+ type: "ParameterType:number",
3587
+ erased: true
3588
+ }
3589
+ },
3590
+ outputProperties: { substring: { type: "ParameterType:string" } }
3591
+ };
3592
+ }
3593
+
3594
+ // src/operation/metadata/toggle-class.ts
3595
+ function toggleClass() {
3596
+ return {
3597
+ description: `This operation toggles the specfied class name on the given selected element.
3598
+
3599
+ Meaning, if the specified class name exists on the given element it will be removed,
3600
+ otherwise it will be added.`,
3601
+ category: `DOM`,
3602
+ dependentProperties: ["selectedElement"],
3603
+ properties: { className: {
3604
+ type: "ParameterType:className",
3605
+ required: true,
3606
+ erased: true
3607
+ } }
3608
+ };
3609
+ }
3610
+
3611
+ // src/operation/metadata/toggle-element.ts
3612
+ function toggleElement() {
3613
+ return {
3614
+ description: `This operation toggles the visibility of the given selected element.
3615
+
3616
+ Meaning, if the element is hidden, it will be made visible, otherwise
3617
+ it will be hidden.`,
3618
+ category: `DOM`,
3619
+ dependentProperties: ["selectedElement"]
3620
+ };
3621
+ }
3622
+
3623
+ // src/operation/metadata/toggle-form-element.ts
3624
+ function toggleFormElement() {
3625
+ return {
3626
+ description: `Enables or disables form input elements (inputs, selects, textareas, buttons).
3627
+
3628
+ Sets the \`disabled\` property on the element. When \`enabled\` is true, removes the disabled
3629
+ attribute; when false, adds the disabled attribute.`,
3630
+ category: `Form`,
3631
+ dependentProperties: ["selectedElement"],
3632
+ properties: { enabled: {
3633
+ type: "ParameterType:boolean",
3634
+ required: true,
3635
+ erased: true
3636
+ } }
3637
+ };
3638
+ }
3639
+
3640
+ // src/operation/metadata/validate-form.ts
3641
+ function validateForm() {
3642
+ return {
3643
+ description: `Validates form fields against HTML5 validation and custom rules.
3644
+
3645
+ Uses HTML5 validation API (checkValidity()) for native validation, and supports
3646
+ custom validation rules for: required, minLength, maxLength, pattern (regex), and email format.
3647
+
3648
+ Checkboxes and radio buttons are validated once per name: \`required\` passes when at least one
3649
+ of them is checked, and the string rules do not apply to them. For a \`<select multiple>\`,
3650
+ \`required\`, \`minLength\` and \`maxLength\` count the selected options, and \`pattern\` and \`email\`
3651
+ apply to each selected value.`,
3652
+ category: `Form`,
3653
+ dependentProperties: ["selectedElement"],
3654
+ properties: { validationRules: {
3655
+ type: "ParameterType:object",
3656
+ erased: true
3657
+ } },
3658
+ outputProperties: {
3659
+ validationErrors: { type: "ParameterType:object" },
3660
+ isValid: { type: "ParameterType:boolean" }
3661
+ }
3662
+ };
3663
+ }
3664
+
3665
+ // src/operation/metadata/wait.ts
3666
+ function wait() {
3667
+ return {
3668
+ description: `This operation waits for the specified amount of milliseconds.`,
3669
+ category: `Utility`,
3670
+ properties: { milliseconds: {
3671
+ type: "ParameterType:number",
3672
+ required: true,
3673
+ erased: true
3674
+ } }
3675
+ };
3676
+ }
3677
+
3678
+ // src/operation/metadata/when.ts
3679
+ function when() {
3680
+ return {
3681
+ description: `When the given expression evaluates to false, subsequent operations will be skipped
3682
+ until an {@link endWhen} or {@link otherwise} operation is encountered.
3683
+
3684
+ Practically, this means an \`if\` or \`if\`/\`else\` statement control flow implementation in a list of operations.
3685
+
3686
+ The expression is passed in as a formatted string. An operand can be one of:
3687
+
3688
+ 'constant': for a constant string (operators and parentheses inside the quotes are text)
3689
+ 100: for a constant number (the whole operand must be numeric, \`10px\` is invalid)
3690
+ true, false, null: for a boolean or null constant
3691
+ $operationData.foo: for an operation data value
3692
+ $globaldata.foo: for a global data value
3693
+ $scope.loopIndex: for a scope value
3694
+ $scope.variables.foo: for a variable set with \`setVariable\`
3695
+
3696
+ Any other operand is an error, so a misspelled chain prefix fails instead of being compared
3697
+ as a string.
3698
+
3699
+ Operands are combined with these operators, from highest to lowest precedence:
3700
+
3701
+ \`!\`: negation
3702
+ \`==\`, \`!=\`, \`>\`, \`<\`, \`>=\`, \`<=\`: comparison (\`==\` and \`!=\` compare strictly, without type
3703
+ conversion; comparisons do not chain, so write \`0<$scope.loopIndex && $scope.loopIndex<5\`)
3704
+ \`&&\`: and
3705
+ \`||\`: or
3706
+
3707
+ Parentheses group. A bare operand is true when its value is truthy, so \`'false'\` and \`'0'\`
3708
+ are true and \`0\`, \`''\`, \`null\` and a missing value are false. \`!\`, \`&&\` and \`||\` always
3709
+ produce \`true\` or \`false\`. \`!\` binds tighter than a comparison: \`!$operationdata.a==1\`
3710
+ compares \`!$operationdata.a\` with 1, write \`!($operationdata.a==1)\` to negate the comparison.
3711
+ \`&&\` and \`||\` short-circuit: when the left side decides the result, the right side is not
3712
+ resolved, so \`$operationdata.user && $operationdata.user.name=='John'\` does not fail when
3713
+ \`user\` is missing.
3714
+
3715
+ Arithmetic (\`+\`, \`-\`, \`*\`, \`/\`) is not supported: \`-\` is a valid character in a property
3716
+ chain, so \`$operationdata.a-1\` would be ambiguous. Nothing in the expression is executed as
3717
+ code, and property chains are resolved with the usual prototype-pollution and global-object
3718
+ guards.`,
3719
+ category: `Control Flow`,
3720
+ properties: { expression: {
3721
+ type: "ParameterType:expression",
3722
+ required: true,
3723
+ erased: true
3724
+ } }
3725
+ };
3726
+ }
3727
+
3728
+ // src/operation/metadata/index.ts
3729
+ var metadata_exports = /* @__PURE__ */ __exportAll({
3730
+ addClass: () => addClass,
3731
+ addControllerToElement: () => addControllerToElement,
3732
+ addGlobalsToOperation: () => addGlobalsToOperation,
3733
+ animate: () => animate,
3734
+ animateWithClass: () => animateWithClass,
3735
+ announceToScreenReader: () => announceToScreenReader,
3736
+ breakForEach: () => breakForEach,
3737
+ broadcastEvent: () => broadcastEvent,
3738
+ calc: () => calc,
3739
+ clearElement: () => clearElement,
3740
+ clearOperationData: () => clearOperationData,
3741
+ clearStorage: () => clearStorage,
3742
+ compareDate: () => compareDate,
3743
+ concatenateStrings: () => concatenateStrings,
3744
+ continueForEach: () => continueForEach,
3745
+ createElement: () => createElement,
3746
+ customFunction: () => customFunction,
3747
+ endAction: () => endAction,
3748
+ endForEach: () => endForEach,
3749
+ endWhen: () => endWhen,
3750
+ extendController: () => extendController,
3751
+ filterArray: () => filterArray,
3752
+ findInArray: () => findInArray,
3753
+ forEach: () => forEach,
3754
+ formatDate: () => formatDate,
3755
+ formatText: () => formatText,
3756
+ getAttributesFromElement: () => getAttributesFromElement,
3757
+ getControllerFromElement: () => getControllerFromElement,
3758
+ getControllerInstance: () => getControllerInstance,
3759
+ getCurrentTime: () => getCurrentTime,
3760
+ getElementDimensions: () => getElementDimensions,
3761
+ getFocusedElement: () => getFocusedElement,
3762
+ getFormData: () => getFormData,
3763
+ getImport: () => getImport,
3764
+ getQueryParams: () => getQueryParams,
3765
+ getScrollPosition: () => getScrollPosition,
3766
+ getTextContent: () => getTextContent,
3767
+ httpDelete: () => httpDelete,
3768
+ httpPost: () => httpPost,
3769
+ httpPut: () => httpPut,
3770
+ invokeObjectMethod: () => invokeObjectMethod,
3771
+ isElementInViewport: () => isElementInViewport,
3772
+ loadFromStorage: () => loadFromStorage,
3773
+ loadJson: () => loadJson,
3774
+ log: () => log,
3775
+ mapArray: () => mapArray,
3776
+ math: () => math,
3777
+ otherwise: () => otherwise,
3778
+ removeClass: () => removeClass,
3779
+ removeControllerFromElement: () => removeControllerFromElement,
3780
+ removeElement: () => removeElement,
3781
+ removePropertiesFromOperationData: () => removePropertiesFromOperationData,
3782
+ reparentElement: () => reparentElement,
3783
+ replaceString: () => replaceString,
3784
+ replaceText: () => replaceText,
3785
+ requestAction: () => requestAction,
3786
+ saveToStorage: () => saveToStorage,
3787
+ scrollToElement: () => scrollToElement,
3788
+ scrollToPosition: () => scrollToPosition,
3789
+ selectElement: () => selectElement,
3790
+ setData: () => setData,
3791
+ setElementAttributes: () => setElementAttributes,
3792
+ setElementContent: () => setElementContent,
3793
+ setFocus: () => setFocus,
3794
+ setFormValue: () => setFormValue,
3795
+ setGlobalData: () => setGlobalData,
3796
+ setOperationData: () => setOperationData,
3797
+ setStyle: () => setStyle,
3798
+ setVariable: () => setVariable,
3799
+ sortArray: () => sortArray,
3800
+ splitString: () => splitString,
3801
+ startAction: () => startAction,
3802
+ substringText: () => substringText,
3803
+ toggleClass: () => toggleClass,
3804
+ toggleElement: () => toggleElement,
3805
+ toggleFormElement: () => toggleFormElement,
3806
+ validateForm: () => validateForm,
3807
+ wait: () => wait,
3808
+ when: () => when
3809
+ });
3810
+
3811
+ // src/lint/built-in-names.ts
3812
+ /**
3813
+ * The names `EligiusResourceImporter` lists, without importing the
3814
+ * implementations: the linter must stay free of jquery and lottie-web.
3815
+ *
3816
+ * Operation and controller names come from the generated metadata. The
3817
+ * timeline provider exports have no metadata, so they are listed here, in
3818
+ * the order of `src/timelineproviders/index.ts`; the conformance test in
3819
+ * `src/test/unit/lint/built-in-names.spec.ts` keeps the three lists equal to
3820
+ * what the runtime importer returns.
3821
+ */
3822
+ const builtInOperationNames = Object.keys(metadata_exports);
3823
+ const builtInControllerNames = Object.keys(metadata_exports$1);
3824
+ const builtInProviderNames = [
3825
+ "isSeekable",
3826
+ "BasePositionSource",
3827
+ "KeyboardStepSource",
3828
+ "RafPositionSource",
3829
+ "ScrollPositionSource",
3830
+ "VideoPositionSource",
3831
+ "DomContainerProvider",
3832
+ "SimplePlaylist"
3833
+ ];
3834
+
3835
+ // src/lint/lint-importer.ts
3836
+ function stubOperation(operationData) {
3837
+ return operationData;
3838
+ }
3839
+ function stubFunction() {}
3840
+ var StubController = class {
3841
+ name = "StubController";
3842
+ init() {}
3843
+ attach() {}
3844
+ detach() {}
3845
+ };
3846
+ var StubProvider = class {};
3847
+ /**
3848
+ * Creates the importer the linter runs the real `ConfigurationResolver` with.
3849
+ * It serves a stand-in for every built-in and declared name, so the resolver
3850
+ * does the same name checks it does at runtime, without loading jquery or
3851
+ * lottie-web.
3852
+ *
3853
+ * @param options - The declared custom resources
3854
+ * @param placeholders - The placeholder names found in the configuration
3855
+ */
3856
+ function createLintImporter(options, placeholders) {
3857
+ const operations = [...builtInOperationNames, ...options.customOperations ?? []];
3858
+ const controllers = [...builtInControllerNames, ...options.customControllers ?? []];
3859
+ const providers = [...builtInProviderNames, ...options.customProviders ?? []];
3860
+ const functions = [...options.customFunctions ?? []];
3861
+ const operationSet = new Set(operations);
3862
+ const controllerSet = new Set(controllers);
3863
+ const providerSet = new Set(providers);
3864
+ const functionSet = new Set(functions);
3865
+ const placeholderValue = (kind, name, fallback) => {
3866
+ const declared = options[kind];
3867
+ if (declared === void 0) return fallback;
3868
+ const names = Array.isArray(declared) ? declared : Object.keys(declared);
3869
+ if (!names.includes(name)) {
3870
+ const what = kind === "templates" ? "template" : "JSON value";
3871
+ const didYouMean = formatDidYouMean(findClosestNames(name, names));
3872
+ throw new Error(`eligius/lint: unknown ${what} '${name}'. ${didYouMean || `Add it to the '${kind}' lint option.`}`);
3873
+ }
3874
+ return Array.isArray(declared) ? fallback : declared[name];
3875
+ };
3876
+ return {
3877
+ getOperationNames: () => [...operations],
3878
+ getControllerNames: () => [...controllers],
3879
+ getProviderNames: () => [...providers],
3880
+ getFunctionNames: () => [...functions],
3881
+ import(name) {
3882
+ if (operationSet.has(name)) return { [name]: stubOperation };
3883
+ if (controllerSet.has(name)) return { [name]: StubController };
3884
+ if (providerSet.has(name)) return { [name]: StubProvider };
3885
+ if (functionSet.has(name)) return { [name]: stubFunction };
3886
+ if (placeholders.templates.has(name)) return { [name]: placeholderValue("templates", name, "") };
3887
+ if (placeholders.json.has(name)) return { [name]: placeholderValue("json", name, {}) };
3888
+ const didYouMean = formatDidYouMean(findClosestNames(String(name), [
3889
+ ...operations,
3890
+ ...controllers,
3891
+ ...providers,
3892
+ ...functions
3893
+ ]));
3894
+ throw new Error(`eligius/lint: unknown system name '${name}'.${didYouMean ? ` ${didYouMean}` : ""}`);
3895
+ }
3896
+ };
3897
+ }
3898
+
3899
+ // src/lint/operation-lists.ts
3900
+ /**
3901
+ * True when `value` is shaped like an operation configuration: a plain
3902
+ * object with a string `systemName`.
3903
+ */
3904
+ function isOperationConfiguration(value) {
3905
+ return isPlainObject(value) && typeof value.systemName === "string";
3906
+ }
3907
+ /**
3908
+ * Collects every operation list of the configuration in document order.
3909
+ * Values that are not arrays are skipped; the resolver reports those.
3910
+ */
3911
+ function collectOperationLists(configuration) {
3912
+ const lists = [];
3913
+ const add = (owner, path, key, startsEmpty) => {
3914
+ if (isPlainObject(owner) && Array.isArray(owner[key])) lists.push({
3915
+ operations: owner[key],
3916
+ path: `${path}.${key}`,
3917
+ startsEmpty
3918
+ });
3919
+ };
3920
+ const addEndable = (owner, path, startsEmpty, withEnd) => {
3921
+ add(owner, path, "startOperations", startsEmpty);
3922
+ if (withEnd) add(owner, path, "endOperations", startsEmpty);
3923
+ };
3924
+ const each = (items, path, visit) => {
3925
+ if (Array.isArray(items)) items.forEach((item, index) => visit(item, `${path}[${index}]`));
3926
+ };
3927
+ each(configuration.initActions, "initActions", (action, path) => addEndable(action, path, true, true));
3928
+ each(configuration.actions, "actions", (action, path) => addEndable(action, path, false, true));
3929
+ each(configuration.eventActions, "eventActions", (action, path) => addEndable(action, path, false, false));
3930
+ each(configuration.timelines, "timelines", (timeline, path) => {
3931
+ if (isPlainObject(timeline)) each(timeline.timelineActions, `${path}.timelineActions`, (action, p) => addEndable(action, p, true, true));
3932
+ });
3933
+ return lists;
3934
+ }
3935
+
3936
+ // src/lint/operation-metadata.ts
3937
+ const factories = metadata_exports;
3938
+ const cache = /* @__PURE__ */ new Map();
3939
+ /**
3940
+ * Returns the generated metadata of a built-in operation, or undefined for
3941
+ * any other name. The metadata is created once per name.
3942
+ */
3943
+ function getOperationMetadata(systemName) {
3944
+ if (!Object.hasOwn(factories, systemName)) return;
3945
+ let metadata = cache.get(systemName);
3946
+ if (metadata === void 0) {
3947
+ metadata = factories[systemName]();
3948
+ cache.set(systemName, metadata);
3949
+ }
3950
+ return metadata;
3951
+ }
3952
+ function isRequiredProperty(property) {
3953
+ return typeof property === "object" && property.required === true;
3954
+ }
3955
+ function isErasedProperty(property) {
3956
+ return typeof property === "object" && property.erased === true;
3957
+ }
3958
+ /**
3959
+ * The values a property restricted to a literal union accepts, or undefined
3960
+ * when the property takes any value of its type.
3961
+ */
3962
+ function literalValuesOf(property) {
3963
+ if (typeof property !== "object" || !Array.isArray(property.type)) return;
3964
+ return property.type.map((constant) => constant.value);
3965
+ }
3966
+ const producersByProperty = /* @__PURE__ */ new Map();
3967
+ /**
3968
+ * The built-in operations whose `outputProperties` include `property`, for
3969
+ * the hint in a missing-dependency warning.
3970
+ */
3971
+ function findProducers(property) {
3972
+ let producers = producersByProperty.get(property);
3973
+ if (producers === void 0) {
3974
+ producers = Object.keys(factories).filter((name) => {
3975
+ const output = getOperationMetadata(name)?.outputProperties;
3976
+ return output !== void 0 && Object.hasOwn(output, property);
3977
+ });
3978
+ producersByProperty.set(property, producers);
3979
+ }
3980
+ return producers;
3981
+ }
3982
+
3983
+ // src/lint/resolving-fields.ts
3984
+ /**
3985
+ * The operation data fields in which an operation resolves `$operationdata.`,
3986
+ * `$globaldata.` and `$scope.` property chains. A chain in any other field of
3987
+ * any operation is passed on as text, which the linter reports (W150).
3988
+ *
3989
+ * This list is maintained by hand. The conformance test in
3990
+ * `src/test/unit/lint/resolving-fields.spec.ts` checks that exactly the
3991
+ * operations listed here import a chain-resolving helper, so a new resolving
3992
+ * operation cannot be forgotten and a removed one cannot linger.
3993
+ */
3994
+ const RESOLVING_FIELDS = {
3995
+ broadcastEvent: ["eventArgs"],
3996
+ calc: [
3997
+ "left",
3998
+ "right",
3999
+ "operator"
4000
+ ],
4001
+ createElement: [
4002
+ "elementName",
4003
+ "attributes",
4004
+ "text"
4005
+ ],
4006
+ forEach: ["collection"],
4007
+ math: ["args", "functionName"],
4008
+ selectElement: ["selector"],
4009
+ setData: ["properties"],
4010
+ setOperationData: ["properties"],
4011
+ setStyle: ["properties"],
4012
+ when: ["expression"]
4013
+ };
4014
+ /**
4015
+ * True when `systemName` resolves chains in its `field`.
4016
+ */
4017
+ function resolvesField(systemName, field) {
4018
+ return Object.hasOwn(RESOLVING_FIELDS, systemName) && RESOLVING_FIELDS[systemName].includes(field);
4019
+ }
4020
+
4021
+ // src/lint/rules.ts
4022
+ /**
4023
+ * Scope fields the engine uses to run an action. Writing them with `setData`
4024
+ * breaks the action; `newIndex` is left out because writing it is the
4025
+ * documented way to jump.
4026
+ */
4027
+ const RESERVED_SCOPE_KEYS = /* @__PURE__ */ new Set([
4028
+ "eventbus",
4029
+ "operations",
4030
+ "currentIndex",
4031
+ "parent",
4032
+ "owner",
4033
+ "loopIndex",
4034
+ "loopLength",
4035
+ "loopStartIndex",
4036
+ "loopEndIndex"
4037
+ ]);
4038
+ const DATA_TARGETS = [
4039
+ "scope",
4040
+ "operationdata",
4041
+ "globaldata"
4042
+ ];
4043
+ const identifierPattern = /^[A-Za-z_$][\w$]*$/;
4044
+ /**
4045
+ * Appends a key to a JSON path, in the resolver's notation: dots for plain
4046
+ * keys, brackets for everything else.
4047
+ */
4048
+ function childPath(path, key) {
4049
+ if (typeof key === "number") return `${path}[${key}]`;
4050
+ return identifierPattern.test(key) ? `${path}.${key}` : `${path}['${key.replace(/'/g, "\\'")}']`;
4051
+ }
4052
+ /**
4053
+ * The operation data keys that are known to be present when an operation
4054
+ * runs, following the list from its start. It never removes a key: a key
4055
+ * erased or cleared inside a branch may still be present on another path,
4056
+ * so the rules only report what is missing on every path.
4057
+ */
4058
+ var DataFlow = class {
4059
+ _known = /* @__PURE__ */ new Set();
4060
+ /**
4061
+ * True once the data can hold anything: the list started with caller-owned
4062
+ * data, or an operation ran whose effect on the data is not described.
4063
+ */
4064
+ _unknown;
4065
+ constructor(startsEmpty) {
4066
+ this._unknown = !startsEmpty;
4067
+ }
4068
+ /** True when the absence of a key is certain, not merely undescribed */
4069
+ get certain() {
4070
+ return !this._unknown;
4071
+ }
4072
+ has(key) {
4073
+ return this._known.has(key);
4074
+ }
4075
+ /**
4076
+ * Records what `operation` leaves in the data for the operations after it.
4077
+ */
4078
+ after(operation, data, metadata) {
4079
+ if (metadata === void 0) this._unknown = true;
4080
+ switch (operation.systemName) {
4081
+ case "setOperationData":
4082
+ if (data && isPlainObject(data.properties)) for (const key of Object.keys(data.properties)) this._known.add(key);
4083
+ break;
4084
+ case "setData":
4085
+ if (data && isPlainObject(data.properties)) for (const target of Object.keys(data.properties)) {
4086
+ const segments = target.split(".");
4087
+ if (segments[0].toLowerCase() === "$operationdata" && segments.length === 2) this._known.add(segments[1]);
4088
+ }
4089
+ break;
4090
+ case "addGlobalsToOperation":
4091
+ if (data && Array.isArray(data.globalProperties)) {
4092
+ for (const name of data.globalProperties) if (typeof name === "string") this._known.add(name);
4093
+ }
4094
+ break;
4095
+ case "customFunction":
4096
+ case "startAction":
4097
+ case "endAction": this._unknown = true;
4098
+ }
4099
+ if (metadata?.outputProperties) for (const key of Object.keys(metadata.outputProperties)) this._known.add(key);
4100
+ if (data) {
4101
+ for (const key of Object.keys(data)) if (data[key] !== void 0 && !isErasedProperty(metadata?.properties?.[key])) this._known.add(key);
4102
+ }
4103
+ }
4104
+ };
4105
+ /**
4106
+ * Runs every operation-level rule over one operation list.
4107
+ */
4108
+ function lintOperationList(list, context) {
4109
+ const report = (code, severity, path, message) => {
4110
+ context.diagnostics.push({
4111
+ code,
4112
+ severity,
4113
+ path,
4114
+ message
4115
+ });
4116
+ };
4117
+ const systemNames = list.operations.map((operation) => isOperationConfiguration(operation) ? operation.systemName : "");
4118
+ for (const problem of findFlowControlProblems(systemNames)) report("E101", "error", childPath(childPath(list.path, problem.index), "systemName"), `${problem.message} The engine pops the wrong scope at runtime, and the action fails or runs with the wrong data.`);
4119
+ const flow = new DataFlow(list.startsEmpty);
4120
+ list.operations.forEach((operation, index) => {
4121
+ if (!isOperationConfiguration(operation)) return;
4122
+ const { systemName } = operation;
4123
+ const operationPath = childPath(list.path, index);
4124
+ const dataPath = childPath(operationPath, "operationData");
4125
+ const data = isPlainObject(operation.operationData) ? operation.operationData : void 0;
4126
+ const metadata = getOperationMetadata(systemName);
4127
+ const isCustom = context.customOperations.has(systemName);
4128
+ const hasOwnData = (key) => data !== void 0 && Object.hasOwn(data, key) && data[key] !== void 0;
4129
+ const isAvailable = (key) => flow.has(key) || hasOwnData(key);
4130
+ const reportUnknownRead = (chain, head, path) => {
4131
+ if (flow.certain && head !== "" && !isAvailable(head)) report("W151", "warning", path, `${systemName}: '${chain}' reads '${head}' from the operation data, but no operation before it in this list provides '${head}'.`);
4132
+ };
4133
+ if (data !== void 0) {
4134
+ walkData(data, dataPath, (value, path) => {
4135
+ if (isPlainObject(value) && Object.hasOwn(value, "__proto__")) report("E141", "error", childPath(path, "__proto__"), `${systemName}: operation data must not contain a '__proto__' key. The engine rejects the operation when it runs.`);
4136
+ });
4137
+ walkData(data, dataPath, (value, path, topKey) => {
4138
+ if (typeof value !== "string" || topKey === void 0) return;
4139
+ if (systemName === "when" && topKey === "expression") return;
4140
+ const parsed = getParsedChain(value);
4141
+ if (parsed === null) return;
4142
+ if (parsed.forbidden !== void 0) {
4143
+ report("E140", "error", path, `${systemName}: property chain '${value}' contains forbidden segment '${parsed.forbidden.segment}'. Property chains may not contain __proto__, prototype or constructor.`);
4144
+ return;
4145
+ }
4146
+ if (!resolvesField(systemName, topKey)) {
4147
+ if (!isCustom && metadata !== void 0) report("W150", "warning", path, `${systemName}: '${value}' in '${topKey}' is passed on as text, ${systemName} does not resolve property chains in '${topKey}'. Resolve it first with setOperationData, or use a literal value.`);
4148
+ return;
4149
+ }
4150
+ if (parsed.prefix === "operationdata") reportUnknownRead(value, parsed.segments[0] ?? "", path);
4151
+ });
4152
+ }
4153
+ if (systemName === "when") lintWhen(data, dataPath, report, reportUnknownRead);
4154
+ if (systemName === "setData") lintSetData(data, dataPath, report, reportUnknownRead);
4155
+ if (systemName === "requestAction") lintRequestAction(data, dataPath, context, report);
4156
+ if (metadata !== void 0) {
4157
+ for (const [key, property] of Object.entries(metadata.properties ?? {})) if (isRequiredProperty(property) && !isAvailable(key)) report(flow.certain ? "E111" : "W111", flow.certain ? "error" : "warning", dataPath, `${systemName}: '${key}' is required, and neither its operation data nor an operation before it in this list provides it.`);
4158
+ for (const [key, property] of Object.entries(metadata.properties ?? {})) {
4159
+ const values = literalValuesOf(property);
4160
+ const value = data?.[key];
4161
+ if (values !== void 0 && typeof value === "string" && getParsedChain(value) === null && !values.includes(value)) report("E120", "error", childPath(dataPath, key), `${systemName}: '${key}' must be one of ${values.map((v) => `'${v}'`).join(", ")}, got '${value}'.`);
4162
+ }
4163
+ for (const dependency of metadata.dependentProperties ?? []) {
4164
+ const key = String(dependency);
4165
+ if (flow.certain && !isAvailable(key)) {
4166
+ const producers = findProducers(key);
4167
+ const hint = producers.length > 0 ? ` Operations that provide it: ${producers.slice(0, 4).join(", ")}.` : "";
4168
+ report("W110", "warning", operationPath, `${systemName}: '${key}' must be provided by an earlier operation in this list, but none before it provides it.${hint}`);
4169
+ }
4170
+ }
4171
+ }
4172
+ flow.after(operation, data, metadata);
4173
+ });
4174
+ }
4175
+ function lintWhen(data, dataPath, report, reportUnknownRead) {
4176
+ const expression = data?.expression;
4177
+ if (expression === void 0) return;
4178
+ const path = childPath(dataPath, "expression");
4179
+ let parsed;
4180
+ try {
4181
+ parsed = parseExpression(expression, "when");
4182
+ } catch (error) {
4183
+ const message = error instanceof Error ? error.message : String(error);
4184
+ report(/unknown operand/.test(message) ? "E131" : "E130", "error", path, message);
4185
+ return;
4186
+ }
4187
+ for (const chain of collectChainOperands(parsed)) {
4188
+ const parsedChain = getParsedChain(chain);
4189
+ if (parsedChain === null) continue;
4190
+ if (parsedChain.forbidden !== void 0) report("E140", "error", path, `when: property chain '${chain}' contains forbidden segment '${parsedChain.forbidden.segment}'. Property chains may not contain __proto__, prototype or constructor.`);
4191
+ else if (parsedChain.prefix === "operationdata") reportUnknownRead(chain, parsedChain.segments[0] ?? "", path);
4192
+ }
4193
+ }
4194
+ function collectChainOperands(node) {
4195
+ switch (node.kind) {
4196
+ case "operand": return node.operand.kind === "chain" ? [node.operand.chain] : [];
4197
+ case "not": return collectChainOperands(node.operand);
4198
+ default: return [...collectChainOperands(node.left), ...collectChainOperands(node.right)];
4199
+ }
4200
+ }
4201
+ function lintSetData(data, dataPath, report, reportUnknownRead) {
4202
+ const properties = data?.properties;
4203
+ if (!isPlainObject(properties)) return;
4204
+ for (const target of Object.keys(properties)) {
4205
+ const path = childPath(childPath(dataPath, "properties"), target);
4206
+ const segments = target.split(".");
4207
+ const root = segments[0].toLowerCase().substring(1);
4208
+ if (!segments[0].startsWith("$") || !DATA_TARGETS.includes(root)) {
4209
+ report("E160", "error", path, `setData: unrecognized target '${target}'; a target starts with $scope, $operationdata or $globaldata.`);
4210
+ continue;
4211
+ }
4212
+ const rest = segments.slice(1);
4213
+ const forbidden = findForbiddenSegment(rest);
4214
+ if (forbidden !== void 0) {
4215
+ report("E140", "error", path, `setData: property chain '${target}' contains forbidden segment '${forbidden}'. Property chains may not contain __proto__, prototype or constructor.`);
4216
+ continue;
4217
+ }
4218
+ if (root === "scope" && rest.length === 1 && RESERVED_SCOPE_KEYS.has(rest[0])) report("W160", "warning", path, `setData: '${target}' overwrites '${rest[0]}', which the engine uses to run the action. Use $scope.variables.${rest[0]} for your own value.`);
4219
+ if (root === "operationdata" && rest.length > 1) reportUnknownRead(target, rest[0], path);
4220
+ }
4221
+ }
4222
+ function lintRequestAction(data, dataPath, context, report) {
4223
+ const name = data?.systemName;
4224
+ if (typeof name !== "string" || getParsedChain(name) !== null || context.actionNames.has(name)) return;
4225
+ const didYouMean = formatDidYouMean(findClosestNames(name, [...context.actionNames]));
4226
+ report("E310", "error", childPath(dataPath, "systemName"), `requestAction: there is no action named '${name}'. ${didYouMean || "Action names come from actions[].name and eventActions[].name."}`);
4227
+ }
4228
+ /**
4229
+ * Visits every value in the operation data, depth first, with its JSON path
4230
+ * and the top-level key it sits under.
4231
+ */
4232
+ function walkData(data, dataPath, visit) {
4233
+ const visiting = /* @__PURE__ */ new Set();
4234
+ const walk = (value, path, topKey) => {
4235
+ visit(value, path, topKey);
4236
+ if (value === null || typeof value !== "object" || visiting.has(value)) return;
4237
+ if (Array.isArray(value)) {
4238
+ visiting.add(value);
4239
+ value.forEach((item, index) => walk(item, childPath(path, index), topKey));
4240
+ visiting.delete(value);
4241
+ return;
4242
+ }
4243
+ if (!isPlainObject(value)) return;
4244
+ visiting.add(value);
4245
+ for (const key of Object.keys(value)) walk(value[key], childPath(path, key), topKey ?? key);
4246
+ visiting.delete(value);
4247
+ };
4248
+ walk(data, dataPath, void 0);
4249
+ }
4250
+
4251
+ // src/lint/lint-configuration.ts
4252
+ /**
4253
+ * Checks a configuration without a DOM and without running it, and returns
4254
+ * what the engine would reject or what is likely wrong.
4255
+ *
4256
+ * The real `ConfigurationResolver` runs first, with a stand-in for every
4257
+ * operation, controller and timeline provider, so every error it throws at
4258
+ * `createEngine` time is reported here with the same message and JSON path
4259
+ * (code `E001`). The structural and data-flow rules then run over every
4260
+ * operation list:
4261
+ *
4262
+ * - `E101` control-flow blocks that are not balanced or do not nest
4263
+ * - `E111` a required property that nothing provides (`W111` when the list
4264
+ * starts with caller-owned data)
4265
+ * - `E120` a literal outside its allowed values
4266
+ * - `E130`, `E131` a `when` expression that does not parse, an unknown operand
4267
+ * - `E140` a property chain with a forbidden segment
4268
+ * - `E141` a `__proto__` key in operation data
4269
+ * - `E160` an unrecognized `setData` target, `W160` a reserved scope field
4270
+ * - `E310` a `requestAction` name that no action has
4271
+ * - `W110` a dependency on an earlier operation that no earlier operation provides
4272
+ * - `W150` a property chain in a field the operation does not resolve
4273
+ * - `W151` an `$operationdata` read of a property that nothing provides
4274
+ *
4275
+ * Errors are certain: the engine throws, or the operation fails when it
4276
+ * runs. Warnings are likely mistakes. Data-flow warnings are only reported
4277
+ * for the operation lists that start with empty data (timeline actions and
4278
+ * init actions), and never after an operation whose effect on the data is
4279
+ * not described (a custom operation, `customFunction`, `startAction`).
4280
+ *
4281
+ * The configuration is not changed.
4282
+ *
4283
+ * @param configuration - The configuration to check
4284
+ * @param options - The custom resources the host registers, so their names
4285
+ * are accepted
4286
+ * @returns The diagnostics, resolver errors first, then in document order.
4287
+ * Empty when nothing was found.
4288
+ *
4289
+ * @example
4290
+ * ```ts
4291
+ * import {lintConfiguration} from 'eligius/lint';
4292
+ *
4293
+ * const diagnostics = lintConfiguration(configuration, {
4294
+ * customOperations: ['trackEvent'],
4295
+ * });
4296
+ * for (const {severity, code, path, message} of diagnostics) {
4297
+ * console.log(`${severity} ${code} at ${path}: ${message}`);
4298
+ * }
4299
+ * ```
4300
+ */
4301
+ function lintConfiguration(configuration, options = {}) {
4302
+ if (!isPlainObject(configuration)) return [{
4303
+ code: "E001",
4304
+ severity: "error",
4305
+ path: "",
4306
+ message: `The configuration must be an object, got ${describeKind(configuration)}.`
4307
+ }];
4308
+ const diagnostics = [];
4309
+ const copy = deepCopy(configuration);
4310
+ const importer = createLintImporter(options, collectPlaceholderNames(copy));
4311
+ const resolver = new ConfigurationResolver(importer, new Eventbus(), { onWarning: () => {} });
4312
+ try {
4313
+ resolver.process(copy, new ActionRegistryEventbusListener());
4314
+ } catch (error) {
4315
+ const message = error instanceof Error ? error.message : String(error);
4316
+ diagnostics.push({
4317
+ code: "E001",
4318
+ severity: "error",
4319
+ path: extractPath(message),
4320
+ message
4321
+ });
4322
+ }
4323
+ const context = {
4324
+ diagnostics,
4325
+ actionNames: collectActionNames(configuration),
4326
+ customOperations: new Set(options.customOperations ?? [])
4327
+ };
4328
+ for (const list of collectOperationLists(configuration)) lintOperationList(list, context);
4329
+ return diagnostics;
4330
+ }
4331
+ function describeKind(value) {
4332
+ if (value === null) return "null";
4333
+ if (Array.isArray(value)) return "an array";
4334
+ return typeof value === "undefined" ? "undefined" : `a ${typeof value}`;
4335
+ }
4336
+ const TOP_LEVEL_KEYS = /* @__PURE__ */ new Set([
4337
+ "id",
4338
+ "engine",
4339
+ "timelineProviderSettings",
4340
+ "containerSelector",
4341
+ "cssFiles",
4342
+ "language",
4343
+ "layoutTemplate",
4344
+ "availableLanguages",
4345
+ "initActions",
4346
+ "actions",
4347
+ "eventActions",
4348
+ "timelines",
4349
+ "timelineFlow",
4350
+ "locales"
4351
+ ]);
4352
+ const pathPattern = /\bat ((?:[A-Za-z_$][\w$]*)(?:\.[A-Za-z_$][\w$]*|\[\d+\]|\['[^']*'\])*)/g;
4353
+ /**
4354
+ * The JSON path a resolver message names: the first `at <path>` whose first
4355
+ * segment is a top-level configuration key.
4356
+ */
4357
+ function extractPath(message) {
4358
+ for (const match of message.matchAll(pathPattern)) {
4359
+ const path = match[1];
4360
+ const firstSegment = path.split(/[.[]/, 1)[0];
4361
+ if (TOP_LEVEL_KEYS.has(firstSegment)) return path.replace(/[.,:]$/, "");
4362
+ }
4363
+ return "";
4364
+ }
4365
+ function collectActionNames(configuration) {
4366
+ const names = /* @__PURE__ */ new Set();
4367
+ for (const list of [configuration.actions, configuration.eventActions]) if (Array.isArray(list)) {
4368
+ for (const action of list) if (isPlainObject(action) && typeof action.name === "string") names.add(action.name);
4369
+ }
4370
+ return names;
4371
+ }
4372
+ /**
4373
+ * The names the `template:` and `json:` placeholders of the configuration
4374
+ * ask the importer for. Walks what the resolver walks: plain objects and
4375
+ * arrays.
4376
+ */
4377
+ function collectPlaceholderNames(configuration) {
4378
+ const templates = /* @__PURE__ */ new Set();
4379
+ const json = /* @__PURE__ */ new Set();
4380
+ const visiting = /* @__PURE__ */ new Set();
4381
+ const walk = (value) => {
4382
+ if (typeof value === "string") {
4383
+ if (value.startsWith("template:")) templates.add(value.substring(9));
4384
+ else if (value.startsWith("json:")) json.add(value.substring(5));
4385
+ return;
4386
+ }
4387
+ if (value === null || typeof value !== "object" || visiting.has(value)) return;
4388
+ if (Array.isArray(value)) {
4389
+ visiting.add(value);
4390
+ value.forEach(walk);
4391
+ visiting.delete(value);
4392
+ } else if (isPlainObject(value)) {
4393
+ visiting.add(value);
4394
+ for (const key of Object.keys(value)) walk(value[key]);
4395
+ visiting.delete(value);
4396
+ }
4397
+ };
4398
+ walk(configuration);
4399
+ return {
4400
+ templates,
4401
+ json
4402
+ };
4403
+ }
4404
+
4405
+ export { findFlowControlProblems, lintConfiguration };
4406
+ //# sourceMappingURL=lint.mjs.map