@altopelago/sansa 0.14.2 → 0.15.0-rc.3

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.
Files changed (184) hide show
  1. package/CHANGELOG.md +133 -1
  2. package/README.md +98 -1
  3. package/conformance/README.md +8 -0
  4. package/conformance/aeonic-anchor-claims.json +133 -0
  5. package/conformance/aeonic-arithmetic-claims.json +60 -0
  6. package/conformance/aeonic-clock-claims.json +123 -0
  7. package/conformance/aeonic-comparison-claims.json +37 -0
  8. package/conformance/aeonic-datetime-claims.json +110 -0
  9. package/conformance/aeonic-rational-arithmetic-claims.json +72 -0
  10. package/conformance/aeonic-temporal-claims.json +105 -0
  11. package/conformance/cts-claims.json +17 -3
  12. package/conformance/results/aeonic-anchor-bounded-expansion-2026-11-24.json +39 -0
  13. package/conformance/results/aeonic-anchor-capacity-bounded-expansion-2026-11-24.json +452 -0
  14. package/conformance/results/aeonic-anchor-capacity-rc3-2026-11-24.json +452 -0
  15. package/conformance/results/aeonic-anchor-capacity.json +452 -0
  16. package/conformance/results/aeonic-anchor-rc3-2026-11-24.json +39 -0
  17. package/conformance/results/aeonic-anchor-snapshot-0.1.json +39 -0
  18. package/conformance/results/aeonic-arithmetic-snapshot-0.1.json +28 -0
  19. package/conformance/results/aeonic-clock-all-bounded-expansion-2026-11-24.json +49 -0
  20. package/conformance/results/aeonic-clock-all-rc3-2026-11-24.json +49 -0
  21. package/conformance/results/aeonic-clock-all-snapshot-0.1.json +49 -0
  22. package/conformance/results/aeonic-clock-arithmetic-bounded-expansion-2026-11-24.json +48 -0
  23. package/conformance/results/aeonic-clock-arithmetic-rc3-2026-11-24.json +48 -0
  24. package/conformance/results/aeonic-clock-arithmetic-snapshot-0.1.json +48 -0
  25. package/conformance/results/aeonic-clock-capacity-bounded-expansion-2026-11-24.json +326 -0
  26. package/conformance/results/aeonic-clock-capacity-rc3-2026-11-24.json +326 -0
  27. package/conformance/results/aeonic-clock-capacity.json +326 -0
  28. package/conformance/results/aeonic-clock-relations-bounded-expansion-2026-11-24.json +48 -0
  29. package/conformance/results/aeonic-clock-relations-rc3-2026-11-24.json +48 -0
  30. package/conformance/results/aeonic-clock-relations-snapshot-0.1.json +48 -0
  31. package/conformance/results/aeonic-comparison-snapshot-0.1.json +19 -0
  32. package/conformance/results/aeonic-datetime-all-bounded-expansion-2026-11-24.json +47 -0
  33. package/conformance/results/aeonic-datetime-all-rc3-2026-11-24.json +47 -0
  34. package/conformance/results/aeonic-datetime-all-snapshot-0.1.json +47 -0
  35. package/conformance/results/aeonic-datetime-arithmetic-bounded-expansion-2026-11-24.json +46 -0
  36. package/conformance/results/aeonic-datetime-arithmetic-rc3-2026-11-24.json +46 -0
  37. package/conformance/results/aeonic-datetime-arithmetic-snapshot-0.1.json +46 -0
  38. package/conformance/results/aeonic-datetime-capacity-bounded-expansion-2026-11-24.json +302 -0
  39. package/conformance/results/aeonic-datetime-capacity-rc3-2026-11-24.json +302 -0
  40. package/conformance/results/aeonic-datetime-capacity.json +302 -0
  41. package/conformance/results/aeonic-datetime-relations-bounded-expansion-2026-11-24.json +46 -0
  42. package/conformance/results/aeonic-datetime-relations-rc3-2026-11-24.json +46 -0
  43. package/conformance/results/aeonic-datetime-relations-snapshot-0.1.json +46 -0
  44. package/conformance/results/aeonic-rational-arithmetic-capacity.json +100 -0
  45. package/conformance/results/aeonic-rational-arithmetic-snapshot-0.2.json +30 -0
  46. package/conformance/results/aeonic-temporal-all-bounded-expansion-2026-11-24.json +39 -0
  47. package/conformance/results/aeonic-temporal-all-property-addressing-2026-11-16.json +39 -0
  48. package/conformance/results/aeonic-temporal-all-rc3-2026-11-24.json +39 -0
  49. package/conformance/results/aeonic-temporal-all-snapshot-0.1.json +39 -0
  50. package/conformance/results/aeonic-temporal-calendar-bounded-expansion-2026-11-24.json +38 -0
  51. package/conformance/results/aeonic-temporal-calendar-property-addressing-2026-11-16.json +38 -0
  52. package/conformance/results/aeonic-temporal-calendar-rc3-2026-11-24.json +38 -0
  53. package/conformance/results/aeonic-temporal-calendar-snapshot-0.1.json +38 -0
  54. package/conformance/results/aeonic-temporal-capacity-bounded-expansion-2026-11-24.json +136 -0
  55. package/conformance/results/aeonic-temporal-capacity-property-addressing-2026-11-16.json +136 -0
  56. package/conformance/results/aeonic-temporal-capacity-rc3-2026-11-24.json +136 -0
  57. package/conformance/results/aeonic-temporal-capacity.json +136 -0
  58. package/conformance/results/aeonic-temporal-relations-bounded-expansion-2026-11-24.json +38 -0
  59. package/conformance/results/aeonic-temporal-relations-property-addressing-2026-11-16.json +38 -0
  60. package/conformance/results/aeonic-temporal-relations-rc3-2026-11-24.json +38 -0
  61. package/conformance/results/aeonic-temporal-relations-snapshot-0.1.json +38 -0
  62. package/docs/aeonic-arithmetic.md +126 -0
  63. package/docs/aeonic-comparison.md +123 -0
  64. package/docs/aeonic-rational-arithmetic.md +167 -0
  65. package/docs/aeonic-temporal-civil-anchor.md +89 -0
  66. package/docs/aeonic-temporal-civil-clock.md +100 -0
  67. package/docs/aeonic-temporal-civil-date.md +124 -0
  68. package/docs/aeonic-temporal-civil-datetime.md +122 -0
  69. package/docs/api-contract.md +130 -3
  70. package/docs/capabilities.json +106 -2
  71. package/docs/child-identity-activation.md +93 -0
  72. package/docs/child-identity-candidate.md +60 -0
  73. package/docs/child-identity-tooling.md +31 -0
  74. package/docs/child-identity-workflows.md +102 -0
  75. package/docs/empty-keys-candidate.md +29 -0
  76. package/docs/migration-0.15.0.md +86 -0
  77. package/docs/property-addressing-implementation.md +118 -0
  78. package/docs/property-resolve-implementation.md +105 -0
  79. package/docs/property-selector-support.md +65 -0
  80. package/docs/property-selectors-api.d.ts +43 -0
  81. package/docs/property-selectors-api.pyi +27 -0
  82. package/docs/property-selectors-api.rs +48 -0
  83. package/docs/property-selectors-contract.md +168 -0
  84. package/docs/query-tool.md +32 -1
  85. package/docs/selector-cursor.md +45 -0
  86. package/docs/unicode-hardening.md +41 -0
  87. package/fixtures/address-v1.json +4 -3
  88. package/fixtures/child-identity-workflows/README.md +9 -0
  89. package/fixtures/child-identity-workflows/moved.aeon +10 -0
  90. package/fixtures/child-identity-workflows/original.aeon +10 -0
  91. package/fixtures/child-identity-workflows/reordered.aeon +10 -0
  92. package/fixtures/child-identity-workflows/replacement.aeon +10 -0
  93. package/fixtures/child-identity-workflows/workflows.json +89 -0
  94. package/fixtures/property-namespace-candidate-v1.json +336 -0
  95. package/fixtures/property-parser-candidate-v1.json +705 -0
  96. package/fixtures/property-query-candidate-v1.json +398 -0
  97. package/fixtures/property-resolve-candidate-v1.json +2702 -0
  98. package/fixtures/unicode-hardening-v1.json +401 -0
  99. package/package.json +30 -3
  100. package/scripts/calibrate-aeonic-anchor-capacity.py +294 -0
  101. package/scripts/calibrate-aeonic-clock-capacity.py +62 -0
  102. package/scripts/calibrate-aeonic-datetime-capacity.py +76 -0
  103. package/scripts/calibrate-aeonic-rational-capacity.py +85 -0
  104. package/scripts/calibrate-aeonic-temporal-capacity.py +95 -0
  105. package/scripts/cts-address.mjs +6 -2
  106. package/scripts/cts-aeonic-anchor.mjs +21 -0
  107. package/scripts/cts-aeonic-arithmetic-adapter.mjs +25 -0
  108. package/scripts/cts-aeonic-arithmetic.mjs +24 -0
  109. package/scripts/cts-aeonic-clock.mjs +24 -0
  110. package/scripts/cts-aeonic-comparison-adapter.mjs +30 -0
  111. package/scripts/cts-aeonic-comparison.mjs +25 -0
  112. package/scripts/cts-aeonic-datetime.mjs +24 -0
  113. package/scripts/cts-aeonic-rational-arithmetic-adapter.mjs +25 -0
  114. package/scripts/cts-aeonic-rational-arithmetic.mjs +24 -0
  115. package/scripts/cts-aeonic-temporal-civil-anchor-adapter.mjs +26 -0
  116. package/scripts/cts-aeonic-temporal-civil-clock-adapter.mjs +28 -0
  117. package/scripts/cts-aeonic-temporal-civil-date-adapter.mjs +28 -0
  118. package/scripts/cts-aeonic-temporal-civil-datetime-adapter.mjs +28 -0
  119. package/scripts/cts-aeonic-temporal.mjs +24 -0
  120. package/scripts/cts-instruction.mjs +4 -2
  121. package/scripts/cts-mutate.mjs +3 -2
  122. package/scripts/cts-resolve.mjs +17 -2
  123. package/scripts/playground.mjs +110 -0
  124. package/src/aeonic-arithmetic-binding.js +61 -0
  125. package/src/aeonic-arithmetic.d.ts +84 -0
  126. package/src/aeonic-arithmetic.js +276 -0
  127. package/src/aeonic-comparison.d.ts +86 -0
  128. package/src/aeonic-comparison.js +274 -0
  129. package/src/aeonic-convenience.d.ts +30 -0
  130. package/src/aeonic-convenience.js +45 -0
  131. package/src/aeonic-exact-number.js +34 -0
  132. package/src/aeonic-json.js +45 -0
  133. package/src/aeonic-rational-arithmetic.d.ts +86 -0
  134. package/src/aeonic-rational-arithmetic.js +417 -0
  135. package/src/aeonic-rational-json.js +51 -0
  136. package/src/aeonic-temporal-civil-anchor.d.ts +54 -0
  137. package/src/aeonic-temporal-civil-anchor.js +316 -0
  138. package/src/aeonic-temporal-civil-clock.d.ts +124 -0
  139. package/src/aeonic-temporal-civil-clock.js +388 -0
  140. package/src/aeonic-temporal-civil-date.d.ts +123 -0
  141. package/src/aeonic-temporal-civil-date.js +310 -0
  142. package/src/aeonic-temporal-civil-datetime.d.ts +138 -0
  143. package/src/aeonic-temporal-civil-datetime.js +501 -0
  144. package/src/index.d.ts +84 -1
  145. package/src/index.js +859 -190
  146. package/src/property-address.js +196 -0
  147. package/src/property-resolve.js +132 -0
  148. package/src/query-metadata.d.ts +16 -0
  149. package/src/query-metadata.js +25 -0
  150. package/src/selector-cursor.d.ts +19 -0
  151. package/src/selector-cursor.js +79 -0
  152. package/stress-tests/address/invalid.sansa-cases +0 -2
  153. package/stress-tests/address/valid.sansa-cases +3 -0
  154. package/tools/mutate-web/examples.mjs +1 -1
  155. package/tools/mutate-web/runtime.mjs +0 -2
  156. package/tools/playground/README.md +165 -0
  157. package/tools/playground/accessibility.js +91 -0
  158. package/tools/playground/aeon-highlight.js +77 -0
  159. package/tools/playground/aeon-source-composer.js +1077 -0
  160. package/tools/playground/anchor-examples.mjs +16 -0
  161. package/tools/playground/arithmetic-evaluator.mjs +28 -0
  162. package/tools/playground/arithmetic-model.mjs +187 -0
  163. package/tools/playground/arithmetic-worker.mjs +14 -0
  164. package/tools/playground/arithmetic.css +1 -0
  165. package/tools/playground/arithmetic.html +29 -0
  166. package/tools/playground/arithmetic.mjs +110 -0
  167. package/tools/playground/clock-examples.mjs +16 -0
  168. package/tools/playground/datetime-examples.mjs +22 -0
  169. package/tools/playground/examples.mjs +46 -0
  170. package/tools/playground/index.html +174 -0
  171. package/tools/playground/local.css +25 -0
  172. package/tools/playground/namespace.mjs +39 -0
  173. package/tools/playground/sansa-playground.js +1565 -0
  174. package/tools/playground/site.css +3914 -0
  175. package/tools/playground/temporal-examples.mjs +20 -0
  176. package/tools/playground/walkthrough.js +90 -0
  177. package/tools/playground/website-origin.json +16 -0
  178. package/tools/query-web/IDENTITY_SELECTORS.md +44 -0
  179. package/tools/query-web/app.js +4 -0
  180. package/tools/query-web/index.html +4 -0
  181. package/tools/query-web/runtime.mjs +70 -19
  182. package/tools/workflows/property-playground-assertions.mjs +33 -0
  183. package/tools/workflows/verify-child-identities.mjs +137 -0
  184. package/tools/workflows/verify-property-playground.mjs +48 -0
