@ontrails/core 1.0.0-beta.3 → 1.0.0-beta.32

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 (249) hide show
  1. package/CHANGELOG.md +323 -8
  2. package/README.md +114 -33
  3. package/package.json +11 -1
  4. package/src/activation-provenance.ts +111 -0
  5. package/src/activation-source-compatibility.ts +430 -0
  6. package/src/activation-source-projection.ts +221 -0
  7. package/src/activation-source.ts +91 -0
  8. package/src/blob-ref.ts +51 -0
  9. package/src/branded.ts +1 -1
  10. package/src/compose-batch.ts +69 -0
  11. package/src/compose-schema.ts +36 -0
  12. package/src/context.ts +44 -10
  13. package/src/contour.ts +346 -0
  14. package/src/derive.ts +250 -19
  15. package/src/detours.ts +8 -0
  16. package/src/diagnostics.ts +21 -0
  17. package/src/draft.ts +350 -0
  18. package/src/error-projection.ts +51 -0
  19. package/src/errors.ts +335 -48
  20. package/src/execute.ts +1577 -0
  21. package/src/fire.ts +1169 -0
  22. package/src/glob.ts +81 -0
  23. package/src/index.ts +526 -35
  24. package/src/internal/fork-ctx.ts +69 -0
  25. package/src/layer-projection.ts +193 -0
  26. package/src/layer.ts +43 -6
  27. package/src/observe.ts +361 -0
  28. package/src/path-scope.ts +66 -0
  29. package/src/path-security.ts +1 -1
  30. package/src/permits.ts +12 -0
  31. package/src/redaction/patterns.ts +6 -3
  32. package/src/resilience.ts +11 -11
  33. package/src/resource-config.ts +792 -0
  34. package/src/resource.ts +194 -0
  35. package/src/result.ts +18 -0
  36. package/src/run.ts +76 -0
  37. package/src/schedule-runtime.ts +689 -0
  38. package/src/schedule.ts +326 -0
  39. package/src/serialization.ts +92 -55
  40. package/src/signal-diagnostics.ts +633 -0
  41. package/src/signal-ref.ts +87 -0
  42. package/src/signal.ts +104 -0
  43. package/src/store/accessor-protocol.ts +56 -0
  44. package/src/store/index.ts +4 -0
  45. package/src/structured-examples.ts +248 -0
  46. package/src/surface-derivation.ts +91 -0
  47. package/src/surface-filter.ts +101 -0
  48. package/src/surface-versioning.ts +42 -0
  49. package/src/topo.ts +769 -67
  50. package/src/tracing.ts +345 -0
  51. package/src/trail-id-glob.ts +15 -0
  52. package/src/trail.ts +1168 -30
  53. package/src/trails/derive-trail.ts +842 -0
  54. package/src/trails/index.ts +9 -0
  55. package/src/trails/ingest.ts +139 -0
  56. package/src/trails-db.ts +206 -0
  57. package/src/transport-error-map.ts +174 -0
  58. package/src/type-utils.ts +87 -0
  59. package/src/types.ts +254 -12
  60. package/src/validate-established-topo.ts +69 -0
  61. package/src/validate-topo.ts +414 -56
  62. package/src/validation.ts +152 -4
  63. package/src/version-marker.ts +716 -0
  64. package/src/version-resolution.ts +308 -0
  65. package/src/version-runtime.ts +120 -0
  66. package/src/webhook.ts +278 -0
  67. package/src/workspace.ts +162 -1
  68. package/src/zod-wrappers.ts +72 -0
  69. package/.turbo/turbo-build.log +0 -1
  70. package/.turbo/turbo-lint.log +0 -3
  71. package/.turbo/turbo-typecheck.log +0 -1
  72. package/dist/adapters.d.ts +0 -39
  73. package/dist/adapters.d.ts.map +0 -1
  74. package/dist/adapters.js +0 -2
  75. package/dist/adapters.js.map +0 -1
  76. package/dist/blob-ref.d.ts +0 -20
  77. package/dist/blob-ref.d.ts.map +0 -1
  78. package/dist/blob-ref.js +0 -22
  79. package/dist/blob-ref.js.map +0 -1
  80. package/dist/branded.d.ts +0 -36
  81. package/dist/branded.d.ts.map +0 -1
  82. package/dist/branded.js +0 -89
  83. package/dist/branded.js.map +0 -1
  84. package/dist/collections.d.ts +0 -31
  85. package/dist/collections.d.ts.map +0 -1
  86. package/dist/collections.js +0 -60
  87. package/dist/collections.js.map +0 -1
  88. package/dist/context.d.ts +0 -10
  89. package/dist/context.d.ts.map +0 -1
  90. package/dist/context.js +0 -15
  91. package/dist/context.js.map +0 -1
  92. package/dist/derive.d.ts +0 -33
  93. package/dist/derive.d.ts.map +0 -1
  94. package/dist/derive.js +0 -125
  95. package/dist/derive.js.map +0 -1
  96. package/dist/errors.d.ts +0 -83
  97. package/dist/errors.d.ts.map +0 -1
  98. package/dist/errors.js +0 -142
  99. package/dist/errors.js.map +0 -1
  100. package/dist/event.d.ts +0 -45
  101. package/dist/event.d.ts.map +0 -1
  102. package/dist/event.js +0 -17
  103. package/dist/event.js.map +0 -1
  104. package/dist/fetch.d.ts +0 -15
  105. package/dist/fetch.d.ts.map +0 -1
  106. package/dist/fetch.js +0 -102
  107. package/dist/fetch.js.map +0 -1
  108. package/dist/guards.d.ts +0 -17
  109. package/dist/guards.d.ts.map +0 -1
  110. package/dist/guards.js +0 -25
  111. package/dist/guards.js.map +0 -1
  112. package/dist/health.d.ts +0 -18
  113. package/dist/health.d.ts.map +0 -1
  114. package/dist/health.js +0 -5
  115. package/dist/health.js.map +0 -1
  116. package/dist/hike.d.ts +0 -36
  117. package/dist/hike.d.ts.map +0 -1
  118. package/dist/hike.js +0 -20
  119. package/dist/hike.js.map +0 -1
  120. package/dist/index.d.ts +0 -36
  121. package/dist/index.d.ts.map +0 -1
  122. package/dist/index.js +0 -40
  123. package/dist/index.js.map +0 -1
  124. package/dist/job.d.ts +0 -24
  125. package/dist/job.d.ts.map +0 -1
  126. package/dist/job.js +0 -17
  127. package/dist/job.js.map +0 -1
  128. package/dist/layer.d.ts +0 -17
  129. package/dist/layer.d.ts.map +0 -1
  130. package/dist/layer.js +0 -21
  131. package/dist/layer.js.map +0 -1
  132. package/dist/path-security.d.ts +0 -28
  133. package/dist/path-security.d.ts.map +0 -1
  134. package/dist/path-security.js +0 -63
  135. package/dist/path-security.js.map +0 -1
  136. package/dist/patterns/bulk.d.ts +0 -15
  137. package/dist/patterns/bulk.d.ts.map +0 -1
  138. package/dist/patterns/bulk.js +0 -14
  139. package/dist/patterns/bulk.js.map +0 -1
  140. package/dist/patterns/change.d.ts +0 -10
  141. package/dist/patterns/change.d.ts.map +0 -1
  142. package/dist/patterns/change.js +0 -10
  143. package/dist/patterns/change.js.map +0 -1
  144. package/dist/patterns/date-range.d.ts +0 -10
  145. package/dist/patterns/date-range.d.ts.map +0 -1
  146. package/dist/patterns/date-range.js +0 -10
  147. package/dist/patterns/date-range.js.map +0 -1
  148. package/dist/patterns/index.d.ts +0 -9
  149. package/dist/patterns/index.d.ts.map +0 -1
  150. package/dist/patterns/index.js +0 -9
  151. package/dist/patterns/index.js.map +0 -1
  152. package/dist/patterns/pagination.d.ts +0 -18
  153. package/dist/patterns/pagination.d.ts.map +0 -1
  154. package/dist/patterns/pagination.js +0 -18
  155. package/dist/patterns/pagination.js.map +0 -1
  156. package/dist/patterns/progress.d.ts +0 -11
  157. package/dist/patterns/progress.d.ts.map +0 -1
  158. package/dist/patterns/progress.js +0 -11
  159. package/dist/patterns/progress.js.map +0 -1
  160. package/dist/patterns/sorting.d.ts +0 -13
  161. package/dist/patterns/sorting.d.ts.map +0 -1
  162. package/dist/patterns/sorting.js +0 -10
  163. package/dist/patterns/sorting.js.map +0 -1
  164. package/dist/patterns/status.d.ts +0 -15
  165. package/dist/patterns/status.d.ts.map +0 -1
  166. package/dist/patterns/status.js +0 -9
  167. package/dist/patterns/status.js.map +0 -1
  168. package/dist/patterns/timestamps.d.ts +0 -10
  169. package/dist/patterns/timestamps.d.ts.map +0 -1
  170. package/dist/patterns/timestamps.js +0 -10
  171. package/dist/patterns/timestamps.js.map +0 -1
  172. package/dist/redaction/index.d.ts +0 -4
  173. package/dist/redaction/index.d.ts.map +0 -1
  174. package/dist/redaction/index.js +0 -3
  175. package/dist/redaction/index.js.map +0 -1
  176. package/dist/redaction/patterns.d.ts +0 -9
  177. package/dist/redaction/patterns.d.ts.map +0 -1
  178. package/dist/redaction/patterns.js +0 -39
  179. package/dist/redaction/patterns.js.map +0 -1
  180. package/dist/redaction/redactor.d.ts +0 -27
  181. package/dist/redaction/redactor.d.ts.map +0 -1
  182. package/dist/redaction/redactor.js +0 -89
  183. package/dist/redaction/redactor.js.map +0 -1
  184. package/dist/resilience.d.ts +0 -34
  185. package/dist/resilience.d.ts.map +0 -1
  186. package/dist/resilience.js +0 -164
  187. package/dist/resilience.js.map +0 -1
  188. package/dist/result.d.ts +0 -57
  189. package/dist/result.d.ts.map +0 -1
  190. package/dist/result.js +0 -156
  191. package/dist/result.js.map +0 -1
  192. package/dist/serialization.d.ts +0 -27
  193. package/dist/serialization.d.ts.map +0 -1
  194. package/dist/serialization.js +0 -153
  195. package/dist/serialization.js.map +0 -1
  196. package/dist/topo.d.ts +0 -18
  197. package/dist/topo.d.ts.map +0 -1
  198. package/dist/topo.js +0 -80
  199. package/dist/topo.js.map +0 -1
  200. package/dist/trail.d.ts +0 -83
  201. package/dist/trail.d.ts.map +0 -1
  202. package/dist/trail.js +0 -16
  203. package/dist/trail.js.map +0 -1
  204. package/dist/types.d.ts +0 -46
  205. package/dist/types.d.ts.map +0 -1
  206. package/dist/types.js +0 -2
  207. package/dist/types.js.map +0 -1
  208. package/dist/validate-topo.d.ts +0 -24
  209. package/dist/validate-topo.d.ts.map +0 -1
  210. package/dist/validate-topo.js +0 -156
  211. package/dist/validate-topo.js.map +0 -1
  212. package/dist/validation.d.ts +0 -27
  213. package/dist/validation.d.ts.map +0 -1
  214. package/dist/validation.js +0 -134
  215. package/dist/validation.js.map +0 -1
  216. package/dist/workspace.d.ts +0 -25
  217. package/dist/workspace.d.ts.map +0 -1
  218. package/dist/workspace.js +0 -57
  219. package/dist/workspace.js.map +0 -1
  220. package/src/__tests__/blob-ref.test.ts +0 -103
  221. package/src/__tests__/branded.test.ts +0 -148
  222. package/src/__tests__/collections.test.ts +0 -126
  223. package/src/__tests__/context.test.ts +0 -66
  224. package/src/__tests__/derive.test.ts +0 -203
  225. package/src/__tests__/errors.test.ts +0 -309
  226. package/src/__tests__/event.test.ts +0 -82
  227. package/src/__tests__/fetch.test.ts +0 -217
  228. package/src/__tests__/guards.test.ts +0 -102
  229. package/src/__tests__/hike.test.ts +0 -117
  230. package/src/__tests__/job.test.ts +0 -98
  231. package/src/__tests__/layer.test.ts +0 -224
  232. package/src/__tests__/path-security.test.ts +0 -114
  233. package/src/__tests__/patterns.test.ts +0 -273
  234. package/src/__tests__/redaction.test.ts +0 -244
  235. package/src/__tests__/resilience.test.ts +0 -246
  236. package/src/__tests__/result.test.ts +0 -155
  237. package/src/__tests__/serialization.test.ts +0 -401
  238. package/src/__tests__/topo.test.ts +0 -220
  239. package/src/__tests__/trail.test.ts +0 -179
  240. package/src/__tests__/validate-topo.test.ts +0 -280
  241. package/src/__tests__/validation.test.ts +0 -283
  242. package/src/__tests__/workspace.test.ts +0 -183
  243. package/src/adapters.ts +0 -68
  244. package/src/event.ts +0 -77
  245. package/src/health.ts +0 -23
  246. package/src/hike.ts +0 -77
  247. package/src/job.ts +0 -20
  248. package/tsconfig.json +0 -9
  249. package/tsconfig.tsbuildinfo +0 -1
