@pbuilder/sdk 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +69 -3
  2. package/dist/acl/irwire/stdio-engine-client.d.ts +1 -1
  3. package/dist/acl/irwire/stdio-engine-client.js +3 -2
  4. package/dist/bin/pbuilder-codegen.js +59 -1
  5. package/dist/bin/pbuilder-conformance.d.ts +2 -0
  6. package/dist/bin/pbuilder-conformance.js +45 -0
  7. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.d.ts +12 -3
  8. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.js +23 -9
  9. package/dist/bounded-contexts/authoring/application/usecases/scaffold/expander.js +4 -4
  10. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.d.ts +2 -1
  11. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.js +56 -6
  12. package/dist/bounded-contexts/authoring/domain/entities/dialect-handle.d.ts +2 -1
  13. package/dist/bounded-contexts/authoring/domain/entities/dialect-handle.js +108 -30
  14. package/dist/bounded-contexts/authoring/domain/ports/engine-client.d.ts +1 -1
  15. package/dist/bounded-contexts/authoring/domain/services/define-dialect.d.ts +48 -10
  16. package/dist/bounded-contexts/authoring/domain/services/define-dialect.js +37 -9
  17. package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.d.ts +1 -0
  18. package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.js +4 -0
  19. package/dist/bounded-contexts/authoring/domain/services/schema/schema-parse.d.ts +3 -2
  20. package/dist/bounded-contexts/authoring/domain/services/schema/schema-parse.js +46 -4
  21. package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.d.ts +16 -1
  22. package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.js +125 -0
  23. package/dist/bounded-contexts/authoring/domain/valueobjects/authoring-error.d.ts +3 -2
  24. package/dist/bounded-contexts/authoring/domain/valueobjects/authoring-error.js +2 -0
  25. package/dist/bounded-contexts/authoring/domain/valueobjects/schema-model.d.ts +17 -0
  26. package/dist/bounded-contexts/authoring/domain/valueobjects/schema-model.js +1 -0
  27. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.d.ts +1 -0
  28. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.js +23 -0
  29. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.js +2 -2
  30. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.d.ts +8 -5
  31. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.js +7 -4
  32. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.d.ts +1 -1
  33. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.js +20 -7
  34. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.d.ts +20 -2
  35. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.js +19 -3
  36. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.d.ts +5 -0
  37. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.js +89 -20
  38. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.js +2 -2
  39. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/ast.d.ts +2 -0
  40. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/ast.js +4 -0
  41. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.js +3 -3
  42. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/ast.d.ts +2 -0
  43. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/ast.js +4 -0
  44. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.js +2 -2
  45. package/dist/bounded-contexts/authoring/testing/conformance/index.d.ts +10 -12
  46. package/dist/bounded-contexts/authoring/testing/conformance/index.js +17 -2
  47. package/dist/bounded-contexts/authoring/testing/conformance/run-package.d.ts +37 -0
  48. package/dist/bounded-contexts/authoring/testing/conformance/run-package.js +209 -0
  49. package/dist/bounded-contexts/authoring/testing/harness/index.d.ts +13 -4
  50. package/dist/bounded-contexts/authoring/testing/harness/index.js +10 -4
  51. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.d.ts +3 -0
  52. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.js +2 -0
  53. package/dist/bounded-contexts/runner-hosting/infrastructure/in/runner.js +69 -3
  54. package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.d.ts +24 -0
  55. package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.js +34 -1
  56. package/dist/conformance/index.d.ts +1 -0
  57. package/dist/conformance/index.js +1 -0
  58. package/dist/dialect/index.d.ts +2 -0
  59. package/dist/dialect/index.js +3 -0
  60. package/dist/runner-manifest.json +12 -12
  61. package/package.json +8 -2
@@ -6,7 +6,7 @@
6
6
  // module lives under src/core/**, is never a public subpath, and its shape is not
7
7
  // fitness-pinned. Only the PUBLIC `find(path)` signature and the `Handle<State, Ast, Ops>`
8
8
  // TYPE (define-dialect.ts) are frozen.
9
- import { currentRun } from "../services/run-context.js";
9
+ import { currentRun, getSessionAls } from "../services/run-context.js";
10
10
  import { dialectError, isContained } from "../valueobjects/dialect-error.js";
11
11
  // `.modify()`'s `fn` is typed `(ast: Ast) => void`, but TS's void-return compatibility lets an
12
12
  // author pass an async function anyway — this is the runtime check that catches that case.