package/src/index.js CHANGED
@@ -1,3 +1,46 @@
1
+ export { evaluateAeonicCivilAnchor, evaluateAeonicCivilAnchorText, AEONIC_TEMPORAL_CIVIL_ANCHOR_PROFILE, AEONIC_TEMPORAL_CIVIL_ANCHOR_DEFAULT_RESOURCE_LIMITS } from './aeonic-temporal-civil-anchor.js';
2
+ export { evaluateAeonicCivilClock, evaluateAeonicCivilClockText, AEONIC_TEMPORAL_CIVIL_CLOCK_PROFILE, AEONIC_TEMPORAL_CIVIL_CLOCK_DEFAULT_RESOURCE_LIMITS } from './aeonic-temporal-civil-clock.js';
3
+ export { evaluateAeonicCivilDateTime, evaluateAeonicCivilDateTimeText, AEONIC_TEMPORAL_CIVIL_DATETIME_PROFILE, AEONIC_TEMPORAL_CIVIL_DATETIME_DEFAULT_RESOURCE_LIMITS } from './aeonic-temporal-civil-datetime.js';
4
+ import {PropertyAddressError, data as astData, hasPropertySyntax, hasPropertyAst, propertyLimit, renderPropertyAddress, parsePropertyQualifiers} from './property-address.js';
5
+ import {DEFAULT_PROPERTY_INSPECTIONS, validPropertyLimit, prepareProperties, propertyContext, selectProperty} from './property-resolve.js';
6
+ export { evaluateAeonicTemporal, evaluateAeonicTemporalText, AEONIC_TEMPORAL_CIVIL_DATE_PROFILE, AEONIC_TEMPORAL_CIVIL_DATE_DEFAULT_RESOURCE_LIMITS } from './aeonic-temporal-civil-date.js';
7
+ export {
8
+ evaluateAeonicRationalArithmetic,
9
+ evaluateAeonicRationalArithmeticText,
10
+ AEONIC_RATIONAL_ARITHMETIC_PROFILE,
11
+ AEONIC_RATIONAL_ARITHMETIC_DEFAULT_RESOURCE_LIMITS,
12
+ } from './aeonic-rational-arithmetic.js';
13
+ export {
14
+ evaluateAeonicArithmeticAndMaterialize,
15
+ evaluateAeonicArithmeticAndMaterializeText,
16
+ evaluateAeonicRationalArithmeticAndMaterialize,
17
+ evaluateAeonicRationalArithmeticAndMaterializeText,
18
+ } from './aeonic-convenience.js';
19
+
20
+ export {
21
+ evaluateAeonicArithmetic,
22
+ evaluateAeonicArithmeticText,
23
+ AEONIC_ARITHMETIC_PROFILE,
24
+ AEONIC_ARITHMETIC_DEFAULT_RESOURCE_LIMITS,
25
+ } from './aeonic-arithmetic.js';
26
+
27
+ export {
28
+ evaluateAeonicComparison,
29
+ evaluateAeonicComparisonText,
30
+ AEONIC_COMPARISON_BASELINE_PROFILE,
31
+ AEONIC_COMPARISON_CODEPOINT_PROFILE,
32
+ AEONIC_COMPARISON_DEFAULT_RESOURCE_LIMITS,
33
+ } from './aeonic-comparison.js';
34
+ import { parseDotSelectorFromCursor, parsePositionSelectorFromCursor, validatePositionIndex } from './selector-cursor.js';
35
+ const CHILD_IDENTITY_RE = /^[A-Za-z0-9_-]+$/;
36
+ const DENY_CHILD_IDENTITY = Symbol('consumer identity admission');
37
+ const DENY_PROPERTIES = Symbol('consumer property admission');
38
+ const QUERY_PROPERTIES = Symbol('query property state');
39
+ const QUERY_CURRENT_FRAME = Symbol('query current occurrence');
40
+ const QUERY_RESOLVE_FRAME = Symbol('query resolve occurrence');
41
+ const QUERY_IDENTITY_BUDGET = Symbol('query identity inspections');
42
+ const IDENTITY_ACTIVATION_GUARD = Symbol('identity activation scope');
43
+ const DEFAULT_IDENTITY_INSPECTIONS = 10_000;
1
44
  const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
2
45
  const QUALIFIER_NUMBER_RE = /^[+-]?(?:(?:0|[1-9][0-9]*)(?:\.[0-9]+)?|\.[0-9]+)$/;
3
46
  export const SANSA_MAX_POSITION_INDEX = 999_999;
