@pbuilder/sdk 0.16.0 → 0.18.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 +75 -1
- package/dist/bin/pbuilder-conformance.d.ts +2 -0
- package/dist/bin/pbuilder-conformance.js +26 -0
- package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.d.ts +7 -1
- package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.js +2 -1
- package/dist/bounded-contexts/authoring/application/usecases/scaffold/expander.js +4 -4
- package/dist/bounded-contexts/authoring/domain/aggregates/session/session.d.ts +1 -0
- package/dist/bounded-contexts/authoring/domain/aggregates/session/session.js +54 -4
- 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/services/define-dialect.d.ts +48 -10
- package/dist/bounded-contexts/authoring/domain/services/define-dialect.js +37 -9
- 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 +51 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.js +49 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.d.ts +11 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.js +139 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/ast.d.ts +29 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/ast.js +41 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/index.d.ts +44 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/index.js +45 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/names.d.ts +7 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/names.js +72 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/ops.d.ts +19 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/ops.js +255 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/pack.d.ts +9 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/pack.js +2 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/syntax.d.ts +26 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/syntax.js +111 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/tree-sitter-c_sharp.LICENSE +23 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/tree-sitter-c_sharp.wasm +0 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ast.d.ts +22 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ast.js +17 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.d.ts +55 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.js +54 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.d.ts +7 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.js +162 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/xml.d.ts +20 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/xml.js +50 -0
- 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 +20 -0
- package/dist/bounded-contexts/authoring/testing/conformance/run-package.js +129 -0
- package/dist/bounded-contexts/authoring/testing/harness/index.d.ts +3 -0
- package/dist/bounded-contexts/authoring/testing/harness/index.js +5 -1
- 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 +42 -3
- package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.d.ts +13 -0
- package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.js +25 -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/dialects/aspnet/index.d.ts +1 -0
- package/dist/dialects/aspnet/index.js +1 -0
- package/dist/dialects/csharp/index.d.ts +1 -0
- package/dist/dialects/csharp/index.js +1 -0
- package/dist/dialects/msbuild/index.d.ts +1 -0
- package/dist/dialects/msbuild/index.js +1 -0
- package/dist/runner-manifest.json +10 -6
- package/package.json +27 -3
package/README.md
CHANGED
|
@@ -576,7 +576,8 @@ When string-level mutation isn't enough — "add an import to this module", "set
|
|
|
576
576
|
this JSX element" — **dialects** provide structured, AST-aware operations for one file
|
|
577
577
|
type: see [authoring a dialect](./docs/guides/authoring-a-dialect.md) for the full story. Seven
|
|
578
578
|
ship today: `@pbuilder/sdk/typescript`, `@pbuilder/sdk/react`, `@pbuilder/sdk/nestjs`,
|
|
579
|
-
`@pbuilder/sdk/angular`, `@pbuilder/sdk/json`, `@pbuilder/sdk/yaml`,
|
|
579
|
+
`@pbuilder/sdk/angular`, `@pbuilder/sdk/json`, `@pbuilder/sdk/yaml`, `@pbuilder/sdk/css`,
|
|
580
|
+
`@pbuilder/sdk/csharp`, `@pbuilder/sdk/aspnet`, and `@pbuilder/sdk/msbuild`.
|
|
580
581
|
|
|
581
582
|
A dialect's entry point is its own `find(path)`: it opens a **coalescing, awaitable
|
|
582
583
|
handle**. Every op you chain mutates the same live AST, and the handle serializes to
|
|
@@ -612,6 +613,7 @@ await ts.find("src/index.ts")
|
|
|
612
613
|
| `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. |
|
|
613
614
|
| `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. |
|
|
614
615
|
| `.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. |
|
|
616
|
+
| `.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. |
|
|
615
617
|
|
|
616
618
|
The `add*` ops fail loud on a name collision with an existing value declaration or import
|
|
617
619
|
binding (two value declarations sharing a name is invalid TypeScript); a `type`/`interface`
|
|
@@ -713,6 +715,58 @@ which ends the chain and resolves to `{ value, important }` (also exported as
|
|
|
713
715
|
`getDeclaration(root, target, property)` for use inside `.modify(fn)`). `.modify(fn)` exposes
|
|
714
716
|
[postcss](https://postcss.org/). See [the CSS dialect guide](./docs/guides/css-dialect.md).
|
|
715
717
|
|
|
718
|
+
### `@pbuilder/sdk/csharp`
|
|
719
|
+
|
|
720
|
+
Adds using directives, base types, members and primary constructor parameters to `.cs` files.
|
|
721
|
+
An op that takes a type name can import its namespace with `from`; everything else keeps its bytes.
|
|
722
|
+
|
|
723
|
+
```ts
|
|
724
|
+
import * as csharp from "@pbuilder/sdk/csharp";
|
|
725
|
+
|
|
726
|
+
await csharp
|
|
727
|
+
.find("src/Shop.Infrastructure/SqlOrders.cs")
|
|
728
|
+
.addBaseType("SqlOrders", "IOrders", { from: "Shop.Application.Ports" })
|
|
729
|
+
.addConstructorParameter("SqlOrders", "db", "ShopDb", { from: "Shop.Data" });
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
Named ops: `addUsing`, `addBaseType`, `addMember`, `addConstructorParameter`. `.modify(fn)` exposes
|
|
733
|
+
[web-tree-sitter](https://github.com/tree-sitter/tree-sitter/tree/master/lib/binding_web) and the
|
|
734
|
+
C# `language`. See [the C# dialect guide](./docs/guides/csharp-dialect.md).
|
|
735
|
+
|
|
736
|
+
### `@pbuilder/sdk/aspnet`
|
|
737
|
+
|
|
738
|
+
Every `@pbuilder/sdk/csharp` op, plus `addService`, which registers a service in the dependency
|
|
739
|
+
injection container: in the top-level statements of `Program.cs`, or in one
|
|
740
|
+
`IServiceCollection` extension method.
|
|
741
|
+
|
|
742
|
+
```ts
|
|
743
|
+
import * as aspnet from "@pbuilder/sdk/aspnet";
|
|
744
|
+
|
|
745
|
+
await aspnet
|
|
746
|
+
.find("Program.cs")
|
|
747
|
+
.addService("Scoped", "IOrders", "SqlOrders", { serviceFrom: "Shop.Application.Ports", implementationFrom: "Shop.Infrastructure" });
|
|
748
|
+
```
|
|
749
|
+
|
|
750
|
+
See [the ASP.NET dialect guide](./docs/guides/aspnet-dialect.md).
|
|
751
|
+
|
|
752
|
+
### `@pbuilder/sdk/msbuild`
|
|
753
|
+
|
|
754
|
+
Adds project references to `.csproj`, `.props` and `.targets` files, and projects to `.slnx`
|
|
755
|
+
solutions, by editing the XML text, never through the `dotnet` CLI; the classic `.sln` is rejected.
|
|
756
|
+
|
|
757
|
+
```ts
|
|
758
|
+
import * as msbuild from "@pbuilder/sdk/msbuild";
|
|
759
|
+
|
|
760
|
+
await msbuild
|
|
761
|
+
.find("src/Shop.Infrastructure/Shop.Infrastructure.csproj")
|
|
762
|
+
.addProjectReference("../Shop.Application/Shop.Application.csproj");
|
|
763
|
+
|
|
764
|
+
await msbuild.find("Shop.slnx").addProject("src/Shop.Api/Shop.Api.csproj", { folder: "/src/" });
|
|
765
|
+
```
|
|
766
|
+
|
|
767
|
+
Named ops: `addProjectReference`, `addProject`. `.modify(fn)` exposes [saxes](https://github.com/lddubeau/saxes).
|
|
768
|
+
See [the MSBuild dialect guide](./docs/guides/msbuild-dialect.md).
|
|
769
|
+
|
|
716
770
|
### `@pbuilder/sdk/nestjs`
|
|
717
771
|
|
|
718
772
|
Every `@pbuilder/sdk/typescript` op, plus ops that import a class and register it in the
|
|
@@ -786,6 +840,26 @@ still flushes as a **single** write. Two things to respect:
|
|
|
786
840
|
callbacks are your own trust; before importing a *third-party* dialect or op-pack built
|
|
787
841
|
on it, read [SECURITY.md](./SECURITY.md).
|
|
788
842
|
|
|
843
|
+
### `.inspect()` — reading the AST back
|
|
844
|
+
|
|
845
|
+
`.inspect(ast => value)` is the read counterpart of `.modify()`. It hands the callback the same
|
|
846
|
+
live AST, after every op chained before it, and resolves to what the callback returns. It ends
|
|
847
|
+
the chain, emits nothing, and is offered to every factory, so a generator can read a value to
|
|
848
|
+
decide what to write:
|
|
849
|
+
|
|
850
|
+
```ts
|
|
851
|
+
import * as ts from "@pbuilder/sdk/typescript";
|
|
852
|
+
|
|
853
|
+
const imports = await ts.find("src/main.ts")
|
|
854
|
+
.addImport("BooksModule", "./books/books.module")
|
|
855
|
+
.inspect((ast) => ast.getImportDeclarations().length);
|
|
856
|
+
```
|
|
857
|
+
|
|
858
|
+
The callback must not change the AST. The SDK prints the file before and after it, and a
|
|
859
|
+
difference fails the factory with `inspect() must not change "<path>"`. A callback that throws
|
|
860
|
+
fails it with `inspect() on "<path>" threw`, without the original message. Return plain data:
|
|
861
|
+
a node you keep goes stale after the next edit.
|
|
862
|
+
|
|
789
863
|
### Going deeper
|
|
790
864
|
|
|
791
865
|
Everything dialect-related lives in one reference page —
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// `pbuilder-conformance --dialect <installed package dir>` (CA-13): prints one JSON report line.
|
|
3
|
+
// Exit 0: the fixture passed. Exit 1: it ran and failed, a missing fixture included. Exit 2: it
|
|
4
|
+
// could not run, with nothing on stdout. Runs under Bun, from the SDK root of the Run, so the
|
|
5
|
+
// dialect's `@pbuilder/sdk` imports reach this same SDK.
|
|
6
|
+
import { checkDialectPackage } from "../conformance/index.js";
|
|
7
|
+
import { redirectConsoleToStderr } from "../shared-kernel/framing.js";
|
|
8
|
+
// The fixture runs the author's code, so everything but the report goes to stderr.
|
|
9
|
+
const writeReport = process.stdout.write.bind(process.stdout);
|
|
10
|
+
Object.defineProperty(process, "stdout", { value: process.stderr, writable: true, configurable: true });
|
|
11
|
+
redirectConsoleToStderr();
|
|
12
|
+
const COULD_NOT_RUN = 2;
|
|
13
|
+
async function main(argv) {
|
|
14
|
+
if (argv.length !== 2 || argv[0] !== "--dialect" || argv[1] === "") {
|
|
15
|
+
process.stderr.write("usage: pbuilder-conformance --dialect <installed package dir>\n");
|
|
16
|
+
return COULD_NOT_RUN;
|
|
17
|
+
}
|
|
18
|
+
const report = await checkDialectPackage(argv[1]);
|
|
19
|
+
await new Promise((done) => writeReport(`${JSON.stringify(report)}\n`, () => done()));
|
|
20
|
+
return report.passed ? 0 : 1;
|
|
21
|
+
}
|
|
22
|
+
// Exits explicitly: a timer or socket the author's code left open must not keep the process alive.
|
|
23
|
+
main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
|
|
24
|
+
const detail = err instanceof Error && err.message.startsWith("pbuilder-conformance:") ? err.message : "the fixture could not run";
|
|
25
|
+
process.stderr.write(`${detail}\n`, () => process.exit(COULD_NOT_RUN));
|
|
26
|
+
});
|
|
@@ -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;
|
|
@@ -78,9 +79,14 @@ export declare function requirePackageAnchors(missingAnchorMessage: string): {
|
|
|
78
79
|
* const runner = defineFactory<Input>(bareFactory, { packageDir: import.meta.dir });
|
|
79
80
|
* await runner(input, { client });
|
|
80
81
|
*/
|
|
81
|
-
export declare function defineFactory<O>(fn: (o: O) => void | Promise<void>, options?: {
|
|
82
|
+
export declare function defineFactory<O>(fn: (o: O) => void | Promise<void>, options?: ({
|
|
82
83
|
packageDir: string | URL;
|
|
83
84
|
packageFiles: PackageFiles;
|
|
85
|
+
} | {
|
|
86
|
+
packageDir?: undefined;
|
|
87
|
+
packageFiles?: undefined;
|
|
88
|
+
}) & {
|
|
89
|
+
declaredDialects?: readonly string[];
|
|
84
90
|
}): (o: O, deps: {
|
|
85
91
|
client: EngineClient;
|
|
86
92
|
}) => Promise<void>;
|
|
@@ -200,7 +200,7 @@ export function defineFactory(fn, options) {
|
|
|
200
200
|
const wrapped = async (o, { client }) => {
|
|
201
201
|
let packageAnchors;
|
|
202
202
|
let packageFiles;
|
|
203
|
-
if (options !== undefined) {
|
|
203
|
+
if (options?.packageDir !== undefined) {
|
|
204
204
|
const pkg = { files: options.packageFiles, dir: resolvePackageDir(options.packageDir) };
|
|
205
205
|
// REQ-RBV-06: exactly TWO reads, in this order — reserved-name check, then schema
|
|
206
206
|
// validation. No third (containment-ceiling) read exists (ADR-0077 §C).
|
|
@@ -215,6 +215,7 @@ export function defineFactory(fn, options) {
|
|
|
215
215
|
dialects: new DialectRegistryImpl(),
|
|
216
216
|
packageAnchors,
|
|
217
217
|
packageFiles,
|
|
218
|
+
declaredDialects: new Set(options?.declaredDialects),
|
|
218
219
|
};
|
|
219
220
|
// ADR-01: no `finally` — success (commit) and failure (discard) are distinct paths.
|
|
220
221
|
// The final flush is INSIDE the try, so a flush-time emit rejection (already an
|
|
@@ -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,6 +4,7 @@ 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>;
|
|
@@ -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.
|
|
@@ -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 {};
|
|
@@ -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
|
-
|
|
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
|
-
|
|
170
|
-
|
|
171
|
-
|
|
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
|
-
|
|
209
|
+
next = this.#dialectAst.parse(content);
|
|
179
210
|
}
|
|
180
211
|
catch {
|
|
181
212
|
throw dialectError(`could not parse "${this.#path}"`);
|
|
182
213
|
}
|
|
183
|
-
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
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
|
-
|
|
279
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(`${
|
|
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
|
-
|
|
310
|
-
|
|
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.#
|
|
397
|
+
this.#relocate((factory) => factory.rename({ path: this.#path, newName, force: opts?.force }));
|
|
334
398
|
}
|
|
335
399
|
runMove(toDir, opts) {
|
|
336
|
-
this.#
|
|
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;
|