asma-core-helpers 0.32.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/lib/collaboration/applyOperation.d.ts +5 -13
  2. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  3. package/lib/collaboration/applyOperation.js +450 -20
  4. package/lib/collaboration/applyOperation.js.map +1 -1
  5. package/lib/collaboration/operations.d.ts +113 -1
  6. package/lib/collaboration/operations.d.ts.map +1 -1
  7. package/lib/collaboration/operations.js +7 -0
  8. package/lib/collaboration/operations.js.map +1 -1
  9. package/lib/collaboration/schemas.d.ts +54 -0
  10. package/lib/collaboration/schemas.d.ts.map +1 -1
  11. package/lib/collaboration/schemas.js +74 -1
  12. package/lib/collaboration/schemas.js.map +1 -1
  13. package/lib/collaboration/templateDocument.d.ts +194 -0
  14. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  15. package/lib/collaboration/templateDocument.js +104 -0
  16. package/lib/collaboration/templateDocument.js.map +1 -1
  17. package/lib/collaboration/testHelpers/documentGenerator.d.ts +24 -0
  18. package/lib/collaboration/testHelpers/documentGenerator.d.ts.map +1 -1
  19. package/lib/collaboration/testHelpers/documentGenerator.js +180 -2
  20. package/lib/collaboration/testHelpers/documentGenerator.js.map +1 -1
  21. package/lib/collaboration/typeContracts.d.ts +73 -1
  22. package/lib/collaboration/typeContracts.d.ts.map +1 -1
  23. package/lib/g-definitions.d.ts +17 -0
  24. package/lib/g-definitions.d.ts.map +1 -1
  25. package/lib/g-definitions.js +13 -0
  26. package/lib/g-definitions.js.map +1 -1
  27. package/lib/helpers/sectionPath.helpers.d.ts +64 -0
  28. package/lib/helpers/sectionPath.helpers.d.ts.map +1 -0
  29. package/lib/helpers/sectionPath.helpers.js +68 -0
  30. package/lib/helpers/sectionPath.helpers.js.map +1 -0
  31. package/lib/index.d.ts +1 -0
  32. package/lib/index.d.ts.map +1 -1
  33. package/lib/index.js +1 -0
  34. package/lib/index.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/collaboration/applyOperation.ts +517 -17
  37. package/src/collaboration/operations.ts +95 -0
  38. package/src/collaboration/property.test.ts +49 -0
  39. package/src/collaboration/schemas.ts +82 -0
  40. package/src/collaboration/templateDocument.ts +238 -1
  41. package/src/collaboration/testHelpers/documentGenerator.ts +201 -2
  42. package/src/collaboration/typeContracts.ts +106 -1
  43. package/src/collaboration/typedAuthoring.test.ts +1091 -0
  44. package/src/collaboration/typedAuthoringHardening.test.ts +344 -1
  45. package/src/g-definitions.ts +29 -0
  46. package/src/helpers/sectionPath.helpers.test.ts +159 -0
  47. package/src/helpers/sectionPath.helpers.ts +129 -0
  48. package/src/index.ts +1 -0
@@ -10,7 +10,18 @@ import {
10
10
  } from './applyOperation.js'
11
11
  import type { TemplateOp } from './operations.js'
12
12
  import { templateOpSchema } from './schemas.js'
13
- import { emptyTemplateDocument, type ActionMetadata, type QnrTemplateDocument } from './templateDocument.js'
13
+ import {
14
+ emptyTemplateDocument,
15
+ isLegacyUnresolvedId,
16
+ LEGACY_UNRESOLVED_ID_PREFIX,
17
+ makeLegacyUnresolvedId,
18
+ parseLegacyBindingOverride,
19
+ type ActionMetadata,
20
+ type QnrTemplateDocument,
21
+ } from './templateDocument.js'
22
+ import { canonicalJson, reduceToMinimalForm } from './canonicalize.js'
23
+ import { templateDocumentIsDefault, validateTemplateDocument } from './schemas.js'
24
+ import { findDocLawViolations as findDocLawViolationsOf } from './docLaws.js'
14
25
 
