@ontrails/core 0.2.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 (86) hide show
  1. package/CHANGELOG.md +849 -0
  2. package/README.md +190 -0
  3. package/package.json +36 -0
  4. package/src/activation-provenance.ts +116 -0
  5. package/src/activation-source-compatibility.ts +430 -0
  6. package/src/activation-source-derivation.ts +227 -0
  7. package/src/activation-source.ts +93 -0
  8. package/src/blob-ref.ts +90 -0
  9. package/src/branded.ts +135 -0
  10. package/src/collections.ts +99 -0
  11. package/src/compose-batch.ts +69 -0
  12. package/src/compose-schema.ts +36 -0
  13. package/src/context.ts +66 -0
  14. package/src/derive.ts +485 -0
  15. package/src/detours.ts +8 -0
  16. package/src/diagnostics.ts +21 -0
  17. package/src/draft.ts +350 -0
  18. package/src/entity.ts +346 -0
  19. package/src/error-rendering.ts +87 -0
  20. package/src/errors.ts +483 -0
  21. package/src/execute.ts +1577 -0
  22. package/src/fetch.ts +138 -0
  23. package/src/fire.ts +1172 -0
  24. package/src/glob.ts +81 -0
  25. package/src/guards.ts +37 -0
  26. package/src/index.ts +704 -0
  27. package/src/internal/fork-ctx.ts +69 -0
  28. package/src/layer-field-rendering.ts +193 -0
  29. package/src/layer.ts +81 -0
  30. package/src/observe.ts +361 -0
  31. package/src/path-scope.ts +66 -0
  32. package/src/path-security.ts +98 -0
  33. package/src/patterns/bulk.ts +16 -0
  34. package/src/patterns/change.ts +12 -0
  35. package/src/patterns/date-range.ts +12 -0
  36. package/src/patterns/index.ts +8 -0
  37. package/src/patterns/pagination.ts +22 -0
  38. package/src/patterns/progress.ts +13 -0
  39. package/src/patterns/sorting.ts +14 -0
  40. package/src/patterns/status.ts +11 -0
  41. package/src/patterns/timestamps.ts +12 -0
  42. package/src/permits.ts +12 -0
  43. package/src/queue.ts +163 -0
  44. package/src/redaction/index.ts +3 -0
  45. package/src/redaction/patterns.ts +50 -0
  46. package/src/redaction/redactor.ts +178 -0
  47. package/src/resilience.ts +234 -0
  48. package/src/resource-config.ts +804 -0
  49. package/src/resource.ts +194 -0
  50. package/src/result.ts +212 -0
  51. package/src/run.ts +76 -0
  52. package/src/runtime-builtins.ts +69 -0
  53. package/src/schedule-runtime.ts +689 -0
  54. package/src/schedule.ts +326 -0
  55. package/src/serialization.ts +265 -0
  56. package/src/sha256.ts +136 -0
  57. package/src/signal-diagnostics.ts +633 -0
  58. package/src/signal-ref.ts +111 -0
  59. package/src/signal.ts +104 -0
  60. package/src/store/accessor-protocol.ts +56 -0
  61. package/src/store/index.ts +4 -0
  62. package/src/structured-examples.ts +248 -0
  63. package/src/surface-derivation.ts +91 -0
  64. package/src/surface-filter.ts +101 -0
  65. package/src/surface-overlay.ts +694 -0
  66. package/src/surface-versioning.ts +42 -0
  67. package/src/topo.ts +835 -0
  68. package/src/tracing.ts +346 -0
  69. package/src/trail-id-glob.ts +15 -0
  70. package/src/trail.ts +1351 -0
  71. package/src/trails/derive-trail.ts +835 -0
  72. package/src/trails/index.ts +9 -0
  73. package/src/trails/ingest.ts +152 -0
  74. package/src/trails-db.ts +212 -0
  75. package/src/transport-error-map.ts +163 -0
  76. package/src/type-utils.ts +87 -0
  77. package/src/types.ts +300 -0
  78. package/src/validate-established-topo.ts +73 -0
  79. package/src/validate-topo.ts +725 -0
  80. package/src/validation.ts +330 -0
  81. package/src/version-marker.ts +716 -0
  82. package/src/version-resolution.ts +308 -0
  83. package/src/version-runtime.ts +120 -0
  84. package/src/webhook.ts +461 -0
  85. package/src/workspace.ts +244 -0
  86. package/src/zod-wrappers.ts +72 -0
