@zvenigora/ng-eval-core 0.11.0 → 0.12.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.
@@ -1,7 +1,7 @@
1
1
  import * as i0 from '@angular/core';
2
- import { Injectable, inject } from '@angular/core';
2
+ import { InjectionToken, inject, makeEnvironmentProviders, provideEnvironmentInitializer, Injectable } from '@angular/core';
3
3
  import { sha256 } from 'js-sha256';
4
- import { parse as parse$1, defaultOptions, version } from 'acorn';
4
+ import { tokTypes, Parser, parse as parse$1, defaultOptions, version } from 'acorn';
5
5
  import * as walk from 'acorn-walk';
6
6
 
7
7
  /**
@@ -1119,8 +1119,13 @@ const literals = Registry.fromObject({
1119
1119
  * the source name stands in. The path is always the source spelling, since it
1120
1120
  * is reconstructed statically.
1121
1121
  *
1122
- * `scoped` marks a read of a name bound by a scope pushed *during this walk* -
1123
- * an arrow-function parameter. It is asked of `EvalContext.hasInScopes`, which
1122
+ * `scoped` marks a read of a name bound by any scope on the context's scope
1123
+ * stack when the name is read, whoever pushed it: an arrow-function
1124
+ * parameter, a declaration in the lexical scope `program.ts`,
1125
+ * `block-statement.ts` or `for-statement.ts` pushes, or a binding the caller
1126
+ * pushed with `EvalContext.push` before the walk - which is how `eval-signals`
1127
+ * binds a run's `AbortSignal` under `abortSignalKey`, and why that key never
1128
+ * reaches its `dependencies`. It is asked of `EvalContext.hasInScopes`, which
1124
1129
  * tests for the binding rather than for its value: a parameter bound to
1125
1130
  * `undefined` is still a parameter, and reading the flag off the resolved value
1126
1131
  * would make it vary with the data rather than with the expression.
@@ -1131,8 +1136,10 @@ const literals = Registry.fromObject({
1131
1136
  * than set to false, so absent reads as "not scoped" the same way it does at
1132
1137
  * the member emission sites.
1133
1138
  *
1134
- * The scope stack is empty for any expression without an arrow function, and
1135
- * `Stack.asArray` allocates, so the common case is short-circuited on length.
1139
+ * The scope stack is empty only for a walk that does not start at a `Program`
1140
+ * and has nothing pushed by its caller: `program.ts` pushes a scope at the root
1141
+ * of every walk through `EvalService`. `Stack.asArray` allocates, so that empty
1142
+ * case is short-circuited on length.
1136
1143
  */
