@pbuilder/sdk 0.19.0 → 0.21.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 (68) hide show
  1. package/README.md +81 -38
  2. package/dist/acl/irwire/stdio-engine-client.d.ts +1 -0
  3. package/dist/acl/irwire/stdio-engine-client.js +9 -0
  4. package/dist/bin/pbuilder-codegen.js +90 -18
  5. package/dist/bounded-contexts/authoring/application/usecases/authoring-verbs/index.d.ts +15 -0
  6. package/dist/bounded-contexts/authoring/application/usecases/authoring-verbs/index.js +17 -0
  7. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.d.ts +16 -3
  8. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.js +45 -11
  9. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.d.ts +3 -1
  10. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.js +10 -1
  11. package/dist/bounded-contexts/authoring/domain/ports/engine-client.d.ts +1 -0
  12. package/dist/bounded-contexts/authoring/domain/services/define-dialect.d.ts +28 -1
  13. package/dist/bounded-contexts/authoring/domain/services/define-dialect.js +27 -3
  14. package/dist/bounded-contexts/authoring/domain/services/evaluation.d.ts +29 -0
  15. package/dist/bounded-contexts/authoring/domain/services/evaluation.js +43 -0
  16. package/dist/bounded-contexts/authoring/domain/services/glob-match.d.ts +4 -0
  17. package/dist/bounded-contexts/authoring/domain/services/glob-match.js +81 -0
  18. package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.d.ts +1 -0
  19. package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.js +4 -0
  20. package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.d.ts +2 -1
  21. package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.js +6 -2
  22. package/dist/bounded-contexts/authoring/domain/valueobjects/findings.d.ts +12 -0
  23. package/dist/bounded-contexts/authoring/domain/valueobjects/findings.js +57 -0
  24. package/dist/bounded-contexts/authoring/domain/valueobjects/schema-model.d.ts +2 -0
  25. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/cli.d.ts +7 -2
  26. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/cli.js +28 -7
  27. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.d.ts +6 -2
  28. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.js +23 -13
  29. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/project-codegen.d.ts +1 -0
  30. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/project-codegen.js +5 -2
  31. package/dist/bounded-contexts/authoring/infrastructure/in/commons/index.d.ts +2 -1
  32. package/dist/bounded-contexts/authoring/infrastructure/in/commons/index.js +1 -1
  33. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.d.ts +14 -1
  34. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.js +15 -0
  35. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.d.ts +14 -1
  36. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.js +15 -0
  37. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/index.d.ts +14 -1
  38. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/index.js +15 -0
  39. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/css/index.d.ts +14 -1
  40. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/css/index.js +15 -0
  41. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/json/index.d.ts +14 -1
  42. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/json/index.js +15 -0
  43. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.d.ts +14 -1
  44. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.js +15 -0
  45. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.d.ts +14 -1
  46. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.js +15 -0
  47. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.d.ts +14 -1
  48. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.js +15 -0
  49. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.d.ts +14 -1
  50. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.js +15 -0
  51. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/yaml/index.d.ts +14 -1
  52. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/yaml/index.js +15 -0
  53. package/dist/bounded-contexts/authoring/testing/contract-fake.d.ts +1 -0
  54. package/dist/bounded-contexts/authoring/testing/contract-fake.js +8 -0
  55. package/dist/bounded-contexts/authoring/testing/glob-pattern.d.ts +5 -0
  56. package/dist/bounded-contexts/authoring/testing/glob-pattern.js +20 -0
  57. package/dist/bounded-contexts/authoring/testing/harness/index.d.ts +8 -0
  58. package/dist/bounded-contexts/authoring/testing/harness/index.js +12 -1
  59. package/dist/bounded-contexts/authoring/testing/run-vehicle.d.ts +1 -0
  60. package/dist/bounded-contexts/authoring/testing/run-vehicle.js +4 -0
  61. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.d.ts +3 -0
  62. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.js +4 -0
  63. package/dist/bounded-contexts/runner-hosting/infrastructure/in/runner.js +15 -3
  64. package/dist/runner-manifest.json +33 -9
  65. package/dist/shared-kernel/wire-protocol.d.ts +1 -1
  66. package/dist/shared-kernel/wire-protocol.js +1 -1
  67. package/package.json +1 -1
  68. package/schemas/project-builder.schema.json +75 -2
@@ -10,7 +10,9 @@ import { currentRun, getSessionAls } from "../../../domain/services/run-context.
10
10
  import { schemaPathFor } from "../../../domain/services/schema/schema-files.js";
