@pbuilder/sdk 0.1.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/LICENSE +21 -0
- package/README.md +202 -0
- package/dist/bin/pbuilder-codegen.js +506 -0
- package/dist/bin/pbuilder-runner.d.ts +1 -0
- package/dist/bin/pbuilder-runner.js +47 -0
- package/dist/commons/classify-content.d.ts +40 -0
- package/dist/commons/classify-content.js +32 -0
- package/dist/commons/index.d.ts +271 -0
- package/dist/commons/index.js +276 -0
- package/dist/conformance/index.d.ts +115 -0
- package/dist/conformance/index.js +218 -0
- package/dist/conformance/run-vehicle.d.ts +19 -0
- package/dist/conformance/run-vehicle.js +104 -0
- package/dist/core/authoring-error.d.ts +116 -0
- package/dist/core/authoring-error.js +205 -0
- package/dist/core/base-handle.d.ts +17 -0
- package/dist/core/base-handle.js +4 -0
- package/dist/core/context.d.ts +85 -0
- package/dist/core/context.js +356 -0
- package/dist/core/deep-equal.d.ts +1 -0
- package/dist/core/deep-equal.js +29 -0
- package/dist/core/define-dialect.d.ts +94 -0
- package/dist/core/define-dialect.js +121 -0
- package/dist/core/dialect-error.d.ts +8 -0
- package/dist/core/dialect-error.js +26 -0
- package/dist/core/dialect-handle.d.ts +21 -0
- package/dist/core/dialect-handle.js +382 -0
- package/dist/core/directive-factory.d.ts +47 -0
- package/dist/core/directive-factory.js +154 -0
- package/dist/core/emit-rejection.d.ts +19 -0
- package/dist/core/emit-rejection.js +31 -0
- package/dist/core/engine-client.d.ts +7 -0
- package/dist/core/engine-client.js +5 -0
- package/dist/core/fs-errors.d.ts +1 -0
- package/dist/core/fs-errors.js +5 -0
- package/dist/core/handle-state.d.ts +24 -0
- package/dist/core/handle-state.js +4 -0
- package/dist/core/index.d.ts +10 -0
- package/dist/core/index.js +6 -0
- package/dist/core/jsx-name-validator.d.ts +19 -0
- package/dist/core/jsx-name-validator.js +104 -0
- package/dist/core/reject-tail.d.ts +23 -0
- package/dist/core/reject-tail.js +63 -0
- package/dist/core/schema/input-rejection.d.ts +4 -0
- package/dist/core/schema/input-rejection.js +32 -0
- package/dist/core/schema/schema-digest.d.ts +1 -0
- package/dist/core/schema/schema-digest.js +7 -0
- package/dist/core/schema/schema-discovery.d.ts +13 -0
- package/dist/core/schema/schema-discovery.js +51 -0
- package/dist/core/schema/schema-locate.d.ts +10 -0
- package/dist/core/schema/schema-locate.js +192 -0
- package/dist/core/schema/schema-model.d.ts +18 -0
- package/dist/core/schema/schema-model.js +15 -0
- package/dist/core/schema/schema-parse.d.ts +20 -0
- package/dist/core/schema/schema-parse.js +80 -0
- package/dist/core/schema/schema-sufficiency.d.ts +17 -0
- package/dist/core/schema/schema-sufficiency.js +54 -0
- package/dist/core/schema/schema-validate.d.ts +14 -0
- package/dist/core/schema/schema-validate.js +64 -0
- package/dist/core/session.d.ts +13 -0
- package/dist/core/session.js +72 -0
- package/dist/core/wire.d.ts +87 -0
- package/dist/core/wire.js +49 -0
- package/dist/dialects/react/ast.d.ts +25 -0
- package/dist/dialects/react/ast.js +80 -0
- package/dist/dialects/react/index.d.ts +39 -0
- package/dist/dialects/react/index.js +71 -0
- package/dist/dialects/react/ops.d.ts +56 -0
- package/dist/dialects/react/ops.js +186 -0
- package/dist/dialects/typescript/ast.d.ts +42 -0
- package/dist/dialects/typescript/ast.js +93 -0
- package/dist/dialects/typescript/index.d.ts +32 -0
- package/dist/dialects/typescript/index.js +40 -0
- package/dist/dialects/typescript/ops.d.ts +123 -0
- package/dist/dialects/typescript/ops.js +365 -0
- package/dist/dry-run/index.d.ts +2 -0
- package/dist/dry-run/index.js +1 -0
- package/dist/dry-run/plan.d.ts +69 -0
- package/dist/dry-run/plan.js +44 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -0
- package/dist/runner-manifest.json +104 -0
- package/dist/scaffold/classify-transport.d.ts +57 -0
- package/dist/scaffold/classify-transport.js +123 -0
- package/dist/scaffold/containment.d.ts +54 -0
- package/dist/scaffold/containment.js +242 -0
- package/dist/scaffold/expander.d.ts +30 -0
- package/dist/scaffold/expander.js +161 -0
- package/dist/scaffold/filename-pipeline.d.ts +39 -0
- package/dist/scaffold/filename-pipeline.js +125 -0
- package/dist/scaffold/index.d.ts +45 -0
- package/dist/scaffold/index.js +99 -0
- package/dist/scaffold/walk.d.ts +25 -0
- package/dist/scaffold/walk.js +124 -0
- package/dist/testing/contract-fake.d.ts +17 -0
- package/dist/testing/contract-fake.js +221 -0
- package/dist/testing/index.d.ts +84 -0
- package/dist/testing/index.js +82 -0
- package/dist/testing/rejection-messages.d.ts +7 -0
- package/dist/testing/rejection-messages.js +12 -0
- package/dist/transport/bootstrap-bridge.d.ts +33 -0
- package/dist/transport/bootstrap-bridge.js +65 -0
- package/dist/transport/error-text.d.ts +8 -0
- package/dist/transport/error-text.js +44 -0
- package/dist/transport/exit-codes.d.ts +2 -0
- package/dist/transport/exit-codes.js +35 -0
- package/dist/transport/factory-pointer.d.ts +32 -0
- package/dist/transport/factory-pointer.js +63 -0
- package/dist/transport/frame-reader.d.ts +10 -0
- package/dist/transport/frame-reader.js +81 -0
- package/dist/transport/framing.d.ts +20 -0
- package/dist/transport/framing.js +98 -0
- package/dist/transport/runner.d.ts +25 -0
- package/dist/transport/runner.js +308 -0
- package/dist/transport/single-instance-probe.d.ts +23 -0
- package/dist/transport/single-instance-probe.js +119 -0
- package/dist/transport/stdio-engine-client.d.ts +27 -0
- package/dist/transport/stdio-engine-client.js +243 -0
- package/dist/transport/wire-protocol.d.ts +33 -0
- package/dist/transport/wire-protocol.js +22 -0
- package/package.json +93 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// REQ-SEC-07 (ADR-05): at handshake time, before the factory import proceeds, compares the
|
|
2
|
+
// runner's OWN resolved `@pbuilder/sdk` package root against the one the factory's module
|
|
3
|
+
// graph resolves to — a consistency check for the module-level ALS single-instance pin
|
|
4
|
+
// (`context.ts:74`), never an anti-tamper/supply-chain control (A3, explicitly out of
|
|
5
|
+
// scope). Resolution-only: `module.createRequire(anchorUrl).resolve(specifier)` never
|
|
6
|
+
// executes the target module's top-level code — a pure specifier->path lookup, satisfying
|
|
7
|
+
// SEC-07.3 for real, not by convention.
|
|
8
|
+
//
|
|
9
|
+
// ADR-05 DEVIATION (discovered building this slice, not guessed): ADR-05 names Bun's
|
|
10
|
+
// `import.meta.resolveSync` as primary with `createRequire(...).resolve` as fallback "if
|
|
11
|
+
// Bun's import.meta.resolve semantics prove unavailable". Both halves of that premise
|
|
12
|
+
// proved true here: (1) `import.meta.resolveSync` is Bun-only and untyped under
|
|
13
|
+
// `tsconfig.build.json` (this repo's OWN build-time config types `src/**` against plain
|
|
14
|
+
// `"node"`, per the project's Node-type-portable-.d.ts convention — verified by running
|
|
15
|
+
// `bun run build`, which fails `tsc -p tsconfig.build.json` on `Property 'resolveSync'
|
|
16
|
+
// does not exist on type 'ImportMeta'`); (2) `createRequire(...).resolve` does NOT support
|
|
17
|
+
// Node's package self-reference resolution in this Bun version (verified empirically:
|
|
18
|
+
// `import.meta.resolveSync("@pbuilder/sdk", anchor)` resolves this repo's own package by
|
|
19
|
+
// name via its `exports` map, but `createRequire(anchor).resolve("@pbuilder/sdk")` throws
|
|
20
|
+
// "Cannot find module" for the identical anchor) — so it is not a drop-in fallback for the
|
|
21
|
+
// self-reference case. Given `import.meta.resolveSync` is unusable at compile time for the
|
|
22
|
+
// published source tree regardless, `createRequire` is the SOLE mechanism here — fully
|
|
23
|
+
// portable, and correct for the REAL production shape of this check (a factory in a
|
|
24
|
+
// consumer project resolving `@pbuilder/sdk` as an ordinary `node_modules` dependency,
|
|
25
|
+
// never as a self-reference — self-reference only arose in this repo's OWN dogfooding
|
|
26
|
+
// tests, not in any real caller).
|
|
27
|
+
//
|
|
28
|
+
// Constraint 4 (docs/runner-integrity-invariants.md) makes this ENFORCED, not conventional:
|
|
29
|
+
// any `createRequire` reference outside this anchored site fails the build (fit-42).
|
|
30
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
31
|
+
import { createRequire } from "node:module";
|
|
32
|
+
import { fileURLToPath } from "node:url";
|
|
33
|
+
import { dirname, join } from "node:path";
|
|
34
|
+
import { toProjectRelativePath } from "./error-text.js";
|
|
35
|
+
const SDK_SPECIFIER = "@pbuilder/sdk";
|
|
36
|
+
// Resolution-only: never `import()`s the target, only locates it.
|
|
37
|
+
function resolveSpecifierPath(specifier, anchorUrl) {
|
|
38
|
+
return createRequire(anchorUrl).resolve(specifier);
|
|
39
|
+
}
|
|
40
|
+
// Walks up from a resolved file to its nearest package.json ancestor, so two resolutions
|
|
41
|
+
// landing on DIFFERENT files inside the SAME package (e.g. one via `main`, one via a
|
|
42
|
+
// deep-import) still compare equal — the comparison unit is the PACKAGE, not one file.
|
|
43
|
+
function packageRootFor(filePath) {
|
|
44
|
+
let dir = dirname(filePath);
|
|
45
|
+
for (;;) {
|
|
46
|
+
if (existsSync(join(dir, "package.json")))
|
|
47
|
+
return realpathSync(dir);
|
|
48
|
+
const parent = dirname(dir);
|
|
49
|
+
if (parent === dir)
|
|
50
|
+
return realpathSync(dirname(filePath));
|
|
51
|
+
dir = parent;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
// `path.relative(root, root)` is `""` — a project-relative path to the project root
|
|
55
|
+
// itself. Rendered as "." for readability; still never an absolute path.
|
|
56
|
+
function displayRelative(absolutePath) {
|
|
57
|
+
const relative = toProjectRelativePath(absolutePath);
|
|
58
|
+
return relative === "" ? "." : relative;
|
|
59
|
+
}
|
|
60
|
+
function splitMessage(runnerRoot, factoryRoot) {
|
|
61
|
+
return (`single-instance probe: the runner's SDK copy (${displayRelative(runnerRoot)}) and the ` +
|
|
62
|
+
`factory's resolved SDK copy (${displayRelative(factoryRoot)}) are not the same package — ` +
|
|
63
|
+
`a split module graph breaks the single-instance ALS pin`);
|
|
64
|
+
}
|
|
65
|
+
// REQ-SEC-07.3: this module IS part of the runner's own SDK copy — its own on-disk
|
|
66
|
+
// location needs no specifier resolution, only a realpath + package-root walk.
|
|
67
|
+
function runnerOwnPackageRoot() {
|
|
68
|
+
return packageRootFor(fileURLToPath(import.meta.url));
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* REQ-SEC-07: probes whether `factoryUrl`'s module graph would resolve the SAME
|
|
72
|
+
* `@pbuilder/sdk` copy the runner itself is. MUST be called BEFORE the factory's dynamic
|
|
73
|
+
* import (RUN-02/RUN-03) proceeds — resolution-only, never executes any of the factory's
|
|
74
|
+
* or the resolved package's top-level code. A resolution failure (the factory's location
|
|
75
|
+
* has no resolvable `@pbuilder/sdk` at all) fails closed the same way a split does — never
|
|
76
|
+
* throws, never guesses a match.
|
|
77
|
+
*
|
|
78
|
+
* `resolveSpecifier` is injectable (mirrors this codebase's `FrameChannel`/`RunnerIo`
|
|
79
|
+
* pattern) — production always uses the default (real `createRequire` resolution); tests
|
|
80
|
+
* override it ONLY where real package resolution has an orthogonal fixture-construction
|
|
81
|
+
* problem (this repo's own `package.json` has no CJS-`require`-resolvable `exports`
|
|
82
|
+
* condition, so it cannot itself be used as a synthetic "same package" fixture). The
|
|
83
|
+
* resolution MECHANISM itself (never executes, genuinely finds real packages) is proven
|
|
84
|
+
* with the REAL default resolver in the split/unresolvable test cases.
|
|
85
|
+
*/
|
|
86
|
+
export function probeSingleInstance(factoryUrl, resolveSpecifier = resolveSpecifierPath) {
|
|
87
|
+
const runnerRoot = runnerOwnPackageRoot();
|
|
88
|
+
let factoryRoot;
|
|
89
|
+
try {
|
|
90
|
+
factoryRoot = packageRootFor(resolveSpecifier(SDK_SPECIFIER, factoryUrl));
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// Self-contained fallback: `createRequire` does not resolve a package's OWN name from
|
|
94
|
+
// within itself in this Bun version (the self-reference gap documented above). If the
|
|
95
|
+
// factory's OWN nearest package.json ancestor already IS the runner's package root,
|
|
96
|
+
// there is only ONE copy by construction — no separate specifier resolution can prove
|
|
97
|
+
// more than that. This is the ordinary shape of THIS repo's own dogfooding fixtures
|
|
98
|
+
// (factories living inside @pbuilder/sdk's own source tree); a real external consumer's
|
|
99
|
+
// factory is never inside this package, so it always resolves via the primary path
|
|
100
|
+
// above and never reaches this fallback.
|
|
101
|
+
try {
|
|
102
|
+
if (packageRootFor(fileURLToPath(factoryUrl)) === runnerRoot)
|
|
103
|
+
return { ok: true };
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
// Falls through to the original resolution failure below.
|
|
107
|
+
}
|
|
108
|
+
// REQ-WPS-07 (judgment-day F9): fixed text only — the resolver's raw error message
|
|
109
|
+
// embeds the factory's ABSOLUTE path ("Cannot find module ... from '/abs/...'") and
|
|
110
|
+
// must never be interpolated.
|
|
111
|
+
return {
|
|
112
|
+
ok: false,
|
|
113
|
+
message: `single-instance probe: could not resolve "${SDK_SPECIFIER}" from the factory's location`,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
if (runnerRoot === factoryRoot)
|
|
117
|
+
return { ok: true };
|
|
118
|
+
return { ok: false, message: splitMessage(runnerRoot, factoryRoot) };
|
|
119
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { EngineClient } from "../core/engine-client.ts";
|
|
2
|
+
import type { Batch } from "../core/wire.ts";
|
|
3
|
+
export interface FrameChannel {
|
|
4
|
+
write(value: unknown): void;
|
|
5
|
+
read(): Promise<unknown>;
|
|
6
|
+
writeStderr(text: string): void;
|
|
7
|
+
}
|
|
8
|
+
export declare class IntentRejectedError extends Error {
|
|
9
|
+
constructor(message: string);
|
|
10
|
+
}
|
|
11
|
+
export declare class OverlappingRunError extends Error {
|
|
12
|
+
constructor(message: string);
|
|
13
|
+
}
|
|
14
|
+
export declare class TransportFault extends Error {
|
|
15
|
+
readonly kind: "malformed" | "desync" | "oversize" | "timeout" | "eof";
|
|
16
|
+
constructor(kind: TransportFault["kind"], message: string);
|
|
17
|
+
}
|
|
18
|
+
export declare class StdioEngineClient implements EngineClient {
|
|
19
|
+
#private;
|
|
20
|
+
constructor(io: FrameChannel, opts?: {
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
});
|
|
23
|
+
emit(batch: Batch): Promise<void>;
|
|
24
|
+
read(path: string): Promise<string | undefined>;
|
|
25
|
+
commit(): Promise<void>;
|
|
26
|
+
discard(): Promise<void>;
|
|
27
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// REQ-SEC-01/03/04/05/06/08, REQ-WPS-03/04/05/08/10: the first real EngineClient
|
|
2
|
+
// implementer. FIT-10's port allow-list is extended to name this file (ADR-01).
|
|
3
|
+
//
|
|
4
|
+
// ADR-03 sequential single-in-flight, single pending slot: each reverse callback writes
|
|
5
|
+
// exactly one request frame then awaits exactly one response frame — no pending-ID map.
|
|
6
|
+
// Single-in-flight is ENFORCED internally (an internal dispatch chain serializes calls), not
|
|
7
|
+
// merely assumed from the callers' own sequencing — a concurrent caller can never interleave
|
|
8
|
+
// two read loops over the shared channel.
|
|
9
|
+
// ADR-02: the SDK owns the read loop; this class receives an already-framed FrameChannel,
|
|
10
|
+
// never raw stdio bytes (the ONE encode step it performs — the outbound frame body, for the
|
|
11
|
+
// WPS-04.1 cap check — delegates to framing.ts, the codec's single owner).
|
|
12
|
+
//
|
|
13
|
+
// Scope boundary (S-000, happy path only) CLOSED by S-001: routing/discard (WPS-03),
|
|
14
|
+
// fail-closed propagation (SEC-08), injectable timeout (SEC-05), and the EmitRejection
|
|
15
|
+
// precondition/degrade (SEC-04) all now hold.
|
|
16
|
+
import { exceedsEmitBatchBudget } from "../core/wire.js";
|
|
17
|
+
import { EmitRejection } from "../core/emit-rejection.js";
|
|
18
|
+
import { encodeFrameBody, withPreserializedBody } from "./framing.js";
|
|
19
|
+
import { boundMessage } from "./error-text.js";
|
|
20
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
21
|
+
// REQ-SEC-04: directive-level codes carry a failedIndex; batch-level codes never do.
|
|
22
|
+
const DIRECTIVE_LEVEL_CODES = new Set(["collision", "not-found"]);
|
|
23
|
+
const BATCH_LEVEL_CODES = new Set(["unrepresentable", "cap", "unknown"]);
|
|
24
|
+
const RECOGNIZED_EMIT_REJECTION_CODES = new Set([...DIRECTIVE_LEVEL_CODES, ...BATCH_LEVEL_CODES]);
|
|
25
|
+
function isNonNegativeInteger(value) {
|
|
26
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
27
|
+
}
|
|
28
|
+
// REQ-SEC-04 / REQ-WPS-08.2/.3: reconstructs EmitRejection from a host's ir.emit rejection,
|
|
29
|
+
// honoring the directive-vs-batch-level failedIndex precondition. An out-of-contract
|
|
30
|
+
// payload — an unrecognized code, a failedIndex present alongside a batch-level code, or a
|
|
31
|
+
// failedIndex that is negative/non-integer — degrades to code:"unknown" with failedIndex
|
|
32
|
+
// omitted; NEVER guesses an index, NEVER crashes on a malformed payload. `"unknown"` sent
|
|
33
|
+
// explicitly by the host round-trips like any other allowlisted code (WPS-08.3) — it is not
|
|
34
|
+
// itself an out-of-contract signal.
|
|
35
|
+
function isRecognizedEmitRejectionCode(value) {
|
|
36
|
+
return typeof value === "string" && RECOGNIZED_EMIT_REJECTION_CODES.has(value);
|
|
37
|
+
}
|
|
38
|
+
function reconstructEmitRejection(error) {
|
|
39
|
+
const data = error.data;
|
|
40
|
+
const rawCode = data?.emitRejectionCode;
|
|
41
|
+
const rawIndex = data?.failedIndex;
|
|
42
|
+
if (!isRecognizedEmitRejectionCode(rawCode)) {
|
|
43
|
+
return new EmitRejection("unknown", error.message);
|
|
44
|
+
}
|
|
45
|
+
const isDirectiveLevel = DIRECTIVE_LEVEL_CODES.has(rawCode);
|
|
46
|
+
const indexPresent = rawIndex !== undefined;
|
|
47
|
+
const indexValid = isNonNegativeInteger(rawIndex);
|
|
48
|
+
if ((isDirectiveLevel && !indexValid) || (!isDirectiveLevel && indexPresent)) {
|
|
49
|
+
return new EmitRejection("unknown", error.message);
|
|
50
|
+
}
|
|
51
|
+
return new EmitRejection(rawCode, error.message, isDirectiveLevel ? { failedIndex: rawIndex, appliedCount: data?.appliedCount ?? 0 } : undefined);
|
|
52
|
+
}
|
|
53
|
+
// REQ-SEC-03: stable, distinguishable identity for a host-rejected commit/discard intent —
|
|
54
|
+
// distinct from EmitRejection and OverlappingRunError.
|
|
55
|
+
export class IntentRejectedError extends Error {
|
|
56
|
+
constructor(message) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = "IntentRejectedError";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
// REQ-SEC-02: stable, distinguishable identity for an overlapping run-entry invocation —
|
|
62
|
+
// thrown by runner.ts's composition-root reentrancy guard, never by this class itself
|
|
63
|
+
// (this file only owns the error taxonomy's identities, per design § 4.3).
|
|
64
|
+
export class OverlappingRunError extends Error {
|
|
65
|
+
constructor(message) {
|
|
66
|
+
super(message);
|
|
67
|
+
this.name = "OverlappingRunError";
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
// REQ-SEC-05/08/10: the classified wire-fault identity. `kind` distinguishes WHY the run
|
|
71
|
+
// fails closed — a hung host (timeout), an inbound frame over BATCH_CAP_BYTES (oversize),
|
|
72
|
+
// JSON that fails to parse or a length-prefix that undercounts its own body (malformed —
|
|
73
|
+
// this implementation classifies both under one kind: mechanically indistinguishable once
|
|
74
|
+
// the misaligned bytes reach decodeFrameBody, see frame-reader.ts), and stdin ending
|
|
75
|
+
// mid-frame or while a callback is pending (eof).
|
|
76
|
+
export class TransportFault extends Error {
|
|
77
|
+
kind;
|
|
78
|
+
constructor(kind, message) {
|
|
79
|
+
super(message);
|
|
80
|
+
this.name = "TransportFault";
|
|
81
|
+
this.kind = kind;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
// Module-private control-flow signal: ends an ABANDONED read loop (its caller already
|
|
85
|
+
// rejected via timeout) without consuming the frame it was awaiting. Never escapes this
|
|
86
|
+
// module — the abandoned loop's promise is defused in #awaitResponse.
|
|
87
|
+
class AbandonedCallSignal {
|
|
88
|
+
}
|
|
89
|
+
export class StdioEngineClient {
|
|
90
|
+
#io;
|
|
91
|
+
#timeoutMs;
|
|
92
|
+
#nextRequestId = 0;
|
|
93
|
+
// ADR-03 single-in-flight, enforced HERE: every dispatch chains behind the previous one,
|
|
94
|
+
// so two concurrent public calls can never interleave writes/reads on the shared channel.
|
|
95
|
+
#chain = Promise.resolve();
|
|
96
|
+
// A channel read left pending by a timed-out (abandoned) call. The successor call adopts
|
|
97
|
+
// it instead of issuing a second concurrent read — the frame that eventually satisfies it
|
|
98
|
+
// is consumed exactly once, by the live call, never discarded by a zombie loop.
|
|
99
|
+
#danglingRead;
|
|
100
|
+
constructor(io, opts) {
|
|
101
|
+
this.#io = io;
|
|
102
|
+
this.#timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
103
|
+
}
|
|
104
|
+
#enqueue(dispatch) {
|
|
105
|
+
const run = this.#chain.then(dispatch);
|
|
106
|
+
// The chain must survive a failed dispatch (the failure belongs to that call alone).
|
|
107
|
+
this.#chain = run.then(() => undefined, () => undefined);
|
|
108
|
+
return run;
|
|
109
|
+
}
|
|
110
|
+
async #call(method, params) {
|
|
111
|
+
return this.#enqueue(() => {
|
|
112
|
+
const id = `s${this.#nextRequestId++}`;
|
|
113
|
+
this.#io.write({ type: "request", id, method, params });
|
|
114
|
+
return this.#awaitResponse(id);
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
// REQ-SEC-05: bounds the wait for the matching response. A response arriving before the
|
|
118
|
+
// bound resolves normally and clears the timer — no stray rejection ever raised
|
|
119
|
+
// afterward. Expiry rejects TransportFault{kind:"timeout"} and marks the call ABANDONED:
|
|
120
|
+
// its read loop stops at the next frame WITHOUT consuming it (no zombie loop discarding a
|
|
121
|
+
// successor's response). The abandoned promise is defused so a later settle never
|
|
122
|
+
// surfaces as an unhandled rejection.
|
|
123
|
+
async #awaitResponse(id) {
|
|
124
|
+
const call = { abandoned: false };
|
|
125
|
+
const matching = this.#readUntilMatch(id, call);
|
|
126
|
+
let timer;
|
|
127
|
+
const timeout = new Promise((_, reject) => {
|
|
128
|
+
timer = setTimeout(() => {
|
|
129
|
+
reject(new TransportFault("timeout", `timed out after ${this.#timeoutMs}ms waiting for a response to ${id}`));
|
|
130
|
+
}, this.#timeoutMs);
|
|
131
|
+
});
|
|
132
|
+
try {
|
|
133
|
+
return await Promise.race([matching, timeout]);
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
// Timeout won (or the loop itself rejected — then the loop is already finished and
|
|
137
|
+
// this flag is inert): stop the loop before it can consume a successor's frame.
|
|
138
|
+
call.abandoned = true;
|
|
139
|
+
throw err;
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
matching.catch(() => {
|
|
144
|
+
// Defused: this rejection is only interesting if `matching` won the race above;
|
|
145
|
+
// when `timeout` wins instead, the abandoned promise is never awaited again.
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
// Reads one frame off the shared channel, adopting a dangling read left behind by an
|
|
150
|
+
// abandoned predecessor. An abandoned call NEVER consumes: the settled read stays parked
|
|
151
|
+
// in #danglingRead for the live successor.
|
|
152
|
+
async #readNextFrame(call) {
|
|
153
|
+
const read = (this.#danglingRead ??= this.#io.read());
|
|
154
|
+
let frame;
|
|
155
|
+
try {
|
|
156
|
+
frame = await read;
|
|
157
|
+
}
|
|
158
|
+
catch (err) {
|
|
159
|
+
this.#danglingRead = undefined;
|
|
160
|
+
throw call.abandoned ? new AbandonedCallSignal() : err;
|
|
161
|
+
}
|
|
162
|
+
if (call.abandoned)
|
|
163
|
+
throw new AbandonedCallSignal();
|
|
164
|
+
this.#danglingRead = undefined;
|
|
165
|
+
return frame;
|
|
166
|
+
}
|
|
167
|
+
// REQ-WPS-03: reads raw frames until the one matching `id` arrives, silently discarding
|
|
168
|
+
// (wire-silent, stderr-noted) anything else — an unrecognized/missing type, or a
|
|
169
|
+
// response for a different (stale/foreign) id. A discard never affects this call's
|
|
170
|
+
// ability to keep reading (M16 liveness). Faults thrown by the channel (SEC-08, e.g. a
|
|
171
|
+
// frame-reader TransportFault) propagate through unchanged.
|
|
172
|
+
async #readUntilMatch(id, call) {
|
|
173
|
+
const discard = (what) => {
|
|
174
|
+
this.#io.writeStderr(boundMessage(`discarding ${what} while awaiting response to ${id}`));
|
|
175
|
+
};
|
|
176
|
+
for (;;) {
|
|
177
|
+
const frame = await this.#readNextFrame(call);
|
|
178
|
+
if (typeof frame !== "object" || frame === null) {
|
|
179
|
+
discard("non-object frame");
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
const candidate = frame;
|
|
183
|
+
if (candidate.type !== "response") {
|
|
184
|
+
discard(`frame with type "${String(candidate.type)}"`);
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (candidate.id !== id) {
|
|
188
|
+
discard(`response for id "${String(candidate.id)}"`);
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
return frame;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
// REQ-WPS-04.1 (spec V4, judgment-day R2): the outbound cap is enforced via the ONE
|
|
195
|
+
// deterministic batch-anchored measurer (`exceedsEmitBatchBudget`, wire.ts) — the SAME
|
|
196
|
+
// check `ContractFake.emit` runs (FEH-01 parity), independent of this call's request-id
|
|
197
|
+
// length. The budget reserves a fixed allowance bounding every possible envelope's
|
|
198
|
+
// overhead, so an accepted batch's ENCODED FRAME BODY can never exceed BATCH_CAP_BYTES
|
|
199
|
+
// (the inbound leg's measure). An over-budget batch is rejected LOCALLY — no id minted,
|
|
200
|
+
// nothing written to the wire. On acceptance the frame body is serialized exactly ONCE
|
|
201
|
+
// and handed to the writer (withPreserializedBody). REQ-SEC-04: a host rejection
|
|
202
|
+
// reconstructs via the failedIndex precondition.
|
|
203
|
+
async emit(batch) {
|
|
204
|
+
const response = await this.#enqueue(() => {
|
|
205
|
+
if (exceedsEmitBatchBudget(batch)) {
|
|
206
|
+
throw new EmitRejection("cap", "serialized ir.emit batch exceeds the outbound frame-body budget — not written to the wire");
|
|
207
|
+
}
|
|
208
|
+
const id = `s${this.#nextRequestId++}`;
|
|
209
|
+
const frame = { type: "request", id, method: "ir.emit", params: { batch } };
|
|
210
|
+
this.#io.write(withPreserializedBody(frame, encodeFrameBody(frame)));
|
|
211
|
+
return this.#awaitResponse(id);
|
|
212
|
+
});
|
|
213
|
+
if (response.error !== undefined) {
|
|
214
|
+
throw reconstructEmitRejection(response.error);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
// REQ-SEC-06: null -> undefined (not-found), {content: ""} -> "" (empty file), never
|
|
218
|
+
// conflated. A host REJECTION (error envelope, WPS-10) throws the same host-refusal
|
|
219
|
+
// identity commit/discard use — never silently resolved as not-found (the trichotomy
|
|
220
|
+
// stays three-way; a refusal is not an absence).
|
|
221
|
+
async read(path) {
|
|
222
|
+
const response = await this.#call("tree.read", { path });
|
|
223
|
+
if (response.error !== undefined) {
|
|
224
|
+
throw new IntentRejectedError(response.error.message);
|
|
225
|
+
}
|
|
226
|
+
const result = response.result;
|
|
227
|
+
if (result === null || result === undefined)
|
|
228
|
+
return undefined;
|
|
229
|
+
return result.content;
|
|
230
|
+
}
|
|
231
|
+
async commit() {
|
|
232
|
+
const response = await this.#call("ir.commit", {});
|
|
233
|
+
if (response.error !== undefined) {
|
|
234
|
+
throw new IntentRejectedError(response.error.message);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
async discard() {
|
|
238
|
+
const response = await this.#call("ir.discard", {});
|
|
239
|
+
if (response.error !== undefined) {
|
|
240
|
+
throw new IntentRejectedError(response.error.message);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export declare const WIRE_PROTOCOL_VERSION = 1;
|
|
2
|
+
export declare const BRIDGE_CONTRACT_VERSION = 1;
|
|
3
|
+
export declare const REVERSE_CALLBACK_METHODS: readonly ["tree.read", "ir.emit", "ir.commit", "ir.discard"];
|
|
4
|
+
export type ReverseMethod = (typeof REVERSE_CALLBACK_METHODS)[number];
|
|
5
|
+
export interface ReadyGreeting {
|
|
6
|
+
method: "ready";
|
|
7
|
+
protocolVersion: number;
|
|
8
|
+
}
|
|
9
|
+
export interface RequestFrame {
|
|
10
|
+
type: "request";
|
|
11
|
+
id: `s${number}`;
|
|
12
|
+
method: ReverseMethod;
|
|
13
|
+
params: unknown;
|
|
14
|
+
}
|
|
15
|
+
export interface EmitRejectionData {
|
|
16
|
+
emitRejectionCode: "collision" | "not-found" | "unrepresentable" | "cap" | "unknown";
|
|
17
|
+
failedIndex?: number;
|
|
18
|
+
appliedCount: number;
|
|
19
|
+
}
|
|
20
|
+
export interface WireError {
|
|
21
|
+
code: number;
|
|
22
|
+
message: string;
|
|
23
|
+
data?: EmitRejectionData;
|
|
24
|
+
}
|
|
25
|
+
export interface ResponseFrame {
|
|
26
|
+
type: "response";
|
|
27
|
+
id: string;
|
|
28
|
+
result?: unknown;
|
|
29
|
+
error?: WireError;
|
|
30
|
+
}
|
|
31
|
+
export declare function isStructurallyValidGreeting(value: unknown): value is ReadyGreeting;
|
|
32
|
+
export declare function versionMatches(greeting: ReadyGreeting): boolean;
|
|
33
|
+
export declare function isReverseMethod(value: string): value is ReverseMethod;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// src/transport/wire-protocol.ts — wire-level constants, frame shapes, and structural
|
|
2
|
+
// guards (WPS-02/03/05/09). design.md § 4.3 Data Model gives these signatures verbatim.
|
|
3
|
+
export const WIRE_PROTOCOL_VERSION = 1; // ready.protocolVersion (transport) — DISTINCT from Batch.protocolVersion (IR)
|
|
4
|
+
export const BRIDGE_CONTRACT_VERSION = 1; // in-process JS bridge; independent of the wire (BRB-01)
|
|
5
|
+
export const REVERSE_CALLBACK_METHODS = ["tree.read", "ir.emit", "ir.commit", "ir.discard"];
|
|
6
|
+
// REQ-WPS-02.3: structural validity is method === "ready" plus an integer protocolVersion —
|
|
7
|
+
// no other shape (missing field, wrong type, non-integer version) qualifies.
|
|
8
|
+
export function isStructurallyValidGreeting(value) {
|
|
9
|
+
if (typeof value !== "object" || value === null)
|
|
10
|
+
return false;
|
|
11
|
+
const candidate = value;
|
|
12
|
+
return candidate.method === "ready" && typeof candidate.protocolVersion === "number" && Number.isInteger(candidate.protocolVersion);
|
|
13
|
+
}
|
|
14
|
+
// REQ-WPS-02.1/.2: an exact match against the runner's compiled-in wire version — never a
|
|
15
|
+
// range or a >= check.
|
|
16
|
+
export function versionMatches(greeting) {
|
|
17
|
+
return greeting.protocolVersion === WIRE_PROTOCOL_VERSION;
|
|
18
|
+
}
|
|
19
|
+
// REQ-WPS-05: the runner MUST NOT issue any reverse-callback method outside this closed set.
|
|
20
|
+
export function isReverseMethod(value) {
|
|
21
|
+
return REVERSE_CALLBACK_METHODS.includes(value);
|
|
22
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@pbuilder/sdk",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The public TypeScript/Bun authoring layer for Project Builder schematics. Authors file mutations (create, modify, remove, rename, move, copy, copyIn), lowers them to IR, and talks to the Project Builder engine over framed stdio (see docs/engine-sdk-wire-spec.md).",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"private": false,
|
|
8
|
+
"author": "Project Builder Schematics",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/Project-Builder-Schematics/project-builder-sdk.git"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/Project-Builder-Schematics/project-builder-sdk#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/Project-Builder-Schematics/project-builder-sdk/issues"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"project-builder",
|
|
19
|
+
"schematics",
|
|
20
|
+
"code-generation",
|
|
21
|
+
"scaffolding",
|
|
22
|
+
"ast",
|
|
23
|
+
"codemod"
|
|
24
|
+
],
|
|
25
|
+
"engines": {
|
|
26
|
+
"bun": "1.3.14",
|
|
27
|
+
"node": ">=25.9.0"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist"
|
|
34
|
+
],
|
|
35
|
+
"bin": {
|
|
36
|
+
"pbuilder-codegen": "dist/bin/pbuilder-codegen.js"
|
|
37
|
+
},
|
|
38
|
+
"exports": {
|
|
39
|
+
".": {
|
|
40
|
+
"types": "./dist/index.d.ts",
|
|
41
|
+
"import": "./dist/index.js",
|
|
42
|
+
"default": "./dist/index.js"
|
|
43
|
+
},
|
|
44
|
+
"./commons": {
|
|
45
|
+
"types": "./dist/commons/index.d.ts",
|
|
46
|
+
"import": "./dist/commons/index.js",
|
|
47
|
+
"default": "./dist/commons/index.js"
|
|
48
|
+
},
|
|
49
|
+
"./conformance": {
|
|
50
|
+
"types": "./dist/conformance/index.d.ts",
|
|
51
|
+
"import": "./dist/conformance/index.js",
|
|
52
|
+
"default": "./dist/conformance/index.js"
|
|
53
|
+
},
|
|
54
|
+
"./testing": {
|
|
55
|
+
"types": "./dist/testing/index.d.ts",
|
|
56
|
+
"import": "./dist/testing/index.js",
|
|
57
|
+
"default": "./dist/testing/index.js"
|
|
58
|
+
},
|
|
59
|
+
"./typescript": {
|
|
60
|
+
"types": "./dist/dialects/typescript/index.d.ts",
|
|
61
|
+
"import": "./dist/dialects/typescript/index.js",
|
|
62
|
+
"default": "./dist/dialects/typescript/index.js"
|
|
63
|
+
},
|
|
64
|
+
"./react": {
|
|
65
|
+
"types": "./dist/dialects/react/index.d.ts",
|
|
66
|
+
"import": "./dist/dialects/react/index.js",
|
|
67
|
+
"default": "./dist/dialects/react/index.js"
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
"scripts": {
|
|
71
|
+
"test": "bun test",
|
|
72
|
+
"typecheck": "tsc --noEmit",
|
|
73
|
+
"typecheck:permissive-proof": "tsc --noEmit -p tsconfig.permissive-proof.json",
|
|
74
|
+
"prebuild": "rm -rf dist",
|
|
75
|
+
"build": "tsc -p tsconfig.build.json && bun run build:codegen && bun run build:manifest",
|
|
76
|
+
"build:codegen": "bun build bin/pbuilder-codegen.ts --outfile dist/bin/pbuilder-codegen.js --target node --banner \"#!/usr/bin/env node\"",
|
|
77
|
+
"build:manifest": "bun scripts/generate-runner-manifest.ts",
|
|
78
|
+
"regen:closure-baseline": "bun scripts/regen-closure-baseline.ts",
|
|
79
|
+
"prepublishOnly": "bun run build",
|
|
80
|
+
"publish:dry": "npm publish --dry-run",
|
|
81
|
+
"registry:up": "bunx verdaccio --config tools/verdaccio/config.yaml --listen 4873",
|
|
82
|
+
"publish:local": "npm publish --registry http://localhost:4873 --tag local",
|
|
83
|
+
"link:sdk": "bun run build && bun link"
|
|
84
|
+
},
|
|
85
|
+
"devDependencies": {
|
|
86
|
+
"@types/bun": "^1.3.14",
|
|
87
|
+
"expect-type": "^1.3.0",
|
|
88
|
+
"typescript": "^7.0.2"
|
|
89
|
+
},
|
|
90
|
+
"dependencies": {
|
|
91
|
+
"ts-morph": "28.0.0"
|
|
92
|
+
}
|
|
93
|
+
}
|