15
26
  /**
16
27
  * The hardening pass over ASMA-7683's typed authoring surface.
@@ -406,3 +417,335 @@ describe('mappingFilter.setTyped is validated in the reducer, not only at the wi
406
417
  assert.deepEqual(doc.mappingFiltersById?.['f-1'], { fieldId: 'Navn', operator: 'contains', value: 'ada' })
407
418
  })
408
419
  })
420
+
421
+ // ───────────────── the legacy mapping exception and its reserved evidence ids (freeze §1a) ─────────────────
422
+
423
+ /**
424
+ * `legacyOverride` is a **released, open** document member with a new closed producer on top.
425
+ *
426
+ * That split is the whole design: stored documents already carry arbitrary values there, so the
427
+ * document type and schema keep admitting them (DEC-006), while the new operation admits nothing but
428
+ * canonical. The three-way parser is what lets a consumer act on the difference — publication refuses a
429
+ * malformed value, and a bundle pick reports it unrepresentable instead of silently dropping evidence.
430
+ */
431
+ const bindingScaffold = (): QnrTemplateDocument =>
432
+ apply([
433
+ { type: 'question.create', questionId: 'q-1', questionType: 'TextShort' },
434
+ { type: 'mappingBinding.create', bindingId: 'b-1', nodeId: 'n-1', fieldId: 'Navn', target: { kind: 'question', questionId: 'q-1' } },
435
+ ], scaffold())
436
+
437
+ const binding = (doc: QnrTemplateDocument, id = 'b-1') => doc.mappingBindingsById?.[id]
438
+
439
+ describe('parseLegacyBindingOverride is total over three outcomes', () => {
440
+ it('separates absent from malformed, which a boolean guard would merge', () => {
441
+ // A consumer must tell "nothing to refuse" from "refuse this". Collapsing them would make
442
+ // publication either reject every unmapped binding or accept every malformed one.
443
+ assert.equal(parseLegacyBindingOverride(undefined).status, 'absent')
444
+ assert.equal(parseLegacyBindingOverride(null).status, 'malformed')
445
+ })
446
+
447
+ it('accepts each single member and the all-member record', () => {
448
+ for (const value of [
449
+ { planId: 'Actor.Navn' },
450
+ { kind: 'connector' },
451
+ { mappingRule: 'rule-7' },
452
+ { planId: 'Actor.Navn', kind: 'connector', mappingRule: 'rule-7' },
453
+ ]) {
454
+ const result = parseLegacyBindingOverride(value)
455
+ assert.equal(result.status, 'known', JSON.stringify(value))
456
+ assert.deepEqual(result.status === 'known' ? result.value : undefined, value)
457
+ }
458
+ })
459
+
460
+ it('classifies every forbidden shape as malformed rather than known', () => {
461
+ for (const value of [
462
+ {}, // records nothing; also a second encoding of absent
463
+ { planId: '' }, // an empty string is not a value
464
+ { planId: 1 },
465
+ { planId: true },
466
+ { planId: { nested: 'x' } },
467
+ { planId: ['a'] },
468
+ [],
469
+ ['Actor.Navn'],
470
+ 'Actor.Navn',
471
+ 42,
472
+ { actorType: 'mappable' }, // the exact member the freeze names as forbidden
473
+ { planId: 'Actor.Navn', actorType: 'mappable' },
474
+ { planId: 'Actor.Navn', customerId: 'c-1' },
475
+ { planId: 'Actor.Navn', credentials: 'secret' },
476
+ { mapping_rule: 'rule-7' }, // the snake_case legacy spelling is boundary-only
477
+ ]) {
478
+ assert.equal(parseLegacyBindingOverride(value).status, 'malformed', JSON.stringify(value))
479
+ }
480
+ })
481
+ })
482
+
483
+ describe('mappingBinding.setLegacyOverride is member-only', () => {
484
+ it('sets, replaces, clears, and leaves no empty object behind', () => {
485
+ const set = apply(
486
+ [{ type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: { planId: 'Actor.Navn' } }],
487
+ bindingScaffold(),
488
+ )
489
+ assert.deepEqual(binding(set)?.legacyOverride, { planId: 'Actor.Navn' })
490
+
491
+ const replaced = apply(
492
+ [{ type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: { kind: 'connector' } }],
493
+ set,
494
+ )
495
+ // A replace is a whole-value write: the previous `planId` must not survive underneath.
496
+ assert.deepEqual(binding(replaced)?.legacyOverride, { kind: 'connector' })
497
+
498
+ const cleared = apply([{ type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: null }], replaced)
499
+ assert.equal('legacyOverride' in (binding(cleared) ?? {}), false)
500
+ assert.deepEqual(findDocLawViolationsOf(cleared), [])
501
+ })
502
+
503
+ it('is idempotent for the same value and last-writer-wins for the same binding', () => {
504
+ const once = apply(
505
+ [{ type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: { planId: 'Actor.Navn' } }],
506
+ bindingScaffold(),
507
+ )
508
+ const twice = apply(
509
+ [{ type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: { planId: 'Actor.Navn' } }],
510
+ once,
511
+ )
512
+ // Content, not `revision`: the revision is a monotonic counter every applied op bumps, so
513
+ // comparing whole documents would assert the counter never moves rather than that the write is
514
+ // idempotent.
515
+ assert.equal(canonicalJson({ ...once, revision: 0 }), canonicalJson({ ...twice, revision: 0 }))
516
+
517
+ const last = apply(
518
+ [
519
+ { type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: { planId: 'A' } },
520
+ { type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: { planId: 'B' } },
521
+ ],
522
+ bindingScaffold(),
523
+ )
524
+ assert.deepEqual(binding(last)?.legacyOverride, { planId: 'B' })
525
+ })
526
+
527
+ it('leaves node, field, target, options and every bindingOrder byte-identical', () => {
528
+ const base = apply(
529
+ [
530
+ { type: 'mappingBinding.update', bindingId: 'b-1', patch: { cardinality: '1..*', onMissing: 'error', onMany: 'first' } },
531
+ { type: 'dataMapping.create', mappingId: 'm-1', sourceId: 'src-1', rootNodeId: 'n-1' },
532
+ ],
533
+ bindingScaffold(),
534
+ )
535
+ const before = canonicalJson({ binding: binding(base), mappings: base.dataMappingsById })
536
+
537
+ const after = apply(
538
+ [
539
+ { type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: { planId: 'Actor.Navn' } },
540
+ { type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: null },
541
+ ],
542
+ base,
543
+ )
544
+ // Set-then-clear must be a round trip: an exception is repair evidence, never a graph edit.
545
+ assert.equal(canonicalJson({ binding: binding(after), mappings: after.dataMappingsById }), before)
546
+ })
547
+
548
+ it('refuses a missing binding and refuses a malformed value on replay', () => {
549
+ throwsConflict(
550
+ () => apply([{ type: 'mappingBinding.setLegacyOverride', bindingId: 'ghost', legacyOverride: { planId: 'x' } }], bindingScaffold()),
551
+ 'a missing binding must be refused',
552
+ )
553
+ // The reducer re-checks: a replayed log reaches it with no validator in front, so a malformed
554
+ // value must not become canonical merely by being replayed.
555
+ for (const bad of [{}, { planId: '' }, { actorType: 'mappable' }]) {
556
+ throwsConflict(
557
+ () => apply([{ type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: bad as never }], bindingScaffold()),
558
+ `${JSON.stringify(bad)} must be refused by the reducer`,
559
+ )
560
+ }
561
+ })
562
+
563
+ it('changes on distinct bindings both survive', () => {
564
+ const two = apply(
565
+ [
566
+ { type: 'question.create', questionId: 'q-2', questionType: 'TextShort' },
567
+ { type: 'mappingBinding.create', bindingId: 'b-2', nodeId: 'n-1', fieldId: 'Alder', target: { kind: 'question', questionId: 'q-2' } },
568
+ { type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: { planId: 'A' } },
569
+ { type: 'mappingBinding.setLegacyOverride', bindingId: 'b-2', legacyOverride: { planId: 'B' } },
570
+ ],
571
+ bindingScaffold(),
572
+ )
573
+ assert.deepEqual(binding(two, 'b-1')?.legacyOverride, { planId: 'A' })
574
+ assert.deepEqual(binding(two, 'b-2')?.legacyOverride, { planId: 'B' })
575
+ })
576
+ })
577
+
578
+ describe('historical binding values stay readable and replayable', () => {
579
+ it('keeps an arbitrary stored override readable, and the parser calls it malformed', () => {
580
+ // The v0.31 way of getting a value in there: `mappingBinding.update`, untouched by this repair.
581
+ const doc = apply(
582
+ [{ type: 'mappingBinding.update', bindingId: 'b-1', patch: { legacyOverride: { actorType: 'mappable', planId: 'Actor.Navn' } } }],
583
+ bindingScaffold(),
584
+ )
585
+ // Readable and schema-valid: narrowing the document member would make this row unloadable.
586
+ const validated = validateTemplateDocument(doc)
587
+ assert.ok(validated.ok, validated.ok ? '' : validated.summary)
588
+ assert.equal(parseLegacyBindingOverride(binding(doc)?.legacyOverride).status, 'malformed')
589
+ // …but the new typed writer will not reproduce it.
590
+ throwsConflict(
591
+ () => apply([{ type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: { actorType: 'mappable' } as never }], doc),
592
+ 'the typed op must refuse what update tolerated',
593
+ )
594
+ })
595
+
596
+ it('replays a v0.31 create/update log to a byte-identical document', () => {
597
+ // Recorded literally: if either arm changed shape, this string moves.
598
+ const doc = apply(
599
+ [
600
+ { type: 'mappingBinding.update', bindingId: 'b-1', patch: { fieldId: 'Fodselsnummer', cardinality: '1' } },
601
+ { type: 'mappingBinding.update', bindingId: 'b-1', patch: { someUnknownMember: 'kept' } },
602
+ ],
603
+ bindingScaffold(),
604
+ )
605
+ assert.equal(
606
+ canonicalJson(binding(doc)),
607
+ '{"cardinality":"1","fieldId":"Fodselsnummer","nodeId":"n-1","someUnknownMember":"kept","target":{"kind":"question","questionId":"q-1"}}',
608
+ )
609
+ })
610
+
611
+ it('survives canonical reduction when non-empty, and is pruned only by an explicit clear', () => {
612
+ const set = apply(
613
+ [{ type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride: { planId: 'Actor.Navn', kind: 'connector' } }],
614
+ bindingScaffold(),
615
+ )
616
+ const reduced = reduceToMinimalForm(set, { isDefault: templateDocumentIsDefault })
617
+ // DOC-LAW-2 prunes defaults and empties; a recorded exception is neither.
618
+ assert.deepEqual(
619
+ (reduced.mappingBindingsById?.['b-1'] as Record<string, unknown>)['legacyOverride'],
620
+ { planId: 'Actor.Navn', kind: 'connector' },
621
+ )
622
+ })
623
+ })
624
+
625
+ describe('reserved unresolved-evidence ids', () => {
626
+ const digest = 'a'.repeat(64)
627
+ const other = 'b'.repeat(64)
628
+
629
+ it('is deterministic and disjoint by discriminator', () => {
630
+ assert.equal(makeLegacyUnresolvedId('entity', digest), makeLegacyUnresolvedId('entity', digest))
631
+ // One evidence digest must not produce a string that satisfies both address spaces, or a field
632
+ // placeholder would pass where an entity was required.
633
+ assert.notEqual(makeLegacyUnresolvedId('entity', digest), makeLegacyUnresolvedId('field', digest))
634
+ assert.notEqual(makeLegacyUnresolvedId('entity', digest), makeLegacyUnresolvedId('entity', other))
635
+ assert.equal(makeLegacyUnresolvedId('entity', digest), `${LEGACY_UNRESOLVED_ID_PREFIX}entity:${digest}`)
636
+ })
637
+
638
+ it('is deliberately invalid under the engine MachineId grammar', () => {
639
+ // `^[A-Za-z0-9_.-]+$` forbids the colon, so a curated id can never collide with a placeholder
640
+ // and no activation rule has to change to keep them apart.
641
+ for (const kind of ['entity', 'field'] as const) {
642
+ assert.equal(/^[A-Za-z0-9_.-]+$/.test(makeLegacyUnresolvedId(kind, digest)), false)
643
+ }
644
+ })
645
+
646
+ it('recognizes exactly the canonical grammar', () => {
647
+ assert.equal(isLegacyUnresolvedId(makeLegacyUnresolvedId('entity', digest)), true)
648
+ assert.equal(isLegacyUnresolvedId(makeLegacyUnresolvedId('field', digest)), true)
649
+ })
650
+
651
+ it('refuses every prefix claimant, which is what splits the quarantine into two classes', () => {
652
+ for (const value of [
653
+ `${LEGACY_UNRESOLVED_ID_PREFIX}node:${digest}`, // wrong discriminator
654
+ `${LEGACY_UNRESOLVED_ID_PREFIX}entity:${'A'.repeat(64)}`, // uppercase digest
655
+ `${LEGACY_UNRESOLVED_ID_PREFIX}entity:${'a'.repeat(63)}`, // short
656
+ `${LEGACY_UNRESOLVED_ID_PREFIX}entity:${'a'.repeat(65)}`, // long
657
+ `${LEGACY_UNRESOLVED_ID_PREFIX}entity:${'g'.repeat(64)}`, // non-hex
658
+ `${LEGACY_UNRESOLVED_ID_PREFIX}entity:`, // empty suffix
659
+ LEGACY_UNRESOLVED_ID_PREFIX, // prefix only
660
+ `${LEGACY_UNRESOLVED_ID_PREFIX}entity:${digest} `, // trailing space
661
+ ` ${LEGACY_UNRESOLVED_ID_PREFIX}entity:${digest}`, // leading space
662
+ `x${LEGACY_UNRESOLVED_ID_PREFIX}entity:${digest}`, // prefixed lookalike
663
+ `${LEGACY_UNRESOLVED_ID_PREFIX}entity:${digest}:extra`, // suffixed lookalike
664
+ 'legacy-unresolved-entity:' + digest, // separator swapped
665
+ undefined,
666
+ null,
667
+ 42,
668
+ ]) {
669
+ assert.equal(isLegacyUnresolvedId(value), false, String(value))
670
+ }
671
+ })
672
+
673
+ it('refuses to build from a digest that is not 64 lowercase hex characters', () => {
674
+ // A placeholder the recognizer would reject is worse than an error: consumers would quarantine
675
+ // it as a malformed claimant, which is not what the caller meant to record.
676
+ for (const bad of ['', 'abc', 'A'.repeat(64), 'g'.repeat(64), 'a'.repeat(63), 'a'.repeat(65), `${digest} `]) {
677
+ assert.throws(() => makeLegacyUnresolvedId('entity', bad), /not a 64-character lowercase SHA-256 hex digest/)
678
+ }
679
+ })
680
+
681
+ it('is usable as a node entityId and a binding fieldId that still validate', () => {
682
+ // The point of the placeholder: the graph keeps its shape instead of losing the observed binding.
683
+ const doc = apply(
684
+ [
685
+ { type: 'mappingNode.create', nodeId: 'n-u', entityId: makeLegacyUnresolvedId('entity', digest) },
686
+ { type: 'question.create', questionId: 'q-u', questionType: 'TextShort' },
687
+ { type: 'mappingBinding.create', bindingId: 'b-u', nodeId: 'n-u', fieldId: makeLegacyUnresolvedId('field', other), target: { kind: 'question', questionId: 'q-u' } },
688
+ { type: 'mappingBinding.setLegacyOverride', bindingId: 'b-u', legacyOverride: { planId: 'Actor.Ukjent' } },
689
+ ],
690
+ bindingScaffold(),
691
+ )
692
+ const validated = validateTemplateDocument(doc)
693
+ assert.ok(validated.ok, validated.ok ? '' : validated.summary)
694
+ assert.equal(isLegacyUnresolvedId(doc.mappingNodesById?.['n-u']?.entityId), true)
695
+ assert.equal(isLegacyUnresolvedId(binding(doc, 'b-u')?.fieldId), true)
696
+ })
697
+ })
698
+
699
+ // ───────── survivor closure: the override wire boundary and the array guard ─────────
700
+
701
+ describe('the setLegacyOverride op schema is closed at the wire', () => {
702
+ const op = (legacyOverride: unknown) =>
703
+ templateOpSchema({ type: 'mappingBinding.setLegacyOverride', bindingId: 'b-1', legacyOverride })
704
+
705
+ it('refuses an undeclared member on every arm of the union', () => {
706
+ // ArkType admits undeclared keys unless told otherwise, and the union has three arms — so
707
+ // `'+': 'reject'` has to be on each. Dropping it from the `planId` arm alone let
708
+ // `{planId, actorType}` through, which is the exact member the freeze names as forbidden.
709
+ for (const value of [
710
+ { planId: 'Actor.Navn', actorType: 'mappable' },
711
+ { kind: 'connector', actorType: 'mappable' },
712
+ { mappingRule: 'rule-7', actorType: 'mappable' },
713
+ { planId: 'Actor.Navn', customerId: 'c-1' },
714
+ { planId: 'Actor.Navn', credentials: 'secret' },
715
+ { mapping_rule: 'rule-7' },
716
+ ]) {
717
+ assert.ok(op(value) instanceof type.errors, `${JSON.stringify(value)} must not validate`)
718
+ }
719
+ })
720
+
721
+ it('refuses the empty record, an empty string, a wrong scalar and a nested object', () => {
722
+ for (const value of [{}, { planId: '' }, { planId: 1 }, { planId: { nested: 'x' } }, [], 'Actor.Navn']) {
723
+ assert.ok(op(value) instanceof type.errors, `${JSON.stringify(value)} must not validate`)
724
+ }
725
+ })
726
+
727
+ it('accepts each legal arm and the null clear', () => {
728
+ for (const value of [
729
+ { planId: 'Actor.Navn' },
730
+ { kind: 'connector' },
731
+ { mappingRule: 'rule-7' },
732
+ { planId: 'Actor.Navn', kind: 'connector', mappingRule: 'rule-7' },
733
+ null,
734
+ ]) {
735
+ assert.ok(!(op(value) instanceof type.errors), `${JSON.stringify(value)} must validate`)
736
+ }
737
+ })
738
+ })
739
+
740
+ describe('the parser array guard is load-bearing', () => {
741
+ it('refuses an array carrying a whitelisted own-property', () => {
742
+ // `typeof [] === 'object'`, so without the `Array.isArray` check an array reaches the member
743
+ // loop. A plain array is still malformed via its numeric keys — but an array with a `planId`
744
+ // own-property has exactly the entries of a legal record, and would be classified `known`.
745
+ const arrayWithMember = Object.assign([], { planId: 'Actor.Navn' })
746
+ assert.equal(parseLegacyBindingOverride(arrayWithMember).status, 'malformed')
747
+ // The plain cases stay malformed too, so the guard is additive rather than the only check.
748
+ assert.equal(parseLegacyBindingOverride([]).status, 'malformed')
749
+ assert.equal(parseLegacyBindingOverride(['Actor.Navn']).status, 'malformed')
750
+ })
751
+ })
@@ -143,6 +143,17 @@ declare global {
143
143
  isLogged?: () => boolean
144
144
  logoutUser?: () => void
145
145
  //logoutMfes?: (() => void)[]
146
+ /**
147
+ * Feature flags the currently-running shell declares support for. Widgets read this to
148
+ * detect an old, already-deployed shell that can't recognise a capability yet (per-tenant
149
+ * shell/widget versions are pinned independently, so a widget can run under a shell older
150
+ * than itself) — absence of a key means "not supported," never a hard error.
151
+ */
152
+ capabilities?: {
153
+ /** Shell registers `<section>/*` wildcard routes, so a widget may put its selected
154
+ * tab in the URL path (`createSectionPath`/`useSectionTab`). */
155
+ sectionRoutePaths?: boolean
156
+ }
146
157
  }