1137
1144
  const emitRead = (node, st, value) => {
1138
1145
  const key = st.context?.getKey(node.name) ?? node.name;
@@ -1414,144 +1421,67 @@ const binaryExpressionVisitor = (node, st, callback) => {
1414
1421
  /**
1415
1422
  * Property Lookup Cache
1416
1423
  *
1417
- * Provides efficient caching for case-insensitive property lookups
1418
- * to avoid repeated O(n) searches through object property lists.
1424
+ * Remembers, per object, which own key a case-insensitive name resolved to,
1425
+ * so that a repeated read skips the O(n) scan of the object's own names.
1426
+ *
1427
+ * Keyed by the object itself (`docs/backlog-retired.md` A31). Up to 0.11.0 the
1428
+ * key was the object's own-key count and its first five own names, in one
1429
+ * cache for the whole process, so two objects that shared those answered for
1430
+ * each other: a read could return the wrong property, or `undefined`, and a
1431
+ * case variant of a blocked name read `undefined` instead of being refused.
1419
1432
  */
1433
+ // A `WeakMap`, so an entry lives exactly as long as its object, and nothing
1434
+ // one object answered can be read for another.
1435
+ let propertyLookupCache = new WeakMap();
1436
+ // Entries made since the last clear. A `WeakMap` cannot say how many are live.
1437
+ let entriesCreated = 0;
1420
1438
  /**
1421
- * Cache for property lookup results to optimize case-insensitive property access
1439
+ * Performs optimized case-insensitive property lookup with caching.
1440
+ *
1441
+ * A key found before is still the answer while it is still an own key of the
1442
+ * object, which is checked without a scan. One deleted or renamed since is
1443
+ * scanned for again. A miss stays a miss while the object's own-key count is
1444
+ * unchanged; a key added since changes the count, and the object's answers
1445
+ * are made afresh. Not caught: a key added in the same interval as another is
1446
+ * deleted, which leaves the count as it was, so a cached miss can outlive it.
1422
1447
  */
1423
- class PropertyLookupCache {
1424
- constructor(maxSize = 1000, expirationTimeMs = 5 * 60 * 1000) {
1425
- this._cache = new Map();
1426
- this._maxSize = maxSize;
1427
- this._expirationTime = expirationTimeMs;
1428
- }
1429
- /**
1430
- * Generates a simple hash for an object based on its own property names
1431
- */
1432
- generateObjectHash(obj) {
1433
- try {
1434
- const keys = Object.getOwnPropertyNames(obj);
1435
- return keys.length.toString() + '_' + keys.slice(0, 5).join('_');
1436
- }
1437
- catch {
1438
- return 'unknown_hash';
1439
- }
1440
- }
1441
- /**
1442
- * Generates a cache key for a property lookup
1443
- */
1444
- generateCacheKey(objectHash, searchKey) {
1445
- return `${objectHash}:${searchKey.toLowerCase()}`;
1446
- }
1447
- /**
1448
- * Checks if a cache entry is still valid
1449
- */
1450
- isEntryValid(entry, objectHash) {
1451
- const now = Date.now();
1452
- return (entry.objectHash === objectHash &&
1453
- (now - entry.lastAccessed) < this._expirationTime);
1454
- }
1455
- /**
1456
- * Cleans up expired entries and maintains cache size
1457
- */
1458
- cleanup() {
1459
- const now = Date.now();
1460
- const entries = Array.from(this._cache.entries());
1461
- // Remove expired entries
1462
- for (const [key, entry] of entries) {
1463
- if ((now - entry.lastAccessed) >= this._expirationTime) {
1464
- this._cache.delete(key);
1465
- }
1466
- }
1467
- // If still too large, remove oldest entries
1468
- if (this._cache.size > this._maxSize) {
1469
- const sortedEntries = Array.from(this._cache.entries())
1470
- .sort(([, a], [, b]) => a.lastAccessed - b.lastAccessed);
1471
- const entriesToRemove = sortedEntries.slice(0, this._cache.size - this._maxSize);
1472
- for (const [key] of entriesToRemove) {
1473
- this._cache.delete(key);
1474
- }
1475
- }
1476
- }
1477
- /**
1478
- * Gets a cached property lookup result
1479
- */
1480
- get(obj, searchKey) {
1481
- const objectHash = this.generateObjectHash(obj);
1482
- const cacheKey = this.generateCacheKey(objectHash, searchKey);
1483
- const entry = this._cache.get(cacheKey);
1484
- if (entry && this.isEntryValid(entry, objectHash)) {
1485
- // Update access time
1486
- entry.lastAccessed = Date.now();
1487
- return entry.foundKey;
1488
- }
1489
- return undefined; // Cache miss
1448
+ function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1449
+ if (!obj || typeof obj !== 'object') {
1450
+ return null;
1490
1451
  }
1491
- /**
1492
- * Sets a cached property lookup result
1493
- */
1494
- set(obj, searchKey, foundKey) {
1495
- // Perform cleanup periodically
1496
- if (this._cache.size > this._maxSize * 0.8) {
1497
- this.cleanup();
1498
- }
1499
- const objectHash = this.generateObjectHash(obj);
1500
- const cacheKey = this.generateCacheKey(objectHash, searchKey);
1501
- this._cache.set(cacheKey, {
1502
- foundKey,
1503
- lastAccessed: Date.now(),
1504
- objectHash
1505
- });
1452
+ const lowered = searchKey.toLowerCase();
1453
+ let entry = propertyLookupCache.get(obj);
1454
+ const cached = entry?.found.get(lowered);
1455
+ if (typeof cached === 'string' && Object.prototype.hasOwnProperty.call(obj, cached)) {
1456
+ return cached;
1506
1457
  }
1507
- /**
1508
- * Clears the entire cache
1509
- */
1510
- clear() {
1511
- this._cache.clear();
1458
+ const ownKeys = Object.getOwnPropertyNames(obj);
1459
+ if (!entry || entry.keyCount !== ownKeys.length) {
1460
+ entry = { keyCount: ownKeys.length, found: new Map() };
1461
+ propertyLookupCache.set(obj, entry);
1462
+ entriesCreated++;
1512
1463
  }
1513
- /**
1514
- * Gets current cache size
1515
- */
1516
- get size() {
1517
- return this._cache.size;
1464
+ else if (cached === null) {
1465
+ return null;
1518
1466
  }
1519
- }
1520
- // Global property lookup cache instance
1521
- const propertyLookupCache = new PropertyLookupCache();
1522
- /**
1523
- * Performs optimized case-insensitive property lookup with caching
1524
- */
1525
- function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1526
- // Try to get from cache first
1527
- const cachedResult = propertyLookupCache.get(obj, searchKey);
1528
- if (cachedResult !== undefined) {
1529
- return cachedResult;
1530
- }
1531
- // Cache miss - perform actual lookup
1532
- let foundKey = null;
1533
- if (obj && typeof obj === 'object') {
1534
- const ownKeys = Object.getOwnPropertyNames(obj);
1535
- const matchingKey = ownKeys.find(k => equalIgnoreCase(k, searchKey));
1536
- foundKey = matchingKey || null;
1537
- }
1538
- // Cache the result
1539
- propertyLookupCache.set(obj, searchKey, foundKey);
1467
+ const foundKey = ownKeys.find(k => equalIgnoreCase(k, searchKey)) || null;
1468
+ entry.found.set(lowered, foundKey);
1540
1469
  return foundKey;
1541
1470
  }
1542
1471
  /**
1543
1472
  * Clears the property lookup cache (for testing or memory management)
1544
1473
  */
1545
1474
  function clearPropertyLookupCache() {
1546
- propertyLookupCache.clear();
1475
+ propertyLookupCache = new WeakMap();
1476
+ entriesCreated = 0;
1547
1477
  }
1548
1478
  /**
1549
- * Gets current property lookup cache statistics
1479
+ * Gets current property lookup cache statistics: the number of objects given
1480
+ * an entry since the last clear, live or collected.
1550
1481
  */
1551
1482
  function getPropertyLookupCacheStats() {
1552
1483
  return {
1553
- size: propertyLookupCache.size,
1554
- maxSize: 1000 // This should match the maxSize in constructor
1484
+ size: entriesCreated
1555
1485
  };
1556
1486
  }
1557
1487
 
@@ -3076,16 +3006,211 @@ const updateExpressionVisitor = (node, st, callback) => {
3076
3006
  afterVisitor(node, st);
3077
3007
  };
3078
3008
 
3009
+ /**
3010
+ * @description
3011
+ * The colon-joined name grammar of `docs/colon-identifiers/phase-9-plan.md`
3012
+ * § 3.4, as an acorn plugin (§ 3.5). `parse` uses the parser built here when
3013
+ * `colonIdentifiers` is set, and acorn's own `parse` otherwise. No source text
3014
+ * is rewritten, so every position acorn reports is a position in what the
3015
+ * author wrote. Not re-exported from any barrel.
3016
+ *
3017
+ * Of acorn's documented API this module uses `Parser.extend`, `tokTypes` and
3018
+ * the `input` member. Everything else it touches is an acorn internal,
3019
+ * undeclared in acorn's `.d.ts`, and this is the complete list — what § 8 q3
3020
+ * checks at the `acorn` peer floor:
3021
+ *
3022
+ * - members read: `pos`, `start`, `type`, `value`, `keywords`;
3023
+ * - members written: `pos`, `containsEsc`;
3024
+ * - methods overridden, each calling acorn's own through `super`: `readWord`,
3025
+ * `finishToken`, `parsePropertyName`, `parseStatement`, `unexpected`;
3026
+ * - methods called: `finishToken`, `raise`;
3027
+ * - what the overrides assume of acorn's tokenizer: `readToken` is the only
3028
+ * caller of `readWord`, with `pos` at the token's first character; every
3029
+ * token is finished through `finishToken`, in source order, before the next
3030
+ * is read — except that a `/` read as `slash` is finished again as
3031
+ * `regexp`, and neither type is counted here; `?.`, `??` and `??=` are never
3032
+ * `question` tokens; the `}` that closes a `${` is finished as `braceR`; the
3033
+ * constructor reads no token;
3034
+ * - what they assume of acorn's parser: every key of an object literal, an
3035
+ * object pattern or a class body is read through `parsePropertyName`, with
3036
+ * the key as the current token; every statement through `parseStatement`,
3037
+ * with its first token as the current token; a colon the grammar cannot
3038
+ * place reaches `unexpected`, from `expect` or `semicolon`, with `type` and
3039
+ * `start` still at that colon.
3040
+ *
3041
+ * The token types it compares by identity, from `tokTypes`: `name`, `colon`,
3042
+ * `question`, `comma`, `semi`, `parenL`, `parenR`, `bracketL`, `bracketR`,
3043
+ * `braceL`, `braceR`, `dollarBraceL`.
3044
+ */
3045
+ const COLON = 58;
3046
+ /** `[A-Za-z_$]`: the first character of a name that may join. */
3047
+ const isFirstChar = (code) => (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95 || code === 36;
3048
+ /** `[A-Za-z0-9_$]`: any later character, and a segment's first. */
3049
+ const isSegmentChar = (code) => isFirstChar(code) || (code >= 48 && code <= 57);
3050
+ /** Whether a `:segment` starts at `pos`: a colon with a segment character after it. */
3051
+ const joinsAt = (input, pos) => input.charCodeAt(pos) === COLON && isSegmentChar(input.charCodeAt(pos + 1));
3052
+ const colonIdentifiers = (Base) => {
3053
+ class ColonParser extends Base {
3054
+ constructor() {
3055
+ super(...arguments);
3056
+ /** Never empty: the top level is never closed. */
3057
+ this.levels = [{ pending: 0 }];
3058
+ /**
3059
+ * The level the current token was read at: for a `(`, `[`, `{` or `${`,
3060
+ * the one around the level it opened.
3061
+ */
3062
+ this.tokenLevel = this.levels[0];
3063
+ }
3064
+ get level() {
3065
+ return this.levels[this.levels.length - 1];
3066
+ }
3067
+ /**
3068
+ * Reads a colon-joined name as one `name` token when one starts at `pos`
3069
+ * and no `?` at this level is waiting for its `:` (§ 3.4, 1). In every
3070
+ * other case acorn's own `readWord`, so a word that does not join is read
3071
+ * exactly as acorn reads it.
3072
+ */
3073
+ readWord() {
3074
+ const end = this.colonNameEnd();
3075
+ if (end === undefined) {
3076
+ return super.readWord();
3077
+ }
3078
+ const name = this.input.slice(this.pos, end);
3079
+ if (this.level.pending > 0) {
3080
+ this.level.suppressed = name;
3081
+ return super.readWord();
3082
+ }
3083
+ this.pos = end;
3084
+ this.containsEsc = false;
3085
+ this.finishToken(tokTypes.name, name);
3086
+ }
3087
+ /**
3088
+ * Where the colon name that starts at `pos` ends — its longest match — or
3089
+ * `undefined` when none does: the first segment is not ASCII, is a keyword
3090
+ * of the parse's `ecmaVersion`, or has no `:segment` directly after it.
3091
+ */
3092
+ colonNameEnd() {
3093
+ const input = this.input;
3094
+ let end = this.pos;
3095
+ if (!isFirstChar(input.charCodeAt(end))) {
3096
+ return undefined;
3097
+ }
3098
+ do {
3099
+ end++;
3100
+ } while (isSegmentChar(input.charCodeAt(end)));
3101
+ if (!joinsAt(input, end) || this.keywords.test(input.slice(this.pos, end))) {
3102
+ return undefined;
3103
+ }
3104
+ do {
3105
+ end += 2;
3106
+ while (isSegmentChar(input.charCodeAt(end))) {
3107
+ end++;
3108
+ }
3109
+ } while (joinsAt(input, end));
3110
+ return end;
3111
+ }
3112
+ /**
3113
+ * Keeps the levels after acorn has finished the token, recording the one
3114
+ * the token was read at: `(`, `[`, `{` and `${` open a level and `)`, `]`
3115
+ * and `}` close it; a `?` is counted at its level and a `:` there
3116
+ * uncounts it. `?.` and `??` are other token types, and count for nothing.
3117
+ */
3118
+ finishToken(type, value) {
3119
+ super.finishToken(type, value);
3120
+ const level = this.level;
3121
+ this.tokenLevel = level;
3122
+ switch (type) {
3123
+ case tokTypes.parenL:
3124
+ case tokTypes.bracketL:
3125
+ case tokTypes.braceL:
3126
+ case tokTypes.dollarBraceL:
3127
+ this.levels.push({ pending: 0 });
3128
+ break;
3129
+ case tokTypes.parenR:
3130
+ case tokTypes.bracketR:
3131
+ case tokTypes.braceR:
3132
+ if (this.levels.length > 1) {
3133
+ this.levels.pop();
3134
+ }
3135
+ break;
3136
+ case tokTypes.question:
3137
+ level.pending++;
3138
+ break;
3139
+ case tokTypes.colon:
3140
+ if (level.pending > 0) {
3141
+ level.pending--;
3142
+ }
3143
+ break;
3144
+ case tokTypes.comma:
3145
+ case tokTypes.semi:
3146
+ level.suppressed = undefined;
3147
+ break;
3148
+ }
3149
+ }
3150
+ /**
3151
+ * Refuses a colon name as an object key, in a literal or a pattern alike
3152
+ * (§ 3.4, 2): `{Q1:1}` is `{Q1: 1}` to JavaScript and a shorthand to the
3153
+ * grammar, and keeping either would answer some author wrongly. Only a
3154
+ * joined token is a `name` holding a colon.
3155
+ */
3156
+ parsePropertyName(prop) {
3157
+ const name = this.value;
3158
+ if (this.type === tokTypes.name && typeof name === 'string' && name.includes(':')) {
3159
+ const first = name.slice(0, name.indexOf(':'));
3160
+ this.raise(this.start, `Colon-joined name '${name}' cannot be an object key: ` +
3161
+ `write '${first}: ...' with a space for a property, or quote the key`);
3162
+ }
3163
+ return super.parsePropertyName(prop);
3164
+ }
3165
+ /**
3166
+ * Forgets the name not joined at the level a statement starts at: the
3167
+ * statement boundary ended the conditional whose consequent lost it. A
3168
+ * semicolon acorn inserts at a line break is such a boundary, and no `;`
3169
+ * token marks it.
3170
+ */
3171
+ parseStatement(...args) {
3172
+ this.tokenLevel.suppressed = undefined;
3173
+ return super.parseStatement(...args);
3174
+ }
3175
+ /**
3176
+ * acorn's own error, with the hint of § 3.4, 1 when the unexpected token
3177
+ * is a `:` at a level that did not join a name since its last `,`, `;` or
3178
+ * statement start: the colon the name lost to the conditional. Any other
3179
+ * error is left as acorn words it.
3180
+ */
3181
+ unexpected(pos) {
3182
+ const suppressed = this.tokenLevel.suppressed;
3183
+ if (suppressed !== undefined && this.type === tokTypes.colon &&
3184
+ (pos === undefined || pos === this.start)) {
3185
+ return this.raise(this.start, 'Unexpected token: a colon-joined name in the ' +
3186
+ `consequent of a conditional needs parentheses: (${suppressed})`);
3187
+ }
3188
+ return super.unexpected(pos);
3189
+ }
3190
+ }
3191
+ return ColonParser;
3192
+ };
3193
+ /**
3194
+ * acorn's `Parser` with the grammar, built once, at module load. `extend`
3195
+ * returns a subclass, so acorn's own `Parser`, which `acorn.parse` uses, is
3196
+ * left as it was.
3197
+ */
3198
+ const ColonIdentifiersParser = Parser.extend(colonIdentifiers);
3199
+
3079
3200
  /**
3080
3201
  * @description
3081
3202
  * Parses expression and returns ES6/ES2020 AST.
3203
+ * With `colonIdentifiers` set the parser is the colon-joined name grammar's;
3204
+ * otherwise it is acorn's own `parse`.
3082
3205
  * @param expr expression to parse
3083
3206
  * @param options parser options
3084
3207
  */
3085
3208
  const parse = (expr, options) => {
3086
3209
  options = { ecmaVersion: 2020, ...options };
3087
3210
  const acornOptions = { ecmaVersion: 2020, ...options };
3088
- const program = parse$1(expr, acornOptions);
3211
+ const program = options.colonIdentifiers
3212
+ ? ColonIdentifiersParser.parse(expr, acornOptions)
3213
+ : parse$1(expr, acornOptions);
3089
3214
  if (!options.extractExpressions) {
3090
3215
  return program;
3091
3216
  }
@@ -4062,8 +4187,8 @@ class EvalContext {
4062
4187
  return resolve(this, key)?.value;
4063
4188
  }
4064
4189
  /**
4065
- * Step 1 of {@link get}'s resolution order on its own: the scopes pushed
4066
- * during this evaluation, innermost first.
4190
+ * Step 1 of {@link get}'s resolution order on its own: the scope stack,
4191
+ * innermost first, whoever pushed each scope.
4067
4192
  *
4068
4193
  * {@link get} calls this rather than inlining the loop, so that the read
4069
4194
  * hooks' `scoped` flag and the resolution it describes are the *same*
@@ -4137,8 +4262,11 @@ class EvalContext {
4137
4262
  return undefined;
4138
4263
  }
4139
4264
  /**
4140
- * Whether any scope pushed during this evaluation *binds* the key - the
4141
- * question the read hooks' `scoped` flag asks.
4265
+ * Whether any scope on the scope stack *binds* the key - the question the
4266
+ * read hooks' `scoped` flag asks. Every scope on the stack counts, whoever
4267
+ * pushed it: an arrow call's parameters, the lexical scope of a program, a
4268
+ * block or a `for` loop, and a scope a caller pushed with {@link push}
4269
+ * before the walk.
4142
4270
  *
4143
4271
  * Deliberately about binding rather than about value. It no longer parts
4144
4272
  * company with {@link getFromScopes} over it: both go through
@@ -5616,9 +5744,11 @@ const rootOf = (path) => {
5616
5744
  * rules do the filtering:
5617
5745
  *
5618
5746
  * 1. **Scope bindings are not dependencies.** A read flagged `scoped` resolved
5619
- * from a scope pushed during the walk - an arrow-function parameter. Only
5620
- * the walker can tell one from a real context read, which is why the flag
5621
- * exists; a consumer using this tracker inherits the filtering for free.
5747
+ * from a scope on the context's scope stack, whoever pushed it - an
5748
+ * arrow-function parameter, a declaration in a program, block or `for`
5749
+ * scope, or a binding the caller pushed before the walk. Only the walker
5750
+ * can tell one from a real context read, which is why the flag exists; a
5751
+ * consumer using this tracker inherits the filtering for free.
5622
5752
  * 2. **Nor is anything reached *through* one.** `item` being a binding makes
5623
5753
  * `item.name` one too, and that read carries no flag of its own: `scoped` is
5624
5754
  * set at identifier resolution, and the member hop resolves against the
@@ -5747,6 +5877,148 @@ class BaseEval {
5747
5877
  }
5748
5878
  }
5749
5879
 
5880
+ /**
5881
+ * The options a cached AST cannot honour: acorn calls each callback as it
5882
+ * parses, and appends to a caller's `program` node. A parse carrying any of
5883
+ * them with a value acorn acts on bypasses the cache, reading and writing
5884
+ * (`docs/colon-identifiers/phase-9-plan.md` § 3.2). The test is on the value,
5885
+ * never the key: `defaultParserOptions`, which every service passes, carries
5886
+ * all five as `null`.
5887
+ */
5888
+ const UNCACHEABLE_OPTIONS = [
5889
+ 'onToken', 'onComment', 'onInsertedSemicolon', 'onTrailingComma', 'program'
5890
+ ];
5891
+ /**
5892
+ * Left out of the fingerprint: the five above, and `cacheSize`, which sizes
5893
+ * the cache and changes no parse.
5894
+ */
5895
+ const UNKEYED_OPTIONS = new Set([...UNCACHEABLE_OPTIONS, 'cacheSize']);
5896
+ /** Stands for a call that passes no options object of its own. */
5897
+ const NO_CALL_OPTIONS = Object.freeze({});
5898
+ /**
5899
+ * Builds the fingerprint of a parse with the given options — the service's and
5900
+ * the call's, merged as `ParserService.parse` merges them — or `null` when the
5901
+ * parse must bypass the cache.
5902
+ *
5903
+ * Every other option is in it under its own name, so an option this file does
5904
+ * not list keys the cache with no change here. Sorted `[key, value]` pairs as
5905
+ * JSON: canonical, so equal options give one fingerprint whatever their key
5906
+ * order or identity. A key whose value is `undefined` is written `[key]`
5907
+ * rather than dropped, since acorn reads it differently from a missing key:
5908
+ * `checkPrivateFields` defaults to `true`. A value JSON cannot hold, a cycle
5909
+ * or a `BigInt`, gives no fingerprint, so that parse bypasses the cache rather
5910
+ * than throw where it used to succeed.
5911
+ */
5912
+ const buildParseFingerprint = (options) => {
5913
+ for (const key of UNCACHEABLE_OPTIONS) {
5914
+ if (options[key]) {
5915
+ return null;
5916
+ }
5917
+ }
5918
+ const values = options;
5919
+ const pairs = Object.keys(values)
5920
+ .filter(key => !UNKEYED_OPTIONS.has(key))
5921
+ .sort()
5922
+ .map(key => values[key] === undefined ? [key] : [key, values[key]]);
5923
+ try {
5924
+ return JSON.stringify(pairs);
5925
+ }
5926
+ catch {
5927
+ return null;
5928
+ }
5929
+ };
5930
+ /**
5931
+ * Returns the cache namespace for a parse with the service's options and the
5932
+ * call's — the sha256 of their fingerprint, in hex — or `null` when the parse
5933
+ * must bypass the cache. Built once per pair of objects and remembered by
5934
+ * identity in the service's `memo`, so `EvalService`, which passes the same
5935
+ * `defaultParserOptions` on every call, pays two lookups per parse rather than
5936
+ * a serialization and a digest. The digest keeps `getHashKey`'s input short:
5937
+ * it joins the namespace and the text with `:`, and 64 hex characters, none a
5938
+ * colon, cannot make two (options, text) pairs one key when the text holds
5939
+ * colons.
5940
+ *
5941
+ * Remembered by identity, it does not see an object changed in place: the
5942
+ * object the `parserOptions` getter returns, an options object a caller passes
5943
+ * again after writing into it, or the exported `defaultParserOptions`. A change
5944
+ * through the `parserOptions` setter installs a new object, and is seen
5945
+ * (`docs/backlog.md` A34).
5946
+ */
5947
+ const parseFingerprint = (memo, serviceOptions, callOptions) => {
5948
+ let byCall = memo.get(serviceOptions);
5949
+ if (!byCall) {
5950
+ byCall = new WeakMap();
5951
+ memo.set(serviceOptions, byCall);
5952
+ }
5953
+ // A JavaScript caller can pass something other than an object, such as the
5954
+ // `false` of `condition && options`. It cannot be a `WeakMap` key, and acorn
5955
+ // reads none of its options from it, so it is fingerprinted as none.
5956
+ const call = typeof callOptions === 'object' && callOptions !== null
5957
+ ? callOptions : undefined;
5958
+ const callKey = call ?? NO_CALL_OPTIONS;
5959
+ let digest = byCall.get(callKey);
5960
+ if (digest === undefined) {
5961
+ const fingerprint = buildParseFingerprint({ ...serviceOptions, ...call });
5962
+ digest = fingerprint === null ? null : sha256(fingerprint);
5963
+ byCall.set(callKey, digest);
5964
+ }
5965
+ return digest;
5966
+ };
5967
+
5968
+ /**
5969
+ * Set by {@link provideColonIdentifiers}, and by nothing else. Exported from no
5970
+ * barrel: the provider is the only way to set it, and
5971
+ * `inject(ParserService).parserOptions` the published way to read the
5972
+ * effective value (`docs/colon-identifiers/phase-9-plan.md` § 3.3).
5973
+ */
5974
+ const COLON_IDENTIFIERS = new InjectionToken('COLON_IDENTIFIERS');
5975
+ /** Angular's code for `inject()` called outside an injection context, NG0203. */
5976
+ const MISSING_INJECTION_CONTEXT = -203;
5977
+ /**
5978
+ * Whether the injector constructing a `ParserService` holds
5979
+ * {@link provideColonIdentifiers}. `false` outside an injection context:
5980
+ * `new ParserService()` constructed a working service before the provider
5981
+ * existed, and still does, with the option off. Any other error from the read
5982
+ * is rethrown (plan § 3.1).
5983
+ */
5984
+ const injectColonIdentifiers = () => {
5985
+ try {
5986
+ return inject(COLON_IDENTIFIERS, { optional: true }) === true;
5987
+ }
5988
+ catch (error) {
5989
+ if (error?.code === MISSING_INJECTION_CONTEXT) {
5990
+ return false;
5991
+ }
5992
+ throw error;
5993
+ }
5994
+ };
5995
+ /**
5996
+ * Turns `colonIdentifiers` on for every parse through `ParserService`, and so
5997
+ * through `EvalService`, `CompilerService` and `DiscoveryService`: a
5998
+ * colon-joined name such as `Q1:1:3` parses as one identifier and reads the
5999
+ * context key of that spelling. A per-call `colonIdentifiers` overrides it.
6000
+ *
6001
+ * Belongs in the application's root providers. `ParserService` is provided in
6002
+ * the root, so in a child environment injector - a lazy route's `providers` -
6003
+ * it would reach no parse; there it throws when that injector is created.
6004
+ *
6005
+ * @returns The providers, for the application's root providers.
6006
+ */
6007
+ function provideColonIdentifiers() {
6008
+ return makeEnvironmentProviders([
6009
+ { provide: COLON_IDENTIFIERS, useValue: true },
6010
+ provideEnvironmentInitializer(() => {
6011
+ if (inject(ParserService).parserOptions?.colonIdentifiers !== true) {
6012
+ throw new Error('provideColonIdentifiers() reaches no parse here: ' +
6013
+ 'ParserService is provided in the root, and the root ParserService ' +
6014
+ 'does not have colonIdentifiers on. Put provideColonIdentifiers() in ' +
6015
+ 'the application\'s root providers, not a lazy route\'s or another ' +
6016
+ 'child injector\'s.');
6017
+ }
6018
+ }),
6019
+ ]);
6020
+ }
6021
+
5750
6022
  /**
5751
6023
  * @description
5752
6024
  * Service for parsing expressions and returning ES6/ES2020 AST.
@@ -5767,13 +6039,17 @@ class ParserService {
5767
6039
  this._parserOptions = value;
5768
6040
  }
5769
6041
  /**
5770
- * Constructs a new instance of the ParserService class.
6042
+ * Constructs a new instance of the ParserService class. Its options carry
6043
+ * `colonIdentifiers: true` when the injector constructing it holds
6044
+ * `provideColonIdentifiers()`, and no such key otherwise.
5771
6045
  */
5772
6046
  constructor() {
6047
+ this._fingerprints = new WeakMap();
5773
6048
  this._isDestroyed = false;
5774
6049
  this.parserOptions = {
5775
6050
  ...defaultParserOptions,
5776
- extractExpressions: true
6051
+ extractExpressions: true,
6052
+ ...(injectColonIdentifiers() ? { colonIdentifiers: true } : {})
5777
6053
  };
5778
6054
  if (this.parserOptions.cacheSize) {
5779
6055
  this._cache = new Cache(this.parserOptions.cacheSize);
@@ -5842,19 +6118,30 @@ class ParserService {
5842
6118
  const parserOptions = { ...this.parserOptions, ...options };
5843
6119
  const isCache = this.parserOptions.cacheSize && this._cache;
5844
6120
  const ast = isCache
5845
- ? this.fromCacheOrParse(expr, parserOptions)
6121
+ ? this.fromCacheOrParse(expr, parserOptions, options)
5846
6122
  : parse(expr, parserOptions);
5847
6123
  return ast;
5848
6124
  }
5849
6125
  return undefined;
5850
6126
  }
5851
6127
  //#region Private methods
5852
- fromCacheOrParse(expr, options) {
6128
+ /**
6129
+ * Serves a cached AST only to a parse whose parse-relevant options match the
6130
+ * parse that cached it: the key is the text under a digest of the
6131
+ * fingerprint of the service's options and the call's, not the text alone
6132
+ * (`docs/backlog-retired.md` A26). A parse carrying a callback or a
6133
+ * `program` neither reads nor writes the cache.
6134
+ */
6135
+ fromCacheOrParse(expr, parserOptions, callOptions) {
5853
6136
  if (this._cache) {
5854
- const hashKey = this._cache.getHashKey('', expr);
6137
+ const namespace = parseFingerprint(this._fingerprints, this.parserOptions, callOptions);
6138
+ if (namespace === null) {
6139
+ return parse(expr, parserOptions);
6140
+ }
6141
+ const hashKey = this._cache.getHashKey(namespace, expr);
5855
6142
  let ast = this._cache.get(hashKey);
5856
6143
  if (!ast) {
5857
- ast = parse(expr, options);
6144
+ ast = parse(expr, parserOptions);
5858
6145
  this._cache.set(hashKey, ast);
5859
6146
  }
5860
6147
  return ast;
@@ -5993,6 +6280,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImpor
5993
6280
  }]
5994
6281
  }], ctorParameters: () => [] });
5995
6282
 
6283
+ /** Stands for a `ParserService` that has no options object of its own. */
6284
+ const NO_SERVICE_OPTIONS = Object.freeze({});
5996
6285
  /**
5997
6286
  * CompilerService class that extends BaseEval.
5998
6287
  * Provides methods for compiling and evaluating expressions with performance caching.
@@ -6006,6 +6295,7 @@ class CompilerService extends BaseEval {
6006
6295
  this._cacheTTL = 10 * 60 * 1000; // 10 minutes
6007
6296
  this._accessOrder = new Set();
6008
6297
  this._isDestroyed = false;
6298
+ this._fingerprints = new WeakMap();
6009
6299
  this.parserService = inject(ParserService);
6010
6300
  this.evalService = inject(EvalService);
6011
6301
  this.parserOptions = defaultParserOptions;
@@ -6064,21 +6354,24 @@ class CompilerService extends BaseEval {
6064
6354
  }
6065
6355
  }
6066
6356
  /**
6067
- * Generate cache key for expression
6357
+ * Generate cache key for expression. Only a string is cached, so only a
6358
+ * string has a key: the text under the digest of the options its parse
6359
+ * uses, `ParserService`'s merged with this service's, so a change through
6360
+ * the `ParserService.parserOptions` setter reaches a string compiled before
6361
+ * it (`docs/colon-identifiers/phase-9-plan.md` § 3.2). The memo is
6362
+ * `ParserService`'s kind, and a write in place goes unseen here as there
6363
+ * (`docs/backlog.md` A34). `null` when that parse bypasses `ParserService`'s
6364
+ * cache - a callback or a `program` among its options, or a value JSON
6365
+ * cannot hold - and this cache then bypasses too, since a cached function
6366
+ * runs no callback.
6068
6367
  */
6069
6368
  generateCacheKey(expression) {
6070
- if (typeof expression === 'string') {
6071
- return `str:${expression}`;
6072
- }
6073
- else if (expression && typeof expression === 'object') {
6074
- // Use a simplified hash for AST nodes to avoid deep serialization overhead
6075
- return `ast:${expression.type}:${JSON.stringify({
6076
- type: expression.type,
6077
- start: expression.start,
6078
- end: expression.end
6079
- })}:${expression.toString()}`;
6080
- }
6081
- return 'undefined';
6369
+ // A test double for `ParserService` need not carry `parserOptions`, and a
6370
+ // missing one cannot key the memo; it is fingerprinted as none.
6371
+ const serviceOptions = this.parserService.parserOptions;
6372
+ const digest = parseFingerprint(this._fingerprints, typeof serviceOptions === 'object' && serviceOptions !== null
6373
+ ? serviceOptions : NO_SERVICE_OPTIONS, this.parserOptions);
6374
+ return digest === null ? null : `str:${digest}:${expression}`;
6082
6375
  }
6083
6376
  /**
6084
6377
  * Update access order for LRU cache
@@ -6088,7 +6381,9 @@ class CompilerService extends BaseEval {
6088
6381
  this._accessOrder.add(key);
6089
6382
  }
6090
6383
  /**
6091
- * Compiles the given expression into a state callback function with caching.
6384
+ * Compiles the given expression into a state callback function. A string is
6385
+ * compiled once and cached, unless its parse bypasses `ParserService`'s
6386
+ * cache; an AST is compiled on every call.
6092
6387
  * @param expression - The expression to compile.
6093
6388
  * @returns The compiled state callback function.
6094
6389
  * @throws Error if there is an error during compilation.
@@ -6098,7 +6393,18 @@ class CompilerService extends BaseEval {
6098
6393
  // thrown. Each used to raise a bare `Error` carrying only the message in its
6099
6394
  // place, or a fixed message for a thrown non-`Error`
6100
6395
  // (`docs/backlog-retired.md` A5).
6396
+ // Only a string is cached, here and in `compileAsync`. Compiling a node is
6397
+ // binding `evaluate` to it, so caching one saves nothing, and the key it
6398
+ // was cached under - its type, start, end and `toString()`, which is
6399
+ // `[object Object]` for every node - gave two expressions of one shape and
6400
+ // span one compiled function (`docs/backlog-retired.md` A29).
6401
+ if (typeof expression !== 'string') {
6402
+ return compile(this.parse(expression));
6403
+ }
6101
6404
  const cacheKey = this.generateCacheKey(expression);
6405
+ if (cacheKey === null) {
6406
+ return compile(this.parse(expression));
6407
+ }
6102
6408
  // Check cache first
6103
6409
  const cached = this._compilationCache.get(cacheKey);
6104
6410
  if (cached?.sync) {
@@ -6164,13 +6470,22 @@ class CompilerService extends BaseEval {
6164
6470
  return undefined;
6165
6471
  }
6166
6472
  /**
6167
- * Compiles the given expression into an asynchronous state callback function with caching.
6473
+ * Compiles the given expression into an asynchronous state callback
6474
+ * function. A string is compiled once and cached, unless its parse bypasses
6475
+ * `ParserService`'s cache; an AST is compiled on every call.
6168
6476
  * @param expression - The expression to compile.
6169
6477
  * @returns The compiled asynchronous state callback function.
6170
6478
  * @throws Error if there is an error during compilation.
6171
6479
  */
6172
6480
  compileAsync(expression) {
6481
+ // Only a string is cached, as in `compile` (`docs/backlog-retired.md` A29).
6482
+ if (typeof expression !== 'string') {
6483
+ return compileAsync(this.parse(expression));
6484
+ }
6173
6485
  const cacheKey = this.generateCacheKey(expression);
6486
+ if (cacheKey === null) {
6487
+ return compileAsync(this.parse(expression));
6488
+ }
6174
6489
  // Check cache first
6175
6490
  const cached = this._compilationCache.get(cacheKey);
6176
6491
  if (cached?.async) {
@@ -6291,5 +6606,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImpor
6291
6606
  * Generated bundle index. Do not edit.
6292
6607
  */
6293
6608
 
6294
- export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EMPTY_COMPLETION, EvalContext, EvalHooks, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Registry, Stack, call, callAsync, compile, compileAsync, createDependencyTracker, createTimingHook, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextValue, parse };
6609
+ export { ASYNC_HOOK_MESSAGE, BaseRegistry, Cache, CaseInsensitiveRegistry, CompilerService, DiscoveryService, EMPTY_COMPLETION, EvalContext, EvalHooks, EvalResult, EvalScope, EvalService, EvalState, EvalTrace, ParserService, Registry, Stack, call, callAsync, compile, compileAsync, createDependencyTracker, createTimingHook, defaultParserOptions, evaluate, evaluateAsync, extract, extractExpression, fromContext, getContextValue, parse, provideColonIdentifiers };
6295
6610
  //# sourceMappingURL=zvenigora-ng-eval-core.mjs.map