package/src/topo.ts ADDED
@@ -0,0 +1,835 @@
1
+ /**
2
+ * Application entry point — scans module exports to build a topology graph.
3
+ */
4
+
5
+ import type { AnyEntity } from './entity.js';
6
+ import { ValidationError } from './errors.js';
7
+ import type { ActivationEntry } from './activation-source.js';
8
+ import {
9
+ getLateBoundSignalRef,
10
+ parseLateBoundSignalMarker,
11
+ } from './signal-ref.js';
12
+ import type { Layer } from './layer.js';
13
+ import {
14
+ hasObserveCapabilities,
15
+ isLogger,
16
+ isLogSink,
17
+ isObserveConfig,
18
+ isObserveInput,
19
+ isTraceSink,
20
+ normalizeObserve,
21
+ } from './observe.js';
22
+ import type { ObserveConfig, TopoOptions } from './observe.js';
23
+ import type { AnySignal } from './signal.js';
24
+ import type { AnyResource } from './resource.js';
25
+ import { isResource } from './resource.js';
26
+ import type { AnyTrail } from './trail.js';
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // Public types
30
+ // ---------------------------------------------------------------------------
31
+
32
+ export interface TopoIdentity {
33
+ readonly name: string;
34
+ readonly version?: string;
35
+ readonly description?: string;
36
+ }
37
+
38
+ export interface Topo {
39
+ readonly name: string;
40
+ readonly version?: string;
41
+ readonly description?: string;
42
+ readonly entities: ReadonlyMap<string, AnyEntity>;
43
+ readonly trails: ReadonlyMap<string, AnyTrail>;
44
+ readonly signals: ReadonlyMap<string, AnySignal>;
45
+ readonly resources: ReadonlyMap<string, AnyResource>;
46
+ readonly observe?: ObserveConfig | undefined;
47
+ /**
48
+ * Typed layers attached at topo scope (always present, default `[]`).
49
+ *
50
+ * The CLI/MCP/HTTP surfaces forward these into `executeTrail` as
51
+ * `topoLayers`, where they are composed outermost in the layer chain.
52
+ * The final composition order is `topo → surface → trail → implementation`
53
+ * (outermost-first).
54
+ */
55
+ readonly layers: readonly Layer[];
56
+ readonly count: number;
57
+ readonly entityCount: number;
58
+ readonly resourceCount: number;
59
+ getEntity(name: string): AnyEntity | undefined;
60
+ get(id: string): AnyTrail | undefined;
61
+ getResource(id: string): AnyResource | undefined;
62
+ hasEntity(name: string): boolean;
63
+ has(id: string): boolean;
64
+ hasResource(id: string): boolean;
65
+ entityIds(): string[];
66
+ ids(): string[];
67
+ resourceIds(): string[];
68
+ listEntities(): AnyEntity[];
69
+ list(): AnyTrail[];
70
+ listSignals(): AnySignal[];
71
+ listResources(): AnyResource[];
72
+ }
73
+
74
+ // ---------------------------------------------------------------------------
75
+ // Kind discriminant check
76
+ // ---------------------------------------------------------------------------
77
+
78
+ type Registrable = AnyEntity | AnyTrail | AnySignal | AnyResource;
79
+
80
+ const isRegistrable = (value: unknown): value is Registrable => {
81
+ if (typeof value !== 'object' || value === null) {
82
+ return false;
83
+ }
84
+ const { kind } = value as Record<string, unknown>;
85
+ return kind === 'entity' || kind === 'trail' || kind === 'signal';
86
+ };
87
+
88
+ // ---------------------------------------------------------------------------
89
+ // Topo implementation
90
+ // ---------------------------------------------------------------------------
91
+
92
+ const createTopo = (
93
+ identity: TopoIdentity,
94
+ entities: ReadonlyMap<string, AnyEntity>,
95
+ trails: ReadonlyMap<string, AnyTrail>,
96
+ signals: ReadonlyMap<string, AnySignal>,
97
+ resources: ReadonlyMap<string, AnyResource>,
98
+ observe: ObserveConfig | undefined,
99
+ layers: readonly Layer[]
100
+ ): Topo => ({
101
+ count: trails.size,
102
+ entities,
103
+ entityCount: entities.size,
104
+ entityIds(): string[] {
105
+ return [...entities.keys()];
106
+ },
107
+ get(id: string): AnyTrail | undefined {
108
+ return trails.get(id);
109
+ },
110
+ getEntity(entityName: string): AnyEntity | undefined {
111
+ return entities.get(entityName);
112
+ },
113
+ getResource(id: string): AnyResource | undefined {
114
+ return resources.get(id);
115
+ },
116
+ has(id: string): boolean {
117
+ return trails.has(id);
118
+ },
119
+ hasEntity(entityName: string): boolean {
120
+ return entities.has(entityName);
121
+ },
122
+ hasResource(id: string): boolean {
123
+ return resources.has(id);
124
+ },
125
+ ids(): string[] {
126
+ return [...trails.keys()];
127
+ },
128
+
129
+ list(): AnyTrail[] {
130
+ return [...trails.values()];
131
+ },
132
+ listEntities(): AnyEntity[] {
133
+ return [...entities.values()];
134
+ },
135
+ listResources(): AnyResource[] {
136
+ return [...resources.values()];
137
+ },
138
+
139
+ listSignals(): AnySignal[] {
140
+ return [...signals.values()];
141
+ },
142
+
143
+ name: identity.name,
144
+ ...(identity.version !== undefined && { version: identity.version }),
145
+ ...(identity.description !== undefined && {
146
+ description: identity.description,
147
+ }),
148
+ ...(observe !== undefined && { observe }),
149
+ layers,
150
+ resourceCount: resources.size,
151
+ resourceIds(): string[] {
152
+ return [...resources.keys()];
153
+ },
154
+ resources,
155
+ signals,
156
+ trails,
157
+ });
158
+
159
+ // ---------------------------------------------------------------------------
160
+ // topo()
161
+ // ---------------------------------------------------------------------------
162
+
163
+ const registerUnique = <T>(
164
+ collection: Map<string, T>,
165
+ id: string,
166
+ value: T,
167
+ duplicateMessage: string
168
+ ): void => {
169
+ const existing = collection.get(id);
170
+ if (existing === value) {
171
+ return;
172
+ }
173
+ if (existing !== undefined) {
174
+ throw new ValidationError(duplicateMessage);
175
+ }
176
+ collection.set(id, value);
177
+ };
178
+
179
+ const registerEntity = (
180
+ entity: AnyEntity,
181
+ entities: Map<string, AnyEntity>
182
+ ): void => {
183
+ registerUnique(
184
+ entities,
185
+ entity.name,
186
+ entity,
187
+ `Duplicate entity name: "${entity.name}"`
188
+ );
189
+ };
190
+
191
+ const registerResourceValue = (
192
+ resource: AnyResource,
193
+ resources: Map<string, AnyResource>
194
+ ): void => {
195
+ registerUnique(
196
+ resources,
197
+ resource.id,
198
+ resource,
199
+ `Duplicate resource ID: "${resource.id}"`
200
+ );
201
+ };
202
+
203
+ const registerSignal = (
204
+ signal: AnySignal,
205
+ signals: Map<string, AnySignal>
206
+ ): void => {
207
+ registerUnique(
208
+ signals,
209
+ signal.id,
210
+ signal,
211
+ `Duplicate signal ID: "${signal.id}"`
212
+ );
213
+ };
214
+
215
+ const registerResourceSignals = (
216
+ resource: AnyResource,
217
+ signals: Map<string, AnySignal>
218
+ ): void => {
219
+ for (const derived of resource.signals ?? []) {
220
+ registerSignal(derived, signals);
221
+ }
222
+ };
223
+
224
+ const registerTrail = (
225
+ trail: AnyTrail,
226
+ trails: Map<string, AnyTrail>
227
+ ): void => {
228
+ registerUnique(trails, trail.id, trail, `Duplicate trail ID: "${trail.id}"`);
229
+ };
230
+
231
+ const registerLateBoundSignalId = (
232
+ byToken: Map<string, Set<string>>,
233
+ signal: AnySignal
234
+ ): void => {
235
+ const ref = getLateBoundSignalRef(signal);
236
+ if (!ref) {
237
+ return;
238
+ }
239
+
240
+ const ids = byToken.get(ref.token) ?? new Set<string>();
241
+ ids.add(signal.id);
242
+ byToken.set(ref.token, ids);
243
+ };
244
+
245
+ const collectLateBoundSignalIdsByToken = (
246
+ resources: ReadonlyMap<string, AnyResource>
247
+ ): ReadonlyMap<string, readonly string[]> => {
248
+ const byToken = new Map<string, Set<string>>();
249
+
250
+ for (const resource of resources.values()) {
251
+ for (const signal of resource.signals ?? []) {
252
+ registerLateBoundSignalId(byToken, signal);
253
+ }
254
+ }
255
+
256
+ return new Map(
257
+ [...byToken.entries()].map(([token, ids]) => [token, [...ids]])
258
+ );
259
+ };
260
+
261
+ const resolveLateBoundSignalId = (
262
+ trailId: string,
263
+ signalId: string,
264
+ lateBoundSignalIdsByToken: ReadonlyMap<string, readonly string[]>
265
+ ): string => {
266
+ const marker = parseLateBoundSignalMarker(signalId);
267
+ if (!marker) {
268
+ return signalId;
269
+ }
270
+
271
+ const matches = lateBoundSignalIdsByToken.get(marker.token) ?? [];
272
+ if (matches.length === 1) {
273
+ return matches[0] ?? signalId;
274
+ }
275
+
276
+ if (matches.length === 0) {
277
+ // Intentional throw: split-topo composition (where a trail and the
278
+ // store that backs its signals live in different topos) is not yet
279
+ // supported. Failing loudly here surfaces the case at assembly time
280
+ // instead of silently producing a trail with an unresolved store
281
+ // reference that would misbehave at runtime.
282
+ throw new ValidationError(
283
+ `Trail "${trailId}" references store-derived signal "${marker.displayId}", but no resource bound in this topo exposes it. ` +
284
+ 'This usually means the store that backs this signal is not bound in this topo. ' +
285
+ `Bind the store via resource() in the same topo() call as "${trailId}", or compose this topo with the topo that binds the store. ` +
286
+ 'Splitting a trail and its backing store across independent topos is not yet supported.'
287
+ );
288
+ }
289
+
290
+ throw new ValidationError(
291
+ `Trail "${trailId}" references late-bound signal "${marker.displayId}" but it resolves to multiple bound resource signals: ${matches.join(', ')}. Use canonical scoped ids when the same store definition is bound more than once.`
292
+ );
293
+ };
294
+
295
+ const resolveTrailSignalIds = (
296
+ trailId: string,
297
+ signalIds: readonly string[],
298
+ lateBoundSignalIdsByToken: ReadonlyMap<string, readonly string[]>
299
+ ): { changed: boolean; ids: readonly string[] } => {
300
+ let changed = false;
301
+ const ids = Object.freeze(
302
+ signalIds.map((signalId) => {
303
+ const resolved = resolveLateBoundSignalId(
304
+ trailId,
305
+ signalId,
306
+ lateBoundSignalIdsByToken
307
+ );
308
+ changed ||= resolved !== signalId;
309
+ return resolved;
310
+ })
311
+ );
312
+
313
+ return { changed, ids };
314
+ };
315
+
316
+ const resolveTrailActivationSources = (
317
+ trailId: string,
318
+ activations: readonly ActivationEntry[],
319
+ lateBoundSignalIdsByToken: ReadonlyMap<string, readonly string[]>
320
+ ): { changed: boolean; activations: readonly ActivationEntry[] } => {
321
+ let changed = false;
322
+ const resolved = Object.freeze(
323
+ activations.map((entry) => {
324
+ if (entry.source.kind !== 'signal') {
325
+ return entry;
326
+ }
327
+
328
+ const resolvedId = resolveLateBoundSignalId(
329
+ trailId,
330
+ entry.source.id,
331
+ lateBoundSignalIdsByToken
332
+ );
333
+ if (resolvedId === entry.source.id) {
334
+ return entry;
335
+ }
336
+
337
+ changed = true;
338
+ return Object.freeze({
339
+ ...entry,
340
+ source: Object.freeze({ ...entry.source, id: resolvedId }),
341
+ });
342
+ })
343
+ );
344
+
345
+ return { activations: resolved, changed };
346
+ };
347
+
348
+ const finalizeTrailSignals = (
349
+ trails: ReadonlyMap<string, AnyTrail>,
350
+ resources: ReadonlyMap<string, AnyResource>
351
+ ): Map<string, AnyTrail> => {
352
+ const lateBoundSignalIdsByToken = collectLateBoundSignalIdsByToken(resources);
353
+ const finalized = new Map<string, AnyTrail>();
354
+
355
+ for (const trail of trails.values()) {
356
+ const resolvedFires = resolveTrailSignalIds(
357
+ trail.id,
358
+ trail.fires ?? [],
359
+ lateBoundSignalIdsByToken
360
+ );
361
+ const resolvedOn = resolveTrailSignalIds(
362
+ trail.id,
363
+ trail.on ?? [],
364
+ lateBoundSignalIdsByToken
365
+ );
366
+ const resolvedActivationSources = resolveTrailActivationSources(
367
+ trail.id,
368
+ trail.activationSources ?? [],
369
+ lateBoundSignalIdsByToken
370
+ );
371
+
372
+ if (
373
+ !resolvedFires.changed &&
374
+ !resolvedOn.changed &&
375
+ !resolvedActivationSources.changed
376
+ ) {
377
+ finalized.set(trail.id, trail);
378
+ continue;
379
+ }
380
+
381
+ finalized.set(
382
+ trail.id,
383
+ Object.freeze({
384
+ ...trail,
385
+ activationSources: resolvedActivationSources.activations,
386
+ fires: resolvedFires.ids,
387
+ on: resolvedOn.ids,
388
+ })
389
+ );
390
+ }
391
+
392
+ return finalized;
393
+ };
394
+
395
+ /** Register a single registrable value into the appropriate map. */
396
+ const register = (
397
+ value: Registrable,
398
+ entities: Map<string, AnyEntity>,
399
+ trails: Map<string, AnyTrail>,
400
+ signals: Map<string, AnySignal>,
401
+ resources: Map<string, AnyResource>
402
+ ): void => {
403
+ switch (value.kind) {
404
+ case 'entity': {
405
+ registerEntity(value as AnyEntity, entities);
406
+ break;
407
+ }
408
+ case 'resource': {
409
+ registerResourceValue(value as AnyResource, resources);
410
+ break;
411
+ }
412
+ case 'signal': {
413
+ registerSignal(value as AnySignal, signals);
414
+ break;
415
+ }
416
+ case 'trail': {
417
+ registerTrail(value as AnyTrail, trails);
418
+ break;
419
+ }
420
+ default: {
421
+ throw new ValidationError('Unsupported registrable value in topo()');
422
+ }
423
+ }
424
+ };
425
+
426
+ const registerTrailEntities = (
427
+ trail: AnyTrail,
428
+ entities: Map<string, AnyEntity>,
429
+ trails: Map<string, AnyTrail>,
430
+ signals: Map<string, AnySignal>,
431
+ resources: Map<string, AnyResource>
432
+ ): void => {
433
+ for (const entity of trail.entities ?? []) {
434
+ register(entity, entities, trails, signals, resources);
435
+ }
436
+ };
437
+
438
+ const markUniqueObject = (
439
+ value: unknown,
440
+ seenValues: WeakSet<object>
441
+ ): boolean => {
442
+ if (typeof value !== 'object' || value === null) {
443
+ return true;
444
+ }
445
+ if (seenValues.has(value)) {
446
+ return false;
447
+ }
448
+ seenValues.add(value);
449
+ return true;
450
+ };
451
+
452
+ const registerModuleValue = (
453
+ value: unknown,
454
+ entities: Map<string, AnyEntity>,
455
+ trails: Map<string, AnyTrail>,
456
+ signals: Map<string, AnySignal>,
457
+ resources: Map<string, AnyResource>
458
+ ): void => {
459
+ if (isResource(value) || isRegistrable(value)) {
460
+ register(value, entities, trails, signals, resources);
461
+ }
462
+
463
+ if (isResource(value)) {
464
+ registerResourceSignals(value, signals);
465
+ }
466
+
467
+ if (
468
+ typeof value === 'object' &&
469
+ value !== null &&
470
+ (value as { kind?: unknown }).kind === 'trail'
471
+ ) {
472
+ registerTrailEntities(
473
+ value as AnyTrail,
474
+ entities,
475
+ trails,
476
+ signals,
477
+ resources
478
+ );
479
+ }
480
+ };
481
+
482
+ const registerModuleValues = (
483
+ mod: Record<string, unknown>,
484
+ entities: Map<string, AnyEntity>,
485
+ trails: Map<string, AnyTrail>,
486
+ signals: Map<string, AnySignal>,
487
+ resources: Map<string, AnyResource>
488
+ ): void => {
489
+ const seenValues = new WeakSet<object>();
490
+ for (const value of Object.values(mod)) {
491
+ if (!markUniqueObject(value, seenValues)) {
492
+ continue;
493
+ }
494
+ registerModuleValue(value, entities, trails, signals, resources);
495
+ }
496
+ };
497
+
498
+ const TOPO_OPTION_KEYS = ['layers', 'observe'] as const;
499
+ const TOPO_OPTION_KEY_SET: ReadonlySet<string> = new Set(TOPO_OPTION_KEYS);
500
+
501
+ /**
502
+ * Brand symbol applied by `topo.options()`. The presence of this symbol
503
+ * marks an object as an explicit `TopoOptions` payload, which is the
504
+ * unambiguous way to disambiguate a trailing options object from a
505
+ * trailing module export. Use `topo.options()` whenever a module might
506
+ * legitimately export only fields whose names collide with topo options
507
+ * (for example a module whose sole export is `observe`).
508
+ */
509
+ const TOPO_OPTIONS_BRAND: unique symbol = Symbol('trails.topo.options');
510
+
511
+ const hasOptionsBrand = (value: object): boolean =>
512
+ (value as { [TOPO_OPTIONS_BRAND]?: true })[TOPO_OPTIONS_BRAND] === true;
513
+
514
+ const looksLikeTopoOptionsShape = (value: object): boolean => {
515
+ const keys = Object.keys(value);
516
+ if (keys.length === 0) {
517
+ return false;
518
+ }
519
+ return keys.every((key) => TOPO_OPTION_KEY_SET.has(key));
520
+ };
521
+
522
+ const detectUnknownOptionKeys = (value: object): readonly string[] => {
523
+ const unknown: string[] = [];
524
+ for (const key of Object.keys(value)) {
525
+ if (!TOPO_OPTION_KEY_SET.has(key)) {
526
+ unknown.push(key);
527
+ }
528
+ }
529
+ return unknown;
530
+ };
531
+
532
+ const hasRegistrableKind = (value: unknown): boolean => {
533
+ if (typeof value !== 'object' || value === null) {
534
+ return false;
535
+ }
536
+ const { kind } = value as { kind?: unknown };
537
+ return (
538
+ kind === 'entity' ||
539
+ kind === 'trail' ||
540
+ kind === 'signal' ||
541
+ kind === 'resource'
542
+ );
543
+ };
544
+
545
+ /**
546
+ * When a branded `topo.options()` payload carries a bare `LogSink` in the
547
+ * `observe` slot, rewrite it to the explicit `{ log: sink }` form. The brand
548
+ * already signals "this is options, not a module"; once that is settled, a
549
+ * bare `LogSink` unambiguously names a log target and should not be rejected
550
+ * as ambiguous downstream.
551
+ *
552
+ * Bare `TraceSink` values (no `name` field) are left untouched — they already
553
+ * round-trip through `normalizeObserve` via the `isTraceSink` fallthrough.
554
+ * Already-disambiguated shapes (`{ log }`, `{ trace }`, `Logger`,
555
+ * `ObserveCapable`, etc.) are also left untouched.
556
+ */
557
+ const disambiguateBrandedObserve = (options: TopoOptions): TopoOptions => {
558
+ const { observe } = options;
559
+ if (
560
+ observe === undefined ||
561
+ isLogger(observe) ||
562
+ isObserveConfig(observe) ||
563
+ hasObserveCapabilities(observe)
564
+ ) {
565
+ return options;
566
+ }
567
+ if (isLogSink(observe)) {
568
+ return { ...options, observe: { log: observe } };
569
+ }
570
+ return options;
571
+ };
572
+
573
+ /**
574
+ * Decide whether the trailing argument should be treated as a
575
+ * `TopoOptions` payload, a module export, or rejected as ambiguous.
576
+ *
577
+ * Resolution rules (in order):
578
+ * 1. Branded via `topo.options()` → always options. Unknown option
579
+ * keys throw, and downstream `normalizeObserve` rejects malformed
580
+ * values. A bare `LogSink` (`{ name, write }`) in the `observe`
581
+ * slot is auto-wrapped as `{ log: sink }` so the brand is the
582
+ * complete escape hatch the docs promise.
583
+ * 2. The shape does not look like `TopoOptions` (mixed keys or no
584
+ * keys) → module.
585
+ * 3. The trailing arg is a registrable module export
586
+ * (`kind: 'trail' | 'entity' | …`) under a known option key →
587
+ * module. Preserves the "module exporting a single trail named
588
+ * `observe`" case that the warden and existing apps rely on.
589
+ * 4. The `observe` value is a bare `LogSink` or `TraceSink` (a sink
590
+ * shape that could equally plausibly be a module export named
591
+ * `observe`) → throw, since the call is genuinely ambiguous.
592
+ * `topo.options()` exists to disambiguate.
593
+ * 5. The `observe` value is otherwise a recognizable `ObserveInput`
594
+ * (`Logger`, `ObserveConfig`, or `ObserveCapable`) → options.
595
+ * Those shapes carry enough structure that they cannot be
596
+ * mistaken for a generic module export.
597
+ * 6. Otherwise (non-sink helper object, function, primitive, etc.)
598
+ * → module. The non-registrable export is silently ignored, the
599
+ * same as any other unrecognized value in a module record.
600
+ */
601
+ const classifyTrailingArgument = (
602
+ value: unknown
603
+ ):
604
+ | { readonly kind: 'options'; readonly options: TopoOptions }
605
+ | { readonly kind: 'module' }
606
+ | { readonly kind: 'invalid'; readonly message: string } => {
607
+ if (typeof value !== 'object' || value === null) {
608
+ return { kind: 'module' };
609
+ }
610
+
611
+ if (hasOptionsBrand(value)) {
612
+ const unknown = detectUnknownOptionKeys(value);
613
+ if (unknown.length > 0) {
614
+ return {
615
+ kind: 'invalid',
616
+ message: `topo.options() received unknown option keys: ${unknown
617
+ .map((key) => `"${key}"`)
618
+ .join(', ')}. Expected one of: ${TOPO_OPTION_KEYS.map(
619
+ (key) => `"${key}"`
620
+ ).join(', ')}.`,
621
+ };
622
+ }
623
+ // Branding via `topo.options()` is the documented escape hatch for
624
+ // disambiguating bare-sink shorthand. Wrap a bare `LogSink` in the
625
+ // explicit `{ log: sink }` slot before handing off to `normalizeObserve`,
626
+ // which would otherwise reject it as ambiguous (a LogSink shape matches
627
+ // both `isLogSink` and `isTraceSink`). A bare TraceSink (no `name`) does
628
+ // not need rewriting because `normalizeObserve` already accepts it via
629
+ // the `isTraceSink` fallthrough.
630
+ return {
631
+ kind: 'options',
632
+ options: disambiguateBrandedObserve(value as TopoOptions),
633
+ };
634
+ }
635
+
636
+ if (!looksLikeTopoOptionsShape(value)) {
637
+ return { kind: 'module' };
638
+ }
639
+
640
+ // The shape matches `TopoOptions`. Decide whether the values are
641
+ // valid options, a registrable module export, or a non-registrable
642
+ // helper that should be treated as a (silently ignored) module
643
+ // export.
644
+ const observeValue = (value as TopoOptions).observe;
645
+ const layersValue = (value as TopoOptions).layers;
646
+
647
+ // A module export named `layers` would be a non-registrable array, but
648
+ // an explicit `topo.options({ layers: [...] })` is the documented escape
649
+ // hatch for that disambiguation. Without the brand, accept the trailing
650
+ // argument as options when `layers` is an array and `observe` is either
651
+ // unset or already an unambiguous option shape — this mirrors how
652
+ // `observe`-only options are accepted today.
653
+ if (Array.isArray(layersValue) && observeValue === undefined) {
654
+ return { kind: 'options', options: value as TopoOptions };
655
+ }
656
+
657
+ if (hasRegistrableKind(observeValue)) {
658
+ return { kind: 'module' };
659
+ }
660
+ // Unambiguous option shapes: `Logger`, `ObserveConfig`, and
661
+ // `ObserveCapable` carry enough structure that they cannot be
662
+ // confused with a generic module export. Check these first so the
663
+ // sink-ambiguity guard below does not accidentally reject an
664
+ // `ObserveCapable` whose underlying shape happens to also satisfy
665
+ // `isLogSink` / `isTraceSink`.
666
+ if (
667
+ isLogger(observeValue) ||
668
+ isObserveConfig(observeValue) ||
669
+ hasObserveCapabilities(observeValue)
670
+ ) {
671
+ return { kind: 'options', options: value as TopoOptions };
672
+ }
673
+ // Bare sink shapes (`{ write }` / `{ name, write }`) are genuinely
674
+ // ambiguous — they may equally plausibly be a module export named
675
+ // `observe`. Refuse to guess; require `topo.options()` to make the
676
+ // intent explicit.
677
+ if (isLogSink(observeValue) || isTraceSink(observeValue)) {
678
+ return {
679
+ kind: 'invalid',
680
+ message:
681
+ 'topo() received a trailing argument shaped like `{ observe: sink }` that is ambiguous: ' +
682
+ 'the value matches both a TopoOptions sink and a non-registrable module export. ' +
683
+ 'Wrap the options with `topo.options({ observe: sink })` to disambiguate.',
684
+ };
685
+ }
686
+ if (isObserveInput(observeValue)) {
687
+ // Catch-all for any future `ObserveInput` variant added to the
688
+ // type. Today this branch is unreachable given the guards above.
689
+ return { kind: 'options', options: value as TopoOptions };
690
+ }
691
+ // Non-registrable, non-sink helper. Treat as a module export; the
692
+ // unrecognized value is silently ignored during registration, matching
693
+ // the behavior of any other non-registrable export.
694
+ return { kind: 'module' };
695
+ };
696
+
697
+ const splitTopoArguments = (
698
+ modulesOrOptions: readonly (Record<string, unknown> | TopoOptions)[]
699
+ ): {
700
+ readonly modules: readonly Record<string, unknown>[];
701
+ readonly options: TopoOptions | undefined;
702
+ } => {
703
+ // A branded `topo.options(...)` payload is an explicit user signal and must
704
+ // appear last. If it shows up in a non-trailing position the caller almost
705
+ // certainly intended it as options but lost the configuration silently.
706
+ // Reject it so the misconfiguration is visible at construction.
707
+ for (let i = 0; i < modulesOrOptions.length - 1; i += 1) {
708
+ const arg = modulesOrOptions[i];
709
+ if (typeof arg === 'object' && arg !== null && hasOptionsBrand(arg)) {
710
+ throw new ValidationError(
711
+ `topo.options(...) must be the final argument to topo(); received at position ${i + 2} of ${modulesOrOptions.length + 1}.`
712
+ );
713
+ }
714
+ }
715
+
716
+ const last = modulesOrOptions.at(-1);
717
+ const classification = classifyTrailingArgument(last);
718
+
719
+ if (classification.kind === 'invalid') {
720
+ throw new ValidationError(classification.message);
721
+ }
722
+ if (classification.kind === 'options') {
723
+ return {
724
+ modules: modulesOrOptions.slice(0, -1) as Record<string, unknown>[],
725
+ options: classification.options,
726
+ };
727
+ }
728
+ return {
729
+ modules: modulesOrOptions as readonly Record<string, unknown>[],
730
+ options: undefined,
731
+ };
732
+ };
733
+
734
+ /**
735
+ * Brand a plain `TopoOptions` payload so `topo()` treats the trailing
736
+ * argument as options unambiguously, regardless of which keys it
737
+ * contains. Useful when a module export shape would otherwise collide
738
+ * with the inline shorthand (e.g. a module exporting only `observe`).
739
+ *
740
+ * @example
741
+ * ```ts
742
+ * topo('app', userTrails, topo.options({ observe: traceSink }));
743
+ * ```
744
+ */
745
+ const describeNonPlainObject = (value: unknown): string => {
746
+ if (value === null) {
747
+ return 'null';
748
+ }
749
+ if (Array.isArray(value)) {
750
+ return 'array';
751
+ }
752
+ return typeof value;
753
+ };
754
+
755
+ const brandTopoOptions = (options: TopoOptions): TopoOptions => {
756
+ // Reject non-plain-object inputs up front. `{ ...options }` happily
757
+ // accepts `null`, `undefined`, primitives, and arrays, silently
758
+ // producing an empty branded payload that callers would then assume
759
+ // carried real options. Throwing here mirrors the strict handling
760
+ // applied to other malformed options elsewhere in the classifier.
761
+ if (
762
+ typeof options !== 'object' ||
763
+ options === null ||
764
+ Array.isArray(options)
765
+ ) {
766
+ throw new ValidationError(
767
+ `topo.options() expects a plain options object; received ${describeNonPlainObject(
768
+ options
769
+ )}`
770
+ );
771
+ }
772
+ // Return a fresh object rather than mutating the caller's payload.
773
+ // Mutating in place breaks frozen / non-extensible inputs (for example
774
+ // `topo.options(Object.freeze({ observe: sink }))`), which would throw
775
+ // a `TypeError` from `Object.defineProperty` even though the value is
776
+ // a valid `TopoOptions` shape.
777
+ const branded = { ...options };
778
+ Object.defineProperty(branded, TOPO_OPTIONS_BRAND, {
779
+ configurable: false,
780
+ enumerable: false,
781
+ value: true,
782
+ writable: false,
783
+ });
784
+ return branded;
785
+ };
786
+
787
+ interface TopoFn {
788
+ (
789
+ nameOrIdentity: string | TopoIdentity,
790
+ ...modulesOrOptions: (Record<string, unknown> | TopoOptions)[]
791
+ ): Topo;
792
+ /**
793
+ * Brand a plain `TopoOptions` payload so `topo()` treats the trailing
794
+ * argument as options unambiguously, regardless of key shape. Use this
795
+ * when a module export shape might otherwise collide with the inline
796
+ * options shorthand.
797
+ */
798
+ readonly options: (options: TopoOptions) => TopoOptions;
799
+ }
800
+
801
+ const topoImpl = (
802
+ nameOrIdentity: string | TopoIdentity,
803
+ ...modulesOrOptions: (Record<string, unknown> | TopoOptions)[]
804
+ ): Topo => {
805
+ const identity: TopoIdentity =
806
+ typeof nameOrIdentity === 'string'
807
+ ? { name: nameOrIdentity }
808
+ : nameOrIdentity;
809
+ const { modules, options } = splitTopoArguments(modulesOrOptions);
810
+ const observe = normalizeObserve(options?.observe);
811
+ const layers = Object.freeze([...(options?.layers ?? [])]);
812
+
813
+ const entities = new Map<string, AnyEntity>();
814
+ const trails = new Map<string, AnyTrail>();
815
+ const signals = new Map<string, AnySignal>();
816
+ const resources = new Map<string, AnyResource>();
817
+
818
+ for (const mod of modules) {
819
+ registerModuleValues(mod, entities, trails, signals, resources);
820
+ }
821
+
822
+ return createTopo(
823
+ identity,
824
+ entities,
825
+ finalizeTrailSignals(trails, resources),
826
+ signals,
827
+ resources,
828
+ observe,
829
+ layers
830
+ );
831
+ };
832
+
833
+ export const topo: TopoFn = Object.assign(topoImpl, {
834
+ options: brandTopoOptions,
835
+ });