147
158
 
148
159
  _env_cloud?: Record<'adopus' | 'adcuris', Record<string, string>>
@@ -170,6 +181,24 @@ export const subscribeToHistory = (listener: () => void) => {
170
181
  return unsubscribe
171
182
  }
172
183
 
184
+ export type ShellCapability = keyof NonNullable<NonNullable<Window['__ASMA__SHELL__']>['capabilities']>
185
+
186
+ /** `false` for a shell that predates the capability (never declared it) — never throws, never guesses. */
187
+ export const hasShellCapability = (capability: ShellCapability): boolean =>
188
+ !!realWindow.__ASMA__SHELL__?.capabilities?.[capability]
189
+
190
+ /** Called once by the shell on boot. Merges so multiple declarations (or a widget's own defaulting
191
+ * during local dev without a shell) never clobber capabilities set elsewhere. */
192
+ export const declareShellCapability = (capability: ShellCapability): void => {
193
+ realWindow.__ASMA__SHELL__ = {
194
+ ...realWindow.__ASMA__SHELL__,
195
+ capabilities: {
196
+ ...realWindow.__ASMA__SHELL__?.capabilities,
197
+ [capability]: true,
198
+ },
199
+ }
200
+ }
201
+
173
202
  export { type History, createBrowserHistory }
