@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.
- package/README.md +69 -3
- package/dist/acl/irwire/stdio-engine-client.d.ts +1 -1
- package/dist/acl/irwire/stdio-engine-client.js +3 -2
- package/dist/bin/pbuilder-codegen.js +59 -1
- package/dist/bin/pbuilder-conformance.d.ts +2 -0
- package/dist/bin/pbuilder-conformance.js +45 -0
- package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.d.ts +12 -3
- package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.js +23 -9
- package/dist/bounded-contexts/authoring/application/usecases/scaffold/expander.js +4 -4
- package/dist/bounded-contexts/authoring/domain/aggregates/session/session.d.ts +2 -1
- package/dist/bounded-contexts/authoring/domain/aggregates/session/session.js +56 -6
- package/dist/bounded-contexts/authoring/domain/entities/dialect-handle.d.ts +2 -1
- package/dist/bounded-contexts/authoring/domain/entities/dialect-handle.js +108 -30
- package/dist/bounded-contexts/authoring/domain/ports/engine-client.d.ts +1 -1
- package/dist/bounded-contexts/authoring/domain/services/define-dialect.d.ts +48 -10
- package/dist/bounded-contexts/authoring/domain/services/define-dialect.js +37 -9
- package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.d.ts +1 -0
- package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.js +4 -0
- package/dist/bounded-contexts/authoring/domain/services/schema/schema-parse.d.ts +3 -2
- package/dist/bounded-contexts/authoring/domain/services/schema/schema-parse.js +46 -4
- package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.d.ts +16 -1
- package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.js +125 -0
- package/dist/bounded-contexts/authoring/domain/valueobjects/authoring-error.d.ts +3 -2
- package/dist/bounded-contexts/authoring/domain/valueobjects/authoring-error.js +2 -0
- package/dist/bounded-contexts/authoring/domain/valueobjects/schema-model.d.ts +17 -0
- package/dist/bounded-contexts/authoring/domain/valueobjects/schema-model.js +1 -0
- package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.d.ts +1 -0
- package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.js +23 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.js +2 -2
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.d.ts +8 -5
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.js +7 -4
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.d.ts +1 -1
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.js +20 -7
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.d.ts +20 -2
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.js +19 -3
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.d.ts +5 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.js +89 -20
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.js +2 -2
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/ast.d.ts +2 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/ast.js +4 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.js +3 -3
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/ast.d.ts +2 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/ast.js +4 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.js +2 -2
- package/dist/bounded-contexts/authoring/testing/conformance/index.d.ts +10 -12
- package/dist/bounded-contexts/authoring/testing/conformance/index.js +17 -2
- package/dist/bounded-contexts/authoring/testing/conformance/run-package.d.ts +37 -0
- package/dist/bounded-contexts/authoring/testing/conformance/run-package.js +209 -0
- package/dist/bounded-contexts/authoring/testing/harness/index.d.ts +13 -4
- package/dist/bounded-contexts/authoring/testing/harness/index.js +10 -4
- package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.d.ts +3 -0
- package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.js +2 -0
- package/dist/bounded-contexts/runner-hosting/infrastructure/in/runner.js +69 -3
- package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.d.ts +24 -0
- package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.js +34 -1
- package/dist/conformance/index.d.ts +1 -0
- package/dist/conformance/index.js +1 -0
- package/dist/dialect/index.d.ts +2 -0
- package/dist/dialect/index.js +3 -0
- package/dist/runner-manifest.json +12 -12
- package/package.json +8 -2
package/README.md
CHANGED
|
@@ -219,6 +219,45 @@ everything you can do inside a factory, and the
|
|
|
219
219
|
[quickstart](./docs/guides/quickstart.md) covers the standalone-package setup (tsconfig
|
|
220
220
|
included) in more depth.
|
|
221
221
|
|
|
222
|
+
## Returning a Result
|
|
223
|
+
|
|
224
|
+
A factory may hand a value back: to Launch when it is the root schematic, with the Plan of a
|
|
225
|
+
Dry Run or the applied operations of a Commit. Declare it under `result` in `schema.json`,
|
|
226
|
+
next to `properties`:
|
|
227
|
+
|
|
228
|
+
```json
|
|
229
|
+
{
|
|
230
|
+
"properties": {},
|
|
231
|
+
"result": {
|
|
232
|
+
"type": "object",
|
|
233
|
+
"properties": { "name": { "type": "string" }, "files": { "type": "array", "items": { "type": "string" } } },
|
|
234
|
+
"required": ["name"]
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
`type` is one of `string`, `number`, `boolean`, `null`, `object` and `array`, or a list of
|
|
240
|
+
them (`["string", "null"]`). An object with `properties` accepts only the keys it names, and
|
|
241
|
+
`required` lists the ones it must have; an object without `properties` accepts any JSON
|
|
242
|
+
object. An array may give its `items`. A key that is not `required` may be left out, but never set to
|
|
243
|
+
`undefined`: `undefined` is not JSON, so `{ "name": "a", "files": undefined }` fails. The
|
|
244
|
+
generated type marks such a key `files?:`, which TypeScript lets you set to `undefined` unless
|
|
245
|
+
your tsconfig enables `exactOptionalPropertyTypes`; leave the key out instead. Codegen emits the matching `Result` type next to
|
|
246
|
+
`Input`, so the compiler checks what the factory returns:
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
import type { Input, Result } from "./schema.generated.ts";
|
|
250
|
+
|
|
251
|
+
export default (input: Input): Result => ({ name: "payments", files: [] });
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
The SDK checks the returned value at the factory boundary before anything is written. It
|
|
255
|
+
must match the declaration and be JSON: no functions, class instances (a `Date`, a `Map`),
|
|
256
|
+
cycles, `undefined` or non-finite numbers. Its JSON encoding may take at most 1 MiB
|
|
257
|
+
(1048576 bytes). A schematic that declares no Result must return nothing. When any of this
|
|
258
|
+
fails, the run fails with an `AuthoringError` whose reason is `invalid-result`, and nothing
|
|
259
|
+
is written. A declared `null` is a Result and is returned as `null`.
|
|
260
|
+
|
|
222
261
|
## Project-wide type generation
|
|
223
262
|
|
|
224
263
|
```sh
|
|
@@ -554,6 +593,10 @@ Three things to know:
|
|
|
554
593
|
into schema-derived input validation against the adjacent `schema.json`. Without it those
|
|
555
594
|
verbs have nothing to resolve against.
|
|
556
595
|
|
|
596
|
+
- `result.result` is the Result the run committed: what the factory returned, checked
|
|
597
|
+
against the `result` its `schema.json` declares (see [Returning a Result](#returning-a-result)).
|
|
598
|
+
It is `undefined` when the factory declares none or the run failed.
|
|
599
|
+
|
|
557
600
|
- `result.reads` counts the reads the engine served for each path, so a test can check
|
|
558
601
|
that the factory reads a file once however many ops it chains on it. A path the factory
|
|
559
602
|
never read is absent.
|
|
@@ -613,6 +656,7 @@ await ts.find("src/index.ts")
|
|
|
613
656
|
| `addVariable(name, initializer, opts?)` | Appends a top-level variable (`kind` defaults to `const`). A no-op when the same declaration exists; another binding of `name` rejects. |
|
|
614
657
|
| `addClass(name, source, opts?)` | Appends a top-level class. `source` **excludes** the braces — the op adds them. A no-op when the same declaration exists; another binding of `name` rejects. |
|
|
615
658
|
| `.modify(fn)` | The universal escape hatch: direct [ts-morph](https://ts-morph.com) access to the file's AST for anything the named ops don't cover. |
|
|
659
|
+
| `.inspect(fn)` | The read escape hatch: hands `fn` the same live AST and resolves to what `fn` returns. Ends the chain; a callback that changes the file fails the factory. |
|
|
616
660
|
|
|
617
661
|
The `add*` ops fail loud on a name collision with an existing value declaration or import
|
|
618
662
|
binding (two value declarations sharing a name is invalid TypeScript); a `type`/`interface`
|
|
@@ -750,8 +794,8 @@ See [the ASP.NET dialect guide](./docs/guides/aspnet-dialect.md).
|
|
|
750
794
|
|
|
751
795
|
### `@pbuilder/sdk/msbuild`
|
|
752
796
|
|
|
753
|
-
Adds project references to `.csproj`, `.props
|
|
754
|
-
text, never through the `dotnet` CLI; the classic `.sln` is rejected.
|
|
797
|
+
Adds project references to `.csproj`, `.props` and `.targets` files, and projects to `.slnx`
|
|
798
|
+
solutions, by editing the XML text, never through the `dotnet` CLI; the classic `.sln` is rejected.
|
|
755
799
|
|
|
756
800
|
```ts
|
|
757
801
|
import * as msbuild from "@pbuilder/sdk/msbuild";
|
|
@@ -759,9 +803,11 @@ import * as msbuild from "@pbuilder/sdk/msbuild";
|
|
|
759
803
|
await msbuild
|
|
760
804
|
.find("src/Shop.Infrastructure/Shop.Infrastructure.csproj")
|
|
761
805
|
.addProjectReference("../Shop.Application/Shop.Application.csproj");
|
|
806
|
+
|
|
807
|
+
await msbuild.find("Shop.slnx").addProject("src/Shop.Api/Shop.Api.csproj", { folder: "/src/" });
|
|
762
808
|
```
|
|
763
809
|
|
|
764
|
-
Named
|
|
810
|
+
Named ops: `addProjectReference`, `addProject`. `.modify(fn)` exposes [saxes](https://github.com/lddubeau/saxes).
|
|
765
811
|
See [the MSBuild dialect guide](./docs/guides/msbuild-dialect.md).
|
|
766
812
|
|
|
767
813
|
### `@pbuilder/sdk/nestjs`
|
|
@@ -837,6 +883,26 @@ still flushes as a **single** write. Two things to respect:
|
|
|
837
883
|
callbacks are your own trust; before importing a *third-party* dialect or op-pack built
|
|
838
884
|
on it, read [SECURITY.md](./SECURITY.md).
|
|
839
885
|
|
|
886
|
+
### `.inspect()` — reading the AST back
|
|
887
|
+
|
|
888
|
+
`.inspect(ast => value)` is the read counterpart of `.modify()`. It hands the callback the same
|
|
889
|
+
live AST, after every op chained before it, and resolves to what the callback returns. It ends
|
|
890
|
+
the chain, emits nothing, and is offered to every factory, so a generator can read a value to
|
|
891
|
+
decide what to write:
|
|
892
|
+
|
|
893
|
+
```ts
|
|
894
|
+
import * as ts from "@pbuilder/sdk/typescript";
|
|
895
|
+
|
|
896
|
+
const imports = await ts.find("src/main.ts")
|
|
897
|
+
.addImport("BooksModule", "./books/books.module")
|
|
898
|
+
.inspect((ast) => ast.getImportDeclarations().length);
|
|
899
|
+
```
|
|
900
|
+
|
|
901
|
+
The callback must not change the AST. The SDK prints the file before and after it, and a
|
|
902
|
+
difference fails the factory with `inspect() must not change "<path>"`. A callback that throws
|
|
903
|
+
fails it with `inspect() on "<path>" threw`, without the original message. Return plain data:
|
|
904
|
+
a node you keep goes stale after the next edit.
|
|
905
|
+
|
|
840
906
|
### Going deeper
|
|
841
907
|
|
|
842
908
|
Everything dialect-related lives in one reference page —
|
|
@@ -22,6 +22,6 @@ export declare class StdioEngineClient implements EngineClient {
|
|
|
22
22
|
});
|
|
23
23
|
emit(batch: Batch): Promise<void>;
|
|
24
24
|
read(path: string): Promise<string | undefined>;
|
|
25
|
-
commit(): Promise<void>;
|
|
25
|
+
commit(result?: unknown): Promise<void>;
|
|
26
26
|
discard(): Promise<void>;
|
|
27
27
|
}
|
|
@@ -228,8 +228,9 @@ export class StdioEngineClient {
|
|
|
228
228
|
return undefined;
|
|
229
229
|
return result.content;
|
|
230
230
|
}
|
|
231
|
-
|
|
232
|
-
|
|
231
|
+
// A-14: the Result rides in the ir.commit params, the key present only when one is declared.
|
|
232
|
+
async commit(result) {
|
|
233
|
+
const response = await this.#call("ir.commit", result === undefined ? {} : { result });
|
|
233
234
|
if (response.error !== undefined) {
|
|
234
235
|
throw new IntentRejectedError(response.error.message);
|
|
235
236
|
}
|
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
import { join as join3, dirname as dirname2, basename, resolve as resolve2, sep } from "node:path";
|
|
20
20
|
|
|
21
21
|
// src/bounded-contexts/authoring/domain/valueobjects/schema-model.ts
|
|
22
|
+
var RESULT_KINDS = new Set(["string", "number", "boolean", "null", "object", "array"]);
|
|
22
23
|
var FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
23
24
|
function isPlainObject(value) {
|
|
24
25
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
@@ -256,7 +257,46 @@ function parseSchema(raw) {
|
|
|
256
257
|
description: typeof value.description === "string" ? value.description : undefined
|
|
257
258
|
});
|
|
258
259
|
}
|
|
259
|
-
|
|
260
|
+
if (!Object.hasOwn(parsed, "result"))
|
|
261
|
+
return { properties };
|
|
262
|
+
const result = parseResult(parsed.result);
|
|
263
|
+
if (result === undefined) {
|
|
264
|
+
throw new SchemaParseFailure({ problem: 'invalid "result" declaration', line: undefined, column: undefined });
|
|
265
|
+
}
|
|
266
|
+
return { properties, result };
|
|
267
|
+
}
|
|
268
|
+
function parseResult(raw) {
|
|
269
|
+
if (!isPlainObject(raw))
|
|
270
|
+
return;
|
|
271
|
+
const types = Array.isArray(raw.type) ? raw.type : [raw.type];
|
|
272
|
+
if (types.length === 0 || !types.every((type) => typeof type === "string" && RESULT_KINDS.has(type)))
|
|
273
|
+
return;
|
|
274
|
+
const schema = { types };
|
|
275
|
+
if (raw.properties !== undefined) {
|
|
276
|
+
if (!isPlainObject(raw.properties))
|
|
277
|
+
return;
|
|
278
|
+
const properties = [];
|
|
279
|
+
for (const key of Object.keys(raw.properties)) {
|
|
280
|
+
const property = FORBIDDEN_KEYS.has(key) ? undefined : parseResult(raw.properties[key]);
|
|
281
|
+
if (property === undefined)
|
|
282
|
+
return;
|
|
283
|
+
properties.push({ key, schema: property });
|
|
284
|
+
}
|
|
285
|
+
schema.properties = properties;
|
|
286
|
+
}
|
|
287
|
+
if (raw.required !== undefined) {
|
|
288
|
+
const declared = new Set(schema.properties?.map((property) => property.key));
|
|
289
|
+
if (!Array.isArray(raw.required) || !raw.required.every((key) => typeof key === "string" && declared.has(key)))
|
|
290
|
+
return;
|
|
291
|
+
schema.required = raw.required;
|
|
292
|
+
}
|
|
293
|
+
if (raw.items !== undefined) {
|
|
294
|
+
const items = parseResult(raw.items);
|
|
295
|
+
if (items === undefined)
|
|
296
|
+
return;
|
|
297
|
+
schema.items = items;
|
|
298
|
+
}
|
|
299
|
+
return schema;
|
|
260
300
|
}
|
|
261
301
|
|
|
262
302
|
// src/bounded-contexts/authoring/domain/services/schema/schema-digest.ts
|
|
@@ -347,6 +387,23 @@ function emitProperty(property) {
|
|
|
347
387
|
` : "";
|
|
348
388
|
return `${doc} ${key}${optional}: ${type};`;
|
|
349
389
|
}
|
|
390
|
+
function emitResult(result) {
|
|
391
|
+
return result.types.map((kind) => {
|
|
392
|
+
switch (kind) {
|
|
393
|
+
case "array":
|
|
394
|
+
return `Array<${result.items === undefined ? "unknown" : emitResult(result.items)}>`;
|
|
395
|
+
case "object": {
|
|
396
|
+
if (result.properties === undefined)
|
|
397
|
+
return "{ [key: string]: unknown }";
|
|
398
|
+
const required = new Set(result.required);
|
|
399
|
+
const members = result.properties.map(({ key, schema }) => `${emitPropertyKey(key)}${required.has(key) ? "" : "?"}: ${emitResult(schema)}`);
|
|
400
|
+
return members.length === 0 ? "Record<string, never>" : `{ ${members.join("; ")} }`;
|
|
401
|
+
}
|
|
402
|
+
default:
|
|
403
|
+
return kind;
|
|
404
|
+
}
|
|
405
|
+
}).join(" | ");
|
|
406
|
+
}
|
|
350
407
|
function emitInputType(schema, digest) {
|
|
351
408
|
const members = schema.properties.map(emitProperty).join(`
|
|
352
409
|
`);
|
|
@@ -357,6 +414,7 @@ function emitInputType(schema, digest) {
|
|
|
357
414
|
"export type Input = {",
|
|
358
415
|
members,
|
|
359
416
|
"};",
|
|
417
|
+
...schema.result === undefined ? [] : ["", `export type Result = ${emitResult(schema.result)};`],
|
|
360
418
|
""
|
|
361
419
|
].join(`
|
|
362
420
|
`);
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// `pbuilder-conformance --dialect <installed package dir>` (CA-13), or
|
|
3
|
+
// `pbuilder-conformance --local <name> --conformance <file> --path <base file>` for a local dialect
|
|
4
|
+
// (CA-18): prints one JSON report line.
|
|
5
|
+
// Exit 0: the fixture passed. Exit 1: it ran and failed, a missing fixture included. Exit 2: it
|
|
6
|
+
// could not run, with nothing on stdout. Runs under Bun, from the SDK root of the Run, so the
|
|
7
|
+
// dialect's `@pbuilder/sdk` imports reach this same SDK.
|
|
8
|
+
import { checkDialectPackage, checkLocalDialect } from "../conformance/index.js";
|
|
9
|
+
import { redirectConsoleToStderr } from "../shared-kernel/framing.js";
|
|
10
|
+
// The fixture runs the author's code, so everything but the report goes to stderr.
|
|
11
|
+
const writeReport = process.stdout.write.bind(process.stdout);
|
|
12
|
+
Object.defineProperty(process, "stdout", { value: process.stderr, writable: true, configurable: true });
|
|
13
|
+
redirectConsoleToStderr();
|
|
14
|
+
const COULD_NOT_RUN = 2;
|
|
15
|
+
const USAGE = "usage: pbuilder-conformance --dialect <installed package dir>\n" +
|
|
16
|
+
" pbuilder-conformance --local <name> --conformance <file> --path <base file>\n";
|
|
17
|
+
function check(argv) {
|
|
18
|
+
if (argv.some((value) => value === ""))
|
|
19
|
+
return undefined;
|
|
20
|
+
if (argv.length === 2 && argv[0] === "--dialect")
|
|
21
|
+
return checkDialectPackage(argv[1]);
|
|
22
|
+
if (argv.length !== 6 || argv[0] !== "--local")
|
|
23
|
+
return undefined;
|
|
24
|
+
const flags = new Map([[argv[2], argv[3]], [argv[4], argv[5]]]);
|
|
25
|
+
const conformance = flags.get("--conformance");
|
|
26
|
+
const path = flags.get("--path");
|
|
27
|
+
if (conformance === undefined || path === undefined)
|
|
28
|
+
return undefined;
|
|
29
|
+
return checkLocalDialect({ name: argv[1], conformance, path });
|
|
30
|
+
}
|
|
31
|
+
async function main(argv) {
|
|
32
|
+
const checking = check(argv);
|
|
33
|
+
if (checking === undefined) {
|
|
34
|
+
process.stderr.write(USAGE);
|
|
35
|
+
return COULD_NOT_RUN;
|
|
36
|
+
}
|
|
37
|
+
const report = await checking;
|
|
38
|
+
await new Promise((done) => writeReport(`${JSON.stringify(report)}\n`, () => done()));
|
|
39
|
+
return report.passed ? 0 : 1;
|
|
40
|
+
}
|
|
41
|
+
// Exits explicitly: a timer or socket the author's code left open must not keep the process alive.
|
|
42
|
+
main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
|
|
43
|
+
const detail = err instanceof Error && err.message.startsWith("pbuilder-conformance:") ? err.message : "the fixture could not run";
|
|
44
|
+
process.stderr.write(`${detail}\n`, () => process.exit(COULD_NOT_RUN));
|
|
45
|
+
});
|
|
@@ -19,6 +19,7 @@ export interface SessionContext {
|
|
|
19
19
|
packageDir: string;
|
|
20
20
|
};
|
|
21
21
|
packageFiles?: PackageFiles;
|
|
22
|
+
declaredDialects?: ReadonlySet<string>;
|
|
22
23
|
}
|
|
23
24
|
export declare function isDefineFactoryWrapped(value: unknown): boolean;
|
|
24
25
|
export declare function currentContext(): SessionContext;
|
|
@@ -45,7 +46,10 @@ export declare function requirePackageAnchors(missingAnchorMessage: string): {
|
|
|
45
46
|
* Author code never imports this directly; it calls `runFactoryForTest` (test-time) or the
|
|
46
47
|
* future production runner instead — both wrap this SAME seam internally.
|
|
47
48
|
*
|
|
48
|
-
* @param fn - the authoring logic; receives the resolved, schema-validated input
|
|
49
|
+
* @param fn - the authoring logic; receives the resolved, schema-validated input and returns
|
|
50
|
+
* the schematic's Result, or nothing when its `schema.json` declares none (A-14). The Result
|
|
51
|
+
* is checked against that declaration before the flush; the runner resolves to the committed
|
|
52
|
+
* copy. A bare `defineFactory(fn)` declares no Result, so `fn` must return nothing.
|
|
49
53
|
* @param options.packageFiles - the package-files adapter the two reads go through; every
|
|
50
54
|
* caller passes it with `packageDir`.
|
|
51
55
|
* @param options.packageDir - opts into schema-derived input validation and reserved-name
|
|
@@ -78,9 +82,14 @@ export declare function requirePackageAnchors(missingAnchorMessage: string): {
|
|
|
78
82
|
* const runner = defineFactory<Input>(bareFactory, { packageDir: import.meta.dir });
|
|
79
83
|
* await runner(input, { client });
|
|
80
84
|
*/
|
|
81
|
-
export declare function defineFactory<O>(fn: (o: O) =>
|
|
85
|
+
export declare function defineFactory<O, R = void>(fn: (o: O) => R | Promise<R>, options?: ({
|
|
82
86
|
packageDir: string | URL;
|
|
83
87
|
packageFiles: PackageFiles;
|
|
88
|
+
} | {
|
|
89
|
+
packageDir?: undefined;
|
|
90
|
+
packageFiles?: undefined;
|
|
91
|
+
}) & {
|
|
92
|
+
declaredDialects?: readonly string[];
|
|
84
93
|
}): (o: O, deps: {
|
|
85
94
|
client: EngineClient;
|
|
86
|
-
}) => Promise<
|
|
95
|
+
}) => Promise<R>;
|
|
@@ -9,8 +9,8 @@ import { invalidInput } from "../../../domain/valueobjects/authoring-error.js";
|
|
|
9
9
|
import { currentRun, getSessionAls } from "../../../domain/services/run-context.js";
|
|
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
|
-
import { validateInput } from "../../../domain/services/schema/schema-validate.js";
|
|
13
|
-
import { rejectionFor, rejectionForReservedName } from "../../../domain/services/schema/input-rejection.js";
|
|
12
|
+
import { checkResult, validateInput } from "../../../domain/services/schema/schema-validate.js";
|
|
13
|
+
import { rejectionFor, rejectionForReservedName, rejectionForResult } from "../../../domain/services/schema/input-rejection.js";
|
|
14
14
|
class DialectRegistryImpl {
|
|
15
15
|
#handles = [];
|
|
16
16
|
register(handle) {
|
|
@@ -103,7 +103,7 @@ function validateAtRunBoundary(pkg, input) {
|
|
|
103
103
|
}
|
|
104
104
|
if (raw === undefined) {
|
|
105
105
|
console.warn(noSchemaWarning(pkg));
|
|
106
|
-
return;
|
|
106
|
+
return undefined;
|
|
107
107
|
}
|
|
108
108
|
let schema;
|
|
109
109
|
try {
|
|
@@ -117,13 +117,14 @@ function validateAtRunBoundary(pkg, input) {
|
|
|
117
117
|
}
|
|
118
118
|
if (schema.properties.length === 0) {
|
|
119
119
|
console.warn(emptySchemaWarning(pkg));
|
|
120
|
-
return;
|
|
120
|
+
return schema;
|
|
121
121
|
}
|
|
122
122
|
const findings = validateInput(schema, input);
|
|
123
123
|
const [firstFinding] = findings;
|
|
124
124
|
if (firstFinding !== undefined) {
|
|
125
125
|
throw rejectionFor(firstFinding);
|
|
126
126
|
}
|
|
127
|
+
return schema;
|
|
127
128
|
}
|
|
128
129
|
// Reserved-lifecycle-name enforcement (S-004, ADR-0028, REQ-RLN-01/02): resolves
|
|
129
130
|
// reserved-name status from the factory package's OWN MODULE STRUCTURE only — never from
|
|
@@ -163,7 +164,10 @@ function checkReservedNames(pkg) {
|
|
|
163
164
|
* Author code never imports this directly; it calls `runFactoryForTest` (test-time) or the
|
|
164
165
|
* future production runner instead — both wrap this SAME seam internally.
|
|
165
166
|
*
|
|
166
|
-
* @param fn - the authoring logic; receives the resolved, schema-validated input
|
|
167
|
+
* @param fn - the authoring logic; receives the resolved, schema-validated input and returns
|
|
168
|
+
* the schematic's Result, or nothing when its `schema.json` declares none (A-14). The Result
|
|
169
|
+
* is checked against that declaration before the flush; the runner resolves to the committed
|
|
170
|
+
* copy. A bare `defineFactory(fn)` declares no Result, so `fn` must return nothing.
|
|
167
171
|
* @param options.packageFiles - the package-files adapter the two reads go through; every
|
|
168
172
|
* caller passes it with `packageDir`.
|
|
169
173
|
* @param options.packageDir - opts into schema-derived input validation and reserved-name
|
|
@@ -200,12 +204,13 @@ export function defineFactory(fn, options) {
|
|
|
200
204
|
const wrapped = async (o, { client }) => {
|
|
201
205
|
let packageAnchors;
|
|
202
206
|
let packageFiles;
|
|
203
|
-
|
|
207
|
+
let schema;
|
|
208
|
+
if (options?.packageDir !== undefined) {
|
|
204
209
|
const pkg = { files: options.packageFiles, dir: resolvePackageDir(options.packageDir) };
|
|
205
210
|
// REQ-RBV-06: exactly TWO reads, in this order — reserved-name check, then schema
|
|
206
211
|
// validation. No third (containment-ceiling) read exists (ADR-0077 §C).
|
|
207
212
|
checkReservedNames(pkg);
|
|
208
|
-
validateAtRunBoundary(pkg, o);
|
|
213
|
+
schema = validateAtRunBoundary(pkg, o);
|
|
209
214
|
packageAnchors = { packageDir: pkg.dir };
|
|
210
215
|
packageFiles = pkg.files;
|
|
211
216
|
}
|
|
@@ -215,6 +220,7 @@ export function defineFactory(fn, options) {
|
|
|
215
220
|
dialects: new DialectRegistryImpl(),
|
|
216
221
|
packageAnchors,
|
|
217
222
|
packageFiles,
|
|
223
|
+
declaredDialects: new Set(options?.declaredDialects),
|
|
218
224
|
};
|
|
219
225
|
// ADR-01: no `finally` — success (commit) and failure (discard) are distinct paths.
|
|
220
226
|
// The final flush is INSIDE the try, so a flush-time emit rejection (already an
|
|
@@ -224,11 +230,19 @@ export function defineFactory(fn, options) {
|
|
|
224
230
|
// unawaited dialect chain (forgotten `await`) still completes and commits; a drain
|
|
225
231
|
// rejection (an unawaited chain that threw) routes through the SAME catch below as a
|
|
226
232
|
// flush rejection already does.
|
|
233
|
+
//
|
|
234
|
+
// A-14: the Result is checked after the drain and before the final flush, so an invalid
|
|
235
|
+
// one takes the discard path below and nothing is written. A bare factory, or one with no `result` in its schema,
|
|
236
|
+
// declares none and must return nothing; the commit then carries no Result.
|
|
227
237
|
try {
|
|
228
|
-
await getSessionAls().run(ctx, () => fn(o));
|
|
238
|
+
const returned = await getSessionAls().run(ctx, () => fn(o));
|
|
229
239
|
await ctx.dialects.drain();
|
|
240
|
+
const checked = checkResult(schema?.result, returned);
|
|
241
|
+
if ("problem" in checked)
|
|
242
|
+
throw rejectionForResult(checked.problem);
|
|
230
243
|
await ctx.session.flush();
|
|
231
|
-
await ctx.session.commit();
|
|
244
|
+
await ctx.session.commit(checked.result);
|
|
245
|
+
return checked.result;
|
|
232
246
|
}
|
|
233
247
|
catch (thrown) {
|
|
234
248
|
// A thrown `undefined` or `null` would read as success to anyone testing the error.
|
|
@@ -16,10 +16,10 @@
|
|
|
16
16
|
// — no synchronous flush variant may be added. The bridge is the EXISTING `DialectRegistry`
|
|
17
17
|
// (`context.ts`, ADR-0037), documented as generic over "anything with a `settle()`": a
|
|
18
18
|
// mid-run `session.flush()` call is fired here WITHOUT awaiting (its synchronous prefix —
|
|
19
|
-
// draining `#pending`, building the batch, and
|
|
20
|
-
// loop —
|
|
21
|
-
//
|
|
22
|
-
//
|
|
19
|
+
// draining `#pending`, building the batch, and, when no earlier batch is still in flight, the
|
|
20
|
+
// fake's entirely-synchronous `#apply` loop — runs before `flush()` suspends; a batch fired
|
|
21
|
+
// while another is in flight waits its turn, so each group's `#tree` mutation still lands in
|
|
22
|
+
// order) and REGISTERED as a dialect handle. `defineFactory` already awaits
|
|
23
23
|
// `ctx.dialects.drain()` BEFORE its own run-end `session.flush()` (which covers the final,
|
|
24
24
|
// still-pending group) and BEFORE `commit()` — so a later-chunk rejection surfaces through
|
|
25
25
|
// `drain()`, routes to `defineFactory`'s existing catch, and `discard()` clears the SAME
|
|
@@ -4,10 +4,11 @@ export declare class Session {
|
|
|
4
4
|
#private;
|
|
5
5
|
constructor(client: EngineClient);
|
|
6
6
|
buffer(directive: Directive): void;
|
|
7
|
+
versionOf(path: string): number;
|
|
7
8
|
pendingDirectives(): readonly Directive[];
|
|
8
9
|
isPending(directive: Directive): boolean;
|
|
9
10
|
read(path: string): Promise<string | undefined>;
|
|
10
|
-
commit(): Promise<void>;
|
|
11
|
+
commit(result?: unknown): Promise<void>;
|
|
11
12
|
discard(): Promise<void>;
|
|
12
13
|
flush(): Promise<void>;
|
|
13
14
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// KIT-02 / ADR-0008: holds
|
|
2
|
-
//
|
|
1
|
+
// KIT-02 / ADR-0008: holds the pending directive buffer, the EngineClient, and one content
|
|
2
|
+
// version per path as typed (A-7). No tree. read() flushes pending BEFORE delegating to the client.
|
|
3
3
|
// REQ-KIT-05: flush() is package-internal — called by defineFactory after fn resolves
|
|
4
4
|
// so write-only factories (no read call) still emit their batch.
|
|
5
5
|
//
|
|
@@ -8,14 +8,52 @@
|
|
|
8
8
|
// here because the author API has no run-wide force concept yet. The fake's Row-3 test
|
|
9
9
|
// (FAKE-04) is intentional engine-contract coverage, not dead-code coverage.
|
|
10
10
|
import { toAuthoringError } from "../../valueobjects/authoring-error.js";
|
|
11
|
+
const dirOf = (path) => path.slice(0, path.lastIndexOf("/") + 1);
|
|
12
|
+
const baseOf = (path) => path.slice(path.lastIndexOf("/") + 1);
|
|
13
|
+
// A loop, not a /\/+$/ regex: toDir comes from the author, and that regex backtracks polynomially.
|
|
14
|
+
function withoutTrailingSlashes(dir) {
|
|
15
|
+
let end = dir.length;
|
|
16
|
+
while (end > 0 && dir[end - 1] === "/")
|
|
17
|
+
end--;
|
|
18
|
+
return dir.slice(0, end);
|
|
19
|
+
}
|
|
20
|
+
/** The paths whose content a directive replaces or removes, spelled as the commons verbs spell them; a copy's source is untouched. */
|
|
21
|
+
function touchedPaths(directive) {
|
|
22
|
+
switch (directive.op) {
|
|
23
|
+
case "create":
|
|
24
|
+
return [directive.create.pathTemplate];
|
|
25
|
+
case "modify":
|
|
26
|
+
return [directive.modify.path];
|
|
27
|
+
case "delete":
|
|
28
|
+
return [directive.delete.path];
|
|
29
|
+
case "rename":
|
|
30
|
+
return [directive.rename.path, dirOf(directive.rename.path) + directive.rename.newName];
|
|
31
|
+
case "move":
|
|
32
|
+
return [directive.move.path, `${withoutTrailingSlashes(directive.move.toDir)}/${baseOf(directive.move.path)}`];
|
|
33
|
+
case "copy":
|
|
34
|
+
return [directive.copy.to];
|
|
35
|
+
case "copyIn":
|
|
36
|
+
return [directive.copyIn.to];
|
|
37
|
+
}
|
|
38
|
+
}
|
|
11
39
|
export class Session {
|
|
12
40
|
#client;
|
|
13
41
|
#pending = [];
|
|
42
|
+
#versions = new Map();
|
|
43
|
+
// The batches being emitted, so a read or a later flush never overtakes them.
|
|
44
|
+
#emitting = Promise.resolve();
|
|
45
|
+
#inFlight = 0;
|
|
14
46
|
constructor(client) {
|
|
15
47
|
this.#client = client;
|
|
16
48
|
}
|
|
17
49
|
buffer(directive) {
|
|
18
50
|
this.#pending.push(directive);
|
|
51
|
+
for (const path of touchedPaths(directive))
|
|
52
|
+
this.#versions.set(path, this.versionOf(path) + 1);
|
|
53
|
+
}
|
|
54
|
+
// A-7: how many buffered directives have changed this path's content, keyed by the path as typed.
|
|
55
|
+
versionOf(path) {
|
|
56
|
+
return this.#versions.get(path) ?? 0;
|
|
19
57
|
}
|
|
20
58
|
// SEAM-02 (REQ-03): a defensive copy of the pending buffer for the pending Directives renderer.
|
|
21
59
|
// Later mutations to #pending must NOT affect a snapshot taken earlier.
|
|
@@ -34,8 +72,8 @@ export class Session {
|
|
|
34
72
|
}
|
|
35
73
|
// SEAM-03 (ADR-01): thin wrappers delegating to #client. Session owns #client, so the
|
|
36
74
|
// commit boundary stays inside Session — defineFactory never names #client directly.
|
|
37
|
-
async commit() {
|
|
38
|
-
await this.#client.commit();
|
|
75
|
+
async commit(result) {
|
|
76
|
+
await this.#client.commit(result);
|
|
39
77
|
}
|
|
40
78
|
async discard() {
|
|
41
79
|
await this.#client.discard();
|
|
@@ -52,14 +90,26 @@ export class Session {
|
|
|
52
90
|
// identity, not `instanceof`: importing the TransportFault class here would pull the whole
|
|
53
91
|
// transport client into core's (and the ./commons bundle's) module graph, inverting the
|
|
54
92
|
// port direction. ERM-03's degrade still applies to everything else non-EmitRejection.
|
|
55
|
-
|
|
93
|
+
// The batch is taken synchronously, so a read started right after this call already waits for
|
|
94
|
+
// it. With no batch in flight the client's emit starts synchronously, as callers that fire a
|
|
95
|
+
// flush without awaiting it (scaffold's batch cap) rely on; otherwise it waits its turn.
|
|
96
|
+
flush() {
|
|
56
97
|
if (this.#pending.length === 0)
|
|
57
|
-
return;
|
|
98
|
+
return this.#emitting;
|
|
58
99
|
const batch = {
|
|
59
100
|
protocolVersion: 1,
|
|
60
101
|
force: false,
|
|
61
102
|
instructions: this.#pending.splice(0),
|
|
62
103
|
};
|
|
104
|
+
const emit = this.#inFlight === 0 ? this.#emit(batch) : this.#emitting.then(() => this.#emit(batch));
|
|
105
|
+
this.#inFlight++;
|
|
106
|
+
const done = () => {
|
|
107
|
+
this.#inFlight--;
|
|
108
|
+
};
|
|
109
|
+
this.#emitting = emit.then(done, done);
|
|
110
|
+
return emit;
|
|
111
|
+
}
|
|
112
|
+
async #emit(batch) {
|
|
63
113
|
try {
|
|
64
114
|
await this.#client.emit(batch);
|
|
65
115
|
}
|
|
@@ -2,6 +2,7 @@ import type { OpPack, Handle, Query } from "../services/define-dialect.ts";
|
|
|
2
2
|
interface DialectAst<Ast> {
|
|
3
3
|
parse(source: string): Ast;
|
|
4
4
|
print(ast: Ast): string;
|
|
5
|
+
retire?(ast: Ast): void;
|
|
5
6
|
}
|
|
6
7
|
/**
|
|
7
8
|
* Marks an op-pack entry as a query: on the handle it ends the chain and resolves to `fn`'s
|
|
@@ -30,5 +31,5 @@ export declare function handlePathFor(ast: object): string;
|
|
|
30
31
|
* `DialectHandleController`. Op methods are attached dynamically from `ops`' own keys —
|
|
31
32
|
* `Object.keys(ops)` is exactly the set `OpMethods<Ast, Ops>` describes at the type level.
|
|
32
33
|
*/
|
|
33
|
-
export declare function createDialectHandle<Ast, Ops extends OpPack<Ast>>(dialectAst: DialectAst<Ast>, ops: Ops, path: string): Handle<"found", Ast, Ops>;
|
|
34
|
+
export declare function createDialectHandle<Ast, Ops extends OpPack<Ast>>(dialectAst: DialectAst<Ast>, ops: Ops, path: string, name?: string): Handle<"found", Ast, Ops>;
|
|
34
35
|
export {};
|