@@ -62,13 +105,14 @@ export function parseAddress(input, options = {}) {
62
105
  const address = parser.parse();
63
106
  return { ok: true, address, warnings: parser.warnings };
64
107
  } catch (error) {
65
- if (error instanceof SansaParseError) {
108
+ if (error instanceof SansaParseError || error instanceof PropertyAddressError) {
66
109
  return {
67
110
  ok: false,
68
111
  errors: [{
69
112
  code: error.code,
70
113
  message: error.message,
71
- index: error.index,
114
+ index: error.index ?? 0,
115
+ ...(error.limitKind === undefined ? {} : {limitKind:error.limitKind, limit:error.limit, observed:error.observed}),
72
116
  }],
73
117
  };
74
118
  }
@@ -187,6 +231,10 @@ export function lowerInstruction(input, namespaceOrOptions = {}, maybeOptions =
187
231
  };
188
232
  }
189
233
  try {
234
+ const instruction = parsed.instruction;
235
+ if (instructionHasProperty(instruction, options)) {
236
+ return {ok:false,errors:[instructionLowerError('SANSA_RESOLVE_UNSUPPORTED_SELECTOR','Property instructions are not admitted',{phase:'lower'})]};
237
+ }
190
238
  const lowered = lowerParsedInstruction(parsed.instruction, namespace, options);
191
239
  const request = lowered.preconditions.length === 0
192
240
  ? lowered.operations.length === 1 ? lowered.operations[0] : lowered.operations
@@ -202,6 +250,7 @@ export function lowerInstruction(input, namespaceOrOptions = {}, maybeOptions =
202
250
  warnings: parsed.warnings ?? [],
203
251
  };
204
252
  } catch (error) {
253
+ if (error instanceof PropertyAddressError) return {ok:false,errors:[instructionLowerError('SANSA_RESOLVE_INVALID_ADDRESS','Invalid property address AST',{phase:'lower'})]};
205
254
  if (error instanceof SansaInstructionLowerError) {
206
255
  return { ok: false, errors: [error.diagnostic] };
207
256
  }
@@ -430,6 +479,7 @@ export function evaluateQuery(input, namespace, options = {}) {
430
479
  options = {
431
480
  ...options,
432
481
  valueSemantics: valueSemanticsProfile,
482
+ [QUERY_IDENTITY_BUDGET]: { inspected: 0 },
433
483
  };
434
484
  const parsed = typeof input === 'string' ? parseQuery(input, options.parse) : { ok: true, query: input };
435
485
  if (!parsed.ok) {
@@ -440,7 +490,22 @@ export function evaluateQuery(input, namespace, options = {}) {
440
490
  };
441
491
  }
442
492
 
443
- const query = parsed.query;
493
+ let query = parsed.query;
494
+ let propertySelectors;
495
+ try {
496
+ propertySelectors = queryPropertySelectors(query);
497
+ if (propertySelectors.length && typeof input !== 'string') {
498
+ query = normalizePropertyQuery(query, options.parse);
499
+ propertySelectors = queryPropertySelectors(query);
500
+ }
501
+ } catch (error) {
502
+ if (!(error instanceof PropertyAddressError)) throw error;
503
+ return {ok:false,results:[],errors:[annotateQueryDiagnostic(resolveError('SANSA_RESOLVE_INVALID_ADDRESS','Invalid property address AST'),{phase:'policy'})]};
504
+ }
505
+ if (propertySelectors.length) {
506
+ const error = validatePropertyQueryRoots(query, namespace, options);
507
+ if (error) return {ok:false,results:[],errors:[annotateQueryDiagnostic(error,{phase:"policy"})]};
508
+ }
444
509
  const policy = enforceQueryPolicy(query, options);
445
510
  if (!policy.ok) {
446
511
  return {
@@ -450,6 +515,14 @@ export function evaluateQuery(input, namespace, options = {}) {
450
515
  };
451
516
  }
452
517
 
518
+ if (propertySelectors.length) {
519
+ // Validate options and roots before consumer/capability admission. No child
520
+ // or metadata hooks run during this whole-query preflight.
521
+ const prepared = prepareProperties(namespace, propertySelectors);
522
+ if (prepared.error) return {ok:false,results:[],errors:[annotateQueryDiagnostic({...prepared.error,selectorIndex:propertySelectors[prepared.error.selectorIndex]?.querySelectorIndex},{phase:'policy'})]};
523
+ options = {...options, [QUERY_PROPERTIES]: {prepared, budget:{inspected:0,limit:options.resolve?.maxPropertyInspections === undefined ? DEFAULT_PROPERTY_INSPECTIONS : options.resolve.maxPropertyInspections}, frames:new WeakMap()}};
524
+ }
525
+
453
526
  const from = evaluateQueryFromClause(query.from, namespace, options);
454
527
  if (!from.ok) {
455
528
  return {
@@ -460,6 +533,7 @@ export function evaluateQuery(input, namespace, options = {}) {
460
533
  }
461
534
 
462
535
  let bindings = from.bindings;
536
+ let frames = options[QUERY_PROPERTIES]?.frames.get(from);
463
537
  const fromBudget = checkQueryBudget(options, 'maxFromBindings', bindings.length);
464
538
  if (!fromBudget.ok) {
465
539
  return {
@@ -479,8 +553,10 @@ export function evaluateQuery(input, namespace, options = {}) {
479
553
  };
480
554
  }
481
555
  const filtered = [];
482
- for (const binding of bindings) {
483
- const evaluated = evaluateQueryExpressionValue(query.where.ast, binding, namespace, options);
556
+ const filteredFrames = [];
557
+ for (let row = 0; row < bindings.length; row++) {
558
+ const binding = bindings[row];
559
+ const evaluated = evaluateQueryExpressionValue(query.where.ast, binding, namespace, queryRowOptions(options, frames?.[row]));
484
560
  if (!evaluated.ok) {
485
561
  return {
486
562
  ok: false,
@@ -502,9 +578,10 @@ export function evaluateQuery(input, namespace, options = {}) {
502
578
  })],
503
579
  };
504
580
  }
505
- if (boolean.value) filtered.push(binding);
581
+ if (boolean.value) { filtered.push(binding); if (frames) filteredFrames.push(frames[row]); }
506
582
  }
507
583
  bindings = filtered;
584
+ if (frames) frames = filteredFrames;
508
585
  }
509
586
 
510
587
  if (query.orderBy) {
@@ -516,7 +593,7 @@ export function evaluateQuery(input, namespace, options = {}) {
516
593
  errors: [annotateQueryDiagnostic(orderBudget.error, { phase: 'order' })],
517
594
  };
518
595
  }
519
- const ordered = orderQueryBindings(query.orderBy, bindings, namespace, options);
596
+ const ordered = orderQueryBindings(query.orderBy, bindings, namespace, options, frames);
520
597
  if (!ordered.ok) {
521
598
  return {
522
599
  ok: false,
@@ -525,10 +602,11 @@ export function evaluateQuery(input, namespace, options = {}) {
525
602
  };
526
603
  }
527
604
  bindings = ordered.bindings;
605
+ if (frames) frames = ordered.frames;
528
606
  }
529
607
 
530
- if (query.offset) bindings = bindings.slice(query.offset.value);
531
- if (query.limit) bindings = bindings.slice(0, query.limit.value);
608
+ if (query.offset) { bindings = bindings.slice(query.offset.value); frames = frames?.slice(query.offset.value); }
609
+ if (query.limit) { bindings = bindings.slice(0, query.limit.value); frames = frames?.slice(0, query.limit.value); }
532
610
 
533
611
  const resultBudget = checkQueryBudget(options, 'maxResultRecords', bindings.length);
534
612
  if (!resultBudget.ok) {
@@ -540,8 +618,9 @@ export function evaluateQuery(input, namespace, options = {}) {
540
618
  }
541
619
 
542
620
  const results = [];
543
- for (const binding of bindings) {
544
- const evaluated = evaluateQueryExpressionValue(query.select.ast, binding, namespace, options);
621
+ for (let row = 0; row < bindings.length; row++) {
622
+ const binding = bindings[row];
623
+ const evaluated = evaluateQueryExpressionValue(query.select.ast, binding, namespace, queryRowOptions(options, frames?.[row]));
545
624
  if (!evaluated.ok) {
546
625
  return {
547
626
  ok: false,
@@ -581,6 +660,8 @@ export function planMutation(input, namespace, options = {}) {
581
660
  if (!operationSurface.ok) return { ok: false, errors: [operationSurface.error] };
582
661
  const valueBudget = checkMutationValueBudgets(options, normalized.operations);
583
662
  if (!valueBudget.ok) return { ok: false, errors: [valueBudget.error] };
663
+ const admission = preflightMutationProperties(normalized.operations, normalized.preconditions, options);
664
+ if (admission) return { ok: false, errors: [admission] };
584
665
 
585
666
  const operations = [];
586
667
  const seenDestructiveTargets = new Set();
@@ -652,6 +733,9 @@ export function applyMutationPlan(plan, namespace, options = {}) {
652
733
  if (!valueBudget.ok) {
653
734
  return { ok: false, operationResults: [], errors: [valueBudget.error] };
654
735
  }
736
+ // Recheck policy even when callers explicitly skip precondition evaluation.
737
+ const admission = preflightMutationProperties(plan.operations, plan.preconditions ?? [], options, true);
738
+ if (admission) return { ok: false, operationResults: [], errors: [admission] };
655
739
 
656
740
  for (let operationIndex = 0; operationIndex < plan.operations.length; operationIndex += 1) {
657
741
  const operation = plan.operations[operationIndex];
@@ -1184,10 +1268,10 @@ function planCreateOperation(requested, operationIndex, namespace, options) {
1184
1268
  ),
1185
1269
  };
1186
1270
  }
1187
- if (typeof requested.name !== 'string' || requested.name.length === 0) {
1271
+ if (typeof requested.name !== 'string') {
1188
1272
  return {
1189
1273
  ok: false,
1190
- error: mutationError('SANSA_MUTATE_INVALID_NAME', 'Create requires a non-empty string name', { operationIndex }),
1274
+ error: mutationError('SANSA_MUTATE_INVALID_NAME', 'Create requires a string name', { operationIndex }),
1191
1275
  };
1192
1276
  }
1193
1277
  const datatype = mutationDatatype(requested, operationIndex);
@@ -1386,7 +1470,7 @@ function resolveMutationExactTarget(input, role, operationIndex, namespace, opti
1386
1470
  };
1387
1471
  }
1388
1472
 
1389
- const resolved = resolveAddress(parsed.address, namespace, options.resolve);
1473
+ const resolved = resolveConsumerAddress(parsed.address, namespace, options.resolve);
1390
1474
  if (!resolved.ok) {
1391
1475
  return {
1392
1476
  ok: false,
@@ -1477,7 +1561,7 @@ function verifyMutationOperationStability(operation, operationIndex, namespace,
1477
1561
  }
1478
1562
 
1479
1563
  function verifyMutationTargetStability(target, operationIndex, namespace, options) {
1480
- const resolved = resolveAddress(target.address, namespace, options.resolve);
1564
+ const resolved = resolveConsumerAddress(target.address, namespace, options.resolve);
1481
1565
  if (!resolved.ok || resolved.bindings.length !== 1) {
1482
1566
  return {
1483
1567
  ok: false,
@@ -2069,7 +2153,6 @@ function validateAeonTargetValue(value, hints, path, operationIndex) {
2069
2153
  if (value && typeof value === 'object') {
2070
2154
  for (const [key, entry] of Object.entries(value)) {
2071
2155
  const entryPath = `${path}${renderMutationValuePathSegment(key)}`;
2072
- if (key.length === 0) return invalidAeonTargetValue('Keys must not be empty', entryPath, operationIndex);
2073
2156
  const result = validateAeonTargetValue(entry, {}, entryPath, operationIndex);
2074
2157
  if (!result.ok) return result;
2075
2158
  }
@@ -2101,7 +2184,6 @@ function validateAeonTargetNodeValue(value, path, operationIndex) {
2101
2184
  }
2102
2185
  for (const [key, entry] of Object.entries(value.attributes)) {
2103
2186
  const entryPath = `${path}.attributes${renderMutationValuePathSegment(key)}`;
2104
- if (key.length === 0) return invalidAeonTargetValue('Keys must not be empty', entryPath, operationIndex);
2105
2187
  const result = validateAeonTargetValue(entry, {}, entryPath, operationIndex);
2106
2188
  if (!result.ok) return result;
2107
2189
  }
@@ -2224,7 +2306,7 @@ function validateAeonReservedDatatypeSurface(datatype, base, operationIndex) {
2224
2306
  const source = String(datatype).trim();
2225
2307
  const lowered = source.toLowerCase();
2226
2308
  const loweredBase = typeof base === 'string' ? base.toLowerCase() : base;
2227
- if (/^radix\d+$/.test(lowered) && !['radix2', 'radix6', 'radix8', 'radix12'].includes(lowered)) {
2309
+ if (/^radix\d+$/.test(lowered) && !['radix2', 'radix6', 'radix8', 'radix12', 'radix16'].includes(lowered)) {
2228
2310
  return {
2229
2311
  ok: false,
2230
2312
  error: mutationTargetSurfaceError(
@@ -2610,6 +2692,238 @@ function capitalize(value) {
2610
2692
  return value.slice(0, 1).toUpperCase() + value.slice(1);
2611
2693
  }
2612
2694
 
2695
+ function propertyExpression(expression) {
2696
+ return findExpression(expression, (entry, type) => type === 'resolutionExpression' && hasPropertyAst(astData(entry, 'address')));
2697
+ }
2698
+
2699
+ // Read only own data fields. Admission must not execute caller AST accessors,
2700
+ // including array elements or projection/requirement wrappers.
2701
+ function astArray(value) {
2702
+ if (!Array.isArray(value)) throw new PropertyAddressError('Expected AST array');
2703
+ return value;
2704
+ }
2705
+ function* astEntries(value) {
2706
+ const entries = astArray(value);
2707
+ const length = astData(entries, 'length');
2708
+ for (let i = 0; i < length; i++) yield astData(entries, String(i));
2709
+ }
2710
+ function clauseHasProperty(clause) {
2711
+ return clause != null && propertyExpression(astData(clause, 'ast'));
2712
+ }
2713
+ function instructionHasProperty(instruction, options) {
2714
+ const mutation = astData(instruction, 'mutation');
2715
+ const from = astData(instruction, 'from', true);
2716
+ if (from && hasPropertyAst(astData(from, 'address'))) return true;
2717
+ for (const role of ['target', 'source', 'container', 'parent', 'destination']) {
2718
+ const target = astData(mutation, role, true);
2719
+ // A create destination may be a member name rather than an address role.
2720
+ const address = target && astData(target, 'address', true);
2721
+ if (address && hasPropertyAst(address)) return true;
2722
+ }
2723
+ const placement = astData(mutation, 'placement', true);
2724
+ const anchor = placement && astData(placement, 'anchor', true);
2725
+ if (anchor && hasPropertyAst(astData(anchor, 'address'))) return true;
2726
+ if (clauseHasProperty(astData(instruction, 'where', true))) return true;
2727
+ const requirements = astData(instruction, 'requires', true);
2728
+ if (requirements != null) for (const requirement of astEntries(requirements)) {
2729
+ if (clauseHasProperty(requirement)
2730
+ || propertyExpressionSource(astData(requirement, 'expression'), mutationQueryExpressionParseOptions({parse:options.parse ?? options}))) return true;
2731
+ }
2732
+ return false;
2733
+ }
2734
+
2735
+ function propertyExpressionSource(source, options, details = {}) {
2736
+ if (typeof source !== 'string' || !source.includes('&')) return false;
2737
+ // Reuse the expression cursor's comment normalization. This lexical gate
2738
+ // avoids reparsing inert quoted/encoded data in an unused native requirement;
2739
+ // the real parser and AST scan remain authoritative for candidate suffixes.
2740
+ let input;
2741
+ try { input = new QueryExpressionParser(source, options).input; }
2742
+ catch (error) {
2743
+ if (!(error instanceof SansaParseError)) throw error;
2744
+ throw new PropertyAddressError('Cannot preflight precondition syntax', 'SANSA_MUTATE_INVALID_PRECONDITION', {cause:{code:error.code, message:error.message, index:error.index}, ...details});
2745
+ }
2746
+ let quote = null;
2747
+ let candidate = false;
2748
+ for (let index = 0; index < input.length; index++) {
2749
+ const char = input[index];
2750
+ if (quote) {
2751
+ if (char === '\\') index++;
2752
+ else if (char === quote) quote = null;
2753
+ } else if (char === '"' || isSymbolLiteralStart(input, index)) quote = char;
2754
+ else if (char === '&') {
2755
+ let end = index + 1;
2756
+ while (isIdentifierContinue(input[end])) end++;
2757
+ if (input[end] === '(') { candidate = true; break; }
2758
+ }
2759
+ }
2760
+ if (!candidate) return false;
2761
+ let parsed;
2762
+ try { parsed = parseQueryExpression(source, options); }
2763
+ catch (error) {
2764
+ if (!(error instanceof RangeError)) throw error;
2765
+ throw new PropertyAddressError('Cannot preflight precondition syntax', 'SANSA_MUTATE_INVALID_PRECONDITION', details);
2766
+ }
2767
+ if (!parsed.ok) throw new PropertyAddressError('Cannot preflight precondition syntax', 'SANSA_MUTATE_INVALID_PRECONDITION', {cause:parsed.errors[0], ...details});
2768
+ return propertyExpression(parsed.expression);
2769
+ }
2770
+
2771
+ // This is admission preflight, not evaluation: inspect all active address roles
2772
+ // and preconditions before any operation can resolve a target or invoke a hook.
2773
+ function preflightMutationProperties(operations, preconditions, options, planned = false) {
2774
+ const phase = planned ? 'apply' : 'policy';
2775
+ const addressHasProperty = input => {
2776
+ if (planned && input && typeof input === 'object' && typeof input.canonicalAddress === 'string') input = input.canonicalAddress;
2777
+ if (typeof input !== 'string') return input && typeof input === 'object' && hasPropertyAst(input);
2778
+ if (!hasPropertySyntax(input)) return false;
2779
+ const parsed = parseAddress(input, options.parse);
2780
+ if (!parsed.ok) throw new PropertyAddressError('Invalid property target', 'SANSA_MUTATE_INVALID_TARGET', {cause:parsed.errors[0]});
2781
+ return true;
2782
+ };
2783
+ try {
2784
+ for (let operationIndex = 0; operationIndex < operations.length; operationIndex++) {
2785
+ const operation = operations[operationIndex];
2786
+ for (const role of ['target', 'parent', 'source', 'container']) {
2787
+ if (addressHasProperty(operation?.[role])) return mutationError('SANSA_MUTATE_NON_EXACT_TARGET', 'Property mutation targets are not admitted', {phase, operationIndex});
2788
+ }
2789
+ const anchor = operation?.placement?.anchor ?? operation?.placement?.target;
2790
+ if (addressHasProperty(anchor)) return mutationError('SANSA_MUTATE_NON_EXACT_TARGET', 'Property mutation anchors are not admitted', {phase, operationIndex});
2791
+ }
2792
+ const parseOptions = mutationQueryExpressionParseOptions(options);
2793
+ for (let preconditionIndex = 0; Array.isArray(preconditions) && preconditionIndex < preconditions.length; preconditionIndex++) {
2794
+ const precondition = preconditions[preconditionIndex];
2795
+ if (addressHasProperty(precondition?.target)
2796
+ || propertyExpressionSource(precondition?.expression, parseOptions, {preconditionIndex})
2797
+ || planned && propertyExpressionSource(precondition?.canonical, parseOptions, {preconditionIndex})) {
2798
+ return mutationError('SANSA_RESOLVE_UNSUPPORTED_SELECTOR', 'Property mutation preconditions are not admitted', {phase, preconditionIndex});
2799
+ }
2800
+ }
2801
+ } catch (error) {
2802
+ if (!(error instanceof PropertyAddressError)) throw error;
2803
+ return mutationError(error.code === 'SANSA_MUTATE_INVALID_PRECONDITION' ? error.code : 'SANSA_MUTATE_INVALID_TARGET', error.message,
2804
+ {phase, ...(error.preconditionIndex === undefined ? {} : {preconditionIndex:error.preconditionIndex}), ...(error.cause === undefined ? {} : {cause:error.cause})});
2805
+ }
2806
+ return null;
2807
+ }
2808
+
2809
+ function queryPropertySelectors(query) {
2810
+ const selectors = [];
2811
+ const address = value => {
2812
+ if (hasPropertyAst(value)) {
2813
+ // Rendering validates every selector, including bounds and qualifiers.
2814
+ renderAddress(value);
2815
+ let index=0;
2816
+ for (const selector of astEntries(astData(value,'selectors'))) { if (astData(selector,'type') === 'propertyFilter') selectors.push({type:'propertyFilter',property:astData(selector,'property'),value:astData(selector,'value'),querySelectorIndex:index}); index++; }
2817
+ }
2818
+ };
2819
+ const expression = value => findExpression(value, (entry, type) => {
2820
+ if (type === 'resolutionExpression') address(astData(entry,'address'));
2821
+ return false;
2822
+ });
2823
+ const from = astData(query,'from');
2824
+ if (astData(from,'source') === 'expression') expression(astData(from,'ast')); else address(astData(from,'address'));
2825
+ const where = astData(query,'where',true);
2826
+ if (where) expression(astData(where,'ast'));
2827
+ const order = astData(query,'orderBy',true);
2828
+ if (order) for (const key of astEntries(astData(order,'keys'))) expression(astData(key,'ast'));
2829
+ expression(astData(astData(query,'select'),'ast'));
2830
+ return selectors;
2831
+ }
2832
+ function queryHasProperty(query) { return queryPropertySelectors(query).length > 0; }
2833
+
2834
+ function normalizePropertyQuery(query, parseOptions) {
2835
+ // Snapshot caller data before any namespace hook can mutate it. Bounds apply
2836
+ // only to the newly admitted property Query surface, not existing Query ASTs.
2837
+ const active = new Set();
2838
+ const completed = new WeakMap();
2839
+ let nodes = 0, scalars = 0;
2840
+ const clone = (value, depth) => {
2841
+ if (++nodes > 20000 || depth > 128) throw new PropertyAddressError('Query AST preparation bound exceeded');
2842
+ if (typeof value === 'string') { scalars += value.length; if (scalars > 1048576) throw new PropertyAddressError('Query AST text bound exceeded'); }
2843
+ if (['function','symbol','bigint'].includes(typeof value)) throw new PropertyAddressError('Invalid Query AST value');
2844
+ if (value === null || typeof value !== 'object') return value;
2845
+ if (active.has(value)) throw new PropertyAddressError('Cyclic Query AST');
2846
+ if (completed.has(value)) return completed.get(value);
2847
+ active.add(value);
2848
+ const copy = Array.isArray(value) ? [] : {};
2849
+ for (const key of Object.getOwnPropertyNames(value)) {
2850
+ if (Array.isArray(value) && key === 'length') continue;
2851
+ Object.defineProperty(copy,key,{value:clone(astData(value,key),depth+1),enumerable:true,writable:true,configurable:true});
2852
+ }
2853
+ active.delete(value);
2854
+ if (copy.type === 'resolutionExpression') {
2855
+ const rendered = renderAddress(copy.address);
2856
+ if (!['absolute','contextual','current'].includes(copy.scope)
2857
+ || (copy.scope === 'absolute') !== (copy.address.root.kind === 'absolute')) throw new PropertyAddressError('Invalid resolution scope');
2858
+ copy.canonical = copy.scope === 'current'
2859
+ ? (rendered === '?' ? '.' : rendered[1] === '&' || rendered[1] === '[' ? '.' + rendered.slice(1) : rendered.slice(1)) : rendered;
2860
+ }
2861
+ completed.set(value,copy);
2862
+ return copy;
2863
+ };
2864
+ let rendered;
2865
+ try { const snapshot=clone(query,0); boundPropertyQueryRendering(snapshot); rendered = renderQuery(snapshot); }
2866
+ catch (error) { if (error instanceof PropertyAddressError) throw error; throw new PropertyAddressError('Invalid property Query AST'); }
2867
+ const parsed = parseQuery(rendered, parseOptions);
2868
+ if (!parsed.ok) throw new PropertyAddressError('Invalid property Query AST');
2869
+ return parsed.query;
2870
+ }
2871
+ // Sharing reduces snapshot work, but Query expressions can reuse a subtree at
2872
+ // many semantic positions. Charge those rendered occurrences before invoking
2873
+ // the ordinary renderer, using the existing preparation bounds. Qualifier
2874
+ // convenience aliases are not semantic expression edges.
2875
+ function boundPropertyQueryRendering(query) {
2876
+ const pending=[];
2877
+ let entries=0, text=100;
2878
+ const add=value=>{
2879
+ if(typeof value!=='string')throw new PropertyAddressError('Invalid Query AST text');
2880
+ text+=value.length;
2881
+ if(text>1048576)throw new PropertyAddressError('Query AST text bound exceeded');
2882
+ };
2883
+ if(query.from.source==='expression')pending.push(query.from.ast);else add(renderAddress(query.from.address));
2884
+ if(query.where)pending.push(query.where.ast);
2885
+ if(query.orderBy)for(const key of query.orderBy.keys){add(key.direction);pending.push(key.ast);}
2886
+ for(const clause of [query.offset,query.limit])if(clause && (!Number.isSafeInteger(clause.value)||clause.value<0))throw new PropertyAddressError('Invalid Query AST integer');
2887
+ pending.push(query.select.ast);
2888
+ while(pending.length){
2889
+ const expression=pending.pop();
2890
+ if(++entries>20000)throw new PropertyAddressError('Query AST preparation bound exceeded');
2891
+ add(' ');
2892
+ switch(expression.type){
2893
+ case 'literalExpression':
2894
+ if(expression.canonical!==undefined)add(expression.canonical);
2895
+ else if(expression.value===null||['string','number','boolean'].includes(typeof expression.value))add(renderQueryExpression(expression));
2896
+ else throw new PropertyAddressError('Invalid Query AST literal');
2897
+ break;
2898
+ case 'currentBindingExpression':break;
2899
+ case 'resolutionExpression':add(expression.canonical);break;
2900
+ case 'groupExpression':pending.push(expression.expression);break;
2901
+ case 'unaryExpression':case 'existenceExpression':case 'cardinalityExpression':add(expression.operator);pending.push(expression.argument);break;
2902
+ case 'binaryExpression':add(expression.operator);pending.push(expression.right,expression.left);break;
2903
+ case 'functionCallExpression':add(expression.name);for(const argument of expression.arguments)pending.push(argument);break;
2904
+ case 'projectionExpression':for(const field of expression.fields){add(field.name);pending.push(field.expression);}break;
2905
+ default:throw new PropertyAddressError('Invalid Query AST expression');
2906
+ }
2907
+ }
2908
+ }
2909
+
2910
+ function validatePropertyQueryRoots(query, namespace, options) {
2911
+ const resolve = options.resolve ?? {};
2912
+ const limit = resolve.maxPropertyInspections === undefined ? DEFAULT_PROPERTY_INSPECTIONS : resolve.maxPropertyInspections;
2913
+ if (!validPropertyLimit(limit)) return resolveError('SANSA_RESOLVE_INVALID_PROPERTY_LIMIT','Property inspection limit must be an integer from 0 through 1000000');
2914
+ if (resolve.maxBindings !== undefined && (!Number.isSafeInteger(resolve.maxBindings) || resolve.maxBindings < 0)) return resolveError('SANSA_RESOLVE_INVALID_BINDING_LIMIT','Invalid binding limit');
2915
+ if (resolve.maxIdentityInspections !== undefined && (!Number.isSafeInteger(resolve.maxIdentityInspections) || resolve.maxIdentityInspections < 0)) return resolveError('SANSA_RESOLVE_INVALID_IDENTITY_LIMIT','Invalid identity limit');
2916
+ const from = query.from;
2917
+ const root = resolveRoot(from.source === 'expression' ? {kind:'absolute'} : from.address.root, namespace ?? {}, resolve);
2918
+ return root.ok ? undefined : root.error;
2919
+ }
2920
+ function queryRowOptions(options, context) { return context ? {...options,[QUERY_CURRENT_FRAME]:context} : options; }
2921
+ function transferQueryFrames(source, target, options) {
2922
+ const state = options[QUERY_PROPERTIES];
2923
+ if (state) state.frames.set(target, state.frames.get(source) ?? []);
2924
+ return target;
2925
+ }
2926
+
2613
2927
  function enforceQueryPolicy(query, options) {
2614
2928
  if (!isValidationQueryPolicy(options.policy)) return { ok: true };
2615
2929
 
@@ -2627,8 +2941,8 @@ function enforceQueryPolicy(query, options) {
2627
2941
  query.select.ast,
2628
2942
  ];
2629
2943
  const disallowedFunction = expressions
2630
- .map((expression) => findExpression(expression, (entry) => entry.type === 'functionCallExpression'
2631
- && TRANSFORM_EXTENSION_FUNCTIONS.has(entry.name)))
2944
+ .map((expression) => findExpression(expression, (entry, type) => type === 'functionCallExpression'
2945
+ && TRANSFORM_EXTENSION_FUNCTIONS.has(astData(entry, 'name'))))
2632
2946
  .find(Boolean);
2633
2947
  if (disallowedFunction) {
2634
2948
  return queryPolicyViolation(
@@ -2671,39 +2985,82 @@ function normalizeQueryBudgetLimit(value) {
2671
2985
  }
2672
2986
 
2673
2987
  function findExpression(expression, predicate) {
2674
- if (predicate(expression)) return expression;
2675
-
2676
- switch (expression.type) {
2677
- case 'groupExpression':
2678
- return findExpression(expression.expression, predicate);
2679
- case 'unaryExpression':
2680
- return findExpression(expression.argument, predicate);
2681
- case 'binaryExpression':
2682
- return findExpression(expression.left, predicate)
2683
- ?? findExpression(expression.right, predicate);
2684
- case 'functionCallExpression':
2685
- for (const argument of expression.arguments) {
2686
- const found = findExpression(argument, predicate);
2687
- if (found) return found;
2688
- }
2689
- return null;
2690
- case 'existenceExpression':
2691
- case 'cardinalityExpression':
2692
- return findExpression(expression.argument, predicate);
2693
- case 'projectionExpression':
2694
- for (const field of expression.fields) {
2695
- const found = findExpression(field.expression, predicate);
2696
- if (found) return found;
2988
+ const active = new Set();
2989
+ const complete = new Set();
2990
+ const stack = [{expression, index: -1}];
2991
+ while (stack.length) {
2992
+ const frame = stack.at(-1);
2993
+ if (frame.index === -1) {
2994
+ if (complete.has(frame.expression)) { stack.pop(); continue; }
2995
+ if (active.has(frame.expression)) throw new PropertyAddressError('Cyclic expression AST');
2996
+ const type = astData(frame.expression, 'type');
2997
+ astData(frame.expression, 'canonical', true);
2998
+ if (predicate(frame.expression, type)) return frame.expression;
2999
+ active.add(frame.expression);
3000
+ frame.projection = false;
3001
+ switch (type) {
3002
+ case 'groupExpression': frame.children = [astData(frame.expression, 'expression')]; break;
3003
+ case 'unaryExpression': case 'existenceExpression': case 'cardinalityExpression':
3004
+ astData(frame.expression, 'operator', true);
3005
+ frame.children = [astData(frame.expression, 'argument')]; break;
3006
+ case 'binaryExpression':
3007
+ astData(frame.expression, 'operator', true);
3008
+ frame.children = [astData(frame.expression, 'left'), astData(frame.expression, 'right')]; break;
3009
+ case 'functionCallExpression':
3010
+ astData(frame.expression, 'name');
3011
+ frame.children = astArray(astData(frame.expression, 'arguments')); break;
3012
+ case 'projectionExpression': frame.children = astArray(astData(frame.expression, 'fields')); frame.projection = true; break;
3013
+ case 'resolutionExpression': astData(frame.expression, 'scope', true); frame.children = []; break;
3014
+ case 'literalExpression':
3015
+ astData(frame.expression, 'kind', true); astData(frame.expression, 'value', true); astData(frame.expression, 'nullReason', true);
3016
+ frame.children = []; break;
3017
+ default: frame.children = [];
2697
3018
  }
2698
- return null;
2699
- default:
2700
- return null;
3019
+ frame.length = astData(frame.children, 'length');
3020
+ frame.index = 0;
3021
+ }
3022
+ if (frame.index < frame.length) {
3023
+ const child = astData(frame.children, String(frame.index++));
3024
+ if (frame.projection) astData(child, 'name');
3025
+ stack.push({expression: frame.projection ? astData(child, 'expression') : child, index: -1});
3026
+ } else {
3027
+ active.delete(frame.expression);
3028
+ complete.add(frame.expression);
3029
+ stack.pop();
3030
+ }
2701
3031
  }
3032
+ return null;
3033
+ }
3034
+
3035
+ function resolveConsumerAddress(input, namespace, options = {}) {
3036
+ return resolveAddress(input, namespace, { ...options, [DENY_CHILD_IDENTITY]: true, [DENY_PROPERTIES]: true });
2702
3037
  }
2703
3038
 
2704
3039
  export function resolveAddress(input, namespace, options = {}) {
2705
- const parsed = typeof input === 'string' ? parseAddress(input, options.parse) : { ok: true, address: input };
3040
+ let parsed;
3041
+ try {
3042
+ parsed = typeof input === 'string' ? parseAddress(input, options.parse)
3043
+ : hasPropertyAst(input) ? parseAddress(renderAddress(input), options.parse) : {ok:true,address:input};
3044
+ } catch (error) {
3045
+ return {ok:false,bindings:[],errors:[resolveError('SANSA_RESOLVE_INVALID_ADDRESS','Invalid property address AST', undefined,
3046
+ error instanceof PropertyAddressError ? {causeCode: error.code} : {})]};
3047
+ }
2706
3048
  if (!parsed.ok) return { ok: false, bindings: [], errors: parsed.errors };
3049
+ const hasIdentity = !(typeof input === 'string' && parsed.address.isExact)
3050
+ && Array.isArray(parsed.address?.selectors) && parsed.address.selectors.some(s => s?.type === 'childIdentity');
3051
+ if (hasIdentity && typeof input !== 'string') {
3052
+ try {
3053
+ if (input.type !== 'SansaAddress' || input.root?.type !== 'root' || !['absolute', 'contextual'].includes(input.root.kind)) throw new Error('invalid root');
3054
+ parsed = parseAddress(renderAddress(input), options.parse);
3055
+ if (!parsed.ok) throw new Error('invalid selectors');
3056
+ } catch {
3057
+ return { ok: false, bindings: [], errors: [resolveError('SANSA_RESOLVE_INVALID_ADDRESS', 'Invalid identity address AST')] };
3058
+ }
3059
+ }
3060
+ const maxIdentityInspections = options.maxIdentityInspections === undefined ? DEFAULT_IDENTITY_INSPECTIONS : options.maxIdentityInspections;
3061
+ if (!Number.isSafeInteger(maxIdentityInspections) || maxIdentityInspections < 0) {
3062
+ return { ok: false, bindings: [], errors: [resolveError('SANSA_RESOLVE_INVALID_IDENTITY_LIMIT', 'Identity inspection limit must be a non-negative safe integer')] };
3063
+ }
2707
3064
 
2708
3065
  const maxBindings = options.maxBindings;
2709
3066
  if (maxBindings !== undefined && (!Number.isSafeInteger(maxBindings) || maxBindings < 0)) {
@@ -2714,8 +3071,31 @@ export function resolveAddress(input, namespace, options = {}) {
2714
3071
  };
2715
3072
  }
2716
3073
 
3074
+ const propertyIndex = parsed.address.selectors.findIndex(s => s.type === 'propertyFilter');
3075
+ const maxPropertyInspections = options.maxPropertyInspections === undefined ? DEFAULT_PROPERTY_INSPECTIONS : options.maxPropertyInspections;
3076
+ if (!validPropertyLimit(maxPropertyInspections)) return {ok:false,bindings:[],errors:[resolveError('SANSA_RESOLVE_INVALID_PROPERTY_LIMIT','Property inspection limit must be an integer from 0 through 1000000')]};
3077
+ if (propertyIndex !== -1 && options[DENY_PROPERTIES]) return {ok:false,bindings:[],errors:[resolveError('SANSA_RESOLVE_UNSUPPORTED_SELECTOR','Property selectors are not admitted by this consumer',propertyIndex)]};
2717
3078
  const rootResult = resolveRoot(parsed.address.root, namespace, options);
2718
3079
  if (!rootResult.ok) return { ok: false, bindings: [], errors: [rootResult.error] };
3080
+ const prepared = options[QUERY_PROPERTIES]?.prepared ?? (propertyIndex === -1 ? undefined : prepareProperties(namespace, parsed.address.selectors));
3081
+ if (prepared?.error) return {ok:false,bindings:[],errors:[prepared.error]};
3082
+ if (hasIdentity) {
3083
+ const selectorIndex = parsed.address.selectors.findIndex(s => s.type === 'childIdentity');
3084
+ const identity = parsed.address.selectors[selectorIndex].identity;
3085
+ if (options[DENY_CHILD_IDENTITY] || typeof namespace.identity !== 'function') {
3086
+ const code = options[DENY_CHILD_IDENTITY] ? 'SANSA_RESOLVE_UNSUPPORTED_SELECTOR' : 'SANSA_RESOLVE_UNSUPPORTED_IDENTITY';
3087
+ return { ok: false, bindings: [], errors: [resolveError(code, 'Child identity selection is not supported by this consumer or namespace', selectorIndex, { identity })] };
3088
+ }
3089
+ }
3090
+ const identityBudget = hasIdentity
3091
+ ? (options[QUERY_IDENTITY_BUDGET] ?? { inspected: 0 })
3092
+ : undefined;
3093
+
3094
+ if (prepared) return resolvePropertyAddress(parsed.address, namespace, rootResult.binding, prepared, {
3095
+ effectiveRoot: options.allowParentFromEffectiveRoot === true ? undefined : rootResult.binding,
3096
+ parentTraversal: options.parentTraversal, failOnParentFromEffectiveRoot: options.failOnParentFromEffectiveRoot === true,
3097
+ maxBindings, identityBudget, maxIdentityInspections, identityActivationGuard: options[IDENTITY_ACTIVATION_GUARD],
3098
+ }, maxPropertyInspections, options);
2719
3099
 
2720
3100
  if (maxBindings === 0 && parsed.address.selectors.length === 0) {
2721
3101
  return {
@@ -2738,6 +3118,9 @@ export function resolveAddress(input, namespace, options = {}) {
2738
3118
  parentTraversal: options.parentTraversal,
2739
3119
  failOnParentFromEffectiveRoot: options.failOnParentFromEffectiveRoot === true,
2740
3120
  maxBindings,
3121
+ identityBudget,
3122
+ maxIdentityInspections,
3123
+ identityActivationGuard: options[IDENTITY_ACTIVATION_GUARD],
2741
3124
  },
2742
3125
  );
2743
3126
  if (!selected.ok) return { ok: false, bindings: [], errors: [selected.error] };
@@ -2768,6 +3151,54 @@ export function resolveAddress(input, namespace, options = {}) {
2768
3151
  return { ok: true, bindings: current, diagnostics: [] };
2769
3152
  }
2770
3153
 
3154
+ function resolvePropertyAddress(address, namespace, root, prepared, policy, limit, options = {}) {
3155
+ let current = [{binding: root, context: options[QUERY_RESOLVE_FRAME] ?? propertyContext(root, root)}];
3156
+ const budget = options[QUERY_PROPERTIES]?.budget ?? {inspected: 0, limit: limit === 0 ? 0 : limit};
3157
+ if (policy.maxBindings === 0 && address.selectors.length === 0) return {ok:false,bindings:[],errors:[resolveBindingLimitError(0,1)]};
3158
+ for (let index = 0; index < address.selectors.length; index++) {
3159
+ const selector = address.selectors[index];
3160
+ if (selector.type === 'parent' || selector.type === 'attributeSpace') {
3161
+ // These helpers decide support/policy over the whole input set. Project
3162
+ // their selected values back to occurrence frames before filtering; a
3163
+ // binding-keyed map would merge aliases from different authorized scopes.
3164
+ const sources = selector.type === 'parent'
3165
+ ? current.filter(occurrence => occurrence.binding !== policy.effectiveRoot)
3166
+ : current;
3167
+ const project = (binding, sourceIndex) => ({binding, context: selector.type === 'attributeSpace'
3168
+ ? propertyContext(binding, binding) : sources[sourceIndex].context});
3169
+ const bindings = current.map(occurrence => occurrence.binding);
3170
+ const selected = selector.type === 'parent'
3171
+ ? selectParents(namespace, bindings, index, policy, project)
3172
+ : selectAttributeSpaces(namespace, bindings, index, project);
3173
+ if (!selected.ok) return {ok:false,bindings:[],errors:[selected.error]};
3174
+ if (policy.maxBindings !== undefined && selected.bindings.length > policy.maxBindings) return {ok:false,bindings:[],errors:[resolveBindingLimitError(policy.maxBindings, selected.bindings.length, index)]};
3175
+ current = selected.bindings;
3176
+ if (!current.length) break;
3177
+ continue;
3178
+ }
3179
+ const next = [];
3180
+ for (const occurrence of current) {
3181
+ if (selector.type === 'propertyFilter') {
3182
+ const selected = selectProperty(occurrence.binding, occurrence.context, prepared, selector, index, budget);
3183
+ if (selected.error) return {ok:false,bindings:[],errors:[selected.error]};
3184
+ if (selected.match) next.push(occurrence);
3185
+ } else {
3186
+ const maxBindings = policy.maxBindings === undefined ? undefined : policy.maxBindings - next.length;
3187
+ const selected = applyResolveSelector(selector, [occurrence.binding], namespace, index, {...policy, maxBindings});
3188
+ if (!selected.ok) return {ok:false,bindings:[],errors:[selected.error.code === 'SANSA_RESOLVE_BINDING_LIMIT_EXCEEDED' ? resolveBindingLimitError(policy.maxBindings, policy.maxBindings + 1, index) : selected.error]};
3189
+ for (const binding of selected.bindings) next.push({binding, context: ['attributeSpace', 'localSpace'].includes(selector.type) ? propertyContext(binding, binding) : occurrence.context});
3190
+ }
3191
+ if (policy.maxBindings !== undefined && next.length > policy.maxBindings) return {ok:false,bindings:[],errors:[resolveBindingLimitError(policy.maxBindings, next.length, index)]};
3192
+ }
3193
+ current = next;
3194
+ if (!current.length) break;
3195
+ }
3196
+ if (address.isExact && current.length > 1) return {ok:false,bindings:[],errors:[resolveError('SANSA_RESOLVE_EXACT_MULTIPLICITY_VIOLATION','Exact SANSA resolution produced more than one binding')]};
3197
+ const result = {ok:true,bindings:current.map(occurrence => occurrence.binding),diagnostics:[]};
3198
+ options[QUERY_PROPERTIES]?.frames.set(result,current.map(occurrence => occurrence.context));
3199
+ return result;
3200
+ }
3201
+
2771
3202
  export function traverseGraph(starts, namespace, declarations, options = {}) {
2772
3203
  const invalid = validateGraphInput(starts, namespace, declarations, options);
2773
3204
  if (invalid) return { ok: false, bindings: [], paths: [], errors: [invalid] };
@@ -2796,7 +3227,7 @@ export function traverseGraph(starts, namespace, declarations, options = {}) {
2796
3227
  startAddress,
2797
3228
  });
2798
3229
  }
2799
- const edges = resolveAddress(declaration.edgeAddress, namespace, {
3230
+ const edges = resolveConsumerAddress(declaration.edgeAddress, namespace, {
2800
3231
  contextualRoot: start,
2801
3232
  maxBindings: options.budget.maxVisitedEdges,
2802
3233
  });
@@ -2834,7 +3265,7 @@ export function traverseGraph(starts, namespace, declarations, options = {}) {
2834
3265
  edgeAddress,
2835
3266
  });
2836
3267
  }
2837
- const target = resolveAddress(targetAddress, namespace, { maxBindings: 2 });
3268
+ const target = resolveConsumerAddress(targetAddress, namespace, { maxBindings: 2 });
2838
3269
  if (!target.ok) return { ok: false, bindings: [], paths: [], errors: target.errors };
2839
3270
  if (target.bindings.length === 0) {
2840
3271
  if (declaration.danglingTarget === 'error') {
@@ -3041,6 +3472,7 @@ function validateGraphInput(starts, namespace, declarations, options) {
3041
3472
  || (declaration.danglingTarget !== 'omit' && declaration.danglingTarget !== 'error')) {
3042
3473
  return graphError('SANSA_GRAPH_INVALID_DECLARATION', 'Graph relationship declaration is invalid');
3043
3474
  }
3475
+ if (hasPropertySyntax(declaration.edgeAddress)) return graphError('SANSA_GRAPH_INVALID_DECLARATION','Property selectors are not admitted by Graph');
3044
3476
  if (ids.has(declaration.id)) {
3045
3477
  return graphError('SANSA_GRAPH_DUPLICATE_DECLARATION', `Graph relationship declaration '${declaration.id}' is duplicated`, {
3046
3478
  declarationId: declaration.id,
@@ -3105,6 +3537,13 @@ function graphError(code, message, details = {}) {
3105
3537
  }
3106
3538
 
3107
3539
  export function renderAddress(address) {
3540
+ if (hasPropertyAst(address)) return renderPropertyAddress(address, quotePayload, renderQualifierNumber);
3541
+ return renderLegacyAddress(address);
3542
+ }
3543
+
3544
+ function renderLegacyAddress(address) {
3545
+ if (Array.isArray(address?.selectors) && address.selectors.some(s => s?.type === 'childIdentity')
3546
+ && !validIdentityAddressAst(address)) throw new Error('Invalid identity address AST');
3108
3547
  let output = address.root.kind === 'absolute' ? '$' : '?';
3109
3548
 
3110
3549
  for (const selector of address.selectors) {
@@ -3145,7 +3584,7 @@ export function renderAddress(address) {
3145
3584
  output += `%${selector.name}`;
3146
3585
  break;
3147
3586
  default:
3148
- throw new Error(`Unknown selector type: ${selector.type}`);
3587
+ output += renderExtendedSelector(selector);
3149
3588
  }
3150
3589
  }
3151
3590
 
@@ -3156,6 +3595,75 @@ export function renderAddress(address) {
3156
3595
  return output;
3157
3596
  }
3158
3597
 
3598
+ // Validate caller data before rendering can turn unquoted payloads into syntax.
3599
+ // The ordinary parsed-address rendering path retains its existing contract.
3600
+ function validIdentityAddressAst(address) {
3601
+ if (address.type !== 'SansaAddress' || address.root?.type !== 'root'
3602
+ || !['absolute', 'contextual'].includes(address.root.kind)) return false;
3603
+ const text = value => typeof value === 'string';
3604
+ const index = value => Number.isSafeInteger(value) && value >= 0;
3605
+ for (const s of address.selectors) {
3606
+ if (!s) return false;
3607
+ switch (s.type) {
3608
+ case 'childIdentity':
3609
+ if (!text(s.identity) || !CHILD_IDENTITY_RE.test(s.identity)) return false;
3610
+ break;
3611
+ case 'member': case 'localSpace':
3612
+ if (!text(s.name)) return false;
3613
+ break;
3614
+ case 'namePattern':
3615
+ if (!text(s.pattern)) return false;
3616
+ break;
3617
+ case 'semanticTypeFilter': case 'representationKindFilter':
3618
+ if (!text(s.name) || !IDENTIFIER_RE.test(s.name)) return false;
3619
+ break;
3620
+ case 'position':
3621
+ if (!index(s.index)) return false;
3622
+ break;
3623
+ case 'positionRange':
3624
+ if (![s.start, s.end].every(v => v == null || index(v))) return false;
3625
+ break;
3626
+ case 'parent': case 'attributeSpace': case 'directExpansion': case 'descendantExpansion': break;
3627
+ default: return false;
3628
+ }
3629
+ }
3630
+ if (!address.qualifierExpression) return true;
3631
+ const terms = address.qualifierExpression.terms;
3632
+ if (!Array.isArray(terms) || terms.length === 0) return false;
3633
+ const stack = terms.map(term => [term, false]);
3634
+ const ancestors = new Set();
3635
+ while (stack.length) {
3636
+ const [term, leaving] = stack.pop();
3637
+ if (leaving) { ancestors.delete(term); continue; }
3638
+ if (!term || ancestors.has(term) || !text(term.name) || !IDENTIFIER_RE.test(term.name)
3639
+ || !Array.isArray(term.arguments)) return false;
3640
+ ancestors.add(term);
3641
+ stack.push([term, true]);
3642
+ const groups = term.parameterGroups ?? (Array.isArray(term.parameters) && term.parameters.length ? [term.parameters] : []);
3643
+ if (!Array.isArray(groups)) return false;
3644
+ for (const group of groups) {
3645
+ if (!Array.isArray(group) || group.length === 0) return false;
3646
+ for (const child of group) stack.push([child, false]);
3647
+ }
3648
+ for (const arg of term.arguments) {
3649
+ if (!arg) return false;
3650
+ if (arg.kind === 'quoted') { if (!text(arg.value)) return false; }
3651
+ else if (arg.kind === 'number') {
3652
+ if (typeof arg.value !== 'number' || !Number.isFinite(arg.value)) return false;
3653
+ } else if (arg.kind === 'token') {
3654
+ if (!text(arg.value) || !QUALIFIER_NUMBER_RE.test(arg.value)) return false;
3655
+ } else return false;
3656
+ }
3657
+ }
3658
+ return true;
3659
+ }
3660
+
3661
+ function renderExtendedSelector(selector) {
3662
+ if (selector.type !== 'childIdentity') throw new Error(`Unknown selector type: ${selector.type}`);
3663
+ if (typeof selector.identity !== 'string' || !CHILD_IDENTITY_RE.test(selector.identity)) throw new Error('Invalid child identity');
3664
+ return `.\\${selector.identity}\\`;
3665
+ }
3666
+
3159
3667
  export function renderQuery(query) {
3160
3668
  const lines = [`from ${renderQueryFromClause(query.from)}`];
3161
3669
  if (query.where) lines.push(`where ${renderQueryExpression(query.where.ast)}`);
@@ -3360,7 +3868,7 @@ function resolveInstructionFromCandidates(instruction, namespace, options) {
3360
3868
  return [root.binding];
3361
3869
  }
3362
3870
 
3363
- const resolved = resolveAddress(instruction.from.address, namespace, options.resolve);
3871
+ const resolved = resolveConsumerAddress(instruction.from.address, namespace, options.resolve);
3364
3872
  if (!resolved.ok) {
3365
3873
  throw new SansaInstructionLowerError(instructionLowerError(
3366
3874
  'SANSA_INSTRUCTION_CANDIDATE_RESOLUTION_FAILED',
@@ -3452,7 +3960,7 @@ function resolveInstructionExactAddress(instructionAddress, candidate, namespace
3452
3960
  ));
3453
3961
  }
3454
3962
 
3455
- const resolved = resolveAddress(address, namespace, {
3963
+ const resolved = resolveConsumerAddress(address, namespace, {
3456
3964
  ...(options.resolve ?? {}),
3457
3965
  ...(address.root.kind === 'contextual' ? { contextualRoot: candidate, allowParentFromEffectiveRoot: true } : {}),
3458
3966
  });
@@ -3594,9 +4102,16 @@ function isBindingObject(value) {
3594
4102
  return value !== null && typeof value === 'object';
3595
4103
  }
3596
4104
 
4105
+ function resolveQueryAddress(address, namespace, options, resolveOptions = options.resolve) {
4106
+ const budget = options[QUERY_IDENTITY_BUDGET];
4107
+ return budget === undefined
4108
+ ? resolveConsumerAddress(address, namespace, resolveOptions)
4109
+ : resolveAddress(address, namespace, { ...resolveOptions, [QUERY_IDENTITY_BUDGET]: budget, [DENY_PROPERTIES]: !options[QUERY_PROPERTIES], ...(options[QUERY_PROPERTIES] ? {[QUERY_PROPERTIES]:options[QUERY_PROPERTIES], [QUERY_RESOLVE_FRAME]:resolveOptions?.[QUERY_RESOLVE_FRAME]} : {}) });
4110
+ }
4111
+
3597
4112
  function evaluateQueryFromClause(from, namespace, options) {
3598
4113
  if (from.source !== 'expression') {
3599
- return resolveAddress(from.address, namespace, options.resolve);
4114
+ return resolveQueryAddress(from.address, namespace, options);
3600
4115
  }
3601
4116
 
3602
4117
  const rootResult = resolveRoot({ kind: 'absolute' }, namespace, options.resolve ?? {});
@@ -3616,7 +4131,7 @@ function evaluateQueryFromClause(from, namespace, options) {
3616
4131
  ],
3617
4132
  };
3618
4133
  }
3619
- return { ok: true, bindings: evaluated.value.bindings, diagnostics: [] };
4134
+ return transferQueryFrames(evaluated.value, { ok: true, bindings: evaluated.value.bindings, diagnostics: [] }, options);
3620
4135
  }
3621
4136
 
3622
4137
  function evaluateQueryExpressionValue(expression, currentBinding, namespace, options) {
@@ -3630,13 +4145,9 @@ function evaluateQueryExpressionValue(expression, currentBinding, namespace, opt
3630
4145
  ).value,
3631
4146
  };
3632
4147
  case 'currentBindingExpression':
3633
- return {
3634
- ok: true,
3635
- value: {
3636
- type: 'bindingSet',
3637
- bindings: [currentBinding],
3638
- },
3639
- };
4148
+ { const value = {type:'bindingSet',bindings:[currentBinding]};
4149
+ if (options[QUERY_PROPERTIES]) options[QUERY_PROPERTIES].frames.set(value,[options[QUERY_CURRENT_FRAME] ?? propertyContext(currentBinding,currentBinding)]);
4150
+ return {ok:true,value}; }
3640
4151
  case 'resolutionExpression':
3641
4152
  return evaluateResolutionExpression(expression, currentBinding, namespace, options);
3642
4153
  case 'groupExpression':
@@ -3665,17 +4176,11 @@ function evaluateResolutionExpression(expression, currentBinding, namespace, opt
3665
4176
  const resolveOptions = {
3666
4177
  ...(options.resolve ?? {}),
3667
4178
  ...(['current', 'contextual'].includes(expression.scope) ? { contextualRoot: currentBinding } : {}),
3668
- ...(expression.scope === 'current' ? { allowParentFromEffectiveRoot: true } : {}),
4179
+ ...(expression.scope === 'current' ? { allowParentFromEffectiveRoot: true, [QUERY_RESOLVE_FRAME]: propertyContext(options[QUERY_CURRENT_FRAME]?.scopeRoot ?? currentBinding, currentBinding) } : {}),
3669
4180
  };
3670
- const resolved = resolveAddress(expression.address, namespace, resolveOptions);
4181
+ const resolved = resolveQueryAddress(expression.address, namespace, options, resolveOptions);
3671
4182
  if (!resolved.ok) return { ok: false, error: resolved.errors[0] };
3672
- return {
3673
- ok: true,
3674
- value: {
3675
- type: 'bindingSet',
3676
- bindings: resolved.bindings,
3677
- },
3678
- };
4183
+ return {ok:true,value:transferQueryFrames(resolved,{type:'bindingSet',bindings:resolved.bindings},options)};
3679
4184
  }
3680
4185
 
3681
4186
  function evaluateUnaryExpression(expression, currentBinding, namespace, options) {
@@ -4023,23 +4528,52 @@ function evaluatePathExpression(expression, currentBinding, namespace, options)
4023
4528
  };
4024
4529
  }
4025
4530
 
4026
- const activated = activateAddressLiteral(scalar.value, options.parse?.address);
4531
+ let activated = activateAddressLiteral(scalar.value, options.parse?.address);
4027
4532
  if (!activated.ok) return activated;
4533
+ if (!Array.isArray(activated.address?.selectors) || !['absolute', 'contextual'].includes(activated.address.root?.kind)) {
4534
+ return {ok: false, error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_PATH_LITERAL', 'Invalid activated address AST')};
4535
+ }
4536
+ if (activated.address.selectors.some(s => s?.type === 'propertyFilter')) return deniedAddressActivation('Property activation is not admitted');
4537
+ const hasIdentity = activated.address.selectors.some(s => s?.type === 'childIdentity');
4538
+ if (hasIdentity) {
4539
+ const address = normalizeActivationAst(activated.address, options.parse?.address, false);
4540
+ if (!address) return deniedAddressActivation('Cannot establish a bounded unqualified identity activation address');
4541
+ activated = {ok: true, address};
4542
+ }
4028
4543
 
4029
4544
  const activation = authorizeAddressActivation(
4030
4545
  activated.address,
4031
4546
  currentBinding,
4032
4547
  options.addressActivation,
4033
4548
  options.parse?.address,
4549
+ namespace,
4034
4550
  );
4035
4551
  if (!activation.ok) return activation;
4036
4552
 
4037
- const resolved = resolveAddress(activated.address, namespace, {
4553
+ const identityRoots = activation.identityRoots;
4554
+ const guard = identityRoots === undefined ? undefined : binding => {
4555
+ const address = canonicalActivationPath(getBindingAddress(binding), options.parse?.address);
4556
+ return address && identityRoots.some(root => addressHasStructuralPrefix(address, root))
4557
+ ? undefined
4558
+ : deniedAddressActivation('Identity activation binding has no permitted canonical structural path').error;
4559
+ };
4560
+ const hostLimit = options.resolve?.maxBindings;
4561
+ const activationLimit = activation.maxBindings;
4562
+ if (hasIdentity && hostLimit !== undefined && (!Number.isSafeInteger(hostLimit) || hostLimit < 0)) {
4563
+ return {ok: false, error: resolveError('SANSA_RESOLVE_INVALID_BINDING_LIMIT', 'Resolve maxBindings must be a non-negative safe integer')};
4564
+ }
4565
+ const maxBindings = hasIdentity && hostLimit !== undefined && activationLimit !== undefined
4566
+ ? Math.min(hostLimit, activationLimit) : (activationLimit ?? hostLimit);
4567
+ const resolveOptions = {
4038
4568
  ...(options.resolve ?? {}),
4039
4569
  contextualRoot: currentBinding,
4040
- ...(activation.allowParentFromEffectiveRoot ? { allowParentFromEffectiveRoot: true } : {}),
4041
- ...(activation.maxBindings === undefined ? {} : { maxBindings: activation.maxBindings }),
4042
- });
4570
+ ...(activation.allowParentFromEffectiveRoot ? {allowParentFromEffectiveRoot: true} : {}),
4571
+ ...(maxBindings === undefined ? {} : {maxBindings}),
4572
+ ...(guard ? {[IDENTITY_ACTIVATION_GUARD]: guard} : {}),
4573
+ };
4574
+ const resolved = guard
4575
+ ? resolveQueryAddress(activated.address, namespace, options, resolveOptions)
4576
+ : resolveConsumerAddress(activated.address, namespace, {...resolveOptions,[QUERY_PROPERTIES]:options[QUERY_PROPERTIES]});
4043
4577
  if (!resolved.ok) {
4044
4578
  const error = resolved.errors[0];
4045
4579
  if (error.code === 'SANSA_RESOLVE_BINDING_LIMIT_EXCEEDED') {
@@ -4054,6 +4588,12 @@ function evaluatePathExpression(expression, currentBinding, namespace, options)
4054
4588
  }
4055
4589
  return { ok: false, error };
4056
4590
  }
4591
+ if (guard) {
4592
+ for (const binding of resolved.bindings) {
4593
+ const error = guard(binding);
4594
+ if (error) return {ok: false, error};
4595
+ }
4596
+ }
4057
4597
  if (activation.maxBindings !== undefined && resolved.bindings.length > activation.maxBindings) {
4058
4598
  return {
4059
4599
  ok: false,
@@ -4067,16 +4607,11 @@ function evaluatePathExpression(expression, currentBinding, namespace, options)
4067
4607
  ),
4068
4608
  };
4069
4609
  }
4070
- return {
4071
- ok: true,
4072
- value: {
4073
- type: 'bindingSet',
4074
- bindings: resolved.bindings,
4075
- },
4076
- };
4610
+ return {ok:true,value:transferQueryFrames(resolved,{type:'bindingSet',bindings:resolved.bindings},options)};
4077
4611
  }
4078
4612
 
4079
4613
  const ADDRESS_ACTIVATION_SELECTOR_FEATURE = new Map([
4614
+ ['childIdentity', 'childIdentity'],
4080
4615
  ['member', 'member'],
4081
4616
  ['position', 'position'],
4082
4617
  ['positionRange', 'range'],
@@ -4090,7 +4625,7 @@ const ADDRESS_ACTIVATION_SELECTOR_FEATURE = new Map([
4090
4625
  ['parent', 'parent'],
4091
4626
  ]);
4092
4627
 
4093
- function authorizeAddressActivation(address, currentBinding, policy, parseOptions) {
4628
+ function authorizeAddressActivation(address, currentBinding, policy, parseOptions, namespace) {
4094
4629
  if (policy === 'trusted' || policy?.mode === 'trusted') {
4095
4630
  return { ok: true };
4096
4631
  }
@@ -4139,6 +4674,24 @@ function authorizeAddressActivation(address, currentBinding, policy, parseOption
4139
4674
  return deniedAddressActivation('Contextual-root address activation is not permitted');
4140
4675
  }
4141
4676
 
4677
+ if (address.selectors.some(s => s.type === 'childIdentity')) {
4678
+ if (address.selectors.some(s => s.type === 'parent') || address.qualifierExpression) {
4679
+ return deniedAddressActivation('Identity activation does not admit parent traversal or qualifiers');
4680
+ }
4681
+ const roots = normalizeAddressActivationRoots(policy.allowedRoots, parseOptions);
4682
+ if (!roots.ok) return roots;
4683
+ const binding = address.root.kind === 'contextual' ? currentBinding
4684
+ : (typeof namespace.root === 'function' ? namespace.root() : namespace.root);
4685
+ const base = canonicalActivationPath(getBindingAddress(binding), parseOptions);
4686
+ if (!base) return deniedAddressActivation('Identity activation requires a canonical structural scope root');
4687
+ const firstIdentity = address.selectors.findIndex(s => s.type === 'childIdentity');
4688
+ const prefix = {...base, selectors: [...base.selectors, ...address.selectors.slice(0, firstIdentity)]};
4689
+ if (!roots.roots.some(root => addressHasStructuralPrefix(prefix, root))) {
4690
+ return deniedAddressActivation('Identity scan parent is outside every permitted root');
4691
+ }
4692
+ return {ok: true, maxBindings: maxBindings.value, identityRoots: roots.roots};
4693
+ }
4694
+
4142
4695
  const effective = effectiveActivatedAddress(address, currentBinding, parseOptions);
4143
4696
  if (!effective.ok) return effective;
4144
4697
  const normalized = normalizeActivatedAddressForScope(effective.address);
@@ -4187,7 +4740,8 @@ function normalizeAddressActivationRoots(input, parseOptions) {
4187
4740
  }
4188
4741
  const roots = [];
4189
4742
  for (const root of input) {
4190
- const parsed = typeof root === 'string' ? parseAddress(root, parseOptions) : { ok: true, address: root };
4743
+ const address = typeof root === 'string' ? canonicalActivationPath(root, parseOptions) : normalizeActivationAst(root, parseOptions, true);
4744
+ const parsed = {ok: address !== undefined, address};
4191
4745
  if (!parsed.ok || !parsed.address || parsed.address.type !== 'SansaAddress') {
4192
4746
  return invalidAddressActivationPolicy('Address-activation roots must be valid SANSA addresses');
4193
4747
  }
@@ -4199,6 +4753,41 @@ function normalizeAddressActivationRoots(input, parseOptions) {
4199
4753
  return { ok: true, roots };
4200
4754
  }
4201
4755
 
4756
+ // Bounded scalar-only AST projection before policy decisions. Caller flags carry no authority.
4757
+ function normalizeActivationAst(input, parseOptions, exactOnly) {
4758
+ if (input?.type !== 'SansaAddress' || input.root?.type !== 'root'
4759
+ || !['absolute', 'contextual'].includes(input.root.kind) || input.qualifierExpression
4760
+ || !Array.isArray(input.selectors) || input.selectors.length > 1024) return undefined;
4761
+ let characters = 0;
4762
+ for (const s of input.selectors) {
4763
+ if (!s || exactOnly && !isExactSelector(s)) return undefined;
4764
+ const text = ['member', 'localSpace', 'semanticTypeFilter', 'representationKindFilter'].includes(s.type) ? s.name
4765
+ : s.type === 'childIdentity' ? s.identity : s.type === 'namePattern' ? s.pattern : undefined;
4766
+ if (text !== undefined) {
4767
+ if (typeof text !== 'string') return undefined;
4768
+ characters += text.length;
4769
+ } else if (['member', 'localSpace', 'semanticTypeFilter', 'representationKindFilter', 'childIdentity', 'namePattern'].includes(s.type)) return undefined;
4770
+ if (characters > 65536) return undefined;
4771
+ if (s.type === 'position' && (!Number.isSafeInteger(s.index) || s.index < 0)) return undefined;
4772
+ if (s.type === 'positionRange' && ![s.start, s.end].every(v => v == null || Number.isSafeInteger(v) && v >= 0)) return undefined;
4773
+ }
4774
+ try {
4775
+ const source = renderAddress(input);
4776
+ if (source.length > 65536) return undefined;
4777
+ const parsed = parseAddress(source, parseOptions);
4778
+ return parsed.ok && (!exactOnly || parsed.address.root.kind === 'absolute' && parsed.address.isExact)
4779
+ ? parsed.address : undefined;
4780
+ } catch { return undefined; }
4781
+ }
4782
+
4783
+ function canonicalActivationPath(source, parseOptions) {
4784
+ if (typeof source !== 'string' || source.length > 65536) return undefined;
4785
+ const parsed = parseAddress(source, parseOptions);
4786
+ return parsed.ok && parsed.address.root.kind === 'absolute' && parsed.address.isExact
4787
+ && !parsed.address.qualifierExpression && parsed.address.selectors.length <= 1024
4788
+ ? parsed.address : undefined;
4789
+ }
4790
+
4202
4791
  function effectiveActivatedAddress(address, currentBinding, parseOptions) {
4203
4792
  if (address.root.kind === 'absolute') return { ok: true, address };
4204
4793
  const currentAddress = getBindingAddress(currentBinding);
@@ -4434,13 +5023,10 @@ function evaluateResolveChildExpression(expression, currentBinding, namespace, o
4434
5023
  };
4435
5024
  }
4436
5025
 
4437
- return {
4438
- ok: true,
4439
- value: {
4440
- type: 'bindingSet',
4441
- bindings,
4442
- },
4443
- };
5026
+ const value = {type:'bindingSet',bindings};
5027
+ const state = options[QUERY_PROPERTIES];
5028
+ if (state) state.frames.set(value,bindings.map(() => state.frames.get(base.value)[0]));
5029
+ return {ok:true,value};
4444
5030
  }
4445
5031
 
4446
5032
  function evaluateFollowExpression(expression, currentBinding, namespace, options) {
@@ -4471,7 +5057,7 @@ function evaluateFollowExpression(expression, currentBinding, namespace, options
4471
5057
  };
4472
5058
  }
4473
5059
 
4474
- const resolved = resolveAddress(target.address, namespace, options.resolve);
5060
+ const resolved = resolveConsumerAddress(target.address, namespace, {...options.resolve,[QUERY_PROPERTIES]:options[QUERY_PROPERTIES]});
4475
5061
  if (!resolved.ok) return { ok: false, error: resolved.errors[0] };
4476
5062
  if (resolved.bindings.length === 0) {
4477
5063
  return {
@@ -4480,13 +5066,7 @@ function evaluateFollowExpression(expression, currentBinding, namespace, options
4480
5066
  };
4481
5067
  }
4482
5068
 
4483
- return {
4484
- ok: true,
4485
- value: {
4486
- type: 'bindingSet',
4487
- bindings: resolved.bindings,
4488
- },
4489
- };
5069
+ return {ok:true,value:transferQueryFrames(resolved,{type:'bindingSet',bindings:resolved.bindings},options)};
4490
5070
  }
4491
5071
 
4492
5072
  function isReferenceFormValue(value, metadata) {
@@ -5083,13 +5663,13 @@ function evaluateCardinalityFunctionBooleans(expression, currentBinding, namespa
5083
5663
  return { ok: true, values };
5084
5664
  }
5085
5665
 
5086
- function orderQueryBindings(orderBy, bindings, namespace, options) {
5666
+ function orderQueryBindings(orderBy, bindings, namespace, options, frames) {
5087
5667
  const keyed = [];
5088
5668
  for (let index = 0; index < bindings.length; index += 1) {
5089
5669
  const binding = bindings[index];
5090
5670
  const keys = [];
5091
5671
  for (const key of orderBy.keys) {
5092
- const evaluated = evaluateQueryExpressionValue(key.ast, binding, namespace, options);
5672
+ const evaluated = evaluateQueryExpressionValue(key.ast, binding, namespace, queryRowOptions(options, frames?.[index]));
5093
5673
  if (!evaluated.ok) {
5094
5674
  return {
5095
5675
  ok: false,
@@ -5183,6 +5763,7 @@ function orderQueryBindings(orderBy, bindings, namespace, options) {
5183
5763
  return {
5184
5764
  ok: true,
5185
5765
  bindings: keyed.map((entry) => entry.binding),
5766
+ ...(frames ? {frames:keyed.map(entry => frames[entry.index])} : {}),
5186
5767
  };
5187
5768
  }
5188
5769
 
@@ -6107,9 +6688,9 @@ function normalizeRadixBase(value) {
6107
6688
 
6108
6689
  function radixBaseFromSemanticType(semanticType) {
6109
6690
  if (typeof semanticType !== 'string') return undefined;
6110
- const normalized = semanticType.trim().toLowerCase();
6691
+ const normalized = semanticType.trim();
6111
6692
  if (normalized === 'decimal') return 10;
6112
- const alias = /^radix(2|6|8|12)$/u.exec(normalized);
6693
+ const alias = /^radix(2|6|8|12|16)$/u.exec(normalized);
6113
6694
  if (alias !== null) return Number(alias[1]);
6114
6695
  const clarified = /^radix\[(\d+)\]$/u.exec(normalized);
6115
6696
  if (clarified === null) return undefined;
@@ -6593,6 +7174,8 @@ function scalarMetadataFromInfo(info) {
6593
7174
 
6594
7175
  function applyResolveSelector(selector, bindings, namespace, selectorIndex, policy = {}) {
6595
7176
  switch (selector.type) {
7177
+ case 'childIdentity':
7178
+ return selectChildIdentity(namespace, bindings, selector, selectorIndex, policy);
6596
7179
  case 'member':
6597
7180
  return { ok: true, bindings: collectSelectedBindings(bindings, (binding) => iterateMembers(namespace, binding, selector.name), policy.maxBindings) };
6598
7181
  case 'position':
@@ -6602,7 +7185,7 @@ function applyResolveSelector(selector, bindings, namespace, selectorIndex, poli
6602
7185
  case 'parent':
6603
7186
  return selectParents(namespace, bindings, selectorIndex, policy);
6604
7187
  case 'directExpansion':
6605
- return { ok: true, bindings: collectSelectedBindings(bindings, (binding) => getChildren(namespace, binding), policy.maxBindings) };
7188
+ return { ok: true, bindings: collectSelectedBindings(bindings, (binding) => iterateChildren(namespace, binding), policy.maxBindings) };
6606
7189
  case 'descendantExpansion':
6607
7190
  return { ok: true, bindings: collectSelectedBindings(bindings, (binding) => iterateDescendants(namespace, binding), policy.maxBindings) };
6608
7191
  case 'namePattern': {
@@ -6636,6 +7219,39 @@ function applyResolveSelector(selector, bindings, namespace, selectorIndex, poli
6636
7219
  }
6637
7220
  }
6638
7221
 
7222
+ function selectChildIdentity(namespace, bindings, selector, selectorIndex, policy) {
7223
+ const output = [];
7224
+ for (const binding of bindings) {
7225
+ let match;
7226
+ const guard = policy.identityActivationGuard;
7227
+ if (guard) {
7228
+ const error = guard(binding);
7229
+ if (error) return {ok: false, error};
7230
+ }
7231
+ const children = typeof namespace.children === 'function' ? namespace.children(binding) ?? [] : binding.children ?? [];
7232
+ for (const child of children) {
7233
+ const budget = policy.identityBudget;
7234
+ if (budget.inspected >= policy.maxIdentityInspections) return { ok: false, error: resolveError('SANSA_RESOLVE_IDENTITY_LIMIT_EXCEEDED', 'Identity inspection limit exceeded', selectorIndex, { limit: policy.maxIdentityInspections, observed: budget.inspected + 1 }) };
7235
+ if (guard) {
7236
+ const error = guard(child);
7237
+ if (error) return {ok: false, error};
7238
+ }
7239
+ budget.inspected += 1;
7240
+ const identity = namespace.identity(child);
7241
+ if (identity !== undefined && (typeof identity !== 'string' || !CHILD_IDENTITY_RE.test(identity))) return { ok: false, error: resolveError('SANSA_RESOLVE_INVALID_IDENTITY', 'Adapter returned an invalid structural identity', selectorIndex) };
7242
+ if (identity === selector.identity) {
7243
+ if (match !== undefined) return { ok: false, error: resolveError('SANSA_RESOLVE_AMBIGUOUS_IDENTITY', 'Multiple children have the selected identity', selectorIndex, { identity }) };
7244
+ match = child;
7245
+ }
7246
+ }
7247
+ if (match !== undefined) {
7248
+ if (policy.maxBindings !== undefined && output.length >= policy.maxBindings) return { ok: false, error: resolveBindingLimitError(policy.maxBindings, output.length + 1, selectorIndex) };
7249
+ output.push(match);
7250
+ }
7251
+ }
7252
+ return { ok: true, bindings: output };
7253
+ }
7254
+
6639
7255
  function selectMember(namespace, binding, name) {
6640
7256
  if (typeof namespace.member === 'function') {
6641
7257
  const selected = namespace.member(binding, name);
@@ -6680,7 +7296,7 @@ function* iteratePositionRange(namespace, binding, start, end) {
6680
7296
  }
6681
7297
  }
6682
7298
 
6683
- function selectParents(namespace, bindings, selectorIndex, policy) {
7299
+ function selectParents(namespace, bindings, selectorIndex, policy, project) {
6684
7300
  if (policy.parentTraversal === 'forbid') {
6685
7301
  return {
6686
7302
  ok: false,
@@ -6707,10 +7323,16 @@ function selectParents(namespace, bindings, selectorIndex, policy) {
6707
7323
  const traversable = bindings.filter((binding) => binding !== policy.effectiveRoot);
6708
7324
  if (traversable.length === 0) return { ok: true, bindings: [] };
6709
7325
  if (typeof namespace.parent === 'function') {
6710
- return { ok: true, bindings: traversable.map((binding) => namespace.parent(binding)).filter(Boolean) };
7326
+ return { ok: true, bindings: traversable.map((binding, index) => {
7327
+ const parent = namespace.parent(binding);
7328
+ return parent && project ? project(parent, index) : parent;
7329
+ }).filter(Boolean) };
6711
7330
  }
6712
7331
  if (traversable.some((binding) => Object.prototype.hasOwnProperty.call(binding, 'parent'))) {
6713
- return { ok: true, bindings: traversable.map((binding) => binding.parent).filter(Boolean) };
7332
+ return { ok: true, bindings: traversable.map((binding, index) => {
7333
+ const parent = binding.parent;
7334
+ return parent && project ? project(parent, index) : parent;
7335
+ }).filter(Boolean) };
6714
7336
  }
6715
7337
  if (traversable.length === 0) return { ok: true, bindings: [] };
6716
7338
  return {
@@ -6723,10 +7345,13 @@ function selectParents(namespace, bindings, selectorIndex, policy) {
6723
7345
  };
6724
7346
  }
6725
7347
 
6726
- function selectAttributeSpaces(namespace, bindings, selectorIndex) {
7348
+ function selectAttributeSpaces(namespace, bindings, selectorIndex, project) {
6727
7349
  if (typeof namespace.attributeSpace !== 'function') {
6728
7350
  const selected = bindings
6729
- .map((binding) => binding.attributeSpace ?? binding.attributes)
7351
+ .map((binding, index) => {
7352
+ const attributes = binding.attributeSpace ?? binding.attributes;
7353
+ return attributes && project ? project(attributes, index) : attributes;
7354
+ })
6730
7355
  .filter(Boolean);
6731
7356
  if (selected.length > 0 || bindings.length === 0) return { ok: true, bindings: selected };
6732
7357
  return {
@@ -6740,7 +7365,10 @@ function selectAttributeSpaces(namespace, bindings, selectorIndex) {
6740
7365
  }
6741
7366
  return {
6742
7367
  ok: true,
6743
- bindings: bindings.map((binding) => namespace.attributeSpace(binding)).filter(Boolean),
7368
+ bindings: bindings.map((binding, index) => {
7369
+ const attributes = namespace.attributeSpace(binding);
7370
+ return attributes && project ? project(attributes, index) : attributes;
7371
+ }).filter(Boolean),
6744
7372
  };
6745
7373
  }
6746
7374
 
@@ -6771,13 +7399,37 @@ function getDescendants(namespace, binding) {
6771
7399
  return Array.from(iterateDescendants(namespace, binding));
6772
7400
  }
6773
7401
 
7402
+ function* iterateChildren(namespace, binding) {
7403
+ if (typeof namespace.children === 'function') {
7404
+ yield* namespace.children(binding) ?? [];
7405
+ } else if (Array.isArray(binding.children)) {
7406
+ yield* binding.children;
7407
+ }
7408
+ }
7409
+
6774
7410
  function* iterateDescendants(namespace, binding) {
6775
- const stack = [...getChildren(namespace, binding)].reverse();
6776
- while (stack.length > 0) {
6777
- const child = stack.pop();
6778
- yield child;
6779
- const children = getChildren(namespace, child);
6780
- for (let index = children.length - 1; index >= 0; index -= 1) stack.push(children[index]);
7411
+ const stack = [iterateChildren(namespace, binding)];
7412
+ try {
7413
+ while (stack.length > 0) {
7414
+ const next = stack[stack.length - 1].next();
7415
+ if (next.done) {
7416
+ stack.pop();
7417
+ } else {
7418
+ yield next.value;
7419
+ stack.push(iterateChildren(namespace, next.value));
7420
+ }
7421
+ }
7422
+ } finally {
7423
+ let failed = false;
7424
+ let failure;
7425
+ while (stack.length > 0) {
7426
+ try {
7427
+ stack.pop().return();
7428
+ } catch (error) {
7429
+ if (!failed) { failed = true; failure = error; }
7430
+ }
7431
+ }
7432
+ if (failed) throw failure;
6781
7433
  }
6782
7434
  }
6783
7435
 
@@ -6879,10 +7531,27 @@ export function renderQualifierTerm(term) {
6879
7531
 
6880
7532
  function renderQualifierArgument(argument) {
6881
7533
  if (argument.kind === 'token') return argument.value;
6882
- if (argument.kind === 'number') return String(argument.value);
7534
+ if (argument.kind === 'number') return renderQualifierNumber(argument.value);
6883
7535
  return quotePayload(argument.value);
6884
7536
  }
6885
7537
 
7538
+ // Number's shortest spelling can use an exponent, which qualifier syntax does
7539
+ // not admit. Expand that spelling without changing the represented value.
7540
+ function renderQualifierNumber(value) {
7541
+ const text = String(value);
7542
+ if (typeof value !== 'number' || !Number.isFinite(value)) return text;
7543
+ if (!text.includes('e')) return text;
7544
+ const [mantissa, exponent] = text.split('e');
7545
+ const sign = mantissa.startsWith('-') ? '-' : '';
7546
+ const unsigned = sign ? mantissa.slice(1) : mantissa;
7547
+ const [integer, fraction = ''] = unsigned.split('.');
7548
+ const digits = integer + fraction;
7549
+ const point = integer.length + Number(exponent);
7550
+ if (point <= 0) return sign + '0.' + '0'.repeat(-point) + digits;
7551
+ if (point >= digits.length) return sign + digits + '0'.repeat(point - digits.length);
7552
+ return sign + digits.slice(0, point) + '.' + digits.slice(point);
7553
+ }
7554
+
6886
7555
  class AddressParser {
6887
7556
  constructor(input, options = {}) {
6888
7557
  this.input = input;
@@ -6890,6 +7559,8 @@ class AddressParser {
6890
7559
  this.index = 0;
6891
7560
  this.warnings = [];
6892
7561
  this.maxPositionIndex = normalizeMaxPositionIndex(options.maxPositionIndex);
7562
+ this.propertySyntax = hasPropertySyntax(input);
7563
+ this.propertyWork = 0;
6893
7564
  }
6894
7565
 
6895
7566
  parse() {
@@ -6906,10 +7577,12 @@ class AddressParser {
6906
7577
 
6907
7578
  while (!this.atEnd()) {
6908
7579
  const char = this.peek();
7580
+ if (this.propertySyntax && char !== ':' && selectors.length >= 256) propertyLimit('selectors', 256);
7581
+ if (char === '&') { selectors.push(this.parsePropertySelector()); continue; }
6909
7582
  if (char === ':') {
6910
7583
  this.index += 1;
6911
7584
  if (this.atEnd()) this.fail('Expected qualifier expression', 'SANSA_EXPECTED_QUALIFIER');
6912
- qualifierExpression = this.parseQualifierExpression();
7585
+ qualifierExpression = this.propertySyntax ? parsePropertyQualifiers(this) : this.parseQualifierExpression();
6913
7586
  break;
6914
7587
  }
6915
7588
  if (char === '.') {
@@ -6942,54 +7615,53 @@ class AddressParser {
6942
7615
  qualifierExpression,
6943
7616
  isExact: selectors.every(isExactSelector),
6944
7617
  };
6945
- address.canonical = renderAddress(address);
7618
+ address.canonical = this.propertySyntax ? renderPropertyAddress(address, quotePayload, renderQualifierNumber) : renderLegacyAddress(address);
6946
7619
  return address;
6947
7620
  }
6948
7621
 
6949
- parseDotSelector() {
6950
- this.consume('.');
6951
- if (this.match('@')) return { type: 'attributeSpace' };
6952
- if (this.match('^')) return { type: 'parent' };
6953
- if (this.match('*')) {
6954
- if (this.match('*')) return { type: 'descendantExpansion' };
6955
- return { type: 'directExpansion' };
6956
- }
6957
- if (this.match('[')) {
6958
- const name = this.parseQuotedPayload();
6959
- if (name.length === 0) this.fail('Quoted member names must not be empty', 'SANSA_EMPTY_MEMBER_NAME');
6960
- this.consume(']');
6961
- return { type: 'member', name, quoted: true };
6962
- }
6963
- if (this.match('<')) {
6964
- const name = this.parseQuotedPayload();
6965
- if (name.length === 0) this.fail('Local address-space names must not be empty', 'SANSA_EMPTY_LOCAL_SPACE_NAME');
6966
- this.consume('>');
6967
- return { type: 'localSpace', name };
6968
- }
6969
- if (this.match('(')) {
6970
- const pattern = this.parseQuotedPayload();
6971
- this.consume(')');
6972
- return { type: 'namePattern', pattern };
7622
+ parsePropertySelector() {
7623
+ this.consume('&');
7624
+ const start = this.index;
7625
+ while (isIdentifierContinue(this.peek())) {
7626
+ this.index += 1;
7627
+ if (this.index - start > 7) this.fail('Unknown property selector', 'SANSA_UNKNOWN_PROPERTY_SELECTOR', start);
6973
7628
  }
6974
- return { type: 'member', name: this.parseIdentifier('member selector'), quoted: false };
7629
+ const property = this.input.slice(start, this.index);
7630
+ if (!['key', 'tag', 'headTag'].includes(property)) this.fail('Unknown property selector', 'SANSA_UNKNOWN_PROPERTY_SELECTOR', start);
7631
+ this.consume('(');
7632
+ if (isLayout(this.peek())) this.fail('Whitespace is not allowed inside a SANSA address', 'SANSA_UNEXPECTED_WHITESPACE');
7633
+ if (this.peek() !== '"') this.fail('Expected quoted property argument', 'SANSA_EXPECTED_PROPERTY_ARGUMENT');
7634
+ const value = this.parseQuotedPayload(4096);
7635
+ this.consume(')');
7636
+ return {type:'propertyFilter', property, value};
6975
7637
  }
6976
7638
 
6977
- parsePositionSelector() {
6978
- this.consume('[');
6979
- const selectorStart = this.index;
6980
- const start = this.parseOptionalPositionIndex();
6981
- if (this.input.startsWith('..', this.index)) {
6982
- this.index += 2;
6983
- const end = this.parseOptionalPositionIndex();
6984
- if (start === null && end === null) {
6985
- this.fail('Position ranges must include a start or end index', 'SANSA_EMPTY_POSITION_RANGE', selectorStart);
6986
- }
6987
- this.consume(']');
6988
- return { type: 'positionRange', start, end };
7639
+ chargePropertyWork(count) {
7640
+ if (!this.propertySyntax) return;
7641
+ this.propertyWork += count;
7642
+ if (this.propertyWork > 65536) propertyLimit('canonicalScalars', 65536);
7643
+ }
7644
+
7645
+ peekSyntax() { return this.peek(); }
7646
+ parseDotSelector() { return parseDotSelectorFromCursor(this); }
7647
+ parseChildIdentity() {
7648
+ this.index += 1;
7649
+ const start = this.index;
7650
+ while (!this.atEnd() && this.peek() !== '\\') {
7651
+ if (!/^[A-Za-z0-9_-]$/.test(this.peek())) this.fail('Expected structural identity name', 'SANSA_EXPECTED_IDENTITY');
7652
+ this.index += 1;
6989
7653
  }
6990
- if (start === null) this.fail('Expected positional index', 'SANSA_EXPECTED_INDEX');
6991
- this.consume(']');
6992
- return { type: 'position', index: start };
7654
+ if (this.atEnd()) this.fail('Unterminated structural identity selector', 'SANSA_UNTERMINATED_IDENTITY');
7655
+ if (this.index === start) this.fail('Expected structural identity name', 'SANSA_EXPECTED_IDENTITY');
7656
+ this.chargePropertyWork(this.index - start);
7657
+ const identity = this.input.slice(start, this.index++);
7658
+ return { type: 'childIdentity', identity };
7659
+ }
7660
+ parsePositionSelector() { return parsePositionSelectorFromCursor(this); }
7661
+ matchRangeSeparator() {
7662
+ if (!this.input.startsWith('..', this.index)) return false;
7663
+ this.index += 2;
7664
+ return true;
6993
7665
  }
6994
7666
 
6995
7667
  parseOptionalPositionIndex() {
@@ -6997,24 +7669,8 @@ class AddressParser {
6997
7669
  while (isDigit(this.peek())) this.index += 1;
6998
7670
  if (this.index === start) return null;
6999
7671
  const raw = this.input.slice(start, this.index);
7000
- if (raw.length > 1 && raw.startsWith('0')) {
7001
- this.fail('Positional indexes must not contain leading zeroes', 'SANSA_LEADING_ZERO_INDEX', start);
7002
- }
7003
- if (exceedsUnsignedDecimal(raw, this.maxPositionIndex)) {
7004
- this.fail(
7005
- `Position indexes must be less than or equal to ${this.maxPositionIndex}`,
7006
- 'SANSA_POSITION_INDEX_LIMIT_EXCEEDED',
7007
- start,
7008
- );
7009
- }
7010
- const value = Number(raw);
7011
- if (!Number.isSafeInteger(value)) {
7012
- this.fail(
7013
- `Position indexes must be less than or equal to ${this.maxPositionIndex}`,
7014
- 'SANSA_POSITION_INDEX_LIMIT_EXCEEDED',
7015
- start,
7016
- );
7017
- }
7672
+ const value = validatePositionIndex(raw, this.maxPositionIndex,
7673
+ (message, code) => this.fail(message, code, start));
7018
7674
  if (value > SANSA_MAX_POSITION_INDEX) {
7019
7675
  this.warn(
7020
7676
  `Position index ${value} exceeds the SANSA v1 portable index ceiling ${SANSA_MAX_POSITION_INDEX}`,
@@ -7087,9 +7743,11 @@ class AddressParser {
7087
7743
  this.index += 1;
7088
7744
  }
7089
7745
  if (this.index === start) this.fail('Expected qualifier argument', 'SANSA_EXPECTED_QUALIFIER_ARGUMENT');
7746
+ this.chargePropertyWork(this.index - start);
7090
7747
  const value = this.input.slice(start, this.index);
7091
7748
  if (!QUALIFIER_NUMBER_RE.test(value)) this.fail('Invalid qualifier argument', 'SANSA_INVALID_QUALIFIER_ARGUMENT');
7092
- return { kind: 'number', value: Number(value) };
7749
+ const number = Number(value);
7750
+ return Number.isFinite(number) ? { kind: 'number', value: number } : { kind: 'token', value };
7093
7751
  }
7094
7752
 
7095
7753
  parseIdentifier(context) {
@@ -7098,12 +7756,15 @@ class AddressParser {
7098
7756
  if (!isIdentifierStart(first)) this.fail(`Expected ${context}`, 'SANSA_EXPECTED_IDENTIFIER');
7099
7757
  this.index += 1;
7100
7758
  while (isIdentifierContinue(this.peek())) this.index += 1;
7759
+ this.chargePropertyWork(this.index - start);
7101
7760
  return this.input.slice(start, this.index);
7102
7761
  }
7103
7762
 
7104
- parseQuotedPayload() {
7763
+ parseQuotedPayload(limit = 65536) {
7105
7764
  this.consume('"');
7106
7765
  let output = '';
7766
+ let scalars = 0;
7767
+ this.chargePropertyWork(1);
7107
7768
  while (!this.atEnd()) {
7108
7769
  const char = this.peek();
7109
7770
  if (char === '"') {
@@ -7113,12 +7774,21 @@ class AddressParser {
7113
7774
  if (char === '\n' || char === '\r') {
7114
7775
  this.fail('Quoted payloads must not contain raw newlines', 'SANSA_RAW_NEWLINE_IN_QUOTED_PAYLOAD');
7115
7776
  }
7116
- if (char === '\\') {
7117
- output += this.parseEscape();
7118
- continue;
7777
+ if (!this.propertySyntax) {
7778
+ if (char === '\\') { output += this.parseEscape(); continue; }
7779
+ output += char; this.index += 1; continue;
7119
7780
  }
7120
- output += char;
7121
- this.index += 1;
7781
+ let decoded;
7782
+ if (char === '\\') decoded = this.parseEscape();
7783
+ else {
7784
+ decoded = String.fromCodePoint(this.input.codePointAt(this.index));
7785
+ const point = decoded.codePointAt(0);
7786
+ if (point >= 0xd800 && point <= 0xdfff) this.fail('Invalid Unicode scalar', 'SANSA_INVALID_UNICODE_SCALAR');
7787
+ this.index += decoded.length;
7788
+ }
7789
+ if (++scalars > limit) propertyLimit(limit === 4096 ? 'payloadScalars' : 'canonicalScalars', limit);
7790
+ this.chargePropertyWork(1);
7791
+ output += decoded;
7122
7792
  }
7123
7793
  this.fail('Unterminated quoted payload', 'SANSA_UNTERMINATED_QUOTED_PAYLOAD');
7124
7794
  }
@@ -7498,9 +8168,6 @@ class InstructionParser {
7498
8168
  this.fail('Unexpected token after quoted create member name', 'SANSA_INSTRUCTION_INVALID_CREATE_DESTINATION', offset + parser.index);
7499
8169
  }
7500
8170
  this.warnings.push(...parser.warnings);
7501
- if (name.length === 0) {
7502
- this.fail('Create member name must not be empty', 'SANSA_INSTRUCTION_INVALID_CREATE_DESTINATION', offset);
7503
- }
7504
8171
  return { type: 'createDestination', kind: 'member', name, canonical: quotePayload(name) };
7505
8172
  }
7506
8173
  const address = this.parseAddress(source, offset);
@@ -7847,7 +8514,7 @@ class QueryParser {
7847
8514
  this.fail("Expected SANSA address after 'from'", 'SANSA_QUERY_EXPECTED_FROM_ADDRESS', clause.bodyStart);
7848
8515
  }
7849
8516
  if (expression.startsWith('$') || expression.startsWith('?')) {
7850
- if (/\s/.test(expression)) {
8517
+ if (/\s/.test(expression) && !hasPropertySyntax(expression)) {
7851
8518
  this.fail("Expected a single SANSA address after 'from'", 'SANSA_QUERY_INVALID_FROM_ADDRESS', clause.bodyStart);
7852
8519
  }
7853
8520
  const result = parseAddress(expression, this.options.address);
@@ -8247,7 +8914,7 @@ class QueryExpressionParser {
8247
8914
  canonical: '.',
8248
8915
  };
8249
8916
  }
8250
- const positionalCurrentShorthand = isQueryCurrentPositionalShorthand(source);
8917
+ const positionalCurrentShorthand = isQueryCurrentPositionalShorthand(source) || source.startsWith('.&');
8251
8918
  const parseSource = positionalCurrentShorthand
8252
8919
  ? `?${source.slice(1)}`
8253
8920
  : source.startsWith('.')
@@ -9518,7 +10185,9 @@ function globPatternToRegExp(pattern) {
9518
10185
  source += escapeRegExp(char);
9519
10186
  }
9520
10187
  }
9521
- return new RegExp(`${source}$`, 'u');
10188
+ // Dot-all retains code-point matching for line terminators; the final
10189
+ // assertion requires the actual end rather than JavaScript's pre-newline $.
10190
+ return new RegExp(`${source}(?!.)`, 'su');
9522
10191
  }
9523
10192
 
9524
10193
  function escapeRegExp(value) {