@@ -96,6 +96,7 @@ class DialectHandleController {
96
96
  #dialectAst;
97
97
  #ops;
98
98
  #path;
99
+ #name;
99
100
  #live;
100
101
  #openDirective;
101
102
  #registered = false;
@@ -104,10 +105,28 @@ class DialectHandleController {
104
105
  // this to decide whether an op actually changed anything (REQ-TSD-08.4's zero-directive
105
106
  // no-op) — never re-derived from a print-after-parse (would cost a redundant print).
106
107
  #lastEmittedText;
107
- constructor(dialectAst, ops, path) {
108
+ // A-7: the Session, and its content version of #path, that #live reflects, own writes included.
109
+ #session;
110
+ #version;
111
+ // A-8: set once the handle re-parsed away from a tree, so a failing .modify() names the remedy.
112
+ #retired = false;
113
+ constructor(dialectAst, ops, path, name) {
108
114
  this.#dialectAst = dialectAst;
109
115
  this.#ops = ops;
110
116
  this.#path = path;
117
+ this.#name = name;
118
+ }
119
+ // A-16: a handle opened inside a run fails the run at its end even when no step follows.
120
+ // Outside a run there is no declared set yet, so the first step checks instead.
121
+ checkDeclaredInRun() {
122
+ if (this.#name !== undefined && getSessionAls().getStore() !== undefined)
123
+ this.#enqueue(() => { });
124
+ }
125
+ #assertDeclared(ctx) {
126
+ if (this.#name !== undefined && ctx.declaredDialects?.has(this.#name) !== true) {
127
+ throw dialectError(`the dialect "${this.#name}" is not declared in the Manifest of this schematic's library — ` +
128
+ `add it to the "dialects" section of its project-builder.json.`);
129
+ }
111
130
  }
112
131
  get ops() {
113
132
  return this.#ops;
@@ -134,6 +153,7 @@ class DialectHandleController {
134
153
  throw ctx.sessionFailure.reason;
135
154
  }
136
155
  try {
156
+ this.#assertDeclared(ctx);
137
157
  return await step();
138
158
  }
139
159
  catch (err) {
@@ -166,26 +186,48 @@ class DialectHandleController {
166
186
  this.#registered = true;
167
187
  currentRun().dialects.register({ settle: () => this.settle() });
168
188
  }
169
- async #ensureLive() {
170
- if (this.#live !== undefined)
171
- return;
189
+ // A-7: #live is a cache of the path's content, fresh while no other writer moved the path's
190
+ // content version since it was parsed. Callers loop `while (!#isFresh()) await #reparse()` and
191
+ // run the op in the same synchronous turn as the last check, so no write can land in between.
192
+ #isFresh() {
193
+ const { session } = currentRun();
194
+ return this.#live !== undefined && session === this.#session && session.versionOf(this.#path) === this.#version;
195
+ }
196
+ // The read flushes pending edits first; a version that moves while the read is in flight means
197
+ // the content read is already stale, so the caller's loop reads again.
198
+ async #reparse() {
172
199
  const { session } = currentRun();
200
+ const version = session.versionOf(this.#path);
173
201
  const content = await session.read(this.#path);
202
+ if (session.versionOf(this.#path) !== version)
203
+ return;
174
204
  if (content === undefined) {
175
205
  throw dialectError(`"${this.#path}" does not exist — create it first in this run`);
176
206
  }
207
+ let next;
177
208
  try {
178
- this.#live = this.#dialectAst.parse(content);
209
+ next = this.#dialectAst.parse(content);
179
210
  }
180
211
  catch {
181
212
  throw dialectError(`could not parse "${this.#path}"`);
182
213
  }
183
- astHandlePaths.set(this.#live, this.#path);
214
+ // The drained directive prints the AST it was built from; fix its content before retiring it.
215
+ if (this.#openDirective?.op === "modify")
216
+ void this.#openDirective.modify.content;
217
+ if (this.#live !== undefined) {
218
+ this.#dialectAst.retire?.(this.#live);
219
+ this.#retired = true;
220
+ }
221
+ this.#live = next;
222
+ astHandlePaths.set(next, this.#path);
184
223
  this.#lastEmittedText = content;
224
+ this.#openDirective = undefined;
225
+ this.#session = session;
226
+ this.#version = version;
185
227
  }
186
- #printContained() {
228
+ #printContained(ast = this.#live) {
187
229
  try {
188
- return this.#dialectAst.print(this.#live);
230
+ return this.#dialectAst.print(ast);
189
231
  }
190
232
  catch {
191
233
  throw dialectError(`could not print "${this.#path}"`);
@@ -224,6 +266,10 @@ class DialectHandleController {
224
266
  // instead of unconditionally re-registering a byte-identical directive.
225
267
  #ensureOpen() {
226
268
  const { session } = currentRun();
269
+ // An async op let another writer change the path; printing #live now would erase that write.
270
+ if (session.versionOf(this.#path) !== this.#version) {
271
+ throw dialectError(`"${this.#path}" changed while an op on it ran — await each op before another writer edits the file`);
272
+ }
227
273
  if (this.#hasOpenPendingDirective(session)) {
228
274
  return;
229
275
  }
@@ -236,8 +282,10 @@ class DialectHandleController {
236
282
  if (this.#printContained() === this.#lastEmittedText) {
237
283
  return;
238
284
  }
239
- this.#openDirective = lazyModifyDirective(this.#path, () => this.#printContained());
285
+ const live = this.#live;
286
+ this.#openDirective = lazyModifyDirective(this.#path, () => this.#printContained(live));
240
287
  session.buffer(this.#openDirective);
288
+ this.#version = session.versionOf(this.#path);
241
289
  }
242
290
  // Shared containment primitive (ADR-0037 amendment clause 1): runs `fn`, awaits a
243
291
  // thenable result INSIDE the try (so an async op's rejection is contained, never an
@@ -245,18 +293,23 @@ class DialectHandleController {
245
293
  // NEVER `message.startsWith`) — a caught error already carrying the brand (an author's
246
294
  // deliberate `dialectError` reject) is RETHROWN VERBATIM (REQ-DG-06.5, no double-wrap, no
247
295
  // `.cause`); any foreign error is wrapped fresh via `dialectError(foreignTail)`.
248
- async #invokeContained(fn, foreignTail) {
249
- try {
250
- const result = fn();
251
- if (isThenable(result)) {
252
- await result;
253
- }
254
- }
255
- catch (caught) {
296
+ //
297
+ // Synchronous for a synchronous `fn`, so an op and the #ensureOpen after it run in the turn of
298
+ // the freshness check (A-7); only a thenable result returns a promise.
299
+ #invokeContained(fn, foreignTail) {
300
+ const rethrow = (caught) => {
256
301
  if (isContained(caught))
257
302
  throw caught;
258
303
  throw dialectError(foreignTail);
304
+ };
305
+ let result;
306
+ try {
307
+ result = fn();
308
+ }
309
+ catch (caught) {
310
+ rethrow(caught);
259
311
  }
312
+ return isThenable(result) ? Promise.resolve(result).then(() => undefined, rethrow) : undefined;
260
313
  }
261
314
  // Chaining is the WRAPPER's job (createDialectHandle, below) — these return void; the
262
315
  // wrapper's dispatchers always return the public handle object, never `this` controller.
@@ -275,25 +328,30 @@ class DialectHandleController {
275
328
  // however many params the author did or didn't supply.
276
329
  runOp(fn, args, opName) {
277
330
  this.#enqueue(async () => {
278
- await this.#ensureLive();
279
- await this.#invokeContained(() => fn(this.#live, ...args), `${opName}() on "${this.#path}" threw`);
331
+ while (!this.#isFresh())
332
+ await this.#reparse();
333
+ const pending = this.#invokeContained(() => fn(this.#live, ...args), `${opName}() on "${this.#path}" threw`);
334
+ if (pending !== undefined)
335
+ await pending;
280
336
  this.#ensureOpen();
281
337
  });
282
338
  }
283
339
  // Sequenced on #tail like an op, but it never calls #ensureOpen: a query only reads the live
284
340
  // AST, so it registers no directive (#ensureLive's first read still drains, as for an op).
285
341
  // The print comparison is what keeps it read-only: a query that edits the AST would
286
- // otherwise smuggle its edit into the next op's directive.
287
- runQuery(fn, args, name) {
342
+ // otherwise smuggle its edit into the next op's directive. `.inspect()` runs through here too,
343
+ // under its own name and its own wording for a change.
344
+ runQuery(fn, args, name, changed = `${name}() is a query and must not change`) {
288
345
  return this.#chain(async () => {
289
- await this.#ensureLive();
346
+ while (!this.#isFresh())
347
+ await this.#reparse();
290
348
  const before = this.#printContained();
291
349
  let result;
292
350
  await this.#invokeContained(async () => {
293
351
  result = await fn(this.#live, ...args);
294
352
  }, `${name}() on "${this.#path}" threw`);
295
353
  if (this.#printContained() !== before) {
296
- throw dialectError(`${name}() is a query and must not change "${this.#path}"`);
354
+ throw dialectError(`${changed} "${this.#path}"`);
297
355
  }
298
356
  return result;
299
357
  });
@@ -306,8 +364,14 @@ class DialectHandleController {
306
364
  // resolve-after-delay's mutation may race the print.
307
365
  runModify(fn) {
308
366
  this.#enqueue(async () => {
309
- await this.#ensureLive();
310
- await this.#invokeContained(() => fn(this.#live), `modify() on "${this.#path}" threw`);
367
+ while (!this.#isFresh())
368
+ await this.#reparse();
369
+ const remedy = this.#retired
370
+ ? ` — if it uses a node kept from before "${this.#path}" was re-parsed, look the node up again inside .modify()`
371
+ : "";
372
+ const pending = this.#invokeContained(() => fn(this.#live), `modify() on "${this.#path}" threw${remedy}`);
373
+ if (pending !== undefined)
374
+ await pending;
311
375
  this.#ensureOpen();
312
376
  });
313
377
  }
@@ -330,10 +394,22 @@ class DialectHandleController {
330
394
  });
331
395
  }
332
396
  runRename(newName, opts) {
333
- this.#bufferDirective((factory) => factory.rename({ path: this.#path, newName, force: opts?.force }));
397
+ this.#relocate((factory) => factory.rename({ path: this.#path, newName, force: opts?.force }));
334
398
  }
335
399
  runMove(toDir, opts) {
336
- this.#bufferDirective((factory) => factory.move({ path: this.#path, toDir, force: opts?.force }));
400
+ this.#relocate((factory) => factory.move({ path: this.#path, toDir, force: opts?.force }));
401
+ }
402
+ // The handle's own rename or move, buffered after its still-pending edit, is not another writer:
403
+ // the next op joins that edit, which reaches the engine before the relocation, as it did before
404
+ // A-7. With nothing pending the version moves, and the next op reads the old path again.
405
+ #relocate(build) {
406
+ this.#enqueue(() => {
407
+ const { session, factory } = currentRun();
408
+ const absorb = this.#hasOpenPendingDirective(session) && session === this.#session && session.versionOf(this.#path) === this.#version;
409
+ session.buffer(build(factory));
410
+ if (absorb)
411
+ this.#version = session.versionOf(this.#path);
412
+ });
337
413
  }
338
414
  runCopy(to, opts) {
339
415
  this.#bufferDirective((factory) => factory.copy({ from: this.#path, to, force: opts?.force }));
@@ -375,8 +451,9 @@ class DialectHandleController {
375
451
  * `DialectHandleController`. Op methods are attached dynamically from `ops`' own keys —
376
452
  * `Object.keys(ops)` is exactly the set `OpMethods<Ast, Ops>` describes at the type level.
377
453
  */
378
- export function createDialectHandle(dialectAst, ops, path) {
379
- const controller = new DialectHandleController(dialectAst, ops, path);
454
+ export function createDialectHandle(dialectAst, ops, path, name) {
455
+ const controller = new DialectHandleController(dialectAst, ops, path, name);
456
+ controller.checkDeclaredInRun();
380
457
  // Every chaining method returns `handle` (the PUBLIC wrapper below), never the
381
458
  // controller directly — the author-facing chain must keep landing on an object that
382
459
  // carries `.modify`/`.push`(op methods)/etc., which the controller itself does not expose.
@@ -388,6 +465,7 @@ export function createDialectHandle(dialectAst, ops, path) {
388
465
  controller.runModify(fn);
389
466
  return handle;
390
467
  },
468
+ inspect: (fn) => controller.runQuery(fn, [], "inspect", "inspect() must not change"),
391
469
  replaceContent: (content) => {
392
470
  controller.runReplaceContent(content);
393
471
  return handle;
@@ -2,6 +2,6 @@ import type { Batch } from "../valueobjects/wire.ts";
2
2
  export interface EngineClient {
3
3
  emit(batch: Batch): Promise<void>;
4
4
  read(path: string): Promise<string | undefined>;
5
- commit(): Promise<void>;
5
+ commit(result?: unknown): Promise<void>;
6
6
  discard(): Promise<void>;
7
7
  }
@@ -6,12 +6,24 @@ export type Query<Ast = any, A extends unknown[] = any[], R = unknown> = ((ast:
6
6
  readonly [QUERY]: true;
7
7
  };
8
8
  export type OpPack<Ast = any> = Record<string, Op<Ast>>;
9
+ /**
10
+ * How a dialect reads and writes its files. `retire`, when given, is called on a tree a handle
11
+ * re-parsed away from (A-8): it must make every node of that tree fail when used, so a node kept
12
+ * from before the re-parse never edits a tree no file reflects.
13
+ */
14
+ export interface DialectAst<Ast = any> {
15
+ parse(source: string): Ast;
16
+ print(ast: Ast): string;
17
+ retire?(ast: Ast): void;
18
+ }
9
19
  export interface DialectDescriptor<Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> {
20
+ /**
21
+ * The name of the package that ships an author-defined dialect, the name its Dialect
22
+ * declaration uses (A-16). The SDK's dialects carry none and are never declared.
23
+ */
24
+ name?: string;
10
25
  extensions: string[];
11
- ast: {
12
- parse(source: string): Ast;
13
- print(ast: Ast): string;
14
- };
26
+ ast: DialectAst<Ast>;
15
27
  ops: Ops;
16
28
  }
17
29
  type Bound<Ast, F> = F extends (ast: Ast, ...rest: infer R) => void ? (...rest: R) => void : never;
@@ -33,15 +45,24 @@ type DialectWriteOps<Ast, Ops extends OpPack<Ast>> = {
33
45
  };
34
46
  export type Handle<State extends "found" | "writable" = "found", Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> = ReadOps & DialectWriteOps<Ast, Ops> & {
35
47
  modify(fn: (ast: Ast) => void): Edited<Ast, Ops>;
48
+ /**
49
+ * The read escape hatch, as `.modify()` is the write one (A-128). Hands `fn` the live AST,
50
+ * after every op chained before it, and resolves to what `fn` returns; it ends the chain.
51
+ * The AST is printed before and after `fn`, and a difference fails the factory with
52
+ * `inspect() must not change "<path>"`. Return plain data: a node kept after the next edit
53
+ * is stale (A-8).
54
+ *
55
+ * @example
56
+ * const count = await typescript.find("src/a.ts").addImport("x", "y").inspect((ast) => ast.getImportDeclarations().length);
57
+ */
58
+ inspect<R>(fn: (ast: Ast) => R): Promise<Awaited<R>>;
36
59
  } & OpMethods<Ast, Ops> & (State extends "found" ? {
37
60
  remove(): void;
38
61
  } : {}) & PromiseLike<void>;
39
62
  export interface Dialect<Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> {
63
+ readonly name?: string;
40
64
  readonly extensions: readonly string[];
41
- readonly ast: {
42
- parse(source: string): Ast;
43
- print(ast: Ast): string;
44
- };
65
+ readonly ast: DialectAst<Ast>;
45
66
  readonly ops: Ops;
46
67
  find(path: string): Handle<"found", Ast, Ops>;
47
68
  }
@@ -59,7 +80,8 @@ export declare function defineOpPack<Ast, Ops extends OpPack<Ast>>(ops: Ops): Op
59
80
  /**
60
81
  * Assembles a `Dialect` from its frozen descriptor (extensions, an AST parse/print pair,
61
82
  * and an op-pack). `find` is the dialect's ONLY entry verb into a Session (REQ-DG-01.2) — it
62
- * returns an open, coalescing `Handle`.
83
+ * returns an open, coalescing `Handle`. Throws when an op in `ops` takes the name of a handle
84
+ * verb (`RESERVED_HANDLE_NAMES`).
63
85
  *
64
86
  * @example
65
87
  * const myDialect = defineDialect({
@@ -69,6 +91,22 @@ export declare function defineOpPack<Ast, Ops extends OpPack<Ast>>(ops: Ops): Op
69
91
  * });
70
92
  */
71
93
  export declare function defineDialect<Ast, Ops extends OpPack<Ast>>(d: DialectDescriptor<Ast, Ops>): Dialect<Ast, Ops>;
94
+ /**
95
+ * Defines an author-defined dialect, named by the package that ships it (A-16): a factory opens
96
+ * its handles only when the schematic's library declares that name in its Manifest, and the
97
+ * conformance fixture rejects a name that is not the package's.
98
+ *
99
+ * @example
100
+ * export const ini = defineDialect({
101
+ * name: "@company/ini-dialect",
102
+ * extensions: [".ini"],
103
+ * ast: { parse: (text) => parseIni(text), print: (tree) => printIni(tree) },
104
+ * ops: {},
105
+ * });
106
+ */
107
+ export declare function defineAuthorDialect<Ast, Ops extends OpPack<Ast>>(d: DialectDescriptor<Ast, Ops> & {
108
+ name: string;
109
+ }): Dialect<Ast, Ops>;
72
110
  type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
73
111
  /**
74
112
  * The base handle's own vocabulary (REQ-DG-02, ADR-0010 amendment) — an op-pack op sharing
@@ -82,7 +120,7 @@ type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) exten
82
120
  * import it instead of hand-typing a second literal) — NOT a supported public API member, not
83
121
  * semver-covered beyond the FIT-04 baseline pin it already sits inside (ORCHESTRATOR RULING R2).
84
122
  */
85
- export declare const RESERVED_HANDLE_NAMES: readonly ["then", "read", "raw", "modify", "replaceContent", "rename", "move", "copy", "remove"];
123
+ export declare const RESERVED_HANDLE_NAMES: readonly ["then", "read", "raw", "modify", "inspect", "replaceContent", "rename", "move", "copy", "remove"];
86
124
  /**
87
125
  * Composes additional op-packs onto a base dialect. The resulting handle type is the
88
126
  * INTERSECTION of the base's ops and every attached pack's ops (ADR-0010) — an op from an
@@ -40,7 +40,8 @@ function hasDeclaredExtension(path, extensions) {
40
40
  /**
41
41
  * Assembles a `Dialect` from its frozen descriptor (extensions, an AST parse/print pair,
42
42
  * and an op-pack). `find` is the dialect's ONLY entry verb into a Session (REQ-DG-01.2) — it
43
- * returns an open, coalescing `Handle`.
43
+ * returns an open, coalescing `Handle`. Throws when an op in `ops` takes the name of a handle
44
+ * verb (`RESERVED_HANDLE_NAMES`).
44
45
  *
45
46
  * @example
46
47
  * const myDialect = defineDialect({
@@ -50,7 +51,11 @@ function hasDeclaredExtension(path, extensions) {
50
51
  * });
51
52
  */
52
53
  export function defineDialect(d) {
54
+ // The handle spreads its ops over its verbs, so an op named after a verb would replace it.
55
+ for (const name of Object.keys(d.ops))
56
+ assertNotReserved(name);
53
57
  return {
58
+ name: d.name,
54
59
  extensions: d.extensions,
55
60
  ast: d.ast,
56
61
  ops: d.ops,
@@ -58,10 +63,29 @@ export function defineDialect(d) {
58
63
  if (!hasDeclaredExtension(path, d.extensions)) {
59
64
  throw dialectError(`find(${JSON.stringify(path)}) — the file's extension is not one this dialect declares (${d.extensions.join(", ")}).`);
60
65
  }
61
- return createDialectHandle(d.ast, d.ops, path);
66
+ return createDialectHandle(d.ast, d.ops, path, d.name);
62
67
  },
63
68
  };
64
69
  }
70
+ /**
71
+ * Defines an author-defined dialect, named by the package that ships it (A-16): a factory opens
72
+ * its handles only when the schematic's library declares that name in its Manifest, and the
73
+ * conformance fixture rejects a name that is not the package's.
74
+ *
75
+ * @example
76
+ * export const ini = defineDialect({
77
+ * name: "@company/ini-dialect",
78
+ * extensions: [".ini"],
79
+ * ast: { parse: (text) => parseIni(text), print: (tree) => printIni(tree) },
80
+ * ops: {},
81
+ * });
82
+ */
83
+ export function defineAuthorDialect(d) {
84
+ if (typeof d.name !== "string" || d.name.length === 0) {
85
+ throw new Error('defineDialect failed: "name" is required, the name of the package that ships the dialect (A-16).');
86
+ }
87
+ return defineDialect(d);
88
+ }
65
89
  /**
66
90
  * The base handle's own vocabulary (REQ-DG-02, ADR-0010 amendment) — an op-pack op sharing
67
91
  * any of these names would silently shadow a base verb; `then` in particular would break the
@@ -79,6 +103,7 @@ export const RESERVED_HANDLE_NAMES = [
79
103
  "read",
80
104
  "raw",
81
105
  "modify",
106
+ "inspect",
82
107
  "replaceContent",
83
108
  "rename",
84
109
  "move",
@@ -95,14 +120,17 @@ void _reservedCoversSurface;
95
120
  * `Error`s, NOT minted via `dialectError()` — they are not run-op contained rejects and must
96
121
  * never be recognised by `isContained` as passthrough (design §4.5's own rationale).
97
122
  */
123
+ function assertNotReserved(name) {
124
+ if (!RESERVED_SET.has(name))
125
+ return;
126
+ const hint = name === "raw" ? " — the live AST-fn escape hatch is .modify(fn)" : "";
127
+ throw new Error(`op-pack composition failed: op "${name}" collides with a reserved handle verb${hint}`);
128
+ }
98
129
  function assertNoCompositionCollision(baseOpNames, packs) {
99
130
  const claimed = new Set(baseOpNames);
100
131
  for (const pack of packs) {
101
132
  for (const name of Object.keys(pack)) {
102
- if (RESERVED_SET.has(name)) {
103
- const hint = name === "raw" ? " — the live AST-fn escape hatch is .modify(fn)" : "";
104
- throw new Error(`op-pack composition failed: op "${name}" collides with a reserved handle verb${hint}`);
105
- }
133
+ assertNotReserved(name);
106
134
  if (claimed.has(name)) {
107
135
  throw new Error(`op-pack composition failed: duplicate op "${name}" declared by more than one pack.`);
108
136
  }
@@ -125,7 +153,7 @@ function assertNoCompositionCollision(baseOpNames, packs) {
125
153
  export function withOps(base, ...packs) {
126
154
  assertNoCompositionCollision(Object.keys(base.ops), packs);
127
155
  const merged = Object.assign({}, base.ops, ...packs);
128
- return defineDialect({ extensions: [...base.extensions], ast: base.ast, ops: merged });
156
+ return defineDialect({ name: base.name, extensions: [...base.extensions], ast: base.ast, ops: merged });
129
157
  }
130
158
  function assertKnownOps(ops, names, composer) {
131
159
  for (const name of names) {
@@ -151,7 +179,7 @@ export function withoutOps(dialect, names, reason) {
151
179
  throw dialectError(`${name} is not available for ${files} files — ${reason}. Use .modify() to make this edit directly.`);
152
180
  },
153
181
  ]));
154
- return defineDialect({ extensions: [...dialect.extensions], ast: dialect.ast, ops: { ...dialect.ops, ...blocked } });
182
+ return defineDialect({ name: dialect.name, extensions: [...dialect.extensions], ast: dialect.ast, ops: { ...dialect.ops, ...blocked } });
155
183
  }
156
184
  /**
157
185
  * Derives a dialect whose named ops run `overrides` instead, with the same signatures. Throws at
@@ -162,7 +190,7 @@ export function withoutOps(dialect, names, reason) {
162
190
  */
163
191
  export function overrideOps(dialect, overrides) {
164
192
  assertKnownOps(dialect.ops, Object.keys(overrides), "overrideOps");
165
- return defineDialect({ extensions: [...dialect.extensions], ast: dialect.ast, ops: { ...dialect.ops, ...overrides } });
193
+ return defineDialect({ name: dialect.name, extensions: [...dialect.extensions], ast: dialect.ast, ops: { ...dialect.ops, ...overrides } });
166
194
  }
167
195
  /**
168
196
  * Routes `find` by file extension to one dialect per extension, each with its own AST and ops —
@@ -2,3 +2,4 @@ import { AuthoringError } from "../../valueobjects/authoring-error.ts";
2
2
  import type { ValidationFinding } from "./schema-validate.ts";
3
3
  export declare function rejectionFor(finding: ValidationFinding): AuthoringError;
4
4
  export declare function rejectionForReservedName(name: string): AuthoringError;
5
+ export declare function rejectionForResult(problem: string): AuthoringError;
@@ -30,3 +30,7 @@ export function rejectionFor(finding) {
30
30
  export function rejectionForReservedName(name) {
31
31
  return rejection("reserved-name", `reserved lifecycle name: ${name} is reserved and cannot be declared by a factory module`);
32
32
  }
33
+ // A-14 / E-40: an invalid or oversized Result, from `checkResult`.
34
+ export function rejectionForResult(problem) {
35
+ return rejection("invalid-result", `invalid Result: ${problem}`);
36
+ }
@@ -13,8 +13,9 @@ export declare class SchemaParseFailure extends Error {
13
13
  export declare function formatLocator(line: number | undefined, column: number | undefined): string;
14
14
  /**
15
15
  * Parses the on-disk WRAPPED `schema.json` wire shape (ADR-0027: top-level
16
- * `{ "properties": { "<key>": {...} } }`) into the in-memory `Schema` array model.
17
- * Fail-closed: invalid JSON or a missing/non-object `"properties"` key both throw
16
+ * `{ "properties": { "<key>": {...} } }`, plus an optional `"result"` declaration, A-14) into
17
+ * the in-memory `Schema` array model.
18
+ * Fail-closed: invalid JSON, a missing/non-object `"properties"` key or an invalid `"result"` throw
18
19
  * `SchemaParseFailure` on the same path — the raw content is never echoed.
19
20
  */
20
21
  export declare function parseSchema(raw: string): Schema;
@@ -1,7 +1,7 @@
1
1
  // Bytes -> Schema. Shared by the bin (TFO-04's parse-error template) and the runtime
2
2
  // (RBV-05.1's fail-closed literal) — both format SchemaParseFailure into their own
3
3
  // vocabulary; this module never renders a caller-facing message itself (no-echo, ADR-0027).
4
- import { isPlainObject } from "../../valueobjects/schema-model.js";
4
+ import { FORBIDDEN_KEYS, isPlainObject, RESULT_KINDS } from "../../valueobjects/schema-model.js";
5
5
  import { locateFirstJsonSyntaxError } from "./schema-locate.js";
6
6
  export class SchemaParseFailure extends Error {
7
7
  problem;
@@ -23,8 +23,9 @@ export function formatLocator(line, column) {
23
23
  }
24
24
  /**
25
25
  * Parses the on-disk WRAPPED `schema.json` wire shape (ADR-0027: top-level
26
- * `{ "properties": { "<key>": {...} } }`) into the in-memory `Schema` array model.
27
- * Fail-closed: invalid JSON or a missing/non-object `"properties"` key both throw
26
+ * `{ "properties": { "<key>": {...} } }`, plus an optional `"result"` declaration, A-14) into
27
+ * the in-memory `Schema` array model.
28
+ * Fail-closed: invalid JSON, a missing/non-object `"properties"` key or an invalid `"result"` throw
28
29
  * `SchemaParseFailure` on the same path — the raw content is never echoed.
29
30
  */
30
31
  export function parseSchema(raw) {
@@ -64,5 +65,46 @@ export function parseSchema(raw) {
64
65
  description: typeof value.description === "string" ? value.description : undefined,
65
66
  });
66
67
  }
67
- return { properties };
68
+ if (!Object.hasOwn(parsed, "result"))
69
+ return { properties };
70
+ const result = parseResult(parsed.result);
71
+ if (result === undefined) {
72
+ throw new SchemaParseFailure({ problem: 'invalid "result" declaration', line: undefined, column: undefined });
73
+ }
74
+ return { properties, result };
75
+ }
76
+ // A-14: `type` (one kind or a list of kinds), and for an object `properties` and `required`,
77
+ // for an array `items`. Anything else, or a nested declaration that fails, is undefined.
78
+ function parseResult(raw) {
79
+ if (!isPlainObject(raw))
80
+ return undefined;
81
+ const types = Array.isArray(raw.type) ? raw.type : [raw.type];
82
+ if (types.length === 0 || !types.every((type) => typeof type === "string" && RESULT_KINDS.has(type)))
83
+ return undefined;
84
+ const schema = { types: types };
85
+ if (raw.properties !== undefined) {
86
+ if (!isPlainObject(raw.properties))
87
+ return undefined;
88
+ const properties = [];
89
+ for (const key of Object.keys(raw.properties)) {
90
+ const property = FORBIDDEN_KEYS.has(key) ? undefined : parseResult(raw.properties[key]);
91
+ if (property === undefined)
92
+ return undefined;
93
+ properties.push({ key, schema: property });
94
+ }
95
+ schema.properties = properties;
96
+ }
97
+ if (raw.required !== undefined) {
98
+ const declared = new Set(schema.properties?.map((property) => property.key));
99
+ if (!Array.isArray(raw.required) || !raw.required.every((key) => typeof key === "string" && declared.has(key)))
100
+ return undefined;
101
+ schema.required = raw.required;
102
+ }
103
+ if (raw.items !== undefined) {
104
+ const items = parseResult(raw.items);
105
+ if (items === undefined)
106
+ return undefined;
107
+ schema.items = items;
108
+ }
109
+ return schema;
68
110
  }
@@ -1,4 +1,4 @@
1
- import type { Schema } from "../../valueobjects/schema-model.ts";
1
+ import type { ResultSchema, Schema } from "../../valueobjects/schema-model.ts";
2
2
  export type ValidationFinding = {
3
3
  kind: "missing";
4
4
  field: string;
@@ -12,3 +12,18 @@ export type ValidationFinding = {
12
12
  field: string;
13
13
  };
14
14
  export declare function validateInput(schema: Schema, input: unknown): ValidationFinding[];
15
+ /** E-40: the largest JSON encoding of a Result, in UTF-8 bytes; exactly at it is allowed. */
16
+ export declare const RESULT_CEILING_BYTES = 1048576;
17
+ export type ResultCheck = {
18
+ readonly result: unknown;
19
+ } | {
20
+ readonly problem: string;
21
+ };
22
+ /**
23
+ * Checks `value` as the Result of a factory whose declaration is `declared`. Without a
24
+ * declaration only `undefined`, no Result, passes. A Result that passes comes back as a copy
25
+ * parsed from its JSON encoding, so what is committed is exactly what was checked. The
26
+ * declaration is a parameter so a Result shape a role imposes can be checked the same way as
27
+ * one read from `schema.json`.
28
+ */
29
+ export declare function checkResult(declared: ResultSchema | undefined, value: unknown): ResultCheck;