package/src/signal.ts ADDED
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Signal — a named payload schema with optional provenance meta.
3
+ */
4
+
5
+ import type { z } from 'zod';
6
+
7
+ const formatExampleIssues = (issues: readonly z.core.$ZodIssue[]): string =>
8
+ issues
9
+ .map((issue) => {
10
+ const path = issue.path.length > 0 ? issue.path.join('.') : '<root>';
11
+ return `${path}: ${issue.message}`;
12
+ })
13
+ .join('; ');
14
+
15
+ const assertSignalExamples = <T>(
16
+ id: string,
17
+ payload: z.ZodType<T>,
18
+ examples: readonly T[]
19
+ ): void => {
20
+ for (const [index, example] of examples.entries()) {
21
+ const parsed = payload.safeParse(example);
22
+ if (!parsed.success) {
23
+ throw new TypeError(
24
+ `signal("${id}") example ${index} is invalid: ${formatExampleIssues(parsed.error.issues)}`
25
+ );
26
+ }
27
+ }
28
+ };
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // Spec (input to the factory)
32
+ // ---------------------------------------------------------------------------
33
+
34
+ export interface SignalSpec<T> {
35
+ readonly payload: z.ZodType<T>;
36
+ readonly description?: string | undefined;
37
+ /** Example payloads validated against the signal payload schema. */
38
+ readonly examples?: readonly T[] | undefined;
39
+ readonly meta?: Readonly<Record<string, unknown>> | undefined;
40
+ /** Trail IDs that produce this signal (e.g. the trails it originates from). */
41
+ readonly from?: readonly string[] | undefined;
42
+ /** Reserved for future signal-specific design; trail versioning is trail-only. */
43
+ readonly version?: never;
44
+ }
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // Shape (output of the factory)
48
+ // ---------------------------------------------------------------------------
49
+
50
+ export interface Signal<T> {
51
+ readonly id: string;
52
+ readonly kind: 'signal';
53
+ readonly payload: z.ZodType<T>;
54
+ readonly description?: string | undefined;
55
+ /** Example payloads validated against the signal payload schema. */
56
+ readonly examples?: readonly T[] | undefined;
57
+ readonly meta?: Readonly<Record<string, unknown>> | undefined;
58
+ /** Trail IDs that produce this signal (e.g. the trails it originates from). */
59
+ readonly from?: readonly string[] | undefined;
60
+ }
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Factory
64
+ // ---------------------------------------------------------------------------
65
+
66
+ /**
67
+ * Create a signal definition.
68
+ *
69
+ * A signal is a named payload schema describing something that happened.
70
+ * Returns a frozen object with `kind: "signal"` and all spec fields.
71
+ */
72
+ export function signal<T>(id: string, spec: SignalSpec<T>): Signal<T>;
73
+ export function signal<T>(
74
+ spec: SignalSpec<T> & { readonly id: string }
75
+ ): Signal<T>;
76
+ export function signal<T>(
77
+ idOrSpec: string | (SignalSpec<T> & { readonly id: string }),
78
+ maybeSpec?: SignalSpec<T>
79
+ ): Signal<T> {
80
+ const resolvedId = typeof idOrSpec === 'string' ? idOrSpec : idOrSpec.id;
81
+ // oxlint-disable-next-line no-non-null-assertion -- overload guarantees maybeSpec when idOrSpec is string
82
+ const resolvedSpec = typeof idOrSpec === 'string' ? maybeSpec! : idOrSpec;
83
+ if (resolvedSpec.examples !== undefined) {
84
+ assertSignalExamples(
85
+ resolvedId,
86
+ resolvedSpec.payload,
87
+ resolvedSpec.examples
88
+ );
89
+ }
90
+ return Object.freeze({
91
+ description: resolvedSpec.description,
92
+ examples: resolvedSpec.examples
93
+ ? Object.freeze([...resolvedSpec.examples])
94
+ : undefined,
95
+ from: resolvedSpec.from ? Object.freeze([...resolvedSpec.from]) : undefined,
96
+ id: resolvedId,
97
+ kind: 'signal' as const,
98
+ meta: resolvedSpec.meta,
99
+ payload: resolvedSpec.payload,
100
+ });
101
+ }
102
+
103
+ /** Existential type for heterogeneous signal collections */
104
+ export type AnySignal = Signal<unknown>;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Structural accessor protocol used by `deriveTrail()` to synthesize default
3
+ * blazes for standard CRUD operations without depending on `@ontrails/store`.
4
+ *
5
+ * @remarks
6
+ * This type is intentionally minimal and structural. `@ontrails/store`'s
7
+ * `StoreAccessor` / `StoreTableAccessor` interfaces satisfy this protocol
8
+ * through a compile-time extends check (see `packages/store/src/types.ts`).
9
+ * Keeping the protocol in core avoids a core → store dependency while still
10
+ * allowing the derivation helper to call accessors by convention.
11
+ *
12
+ * Required methods (`get`, `list`, `upsert`, `remove`) match the
13
+ * backend-agnostic write contract every bound store must expose. Optional
14
+ * methods (`insert`, `update`) are declared by tabular adapters that
15
+ * distinguish create-only and patch-only operations from the generalized
16
+ * `upsert` contract.
17
+ */
18
+ export interface StoreAccessorProtocol<
19
+ TInput,
20
+ TEntity,
21
+ TId,
22
+ TFilters = unknown,
23
+ > {
24
+ /** Retrieve a single entity by identity. Returns `null` when not found. */
25
+ get(id: TId): Promise<TEntity | null>;
26
+ /** List entities, optionally filtered. Returns `[]` when no rows match. */
27
+ list(filters?: TFilters): Promise<readonly TEntity[]>;
28
+ /** Create-or-replace one entity using the backend-agnostic contract. */
29
+ upsert(input: TInput): Promise<TEntity>;
30
+ /**
31
+ * Remove an entity by identity. Returns `{ deleted: true }` when the row
32
+ * was found and removed, `{ deleted: false }` when no matching row
33
+ * existed (not an error).
34
+ */
35
+ remove(id: TId): Promise<{ readonly deleted: boolean }>;
36
+ /**
37
+ * Optional insert — available on tabular adapters that distinguish
38
+ * create from update. When absent, synthesized blazes fall back to
39
+ * `upsert`.
40
+ */
41
+ insert?(input: TInput): Promise<TEntity>;
42
+ /**
43
+ * Optional patch-by-identity — available on tabular adapters. Returns
44
+ * `null` when no row with the given identity exists. When absent,
45
+ * synthesized update blazes fall back to `get` + merge + `upsert`.
46
+ */
47
+ update?(id: TId, patch: Partial<TInput>): Promise<TEntity | null>;
48
+ }
49
+
50
+ /**
51
+ * Record shape returned by a resource's `from(ctx)` call, keyed by accessor
52
+ * name. Used by `deriveTrail()` to resolve an accessor by contour name.
53
+ */
54
+ export type StoreAccessorRecord = Readonly<
55
+ Record<string, StoreAccessorProtocol<unknown, unknown, unknown, unknown>>
56
+ >;
@@ -0,0 +1,4 @@
1
+ export type {
2
+ StoreAccessorProtocol,
3
+ StoreAccessorRecord,
4
+ } from './accessor-protocol.js';
@@ -0,0 +1,248 @@
1
+ import type { TrailExample, TrailExampleSignalAssertion } from './trail.js';
2
+
3
+ export interface StructuredTrailExampleProvenance {
4
+ readonly source: 'trail.examples' | 'trail.versions.examples';
5
+ }
6
+
7
+ export interface StructuredSignalExampleProvenance {
8
+ readonly source: 'signal.examples';
9
+ }
10
+
11
+ export type StructuredTrailExampleKind = 'success' | 'error';
12
+
13
+ export interface StructuredTrailExample {
14
+ readonly description?: string | undefined;
15
+ readonly error?: string | undefined;
16
+ readonly expected?: unknown | undefined;
17
+ readonly expectedMatch?: unknown | undefined;
18
+ readonly input: unknown;
19
+ readonly kind: StructuredTrailExampleKind;
20
+ readonly name: string;
21
+ readonly provenance: StructuredTrailExampleProvenance;
22
+ readonly signals?:
23
+ | readonly StructuredTrailExampleSignalAssertion[]
24
+ | undefined;
25
+ }
26
+
27
+ export interface StructuredTrailExampleSignalAssertion {
28
+ readonly payload?: unknown | undefined;
29
+ readonly payloadMatch?: unknown | undefined;
30
+ readonly signalId: string;
31
+ readonly times?: number | undefined;
32
+ }
33
+
34
+ export interface StructuredSignalExample {
35
+ readonly kind: 'payload';
36
+ readonly payload: unknown;
37
+ readonly provenance: StructuredSignalExampleProvenance;
38
+ }
39
+
40
+ // `Date`, `RegExp`, `Map`, and `Set` are objects (`typeof === 'object'`),
41
+ // so they would pass the structural walk and reach `JSON.stringify`, which
42
+ // silently coerces them: a `Date` becomes its ISO string, a `RegExp` and
43
+ // any `Map`/`Set` become `{}`. Either way the projected shape diverges
44
+ // from the example author's declared input. Treat them as non-serializable
45
+ // leaves so the example is dropped rather than misrepresented to MCP
46
+ // clients.
47
+ const isNonJsonLeaf = (value: unknown): boolean => {
48
+ const kind = typeof value;
49
+ if (kind === 'function' || kind === 'symbol' || kind === 'bigint') {
50
+ return true;
51
+ }
52
+ return (
53
+ value instanceof Date ||
54
+ value instanceof RegExp ||
55
+ value instanceof Map ||
56
+ value instanceof Set
57
+ );
58
+ };
59
+
60
+ // `JSON.stringify` silently drops function / symbol property values rather than
61
+ // throwing, so we walk the value first and reject any example whose graph
62
+ // contains a non-serializable leaf. Without this, an MCP client consuming
63
+ // `ontrails/examples` would receive structurally incorrect inputs.
64
+ const containsNonSerializableLeaf = (
65
+ value: unknown,
66
+ seen: WeakSet<object>
67
+ ): boolean => {
68
+ if (isNonJsonLeaf(value)) {
69
+ return true;
70
+ }
71
+ if (value === null || typeof value !== 'object') {
72
+ return false;
73
+ }
74
+ const obj = value as object;
75
+ if (seen.has(obj)) {
76
+ return false;
77
+ }
78
+ seen.add(obj);
79
+ if (Array.isArray(value)) {
80
+ return value.some((entry) => containsNonSerializableLeaf(entry, seen));
81
+ }
82
+ return Object.values(obj).some((entry) =>
83
+ containsNonSerializableLeaf(entry, seen)
84
+ );
85
+ };
86
+
87
+ const toJsonSerializable = (value: unknown): unknown | undefined => {
88
+ if (containsNonSerializableLeaf(value, new WeakSet<object>())) {
89
+ return undefined;
90
+ }
91
+ try {
92
+ const encoded = JSON.stringify(value);
93
+ return encoded === undefined ? undefined : JSON.parse(encoded);
94
+ } catch {
95
+ return undefined;
96
+ }
97
+ };
98
+
99
+ const signalIdFromAssertion = (
100
+ assertion: TrailExampleSignalAssertion
101
+ ): string | undefined => {
102
+ if (typeof assertion.signal === 'string') {
103
+ return assertion.signal;
104
+ }
105
+ return typeof assertion.signal.id === 'string'
106
+ ? assertion.signal.id
107
+ : undefined;
108
+ };
109
+
110
+ const projectSignalAssertion = (
111
+ assertion: TrailExampleSignalAssertion
112
+ ): StructuredTrailExampleSignalAssertion | undefined => {
113
+ const signalId = signalIdFromAssertion(assertion);
114
+ if (signalId === undefined) {
115
+ return undefined;
116
+ }
117
+
118
+ const projected: Record<string, unknown> = { signalId };
119
+ if (assertion.payload !== undefined) {
120
+ const payload = toJsonSerializable(assertion.payload);
121
+ if (payload === undefined) {
122
+ return undefined;
123
+ }
124
+ projected['payload'] = payload;
125
+ }
126
+ if (assertion.payloadMatch !== undefined) {
127
+ const payloadMatch = toJsonSerializable(assertion.payloadMatch);
128
+ if (payloadMatch === undefined) {
129
+ return undefined;
130
+ }
131
+ projected['payloadMatch'] = payloadMatch;
132
+ }
133
+ if (assertion.times !== undefined) {
134
+ projected['times'] = assertion.times;
135
+ }
136
+ return Object.freeze(
137
+ projected
138
+ ) as unknown as StructuredTrailExampleSignalAssertion;
139
+ };
140
+
141
+ const projectSignalAssertions = (
142
+ assertions: readonly TrailExampleSignalAssertion[] | undefined
143
+ ): readonly StructuredTrailExampleSignalAssertion[] | undefined => {
144
+ if (assertions === undefined) {
145
+ return undefined;
146
+ }
147
+ const projected = assertions.map(projectSignalAssertion);
148
+ if (projected.some((assertion) => assertion === undefined)) {
149
+ return undefined;
150
+ }
151
+ return Object.freeze(projected as StructuredTrailExampleSignalAssertion[]);
152
+ };
153
+
154
+ const projectExample = (
155
+ example: TrailExample<unknown, unknown>,
156
+ provenance: StructuredTrailExampleProvenance
157
+ ): StructuredTrailExample | undefined => {
158
+ const input = toJsonSerializable(example.input);
159
+ if (input === undefined) {
160
+ return undefined;
161
+ }
162
+
163
+ const projected: Record<string, unknown> = {
164
+ input,
165
+ kind: example.error === undefined ? 'success' : 'error',
166
+ name: example.name,
167
+ provenance,
168
+ };
169
+
170
+ if (example.description !== undefined) {
171
+ projected['description'] = example.description;
172
+ }
173
+ if (example.expected !== undefined) {
174
+ const expected = toJsonSerializable(example.expected);
175
+ if (expected === undefined) {
176
+ return undefined;
177
+ }
178
+ projected['expected'] = expected;
179
+ }
180
+ if (example.expectedMatch !== undefined) {
181
+ const expectedMatch = toJsonSerializable(example.expectedMatch);
182
+ if (expectedMatch === undefined) {
183
+ return undefined;
184
+ }
185
+ projected['expectedMatch'] = expectedMatch;
186
+ }
187
+ if (example.error !== undefined) {
188
+ projected['error'] = example.error;
189
+ }
190
+ if (example.signals !== undefined) {
191
+ const signals = projectSignalAssertions(example.signals);
192
+ if (signals === undefined) {
193
+ return undefined;
194
+ }
195
+ projected['signals'] = signals;
196
+ }
197
+
198
+ return Object.freeze(projected) as unknown as StructuredTrailExample;
199
+ };
200
+
201
+ const projectSignalExample = (
202
+ payload: unknown
203
+ ): StructuredSignalExample | undefined => {
204
+ const serializablePayload = toJsonSerializable(payload);
205
+ if (serializablePayload === undefined) {
206
+ return undefined;
207
+ }
208
+
209
+ return Object.freeze({
210
+ kind: 'payload',
211
+ payload: serializablePayload,
212
+ provenance: { source: 'signal.examples' },
213
+ } satisfies StructuredSignalExample);
214
+ };
215
+
216
+ export const deriveStructuredTrailExamples = (
217
+ examples: readonly TrailExample<unknown, unknown>[] | undefined,
218
+ options?: { readonly provenance?: StructuredTrailExampleProvenance }
219
+ ): readonly StructuredTrailExample[] | undefined => {
220
+ if (examples === undefined || examples.length === 0) {
221
+ return undefined;
222
+ }
223
+
224
+ const provenance = options?.provenance ?? { source: 'trail.examples' };
225
+ const projected = examples
226
+ .map((example) => projectExample(example, provenance))
227
+ .filter(
228
+ (example): example is StructuredTrailExample => example !== undefined
229
+ );
230
+
231
+ return projected.length > 0 ? Object.freeze(projected) : undefined;
232
+ };
233
+
234
+ export const deriveStructuredSignalExamples = (
235
+ examples: readonly unknown[] | undefined
236
+ ): readonly StructuredSignalExample[] | undefined => {
237
+ if (examples === undefined || examples.length === 0) {
238
+ return undefined;
239
+ }
240
+
241
+ const projected = examples
242
+ .map(projectSignalExample)
243
+ .filter(
244
+ (example): example is StructuredSignalExample => example !== undefined
245
+ );
246
+
247
+ return projected.length > 0 ? Object.freeze(projected) : undefined;
248
+ };
@@ -0,0 +1,91 @@
1
+ import { Result } from './result.js';
2
+ import type { Layer } from './layer.js';
3
+ import type { Intent } from './trail.js';
4
+ import type { Topo } from './topo.js';
5
+ import type { SurfaceName } from './transport-error-map.js';
6
+ import type { TrailContextInit } from './types.js';
7
+ import { SURFACE_KEY, SURFACE_LAYER_NAMES_KEY } from './types.js';
8
+ import { validateEstablishedTopo } from './validate-established-topo.js';
9
+
10
+ export type SurfaceConfigValues = Readonly<
11
+ Record<string, Record<string, unknown>>
12
+ >;
13
+
14
+ export interface SurfaceSelectionOptions {
15
+ /** Glob patterns that remove matching trail IDs. */
16
+ readonly exclude?: readonly string[] | undefined;
17
+ /** Glob patterns that keep only matching trail IDs when provided. */
18
+ readonly include?: readonly string[] | undefined;
19
+ /** Allowed intents for exposed surfaces. Empty arrays act as no filter. */
20
+ readonly intent?: readonly Intent[] | undefined;
21
+ }
22
+
23
+ export interface SurfaceValidationOptions {
24
+ /** Set to `false` to skip established-topo validation during projection. */
25
+ readonly validate?: boolean | undefined;
26
+ }
27
+
28
+ export interface BaseSurfaceOptions
29
+ extends SurfaceSelectionOptions, SurfaceValidationOptions {
30
+ /** Config values for resources that declare a `config` schema, keyed by resource ID. */
31
+ readonly configValues?: SurfaceConfigValues | undefined;
32
+ }
33
+
34
+ export const shouldValidateSurfaceTopo = (
35
+ options?: SurfaceValidationOptions
36
+ ): boolean => options?.validate !== false;
37
+
38
+ export const validateSurfaceTopo = (
39
+ graph: Topo,
40
+ options?: SurfaceValidationOptions
41
+ ): Result<void, Error> => {
42
+ if (!shouldValidateSurfaceTopo(options)) {
43
+ return Result.ok();
44
+ }
45
+
46
+ const validated = validateEstablishedTopo(graph);
47
+ return validated.isErr() ? Result.err(validated.error) : Result.ok();
48
+ };
49
+
50
+ export type SurfaceMarkedContext = Partial<TrailContextInit> & {
51
+ readonly extensions: Readonly<Record<string, unknown>>;
52
+ };
53
+
54
+ export const withSurfaceMarker = (
55
+ surface: SurfaceName,
56
+ ctx: Partial<TrailContextInit> = {}
57
+ ): SurfaceMarkedContext => ({
58
+ ...ctx,
59
+ extensions: {
60
+ ...ctx.extensions,
61
+ [SURFACE_KEY]: surface,
62
+ },
63
+ });
64
+
65
+ const readSurfaceLayerNameRecord = (
66
+ value: unknown
67
+ ): Record<string, readonly string[]> =>
68
+ value !== null && typeof value === 'object' && !Array.isArray(value)
69
+ ? (value as Record<string, readonly string[]>)
70
+ : {};
71
+
72
+ export const withSurfaceLayerNames = (
73
+ surface: SurfaceName,
74
+ layers: readonly Layer[],
75
+ ctx: Partial<TrailContextInit> = {}
76
+ ): SurfaceMarkedContext => {
77
+ const existing = readSurfaceLayerNameRecord(
78
+ ctx.extensions?.[SURFACE_LAYER_NAMES_KEY]
79
+ );
80
+ return {
81
+ ...ctx,
82
+ extensions: {
83
+ ...ctx.extensions,
84
+ [SURFACE_KEY]: surface,
85
+ [SURFACE_LAYER_NAMES_KEY]: {
86
+ ...existing,
87
+ [surface]: layers.map((layer) => layer.name),
88
+ },
89
+ },
90
+ };
91
+ };
@@ -0,0 +1,101 @@
1
+ import type { Intent, Trail } from './trail.js';
2
+ import { matchesAnyTrailIdGlob, matchesTrailIdGlob } from './trail-id-glob.js';
3
+ import type { SurfaceSelectionOptions } from './surface-derivation.js';
4
+
5
+ // ---------------------------------------------------------------------------
6
+ // Public types
7
+ // ---------------------------------------------------------------------------
8
+
9
+ export type SurfaceFilterOptions = SurfaceSelectionOptions;
10
+
11
+ export const matchesTrailPattern = (
12
+ trailId: string,
13
+ pattern: string
14
+ ): boolean => matchesTrailIdGlob(trailId, pattern);
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Surface filtering
18
+ // ---------------------------------------------------------------------------
19
+
20
+ const matchesAnyPattern = (
21
+ trailId: string,
22
+ patterns: readonly string[] | undefined
23
+ ): boolean => matchesAnyTrailIdGlob(trailId, patterns);
24
+
25
+ const isExplicitInternalInclude = (
26
+ trailId: string,
27
+ include: readonly string[] | undefined
28
+ ): boolean => include !== undefined && include.includes(trailId);
29
+
30
+ /**
31
+ * Resolve the effective visibility for a trail.
32
+ *
33
+ * Returns `'internal'` when either the explicit `visibility` field is
34
+ * `'internal'` or the legacy `meta.internal === true` convention is set.
35
+ * Honoring the legacy flag keeps trails authored before the visibility
36
+ * field was introduced (e.g. `meta: { internal: true }`) off surfaces.
37
+ *
38
+ * The runtime always fills in `visibility: 'public'` when the spec did not
39
+ * declare it, so we cannot distinguish explicit `'public'` from the default.
40
+ * This means a trail that sets both `meta.internal = true` and
41
+ * `visibility: 'public'` will still be treated as internal — that
42
+ * combination has never been a documented override and, if the author
43
+ * really means "public", they should remove the legacy flag.
44
+ */
45
+ const effectiveVisibility = (
46
+ trail: Trail<unknown, unknown, unknown>
47
+ ): 'public' | 'internal' => {
48
+ if (trail.visibility === 'internal') {
49
+ return 'internal';
50
+ }
51
+ return trail.meta?.['internal'] === true ? 'internal' : 'public';
52
+ };
53
+
54
+ const isVisibleToSurfaces = (
55
+ trail: Trail<unknown, unknown, unknown>,
56
+ include: readonly string[] | undefined
57
+ ): boolean =>
58
+ effectiveVisibility(trail) !== 'internal' ||
59
+ isExplicitInternalInclude(trail.id, include);
60
+
61
+ const passesIncludeFilter = (
62
+ trailId: string,
63
+ include: readonly string[] | undefined
64
+ ): boolean =>
65
+ include === undefined ||
66
+ include.length === 0 ||
67
+ matchesAnyPattern(trailId, include);
68
+
69
+ const passesIntentFilter = (
70
+ trail: Trail<unknown, unknown, unknown>,
71
+ intent: readonly Intent[] | undefined
72
+ ): boolean =>
73
+ intent === undefined || intent.length === 0 || intent.includes(trail.intent);
74
+
75
+ export const shouldIncludeTrailForSurface = (
76
+ trail: Trail<unknown, unknown, unknown>,
77
+ options: SurfaceFilterOptions = {}
78
+ ): boolean => {
79
+ if (trail.activationSources.length > 0) {
80
+ return false;
81
+ }
82
+
83
+ const { exclude, include, intent } = options;
84
+ if (!isVisibleToSurfaces(trail, include)) {
85
+ return false;
86
+ }
87
+
88
+ if (matchesAnyPattern(trail.id, exclude)) {
89
+ return false;
90
+ }
91
+
92
+ return (
93
+ passesIncludeFilter(trail.id, include) && passesIntentFilter(trail, intent)
94
+ );
95
+ };
96
+
97
+ export const filterSurfaceTrails = (
98
+ trails: readonly Trail<unknown, unknown, unknown>[],
99
+ options: SurfaceFilterOptions = {}
100
+ ): Trail<unknown, unknown, unknown>[] =>
101
+ trails.filter((trail) => shouldIncludeTrailForSurface(trail, options));
@@ -0,0 +1,42 @@
1
+ import type { AnyTrail, TrailVersionStatus } from './trail.js';
2
+ import {
3
+ deriveSupportedTrailVersions,
4
+ isDeprecatedTrailVersionEntry,
5
+ } from './trail.js';
6
+ import { deriveTrailVersionMarkers } from './version-marker.js';
7
+
8
+ export interface SurfaceTrailVersionProjection {
9
+ readonly current: boolean;
10
+ readonly deprecated: boolean;
11
+ readonly marker?: string | undefined;
12
+ readonly status?: TrailVersionStatus | undefined;
13
+ readonly version: number;
14
+ }
15
+
16
+ export const deriveSurfaceTrailVersionProjections = (
17
+ trail: AnyTrail
18
+ ): readonly SurfaceTrailVersionProjection[] | undefined => {
19
+ if (trail.version === undefined) {
20
+ return undefined;
21
+ }
22
+
23
+ const markers = new Map(
24
+ deriveTrailVersionMarkers(trail).map((record) => [
25
+ record.version,
26
+ record.marker,
27
+ ])
28
+ );
29
+
30
+ return deriveSupportedTrailVersions(trail).map((version) => {
31
+ const entry = trail.versions?.[version];
32
+ const marker = markers.get(version);
33
+ return {
34
+ current: version === trail.version,
35
+ deprecated:
36
+ entry === undefined ? false : isDeprecatedTrailVersionEntry(entry),
37
+ ...(marker === undefined ? {} : { marker }),
38
+ ...(entry?.status === undefined ? {} : { status: entry.status }),
39
+ version,
40
+ };
41
+ });
42
+ };