174
203
 
175
204
  function getHistory() {
@@ -0,0 +1,159 @@
1
+ import assert from 'node:assert/strict'
2
+ import { describe, it } from 'node:test'
3
+
4
+ import { createDetailPath, createSectionPath, type HistoryLike } from './sectionPath.helpers.js'
5
+
6
+ type Tab = 'info' | 'users' | 'employees'
7
+ const TABS: readonly Tab[] = ['info', 'users', 'employees']
8
+
9
+ function fakeHistory(pathname: string, search = ''): HistoryLike & { calls: Array<{ method: string; to: unknown; state: unknown }> } {
10
+ const calls: Array<{ method: string; to: unknown; state: unknown }> = []
11
+ return {
12
+ location: { pathname, search },
13
+ push: (to, state) => calls.push({ method: 'push', to, state }),
14
+ replace: (to, state) => calls.push({ method: 'replace', to, state }),
15
+ calls,
16
+ }
17
+ }
18
+
19
+ describe('createSectionPath', () => {
20
+ it('parses the bare root as the default (no) tab', () => {
21
+ const section = createSectionPath({ base: 'reports/time-tracking-list', tabs: TABS, defaultTab: 'info', history: fakeHistory('/') })
22
+ assert.deepEqual(section.parse('/reports/time-tracking-list'), {})
23
+ })
24
+
25
+ it('parses a known tab segment', () => {
26
+ const section = createSectionPath({ base: 'reports/time-tracking-list', tabs: TABS, defaultTab: 'info', history: fakeHistory('/') })
27
+ assert.deepEqual(section.parse('/reports/time-tracking-list/users'), { tab: 'users' })
28
+ })
29
+
30
+ it('treats an unknown tab segment as no tab', () => {
31
+ const section = createSectionPath({ base: 'reports/time-tracking-list', tabs: TABS, defaultTab: 'info', history: fakeHistory('/') })
32
+ assert.deepEqual(section.parse('/reports/time-tracking-list/bogus'), { tab: undefined })
33
+ })
34
+
35
+ it('returns undefined outside the section, so an embedded widget never rewrites the URL', () => {
36
+ const section = createSectionPath({ base: 'reports/time-tracking-list', tabs: TABS, defaultTab: 'info', history: fakeHistory('/') })
37
+ assert.equal(section.parse('/overview'), undefined)
38
+ assert.equal(section.parse('/reports/time-tracking-list-team-leader'), undefined)
39
+ })
40
+
41
+ it('builds a tab path, defaulting to defaultTab', () => {
42
+ const section = createSectionPath({ base: 'tasks', tabs: TABS, defaultTab: 'info', history: fakeHistory('/') })
43
+ assert.equal(section.build('users'), '/tasks/users')
44
+ assert.equal(section.build(), '/tasks/info')
45
+ })
46
+
47
+ it('goToTab pushes the tab path with detail params stripped from the current search', () => {
48
+ const history = fakeHistory('/tasks/info', '?task_id=42&keep=me')
49
+ const section = createSectionPath({
50
+ base: 'tasks',
51
+ tabs: TABS,
52
+ defaultTab: 'info',
53
+ detailParams: ['task_id'],
54
+ history,
55
+ })
56
+ section.goToTab('users')
57
+ assert.deepEqual(history.calls, [{ method: 'push', to: { pathname: '/tasks/users', search: '?keep=me' }, state: undefined }])
58
+ })
59
+
60
+ it('replaceTab issues a replace, not a push', () => {
61
+ const history = fakeHistory('/tasks/info')
62
+ const section = createSectionPath({ base: 'tasks', tabs: TABS, defaultTab: 'info', history })
63
+ section.replaceTab('employees')
64
+ assert.equal(history.calls[0]?.method, 'replace')
65
+ })
66
+
67
+ it('forwards a navigation-guard state marker verbatim', () => {
68
+ const history = fakeHistory('/tasks/info')
69
+ const section = createSectionPath({ base: 'tasks', tabs: TABS, defaultTab: 'info', history })
70
+ section.goToTab('users', 'asma:tab-switch-guarded')
71
+ assert.equal(history.calls[0]?.state, 'asma:tab-switch-guarded')
72
+ })
73
+
74
+ it('searchWithoutDetail is a no-op when nothing to strip', () => {
75
+ const history = fakeHistory('/tasks/info', '?keep=me')
76
+ const section = createSectionPath({ base: 'tasks', tabs: TABS, defaultTab: 'info', detailParams: ['task_id'], history })
77
+ assert.equal(section.searchWithoutDetail(), '?keep=me')
78
+ })
79
+ })
80
+
81
+ describe('createDetailPath', () => {
82
+ const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
83
+ const CUSTOMER_ID = '11111111-1111-1111-1111-111111111111'
84
+
85
+ function customersPath(history: HistoryLike = fakeHistory('/')) {
86
+ return createDetailPath({
87
+ base: 'admin-panel/customers',
88
+ tabs: TABS,
89
+ defaultTab: 'info',
90
+ isDetailId: (segment) => UUID_REGEX.test(segment),
91
+ history,
92
+ })
93
+ }
94
+
95
+ it('parses the bare root as the list (no detail)', () => {
96
+ assert.deepEqual(customersPath().parse('/admin-panel/customers'), {})
97
+ })
98
+
99
+ it('treats a non-UUID first segment as the list, not a detail id', () => {
100
+ assert.deepEqual(customersPath().parse('/admin-panel/customers/not-a-uuid'), {})
101
+ })
102
+
103
+ it('parses a detail id with no tab', () => {
104
+ assert.deepEqual(customersPath().parse(`/admin-panel/customers/${CUSTOMER_ID}`), {
105
+ detailId: CUSTOMER_ID,
106
+ tab: undefined,
107
+ })
108
+ })
109
+
110
+ it('parses a detail id with a known tab', () => {
111
+ assert.deepEqual(customersPath().parse(`/admin-panel/customers/${CUSTOMER_ID}/employees`), {
112
+ detailId: CUSTOMER_ID,
113
+ tab: 'employees',
114
+ })
115
+ })
116
+
117
+ it('returns undefined outside the section', () => {
118
+ assert.equal(customersPath().parse('/admin-panel/designer-overview'), undefined)
119
+ })
120
+
121
+ it('builds a detail path, defaulting the tab', () => {
122
+ const path = customersPath()
123
+ assert.equal(path.build(CUSTOMER_ID), `/admin-panel/customers/${CUSTOMER_ID}/info`)
124
+ assert.equal(path.build(CUSTOMER_ID, 'employees'), `/admin-panel/customers/${CUSTOMER_ID}/employees`)
125
+ })
126
+
127
+ it('goToList pushes the bare root with detail params stripped', () => {
128
+ const history = fakeHistory(`/admin-panel/customers/${CUSTOMER_ID}/info`, '?tekst_grp_nr=9&keep=me')
129
+ const path = createDetailPath({
130
+ base: 'admin-panel/customers',
131
+ tabs: TABS,
132
+ defaultTab: 'info',
133
+ isDetailId: (segment) => UUID_REGEX.test(segment),
134
+ detailParams: ['tekst_grp_nr'],
135
+ history,
136
+ })
137
+ path.goToList()
138
+ assert.deepEqual(history.calls, [
139
+ { method: 'push', to: { pathname: '/admin-panel/customers', search: '?keep=me' }, state: undefined },
140
+ ])
141
+ })
142
+
143
+ it('goToDetail and replaceDetail push/replace the same shape', () => {
144
+ const history = fakeHistory('/admin-panel/customers')
145
+ const path = createDetailPath({
146
+ base: 'admin-panel/customers',
147
+ tabs: TABS,
148
+ defaultTab: 'info',
149
+ isDetailId: (segment) => UUID_REGEX.test(segment),
150
+ history,
151
+ })
152
+ path.goToDetail(CUSTOMER_ID, 'users')
153
+ path.replaceDetail(CUSTOMER_ID, 'employees')
154
+ assert.deepEqual(history.calls, [
155
+ { method: 'push', to: { pathname: `/admin-panel/customers/${CUSTOMER_ID}/users`, search: '' }, state: undefined },
156
+ { method: 'replace', to: { pathname: `/admin-panel/customers/${CUSTOMER_ID}/employees`, search: '' }, state: undefined },
157
+ ])
158
+ })
159
+ })