constructa-core 0.8.2 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -2
- package/dist/index.d.ts +48 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +97 -4
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -4,6 +4,32 @@ UI-agnostic generator registration and execution engine for Constructa.
|
|
|
4
4
|
|
|
5
5
|
This package contains the core runtime responsible for registering, composing, and executing generators. It defines the fundamental behavior of the Constructa generation system without making assumptions about user interfaces, persistence, transport, or application environments.
|
|
6
6
|
|
|
7
|
+
## Example
|
|
8
|
+
|
|
9
|
+
Register the generator implementations your application needs, then execute a
|
|
10
|
+
portable definition. A seed makes the result reproducible.
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import {
|
|
14
|
+
createExecutor,
|
|
15
|
+
createRegistry,
|
|
16
|
+
} from "jsr:@constructa/core";
|
|
17
|
+
import {
|
|
18
|
+
registerIntegerGenerator,
|
|
19
|
+
registerObjectGenerator,
|
|
20
|
+
} from "jsr:@constructa/generators";
|
|
21
|
+
|
|
22
|
+
const registry = createRegistry();
|
|
23
|
+
registerIntegerGenerator(registry);
|
|
24
|
+
registerObjectGenerator(registry);
|
|
25
|
+
|
|
26
|
+
const generate = createExecutor(registry);
|
|
27
|
+
const result = generate.generate(
|
|
28
|
+
{ type: "object", fields: { age: { type: "integer", min: 18, max: 65 } } },
|
|
29
|
+
{ seed: "example" },
|
|
30
|
+
);
|
|
31
|
+
```
|
|
32
|
+
|
|
7
33
|
## Responsibilities
|
|
8
34
|
|
|
9
35
|
Current APIs define trusted generator implementations, portable typed definitions, and engine-provided generation context services. Planned areas include:
|
|
@@ -23,7 +49,7 @@ Use `defineGenerator()` for developer-authored executable implementations. An im
|
|
|
23
49
|
|
|
24
50
|
## Runtime parsing
|
|
25
51
|
|
|
26
|
-
Use `parseDefinition(value, { registry, limits? })` for untrusted runtime definition data, or `parseDocument(value, { registry, limits? })` for a versioned document. Both validate portable JSON, registered generator IDs, each implementation's configuration, and nested typed definitions without invoking `generate`. `safeParseDefinition()` and `safeParseDocument()` return all bounded, deterministic structured issues; the throwing forms return the first issue. Definitions parsed from dynamic data intentionally have broad `GeneratorDefinition` output typing.
|
|
52
|
+
Use `parseDefinition(value, { registry, limits? })` for untrusted runtime definition data, or `parseDocument(value, { registry, limits? })` for a versioned document. Both validate portable JSON, registered generator IDs, each implementation's configuration, and nested typed definitions without invoking `generate`. `safeParseDefinition()` and `safeParseDocument()` return all bounded, deterministic structured issues; the throwing forms return the first issue. `limits` bounds byte size, recursion, nodes, object fields, array length, template source length, template references, and reported issues. Definitions parsed from dynamic data intentionally have broad `GeneratorDefinition` output typing.
|
|
27
53
|
|
|
28
54
|
`parseTemplateTokens(source, { path? })` parses the MVP `{field}` and `{sibling.nested}` reference syntax into literal and reference tokens without resolving a value. Use `{{` and `}}` for literal braces. Empty paths, whitespace, braces inside a reference, and empty dot segments fail with `INVALID_TEMPLATE_TOKEN` at the supplied definition path.
|
|
29
55
|
|
|
@@ -39,7 +65,11 @@ Use `parseDefinition(value, { registry, limits? })` for untrusted runtime defini
|
|
|
39
65
|
|
|
40
66
|
## Single-value execution
|
|
41
67
|
|
|
42
|
-
`createExecutor(registry)` is advanced infrastructure for executing one root definition. It snapshots the supplied registry, parses untrusted definitions, runs dependency analysis, and dispatches the resolved implementation. Its `generate(definition, options?)` method returns the definition's inferred output type. Supply either `{ seed }` for a fresh reproducible source or `{ random }` for a caller-owned injected source; supplying both is invalid. Definitions returned by `parseDefinition()` are recognized by the executor and are not validated again, while ordinary definitions are parsed once before dispatch. `maxDepth` bounds recursive child execution (default: 64). Bulk output is intentionally not part of this boundary.
|
|
68
|
+
`createExecutor(registry)` is advanced infrastructure for executing one root definition. It snapshots the supplied registry, parses untrusted definitions, runs dependency analysis, and dispatches the resolved implementation. Its `generate(definition, options?)` method returns the definition's inferred output type. Supply either `{ seed }` for a fresh reproducible source or `{ random }` for a caller-owned injected source; supplying both is invalid. Definitions returned by `parseDefinition()` are recognized by the executor and are not validated again, while ordinary definitions are parsed once before dispatch. `maxDepth` bounds recursive child execution (default: 64); `signal` and an absolute UTC `deadline` stop execution before a subsequent dispatch. Bulk output is intentionally not part of this boundary.
|
|
69
|
+
|
|
70
|
+
## Performance baseline
|
|
71
|
+
|
|
72
|
+
Run `pnpm benchmark:core -- --iterations=10000` after building workspace packages to emit a JSON report for seeded primitive, composite, and reference execution. Reports include elapsed time and heap delta for comparison; they are measurements, not pass/fail thresholds.
|
|
43
73
|
|
|
44
74
|
## Dependency Boundary
|
|
45
75
|
|
package/dist/index.d.ts
CHANGED
|
@@ -9,8 +9,11 @@ type RandomSource = {
|
|
|
9
9
|
integer(maxExclusive: number): number;
|
|
10
10
|
bytes(length: number): Uint8Array;
|
|
11
11
|
};
|
|
12
|
+
/** An application-provided random source validated by `createRandomSource`. */
|
|
12
13
|
type RandomSourceAdapter = RandomSource;
|
|
14
|
+
/** A deterministic random-source seed. */
|
|
13
15
|
type Seed = number | string;
|
|
16
|
+
/** Per-root-execution limits and random-source options. */
|
|
14
17
|
type ExecutionOptions = {
|
|
15
18
|
/** Uses a fresh deterministic source for this root execution. */
|
|
16
19
|
readonly seed?: Seed;
|
|
@@ -21,16 +24,25 @@ type ExecutionOptions = {
|
|
|
21
24
|
readonly random?: RandomSource;
|
|
22
25
|
/** Maximum child-definition nesting below the root. Defaults to 64. */
|
|
23
26
|
readonly maxDepth?: number;
|
|
27
|
+
/** Stops execution before the next generator dispatch when aborted. */
|
|
28
|
+
readonly signal?: AbortSignal;
|
|
29
|
+
/** Stops execution before the next generator dispatch after this UTC epoch time. */
|
|
30
|
+
readonly deadline?: number;
|
|
24
31
|
};
|
|
32
|
+
/** Executes validated generator definitions through a registry snapshot. */
|
|
25
33
|
type Executor = {
|
|
26
34
|
generate: <Definition extends GeneratorDefinition$1>(definition: Definition, options?: ExecutionOptions) => import("constructa-schema").Infer<Definition>;
|
|
27
35
|
};
|
|
36
|
+
/** The deterministic random algorithm used by `createSeededRandom`. */
|
|
28
37
|
declare const SEEDED_RANDOM_ALGORITHM = "mulberry32";
|
|
38
|
+
/** The compatibility version of the seeded random algorithm. */
|
|
29
39
|
declare const SEEDED_RANDOM_ALGORITHM_VERSION = 1;
|
|
40
|
+
/** Public metadata identifying the seeded random algorithm. */
|
|
30
41
|
type SeededRandomMetadata = {
|
|
31
42
|
readonly algorithm: typeof SEEDED_RANDOM_ALGORITHM;
|
|
32
43
|
readonly version: typeof SEEDED_RANDOM_ALGORITHM_VERSION;
|
|
33
44
|
};
|
|
45
|
+
/** Values that must remain compatible to reproduce an execution. */
|
|
34
46
|
type DeterminismCompatibility = {
|
|
35
47
|
readonly engineVersion: string;
|
|
36
48
|
readonly generatorImplementationVersion: number;
|
|
@@ -56,6 +68,7 @@ declare function createSeededRandom(seed: Seed): RandomSource;
|
|
|
56
68
|
/** Metadata for reproducibility diagnostics. It intentionally contains no seed. */
|
|
57
69
|
declare function getSeededRandomMetadata(): SeededRandomMetadata;
|
|
58
70
|
/** Services supplied by the engine. Implementations must not use global randomness. */
|
|
71
|
+
/** Capabilities supplied to a trusted generator implementation. */
|
|
59
72
|
type GenerationContext = {
|
|
60
73
|
readonly random: RandomSource;
|
|
61
74
|
/** The definition path currently being generated. */
|
|
@@ -73,8 +86,10 @@ type GenerationContext = {
|
|
|
73
86
|
readonly analyzeChildValueDependencies: (definition: GeneratorDefinition$1, pathSegment: ValidationPathSegment$1) => readonly ValueDependency[];
|
|
74
87
|
};
|
|
75
88
|
/** A property path relative to the object containing a reference. */
|
|
89
|
+
/** A property path used by an object-local template reference. */
|
|
76
90
|
type ReferencePath = readonly string[];
|
|
77
91
|
/** A parsed template fragment. Braces are escaped with `{{` and `}}`. */
|
|
92
|
+
/** One literal or reference segment of parsed template source. */
|
|
78
93
|
type TemplateToken = {
|
|
79
94
|
readonly type: "literal";
|
|
80
95
|
readonly value: string;
|
|
@@ -82,6 +97,7 @@ type TemplateToken = {
|
|
|
82
97
|
readonly type: "reference";
|
|
83
98
|
readonly path: ReferencePath;
|
|
84
99
|
};
|
|
100
|
+
/** Options controlling template-token parse diagnostics. */
|
|
85
101
|
type ParseTemplateTokensOptions = {
|
|
86
102
|
/** Definition-relative path reported for malformed template syntax. */
|
|
87
103
|
readonly path?: ValidationPath$1;
|
|
@@ -97,30 +113,41 @@ declare function parseTemplateTokens(source: string, options?: ParseTemplateToke
|
|
|
97
113
|
/** Parses one dot-separated object-local reference path. */
|
|
98
114
|
declare function parseReferencePath(source: string, path?: ValidationPath$1): ReferencePath;
|
|
99
115
|
/** A portable value dependency declared by a generator definition. */
|
|
116
|
+
/** One value dependency declared by a child generator. */
|
|
100
117
|
type ValueDependency = {
|
|
101
118
|
readonly path: ReferencePath;
|
|
102
119
|
};
|
|
103
120
|
/** Dependencies for a direct field in a composite definition. */
|
|
121
|
+
/** A composite child and the values it depends on. */
|
|
104
122
|
type CompositeDependencyNode = {
|
|
105
123
|
readonly fieldPath: readonly [string];
|
|
106
124
|
readonly dependencies: readonly ValueDependency[];
|
|
107
125
|
};
|
|
108
126
|
/** Portable dependency data used to schedule one composite object. */
|
|
127
|
+
/** An immutable analysis of composite-child dependencies. */
|
|
109
128
|
type CompositeDependencyAnalysis = {
|
|
110
129
|
readonly nodes: readonly CompositeDependencyNode[];
|
|
111
130
|
};
|
|
131
|
+
/** Options used to order dependent composite children. */
|
|
112
132
|
type CompositeDependencySchedulingOptions = {
|
|
113
133
|
/** Every reference path that exists in the containing object definition. */
|
|
114
134
|
readonly referencePaths?: readonly ReferencePath[];
|
|
135
|
+
/** Maximum fields participating in one object-local reference graph. */
|
|
136
|
+
readonly maxNodes?: number;
|
|
137
|
+
/** Maximum unique field dependencies in one object-local reference graph. */
|
|
138
|
+
readonly maxEdges?: number;
|
|
115
139
|
};
|
|
116
140
|
/** The read-only capability supplied to generators that resolve references. */
|
|
141
|
+
/** Resolves values visible to an executing generator. */
|
|
117
142
|
type ReferenceResolver = {
|
|
118
143
|
resolve: (path: ReferencePath) => unknown;
|
|
119
144
|
};
|
|
120
145
|
/** Executes and records completed fields within one isolated object scope. */
|
|
146
|
+
/** An isolated object-field execution scope. */
|
|
121
147
|
type ObjectGenerationScope = {
|
|
122
148
|
executeChild: <Output>(definition: GeneratorDefinition$1<Output>, pathSegment: string) => Output;
|
|
123
149
|
};
|
|
150
|
+
/** Inputs used to create a generator execution context. */
|
|
124
151
|
type GenerationContextOptions = {
|
|
125
152
|
readonly random: RandomSource;
|
|
126
153
|
readonly path?: ValidationPath$1;
|
|
@@ -142,16 +169,30 @@ declare function createCompositeDependencyAnalysis(nodes: readonly CompositeDepe
|
|
|
142
169
|
* dependency path may target a nested value below another direct field.
|
|
143
170
|
*/
|
|
144
171
|
declare function scheduleCompositeDependencies(analysis: CompositeDependencyAnalysis, options?: CompositeDependencySchedulingOptions): readonly string[];
|
|
172
|
+
/** Bounds applied while parsing untrusted definitions or documents. */
|
|
145
173
|
type ParseLimits = {
|
|
146
174
|
readonly maxDepth?: number;
|
|
147
175
|
readonly maxIssues?: number;
|
|
148
176
|
readonly maxNodes?: number;
|
|
177
|
+
/** Maximum UTF-8 encoded definition bytes. */
|
|
178
|
+
readonly maxBytes?: number;
|
|
179
|
+
/** Maximum properties in any input object record. */
|
|
180
|
+
readonly maxObjectFields?: number;
|
|
181
|
+
/** Maximum items in any input array. */
|
|
182
|
+
readonly maxArrayLength?: number;
|
|
183
|
+
/** Maximum template source length. */
|
|
184
|
+
readonly maxTemplateLength?: number;
|
|
185
|
+
/** Maximum parsed template references. */
|
|
186
|
+
readonly maxTemplateTokens?: number;
|
|
149
187
|
};
|
|
188
|
+
/** Options for parsing a portable generator definition. */
|
|
150
189
|
type ParseDefinitionOptions = {
|
|
151
190
|
readonly registry: Pick<GeneratorRegistry | GeneratorRegistrySnapshot, "lookup">;
|
|
152
191
|
readonly limits?: ParseLimits;
|
|
153
192
|
};
|
|
193
|
+
/** Options for parsing a versioned generator document. */
|
|
154
194
|
type ParseDocumentOptions = ParseDefinitionOptions;
|
|
195
|
+
/** The success-or-failure result returned by `safeParseDefinition`. */
|
|
155
196
|
type DefinitionParseResult = {
|
|
156
197
|
readonly success: true;
|
|
157
198
|
readonly value: ParsedGeneratorDefinition;
|
|
@@ -159,6 +200,7 @@ type DefinitionParseResult = {
|
|
|
159
200
|
readonly success: false;
|
|
160
201
|
readonly issues: readonly ConstructaError[];
|
|
161
202
|
};
|
|
203
|
+
/** The success-or-failure result returned by `safeParseDocument`. */
|
|
162
204
|
type DocumentParseResult = {
|
|
163
205
|
readonly success: true;
|
|
164
206
|
readonly value: import("constructa-schema").GeneratorDocumentV1;
|
|
@@ -172,15 +214,18 @@ declare function safeParseDefinition(value: unknown, options: ParseDefinitionOpt
|
|
|
172
214
|
/** Parses a versioned document and its root definition through the same pipeline. */
|
|
173
215
|
declare function parseDocument(value: unknown, options: ParseDocumentOptions): import("constructa-schema").GeneratorDocumentV1;
|
|
174
216
|
declare function safeParseDocument(value: unknown, options: ParseDocumentOptions): DocumentParseResult;
|
|
217
|
+
/** A generator type and version required by an implementation. */
|
|
175
218
|
type GeneratorDependency = {
|
|
176
219
|
readonly typeId: string;
|
|
177
220
|
readonly path: ValidationPath$1;
|
|
178
221
|
};
|
|
179
222
|
declare const parsedGeneratorDefinition: unique symbol;
|
|
180
223
|
/** A runtime-validated definition accepted by an executor without revalidation. */
|
|
224
|
+
/** A generator definition already validated against a registry. */
|
|
181
225
|
type ParsedGeneratorDefinition = GeneratorDefinition$1 & {
|
|
182
226
|
readonly [parsedGeneratorDefinition]: true;
|
|
183
227
|
};
|
|
228
|
+
/** A trusted implementation of one portable generator type. */
|
|
184
229
|
type GeneratorImplementation<Definition extends GeneratorDefinition$1<Output>, Output> = {
|
|
185
230
|
readonly type: string;
|
|
186
231
|
readonly version: number;
|
|
@@ -193,14 +238,17 @@ type GeneratorImplementation<Definition extends GeneratorDefinition$1<Output>, O
|
|
|
193
238
|
readonly context: GenerationContext;
|
|
194
239
|
}) => Output;
|
|
195
240
|
};
|
|
241
|
+
/** A registry entry for one generator type. */
|
|
196
242
|
type RegisteredGenerator = {
|
|
197
243
|
readonly type: string;
|
|
198
244
|
readonly version: number;
|
|
199
245
|
};
|
|
246
|
+
/** An immutable point-in-time view of a generator registry. */
|
|
200
247
|
type GeneratorRegistrySnapshot = {
|
|
201
248
|
readonly generators: readonly RegisteredGenerator[];
|
|
202
249
|
readonly lookup: (type: string, path?: ValidationPath$1) => GeneratorImplementation<GeneratorDefinition$1, unknown>;
|
|
203
250
|
};
|
|
251
|
+
/** A mutable registry of trusted generator implementations. */
|
|
204
252
|
type GeneratorRegistry = {
|
|
205
253
|
register: <Definition extends GeneratorDefinition$1<Output>, Output>(implementation: GeneratorImplementation<Definition, Output>) => void;
|
|
206
254
|
replace: <Definition extends GeneratorDefinition$1<Output>, Output>(implementation: GeneratorImplementation<Definition, Output>) => void;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;KAyBY;EACV;EACA,QAAQ;EACR,MAAM,iBAAiB
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;KAyBY;EACV;EACA,QAAQ;EACR,MAAM,iBAAiB;;;KAIb,sBAAsB;;KAKtB;;KAGA;;WAED,OAAO;;;;;WAKP,SAAS;;WAET;;WAEA,SAAS;;WAET;;;KAIC;EACV,WAAW,mBAAmB,uBAC5B,YAAY,YACZ,UAAU,iDACqB,MAAM;;;cAI5B;;cAEA;;KAGD;WACD,kBAAkB;WAClB,gBAAgB;;;KAIf;WACD;WACA;WACA,QAAQ;WACR,YAAY;WACZ,MAAM;WACN;;;;;;iBAYK,mBAAmB,SAAS,sBAAsB;;iBA4ClD,6BAA6B;;;;;iBAwC7B,cAAc,MAAM;;iBAcpB,mBAAmB,MAAM,OAAO;;iBAuChC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aACZ,SAAS;QACd;;;KAII;WACD;WACA;;;KAIC;WACD,qBAAqB;WACrB,SACP,cACA,OAAO,qBACJ,wBAAwB;;;KAInB;EACV,WAAW,mBAAmB,sBAAoB,SAAS,QACzD,gBAAgB,wBAAwB,YAAY;EAEtD,UAAU,mBAAmB,sBAAoB,SAAS,QACxD,gBAAgB,wBAAwB,YAAY;EAEtD,SACE,cACA,OAAO,qBACJ,wBAAwB;EAC7B,gBAAgB;;;iBAUF,kBAAkB;;;;;iBAoDlB,eACd,UAAU,oBAAoB,4BAC7B;;;;;iBA4ca,sBACR,mBAAmB,sBAAoB,SAC7C,QAEA,gBAAgB,wBAAwB,YAAY,UACnD,wBAAwB,YAAY;;iBAMvB,0BACd,cACM,mBAAmB,sBAAoB,SAC7C,YAAY,aAAa;;;;;;iBAUX,8BACd,mBAAmB,sBAAoB,SACvC,QAEA,gBAAgB,wBAAwB,YAAY,SACpD;WACW,YAAY;WACZ,SAAS;WACT,OAAO;IAEjB"}
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { ConstructaError, assertGeneratorDefinition, normalizeConstructaError, parseDocument as parseDocument$1, validateDocument, validateGeneratorDefinition } from "constructa-schema";
|
|
2
2
|
//#region src/index.ts
|
|
3
3
|
const validatedRandomSources = /* @__PURE__ */ new WeakSet();
|
|
4
|
+
/** The deterministic random algorithm used by `createSeededRandom`. */
|
|
4
5
|
const SEEDED_RANDOM_ALGORITHM = "mulberry32";
|
|
6
|
+
/** The compatibility version of the seeded random algorithm. */
|
|
5
7
|
const SEEDED_RANDOM_ALGORITHM_VERSION = 1;
|
|
6
8
|
const SEEDED_RANDOM_METADATA = Object.freeze({
|
|
7
9
|
algorithm: SEEDED_RANDOM_ALGORITHM,
|
|
@@ -248,10 +250,20 @@ function createCompositeDependencyAnalysis(nodes) {
|
|
|
248
250
|
*/
|
|
249
251
|
function scheduleCompositeDependencies(analysis, options = {}) {
|
|
250
252
|
const nodes = analysis.nodes;
|
|
253
|
+
const maxNodes = options.maxNodes ?? 1e4;
|
|
254
|
+
const maxEdges = options.maxEdges ?? 1e5;
|
|
255
|
+
if (!Number.isSafeInteger(maxNodes) || maxNodes < 1 || !Number.isSafeInteger(maxEdges) || maxEdges < 1) throw contextError("INVALID_COMPOSITE_DEPENDENCIES", [], "Composite graph limits must be positive safe integers.");
|
|
256
|
+
if (nodes.length > maxNodes) throw new ConstructaError({
|
|
257
|
+
kind: "configuration",
|
|
258
|
+
code: "REFERENCE_GRAPH_NODE_LIMIT",
|
|
259
|
+
path: [],
|
|
260
|
+
message: "Object reference graph exceeds the configured maximum field count."
|
|
261
|
+
});
|
|
251
262
|
const byName = new Map(nodes.map((node) => [node.fieldPath[0], node]));
|
|
252
263
|
const referencePaths = new Set((options.referencePaths ?? nodes.map((node) => node.fieldPath)).map(referencePathKey));
|
|
253
264
|
const remaining = /* @__PURE__ */ new Map();
|
|
254
265
|
const dependents = /* @__PURE__ */ new Map();
|
|
266
|
+
let edgeCount = 0;
|
|
255
267
|
for (const node of nodes) {
|
|
256
268
|
const dependencies = /* @__PURE__ */ new Set();
|
|
257
269
|
for (const dependency of node.dependencies) {
|
|
@@ -263,7 +275,16 @@ function scheduleCompositeDependencies(analysis, options = {}) {
|
|
|
263
275
|
message: "The referenced object value could not be found.",
|
|
264
276
|
details: { referencePath: [...dependency.path] }
|
|
265
277
|
});
|
|
266
|
-
dependencies.
|
|
278
|
+
if (!dependencies.has(target)) {
|
|
279
|
+
dependencies.add(target);
|
|
280
|
+
edgeCount += 1;
|
|
281
|
+
}
|
|
282
|
+
if (edgeCount > maxEdges) throw new ConstructaError({
|
|
283
|
+
kind: "configuration",
|
|
284
|
+
code: "REFERENCE_GRAPH_EDGE_LIMIT",
|
|
285
|
+
path: [...node.fieldPath],
|
|
286
|
+
message: "Object reference graph exceeds the configured maximum dependency count."
|
|
287
|
+
});
|
|
267
288
|
const targets = dependents.get(target) ?? [];
|
|
268
289
|
if (!targets.includes(node.fieldPath[0])) targets.push(node.fieldPath[0]);
|
|
269
290
|
dependents.set(target, targets);
|
|
@@ -407,6 +428,7 @@ function createExecutor(registry) {
|
|
|
407
428
|
} });
|
|
408
429
|
}
|
|
409
430
|
function executeParsedDefinition(definition, path, depth, state, references = unavailableReferenceResolver(path)) {
|
|
431
|
+
assertExecutionActive(state, path);
|
|
410
432
|
const implementation = state.snapshot.lookup(definition.type, path);
|
|
411
433
|
analyzeGeneratorDependencies(implementation, definition, state.snapshot, path);
|
|
412
434
|
return invokeValidatedGeneratorImplementation(implementation, definition, createGenerationContext({
|
|
@@ -502,11 +524,29 @@ function resolveExecutionOptions(options) {
|
|
|
502
524
|
if (options.seed !== void 0 && options.random !== void 0) throw contextError("CONFLICTING_RANDOM_OPTIONS", ["seed"], "seed and random cannot be supplied together.");
|
|
503
525
|
const maxDepth = options.maxDepth ?? 64;
|
|
504
526
|
if (!Number.isSafeInteger(maxDepth) || maxDepth < 0) throw contextError("INVALID_EXECUTION_OPTIONS", ["maxDepth"], "maxDepth must be a non-negative safe integer.");
|
|
527
|
+
if (options.signal !== void 0 && typeof options.signal !== "object") throw contextError("INVALID_EXECUTION_OPTIONS", ["signal"], "signal must be an AbortSignal when supplied.");
|
|
528
|
+
if (options.deadline !== void 0 && (!Number.isFinite(options.deadline) || options.deadline < 0)) throw contextError("INVALID_EXECUTION_OPTIONS", ["deadline"], "deadline must be a non-negative finite UTC epoch time.");
|
|
505
529
|
return {
|
|
506
530
|
random: options.seed !== void 0 ? createSeededRandom(options.seed) : options.random !== void 0 ? createRandomSource(options.random) : createDefaultRandomSource(),
|
|
507
|
-
maxDepth
|
|
531
|
+
maxDepth,
|
|
532
|
+
signal: options.signal,
|
|
533
|
+
deadline: options.deadline
|
|
508
534
|
};
|
|
509
535
|
}
|
|
536
|
+
function assertExecutionActive(state, path) {
|
|
537
|
+
if (state.signal?.aborted) throw new ConstructaError({
|
|
538
|
+
kind: "execution",
|
|
539
|
+
code: "EXECUTION_ABORTED",
|
|
540
|
+
path,
|
|
541
|
+
message: "Generator execution was aborted."
|
|
542
|
+
});
|
|
543
|
+
if (state.deadline !== void 0 && Date.now() >= state.deadline) throw new ConstructaError({
|
|
544
|
+
kind: "execution",
|
|
545
|
+
code: "EXECUTION_DEADLINE_EXCEEDED",
|
|
546
|
+
path,
|
|
547
|
+
message: "Generator execution exceeded its deadline."
|
|
548
|
+
});
|
|
549
|
+
}
|
|
510
550
|
function analyzeGeneratorDependencies(implementation, definition, registry, path) {
|
|
511
551
|
if (implementation.analyzeDependencies === void 0) return;
|
|
512
552
|
let dependencies;
|
|
@@ -659,7 +699,12 @@ function invokeGeneratorImplementation(implementation, input) {
|
|
|
659
699
|
const DEFAULT_PARSE_LIMITS = Object.freeze({
|
|
660
700
|
maxDepth: 64,
|
|
661
701
|
maxIssues: 100,
|
|
662
|
-
maxNodes: 1e4
|
|
702
|
+
maxNodes: 1e4,
|
|
703
|
+
maxBytes: 1e6,
|
|
704
|
+
maxObjectFields: 1e4,
|
|
705
|
+
maxArrayLength: 1e4,
|
|
706
|
+
maxTemplateLength: 1e5,
|
|
707
|
+
maxTemplateTokens: 1e4
|
|
663
708
|
});
|
|
664
709
|
function parseRuntimeDefinition(value, path, options) {
|
|
665
710
|
const limits = resolveParseLimits(options);
|
|
@@ -668,6 +713,11 @@ function parseRuntimeDefinition(value, path, options) {
|
|
|
668
713
|
success: false,
|
|
669
714
|
issues: schemaIssues
|
|
670
715
|
};
|
|
716
|
+
const limitIssue = findInputLimitIssue(value, path, limits);
|
|
717
|
+
if (limitIssue !== void 0) return {
|
|
718
|
+
success: false,
|
|
719
|
+
issues: [limitIssue]
|
|
720
|
+
};
|
|
671
721
|
const issues = [];
|
|
672
722
|
const visited = /* @__PURE__ */ new Set();
|
|
673
723
|
visitRuntimeDefinition(value, path, 0, options.registry, limits, visited, issues);
|
|
@@ -758,11 +808,54 @@ function resolveParseLimits(options) {
|
|
|
758
808
|
const resolved = {
|
|
759
809
|
maxDepth: supplied.maxDepth ?? DEFAULT_PARSE_LIMITS.maxDepth,
|
|
760
810
|
maxIssues: supplied.maxIssues ?? DEFAULT_PARSE_LIMITS.maxIssues,
|
|
761
|
-
maxNodes: supplied.maxNodes ?? DEFAULT_PARSE_LIMITS.maxNodes
|
|
811
|
+
maxNodes: supplied.maxNodes ?? DEFAULT_PARSE_LIMITS.maxNodes,
|
|
812
|
+
maxBytes: supplied.maxBytes ?? DEFAULT_PARSE_LIMITS.maxBytes,
|
|
813
|
+
maxObjectFields: supplied.maxObjectFields ?? DEFAULT_PARSE_LIMITS.maxObjectFields,
|
|
814
|
+
maxArrayLength: supplied.maxArrayLength ?? DEFAULT_PARSE_LIMITS.maxArrayLength,
|
|
815
|
+
maxTemplateLength: supplied.maxTemplateLength ?? DEFAULT_PARSE_LIMITS.maxTemplateLength,
|
|
816
|
+
maxTemplateTokens: supplied.maxTemplateTokens ?? DEFAULT_PARSE_LIMITS.maxTemplateTokens
|
|
762
817
|
};
|
|
763
818
|
for (const [name, value] of Object.entries(resolved)) if (!Number.isSafeInteger(value) || value < 1) throw contextError("INVALID_PARSE_LIMITS", ["limits", name], `${name} must be a positive safe integer.`);
|
|
764
819
|
return resolved;
|
|
765
820
|
}
|
|
821
|
+
function findInputLimitIssue(value, path, limits) {
|
|
822
|
+
if (new TextEncoder().encode(JSON.stringify(value)).length > limits.maxBytes) return inputLimitError("PARSE_BYTE_LIMIT", path, "Definition exceeds the maximum serialized byte size.");
|
|
823
|
+
const visit = (candidate, candidatePath) => {
|
|
824
|
+
if (Array.isArray(candidate)) {
|
|
825
|
+
if (candidate.length > limits.maxArrayLength) return inputLimitError("PARSE_ARRAY_LIMIT", candidatePath, "Definition contains an array exceeding the configured maximum length.");
|
|
826
|
+
for (let index = 0; index < candidate.length; index += 1) {
|
|
827
|
+
const issue = visit(candidate[index], [...candidatePath, index]);
|
|
828
|
+
if (issue !== void 0) return issue;
|
|
829
|
+
}
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
if (typeof candidate !== "object" || candidate === null) return void 0;
|
|
833
|
+
const record = candidate;
|
|
834
|
+
const keys = Object.keys(record);
|
|
835
|
+
if (keys.length > limits.maxObjectFields) return inputLimitError("PARSE_OBJECT_FIELD_LIMIT", candidatePath, "Definition contains an object exceeding the configured maximum field count.");
|
|
836
|
+
if (record.type === "template" && typeof record.source === "string") {
|
|
837
|
+
if (record.source.length > limits.maxTemplateLength) return inputLimitError("PARSE_TEMPLATE_LENGTH_LIMIT", [...candidatePath, "source"], "Template source exceeds the configured maximum length.");
|
|
838
|
+
let tokenCount = 0;
|
|
839
|
+
try {
|
|
840
|
+
tokenCount = parseTemplateTokens(record.source).filter((token) => token.type === "reference").length;
|
|
841
|
+
} catch (_cause) {}
|
|
842
|
+
if (tokenCount > limits.maxTemplateTokens) return inputLimitError("PARSE_TEMPLATE_TOKEN_LIMIT", [...candidatePath, "source"], "Template source exceeds the configured maximum reference count.");
|
|
843
|
+
}
|
|
844
|
+
for (const key of keys) {
|
|
845
|
+
const issue = visit(record[key], [...candidatePath, key]);
|
|
846
|
+
if (issue !== void 0) return issue;
|
|
847
|
+
}
|
|
848
|
+
};
|
|
849
|
+
return visit(value, path);
|
|
850
|
+
}
|
|
851
|
+
function inputLimitError(code, path, message) {
|
|
852
|
+
return new ConstructaError({
|
|
853
|
+
kind: "configuration",
|
|
854
|
+
code,
|
|
855
|
+
path,
|
|
856
|
+
message
|
|
857
|
+
});
|
|
858
|
+
}
|
|
766
859
|
function validateDefinitionSafely(value, path) {
|
|
767
860
|
try {
|
|
768
861
|
return validateGeneratorDefinition(value, path);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["parseSchemaDocument"],"sources":["../src/index.ts"],"sourcesContent":["import {\n assertGeneratorDefinition,\n ConstructaError,\n type GeneratorDefinition,\n normalizeConstructaError,\n parseDocument as parseSchemaDocument,\n type ValidationIssue,\n type ValidationPath,\n type ValidationPathSegment,\n validateDocument,\n validateGeneratorDefinition,\n} from \"constructa-schema\";\n\nexport type {\n GeneratorDefinition,\n Infer,\n ValidationIssue,\n ValidationPath,\n ValidationPathSegment,\n} from \"constructa-schema\";\n\n/**\n * Random values are always half-open: `float()` returns [0, 1), while\n * `integer(maxExclusive)` returns an integer in [0, maxExclusive).\n */\nexport type RandomSource = {\n float(): number;\n integer(maxExclusive: number): number;\n bytes(length: number): Uint8Array;\n};\n\nexport type RandomSourceAdapter = RandomSource;\n\nconst validatedRandomSources = new WeakSet<object>();\n\nexport type Seed = number | string;\n\nexport type ExecutionOptions = {\n /** Uses a fresh deterministic source for this root execution. */\n readonly seed?: Seed;\n /**\n * A caller-owned source consumed by this execution. The executor does not\n * reset, clone, or otherwise retain it after the call returns.\n */\n readonly random?: RandomSource;\n /** Maximum child-definition nesting below the root. Defaults to 64. */\n readonly maxDepth?: number;\n};\n\nexport type Executor = {\n generate: <Definition extends GeneratorDefinition>(\n definition: Definition,\n options?: ExecutionOptions,\n ) => import(\"constructa-schema\").Infer<Definition>;\n};\n\nexport const SEEDED_RANDOM_ALGORITHM = \"mulberry32\";\nexport const SEEDED_RANDOM_ALGORITHM_VERSION = 1;\n\nexport type SeededRandomMetadata = {\n readonly algorithm: typeof SEEDED_RANDOM_ALGORITHM;\n readonly version: typeof SEEDED_RANDOM_ALGORITHM_VERSION;\n};\n\nexport type DeterminismCompatibility = {\n readonly engineVersion: string;\n readonly generatorImplementationVersion: number;\n readonly random: SeededRandomMetadata;\n readonly definition: GeneratorDefinition;\n readonly seed: Seed;\n readonly executionMode: string;\n};\n\nconst SEEDED_RANDOM_METADATA: SeededRandomMetadata = Object.freeze({\n algorithm: SEEDED_RANDOM_ALGORITHM,\n version: SEEDED_RANDOM_ALGORITHM_VERSION,\n});\n\n/**\n * Validates an injected source and guards every produced value. No fallback\n * randomness is used when an adapter violates its contract.\n */\nexport function createRandomSource(adapter: RandomSourceAdapter): RandomSource {\n assertRandomSourceAdapter(adapter);\n\n const source = Object.freeze({\n float() {\n const value = adapter.float();\n if (\n typeof value !== \"number\" ||\n !Number.isFinite(value) ||\n value < 0 ||\n value >= 1\n ) {\n throw invalidRandomSource(\n \"float() must return a finite number in [0, 1).\",\n );\n }\n return value;\n },\n integer(maxExclusive: number) {\n assertRandomLength(maxExclusive, \"maxExclusive\");\n const value = adapter.integer(maxExclusive);\n if (!Number.isSafeInteger(value) || value < 0 || value >= maxExclusive) {\n throw invalidRandomSource(\n \"integer(maxExclusive) must return a safe integer in [0, maxExclusive).\",\n );\n }\n return value;\n },\n bytes(length: number) {\n assertByteLength(length);\n const value = adapter.bytes(length);\n if (!(value instanceof Uint8Array) || value.length !== length) {\n throw invalidRandomSource(\n \"bytes(length) must return a Uint8Array with exactly length bytes.\",\n );\n }\n return value;\n },\n });\n validatedRandomSources.add(source);\n return source;\n}\n\n/** Creates the default platform-backed random source. It makes no security claim. */\nexport function createDefaultRandomSource(): RandomSource {\n const crypto = globalThis.crypto;\n if (crypto?.getRandomValues === undefined) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"SYSTEM_RANDOM_UNAVAILABLE\",\n path: [],\n message: \"Platform cryptographic random values are unavailable.\",\n });\n }\n\n const randomBytes = (length: number) => {\n const bytes = new Uint8Array(length);\n for (let offset = 0; offset < length; offset += 65_536) {\n crypto.getRandomValues(bytes.subarray(offset, offset + 65_536));\n }\n return bytes;\n };\n const uint32 = () => new DataView(randomBytes(4).buffer).getUint32(0);\n const uint53 = () => (uint32() & 0x1f_ffff) * 2 ** 32 + uint32();\n\n return createRandomSource({\n float() {\n return uint53() / 2 ** 53;\n },\n integer(maxExclusive: number) {\n const range = 2 ** 53;\n const upperLimit = range - (range % maxExclusive);\n let value = uint53();\n while (value >= upperLimit) value = uint53();\n return value % maxExclusive;\n },\n bytes: randomBytes,\n });\n}\n\n/**\n * Returns a canonical seed representation. Strings use UTF-8 exactly; finite\n * numbers use their JavaScript numeric representation, with -0 normalized to 0.\n */\nexport function normalizeSeed(seed: Seed): string {\n if (typeof seed === \"string\") return `string:${seed}`;\n if (typeof seed === \"number\" && Number.isFinite(seed)) {\n return `number:${Object.is(seed, -0) ? \"0\" : String(seed)}`;\n }\n throw new ConstructaError({\n kind: \"configuration\",\n code: \"INVALID_SEED\",\n path: [\"seed\"],\n message: \"seed must be a string or finite number.\",\n });\n}\n\n/** Creates an isolated deterministic random source for the current algorithm version. */\nexport function createSeededRandom(seed: Seed): RandomSource {\n let state = hashSeed(normalizeSeed(seed));\n const uint32 = () => {\n state = (state + 0x6d2b_79f5) >>> 0;\n let value = state;\n value = Math.imul(value ^ (value >>> 15), value | 1);\n value ^= value + Math.imul(value ^ (value >>> 7), value | 61);\n return (value ^ (value >>> 14)) >>> 0;\n };\n const uint53 = () => (uint32() & 0x1f_ffff) * 2 ** 32 + uint32();\n\n return createRandomSource({\n float() {\n return uint53() / 2 ** 53;\n },\n integer(maxExclusive: number) {\n const range = 2 ** 53;\n const upperLimit = range - (range % maxExclusive);\n let value = uint53();\n while (value >= upperLimit) value = uint53();\n return value % maxExclusive;\n },\n bytes(length: number) {\n const bytes = new Uint8Array(length);\n for (let index = 0; index < length; index += 1) {\n if (index % 4 === 0) {\n const value = uint32();\n bytes[index] = value & 0xff;\n if (index + 1 < length) bytes[index + 1] = (value >>> 8) & 0xff;\n if (index + 2 < length) bytes[index + 2] = (value >>> 16) & 0xff;\n if (index + 3 < length) bytes[index + 3] = value >>> 24;\n }\n }\n return bytes;\n },\n });\n}\n\n/** Metadata for reproducibility diagnostics. It intentionally contains no seed. */\nexport function getSeededRandomMetadata(): SeededRandomMetadata {\n return SEEDED_RANDOM_METADATA;\n}\n\n/** Services supplied by the engine. Implementations must not use global randomness. */\nexport type GenerationContext = {\n readonly random: RandomSource;\n /** The definition path currently being generated. */\n readonly path: ValidationPath;\n /** Delegates a typed child definition to the engine. */\n readonly executeChild: <Output>(\n definition: GeneratorDefinition<Output>,\n pathSegment: ValidationPathSegment,\n ) => Output;\n /**\n * Read-only values from the object currently being generated. Values are\n * available only after their field has completed.\n */\n readonly references: ReferenceResolver;\n /** Creates an isolated scope for the fields of one composite object. */\n readonly createObjectScope: () => ObjectGenerationScope;\n /** Returns value dependencies declared by one direct child definition. */\n readonly analyzeChildValueDependencies: (\n definition: GeneratorDefinition,\n pathSegment: ValidationPathSegment,\n ) => readonly ValueDependency[];\n};\n\n/** A property path relative to the object containing a reference. */\nexport type ReferencePath = readonly string[];\n\n/** A parsed template fragment. Braces are escaped with `{{` and `}}`. */\nexport type TemplateToken =\n | { readonly type: \"literal\"; readonly value: string }\n | { readonly type: \"reference\"; readonly path: ReferencePath };\n\nexport type ParseTemplateTokensOptions = {\n /** Definition-relative path reported for malformed template syntax. */\n readonly path?: ValidationPath;\n};\n\n/**\n * Parses MVP template syntax without executing or resolving references.\n *\n * `{field}` addresses a sibling and `{field.nested}` addresses a value below\n * that sibling. `{{` and `}}` emit literal braces. Whitespace, empty path\n * segments, and expression characters inside a reference are unsupported.\n */\nexport function parseTemplateTokens(\n source: string,\n options: ParseTemplateTokensOptions = {},\n): readonly TemplateToken[] {\n const path = options.path ?? [];\n if (typeof source !== \"string\") {\n throw templateTokenError(path, \"Template source must be a string.\");\n }\n assertContextPath(path);\n\n const tokens: TemplateToken[] = [];\n let literal = \"\";\n const appendLiteral = (value: string) => {\n literal += value;\n };\n const flushLiteral = () => {\n if (literal.length === 0) return;\n tokens.push(Object.freeze({ type: \"literal\", value: literal }));\n literal = \"\";\n };\n\n for (let index = 0; index < source.length; index += 1) {\n const character = source[index];\n if (character === \"{\") {\n if (source[index + 1] === \"{\") {\n appendLiteral(\"{\");\n index += 1;\n continue;\n }\n const closingIndex = source.indexOf(\"}\", index + 1);\n if (closingIndex === -1) {\n throw templateTokenError(\n path,\n \"Template reference is missing a closing brace.\",\n );\n }\n const reference = source.slice(index + 1, closingIndex);\n const referencePath = parseReferencePath(reference, path);\n flushLiteral();\n tokens.push(Object.freeze({ type: \"reference\", path: referencePath }));\n index = closingIndex;\n continue;\n }\n if (character === \"}\") {\n if (source[index + 1] === \"}\") {\n appendLiteral(\"}\");\n index += 1;\n continue;\n }\n throw templateTokenError(\n path,\n \"Template contains an unmatched closing brace.\",\n );\n }\n appendLiteral(character ?? \"\");\n }\n flushLiteral();\n return Object.freeze(tokens);\n}\n\n/** Parses one dot-separated object-local reference path. */\nexport function parseReferencePath(\n source: string,\n path: ValidationPath = [],\n): ReferencePath {\n if (typeof source !== \"string\" || source.length === 0) {\n throw templateTokenError(path, \"Template reference must not be empty.\");\n }\n assertContextPath(path);\n const segments = source.split(\".\");\n if (\n segments.some(\n (segment) => segment.length === 0 || !/^[\\p{L}\\p{N}_$-]+$/u.test(segment),\n )\n ) {\n throw templateTokenError(\n path,\n \"Template reference segments must use letters, numbers, underscores, dollar signs, or hyphens.\",\n );\n }\n return Object.freeze(segments);\n}\n\nfunction templateTokenError(\n path: ValidationPath,\n message: string,\n): ConstructaError {\n return new ConstructaError({\n kind: \"configuration\",\n code: \"INVALID_TEMPLATE_TOKEN\",\n path,\n message,\n });\n}\n\n/** A portable value dependency declared by a generator definition. */\nexport type ValueDependency = {\n readonly path: ReferencePath;\n};\n\n/** Dependencies for a direct field in a composite definition. */\nexport type CompositeDependencyNode = {\n readonly fieldPath: readonly [string];\n readonly dependencies: readonly ValueDependency[];\n};\n\n/** Portable dependency data used to schedule one composite object. */\nexport type CompositeDependencyAnalysis = {\n readonly nodes: readonly CompositeDependencyNode[];\n};\n\nexport type CompositeDependencySchedulingOptions = {\n /** Every reference path that exists in the containing object definition. */\n readonly referencePaths?: readonly ReferencePath[];\n};\n\n/** The read-only capability supplied to generators that resolve references. */\nexport type ReferenceResolver = {\n resolve: (path: ReferencePath) => unknown;\n};\n\n/** Executes and records completed fields within one isolated object scope. */\nexport type ObjectGenerationScope = {\n executeChild: <Output>(\n definition: GeneratorDefinition<Output>,\n pathSegment: string,\n ) => Output;\n};\n\nexport type GenerationContextOptions = {\n readonly random: RandomSource;\n readonly path?: ValidationPath;\n readonly executeChild?: GenerationContext[\"executeChild\"];\n readonly references?: ReferenceResolver;\n readonly createObjectScope?: GenerationContext[\"createObjectScope\"];\n readonly analyzeChildValueDependencies?: GenerationContext[\"analyzeChildValueDependencies\"];\n};\n\n/**\n * Creates the engine-owned capability view supplied to implementations.\n * Application code normally receives this through `generate`, rather than\n * constructing one directly.\n */\nexport function createGenerationContext(\n options: GenerationContextOptions,\n): GenerationContext {\n if (typeof options !== \"object\" || options === null) {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"Context options must be an object.\",\n );\n }\n assertContextPath(options.path ?? []);\n if (\n typeof options.executeChild !== \"undefined\" &&\n typeof options.executeChild !== \"function\"\n ) {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"executeChild must be a function when present.\",\n );\n }\n\n // This validates the Phase 012 source contract without drawing from it.\n const random = validatedRandomSources.has(options.random)\n ? options.random\n : createRandomSource(options.random);\n const path = Object.freeze([...(options.path ?? [])]);\n const executeChild =\n options.executeChild ??\n ((definition, pathSegment) => {\n assertGeneratorDefinition(definition, [...path, pathSegment]);\n assertContextPathSegment(pathSegment);\n throw new ConstructaError({\n kind: \"execution\",\n code: \"CHILD_EXECUTION_UNAVAILABLE\",\n path: [...path, pathSegment],\n message: \"Child execution is not available in this generation context.\",\n });\n });\n\n const references = options.references ?? unavailableReferenceResolver(path);\n if (\n typeof references !== \"object\" ||\n references === null ||\n typeof references.resolve !== \"function\"\n ) {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"references must provide a resolve function when present.\",\n );\n }\n const createObjectScope =\n options.createObjectScope ??\n (() =>\n Object.freeze({\n executeChild<Output>(\n definition: GeneratorDefinition<Output>,\n pathSegment: string,\n ): Output {\n return executeChild(definition, pathSegment);\n },\n }));\n if (typeof createObjectScope !== \"function\") {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"createObjectScope must be a function when present.\",\n );\n }\n const analyzeChildValueDependencies =\n options.analyzeChildValueDependencies ?? (() => []);\n if (typeof analyzeChildValueDependencies !== \"function\") {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"analyzeChildValueDependencies must be a function when present.\",\n );\n }\n\n return Object.freeze({\n random,\n path,\n executeChild,\n references: Object.freeze({ resolve: references.resolve }),\n createObjectScope,\n analyzeChildValueDependencies,\n });\n}\n\n/** Freezes direct-field dependency declarations into portable analysis data. */\nexport function createCompositeDependencyAnalysis(\n nodes: readonly CompositeDependencyNode[],\n): CompositeDependencyAnalysis {\n if (!Array.isArray(nodes)) {\n throw contextError(\n \"INVALID_COMPOSITE_DEPENDENCIES\",\n [],\n \"Composite dependency nodes must be an array.\",\n );\n }\n const names = new Set<string>();\n const normalized = nodes.map((node, index) => {\n if (!isCompositeDependencyNode(node) || names.has(node.fieldPath[0])) {\n throw contextError(\n \"INVALID_COMPOSITE_DEPENDENCIES\",\n [\"nodes\", index],\n \"Each composite dependency node must name one unique field.\",\n );\n }\n names.add(node.fieldPath[0]);\n return Object.freeze({\n fieldPath: Object.freeze([...node.fieldPath]) as readonly [string],\n dependencies: Object.freeze(\n node.dependencies.map((dependency) =>\n Object.freeze({ path: Object.freeze([...dependency.path]) }),\n ),\n ),\n });\n });\n return Object.freeze({ nodes: Object.freeze(normalized) });\n}\n\n/**\n * Returns a deterministic execution order for direct object fields. A\n * dependency path may target a nested value below another direct field.\n */\nexport function scheduleCompositeDependencies(\n analysis: CompositeDependencyAnalysis,\n options: CompositeDependencySchedulingOptions = {},\n): readonly string[] {\n const nodes = analysis.nodes;\n const byName = new Map(nodes.map((node) => [node.fieldPath[0], node]));\n const referencePaths = new Set(\n (options.referencePaths ?? nodes.map((node) => node.fieldPath)).map(\n referencePathKey,\n ),\n );\n const remaining = new Map<string, Set<string>>();\n const dependents = new Map<string, string[]>();\n\n for (const node of nodes) {\n const dependencies = new Set<string>();\n for (const dependency of node.dependencies) {\n const target = dependency.path[0];\n if (\n target === undefined ||\n !byName.has(target) ||\n !referencePaths.has(referencePathKey(dependency.path))\n ) {\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"REFERENCE_NOT_FOUND\",\n path: [...node.fieldPath],\n message: \"The referenced object value could not be found.\",\n details: { referencePath: [...dependency.path] },\n });\n }\n dependencies.add(target);\n const targets = dependents.get(target) ?? [];\n if (!targets.includes(node.fieldPath[0])) targets.push(node.fieldPath[0]);\n dependents.set(target, targets);\n }\n remaining.set(node.fieldPath[0], dependencies);\n }\n\n const ready = nodes\n .filter((node) => (remaining.get(node.fieldPath[0])?.size ?? 0) === 0)\n .map((node) => node.fieldPath[0])\n .sort();\n const ordered: string[] = [];\n while (ready.length > 0) {\n const field = ready.shift();\n if (field === undefined) continue;\n ordered.push(field);\n for (const dependent of (dependents.get(field) ?? []).sort()) {\n const dependencies = remaining.get(dependent);\n dependencies?.delete(field);\n if (dependencies?.size === 0) {\n ready.push(dependent);\n ready.sort();\n }\n }\n }\n if (ordered.length !== nodes.length) {\n const cycle = findCompositeDependencyCycle(remaining);\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"CIRCULAR_REFERENCE\",\n path: cycle.slice(0, 1),\n message: `Circular object value reference detected: ${cycle.join(\" -> \")}.`,\n details: { fields: cycle },\n });\n }\n return Object.freeze(ordered);\n}\n\nfunction findCompositeDependencyCycle(\n remaining: ReadonlyMap<string, ReadonlySet<string>>,\n): string[] {\n const visited = new Set<string>();\n const active = new Set<string>();\n const stack: string[] = [];\n const visit = (field: string): string[] | undefined => {\n visited.add(field);\n active.add(field);\n stack.push(field);\n for (const dependency of [...(remaining.get(field) ?? [])].sort()) {\n if (!remaining.has(dependency)) continue;\n if (active.has(dependency)) {\n const start = stack.indexOf(dependency);\n return [...stack.slice(start), dependency];\n }\n if (!visited.has(dependency)) {\n const cycle = visit(dependency);\n if (cycle !== undefined) return cycle;\n }\n }\n active.delete(field);\n stack.pop();\n return undefined;\n };\n\n for (const field of [...remaining.keys()].sort()) {\n if (visited.has(field)) continue;\n const cycle = visit(field);\n if (cycle !== undefined) return cycle;\n }\n return [];\n}\n\nexport type ParseLimits = {\n readonly maxDepth?: number;\n readonly maxIssues?: number;\n readonly maxNodes?: number;\n};\n\nexport type ParseDefinitionOptions = {\n readonly registry: Pick<\n GeneratorRegistry | GeneratorRegistrySnapshot,\n \"lookup\"\n >;\n readonly limits?: ParseLimits;\n};\n\nexport type ParseDocumentOptions = ParseDefinitionOptions;\n\nexport type DefinitionParseResult =\n | { readonly success: true; readonly value: ParsedGeneratorDefinition }\n | { readonly success: false; readonly issues: readonly ConstructaError[] };\n\nexport type DocumentParseResult =\n | {\n readonly success: true;\n readonly value: import(\"constructa-schema\").GeneratorDocumentV1;\n }\n | { readonly success: false; readonly issues: readonly ConstructaError[] };\n\n/** Parses untrusted runtime definition data without executing generator code. */\nexport function parseDefinition(\n value: unknown,\n options: ParseDefinitionOptions,\n): ParsedGeneratorDefinition {\n return parseDefinitionAtPath(value, [], options.registry, options.limits);\n}\n\nfunction parseDefinitionAtPath(\n value: unknown,\n path: ValidationPath,\n registry: ParseDefinitionOptions[\"registry\"],\n limits?: ParseLimits,\n): ParsedGeneratorDefinition {\n const result = parseRuntimeDefinition(value, path, { registry, limits });\n if (result.success) return result.value;\n throw result.issues[0];\n}\n\nexport function safeParseDefinition(\n value: unknown,\n options: ParseDefinitionOptions,\n): DefinitionParseResult {\n return parseRuntimeDefinition(value, [], options);\n}\n\n/** Parses a versioned document and its root definition through the same pipeline. */\nexport function parseDocument(\n value: unknown,\n options: ParseDocumentOptions,\n): import(\"constructa-schema\").GeneratorDocumentV1 {\n const result = safeParseDocument(value, options);\n if (result.success) return result.value;\n throw result.issues[0];\n}\n\nexport function safeParseDocument(\n value: unknown,\n options: ParseDocumentOptions,\n): DocumentParseResult {\n const limits = resolveParseLimits(options);\n const documentIssues = validationIssuesToErrors(\n validateDocumentSafely(value),\n [],\n limits.maxIssues,\n );\n if (documentIssues.length > 0)\n return { success: false, issues: documentIssues };\n\n // Schema parsing is now safe because validation has rejected hostile shapes.\n const document = parseSchemaDocument(value);\n const definition = parseRuntimeDefinition(\n document.definition,\n [\"definition\"],\n options,\n );\n return definition.success\n ? { success: true, value: document }\n : { success: false, issues: definition.issues };\n}\n\nexport type GeneratorDependency = {\n readonly typeId: string;\n readonly path: ValidationPath;\n};\n\ndeclare const parsedGeneratorDefinition: unique symbol;\n\n/** A runtime-validated definition accepted by an executor without revalidation. */\nexport type ParsedGeneratorDefinition = GeneratorDefinition & {\n readonly [parsedGeneratorDefinition]: true;\n};\n\nconst parsedDefinitions = new WeakSet<object>();\n\nexport type GeneratorImplementation<\n Definition extends GeneratorDefinition<Output>,\n Output,\n> = {\n readonly type: string;\n readonly version: number;\n readonly validateDefinition: (\n definition: unknown,\n ) => readonly ValidationIssue[];\n readonly analyzeDependencies?: (\n definition: Definition,\n ) => readonly GeneratorDependency[];\n /** Declares object-local value references used by this definition. */\n readonly analyzeValueDependencies?: (\n definition: Definition,\n ) => readonly ValueDependency[];\n readonly generate: (input: {\n readonly definition: Definition;\n readonly context: GenerationContext;\n }) => Output;\n};\n\nexport type RegisteredGenerator = {\n readonly type: string;\n readonly version: number;\n};\n\nexport type GeneratorRegistrySnapshot = {\n readonly generators: readonly RegisteredGenerator[];\n readonly lookup: (\n type: string,\n path?: ValidationPath,\n ) => GeneratorImplementation<GeneratorDefinition, unknown>;\n};\n\nexport type GeneratorRegistry = {\n register: <Definition extends GeneratorDefinition<Output>, Output>(\n implementation: GeneratorImplementation<Definition, Output>,\n ) => void;\n replace: <Definition extends GeneratorDefinition<Output>, Output>(\n implementation: GeneratorImplementation<Definition, Output>,\n ) => void;\n lookup: (\n type: string,\n path?: ValidationPath,\n ) => GeneratorImplementation<GeneratorDefinition, unknown>;\n snapshot: () => GeneratorRegistrySnapshot;\n};\n\nconst RESERVED_GENERATOR_TYPE_IDS = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/** Creates advanced registry infrastructure. Normal factories do not require it. */\nexport function createRegistry(): GeneratorRegistry {\n const implementations = new Map<\n string,\n GeneratorImplementation<GeneratorDefinition, unknown>\n >();\n\n return {\n register(implementation) {\n assertRegistryImplementation(implementation);\n if (implementations.has(implementation.type)) {\n throw registryError(\n \"DUPLICATE_GENERATOR\",\n [\"type\"],\n `A generator with type \"${implementation.type}\" is already registered.`,\n );\n }\n implementations.set(\n implementation.type,\n freezeImplementation(\n implementation,\n ) as unknown as GeneratorImplementation<GeneratorDefinition, unknown>,\n );\n },\n replace(implementation) {\n assertRegistryImplementation(implementation);\n if (!implementations.has(implementation.type)) {\n throw registryError(\n \"UNKNOWN_GENERATOR\",\n [\"type\"],\n `No generator with type \"${implementation.type}\" is registered.`,\n );\n }\n implementations.set(\n implementation.type,\n freezeImplementation(\n implementation,\n ) as unknown as GeneratorImplementation<GeneratorDefinition, unknown>,\n );\n },\n lookup(type, path = []) {\n return lookupImplementation(implementations, type, path);\n },\n snapshot() {\n return createRegistrySnapshot(implementations);\n },\n };\n}\n\n/**\n * Creates an advanced single-value executor over an immutable registry\n * snapshot. Normal applications will receive this behavior through the SDK.\n */\nexport function createExecutor(\n registry: GeneratorRegistry | GeneratorRegistrySnapshot,\n): Executor {\n const snapshot = createExecutionSnapshot(registry);\n\n return Object.freeze({\n generate<Definition extends GeneratorDefinition>(\n definition: Definition,\n options?: ExecutionOptions,\n ): import(\"constructa-schema\").Infer<Definition> {\n const execution = resolveExecutionOptions(options);\n const parsed = parsedDefinitions.has(definition)\n ? definition\n : parseDefinition(definition, { registry: snapshot });\n return executeParsedDefinition(parsed, [], 0, {\n snapshot,\n ...execution,\n }) as import(\"constructa-schema\").Infer<Definition>;\n },\n });\n}\n\ntype ExecutionState = {\n readonly snapshot: GeneratorRegistrySnapshot;\n readonly random: RandomSource;\n readonly maxDepth: number;\n};\n\nfunction executeParsedDefinition(\n definition: GeneratorDefinition,\n path: ValidationPath,\n depth: number,\n state: ExecutionState,\n references: ReferenceResolver = unavailableReferenceResolver(path),\n): unknown {\n const implementation = state.snapshot.lookup(definition.type, path);\n analyzeGeneratorDependencies(\n implementation,\n definition,\n state.snapshot,\n path,\n );\n const context = createGenerationContext({\n random: state.random,\n path,\n references,\n createObjectScope() {\n return createObjectGenerationScope(\n path,\n (child, pathSegment, scopeReferences) => {\n assertChildPathSegment(pathSegment, path);\n const childPath = [...path, pathSegment];\n if (depth >= state.maxDepth) {\n throw new ConstructaError({\n kind: \"execution\",\n code: \"MAX_EXECUTION_DEPTH\",\n path: childPath,\n message: \"Child execution exceeds the configured maximum depth.\",\n });\n }\n const parsed = parseDefinitionAtPath(\n child,\n childPath,\n state.snapshot,\n );\n return executeParsedDefinition(\n parsed,\n childPath,\n depth + 1,\n state,\n scopeReferences,\n );\n },\n );\n },\n analyzeChildValueDependencies(child, pathSegment) {\n assertChildPathSegment(pathSegment, path);\n const childPath = [...path, pathSegment];\n const parsed = parseDefinitionAtPath(child, childPath, state.snapshot);\n const childImplementation = state.snapshot.lookup(parsed.type, childPath);\n return analyzeValueDependencies(childImplementation, parsed, childPath);\n },\n executeChild<Output>(\n child: GeneratorDefinition<Output>,\n pathSegment: ValidationPathSegment,\n ): Output {\n assertChildPathSegment(pathSegment, path);\n const childPath = [...path, pathSegment];\n if (depth >= state.maxDepth) {\n throw new ConstructaError({\n kind: \"execution\",\n code: \"MAX_EXECUTION_DEPTH\",\n path: childPath,\n message: \"Child execution exceeds the configured maximum depth.\",\n });\n }\n const parsed = parseDefinitionAtPath(child, childPath, state.snapshot);\n return executeParsedDefinition(\n parsed,\n childPath,\n depth + 1,\n state,\n references,\n ) as Output;\n },\n });\n return invokeValidatedGeneratorImplementation(\n implementation,\n definition,\n context,\n path,\n );\n}\n\nfunction createObjectGenerationScope(\n path: ValidationPath,\n executeChild: (\n definition: GeneratorDefinition,\n pathSegment: string,\n references: ReferenceResolver,\n ) => unknown,\n): ObjectGenerationScope {\n const completed = new Map<string, unknown>();\n const resolver: ReferenceResolver = Object.freeze({\n resolve(referencePath: ReferencePath): unknown {\n assertReferencePath(referencePath, path);\n const key = referencePathKey(referencePath);\n if (!completed.has(key)) {\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"REFERENCE_NOT_AVAILABLE\",\n path,\n message: \"The referenced object value has not completed.\",\n });\n }\n return completed.get(key);\n },\n });\n return Object.freeze({\n executeChild<Output>(\n definition: GeneratorDefinition<Output>,\n pathSegment: string,\n ): Output {\n const value = executeChild(definition, pathSegment, resolver) as Output;\n recordCompletedValue(completed, [pathSegment], value);\n return value;\n },\n });\n}\n\nfunction recordCompletedValue(\n completed: Map<string, unknown>,\n referencePath: readonly string[],\n value: unknown,\n visited = new WeakSet<object>(),\n): void {\n completed.set(referencePathKey(referencePath), value);\n if (typeof value !== \"object\" || value === null || visited.has(value)) return;\n visited.add(value);\n for (const [key, child] of Object.entries(value)) {\n recordCompletedValue(completed, [...referencePath, key], child, visited);\n }\n}\n\nfunction unavailableReferenceResolver(path: ValidationPath): ReferenceResolver {\n return Object.freeze({\n resolve(referencePath: ReferencePath): never {\n assertReferencePath(referencePath, path);\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"REFERENCE_RESOLUTION_UNAVAILABLE\",\n path,\n message:\n \"Reference resolution is available only inside an object field.\",\n });\n },\n });\n}\n\nfunction assertReferencePath(\n referencePath: ReferencePath,\n contextPath: ValidationPath,\n): void {\n if (\n !Array.isArray(referencePath) ||\n referencePath.length === 0 ||\n referencePath.some(\n (segment) => typeof segment !== \"string\" || segment.length === 0,\n )\n ) {\n throw contextError(\n \"INVALID_REFERENCE_PATH\",\n contextPath,\n \"Reference paths must contain one or more non-empty string segments.\",\n );\n }\n}\n\nfunction referencePathKey(path: readonly string[]): string {\n return JSON.stringify(path);\n}\n\nfunction createExecutionSnapshot(\n registry: GeneratorRegistry | GeneratorRegistrySnapshot,\n): GeneratorRegistrySnapshot {\n if (typeof registry !== \"object\" || registry === null) {\n throw contextError(\n \"INVALID_EXECUTOR_REGISTRY\",\n [\"registry\"],\n \"Executor requires a generator registry.\",\n );\n }\n if (typeof (registry as GeneratorRegistry).snapshot === \"function\") {\n return (registry as GeneratorRegistry).snapshot();\n }\n if (typeof (registry as GeneratorRegistrySnapshot).lookup === \"function\") {\n return registry as GeneratorRegistrySnapshot;\n }\n throw contextError(\n \"INVALID_EXECUTOR_REGISTRY\",\n [\"registry\"],\n \"Executor requires a generator registry.\",\n );\n}\n\nfunction resolveExecutionOptions(\n options: ExecutionOptions | undefined,\n): Omit<ExecutionState, \"snapshot\"> {\n if (options === undefined) {\n return { random: createDefaultRandomSource(), maxDepth: 64 };\n }\n if (typeof options !== \"object\" || options === null) {\n throw contextError(\n \"INVALID_EXECUTION_OPTIONS\",\n [],\n \"Execution options must be an object.\",\n );\n }\n if (options.seed !== undefined && options.random !== undefined) {\n throw contextError(\n \"CONFLICTING_RANDOM_OPTIONS\",\n [\"seed\"],\n \"seed and random cannot be supplied together.\",\n );\n }\n const maxDepth = options.maxDepth ?? 64;\n if (!Number.isSafeInteger(maxDepth) || maxDepth < 0) {\n throw contextError(\n \"INVALID_EXECUTION_OPTIONS\",\n [\"maxDepth\"],\n \"maxDepth must be a non-negative safe integer.\",\n );\n }\n const random =\n options.seed !== undefined\n ? createSeededRandom(options.seed)\n : options.random !== undefined\n ? createRandomSource(options.random)\n : createDefaultRandomSource();\n return { random, maxDepth };\n}\n\nfunction analyzeGeneratorDependencies(\n implementation: GeneratorImplementation<GeneratorDefinition, unknown>,\n definition: GeneratorDefinition,\n registry: GeneratorRegistrySnapshot,\n path: ValidationPath,\n): void {\n if (implementation.analyzeDependencies === undefined) return;\n let dependencies: readonly GeneratorDependency[];\n try {\n dependencies = implementation.analyzeDependencies(definition);\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"dependency\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message: \"Generator dependency analysis failed.\",\n });\n }\n if (!Array.isArray(dependencies)) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message: \"Generator dependency analysis returned an invalid result.\",\n });\n }\n for (const dependency of dependencies) {\n if (!isGeneratorDependency(dependency)) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message:\n \"Generator dependency analysis returned an invalid dependency.\",\n });\n }\n registry.lookup(dependency.typeId, [...path, ...dependency.path]);\n }\n}\n\nfunction analyzeValueDependencies(\n implementation: GeneratorImplementation<GeneratorDefinition, unknown>,\n definition: GeneratorDefinition,\n path: ValidationPath,\n): readonly ValueDependency[] {\n if (implementation.analyzeValueDependencies === undefined) return [];\n let dependencies: readonly ValueDependency[];\n try {\n dependencies = implementation.analyzeValueDependencies(definition);\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"dependency\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message: \"Value dependency analysis failed.\",\n });\n }\n if (!Array.isArray(dependencies) || !dependencies.every(isValueDependency)) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message: \"Value dependency analysis returned an invalid result.\",\n });\n }\n return Object.freeze(\n dependencies.map((dependency) =>\n Object.freeze({ path: Object.freeze([...dependency.path]) }),\n ),\n );\n}\n\nfunction isGeneratorDependency(value: unknown): value is GeneratorDependency {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as GeneratorDependency).typeId === \"string\" &&\n Array.isArray((value as GeneratorDependency).path) &&\n (value as GeneratorDependency).path.every(\n (segment) => typeof segment === \"string\" || Number.isSafeInteger(segment),\n )\n );\n}\n\nfunction isValueDependency(value: unknown): value is ValueDependency {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Array.isArray((value as ValueDependency).path) &&\n (value as ValueDependency).path.length > 0 &&\n (value as ValueDependency).path.every(\n (segment) => typeof segment === \"string\" && segment.length > 0,\n )\n );\n}\n\nfunction isCompositeDependencyNode(\n value: unknown,\n): value is CompositeDependencyNode {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Array.isArray((value as CompositeDependencyNode).fieldPath) &&\n (value as CompositeDependencyNode).fieldPath.length === 1 &&\n typeof (value as CompositeDependencyNode).fieldPath[0] === \"string\" &&\n Array.isArray((value as CompositeDependencyNode).dependencies) &&\n (value as CompositeDependencyNode).dependencies.every(isValueDependency)\n );\n}\n\nfunction invokeValidatedGeneratorImplementation(\n implementation: GeneratorImplementation<GeneratorDefinition, unknown>,\n definition: GeneratorDefinition,\n context: GenerationContext,\n path: ValidationPath,\n): unknown {\n try {\n return implementation.generate({ definition, context });\n } catch (cause) {\n if (cause instanceof ConstructaError) {\n return throwWithExecutionPath(cause, path);\n }\n throw normalizeConstructaError(cause, {\n kind: \"execution\",\n code: \"EXECUTION_FAILED\",\n path,\n message: \"Generator execution failed.\",\n });\n }\n}\n\nfunction throwWithExecutionPath(\n error: ConstructaError,\n path: ValidationPath,\n): never {\n if (path.length === 0 || startsWithPath(error.path, path)) throw error;\n throw new ConstructaError({\n kind: error.kind,\n code: error.code,\n path: [...path, ...error.path],\n message: error.message,\n details: error.details,\n });\n}\n\nfunction startsWithPath(path: ValidationPath, prefix: ValidationPath): boolean {\n return prefix.every((segment, index) => path[index] === segment);\n}\n\n/**\n * Defines a trusted, developer-authored generator implementation. This API has\n * no dependency on a particular validation library.\n */\nexport function defineGenerator<\n const Definition extends GeneratorDefinition<Output>,\n Output,\n>(\n implementation: GeneratorImplementation<Definition, Output>,\n): GeneratorImplementation<Definition, Output> {\n assertGeneratorImplementation(implementation);\n return implementation;\n}\n\n/** Builds a portable definition while preserving literal fields and output inference. */\nexport function createGeneratorDefinition<\n Output,\n const Definition extends GeneratorDefinition<Output>,\n>(definition: Definition): Definition {\n assertGeneratorDefinition(definition);\n return definition;\n}\n\n/**\n * Invokes one validated implementation. Registry lookup and dispatch are added\n * later; this function keeps validation and execution failure normalization in\n * the same shared contract today.\n */\nexport function invokeGeneratorImplementation<\n Definition extends GeneratorDefinition<Output>,\n Output,\n>(\n implementation: GeneratorImplementation<Definition, Output>,\n input: {\n readonly definition: Definition;\n readonly context: GenerationContext;\n readonly path?: ValidationPath;\n },\n): Output {\n const path = input.path ?? [];\n let issues: readonly ValidationIssue[];\n\n try {\n issues = implementation.validateDefinition(input.definition);\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"configuration\",\n code: \"INVALID_CONFIGURATION\",\n path,\n message: \"Generator definition validation failed.\",\n });\n }\n\n if (issues.length > 0) {\n const [issue] = issues;\n if (issue !== undefined) {\n throw new ConstructaError({\n kind: \"configuration\",\n code: errorCodeForValidationIssue(issue.code),\n path: [...path, ...issue.path],\n message: issue.message,\n details: { issueCode: issue.code },\n });\n }\n\n throw new ConstructaError({\n kind: \"system\",\n code: \"EXECUTION_FAILED\",\n path,\n message: \"Generator validation returned an invalid result.\",\n });\n }\n\n try {\n return implementation.generate({\n definition: input.definition,\n context: input.context,\n });\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"execution\",\n code: \"EXECUTION_FAILED\",\n path,\n message: \"Generator execution failed.\",\n });\n }\n}\n\nconst DEFAULT_PARSE_LIMITS = Object.freeze({\n maxDepth: 64,\n maxIssues: 100,\n maxNodes: 10_000,\n});\n\ntype ResolvedParseLimits = {\n readonly maxDepth: number;\n readonly maxIssues: number;\n readonly maxNodes: number;\n};\n\nfunction parseRuntimeDefinition(\n value: unknown,\n path: ValidationPath,\n options: ParseDefinitionOptions,\n): DefinitionParseResult {\n const limits = resolveParseLimits(options);\n const schemaIssues = validationIssuesToErrors(\n validateDefinitionSafely(value, path),\n path,\n limits.maxIssues,\n );\n if (schemaIssues.length > 0) return { success: false, issues: schemaIssues };\n\n const issues: ConstructaError[] = [];\n const visited = new Set<object>();\n visitRuntimeDefinition(\n value as GeneratorDefinition,\n path,\n 0,\n options.registry,\n limits,\n visited,\n issues,\n );\n return issues.length === 0\n ? {\n success: true,\n value: markParsedDefinitions(visited, value as GeneratorDefinition),\n }\n : { success: false, issues: Object.freeze(issues) };\n}\n\nfunction markParsedDefinitions(\n definitions: ReadonlySet<object>,\n definition: GeneratorDefinition,\n): ParsedGeneratorDefinition {\n for (const parsed of definitions) parsedDefinitions.add(parsed);\n return definition as ParsedGeneratorDefinition;\n}\n\nfunction visitRuntimeDefinition(\n definition: GeneratorDefinition,\n path: ValidationPath,\n depth: number,\n registry: ParseDefinitionOptions[\"registry\"],\n limits: ResolvedParseLimits,\n visited: Set<object>,\n issues: ConstructaError[],\n): void {\n if (issues.length >= limits.maxIssues) return;\n if (depth > limits.maxDepth) {\n addParseIssue(\n issues,\n limits,\n \"PARSE_DEPTH_LIMIT\",\n path,\n \"Generator definition exceeds the maximum nesting depth.\",\n );\n return;\n }\n if (visited.size >= limits.maxNodes) {\n addParseIssue(\n issues,\n limits,\n \"PARSE_NODE_LIMIT\",\n path,\n \"Generator definition exceeds the maximum node count.\",\n );\n return;\n }\n visited.add(definition);\n\n let implementation: GeneratorImplementation<GeneratorDefinition, unknown>;\n try {\n implementation = registry.lookup(definition.type, path);\n } catch (cause) {\n const error = normalizeConstructaError(cause, {\n kind: \"dependency\",\n code: \"UNKNOWN_GENERATOR\",\n path: [...path, \"type\"],\n message: \"Generator type could not be resolved.\",\n });\n addExistingParseIssue(issues, limits, error);\n return;\n }\n\n let validationIssues: readonly ValidationIssue[];\n try {\n validationIssues = implementation.validateDefinition(definition);\n } catch (cause) {\n addExistingParseIssue(\n issues,\n limits,\n normalizeConstructaError(cause, {\n kind: \"configuration\",\n code: \"INVALID_CONFIGURATION\",\n path,\n message: \"Generator definition validation failed.\",\n }),\n );\n return;\n }\n if (!Array.isArray(validationIssues)) {\n addParseIssue(\n issues,\n limits,\n \"INVALID_CONFIGURATION\",\n path,\n \"Generator definition validation returned an invalid result.\",\n \"system\",\n );\n return;\n }\n for (const issue of validationIssues) {\n if (!isValidationIssue(issue)) {\n addParseIssue(\n issues,\n limits,\n \"INVALID_CONFIGURATION\",\n path,\n \"Generator definition validation returned an invalid issue.\",\n \"system\",\n );\n return;\n }\n addParseIssue(\n issues,\n limits,\n errorCodeForValidationIssue(issue.code),\n [...path, ...issue.path],\n issue.message,\n );\n }\n\n // Configurations are portable JSON. Every embedded object with a generator\n // discriminator is another definition and must pass the same pipeline.\n for (const [key, child] of Object.entries(definition)) {\n if (key !== \"type\")\n visitEmbeddedDefinitions(\n child,\n [...path, key],\n depth + 1,\n registry,\n limits,\n visited,\n issues,\n );\n if (issues.length >= limits.maxIssues) return;\n }\n}\n\nfunction visitEmbeddedDefinitions(\n value: unknown,\n path: ValidationPath,\n depth: number,\n registry: ParseDefinitionOptions[\"registry\"],\n limits: ResolvedParseLimits,\n visited: Set<object>,\n issues: ConstructaError[],\n): void {\n if (\n issues.length >= limits.maxIssues ||\n value === null ||\n typeof value !== \"object\"\n )\n return;\n if (Array.isArray(value)) {\n for (let index = 0; index < value.length; index += 1) {\n visitEmbeddedDefinitions(\n value[index],\n [...path, index],\n depth,\n registry,\n limits,\n visited,\n issues,\n );\n if (issues.length >= limits.maxIssues) return;\n }\n return;\n }\n if (Object.hasOwn(value, \"type\")) {\n visitRuntimeDefinition(\n value as GeneratorDefinition,\n path,\n depth,\n registry,\n limits,\n visited,\n issues,\n );\n return;\n }\n for (const [key, child] of Object.entries(value)) {\n visitEmbeddedDefinitions(\n child,\n [...path, key],\n depth,\n registry,\n limits,\n visited,\n issues,\n );\n if (issues.length >= limits.maxIssues) return;\n }\n}\n\nfunction resolveParseLimits(\n options: ParseDefinitionOptions,\n): ResolvedParseLimits {\n if (\n typeof options !== \"object\" ||\n options === null ||\n typeof options.registry !== \"object\" ||\n options.registry === null ||\n typeof options.registry.lookup !== \"function\"\n ) {\n throw contextError(\n \"INVALID_PARSE_OPTIONS\",\n [],\n \"Parsing requires a registry with a lookup function.\",\n );\n }\n const supplied = options.limits ?? {};\n const resolved = {\n maxDepth: supplied.maxDepth ?? DEFAULT_PARSE_LIMITS.maxDepth,\n maxIssues: supplied.maxIssues ?? DEFAULT_PARSE_LIMITS.maxIssues,\n maxNodes: supplied.maxNodes ?? DEFAULT_PARSE_LIMITS.maxNodes,\n };\n for (const [name, value] of Object.entries(resolved)) {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw contextError(\n \"INVALID_PARSE_LIMITS\",\n [\"limits\", name],\n `${name} must be a positive safe integer.`,\n );\n }\n }\n return resolved;\n}\n\nfunction validateDefinitionSafely(\n value: unknown,\n path: ValidationPath,\n): readonly ValidationIssue[] {\n try {\n return validateGeneratorDefinition(value, path);\n } catch (_cause) {\n return [\n {\n code: \"invalid_json_value\",\n path,\n message: \"Definition could not be safely inspected.\",\n },\n ];\n }\n}\n\nfunction validateDocumentSafely(value: unknown): readonly ValidationIssue[] {\n try {\n return validateDocument(value);\n } catch {\n return [\n {\n code: \"invalid_json_value\",\n path: [],\n message: \"Document could not be safely inspected.\",\n },\n ];\n }\n}\n\nfunction validationIssuesToErrors(\n issues: readonly ValidationIssue[],\n fallbackPath: ValidationPath,\n maxIssues = Number.POSITIVE_INFINITY,\n): ConstructaError[] {\n return issues.slice(0, maxIssues).map(\n (issue) =>\n new ConstructaError({\n kind: \"configuration\",\n code: isValidationIssue(issue)\n ? errorCodeForValidationIssue(issue.code)\n : \"INVALID_CONFIGURATION\",\n path: isValidationIssue(issue) ? issue.path : fallbackPath,\n message: isValidationIssue(issue)\n ? issue.message\n : \"Validation returned an invalid issue.\",\n details: isValidationIssue(issue)\n ? { issueCode: issue.code }\n : undefined,\n }),\n );\n}\n\nfunction errorCodeForValidationIssue(code: string): Uppercase<string> {\n const reservedCodes: Record<string, Uppercase<string>> = {\n empty_choice: \"EMPTY_CHOICE\",\n invalid_length: \"INVALID_LENGTH\",\n invalid_range: \"INVALID_RANGE\",\n invalid_template_token: \"INVALID_TEMPLATE_TOKEN\",\n };\n return reservedCodes[code] ?? \"INVALID_CONFIGURATION\";\n}\n\nfunction isValidationIssue(value: unknown): value is ValidationIssue {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ValidationIssue).code === \"string\" &&\n typeof (value as ValidationIssue).message === \"string\" &&\n Array.isArray((value as ValidationIssue).path)\n );\n}\n\nfunction addParseIssue(\n issues: ConstructaError[],\n limits: ResolvedParseLimits,\n code: string,\n path: ValidationPath,\n message: string,\n kind: \"configuration\" | \"system\" = \"configuration\",\n): void {\n if (issues.length < limits.maxIssues)\n issues.push(\n new ConstructaError({\n kind,\n code: code as Uppercase<string>,\n path,\n message,\n }),\n );\n}\n\nfunction addExistingParseIssue(\n issues: ConstructaError[],\n limits: ResolvedParseLimits,\n error: ConstructaError,\n): void {\n if (issues.length < limits.maxIssues) issues.push(error);\n}\n\nfunction assertGeneratorImplementation(implementation: {\n readonly type: string;\n readonly version: number;\n readonly validateDefinition: unknown;\n readonly analyzeDependencies?: unknown;\n readonly generate: unknown;\n}): void {\n if (!isStableTypeId(implementation.type)) {\n throw new TypeError(\"generator type must be a stable lowercase identifier\");\n }\n if (\n !Number.isSafeInteger(implementation.version) ||\n implementation.version < 1\n ) {\n throw new TypeError(\"generator version must be a positive safe integer\");\n }\n if (typeof implementation.validateDefinition !== \"function\") {\n throw new TypeError(\"validateDefinition must be a function\");\n }\n if (typeof implementation.generate !== \"function\") {\n throw new TypeError(\"generate must be a function\");\n }\n if (\n implementation.analyzeDependencies !== undefined &&\n typeof implementation.analyzeDependencies !== \"function\"\n ) {\n throw new TypeError(\"analyzeDependencies must be a function when present\");\n }\n}\n\nfunction assertRegistryImplementation(implementation: {\n readonly type: string;\n readonly version: number;\n readonly validateDefinition: unknown;\n readonly analyzeDependencies?: unknown;\n readonly generate: unknown;\n}): void {\n try {\n assertGeneratorImplementation(implementation);\n } catch {\n throw registryError(\n \"INVALID_CONFIGURATION\",\n [\"implementation\"],\n \"Generator implementation is invalid.\",\n );\n }\n if (RESERVED_GENERATOR_TYPE_IDS.has(implementation.type)) {\n throw registryError(\n \"INVALID_CONFIGURATION\",\n [\"type\"],\n `Generator type \"${implementation.type}\" is reserved.`,\n );\n }\n}\n\nfunction freezeImplementation<\n Definition extends GeneratorDefinition<Output>,\n Output,\n>(\n implementation: GeneratorImplementation<Definition, Output>,\n): GeneratorImplementation<Definition, Output> {\n return Object.freeze({ ...implementation });\n}\n\nfunction createRegistrySnapshot(\n implementations: ReadonlyMap<\n string,\n GeneratorImplementation<GeneratorDefinition, unknown>\n >,\n): GeneratorRegistrySnapshot {\n const snapshotImplementations = new Map(implementations);\n const generators = [...snapshotImplementations.values()]\n .map(({ type, version }) => Object.freeze({ type, version }))\n .sort((left, right) => left.type.localeCompare(right.type));\n\n return Object.freeze({\n generators: Object.freeze(generators),\n lookup(type: string, path: ValidationPath = []) {\n return lookupImplementation(snapshotImplementations, type, path);\n },\n });\n}\n\nfunction lookupImplementation(\n implementations: ReadonlyMap<\n string,\n GeneratorImplementation<GeneratorDefinition, unknown>\n >,\n type: string,\n path: ValidationPath,\n): GeneratorImplementation<GeneratorDefinition, unknown> {\n const implementation = implementations.get(type);\n if (implementation !== undefined) return implementation;\n\n const registeredTypes = [...implementations.keys()].sort((left, right) =>\n left.localeCompare(right),\n );\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"UNKNOWN_GENERATOR\",\n path: [...path, \"type\"],\n message: `No generator with type \"${type}\" is registered.`,\n details: { registeredTypes },\n });\n}\n\nfunction registryError(\n code: \"DUPLICATE_GENERATOR\" | \"INVALID_CONFIGURATION\" | \"UNKNOWN_GENERATOR\",\n path: ValidationPath,\n message: string,\n): ConstructaError {\n return new ConstructaError({ kind: \"configuration\", code, path, message });\n}\n\nfunction assertRandomSourceAdapter(adapter: RandomSourceAdapter): void {\n if (\n typeof adapter !== \"object\" ||\n adapter === null ||\n typeof adapter.float !== \"function\" ||\n typeof adapter.integer !== \"function\" ||\n typeof adapter.bytes !== \"function\"\n ) {\n throw invalidRandomSource(\n \"A random source must provide float(), integer(), and bytes() methods.\",\n );\n }\n}\n\nfunction assertRandomLength(value: number, name: string): void {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw invalidRandomSource(`${name} must be a positive safe integer.`);\n }\n}\n\nfunction assertByteLength(length: number): void {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw invalidRandomSource(\"length must be a non-negative safe integer.\");\n }\n}\n\nfunction invalidRandomSource(message: string): ConstructaError {\n return new ConstructaError({\n kind: \"system\",\n code: \"INVALID_RANDOM_SOURCE\",\n path: [\"random\"],\n message,\n });\n}\n\nfunction assertContextPath(path: ValidationPath): void {\n for (const segment of path) assertContextPathSegment(segment);\n}\n\nfunction assertContextPathSegment(\n segment: unknown,\n): asserts segment is ValidationPathSegment {\n if (\n typeof segment !== \"string\" &&\n (!Number.isSafeInteger(segment) || typeof segment !== \"number\")\n ) {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [\"path\"],\n \"Context path segments must be strings or safe integers.\",\n );\n }\n}\n\nfunction assertChildPathSegment(\n segment: unknown,\n path: ValidationPath,\n): asserts segment is ValidationPathSegment {\n if (\n typeof segment !== \"string\" &&\n (typeof segment !== \"number\" || !Number.isSafeInteger(segment))\n ) {\n throw contextError(\n \"INVALID_CHILD_PATH\",\n path,\n \"Child path segments must be strings or safe integers.\",\n );\n }\n}\n\nfunction contextError(\n code: string,\n path: ValidationPath,\n message: string,\n): ConstructaError {\n return new ConstructaError({\n kind: \"configuration\",\n code: code as Uppercase<string>,\n path,\n message,\n });\n}\n\nfunction hashSeed(seed: string): number {\n let hash = 0x811c_9dc5;\n for (const byte of new TextEncoder().encode(seed)) {\n hash = Math.imul(hash ^ byte, 0x0100_0193) >>> 0;\n }\n return hash;\n}\n\nfunction isStableTypeId(value: string): boolean {\n return /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u.test(value);\n}\n"],"mappings":";;AAiCA,MAAM,yCAAyB,IAAI,QAAgB;AAuBnD,MAAa,0BAA0B;AACvC,MAAa,kCAAkC;AAgB/C,MAAM,yBAA+C,OAAO,OAAO;CACjE,WAAW;CACX,SAAA;AACF,CAAC;;;;;AAMD,SAAgB,mBAAmB,SAA4C;CAC7E,0BAA0B,OAAO;CAEjC,MAAM,SAAS,OAAO,OAAO;EAC3B,QAAQ;GACN,MAAM,QAAQ,QAAQ,MAAM;GAC5B,IACE,OAAO,UAAU,YAC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0C;CAC1C,IACE,OAAO,YAAY,aAClB,CAAC,OAAO,cAAc,OAAO,KAAK,OAAO,YAAY,WAEtD,MAAM,aACJ,8BACA,CAAC,MAAM,GACP,yDACF;AAEJ;AAEA,SAAS,uBACP,SACA,MAC0C;CAC1C,IACE,OAAO,YAAY,aAClB,OAAO,YAAY,YAAY,CAAC,OAAO,cAAc,OAAO,IAE7D,MAAM,aACJ,sBACA,MACA,uDACF;AAEJ;AAEA,SAAS,aACP,MACA,MACA,SACiB;CACjB,OAAO,IAAI,gBAAgB;EACzB,MAAM;EACA;EACN;EACA;CACF,CAAC;AACH;AAEA,SAAS,SAAS,MAAsB;CACtC,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,GAC9C,OAAO,KAAK,KAAK,OAAO,MAAM,QAAW,MAAM;CAEjD,OAAO;AACT;AAEA,SAAS,eAAe,OAAwB;CAC9C,OAAO,uCAAuC,KAAK,KAAK;AAC1D"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["parseSchemaDocument"],"sources":["../src/index.ts"],"sourcesContent":["import {\n assertGeneratorDefinition,\n ConstructaError,\n type GeneratorDefinition,\n normalizeConstructaError,\n parseDocument as parseSchemaDocument,\n type ValidationIssue,\n type ValidationPath,\n type ValidationPathSegment,\n validateDocument,\n validateGeneratorDefinition,\n} from \"constructa-schema\";\n\nexport type {\n GeneratorDefinition,\n Infer,\n ValidationIssue,\n ValidationPath,\n ValidationPathSegment,\n} from \"constructa-schema\";\n\n/**\n * Random values are always half-open: `float()` returns [0, 1), while\n * `integer(maxExclusive)` returns an integer in [0, maxExclusive).\n */\nexport type RandomSource = {\n float(): number;\n integer(maxExclusive: number): number;\n bytes(length: number): Uint8Array;\n};\n\n/** An application-provided random source validated by `createRandomSource`. */\nexport type RandomSourceAdapter = RandomSource;\n\nconst validatedRandomSources = new WeakSet<object>();\n\n/** A deterministic random-source seed. */\nexport type Seed = number | string;\n\n/** Per-root-execution limits and random-source options. */\nexport type ExecutionOptions = {\n /** Uses a fresh deterministic source for this root execution. */\n readonly seed?: Seed;\n /**\n * A caller-owned source consumed by this execution. The executor does not\n * reset, clone, or otherwise retain it after the call returns.\n */\n readonly random?: RandomSource;\n /** Maximum child-definition nesting below the root. Defaults to 64. */\n readonly maxDepth?: number;\n /** Stops execution before the next generator dispatch when aborted. */\n readonly signal?: AbortSignal;\n /** Stops execution before the next generator dispatch after this UTC epoch time. */\n readonly deadline?: number;\n};\n\n/** Executes validated generator definitions through a registry snapshot. */\nexport type Executor = {\n generate: <Definition extends GeneratorDefinition>(\n definition: Definition,\n options?: ExecutionOptions,\n ) => import(\"constructa-schema\").Infer<Definition>;\n};\n\n/** The deterministic random algorithm used by `createSeededRandom`. */\nexport const SEEDED_RANDOM_ALGORITHM = \"mulberry32\";\n/** The compatibility version of the seeded random algorithm. */\nexport const SEEDED_RANDOM_ALGORITHM_VERSION = 1;\n\n/** Public metadata identifying the seeded random algorithm. */\nexport type SeededRandomMetadata = {\n readonly algorithm: typeof SEEDED_RANDOM_ALGORITHM;\n readonly version: typeof SEEDED_RANDOM_ALGORITHM_VERSION;\n};\n\n/** Values that must remain compatible to reproduce an execution. */\nexport type DeterminismCompatibility = {\n readonly engineVersion: string;\n readonly generatorImplementationVersion: number;\n readonly random: SeededRandomMetadata;\n readonly definition: GeneratorDefinition;\n readonly seed: Seed;\n readonly executionMode: string;\n};\n\nconst SEEDED_RANDOM_METADATA: SeededRandomMetadata = Object.freeze({\n algorithm: SEEDED_RANDOM_ALGORITHM,\n version: SEEDED_RANDOM_ALGORITHM_VERSION,\n});\n\n/**\n * Validates an injected source and guards every produced value. No fallback\n * randomness is used when an adapter violates its contract.\n */\nexport function createRandomSource(adapter: RandomSourceAdapter): RandomSource {\n assertRandomSourceAdapter(adapter);\n\n const source = Object.freeze({\n float() {\n const value = adapter.float();\n if (\n typeof value !== \"number\" ||\n !Number.isFinite(value) ||\n value < 0 ||\n value >= 1\n ) {\n throw invalidRandomSource(\n \"float() must return a finite number in [0, 1).\",\n );\n }\n return value;\n },\n integer(maxExclusive: number) {\n assertRandomLength(maxExclusive, \"maxExclusive\");\n const value = adapter.integer(maxExclusive);\n if (!Number.isSafeInteger(value) || value < 0 || value >= maxExclusive) {\n throw invalidRandomSource(\n \"integer(maxExclusive) must return a safe integer in [0, maxExclusive).\",\n );\n }\n return value;\n },\n bytes(length: number) {\n assertByteLength(length);\n const value = adapter.bytes(length);\n if (!(value instanceof Uint8Array) || value.length !== length) {\n throw invalidRandomSource(\n \"bytes(length) must return a Uint8Array with exactly length bytes.\",\n );\n }\n return value;\n },\n });\n validatedRandomSources.add(source);\n return source;\n}\n\n/** Creates the default platform-backed random source. It makes no security claim. */\nexport function createDefaultRandomSource(): RandomSource {\n const crypto = globalThis.crypto;\n if (crypto?.getRandomValues === undefined) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"SYSTEM_RANDOM_UNAVAILABLE\",\n path: [],\n message: \"Platform cryptographic random values are unavailable.\",\n });\n }\n\n const randomBytes = (length: number) => {\n const bytes = new Uint8Array(length);\n for (let offset = 0; offset < length; offset += 65_536) {\n crypto.getRandomValues(bytes.subarray(offset, offset + 65_536));\n }\n return bytes;\n };\n const uint32 = () => new DataView(randomBytes(4).buffer).getUint32(0);\n const uint53 = () => (uint32() & 0x1f_ffff) * 2 ** 32 + uint32();\n\n return createRandomSource({\n float() {\n return uint53() / 2 ** 53;\n },\n integer(maxExclusive: number) {\n const range = 2 ** 53;\n const upperLimit = range - (range % maxExclusive);\n let value = uint53();\n while (value >= upperLimit) value = uint53();\n return value % maxExclusive;\n },\n bytes: randomBytes,\n });\n}\n\n/**\n * Returns a canonical seed representation. Strings use UTF-8 exactly; finite\n * numbers use their JavaScript numeric representation, with -0 normalized to 0.\n */\nexport function normalizeSeed(seed: Seed): string {\n if (typeof seed === \"string\") return `string:${seed}`;\n if (typeof seed === \"number\" && Number.isFinite(seed)) {\n return `number:${Object.is(seed, -0) ? \"0\" : String(seed)}`;\n }\n throw new ConstructaError({\n kind: \"configuration\",\n code: \"INVALID_SEED\",\n path: [\"seed\"],\n message: \"seed must be a string or finite number.\",\n });\n}\n\n/** Creates an isolated deterministic random source for the current algorithm version. */\nexport function createSeededRandom(seed: Seed): RandomSource {\n let state = hashSeed(normalizeSeed(seed));\n const uint32 = () => {\n state = (state + 0x6d2b_79f5) >>> 0;\n let value = state;\n value = Math.imul(value ^ (value >>> 15), value | 1);\n value ^= value + Math.imul(value ^ (value >>> 7), value | 61);\n return (value ^ (value >>> 14)) >>> 0;\n };\n const uint53 = () => (uint32() & 0x1f_ffff) * 2 ** 32 + uint32();\n\n return createRandomSource({\n float() {\n return uint53() / 2 ** 53;\n },\n integer(maxExclusive: number) {\n const range = 2 ** 53;\n const upperLimit = range - (range % maxExclusive);\n let value = uint53();\n while (value >= upperLimit) value = uint53();\n return value % maxExclusive;\n },\n bytes(length: number) {\n const bytes = new Uint8Array(length);\n for (let index = 0; index < length; index += 1) {\n if (index % 4 === 0) {\n const value = uint32();\n bytes[index] = value & 0xff;\n if (index + 1 < length) bytes[index + 1] = (value >>> 8) & 0xff;\n if (index + 2 < length) bytes[index + 2] = (value >>> 16) & 0xff;\n if (index + 3 < length) bytes[index + 3] = value >>> 24;\n }\n }\n return bytes;\n },\n });\n}\n\n/** Metadata for reproducibility diagnostics. It intentionally contains no seed. */\nexport function getSeededRandomMetadata(): SeededRandomMetadata {\n return SEEDED_RANDOM_METADATA;\n}\n\n/** Services supplied by the engine. Implementations must not use global randomness. */\n/** Capabilities supplied to a trusted generator implementation. */\nexport type GenerationContext = {\n readonly random: RandomSource;\n /** The definition path currently being generated. */\n readonly path: ValidationPath;\n /** Delegates a typed child definition to the engine. */\n readonly executeChild: <Output>(\n definition: GeneratorDefinition<Output>,\n pathSegment: ValidationPathSegment,\n ) => Output;\n /**\n * Read-only values from the object currently being generated. Values are\n * available only after their field has completed.\n */\n readonly references: ReferenceResolver;\n /** Creates an isolated scope for the fields of one composite object. */\n readonly createObjectScope: () => ObjectGenerationScope;\n /** Returns value dependencies declared by one direct child definition. */\n readonly analyzeChildValueDependencies: (\n definition: GeneratorDefinition,\n pathSegment: ValidationPathSegment,\n ) => readonly ValueDependency[];\n};\n\n/** A property path relative to the object containing a reference. */\n/** A property path used by an object-local template reference. */\nexport type ReferencePath = readonly string[];\n\n/** A parsed template fragment. Braces are escaped with `{{` and `}}`. */\n/** One literal or reference segment of parsed template source. */\nexport type TemplateToken =\n | { readonly type: \"literal\"; readonly value: string }\n | { readonly type: \"reference\"; readonly path: ReferencePath };\n\n/** Options controlling template-token parse diagnostics. */\nexport type ParseTemplateTokensOptions = {\n /** Definition-relative path reported for malformed template syntax. */\n readonly path?: ValidationPath;\n};\n\n/**\n * Parses MVP template syntax without executing or resolving references.\n *\n * `{field}` addresses a sibling and `{field.nested}` addresses a value below\n * that sibling. `{{` and `}}` emit literal braces. Whitespace, empty path\n * segments, and expression characters inside a reference are unsupported.\n */\nexport function parseTemplateTokens(\n source: string,\n options: ParseTemplateTokensOptions = {},\n): readonly TemplateToken[] {\n const path = options.path ?? [];\n if (typeof source !== \"string\") {\n throw templateTokenError(path, \"Template source must be a string.\");\n }\n assertContextPath(path);\n\n const tokens: TemplateToken[] = [];\n let literal = \"\";\n const appendLiteral = (value: string) => {\n literal += value;\n };\n const flushLiteral = () => {\n if (literal.length === 0) return;\n tokens.push(Object.freeze({ type: \"literal\", value: literal }));\n literal = \"\";\n };\n\n for (let index = 0; index < source.length; index += 1) {\n const character = source[index];\n if (character === \"{\") {\n if (source[index + 1] === \"{\") {\n appendLiteral(\"{\");\n index += 1;\n continue;\n }\n const closingIndex = source.indexOf(\"}\", index + 1);\n if (closingIndex === -1) {\n throw templateTokenError(\n path,\n \"Template reference is missing a closing brace.\",\n );\n }\n const reference = source.slice(index + 1, closingIndex);\n const referencePath = parseReferencePath(reference, path);\n flushLiteral();\n tokens.push(Object.freeze({ type: \"reference\", path: referencePath }));\n index = closingIndex;\n continue;\n }\n if (character === \"}\") {\n if (source[index + 1] === \"}\") {\n appendLiteral(\"}\");\n index += 1;\n continue;\n }\n throw templateTokenError(\n path,\n \"Template contains an unmatched closing brace.\",\n );\n }\n appendLiteral(character ?? \"\");\n }\n flushLiteral();\n return Object.freeze(tokens);\n}\n\n/** Parses one dot-separated object-local reference path. */\nexport function parseReferencePath(\n source: string,\n path: ValidationPath = [],\n): ReferencePath {\n if (typeof source !== \"string\" || source.length === 0) {\n throw templateTokenError(path, \"Template reference must not be empty.\");\n }\n assertContextPath(path);\n const segments = source.split(\".\");\n if (\n segments.some(\n (segment) => segment.length === 0 || !/^[\\p{L}\\p{N}_$-]+$/u.test(segment),\n )\n ) {\n throw templateTokenError(\n path,\n \"Template reference segments must use letters, numbers, underscores, dollar signs, or hyphens.\",\n );\n }\n return Object.freeze(segments);\n}\n\nfunction templateTokenError(\n path: ValidationPath,\n message: string,\n): ConstructaError {\n return new ConstructaError({\n kind: \"configuration\",\n code: \"INVALID_TEMPLATE_TOKEN\",\n path,\n message,\n });\n}\n\n/** A portable value dependency declared by a generator definition. */\n/** One value dependency declared by a child generator. */\nexport type ValueDependency = {\n readonly path: ReferencePath;\n};\n\n/** Dependencies for a direct field in a composite definition. */\n/** A composite child and the values it depends on. */\nexport type CompositeDependencyNode = {\n readonly fieldPath: readonly [string];\n readonly dependencies: readonly ValueDependency[];\n};\n\n/** Portable dependency data used to schedule one composite object. */\n/** An immutable analysis of composite-child dependencies. */\nexport type CompositeDependencyAnalysis = {\n readonly nodes: readonly CompositeDependencyNode[];\n};\n\n/** Options used to order dependent composite children. */\nexport type CompositeDependencySchedulingOptions = {\n /** Every reference path that exists in the containing object definition. */\n readonly referencePaths?: readonly ReferencePath[];\n /** Maximum fields participating in one object-local reference graph. */\n readonly maxNodes?: number;\n /** Maximum unique field dependencies in one object-local reference graph. */\n readonly maxEdges?: number;\n};\n\n/** The read-only capability supplied to generators that resolve references. */\n/** Resolves values visible to an executing generator. */\nexport type ReferenceResolver = {\n resolve: (path: ReferencePath) => unknown;\n};\n\n/** Executes and records completed fields within one isolated object scope. */\n/** An isolated object-field execution scope. */\nexport type ObjectGenerationScope = {\n executeChild: <Output>(\n definition: GeneratorDefinition<Output>,\n pathSegment: string,\n ) => Output;\n};\n\n/** Inputs used to create a generator execution context. */\nexport type GenerationContextOptions = {\n readonly random: RandomSource;\n readonly path?: ValidationPath;\n readonly executeChild?: GenerationContext[\"executeChild\"];\n readonly references?: ReferenceResolver;\n readonly createObjectScope?: GenerationContext[\"createObjectScope\"];\n readonly analyzeChildValueDependencies?: GenerationContext[\"analyzeChildValueDependencies\"];\n};\n\n/**\n * Creates the engine-owned capability view supplied to implementations.\n * Application code normally receives this through `generate`, rather than\n * constructing one directly.\n */\nexport function createGenerationContext(\n options: GenerationContextOptions,\n): GenerationContext {\n if (typeof options !== \"object\" || options === null) {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"Context options must be an object.\",\n );\n }\n assertContextPath(options.path ?? []);\n if (\n typeof options.executeChild !== \"undefined\" &&\n typeof options.executeChild !== \"function\"\n ) {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"executeChild must be a function when present.\",\n );\n }\n\n // This validates the Phase 012 source contract without drawing from it.\n const random = validatedRandomSources.has(options.random)\n ? options.random\n : createRandomSource(options.random);\n const path = Object.freeze([...(options.path ?? [])]);\n const executeChild =\n options.executeChild ??\n ((definition, pathSegment) => {\n assertGeneratorDefinition(definition, [...path, pathSegment]);\n assertContextPathSegment(pathSegment);\n throw new ConstructaError({\n kind: \"execution\",\n code: \"CHILD_EXECUTION_UNAVAILABLE\",\n path: [...path, pathSegment],\n message: \"Child execution is not available in this generation context.\",\n });\n });\n\n const references = options.references ?? unavailableReferenceResolver(path);\n if (\n typeof references !== \"object\" ||\n references === null ||\n typeof references.resolve !== \"function\"\n ) {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"references must provide a resolve function when present.\",\n );\n }\n const createObjectScope =\n options.createObjectScope ??\n (() =>\n Object.freeze({\n executeChild<Output>(\n definition: GeneratorDefinition<Output>,\n pathSegment: string,\n ): Output {\n return executeChild(definition, pathSegment);\n },\n }));\n if (typeof createObjectScope !== \"function\") {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"createObjectScope must be a function when present.\",\n );\n }\n const analyzeChildValueDependencies =\n options.analyzeChildValueDependencies ?? (() => []);\n if (typeof analyzeChildValueDependencies !== \"function\") {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"analyzeChildValueDependencies must be a function when present.\",\n );\n }\n\n return Object.freeze({\n random,\n path,\n executeChild,\n references: Object.freeze({ resolve: references.resolve }),\n createObjectScope,\n analyzeChildValueDependencies,\n });\n}\n\n/** Freezes direct-field dependency declarations into portable analysis data. */\nexport function createCompositeDependencyAnalysis(\n nodes: readonly CompositeDependencyNode[],\n): CompositeDependencyAnalysis {\n if (!Array.isArray(nodes)) {\n throw contextError(\n \"INVALID_COMPOSITE_DEPENDENCIES\",\n [],\n \"Composite dependency nodes must be an array.\",\n );\n }\n const names = new Set<string>();\n const normalized = nodes.map((node, index) => {\n if (!isCompositeDependencyNode(node) || names.has(node.fieldPath[0])) {\n throw contextError(\n \"INVALID_COMPOSITE_DEPENDENCIES\",\n [\"nodes\", index],\n \"Each composite dependency node must name one unique field.\",\n );\n }\n names.add(node.fieldPath[0]);\n return Object.freeze({\n fieldPath: Object.freeze([...node.fieldPath]) as readonly [string],\n dependencies: Object.freeze(\n node.dependencies.map((dependency) =>\n Object.freeze({ path: Object.freeze([...dependency.path]) }),\n ),\n ),\n });\n });\n return Object.freeze({ nodes: Object.freeze(normalized) });\n}\n\n/**\n * Returns a deterministic execution order for direct object fields. A\n * dependency path may target a nested value below another direct field.\n */\nexport function scheduleCompositeDependencies(\n analysis: CompositeDependencyAnalysis,\n options: CompositeDependencySchedulingOptions = {},\n): readonly string[] {\n const nodes = analysis.nodes;\n const maxNodes = options.maxNodes ?? 10_000;\n const maxEdges = options.maxEdges ?? 100_000;\n if (\n !Number.isSafeInteger(maxNodes) ||\n maxNodes < 1 ||\n !Number.isSafeInteger(maxEdges) ||\n maxEdges < 1\n ) {\n throw contextError(\n \"INVALID_COMPOSITE_DEPENDENCIES\",\n [],\n \"Composite graph limits must be positive safe integers.\",\n );\n }\n if (nodes.length > maxNodes) {\n throw new ConstructaError({\n kind: \"configuration\",\n code: \"REFERENCE_GRAPH_NODE_LIMIT\",\n path: [],\n message:\n \"Object reference graph exceeds the configured maximum field count.\",\n });\n }\n const byName = new Map(nodes.map((node) => [node.fieldPath[0], node]));\n const referencePaths = new Set(\n (options.referencePaths ?? nodes.map((node) => node.fieldPath)).map(\n referencePathKey,\n ),\n );\n const remaining = new Map<string, Set<string>>();\n const dependents = new Map<string, string[]>();\n let edgeCount = 0;\n\n for (const node of nodes) {\n const dependencies = new Set<string>();\n for (const dependency of node.dependencies) {\n const target = dependency.path[0];\n if (\n target === undefined ||\n !byName.has(target) ||\n !referencePaths.has(referencePathKey(dependency.path))\n ) {\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"REFERENCE_NOT_FOUND\",\n path: [...node.fieldPath],\n message: \"The referenced object value could not be found.\",\n details: { referencePath: [...dependency.path] },\n });\n }\n if (!dependencies.has(target)) {\n dependencies.add(target);\n edgeCount += 1;\n }\n if (edgeCount > maxEdges) {\n throw new ConstructaError({\n kind: \"configuration\",\n code: \"REFERENCE_GRAPH_EDGE_LIMIT\",\n path: [...node.fieldPath],\n message:\n \"Object reference graph exceeds the configured maximum dependency count.\",\n });\n }\n const targets = dependents.get(target) ?? [];\n if (!targets.includes(node.fieldPath[0])) targets.push(node.fieldPath[0]);\n dependents.set(target, targets);\n }\n remaining.set(node.fieldPath[0], dependencies);\n }\n\n const ready = nodes\n .filter((node) => (remaining.get(node.fieldPath[0])?.size ?? 0) === 0)\n .map((node) => node.fieldPath[0])\n .sort();\n const ordered: string[] = [];\n while (ready.length > 0) {\n const field = ready.shift();\n if (field === undefined) continue;\n ordered.push(field);\n for (const dependent of (dependents.get(field) ?? []).sort()) {\n const dependencies = remaining.get(dependent);\n dependencies?.delete(field);\n if (dependencies?.size === 0) {\n ready.push(dependent);\n ready.sort();\n }\n }\n }\n if (ordered.length !== nodes.length) {\n const cycle = findCompositeDependencyCycle(remaining);\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"CIRCULAR_REFERENCE\",\n path: cycle.slice(0, 1),\n message: `Circular object value reference detected: ${cycle.join(\" -> \")}.`,\n details: { fields: cycle },\n });\n }\n return Object.freeze(ordered);\n}\n\nfunction findCompositeDependencyCycle(\n remaining: ReadonlyMap<string, ReadonlySet<string>>,\n): string[] {\n const visited = new Set<string>();\n const active = new Set<string>();\n const stack: string[] = [];\n const visit = (field: string): string[] | undefined => {\n visited.add(field);\n active.add(field);\n stack.push(field);\n for (const dependency of [...(remaining.get(field) ?? [])].sort()) {\n if (!remaining.has(dependency)) continue;\n if (active.has(dependency)) {\n const start = stack.indexOf(dependency);\n return [...stack.slice(start), dependency];\n }\n if (!visited.has(dependency)) {\n const cycle = visit(dependency);\n if (cycle !== undefined) return cycle;\n }\n }\n active.delete(field);\n stack.pop();\n return undefined;\n };\n\n for (const field of [...remaining.keys()].sort()) {\n if (visited.has(field)) continue;\n const cycle = visit(field);\n if (cycle !== undefined) return cycle;\n }\n return [];\n}\n\n/** Bounds applied while parsing untrusted definitions or documents. */\nexport type ParseLimits = {\n readonly maxDepth?: number;\n readonly maxIssues?: number;\n readonly maxNodes?: number;\n /** Maximum UTF-8 encoded definition bytes. */\n readonly maxBytes?: number;\n /** Maximum properties in any input object record. */\n readonly maxObjectFields?: number;\n /** Maximum items in any input array. */\n readonly maxArrayLength?: number;\n /** Maximum template source length. */\n readonly maxTemplateLength?: number;\n /** Maximum parsed template references. */\n readonly maxTemplateTokens?: number;\n};\n\n/** Options for parsing a portable generator definition. */\nexport type ParseDefinitionOptions = {\n readonly registry: Pick<\n GeneratorRegistry | GeneratorRegistrySnapshot,\n \"lookup\"\n >;\n readonly limits?: ParseLimits;\n};\n\n/** Options for parsing a versioned generator document. */\nexport type ParseDocumentOptions = ParseDefinitionOptions;\n\n/** The success-or-failure result returned by `safeParseDefinition`. */\nexport type DefinitionParseResult =\n | { readonly success: true; readonly value: ParsedGeneratorDefinition }\n | { readonly success: false; readonly issues: readonly ConstructaError[] };\n\n/** The success-or-failure result returned by `safeParseDocument`. */\nexport type DocumentParseResult =\n | {\n readonly success: true;\n readonly value: import(\"constructa-schema\").GeneratorDocumentV1;\n }\n | { readonly success: false; readonly issues: readonly ConstructaError[] };\n\n/** Parses untrusted runtime definition data without executing generator code. */\nexport function parseDefinition(\n value: unknown,\n options: ParseDefinitionOptions,\n): ParsedGeneratorDefinition {\n return parseDefinitionAtPath(value, [], options.registry, options.limits);\n}\n\nfunction parseDefinitionAtPath(\n value: unknown,\n path: ValidationPath,\n registry: ParseDefinitionOptions[\"registry\"],\n limits?: ParseLimits,\n): ParsedGeneratorDefinition {\n const result = parseRuntimeDefinition(value, path, { registry, limits });\n if (result.success) return result.value;\n throw result.issues[0];\n}\n\nexport function safeParseDefinition(\n value: unknown,\n options: ParseDefinitionOptions,\n): DefinitionParseResult {\n return parseRuntimeDefinition(value, [], options);\n}\n\n/** Parses a versioned document and its root definition through the same pipeline. */\nexport function parseDocument(\n value: unknown,\n options: ParseDocumentOptions,\n): import(\"constructa-schema\").GeneratorDocumentV1 {\n const result = safeParseDocument(value, options);\n if (result.success) return result.value;\n throw result.issues[0];\n}\n\nexport function safeParseDocument(\n value: unknown,\n options: ParseDocumentOptions,\n): DocumentParseResult {\n const limits = resolveParseLimits(options);\n const documentIssues = validationIssuesToErrors(\n validateDocumentSafely(value),\n [],\n limits.maxIssues,\n );\n if (documentIssues.length > 0)\n return { success: false, issues: documentIssues };\n\n // Schema parsing is now safe because validation has rejected hostile shapes.\n const document = parseSchemaDocument(value);\n const definition = parseRuntimeDefinition(\n document.definition,\n [\"definition\"],\n options,\n );\n return definition.success\n ? { success: true, value: document }\n : { success: false, issues: definition.issues };\n}\n\n/** A generator type and version required by an implementation. */\nexport type GeneratorDependency = {\n readonly typeId: string;\n readonly path: ValidationPath;\n};\n\ndeclare const parsedGeneratorDefinition: unique symbol;\n\n/** A runtime-validated definition accepted by an executor without revalidation. */\n/** A generator definition already validated against a registry. */\nexport type ParsedGeneratorDefinition = GeneratorDefinition & {\n readonly [parsedGeneratorDefinition]: true;\n};\n\nconst parsedDefinitions = new WeakSet<object>();\n\n/** A trusted implementation of one portable generator type. */\nexport type GeneratorImplementation<\n Definition extends GeneratorDefinition<Output>,\n Output,\n> = {\n readonly type: string;\n readonly version: number;\n readonly validateDefinition: (\n definition: unknown,\n ) => readonly ValidationIssue[];\n readonly analyzeDependencies?: (\n definition: Definition,\n ) => readonly GeneratorDependency[];\n /** Declares object-local value references used by this definition. */\n readonly analyzeValueDependencies?: (\n definition: Definition,\n ) => readonly ValueDependency[];\n readonly generate: (input: {\n readonly definition: Definition;\n readonly context: GenerationContext;\n }) => Output;\n};\n\n/** A registry entry for one generator type. */\nexport type RegisteredGenerator = {\n readonly type: string;\n readonly version: number;\n};\n\n/** An immutable point-in-time view of a generator registry. */\nexport type GeneratorRegistrySnapshot = {\n readonly generators: readonly RegisteredGenerator[];\n readonly lookup: (\n type: string,\n path?: ValidationPath,\n ) => GeneratorImplementation<GeneratorDefinition, unknown>;\n};\n\n/** A mutable registry of trusted generator implementations. */\nexport type GeneratorRegistry = {\n register: <Definition extends GeneratorDefinition<Output>, Output>(\n implementation: GeneratorImplementation<Definition, Output>,\n ) => void;\n replace: <Definition extends GeneratorDefinition<Output>, Output>(\n implementation: GeneratorImplementation<Definition, Output>,\n ) => void;\n lookup: (\n type: string,\n path?: ValidationPath,\n ) => GeneratorImplementation<GeneratorDefinition, unknown>;\n snapshot: () => GeneratorRegistrySnapshot;\n};\n\nconst RESERVED_GENERATOR_TYPE_IDS = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/** Creates advanced registry infrastructure. Normal factories do not require it. */\nexport function createRegistry(): GeneratorRegistry {\n const implementations = new Map<\n string,\n GeneratorImplementation<GeneratorDefinition, unknown>\n >();\n\n return {\n register(implementation) {\n assertRegistryImplementation(implementation);\n if (implementations.has(implementation.type)) {\n throw registryError(\n \"DUPLICATE_GENERATOR\",\n [\"type\"],\n `A generator with type \"${implementation.type}\" is already registered.`,\n );\n }\n implementations.set(\n implementation.type,\n freezeImplementation(\n implementation,\n ) as unknown as GeneratorImplementation<GeneratorDefinition, unknown>,\n );\n },\n replace(implementation) {\n assertRegistryImplementation(implementation);\n if (!implementations.has(implementation.type)) {\n throw registryError(\n \"UNKNOWN_GENERATOR\",\n [\"type\"],\n `No generator with type \"${implementation.type}\" is registered.`,\n );\n }\n implementations.set(\n implementation.type,\n freezeImplementation(\n implementation,\n ) as unknown as GeneratorImplementation<GeneratorDefinition, unknown>,\n );\n },\n lookup(type, path = []) {\n return lookupImplementation(implementations, type, path);\n },\n snapshot() {\n return createRegistrySnapshot(implementations);\n },\n };\n}\n\n/**\n * Creates an advanced single-value executor over an immutable registry\n * snapshot. Normal applications will receive this behavior through the SDK.\n */\nexport function createExecutor(\n registry: GeneratorRegistry | GeneratorRegistrySnapshot,\n): Executor {\n const snapshot = createExecutionSnapshot(registry);\n\n return Object.freeze({\n generate<Definition extends GeneratorDefinition>(\n definition: Definition,\n options?: ExecutionOptions,\n ): import(\"constructa-schema\").Infer<Definition> {\n const execution = resolveExecutionOptions(options);\n const parsed = parsedDefinitions.has(definition)\n ? definition\n : parseDefinition(definition, { registry: snapshot });\n return executeParsedDefinition(parsed, [], 0, {\n snapshot,\n ...execution,\n }) as import(\"constructa-schema\").Infer<Definition>;\n },\n });\n}\n\ntype ExecutionState = {\n readonly snapshot: GeneratorRegistrySnapshot;\n readonly random: RandomSource;\n readonly maxDepth: number;\n readonly signal?: AbortSignal;\n readonly deadline?: number;\n};\n\nfunction executeParsedDefinition(\n definition: GeneratorDefinition,\n path: ValidationPath,\n depth: number,\n state: ExecutionState,\n references: ReferenceResolver = unavailableReferenceResolver(path),\n): unknown {\n assertExecutionActive(state, path);\n const implementation = state.snapshot.lookup(definition.type, path);\n analyzeGeneratorDependencies(\n implementation,\n definition,\n state.snapshot,\n path,\n );\n const context = createGenerationContext({\n random: state.random,\n path,\n references,\n createObjectScope() {\n return createObjectGenerationScope(\n path,\n (child, pathSegment, scopeReferences) => {\n assertChildPathSegment(pathSegment, path);\n const childPath = [...path, pathSegment];\n if (depth >= state.maxDepth) {\n throw new ConstructaError({\n kind: \"execution\",\n code: \"MAX_EXECUTION_DEPTH\",\n path: childPath,\n message: \"Child execution exceeds the configured maximum depth.\",\n });\n }\n const parsed = parseDefinitionAtPath(\n child,\n childPath,\n state.snapshot,\n );\n return executeParsedDefinition(\n parsed,\n childPath,\n depth + 1,\n state,\n scopeReferences,\n );\n },\n );\n },\n analyzeChildValueDependencies(child, pathSegment) {\n assertChildPathSegment(pathSegment, path);\n const childPath = [...path, pathSegment];\n const parsed = parseDefinitionAtPath(child, childPath, state.snapshot);\n const childImplementation = state.snapshot.lookup(parsed.type, childPath);\n return analyzeValueDependencies(childImplementation, parsed, childPath);\n },\n executeChild<Output>(\n child: GeneratorDefinition<Output>,\n pathSegment: ValidationPathSegment,\n ): Output {\n assertChildPathSegment(pathSegment, path);\n const childPath = [...path, pathSegment];\n if (depth >= state.maxDepth) {\n throw new ConstructaError({\n kind: \"execution\",\n code: \"MAX_EXECUTION_DEPTH\",\n path: childPath,\n message: \"Child execution exceeds the configured maximum depth.\",\n });\n }\n const parsed = parseDefinitionAtPath(child, childPath, state.snapshot);\n return executeParsedDefinition(\n parsed,\n childPath,\n depth + 1,\n state,\n references,\n ) as Output;\n },\n });\n return invokeValidatedGeneratorImplementation(\n implementation,\n definition,\n context,\n path,\n );\n}\n\nfunction createObjectGenerationScope(\n path: ValidationPath,\n executeChild: (\n definition: GeneratorDefinition,\n pathSegment: string,\n references: ReferenceResolver,\n ) => unknown,\n): ObjectGenerationScope {\n const completed = new Map<string, unknown>();\n const resolver: ReferenceResolver = Object.freeze({\n resolve(referencePath: ReferencePath): unknown {\n assertReferencePath(referencePath, path);\n const key = referencePathKey(referencePath);\n if (!completed.has(key)) {\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"REFERENCE_NOT_AVAILABLE\",\n path,\n message: \"The referenced object value has not completed.\",\n });\n }\n return completed.get(key);\n },\n });\n return Object.freeze({\n executeChild<Output>(\n definition: GeneratorDefinition<Output>,\n pathSegment: string,\n ): Output {\n const value = executeChild(definition, pathSegment, resolver) as Output;\n recordCompletedValue(completed, [pathSegment], value);\n return value;\n },\n });\n}\n\nfunction recordCompletedValue(\n completed: Map<string, unknown>,\n referencePath: readonly string[],\n value: unknown,\n visited = new WeakSet<object>(),\n): void {\n completed.set(referencePathKey(referencePath), value);\n if (typeof value !== \"object\" || value === null || visited.has(value)) return;\n visited.add(value);\n for (const [key, child] of Object.entries(value)) {\n recordCompletedValue(completed, [...referencePath, key], child, visited);\n }\n}\n\nfunction unavailableReferenceResolver(path: ValidationPath): ReferenceResolver {\n return Object.freeze({\n resolve(referencePath: ReferencePath): never {\n assertReferencePath(referencePath, path);\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"REFERENCE_RESOLUTION_UNAVAILABLE\",\n path,\n message:\n \"Reference resolution is available only inside an object field.\",\n });\n },\n });\n}\n\nfunction assertReferencePath(\n referencePath: ReferencePath,\n contextPath: ValidationPath,\n): void {\n if (\n !Array.isArray(referencePath) ||\n referencePath.length === 0 ||\n referencePath.some(\n (segment) => typeof segment !== \"string\" || segment.length === 0,\n )\n ) {\n throw contextError(\n \"INVALID_REFERENCE_PATH\",\n contextPath,\n \"Reference paths must contain one or more non-empty string segments.\",\n );\n }\n}\n\nfunction referencePathKey(path: readonly string[]): string {\n return JSON.stringify(path);\n}\n\nfunction createExecutionSnapshot(\n registry: GeneratorRegistry | GeneratorRegistrySnapshot,\n): GeneratorRegistrySnapshot {\n if (typeof registry !== \"object\" || registry === null) {\n throw contextError(\n \"INVALID_EXECUTOR_REGISTRY\",\n [\"registry\"],\n \"Executor requires a generator registry.\",\n );\n }\n if (typeof (registry as GeneratorRegistry).snapshot === \"function\") {\n return (registry as GeneratorRegistry).snapshot();\n }\n if (typeof (registry as GeneratorRegistrySnapshot).lookup === \"function\") {\n return registry as GeneratorRegistrySnapshot;\n }\n throw contextError(\n \"INVALID_EXECUTOR_REGISTRY\",\n [\"registry\"],\n \"Executor requires a generator registry.\",\n );\n}\n\nfunction resolveExecutionOptions(\n options: ExecutionOptions | undefined,\n): Omit<ExecutionState, \"snapshot\"> {\n if (options === undefined) {\n return { random: createDefaultRandomSource(), maxDepth: 64 };\n }\n if (typeof options !== \"object\" || options === null) {\n throw contextError(\n \"INVALID_EXECUTION_OPTIONS\",\n [],\n \"Execution options must be an object.\",\n );\n }\n if (options.seed !== undefined && options.random !== undefined) {\n throw contextError(\n \"CONFLICTING_RANDOM_OPTIONS\",\n [\"seed\"],\n \"seed and random cannot be supplied together.\",\n );\n }\n const maxDepth = options.maxDepth ?? 64;\n if (!Number.isSafeInteger(maxDepth) || maxDepth < 0) {\n throw contextError(\n \"INVALID_EXECUTION_OPTIONS\",\n [\"maxDepth\"],\n \"maxDepth must be a non-negative safe integer.\",\n );\n }\n if (options.signal !== undefined && typeof options.signal !== \"object\") {\n throw contextError(\n \"INVALID_EXECUTION_OPTIONS\",\n [\"signal\"],\n \"signal must be an AbortSignal when supplied.\",\n );\n }\n if (\n options.deadline !== undefined &&\n (!Number.isFinite(options.deadline) || options.deadline < 0)\n ) {\n throw contextError(\n \"INVALID_EXECUTION_OPTIONS\",\n [\"deadline\"],\n \"deadline must be a non-negative finite UTC epoch time.\",\n );\n }\n const random =\n options.seed !== undefined\n ? createSeededRandom(options.seed)\n : options.random !== undefined\n ? createRandomSource(options.random)\n : createDefaultRandomSource();\n return {\n random,\n maxDepth,\n signal: options.signal,\n deadline: options.deadline,\n };\n}\n\nfunction assertExecutionActive(\n state: ExecutionState,\n path: ValidationPath,\n): void {\n if (state.signal?.aborted) {\n throw new ConstructaError({\n kind: \"execution\",\n code: \"EXECUTION_ABORTED\",\n path,\n message: \"Generator execution was aborted.\",\n });\n }\n if (state.deadline !== undefined && Date.now() >= state.deadline) {\n throw new ConstructaError({\n kind: \"execution\",\n code: \"EXECUTION_DEADLINE_EXCEEDED\",\n path,\n message: \"Generator execution exceeded its deadline.\",\n });\n }\n}\n\nfunction analyzeGeneratorDependencies(\n implementation: GeneratorImplementation<GeneratorDefinition, unknown>,\n definition: GeneratorDefinition,\n registry: GeneratorRegistrySnapshot,\n path: ValidationPath,\n): void {\n if (implementation.analyzeDependencies === undefined) return;\n let dependencies: readonly GeneratorDependency[];\n try {\n dependencies = implementation.analyzeDependencies(definition);\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"dependency\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message: \"Generator dependency analysis failed.\",\n });\n }\n if (!Array.isArray(dependencies)) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message: \"Generator dependency analysis returned an invalid result.\",\n });\n }\n for (const dependency of dependencies) {\n if (!isGeneratorDependency(dependency)) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message:\n \"Generator dependency analysis returned an invalid dependency.\",\n });\n }\n registry.lookup(dependency.typeId, [...path, ...dependency.path]);\n }\n}\n\nfunction analyzeValueDependencies(\n implementation: GeneratorImplementation<GeneratorDefinition, unknown>,\n definition: GeneratorDefinition,\n path: ValidationPath,\n): readonly ValueDependency[] {\n if (implementation.analyzeValueDependencies === undefined) return [];\n let dependencies: readonly ValueDependency[];\n try {\n dependencies = implementation.analyzeValueDependencies(definition);\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"dependency\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message: \"Value dependency analysis failed.\",\n });\n }\n if (!Array.isArray(dependencies) || !dependencies.every(isValueDependency)) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message: \"Value dependency analysis returned an invalid result.\",\n });\n }\n return Object.freeze(\n dependencies.map((dependency) =>\n Object.freeze({ path: Object.freeze([...dependency.path]) }),\n ),\n );\n}\n\nfunction isGeneratorDependency(value: unknown): value is GeneratorDependency {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as GeneratorDependency).typeId === \"string\" &&\n Array.isArray((value as GeneratorDependency).path) &&\n (value as GeneratorDependency).path.every(\n (segment) => typeof segment === \"string\" || Number.isSafeInteger(segment),\n )\n );\n}\n\nfunction isValueDependency(value: unknown): value is ValueDependency {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Array.isArray((value as ValueDependency).path) &&\n (value as ValueDependency).path.length > 0 &&\n (value as ValueDependency).path.every(\n (segment) => typeof segment === \"string\" && segment.length > 0,\n )\n );\n}\n\nfunction isCompositeDependencyNode(\n value: unknown,\n): value is CompositeDependencyNode {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Array.isArray((value as CompositeDependencyNode).fieldPath) &&\n (value as CompositeDependencyNode).fieldPath.length === 1 &&\n typeof (value as CompositeDependencyNode).fieldPath[0] === \"string\" &&\n Array.isArray((value as CompositeDependencyNode).dependencies) &&\n (value as CompositeDependencyNode).dependencies.every(isValueDependency)\n );\n}\n\nfunction invokeValidatedGeneratorImplementation(\n implementation: GeneratorImplementation<GeneratorDefinition, unknown>,\n definition: GeneratorDefinition,\n context: GenerationContext,\n path: ValidationPath,\n): unknown {\n try {\n return implementation.generate({ definition, context });\n } catch (cause) {\n if (cause instanceof ConstructaError) {\n return throwWithExecutionPath(cause, path);\n }\n throw normalizeConstructaError(cause, {\n kind: \"execution\",\n code: \"EXECUTION_FAILED\",\n path,\n message: \"Generator execution failed.\",\n });\n }\n}\n\nfunction throwWithExecutionPath(\n error: ConstructaError,\n path: ValidationPath,\n): never {\n if (path.length === 0 || startsWithPath(error.path, path)) throw error;\n throw new ConstructaError({\n kind: error.kind,\n code: error.code,\n path: [...path, ...error.path],\n message: error.message,\n details: error.details,\n });\n}\n\nfunction startsWithPath(path: ValidationPath, prefix: ValidationPath): boolean {\n return prefix.every((segment, index) => path[index] === segment);\n}\n\n/**\n * Defines a trusted, developer-authored generator implementation. This API has\n * no dependency on a particular validation library.\n */\nexport function defineGenerator<\n const Definition extends GeneratorDefinition<Output>,\n Output,\n>(\n implementation: GeneratorImplementation<Definition, Output>,\n): GeneratorImplementation<Definition, Output> {\n assertGeneratorImplementation(implementation);\n return implementation;\n}\n\n/** Builds a portable definition while preserving literal fields and output inference. */\nexport function createGeneratorDefinition<\n Output,\n const Definition extends GeneratorDefinition<Output>,\n>(definition: Definition): Definition {\n assertGeneratorDefinition(definition);\n return definition;\n}\n\n/**\n * Invokes one validated implementation. Registry lookup and dispatch are added\n * later; this function keeps validation and execution failure normalization in\n * the same shared contract today.\n */\nexport function invokeGeneratorImplementation<\n Definition extends GeneratorDefinition<Output>,\n Output,\n>(\n implementation: GeneratorImplementation<Definition, Output>,\n input: {\n readonly definition: Definition;\n readonly context: GenerationContext;\n readonly path?: ValidationPath;\n },\n): Output {\n const path = input.path ?? [];\n let issues: readonly ValidationIssue[];\n\n try {\n issues = implementation.validateDefinition(input.definition);\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"configuration\",\n code: \"INVALID_CONFIGURATION\",\n path,\n message: \"Generator definition validation failed.\",\n });\n }\n\n if (issues.length > 0) {\n const [issue] = issues;\n if (issue !== undefined) {\n throw new ConstructaError({\n kind: \"configuration\",\n code: errorCodeForValidationIssue(issue.code),\n path: [...path, ...issue.path],\n message: issue.message,\n details: { issueCode: issue.code },\n });\n }\n\n throw new ConstructaError({\n kind: \"system\",\n code: \"EXECUTION_FAILED\",\n path,\n message: \"Generator validation returned an invalid result.\",\n });\n }\n\n try {\n return implementation.generate({\n definition: input.definition,\n context: input.context,\n });\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"execution\",\n code: \"EXECUTION_FAILED\",\n path,\n message: \"Generator execution failed.\",\n });\n }\n}\n\nconst DEFAULT_PARSE_LIMITS = Object.freeze({\n maxDepth: 64,\n maxIssues: 100,\n maxNodes: 10_000,\n maxBytes: 1_000_000,\n maxObjectFields: 10_000,\n maxArrayLength: 10_000,\n maxTemplateLength: 100_000,\n maxTemplateTokens: 10_000,\n});\n\ntype ResolvedParseLimits = {\n readonly maxDepth: number;\n readonly maxIssues: number;\n readonly maxNodes: number;\n readonly maxBytes: number;\n readonly maxObjectFields: number;\n readonly maxArrayLength: number;\n readonly maxTemplateLength: number;\n readonly maxTemplateTokens: number;\n};\n\nfunction parseRuntimeDefinition(\n value: unknown,\n path: ValidationPath,\n options: ParseDefinitionOptions,\n): DefinitionParseResult {\n const limits = resolveParseLimits(options);\n const schemaIssues = validationIssuesToErrors(\n validateDefinitionSafely(value, path),\n path,\n limits.maxIssues,\n );\n if (schemaIssues.length > 0) return { success: false, issues: schemaIssues };\n const limitIssue = findInputLimitIssue(value, path, limits);\n if (limitIssue !== undefined) return { success: false, issues: [limitIssue] };\n\n const issues: ConstructaError[] = [];\n const visited = new Set<object>();\n visitRuntimeDefinition(\n value as GeneratorDefinition,\n path,\n 0,\n options.registry,\n limits,\n visited,\n issues,\n );\n return issues.length === 0\n ? {\n success: true,\n value: markParsedDefinitions(visited, value as GeneratorDefinition),\n }\n : { success: false, issues: Object.freeze(issues) };\n}\n\nfunction markParsedDefinitions(\n definitions: ReadonlySet<object>,\n definition: GeneratorDefinition,\n): ParsedGeneratorDefinition {\n for (const parsed of definitions) parsedDefinitions.add(parsed);\n return definition as ParsedGeneratorDefinition;\n}\n\nfunction visitRuntimeDefinition(\n definition: GeneratorDefinition,\n path: ValidationPath,\n depth: number,\n registry: ParseDefinitionOptions[\"registry\"],\n limits: ResolvedParseLimits,\n visited: Set<object>,\n issues: ConstructaError[],\n): void {\n if (issues.length >= limits.maxIssues) return;\n if (depth > limits.maxDepth) {\n addParseIssue(\n issues,\n limits,\n \"PARSE_DEPTH_LIMIT\",\n path,\n \"Generator definition exceeds the maximum nesting depth.\",\n );\n return;\n }\n if (visited.size >= limits.maxNodes) {\n addParseIssue(\n issues,\n limits,\n \"PARSE_NODE_LIMIT\",\n path,\n \"Generator definition exceeds the maximum node count.\",\n );\n return;\n }\n visited.add(definition);\n\n let implementation: GeneratorImplementation<GeneratorDefinition, unknown>;\n try {\n implementation = registry.lookup(definition.type, path);\n } catch (cause) {\n const error = normalizeConstructaError(cause, {\n kind: \"dependency\",\n code: \"UNKNOWN_GENERATOR\",\n path: [...path, \"type\"],\n message: \"Generator type could not be resolved.\",\n });\n addExistingParseIssue(issues, limits, error);\n return;\n }\n\n let validationIssues: readonly ValidationIssue[];\n try {\n validationIssues = implementation.validateDefinition(definition);\n } catch (cause) {\n addExistingParseIssue(\n issues,\n limits,\n normalizeConstructaError(cause, {\n kind: \"configuration\",\n code: \"INVALID_CONFIGURATION\",\n path,\n message: \"Generator definition validation failed.\",\n }),\n );\n return;\n }\n if (!Array.isArray(validationIssues)) {\n addParseIssue(\n issues,\n limits,\n \"INVALID_CONFIGURATION\",\n path,\n \"Generator definition validation returned an invalid result.\",\n \"system\",\n );\n return;\n }\n for (const issue of validationIssues) {\n if (!isValidationIssue(issue)) {\n addParseIssue(\n issues,\n limits,\n \"INVALID_CONFIGURATION\",\n path,\n \"Generator definition validation returned an invalid issue.\",\n \"system\",\n );\n return;\n }\n addParseIssue(\n issues,\n limits,\n errorCodeForValidationIssue(issue.code),\n [...path, ...issue.path],\n issue.message,\n );\n }\n\n // Configurations are portable JSON. Every embedded object with a generator\n // discriminator is another definition and must pass the same pipeline.\n for (const [key, child] of Object.entries(definition)) {\n if (key !== \"type\")\n visitEmbeddedDefinitions(\n child,\n [...path, key],\n depth + 1,\n registry,\n limits,\n visited,\n issues,\n );\n if (issues.length >= limits.maxIssues) return;\n }\n}\n\nfunction visitEmbeddedDefinitions(\n value: unknown,\n path: ValidationPath,\n depth: number,\n registry: ParseDefinitionOptions[\"registry\"],\n limits: ResolvedParseLimits,\n visited: Set<object>,\n issues: ConstructaError[],\n): void {\n if (\n issues.length >= limits.maxIssues ||\n value === null ||\n typeof value !== \"object\"\n )\n return;\n if (Array.isArray(value)) {\n for (let index = 0; index < value.length; index += 1) {\n visitEmbeddedDefinitions(\n value[index],\n [...path, index],\n depth,\n registry,\n limits,\n visited,\n issues,\n );\n if (issues.length >= limits.maxIssues) return;\n }\n return;\n }\n if (Object.hasOwn(value, \"type\")) {\n visitRuntimeDefinition(\n value as GeneratorDefinition,\n path,\n depth,\n registry,\n limits,\n visited,\n issues,\n );\n return;\n }\n for (const [key, child] of Object.entries(value)) {\n visitEmbeddedDefinitions(\n child,\n [...path, key],\n depth,\n registry,\n limits,\n visited,\n issues,\n );\n if (issues.length >= limits.maxIssues) return;\n }\n}\n\nfunction resolveParseLimits(\n options: ParseDefinitionOptions,\n): ResolvedParseLimits {\n if (\n typeof options !== \"object\" ||\n options === null ||\n typeof options.registry !== \"object\" ||\n options.registry === null ||\n typeof options.registry.lookup !== \"function\"\n ) {\n throw contextError(\n \"INVALID_PARSE_OPTIONS\",\n [],\n \"Parsing requires a registry with a lookup function.\",\n );\n }\n const supplied = options.limits ?? {};\n const resolved = {\n maxDepth: supplied.maxDepth ?? DEFAULT_PARSE_LIMITS.maxDepth,\n maxIssues: supplied.maxIssues ?? DEFAULT_PARSE_LIMITS.maxIssues,\n maxNodes: supplied.maxNodes ?? DEFAULT_PARSE_LIMITS.maxNodes,\n maxBytes: supplied.maxBytes ?? DEFAULT_PARSE_LIMITS.maxBytes,\n maxObjectFields:\n supplied.maxObjectFields ?? DEFAULT_PARSE_LIMITS.maxObjectFields,\n maxArrayLength:\n supplied.maxArrayLength ?? DEFAULT_PARSE_LIMITS.maxArrayLength,\n maxTemplateLength:\n supplied.maxTemplateLength ?? DEFAULT_PARSE_LIMITS.maxTemplateLength,\n maxTemplateTokens:\n supplied.maxTemplateTokens ?? DEFAULT_PARSE_LIMITS.maxTemplateTokens,\n };\n for (const [name, value] of Object.entries(resolved)) {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw contextError(\n \"INVALID_PARSE_LIMITS\",\n [\"limits\", name],\n `${name} must be a positive safe integer.`,\n );\n }\n }\n return resolved;\n}\n\nfunction findInputLimitIssue(\n value: unknown,\n path: ValidationPath,\n limits: ResolvedParseLimits,\n): ConstructaError | undefined {\n const bytes = new TextEncoder().encode(JSON.stringify(value)).length;\n if (bytes > limits.maxBytes) {\n return inputLimitError(\n \"PARSE_BYTE_LIMIT\",\n path,\n \"Definition exceeds the maximum serialized byte size.\",\n );\n }\n const visit = (\n candidate: unknown,\n candidatePath: ValidationPath,\n ): ConstructaError | undefined => {\n if (Array.isArray(candidate)) {\n if (candidate.length > limits.maxArrayLength) {\n return inputLimitError(\n \"PARSE_ARRAY_LIMIT\",\n candidatePath,\n \"Definition contains an array exceeding the configured maximum length.\",\n );\n }\n for (let index = 0; index < candidate.length; index += 1) {\n const issue = visit(candidate[index], [...candidatePath, index]);\n if (issue !== undefined) return issue;\n }\n return undefined;\n }\n if (typeof candidate !== \"object\" || candidate === null) return undefined;\n const record = candidate as Record<string, unknown>;\n const keys = Object.keys(record);\n if (keys.length > limits.maxObjectFields) {\n return inputLimitError(\n \"PARSE_OBJECT_FIELD_LIMIT\",\n candidatePath,\n \"Definition contains an object exceeding the configured maximum field count.\",\n );\n }\n if (record.type === \"template\" && typeof record.source === \"string\") {\n if (record.source.length > limits.maxTemplateLength) {\n return inputLimitError(\n \"PARSE_TEMPLATE_LENGTH_LIMIT\",\n [...candidatePath, \"source\"],\n \"Template source exceeds the configured maximum length.\",\n );\n }\n let tokenCount = 0;\n try {\n tokenCount = parseTemplateTokens(record.source).filter(\n (token) => token.type === \"reference\",\n ).length;\n } catch (_cause) {\n // The owning template implementation reports malformed syntax.\n }\n if (tokenCount > limits.maxTemplateTokens) {\n return inputLimitError(\n \"PARSE_TEMPLATE_TOKEN_LIMIT\",\n [...candidatePath, \"source\"],\n \"Template source exceeds the configured maximum reference count.\",\n );\n }\n }\n for (const key of keys) {\n const issue = visit(record[key], [...candidatePath, key]);\n if (issue !== undefined) return issue;\n }\n return undefined;\n };\n return visit(value, path);\n}\n\nfunction inputLimitError(\n code: string,\n path: ValidationPath,\n message: string,\n): ConstructaError {\n return new ConstructaError({\n kind: \"configuration\",\n code: code as Uppercase<string>,\n path,\n message,\n });\n}\n\nfunction validateDefinitionSafely(\n value: unknown,\n path: ValidationPath,\n): readonly ValidationIssue[] {\n try {\n return validateGeneratorDefinition(value, path);\n } catch (_cause) {\n return [\n {\n code: \"invalid_json_value\",\n path,\n message: \"Definition could not be safely inspected.\",\n },\n ];\n }\n}\n\nfunction validateDocumentSafely(value: unknown): readonly ValidationIssue[] {\n try {\n return validateDocument(value);\n } catch {\n return [\n {\n code: \"invalid_json_value\",\n path: [],\n message: \"Document could not be safely inspected.\",\n },\n ];\n }\n}\n\nfunction validationIssuesToErrors(\n issues: readonly ValidationIssue[],\n fallbackPath: ValidationPath,\n maxIssues = Number.POSITIVE_INFINITY,\n): ConstructaError[] {\n return issues.slice(0, maxIssues).map(\n (issue) =>\n new ConstructaError({\n kind: \"configuration\",\n code: isValidationIssue(issue)\n ? errorCodeForValidationIssue(issue.code)\n : \"INVALID_CONFIGURATION\",\n path: isValidationIssue(issue) ? issue.path : fallbackPath,\n message: isValidationIssue(issue)\n ? issue.message\n : \"Validation returned an invalid issue.\",\n details: isValidationIssue(issue)\n ? { issueCode: issue.code }\n : undefined,\n }),\n );\n}\n\nfunction errorCodeForValidationIssue(code: string): Uppercase<string> {\n const reservedCodes: Record<string, Uppercase<string>> = {\n empty_choice: \"EMPTY_CHOICE\",\n invalid_length: \"INVALID_LENGTH\",\n invalid_range: \"INVALID_RANGE\",\n invalid_template_token: \"INVALID_TEMPLATE_TOKEN\",\n };\n return reservedCodes[code] ?? \"INVALID_CONFIGURATION\";\n}\n\nfunction isValidationIssue(value: unknown): value is ValidationIssue {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ValidationIssue).code === \"string\" &&\n typeof (value as ValidationIssue).message === \"string\" &&\n Array.isArray((value as ValidationIssue).path)\n );\n}\n\nfunction addParseIssue(\n issues: ConstructaError[],\n limits: ResolvedParseLimits,\n code: string,\n path: ValidationPath,\n message: string,\n kind: \"configuration\" | \"system\" = \"configuration\",\n): void {\n if (issues.length < limits.maxIssues)\n issues.push(\n new ConstructaError({\n kind,\n code: code as Uppercase<string>,\n path,\n message,\n }),\n );\n}\n\nfunction addExistingParseIssue(\n issues: ConstructaError[],\n limits: ResolvedParseLimits,\n error: ConstructaError,\n): void {\n if (issues.length < limits.maxIssues) issues.push(error);\n}\n\nfunction assertGeneratorImplementation(implementation: {\n readonly type: string;\n readonly version: number;\n readonly validateDefinition: unknown;\n readonly analyzeDependencies?: unknown;\n readonly generate: unknown;\n}): void {\n if (!isStableTypeId(implementation.type)) {\n throw new TypeError(\"generator type must be a stable lowercase identifier\");\n }\n if (\n !Number.isSafeInteger(implementation.version) ||\n implementation.version < 1\n ) {\n throw new TypeError(\"generator version must be a positive safe integer\");\n }\n if (typeof implementation.validateDefinition !== \"function\") {\n throw new TypeError(\"validateDefinition must be a function\");\n }\n if (typeof implementation.generate !== \"function\") {\n throw new TypeError(\"generate must be a function\");\n }\n if (\n implementation.analyzeDependencies !== undefined &&\n typeof implementation.analyzeDependencies !== \"function\"\n ) {\n throw new TypeError(\"analyzeDependencies must be a function when present\");\n }\n}\n\nfunction assertRegistryImplementation(implementation: {\n readonly type: string;\n readonly version: number;\n readonly validateDefinition: unknown;\n readonly analyzeDependencies?: unknown;\n readonly generate: unknown;\n}): void {\n try {\n assertGeneratorImplementation(implementation);\n } catch {\n throw registryError(\n \"INVALID_CONFIGURATION\",\n [\"implementation\"],\n \"Generator implementation is invalid.\",\n );\n }\n if (RESERVED_GENERATOR_TYPE_IDS.has(implementation.type)) {\n throw registryError(\n \"INVALID_CONFIGURATION\",\n [\"type\"],\n `Generator type \"${implementation.type}\" is reserved.`,\n );\n }\n}\n\nfunction freezeImplementation<\n Definition extends GeneratorDefinition<Output>,\n Output,\n>(\n implementation: GeneratorImplementation<Definition, Output>,\n): GeneratorImplementation<Definition, Output> {\n return Object.freeze({ ...implementation });\n}\n\nfunction createRegistrySnapshot(\n implementations: ReadonlyMap<\n string,\n GeneratorImplementation<GeneratorDefinition, unknown>\n >,\n): GeneratorRegistrySnapshot {\n const snapshotImplementations = new Map(implementations);\n const generators = [...snapshotImplementations.values()]\n .map(({ type, version }) => Object.freeze({ type, version }))\n .sort((left, right) => left.type.localeCompare(right.type));\n\n return Object.freeze({\n generators: Object.freeze(generators),\n lookup(type: string, path: ValidationPath = []) {\n return lookupImplementation(snapshotImplementations, type, path);\n },\n });\n}\n\nfunction lookupImplementation(\n implementations: ReadonlyMap<\n string,\n GeneratorImplementation<GeneratorDefinition, unknown>\n >,\n type: string,\n path: ValidationPath,\n): GeneratorImplementation<GeneratorDefinition, unknown> {\n const implementation = implementations.get(type);\n if (implementation !== undefined) return implementation;\n\n const registeredTypes = [...implementations.keys()].sort((left, right) =>\n left.localeCompare(right),\n );\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"UNKNOWN_GENERATOR\",\n path: [...path, \"type\"],\n message: `No generator with type \"${type}\" is registered.`,\n details: { registeredTypes },\n });\n}\n\nfunction registryError(\n code: \"DUPLICATE_GENERATOR\" | \"INVALID_CONFIGURATION\" | \"UNKNOWN_GENERATOR\",\n path: ValidationPath,\n message: string,\n): ConstructaError {\n return new ConstructaError({ kind: \"configuration\", code, path, message });\n}\n\nfunction assertRandomSourceAdapter(adapter: RandomSourceAdapter): void {\n if (\n typeof adapter !== \"object\" ||\n adapter === null ||\n typeof adapter.float !== \"function\" ||\n typeof adapter.integer !== \"function\" ||\n typeof adapter.bytes !== \"function\"\n ) {\n throw invalidRandomSource(\n \"A random source must provide float(), integer(), and bytes() methods.\",\n );\n }\n}\n\nfunction assertRandomLength(value: number, name: string): void {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw invalidRandomSource(`${name} must be a positive safe integer.`);\n }\n}\n\nfunction assertByteLength(length: number): void {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw invalidRandomSource(\"length must be a non-negative safe integer.\");\n }\n}\n\nfunction invalidRandomSource(message: string): ConstructaError {\n return new ConstructaError({\n kind: \"system\",\n code: \"INVALID_RANDOM_SOURCE\",\n path: [\"random\"],\n message,\n });\n}\n\nfunction assertContextPath(path: ValidationPath): void {\n for (const segment of path) assertContextPathSegment(segment);\n}\n\nfunction assertContextPathSegment(\n segment: unknown,\n): asserts segment is ValidationPathSegment {\n if (\n typeof segment !== \"string\" &&\n (!Number.isSafeInteger(segment) || typeof segment !== \"number\")\n ) {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [\"path\"],\n \"Context path segments must be strings or safe integers.\",\n );\n }\n}\n\nfunction assertChildPathSegment(\n segment: unknown,\n path: ValidationPath,\n): asserts segment is ValidationPathSegment {\n if (\n typeof segment !== \"string\" &&\n (typeof segment !== \"number\" || !Number.isSafeInteger(segment))\n ) {\n throw contextError(\n \"INVALID_CHILD_PATH\",\n path,\n \"Child path segments must be strings or safe integers.\",\n );\n }\n}\n\nfunction contextError(\n code: string,\n path: ValidationPath,\n message: string,\n): ConstructaError {\n return new ConstructaError({\n kind: \"configuration\",\n code: code as Uppercase<string>,\n path,\n message,\n });\n}\n\nfunction hashSeed(seed: string): number {\n let hash = 0x811c_9dc5;\n for (const byte of new TextEncoder().encode(seed)) {\n hash = Math.imul(hash ^ byte, 0x0100_0193) >>> 0;\n }\n return hash;\n}\n\nfunction isStableTypeId(value: string): boolean {\n return /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u.test(value);\n}\n"],"mappings":";;AAkCA,MAAM,yCAAyB,IAAI,QAAgB;;AA+BnD,MAAa,0BAA0B;;AAEvC,MAAa,kCAAkC;AAkB/C,MAAM,yBAA+C,OAAO,OAAO;CACjE,WAAW;CACX,SAAA;AACF,CAAC;;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": "The UI-agnostic Constructa generator execution engine.",
|
|
5
5
|
"private": false,
|
|
6
6
|
"license": "MIT",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"access": "public"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"constructa-schema": "2.4.
|
|
29
|
+
"constructa-schema": "2.4.1"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"typescript": "^6.0.3",
|