@altopelago/sansa 0.10.0 → 0.10.1

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.
@@ -2,9 +2,10 @@ import { existsSync } from 'node:fs';
2
2
  import { createRequire } from 'node:module';
3
3
  import { resolve as resolvePath } from 'node:path';
4
4
  import { fileURLToPath, pathToFileURL } from 'node:url';
5
- import { evaluateQuery, parseQuery } from '../../src/index.js';
5
+ import { evaluateQuery, parseAddress, parseQuery } from '../../src/index.js';
6
6
 
7
7
  const devAeonCoreUrl = new URL('../../../aeon/implementations/typescript/packages/core/dist/index.js', import.meta.url);
8
+ const devAeonAesUrl = new URL('../../../aeon/implementations/typescript/packages/aes/dist/index.js', import.meta.url);
8
9
  const requireFromCwd = createRequire(resolvePath(process.cwd(), 'package.json'));
9
10
  const QUERY_VALUE_METADATA_PROPERTY = '__sansaQueryValueMetadata';
10
11
  const QUERY_OBJECT_FIELD_METADATA_PROPERTY = '__sansaObjectFieldMetadata';
@@ -42,7 +43,9 @@ export async function evaluateQueryForWorkbench({
42
43
  }) {
43
44
  const namespaceResult = sourceKind === 'json'
44
45
  ? namespaceFromJsonSource(source)
45
- : await namespaceFromAeonSource(source);
46
+ : sourceKind === 'telex'
47
+ ? await namespaceFromTelexSource(source)
48
+ : await namespaceFromAeonSource(source);
46
49
 
47
50
  if (!namespaceResult.ok) {
48
51
  return namespaceResult;
@@ -172,6 +175,110 @@ export async function namespaceFromAeonSource(source) {
172
175
  };
173
176
  }
174
177
 
178
+ /**
179
+ * Build a SANSA namespace directly from a complete portable AES stream.
180
+ * The adapter retains portable paths and occurrence identities; it does not
181
+ * reconstruct the implementation-specific AEON parser AST.
182
+ */
183
+ export async function namespaceFromTelexSource(source) {
184
+ const loaded = await loadAeonAesRuntime();
185
+ if (!loaded.ok) {
186
+ const errors = [{
187
+ code: 'SANSA_QUERY_WORKBENCH_TELEX_RUNTIME_UNAVAILABLE',
188
+ message: loaded.message,
189
+ }];
190
+ return {
191
+ ok: false,
192
+ mode: 'evaluate',
193
+ sourceKind: 'telex',
194
+ text: renderDiagnosticText(errors),
195
+ errors,
196
+ };
197
+ }
198
+
199
+ const aes = loaded.module;
200
+ let parsed;
201
+ try {
202
+ parsed = aes.parseTelex(source);
203
+ } catch (error) {
204
+ const errors = [{
205
+ code: error?.code ?? 'TELEX_SYNTAX_ERROR',
206
+ message: error instanceof Error ? error.message : String(error),
207
+ ...(Number.isInteger(error?.line) ? { line: error.line } : {}),
208
+ }];
209
+ return {
210
+ ok: false,
211
+ mode: 'evaluate',
212
+ sourceKind: 'telex',
213
+ text: renderDiagnosticText(errors),
214
+ errors,
215
+ };
216
+ }
217
+
218
+ const validation = aes.validateTelex(parsed, {
219
+ profile: parsed.profile,
220
+ projection: parsed.projection,
221
+ });
222
+ if (!validation.valid) {
223
+ const errors = validation.diagnostics.map((diagnostic) => ({
224
+ code: diagnostic.code,
225
+ message: diagnostic.message,
226
+ ...(typeof diagnostic.path === 'string' ? { path: diagnostic.path } : {}),
227
+ ...(Number.isInteger(diagnostic.record) ? { record: diagnostic.record } : {}),
228
+ }));
229
+ return {
230
+ ok: false,
231
+ mode: 'evaluate',
232
+ sourceKind: 'telex',
233
+ text: renderDiagnosticText(errors),
234
+ errors,
235
+ };
236
+ }
237
+
238
+ if (parsed.profile !== aes.COMPLETE_AES_PROFILE) {
239
+ const errors = [{
240
+ code: 'SANSA_QUERY_WORKBENCH_PARTIAL_AES_UNSUPPORTED',
241
+ message: `SANSA query navigation requires '${aes.COMPLETE_AES_PROFILE}' when no external namespace state is supplied.`,
242
+ }];
243
+ return {
244
+ ok: false,
245
+ mode: 'evaluate',
246
+ sourceKind: 'telex',
247
+ text: renderDiagnosticText(errors),
248
+ errors,
249
+ };
250
+ }
251
+
252
+ try {
253
+ return {
254
+ ok: true,
255
+ namespace: buildNamespaceFromPortableRecords(parsed.records),
256
+ diagnostics: [],
257
+ telex: {
258
+ version: parsed.version,
259
+ profile: parsed.profile,
260
+ profileExplicit: parsed.profileExplicit,
261
+ projection: parsed.projection,
262
+ projectionExplicit: parsed.projectionExplicit,
263
+ canonical: parsed.canonical,
264
+ records: parsed.records,
265
+ },
266
+ };
267
+ } catch (error) {
268
+ const errors = [{
269
+ code: 'SANSA_QUERY_WORKBENCH_INVALID_PORTABLE_AES',
270
+ message: error instanceof Error ? error.message : String(error),
271
+ }];
272
+ return {
273
+ ok: false,
274
+ mode: 'evaluate',
275
+ sourceKind: 'telex',
276
+ text: renderDiagnosticText(errors),
277
+ errors,
278
+ };
279
+ }
280
+ }
281
+
175
282
  async function mountParamsLocalSpace(namespace, paramsSource) {
176
283
  if (String(paramsSource).trim().length === 0) {
177
284
  return { ok: true, namespace, diagnostics: [] };
@@ -256,7 +363,7 @@ async function loadAeonCore() {
256
363
  try {
257
364
  return { ok: true, module: await import(candidate.href) };
258
365
  } catch (error) {
259
- failures.push(`${candidate.label}: ${error.message}`);
366
+ failures.push(`${candidate.label}: ${caughtErrorMessage(error)}`);
260
367
  }
261
368
  }
262
369
 
@@ -270,6 +377,27 @@ async function loadAeonCore() {
270
377
  };
271
378
  }
272
379
 
380
+ export async function loadAeonAesRuntime() {
381
+ const candidates = aeonAesCandidates();
382
+ const failures = [];
383
+ for (const candidate of candidates) {
384
+ try {
385
+ return { ok: true, module: await import(candidate.href) };
386
+ } catch (error) {
387
+ failures.push(`${candidate.label}: ${caughtErrorMessage(error)}`);
388
+ }
389
+ }
390
+
391
+ return {
392
+ ok: false,
393
+ message: [
394
+ 'Could not load an AEON AES TypeScript runtime.',
395
+ 'Install @altopelago/aeon-aes in the calling project, set SANSA_AEON_AES_MODULE to a module path or specifier, or run from the aeon-family development workspace.',
396
+ ...(failures.length === 0 ? [] : [`Tried: ${failures.join('; ')}`]),
397
+ ].join(' '),
398
+ };
399
+ }
400
+
273
401
  function aeonCoreCandidates() {
274
402
  const candidates = [];
275
403
  if (process.env.SANSA_AEON_CORE_MODULE) {
@@ -299,6 +427,35 @@ function aeonCoreCandidates() {
299
427
  return candidates;
300
428
  }
301
429
 
430
+ function aeonAesCandidates() {
431
+ const candidates = [];
432
+ if (process.env.SANSA_AEON_AES_MODULE) {
433
+ candidates.push({
434
+ label: 'SANSA_AEON_AES_MODULE',
435
+ href: moduleHref(process.env.SANSA_AEON_AES_MODULE),
436
+ });
437
+ }
438
+
439
+ try {
440
+ candidates.push({
441
+ label: '@altopelago/aeon-aes',
442
+ href: pathToFileURL(requireFromCwd.resolve('@altopelago/aeon-aes')).href,
443
+ });
444
+ } catch {
445
+ // Optional integration. AEON and JSON sources do not need the AES codec.
446
+ }
447
+
448
+ const devPath = fileURLToPath(devAeonAesUrl);
449
+ if (existsSync(devPath)) {
450
+ candidates.push({
451
+ label: 'aeon-family development path',
452
+ href: devAeonAesUrl.href,
453
+ });
454
+ }
455
+
456
+ return candidates;
457
+ }
458
+
302
459
  function moduleHref(specifier) {
303
460
  if (specifier.startsWith('file:')) return specifier;
304
461
  if (specifier.startsWith('.') || specifier.startsWith('/')) {
@@ -311,6 +468,15 @@ function moduleHref(specifier) {
311
468
  }
312
469
  }
313
470
 
471
+ function caughtErrorMessage(error) {
472
+ if (error instanceof Error) return error.message;
473
+ try {
474
+ return String(error);
475
+ } catch {
476
+ return 'Unknown module import failure';
477
+ }
478
+ }
479
+
314
480
  function remapLocalSpaceBinding(binding, targetAddress) {
315
481
  return remapBindingTree({
316
482
  ...binding,
@@ -392,6 +558,12 @@ function buildNamespaceFromEvents(events, formatPath) {
392
558
  attributeSpace: (binding) => binding.attributeSpace,
393
559
  localSpace: (binding, name) => binding.localSpaces?.[name],
394
560
  parent: (binding) => parents.get(binding) ?? binding.parent,
561
+ representationKindMatches: (binding, expected) => {
562
+ const actual = binding.representationKind;
563
+ return actual === expected
564
+ || lowerFirst(actual) === expected
565
+ || portableRepresentationAlias(actual) === expected;
566
+ },
395
567
  };
396
568
  }
397
569
 
@@ -429,6 +601,234 @@ function buildAttributeSpace(ownerAddress, annotations, parents, parent) {
429
601
  return attributeSpace;
430
602
  }
431
603
 
604
+ function buildNamespaceFromPortableRecords(records) {
605
+ const root = {
606
+ address: '$',
607
+ representationKind: 'object',
608
+ children: [],
609
+ };
610
+ const bodyRecords = records.filter((record) => typeof record.path === 'string');
611
+ const byAddress = new Map([['$', root]]);
612
+ const parsedByAddress = new Map();
613
+ const parents = new Map([[root, null]]);
614
+
615
+ for (const record of bodyRecords) {
616
+ const parsed = parseAddress(record.path);
617
+ if (!parsed.ok || !parsed.address.isExact) {
618
+ const message = parsed.ok
619
+ ? `Portable AES path is not exact: ${record.path}`
620
+ : parsed.errors[0]?.message ?? `Invalid portable AES path: ${record.path}`;
621
+ throw new Error(message);
622
+ }
623
+ const selectors = parsed.address.selectors;
624
+ const final = selectors[selectors.length - 1];
625
+ if (!final || !['member', 'position'].includes(final.type)) {
626
+ throw new Error(`Portable AES event path must end in a member or index: ${record.path}`);
627
+ }
628
+
629
+ byAddress.set(record.path, portableBinding(record, final));
630
+ parsedByAddress.set(record.path, parsed.address);
631
+ }
632
+
633
+ for (const record of bodyRecords) {
634
+ const binding = byAddress.get(record.path);
635
+ const address = parsedByAddress.get(record.path);
636
+ let currentAddress = '$';
637
+ let parent = root;
638
+
639
+ for (const selector of address.selectors.slice(0, -1)) {
640
+ if (selector.type === 'attributeSpace') {
641
+ const spaceAddress = `${currentAddress}.@`;
642
+ let space = byAddress.get(spaceAddress);
643
+ if (!space) {
644
+ space = {
645
+ address: spaceAddress,
646
+ representationKind: 'attributeSpace',
647
+ children: [],
648
+ };
649
+ byAddress.set(spaceAddress, space);
650
+ parents.set(space, parent);
651
+ parent.attributeSpace = space;
652
+ }
653
+ currentAddress = spaceAddress;
654
+ parent = space;
655
+ continue;
656
+ }
657
+
658
+ currentAddress = selector.type === 'member'
659
+ ? appendMember(currentAddress, selector.name)
660
+ : `${currentAddress}[${selector.index}]`;
661
+ const nextParent = byAddress.get(currentAddress);
662
+ if (!nextParent) {
663
+ throw new Error(`Portable AES path '${record.path}' has no parent binding '${currentAddress}'.`);
664
+ }
665
+ parent = nextParent;
666
+ }
667
+
668
+ parent.children.push(binding);
669
+ parents.set(binding, parent);
670
+ if (binding.representationKind === 'NodeHead' && parent.representationKind === 'NodeLiteral') {
671
+ parent.nodeTag = binding.value;
672
+ }
673
+ }
674
+
675
+ return {
676
+ root,
677
+ children: (binding) => binding.children ?? [],
678
+ attributeSpace: (binding) => binding.attributeSpace,
679
+ localSpace: (binding, name) => binding.localSpaces?.[name],
680
+ parent: (binding) => parents.get(binding) ?? binding.parent,
681
+ representationKindMatches: (binding, expected) => {
682
+ const actual = binding.representationKind;
683
+ return actual === expected
684
+ || lowerFirst(actual) === expected
685
+ || portableRepresentationAlias(actual) === expected;
686
+ },
687
+ };
688
+ }
689
+
690
+ function portableBinding(record, finalSelector) {
691
+ const semanticType = typeof record.datatype === 'string'
692
+ ? record.datatype
693
+ : portableSemanticType(record.kind);
694
+ const binding = {
695
+ address: record.path,
696
+ children: [],
697
+ representationKind: record.kind,
698
+ ...(finalSelector.type === 'member' ? { name: finalSelector.name } : { index: finalSelector.index }),
699
+ ...(typeof record.identity === 'string' ? { identity: record.identity } : {}),
700
+ ...(semanticType === undefined ? {} : { semanticType }),
701
+ ...(typeof record.datatype === 'string' ? { datatype: record.datatype } : {}),
702
+ ...(Array.isArray(record.generics) ? { generics: record.generics } : {}),
703
+ ...(Array.isArray(record.clarifiers) ? { clarifiers: record.clarifiers } : {}),
704
+ ...(typeof record.origin === 'string' ? { origin: record.origin } : {}),
705
+ ...(typeof record.span === 'string' ? { span: record.span } : {}),
706
+ };
707
+ const scalarKind = portableScalarKind(record.kind);
708
+ if (scalarKind !== undefined) binding.scalarKind = scalarKind;
709
+ const scalar = scalarFromPortableRecord(record);
710
+ if (scalar.ok) binding.value = scalar.value;
711
+ if (record.kind === 'NullLiteral') binding.nullReason = record.value;
712
+ if (record.kind === 'NodeHead' && typeof record.value === 'string') binding.nodeTag = record.value;
713
+ return binding;
714
+ }
715
+
716
+ function portableSemanticType(kind) {
717
+ switch (kind) {
718
+ case 'StringLiteral': return 'string';
719
+ case 'NumberLiteral': return 'number';
720
+ case 'InfinityLiteral': return 'infinity';
721
+ case 'NaNLiteral': return 'nan';
722
+ case 'NullLiteral': return 'null';
723
+ case 'BooleanLiteral': return 'boolean';
724
+ case 'ToggleLiteral': return 'toggle';
725
+ case 'HexLiteral': return 'hex';
726
+ case 'RadixLiteral': return 'radix';
727
+ case 'EncodingLiteral': return 'encoding';
728
+ case 'SeparatorLiteral': return 'sep';
729
+ case 'SansaAddressLiteral': return 'sansa';
730
+ case 'DateLiteral': return 'date';
731
+ case 'TimeLiteral': return 'time';
732
+ case 'DateTimeLiteral': return 'datetime';
733
+ case 'WTCDateTimeLiteral': return 'wtc';
734
+ default: return undefined;
735
+ }
736
+ }
737
+
738
+ function portableScalarKind(kind) {
739
+ switch (kind) {
740
+ case 'NullLiteral': return 'null';
741
+ case 'InfinityLiteral': return 'infinity';
742
+ case 'NaNLiteral': return 'nan';
743
+ case 'ToggleLiteral': return 'toggle';
744
+ case 'HexLiteral': return 'hex';
745
+ case 'RadixLiteral': return 'radix';
746
+ case 'EncodingLiteral': return 'encoding';
747
+ case 'SeparatorLiteral': return 'separator';
748
+ case 'SansaAddressLiteral': return 'sansaAddress';
749
+ case 'DateLiteral': return 'date';
750
+ case 'TimeLiteral': return 'time';
751
+ case 'DateTimeLiteral': return 'datetime';
752
+ case 'WTCDateTimeLiteral': return 'wtc';
753
+ case 'CloneReference':
754
+ case 'PointerReference':
755
+ return 'referenceForm';
756
+ default:
757
+ return undefined;
758
+ }
759
+ }
760
+
761
+ function portableRepresentationAlias(kind) {
762
+ switch (kind) {
763
+ case 'StringLiteral': return 'string';
764
+ case 'NumberLiteral': return 'number';
765
+ case 'InfinityLiteral': return 'infinity';
766
+ case 'NaNLiteral': return 'nan';
767
+ case 'NullLiteral': return 'null';
768
+ case 'BooleanLiteral': return 'boolean';
769
+ case 'ToggleLiteral': return 'toggle';
770
+ case 'HexLiteral': return 'hex';
771
+ case 'RadixLiteral': return 'radix';
772
+ case 'EncodingLiteral': return 'encoding';
773
+ case 'SeparatorLiteral': return 'separator';
774
+ case 'SansaAddressLiteral': return 'sansa';
775
+ case 'DateLiteral': return 'date';
776
+ case 'TimeLiteral': return 'time';
777
+ case 'DateTimeLiteral': return 'datetime';
778
+ case 'WTCDateTimeLiteral': return 'wtc';
779
+ case 'ObjectNode': return 'object';
780
+ case 'ListNode': return 'list';
781
+ case 'TupleLiteral': return 'tuple';
782
+ case 'NodeLiteral': return 'node';
783
+ case 'CloneReference': return 'cloneReference';
784
+ case 'PointerReference': return 'pointerReference';
785
+ default: return undefined;
786
+ }
787
+ }
788
+
789
+ function scalarFromPortableRecord(record) {
790
+ switch (record.kind) {
791
+ case 'StringLiteral':
792
+ case 'HexLiteral':
793
+ case 'RadixLiteral':
794
+ case 'EncodingLiteral':
795
+ case 'SeparatorLiteral':
796
+ case 'DateLiteral':
797
+ case 'TimeLiteral':
798
+ case 'DateTimeLiteral':
799
+ case 'WTCDateTimeLiteral':
800
+ case 'NodeHead':
801
+ return { ok: true, value: record.value ?? '' };
802
+ case 'SansaAddressLiteral':
803
+ return {
804
+ ok: true,
805
+ value: {
806
+ type: 'SansaAddressLiteral',
807
+ address: record.value ?? '',
808
+ canonical: record.value ?? '',
809
+ },
810
+ };
811
+ case 'NumberLiteral':
812
+ return { ok: true, value: Number(record.value) };
813
+ case 'InfinityLiteral':
814
+ return { ok: true, value: record.value === '-Infinity' ? -Infinity : Infinity };
815
+ case 'NaNLiteral':
816
+ return { ok: true, value: Number.NaN };
817
+ case 'BooleanLiteral':
818
+ return { ok: true, value: record.value === 'true' };
819
+ case 'ToggleLiteral':
820
+ return { ok: true, value: record.value ?? '' };
821
+ case 'NullLiteral':
822
+ return { ok: true, value: null };
823
+ case 'CloneReference':
824
+ return { ok: true, value: referenceFormValue('CloneReference', record.value ?? '') };
825
+ case 'PointerReference':
826
+ return { ok: true, value: referenceFormValue('PointerReference', record.value ?? '') };
827
+ default:
828
+ return { ok: false };
829
+ }
830
+ }
831
+
432
832
  function appendMember(base, name) {
433
833
  return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name)
434
834
  ? `${base}.${name}`
@@ -772,6 +1172,7 @@ function renderBindingInspectLines(binding, label) {
772
1172
  return [
773
1173
  ...(summary.name === undefined ? [] : [`${label}.name: ${summary.name}`]),
774
1174
  ...(summary.index === undefined ? [] : [`${label}.index: ${summary.index}`]),
1175
+ ...(summary.identity === undefined ? [] : [`${label}.identity: ${summary.identity}`]),
775
1176
  ...(summary.semanticType === undefined ? [] : [`${label}.semanticType: ${summary.semanticType}`]),
776
1177
  ...(summary.representationKind === undefined ? [] : [`${label}.representationKind: ${summary.representationKind}`]),
777
1178
  ...(summary.scalarKind === undefined ? [] : [`${label}.scalarKind: ${summary.scalarKind}`]),
@@ -825,6 +1226,7 @@ function summarizeBinding(binding) {
825
1226
  ...(binding.address === undefined ? {} : { address: binding.address }),
826
1227
  ...(binding.name === undefined ? {} : { name: binding.name }),
827
1228
  ...(binding.index === undefined ? {} : { index: binding.index }),
1229
+ ...(binding.identity === undefined ? {} : { identity: binding.identity }),
828
1230
  ...(binding.semanticType === undefined ? {} : { semanticType: binding.semanticType }),
829
1231
  ...(binding.representationKind === undefined ? {} : { representationKind: binding.representationKind }),
830
1232
  ...(binding.scalarKind === undefined ? {} : { scalarKind: binding.scalarKind }),