11
11
  import { parseSchema, SchemaParseFailure, formatLocator } from "../../../domain/services/schema/schema-parse.js";
12
12
  import { checkResult, validateInput } from "../../../domain/services/schema/schema-validate.js";
13
- import { rejectionFor, rejectionForReservedName, rejectionForResult } from "../../../domain/services/schema/input-rejection.js";
13
+ import { rejectionFor, rejectionForReservedName, rejectionForResult, rejectionForScopeInput, } from "../../../domain/services/schema/input-rejection.js";
14
+ import { handedOnFindings, scopeOf } from "../../../domain/services/evaluation.js";
15
+ import { SCOPE_INPUTS, SOURCED_FINDINGS } from "../../../domain/valueobjects/findings.js";
14
16
  class DialectRegistryImpl {
15
17
  #handles = [];
16
18
  register(handle) {
@@ -90,7 +92,7 @@ function emptySchemaWarning(pkg) {
90
92
  // a corrupt/unreadable schema file, only for author-input rejections (invalid-input /
91
93
  // reserved-name). A parsed-but-empty schema (zero declared properties) is distinct from no
92
94
  // schema at all (REQ-RBV-05.2) — it warns and skips validation, it does not opt out.
93
- function validateAtRunBoundary(pkg, input) {
95
+ function validateAtRunBoundary(pkg, input, imposed) {
94
96
  let raw;
95
97
  try {
96
98
  raw = pkg.files.readText(schemaPathFor(pkg.dir));
@@ -119,7 +121,7 @@ function validateAtRunBoundary(pkg, input) {
119
121
  console.warn(emptySchemaWarning(pkg));
120
122
  return schema;
121
123
  }
122
- const findings = validateInput(schema, input);
124
+ const findings = validateInput(schema, input, imposed);
123
125
  const [firstFinding] = findings;
124
126
  if (firstFinding !== undefined) {
125
127
  throw rejectionFor(firstFinding);
@@ -145,6 +147,22 @@ function checkReservedNames(pkg) {
145
147
  throw rejectionForReservedName(reserved);
146
148
  }
147
149
  }
150
+ // A-14 / A-121 / A-124: the Result as it leaves the factory. An evaluation's Findings are checked
151
+ // again once sourced and narrowed, since the `source` it adds counts towards the ceiling (E-40).
152
+ function handOn(declared, returned, source, inScope) {
153
+ const checked = checkResult(declared, returned);
154
+ if ("problem" in checked)
155
+ throw rejectionForResult(checked.problem);
156
+ if (source === undefined)
157
+ return checked.result;
158
+ const handed = handedOnFindings(checked.result, source, inScope);
159
+ if ("problem" in handed)
160
+ throw rejectionForResult(handed.problem);
161
+ const recheck = checkResult(SOURCED_FINDINGS, handed.result);
162
+ if ("problem" in recheck)
163
+ throw rejectionForResult(recheck.problem);
164
+ return recheck.result;
165
+ }
148
166
  /**
149
167
  * Builds a SessionContext and runs the factory inside it, flushing buffered
150
168
  * directives at run end (REQ-KIT-05) — a write-only factory still emits.
@@ -199,23 +217,41 @@ function checkReservedNames(pkg) {
199
217
  *
200
218
  * const runner = defineFactory<Input>(bareFactory, { packageDir: import.meta.dir });
201
219
  * await runner(input, { client });
220
+ *
221
+ * The returned runner takes, besides the client, the `role` and the qualified `name` of the
222
+ * schematic it runs, as the caller received them (CA-19). With the role `evaluation`, `fn`
223
+ * returns its Findings, checked against the shape the role imposes, each finding's `source` is
224
+ * set to `name`, and `fn` receives the scope inputs `include` and `exclude`; every `glob` result
225
+ * is narrowed to the scope and so is every finding with a path (A-120 to A-124). Any other role,
226
+ * or none, runs as a generator.
202
227
  */
203
228
  export function defineFactory(fn, options) {
204
- const wrapped = async (o, { client }) => {
229
+ const wrapped = async (o, { client, role, name }) => {
230
+ if (role === "evaluation" && name === undefined) {
231
+ throw new Error("defineFactory: an evaluation factory needs the qualified name collection:schematic of the schematic");
232
+ }
233
+ const source = role === "evaluation" ? name : undefined;
205
234
  let packageAnchors;
206
235
  let packageFiles;
207
236
  let schema;
237
+ let inScope;
238
+ if (source !== undefined) {
239
+ const scope = scopeOf(o);
240
+ if ("problem" in scope)
241
+ throw rejectionForScopeInput(scope.problem);
242
+ inScope = scope.inScope;
243
+ }
208
244
  if (options?.packageDir !== undefined) {
209
245
  const pkg = { files: options.packageFiles, dir: resolvePackageDir(options.packageDir) };
210
246
  // REQ-RBV-06: exactly TWO reads, in this order — reserved-name check, then schema
211
247
  // validation. No third (containment-ceiling) read exists (ADR-0077 §C).
212
248
  checkReservedNames(pkg);
213
- schema = validateAtRunBoundary(pkg, o);
249
+ schema = validateAtRunBoundary(pkg, o, source === undefined ? [] : SCOPE_INPUTS);
214
250
  packageAnchors = { packageDir: pkg.dir };
215
251
  packageFiles = pkg.files;
216
252
  }
217
253
  const ctx = {
218
- session: new Session(client),
254
+ session: new Session(client, inScope),
219
255
  factory: new DirectiveFactory(),
220
256
  dialects: new DialectRegistryImpl(),
221
257
  packageAnchors,
@@ -237,12 +273,10 @@ export function defineFactory(fn, options) {
237
273
  try {
238
274
  const returned = await getSessionAls().run(ctx, () => fn(o));
239
275
  await ctx.dialects.drain();
240
- const checked = checkResult(schema?.result, returned);
241
- if ("problem" in checked)
242
- throw rejectionForResult(checked.problem);
276
+ const result = handOn(source === undefined ? schema?.result : SOURCED_FINDINGS, returned, source, inScope);
243
277
  await ctx.session.flush();
244
- await ctx.session.commit(checked.result);
245
- return checked.result;
278
+ await ctx.session.commit(result);
279
+ return result;
246
280
  }
247
281
  catch (thrown) {
248
282
  // A thrown `undefined` or `null` would read as success to anyone testing the error.
@@ -2,12 +2,14 @@ import type { EngineClient } from "../../ports/engine-client.ts";
2
2
  import type { Directive } from "../../valueobjects/wire.ts";
3
3
  export declare class Session {
4
4
  #private;
5
- constructor(client: EngineClient);
5
+ /** `inScope`, when given, narrows every listing to the paths it keeps (A-123). */
6
+ constructor(client: EngineClient, inScope?: (path: string) => boolean);
6
7
  buffer(directive: Directive): void;
7
8
  versionOf(path: string): number;
8
9
  pendingDirectives(): readonly Directive[];
9
10
  isPending(directive: Directive): boolean;
10
11
  read(path: string): Promise<string | undefined>;
12
+ list(pattern: string, ignore?: readonly string[]): Promise<readonly string[]>;
11
13
  commit(result?: unknown): Promise<void>;
12
14
  discard(): Promise<void>;
13
15
  flush(): Promise<void>;
@@ -43,8 +43,11 @@ export class Session {
43
43
  // The batches being emitted, so a read or a later flush never overtakes them.
44
44
  #emitting = Promise.resolve();
45
45
  #inFlight = 0;
46
- constructor(client) {
46
+ #inScope;
47
+ /** `inScope`, when given, narrows every listing to the paths it keeps (A-123). */
48
+ constructor(client, inScope) {
47
49
  this.#client = client;
50
+ this.#inScope = inScope;
48
51
  }
49
52
  buffer(directive) {
50
53
  this.#pending.push(directive);
@@ -70,6 +73,12 @@ export class Session {
70
73
  await this.flush();
71
74
  return this.#client.read(path);
72
75
  }
76
+ // A-131: like read(), a listing flushes first, so it sees every write buffered before it.
77
+ async list(pattern, ignore) {
78
+ await this.flush();
79
+ const paths = await this.#client.list(pattern, ignore);
80
+ return this.#inScope === undefined ? paths : paths.filter(this.#inScope);
81
+ }
73
82
  // SEAM-03 (ADR-01): thin wrappers delegating to #client. Session owns #client, so the
74
83
  // commit boundary stays inside Session — defineFactory never names #client directly.
75
84
  async commit(result) {
@@ -2,6 +2,7 @@ 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
+ list(pattern: string, ignore?: readonly string[]): Promise<readonly string[]>;
5
6
  commit(result?: unknown): Promise<void>;
6
7
  discard(): Promise<void>;
7
8
  }
@@ -59,12 +59,27 @@ export type Handle<State extends "found" | "writable" = "found", Ast = any, Ops
59
59
  } & OpMethods<Ast, Ops> & (State extends "found" ? {
60
60
  remove(): void;
61
61
  } : {}) & PromiseLike<void>;
62
+ /**
63
+ * The options of `glob`: the patterns of the files to leave out (A-130).
64
+ *
65
+ * @example
66
+ * const options: GlobOptions = { ignore: ["**\/*.test.ts", "src/generated/**"] };
67
+ */
68
+ export interface GlobOptions {
69
+ ignore?: readonly string[];
70
+ }
62
71
  export interface Dialect<Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> {
63
72
  readonly name?: string;
64
73
  readonly extensions: readonly string[];
65
74
  readonly ast: DialectAst<Ast>;
66
75
  readonly ops: Ops;
67
76
  find(path: string): Handle<"found", Ast, Ops>;
77
+ /**
78
+ * Opens every file `pattern` matches whose extension the dialect declares, ordered by path; a
79
+ * file of any other extension is left out without an error (A-132). Resolves `[]` when none
80
+ * matches. The pattern syntax and `ignore` are commons `glob`'s.
81
+ */
82
+ glob(pattern: string, options?: GlobOptions): Promise<Handle<"found", Ast, Ops>[]>;
68
83
  }
69
84
  /**
70
85
  * Declares a named collection of ops over one AST type — usable standalone (REQ-DG-02.3),
@@ -156,16 +171,28 @@ type DialectsByExtension = {
156
171
  readonly [extension: string]: Dialect;
157
172
  };
158
173
  type HandleOf<D> = D extends Dialect<infer A, infer O> ? Handle<"found", A, O> : never;
174
+ type RouteHandle<M extends DialectsByExtension, K extends keyof M & string> = {
175
+ [Key in K]: HandleOf<M[Key]> & {
176
+ readonly extension: Key;
177
+ };
178
+ }[K];
159
179
  type MatchingKey<M, P extends string> = {
160
180
  [K in keyof M & string]: P extends `${string}${K}` ? K : never;
161
181
  }[keyof M & string];
162
182
  type LongestKey<Ks extends string> = {
163
183
  [K in Ks]: [Extract<Exclude<Ks, K>, `${string}${K}`>] extends [never] ? K : never;
164
184
  }[Ks];
165
- type RoutedHandle<M extends DialectsByExtension, P extends string> = string extends P ? HandleOf<M[keyof M]> : HandleOf<M[LongestKey<MatchingKey<M, P>>]>;
185
+ type RoutedHandle<M extends DialectsByExtension, P extends string> = string extends P ? RouteHandle<M, keyof M & string> : RouteHandle<M, LongestKey<MatchingKey<M, P>>>;
186
+ type GlobbedHandle<M extends DialectsByExtension, P extends string> = [LongestKey<MatchingKey<M, P>>] extends [never] ? RouteHandle<M, keyof M & string> : RoutedHandle<M, P>;
166
187
  export interface ExtensionRouter<M extends DialectsByExtension> {
167
188
  readonly extensions: readonly (keyof M & string)[];
168
189
  find<P extends string>(path: P): RoutedHandle<M, P>;
190
+ /**
191
+ * Opens every file `pattern` matches that a route takes, ordered by path, each through the
192
+ * dialect of its longest matching extension (A-133); other files are left out without an
193
+ * error. Each handle carries its route's key as `extension`.
194
+ */
195
+ glob<P extends string>(pattern: P, options?: GlobOptions): Promise<GlobbedHandle<M, P>[]>;
169
196
  }
170
197
  /**
171
198
  * Routes `find` by file extension to one dialect per extension, each with its own AST and ops —
@@ -13,8 +13,13 @@
13
13
  // "don't care about the concrete Ast" erasure this bare form needs.
14
14
  import { basename } from "node:path";
15
15
  import { createDialectHandle } from "../entities/dialect-handle.js";
16
+ import { currentRun } from "./run-context.js";
16
17
  import { dialectError } from "../valueobjects/dialect-error.js";
17
18
  export { query } from "../entities/dialect-handle.js";
19
+ /** The paths a `glob` of the active run lists, after the run's buffered writes (A-131). */
20
+ function listed(pattern, options) {
21
+ return currentRun().session.list(pattern, options?.ignore);
22
+ }
18
23
  /**
19
24
  * Declares a named collection of ops over one AST type — usable standalone (REQ-DG-02.3),
20
25
  * e.g. shareable across two dialects targeting the same AST type, before any `withOps`
@@ -54,7 +59,7 @@ export function defineDialect(d) {
54
59
  // The handle spreads its ops over its verbs, so an op named after a verb would replace it.
55
60
  for (const name of Object.keys(d.ops))
56
61
  assertNotReserved(name);
57
- return {
62
+ const dialect = {
58
63
  name: d.name,
59
64
  extensions: d.extensions,
60
65
  ast: d.ast,
@@ -65,7 +70,13 @@ export function defineDialect(d) {
65
70
  }
66
71
  return createDialectHandle(d.ast, d.ops, path, d.name);
67
72
  },
73
+ // A-133: written once here, so every dialect built from a descriptor has it.
74
+ async glob(pattern, options) {
75
+ const paths = await listed(pattern, options);
76
+ return paths.filter((path) => hasDeclaredExtension(path, d.extensions)).map((path) => dialect.find(path));
77
+ },
68
78
  };
79
+ return dialect;
69
80
  }
70
81
  /**
71
82
  * Defines an author-defined dialect, named by the package that ships it (A-16): a factory opens
@@ -209,16 +220,29 @@ export function byExtension(dialects) {
209
220
  if (!declared.includes(extension)) {
210
221
  throw new Error(`dialect routing failed: "${extension}" is not an extension its dialect declares (${declared.join(", ")}).`);
211
222
  }
223
+ // A-134: the routing key is set as `extension` on every handle, over any op of that name.
224
+ if (Object.hasOwn(dialects[extension].ops, "extension")) {
225
+ throw new Error(`dialect routing failed: the dialect of "${extension}" has an op named "extension", the field that carries the routing key on its handles.`);
226
+ }
212
227
  }
213
228
  const longestFirst = [...extensions].sort((a, b) => b.length - a.length);
229
+ const routeOf = (path) => longestFirst.find((candidate) => hasDeclaredExtension(path, [candidate]));
230
+ const open = (path, extension) => Object.assign(dialects[extension].find(path), { extension });
214
231
  return {
215
232
  extensions,
216
233
  find(path) {
217
- const extension = longestFirst.find((candidate) => hasDeclaredExtension(path, [candidate]));
234
+ const extension = routeOf(path);
218
235
  if (extension === undefined) {
219
236
  throw dialectError(`find(${JSON.stringify(path)}) — the file's extension is not one this dialect declares (${extensions.join(", ")}).`);
220
237
  }
221
- return dialects[extension].find(path);
238
+ return open(path, extension);
239
+ },
240
+ async glob(pattern, options) {
241
+ const paths = await listed(pattern, options);
242
+ return paths.flatMap((path) => {
243
+ const extension = routeOf(path);
244
+ return extension === undefined ? [] : [open(path, extension)];
245
+ });
222
246
  },
223
247
  };
224
248
  }
@@ -0,0 +1,29 @@
1
+ /** Whether a workspace-relative path is in the scope. */
2
+ export type InScope = (path: string) => boolean;
3
+ /**
4
+ * The scope `include` less `exclude` names, or no scope when neither is given. A problem names the
5
+ * scope input that is not an array of strings.
6
+ */
7
+ export declare function scopeOf(input: unknown): {
8
+ readonly inScope?: InScope;
9
+ } | {
10
+ readonly problem: string;
11
+ };
12
+ type Finding = {
13
+ [key: string]: unknown;
14
+ };
15
+ /**
16
+ * The Findings a factory returned, already checked against SOURCED_FINDINGS: each kept finding
17
+ * gets `source`, and one whose `path` falls outside the scope is dropped. A problem names the first
18
+ * finding whose author set `source`.
19
+ */
20
+ export declare function handedOnFindings(findings: {
21
+ readonly items: readonly Finding[];
22
+ }, source: string, inScope: InScope | undefined): {
23
+ readonly result: {
24
+ items: Finding[];
25
+ };
26
+ } | {
27
+ readonly problem: string;
28
+ };
29
+ export {};
@@ -0,0 +1,43 @@
1
+ // The run-boundary side of the role `evaluation`: the scope its inputs name (A-122, A-123) and
2
+ // the Findings it hands on, each with the `source` the SDK sets (A-121) and inside the scope (A-124).
3
+ import { isPlainObject } from "../valueobjects/schema-model.js";
4
+ import { globMatcher } from "./glob-match.js";
5
+ function globsOf(record, name) {
6
+ const value = Object.hasOwn(record, name) ? record[name] : undefined;
7
+ if (value === undefined)
8
+ return undefined;
9
+ if (!Array.isArray(value) || !value.every((entry) => typeof entry === "string")) {
10
+ return `invalid input: ${name} must be an array of strings`;
11
+ }
12
+ return value.map(globMatcher);
13
+ }
14
+ /**
15
+ * The scope `include` less `exclude` names, or no scope when neither is given. A problem names the
16
+ * scope input that is not an array of strings.
17
+ */
18
+ export function scopeOf(input) {
19
+ const record = isPlainObject(input) ? input : {};
20
+ const include = globsOf(record, "include");
21
+ if (typeof include === "string")
22
+ return { problem: include };
23
+ const exclude = globsOf(record, "exclude");
24
+ if (typeof exclude === "string")
25
+ return { problem: exclude };
26
+ if (include === undefined && exclude === undefined)
27
+ return {};
28
+ return {
29
+ inScope: (path) => (include === undefined || include.some((matches) => matches(path))) && !(exclude ?? []).some((matches) => matches(path)),
30
+ };
31
+ }
32
+ /**
33
+ * The Findings a factory returned, already checked against SOURCED_FINDINGS: each kept finding
34
+ * gets `source`, and one whose `path` falls outside the scope is dropped. A problem names the first
35
+ * finding whose author set `source`.
36
+ */
37
+ export function handedOnFindings(findings, source, inScope) {
38
+ const sourced = findings.items.findIndex((finding) => Object.hasOwn(finding, "source"));
39
+ if (sourced !== -1)
40
+ return { problem: `Result.items[${sourced}].source is set by the SDK, and a finding may not set it` };
41
+ const kept = findings.items.filter((finding) => inScope === undefined || typeof finding.path !== "string" || inScope(finding.path));
42
+ return { result: { items: kept.map((finding) => ({ ...finding, source })) } };
43
+ }
@@ -0,0 +1,4 @@
1
+ /** Every brace-free pattern `{a,b}` groups stand for. A `{` with no closing `}` is literal. */
2
+ export declare function alternatives(pattern: string): string[];
3
+ /** Whether a workspace-relative path matches `pattern`. */
4
+ export declare function globMatcher(pattern: string): (path: string) => boolean;
@@ -0,0 +1,81 @@
1
+ // Glob matching as the engine's `tree.list` matches (E-37, engine ADR-0070): `*` is any run of
2
+ // characters in one segment, `?` one character, `**` as a whole segment any number of segments,
3
+ // zero included, and `{a,b}` either alternative, nested groups included. Every other character is
4
+ // literal, so there is no negation and no class.
5
+ /** Every brace-free pattern `{a,b}` groups stand for. A `{` with no closing `}` is literal. */
6
+ export function alternatives(pattern) {
7
+ const open = pattern.indexOf("{");
8
+ if (open === -1)
9
+ return [pattern];
10
+ const commas = [];
11
+ let depth = 0;
12
+ for (let i = open; i < pattern.length; i++) {
13
+ const char = pattern[i];
14
+ if (char === "{")
15
+ depth++;
16
+ else if (char === "," && depth === 1)
17
+ commas.push(i);
18
+ else if (char === "}" && --depth === 0) {
19
+ const bounds = [open, ...commas, i];
20
+ const rest = pattern.slice(i + 1);
21
+ return bounds
22
+ .slice(1)
23
+ .flatMap((end, k) => alternatives(pattern.slice(0, open) + pattern.slice(bounds[k] + 1, end) + rest));
24
+ }
25
+ }
26
+ return alternatives(pattern.slice(open + 1)).map((tail) => pattern.slice(0, open + 1) + tail);
27
+ }
28
+ // Matched without RegExp, which the runner closure does not admit (Constraint 4).
29
+ // `*` is any run of characters in one segment and `?` one character, by backtracking on the last `*`.
30
+ function segmentMatches(pattern, text) {
31
+ let p = 0;
32
+ let t = 0;
33
+ let star = -1;
34
+ let mark = 0;
35
+ while (t < text.length) {
36
+ if (p < pattern.length && pattern[p] === "*") {
37
+ star = p++;
38
+ mark = t;
39
+ }
40
+ else if (p < pattern.length && (pattern[p] === "?" || pattern[p] === text[t])) {
41
+ p++;
42
+ t++;
43
+ }
44
+ else if (star !== -1) {
45
+ p = star + 1;
46
+ t = ++mark;
47
+ }
48
+ else {
49
+ return false;
50
+ }
51
+ }
52
+ while (pattern[p] === "*")
53
+ p++;
54
+ return p === pattern.length;
55
+ }
56
+ // A `**` segment matches any number of segments, zero included; as the last segment it matches
57
+ // the rest of the path, so it needs at least one more segment there.
58
+ function segmentsMatch(pattern, path, i, j) {
59
+ if (i === pattern.length)
60
+ return j === path.length;
61
+ const segment = pattern[i];
62
+ if (segment !== "**")
63
+ return j < path.length && segmentMatches(segment, path[j]) && segmentsMatch(pattern, path, i + 1, j + 1);
64
+ if (i === pattern.length - 1)
65
+ return j < path.length;
66
+ for (let k = j; k <= path.length; k++) {
67
+ if (k > j && path[k - 1] === "")
68
+ return false;
69
+ if (segmentsMatch(pattern, path, i + 1, k))
70
+ return true;
71
+ }
72
+ return false;
73
+ }
74
+ /** Whether a workspace-relative path matches `pattern`. */
75
+ export function globMatcher(pattern) {
76
+ const compiled = alternatives(pattern).map((alternative) => alternative.split("/"));
77
+ return (path) => {
78
+ const segments = path.split("/");
79
+ return compiled.some((alternative) => segmentsMatch(alternative, segments, 0, 0));
80
+ };
81
+ }
@@ -3,3 +3,4 @@ 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
5
  export declare function rejectionForResult(problem: string): AuthoringError;
6
+ export declare function rejectionForScopeInput(problem: string): AuthoringError;
@@ -34,3 +34,7 @@ export function rejectionForReservedName(name) {
34
34
  export function rejectionForResult(problem) {
35
35
  return rejection("invalid-result", `invalid Result: ${problem}`);
36
36
  }
37
+ // A-122: a scope input of an evaluation factory that is not an array of strings.
38
+ export function rejectionForScopeInput(problem) {
39
+ return rejection("invalid-input", problem);
40
+ }
@@ -11,7 +11,8 @@ export type ValidationFinding = {
11
11
  kind: "disallowed-key";
12
12
  field: string;
13
13
  };
14
- export declare function validateInput(schema: Schema, input: unknown): ValidationFinding[];
14
+ /** `imposed` names the inputs a role adds, which `schema.json` never declares (A-122). */
15
+ export declare function validateInput(schema: Schema, input: unknown, imposed?: readonly string[]): ValidationFinding[];
15
16
  /** E-40: the largest JSON encoding of a Result, in UTF-8 bytes; exactly at it is allowed. */
16
17
  export declare const RESULT_CEILING_BYTES = 1048576;
17
18
  export type ResultCheck = {
@@ -31,7 +31,8 @@ function matchesType(property, value) {
31
31
  return typeof value === "string" && (property.choices ?? []).includes(value);
32
32
  }
33
33
  }
34
- export function validateInput(schema, input) {
34
+ /** `imposed` names the inputs a role adds, which `schema.json` never declares (A-122). */
35
+ export function validateInput(schema, input, imposed = []) {
35
36
  const findings = [];
36
37
  const record = (input !== null && typeof input === "object" ? input : {});
37
38
  for (const property of schema.properties) {
@@ -56,7 +57,7 @@ export function validateInput(schema, input) {
56
57
  // mapping, slices load-bearing literals).
57
58
  const declaredKeys = new Set(schema.properties.map((property) => property.key));
58
59
  for (const key of Object.keys(record)) {
59
- if (RESERVED_INPUT_KEYS.has(key) || FORBIDDEN_KEYS.has(key) || !declaredKeys.has(key)) {
60
+ if (RESERVED_INPUT_KEYS.has(key) || FORBIDDEN_KEYS.has(key) || !(declaredKeys.has(key) || imposed.includes(key))) {
60
61
  findings.push({ kind: "disallowed-key", field: key });
61
62
  }
62
63
  }
@@ -159,6 +160,9 @@ function shapeProblem(declared, value, where) {
159
160
  const kind = kindOf(value);
160
161
  if (!declared.types.includes(kind))
161
162
  return `${where} must be ${declared.types.join(" or ")}`;
163
+ if (kind === "string" && declared.choices !== undefined && !declared.choices.includes(value)) {
164
+ return `${where} must be one of: ${declared.choices.join(", ")}`;
165
+ }
162
166
  if (kind === "array" && declared.items !== undefined) {
163
167
  const items = declared.items;
164
168
  for (const [index, item] of value.entries()) {
@@ -0,0 +1,12 @@
1
+ import type { ResultSchema } from "./schema-model.ts";
2
+ /** The role a schematic declares in its Collection definition entry (CA-14). */
3
+ export type Role = "generator" | "setup" | "teardown" | "evaluation";
4
+ /** The inputs the role `evaluation` imposes; an author input with either name is rejected (A-122). */
5
+ export declare const SCOPE_INPUTS: readonly string[];
6
+ /** The Findings an evaluation factory returns: what codegen emits as its Result type. */
7
+ export declare const FINDINGS: ResultSchema;
8
+ /**
9
+ * FINDINGS with the `source` the SDK sets. The run boundary checks a returned value against it,
10
+ * so an author-set `source` passes the shape check and is then rejected by name.
11
+ */
12
+ export declare const SOURCED_FINDINGS: ResultSchema;
@@ -0,0 +1,57 @@
1
+ // A-120 / A-121 / A-122: what the role `evaluation` imposes on a factory, as data both codegen and
2
+ // the run boundary read, so the emitted types and the checked shape cannot drift apart.
3
+ /** The inputs the role `evaluation` imposes; an author input with either name is rejected (A-122). */
4
+ export const SCOPE_INPUTS = ["include", "exclude"];
5
+ const STRING = { types: ["string"] };
6
+ const NUMBER = { types: ["number"] };
7
+ const POSITION = {
8
+ types: ["object"],
9
+ properties: [
10
+ { key: "line", schema: NUMBER },
11
+ { key: "column", schema: NUMBER },
12
+ ],
13
+ required: ["line", "column"],
14
+ };
15
+ function findingsWith(extra) {
16
+ const finding = {
17
+ types: ["object"],
18
+ properties: [
19
+ { key: "rule", schema: STRING },
20
+ { key: "message", schema: STRING },
21
+ { key: "severity", schema: { types: ["string"], choices: ["error", "warning"] } },
22
+ { key: "path", schema: STRING },
23
+ {
24
+ key: "range",
25
+ schema: {
26
+ types: ["object"],
27
+ properties: [
28
+ { key: "start", schema: POSITION },
29
+ { key: "end", schema: POSITION },
30
+ ],
31
+ required: ["start"],
32
+ },
33
+ },
34
+ {
35
+ key: "fix",
36
+ schema: {
37
+ types: ["object"],
38
+ properties: [
39
+ { key: "schematic", schema: STRING },
40
+ { key: "inputs", schema: { types: ["object"] } },
41
+ ],
42
+ required: ["schematic"],
43
+ },
44
+ },
45
+ ...extra,
46
+ ],
47
+ required: ["rule", "message", "severity"],
48
+ };
49
+ return { types: ["object"], properties: [{ key: "items", schema: { types: ["array"], items: finding } }], required: ["items"] };
50
+ }
51
+ /** The Findings an evaluation factory returns: what codegen emits as its Result type. */
52
+ export const FINDINGS = findingsWith([]);
53
+ /**
54
+ * FINDINGS with the `source` the SDK sets. The run boundary checks a returned value against it,
55
+ * so an author-set `source` passes the shape check and is then rejected by name.
56
+ */
57
+ export const SOURCED_FINDINGS = findingsWith([{ key: "source", schema: STRING }]);
@@ -22,6 +22,8 @@ export interface ResultSchema {
22
22
  }>;
23
23
  required?: string[];
24
24
  items?: ResultSchema;
25
+ /** The values a string may take. `schema.json` cannot declare it; a shape a role imposes can. */
26
+ choices?: string[];
25
27
  }
26
28
  export interface Schema {
27
29
  properties: SchemaProperty[];
@@ -10,11 +10,16 @@ export declare class SchemaSufficiencyFailure extends Error {
10
10
  readonly findings: SufficiencyFinding[];
11
11
  constructor(findings: SufficiencyFinding[]);
12
12
  }
13
+ /** A-120 / A-122: a `schema.json` that declares what the role `evaluation` imposes. */
14
+ export declare class RoleContractFailure extends Error {
15
+ constructor(problem: string);
16
+ }
13
17
  /**
14
18
  * Reads `<packageDir>/schema.json`, parses it, and writes `<packageDir>/schema.generated.ts`
15
- * — the bin's fixed, non-configurable output location (REQ-TFO-05.1/FPS-01).
19
+ * — the bin's fixed, non-configurable output location (REQ-TFO-05.1/FPS-01). `evaluation` is set
20
+ * when the schematic's Collection definition entry declares the role `evaluation`.
16
21
  */
17
- export declare function generateSchema(packageDir: string): GenerateResult;
22
+ export declare function generateSchema(packageDir: string, evaluation?: boolean): GenerateResult;
18
23
  export declare class WriteContainmentRefusal extends Error {
19
24
  constructor(message: string);
20
25
  }