@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,17 @@
|
|
|
1
|
+
export interface ReadOps {
|
|
2
|
+
read(): Promise<string | undefined>;
|
|
3
|
+
}
|
|
4
|
+
export interface WriteOps {
|
|
5
|
+
replaceContent(content: string): WritableHandleRef;
|
|
6
|
+
rename(newName: string, opts?: {
|
|
7
|
+
force?: boolean;
|
|
8
|
+
}): WritableHandleRef;
|
|
9
|
+
move(toDir: string, opts?: {
|
|
10
|
+
force?: boolean;
|
|
11
|
+
}): WritableHandleRef;
|
|
12
|
+
copy(to: string, opts?: {
|
|
13
|
+
force?: boolean;
|
|
14
|
+
}): WritableHandleRef;
|
|
15
|
+
}
|
|
16
|
+
export interface WritableHandleRef extends ReadOps, WriteOps {
|
|
17
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import type { EngineClient } from "./engine-client.ts";
|
|
3
|
+
import { DirectiveFactory } from "./directive-factory.ts";
|
|
4
|
+
import { Session } from "./session.ts";
|
|
5
|
+
export interface DialectRegistry {
|
|
6
|
+
register(handle: {
|
|
7
|
+
readonly settle: () => Promise<void>;
|
|
8
|
+
}): void;
|
|
9
|
+
drain(): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
export interface RunContext {
|
|
12
|
+
session: Session;
|
|
13
|
+
factory: DirectiveFactory;
|
|
14
|
+
dialects: DialectRegistry;
|
|
15
|
+
runFailure?: {
|
|
16
|
+
reason: unknown;
|
|
17
|
+
};
|
|
18
|
+
packageAnchors?: {
|
|
19
|
+
packageDir: string;
|
|
20
|
+
packageRoot: string;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export declare const RUN_ALS_REGISTRY_KEY = "@pbuilder/sdk:core/context#run-als";
|
|
24
|
+
export declare function resolveRunAls(slotValue: unknown): AsyncLocalStorage<RunContext>;
|
|
25
|
+
export declare function isDefineFactoryWrapped(value: unknown): boolean;
|
|
26
|
+
export declare function currentContext(): RunContext;
|
|
27
|
+
export declare function requirePackageAnchors(missingAnchorMessage: string): {
|
|
28
|
+
packageDir: string;
|
|
29
|
+
packageRoot: string;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Builds a run-context and runs the factory inside it, flushing buffered
|
|
33
|
+
* directives at run end (REQ-KIT-05) — a write-only factory still emits.
|
|
34
|
+
*
|
|
35
|
+
* All-or-nothing contract (ADR-01): on success the full directive batch is committed;
|
|
36
|
+
* if `fn` throws (or the run-end flush rejects), the staged set is discarded and the
|
|
37
|
+
* engine commits NOTHING. The original (or attributed) error propagates to the caller —
|
|
38
|
+
* a thrown factory never leaves a partial set of mutations committed.
|
|
39
|
+
*
|
|
40
|
+
* `options.packageDir` (pass `import.meta.dir`, never `import.meta.url`) opts a factory
|
|
41
|
+
* into schema-derived run-boundary validation against its adjacent `schema.json`; a bare
|
|
42
|
+
* `defineFactory(fn)` call is the untyped opt-out and runs exactly as before this option
|
|
43
|
+
* existed (REQ-TFO-02).
|
|
44
|
+
*
|
|
45
|
+
* @internal Sanctioned callers only — `src/core/**`, `src/testing/**`, and
|
|
46
|
+
* `src/conformance/**` (enforced by `test/fitness/fit-29-sanctioned-definefactory-caller.test.ts`).
|
|
47
|
+
* Author code never imports this directly; it calls `runFactoryForTest` (test-time) or the
|
|
48
|
+
* future production runner instead — both wrap this SAME seam internally.
|
|
49
|
+
*
|
|
50
|
+
* @param fn - the authoring logic; receives the resolved, schema-validated input.
|
|
51
|
+
* @param options.packageDir - opts into schema-derived input validation and reserved-name
|
|
52
|
+
* enforcement (both structural checks against this package's `schema.json`/sibling files).
|
|
53
|
+
* Pass `import.meta.dir` (a directory) — NOT `import.meta.url` (a file URL; a common
|
|
54
|
+
* misuse). Two opt-out tiers: omit `options` entirely for the untyped, unvalidated escape
|
|
55
|
+
* hatch (REQ-TFO-02); pass `{ packageDir }` with no adjacent `schema.json` to opt into the
|
|
56
|
+
* flow loudly-schemaless (a warning fires on every run, REQ-RBV-03).
|
|
57
|
+
*
|
|
58
|
+
* @remarks
|
|
59
|
+
* A factory package must never declare a sibling module named `pre-execute` or
|
|
60
|
+
* `post-execute` (file or directory form, case-insensitive) — these are reserved lifecycle
|
|
61
|
+
* names for future SDK use and are rejected at this boundary (the `reserved-lifecycle-names`
|
|
62
|
+
* domain). `add`/`remove` are NOT reserved by this check (collection-level naming, deferred
|
|
63
|
+
* to a future L2 scope).
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* // 1. Generate the typed Input from schema.json:
|
|
67
|
+
* // pbuilder-codegen <package-dir>
|
|
68
|
+
* import type { Input } from "./schema.generated.ts";
|
|
69
|
+
*
|
|
70
|
+
* // 2. Internal: wrap a bare author fn into a client-driven runner:
|
|
71
|
+
* const bareFactory = (input: Input) => {
|
|
72
|
+
* create("server.config.ts", {
|
|
73
|
+
* template: "export const port = {{port}};",
|
|
74
|
+
* options: { port: input.port },
|
|
75
|
+
* });
|
|
76
|
+
* };
|
|
77
|
+
*
|
|
78
|
+
* const runner = defineFactory<Input>(bareFactory, { packageDir: import.meta.dir });
|
|
79
|
+
* await runner(input, { client });
|
|
80
|
+
*/
|
|
81
|
+
export declare function defineFactory<O>(fn: (o: O) => void | Promise<void>, options?: {
|
|
82
|
+
packageDir?: string | URL;
|
|
83
|
+
}): (o: O, deps: {
|
|
84
|
+
client: EngineClient;
|
|
85
|
+
}) => Promise<void>;
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
// KIT-05: Ambient RunContext via AsyncLocalStorage.
|
|
2
|
+
// defineFactory returns a runner that builds the context and runs fn inside the ALS.
|
|
3
|
+
// The EngineClient is injected by the caller (test passes the fake) — no module global.
|
|
4
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
|
+
import { readFileSync, existsSync } from "node:fs";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { relative, dirname, join } from "node:path";
|
|
8
|
+
import { DirectiveFactory } from "./directive-factory.js";
|
|
9
|
+
import { Session } from "./session.js";
|
|
10
|
+
import { AuthoringError, invalidInput } from "./authoring-error.js";
|
|
11
|
+
import { schemaPathFor, findReservedSibling } from "./schema/schema-discovery.js";
|
|
12
|
+
import { parseSchema, SchemaParseFailure, formatLocator } from "./schema/schema-parse.js";
|
|
13
|
+
import { validateInput } from "./schema/schema-validate.js";
|
|
14
|
+
import { rejectionFor, rejectionForReservedName } from "./schema/input-rejection.js";
|
|
15
|
+
import { isErrnoException } from "./fs-errors.js";
|
|
16
|
+
class DialectRegistryImpl {
|
|
17
|
+
#handles = [];
|
|
18
|
+
register(handle) {
|
|
19
|
+
this.#handles.push(handle);
|
|
20
|
+
}
|
|
21
|
+
// Promise.allSettled (never a bare Promise.all): every handle's settle() is awaited
|
|
22
|
+
// regardless of others rejecting, so no settlement is left dangling unobserved; the
|
|
23
|
+
// FIRST rejection (author-chain order) is re-thrown into defineFactory's existing catch.
|
|
24
|
+
async drain() {
|
|
25
|
+
const handles = this.#handles;
|
|
26
|
+
this.#handles = [];
|
|
27
|
+
const results = await Promise.allSettled(handles.map((h) => h.settle()));
|
|
28
|
+
const firstRejection = results.find((r) => r.status === "rejected");
|
|
29
|
+
if (firstRejection !== undefined) {
|
|
30
|
+
throw firstRejection.reason;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// context-singleton-fix (REQ-MIS-01/02, design §4.3): a module-scope `als` is realm-local —
|
|
35
|
+
// when `dist/bin/pbuilder-runner.js` and a src-relative `.ts` factory co-execute in one Bun
|
|
36
|
+
// process, each resolves its OWN copy of this module and its OWN `als`, so a run entered in
|
|
37
|
+
// one realm is invisible to `currentContext()` in the other. The store is therefore parked at
|
|
38
|
+
// `globalThis[Symbol.for(RUN_ALS_REGISTRY_KEY)]` — a process-singleton every realm resolving
|
|
39
|
+
// this file reaches via the SAME well-known key — lazily installed on first access.
|
|
40
|
+
export const RUN_ALS_REGISTRY_KEY = "@pbuilder/sdk:core/context#run-als";
|
|
41
|
+
function isAsyncLocalStorageLike(value) {
|
|
42
|
+
return (typeof value === "object" &&
|
|
43
|
+
value !== null &&
|
|
44
|
+
typeof value.run === "function" &&
|
|
45
|
+
typeof value.getStore === "function");
|
|
46
|
+
}
|
|
47
|
+
// PURE 3-state decision (design §4.3, rev 3 purity split) — no globalThis, no side effects.
|
|
48
|
+
// `undefined` (slot absent) -> fresh ALS; a duck-valid ALS-shaped value (cross-realm reuse)
|
|
49
|
+
// -> returned verbatim, SAME instance; anything else -> fail LOUD (occupied-slot contract,
|
|
50
|
+
// ADR-01 addendum): a foreign/corrupted occupant under this well-known key must never be
|
|
51
|
+
// trusted or silently clobbered. Plain `Error` (NOT AuthoringError) — this is
|
|
52
|
+
// environment/integration corruption, not author-input misuse; the closed reason enum has no
|
|
53
|
+
// member for it (mirrors `validateAtRunBoundary`'s read-path posture).
|
|
54
|
+
export function resolveRunAls(slotValue) {
|
|
55
|
+
if (slotValue === undefined) {
|
|
56
|
+
return new AsyncLocalStorage();
|
|
57
|
+
}
|
|
58
|
+
if (isAsyncLocalStorageLike(slotValue)) {
|
|
59
|
+
return slotValue;
|
|
60
|
+
}
|
|
61
|
+
throw new Error(`[pbuilder] run-context registry slot Symbol.for("${RUN_ALS_REGISTRY_KEY}") is occupied by an ` +
|
|
62
|
+
`incompatible value (expected an AsyncLocalStorage, got ${typeof slotValue}) — another module ` +
|
|
63
|
+
"may have polluted globalThis");
|
|
64
|
+
}
|
|
65
|
+
// IMPURE thin shell: reads the shared slot, delegates the 3-state decision to the pure
|
|
66
|
+
// `resolveRunAls`, and installs the resolved ALS ONLY when the slot was absent — a frozen
|
|
67
|
+
// descriptor (non-enumerable, non-configurable, non-writable) so REQ-MIS-01.2's no-pollution
|
|
68
|
+
// guarantee holds and the slot can never be silently reassigned after first install.
|
|
69
|
+
function getRunAls() {
|
|
70
|
+
const registryKey = Symbol.for(RUN_ALS_REGISTRY_KEY);
|
|
71
|
+
const slot = globalThis[registryKey];
|
|
72
|
+
const resolved = resolveRunAls(slot);
|
|
73
|
+
if (slot === undefined) {
|
|
74
|
+
Object.defineProperty(globalThis, registryKey, {
|
|
75
|
+
value: resolved,
|
|
76
|
+
writable: false,
|
|
77
|
+
enumerable: false,
|
|
78
|
+
configurable: false,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return resolved;
|
|
82
|
+
}
|
|
83
|
+
// ADR-04 (stdio-engine-client, REQ-RUN-06): a non-enumerable, non-configurable brand
|
|
84
|
+
// stamped on defineFactory's returned wrapper — arity-independent double-wrap detection
|
|
85
|
+
// (RUN-06.2 rejected V1's arity-sniffing: an author's bare `(o, unused) => {}` factory must
|
|
86
|
+
// never be misclassified). The symbol stays module-private; only the checker is exported,
|
|
87
|
+
// so a caller asks "is this already wrapped" without being able to forge the brand via a
|
|
88
|
+
// guessed string key.
|
|
89
|
+
const DEFINE_FACTORY_BRAND = Symbol("pbuilder.defineFactory.wrapped");
|
|
90
|
+
export function isDefineFactoryWrapped(value) {
|
|
91
|
+
return typeof value === "function" && Reflect.get(value, DEFINE_FACTORY_BRAND) === true;
|
|
92
|
+
}
|
|
93
|
+
// REQ-AEC-02.1 (2.4): a verb called outside any defineFactory run is SDK-side misuse,
|
|
94
|
+
// independent of any engine round-trip — an AuthoringError{authoring-rejected,outside-run},
|
|
95
|
+
// not a plain Error. The prose lives in authoring-error.ts's outside-run message template
|
|
96
|
+
// (the third template, REQ-AEC-06); this is the one call site that reaches it.
|
|
97
|
+
export function currentContext() {
|
|
98
|
+
const ctx = getRunAls().getStore();
|
|
99
|
+
if (ctx === undefined) {
|
|
100
|
+
throw new AuthoringError({
|
|
101
|
+
verb: undefined,
|
|
102
|
+
path: undefined,
|
|
103
|
+
reason: "outside-run",
|
|
104
|
+
appliedCount: 0,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
return ctx;
|
|
108
|
+
}
|
|
109
|
+
// The one gate every package-local read verb (`scaffold`/`copyIn`/`create({templateFile})`)
|
|
110
|
+
// passes through: returns the run's two-anchor pair or throws the verb's own
|
|
111
|
+
// no-resolution-anchor `invalid-input` when the run opted out of `packageDir`.
|
|
112
|
+
export function requirePackageAnchors(missingAnchorMessage) {
|
|
113
|
+
const { packageAnchors } = currentContext();
|
|
114
|
+
if (packageAnchors === undefined) {
|
|
115
|
+
throw invalidInput(missingAnchorMessage);
|
|
116
|
+
}
|
|
117
|
+
return packageAnchors;
|
|
118
|
+
}
|
|
119
|
+
// packageDir accepts a directory URL (import.meta.dir is a Bun string; import.meta.url
|
|
120
|
+
// is a file URL some authors may pass instead) — never a file URL pointing at a file.
|
|
121
|
+
function resolvePackageDir(packageDir) {
|
|
122
|
+
return typeof packageDir === "string" ? packageDir : fileURLToPath(packageDir);
|
|
123
|
+
}
|
|
124
|
+
// `<dir>` token (all runtime warning/error literals, Executor Context pin): project-root-
|
|
125
|
+
// relative, never absolute — tests run from the repo root, so this is deterministic and
|
|
126
|
+
// leaks no absolute path.
|
|
127
|
+
function relativeDir(packageDir) {
|
|
128
|
+
return relative(process.cwd(), packageDir);
|
|
129
|
+
}
|
|
130
|
+
function missingPackageRootMessage(packageDir) {
|
|
131
|
+
return (`invalid input: no collection.json found at or above ${relativeDir(packageDir)} — ` +
|
|
132
|
+
"cannot resolve the containment root for this factory's package");
|
|
133
|
+
}
|
|
134
|
+
// REQ-PRC-02/REQ-PRC-03 (ADR-0046): the CONTAINMENT ceiling — the nearest `collection.json`
|
|
135
|
+
// ANCESTOR of `packageDir` (itself included), walked upward from `packageDir` to the
|
|
136
|
+
// filesystem root. `collection.json` is a PRESENCE-ONLY marker (never parsed, never read as
|
|
137
|
+
// JSON — charter L2 keeps the manifest out of scope). No ancestor found → fail loud
|
|
138
|
+
// `invalid-input` (REQ-PRC-03.1) BEFORE any source file is read; the ONLY caller is the
|
|
139
|
+
// pre-`als.run` chokepoint below, so this resolves exactly once per run (REQ-PRC-02.1) —
|
|
140
|
+
// scaffold/copyIn never re-walk it themselves, they read the already-resolved
|
|
141
|
+
// `RunContext.packageRoot`.
|
|
142
|
+
function resolvePackageRoot(packageDir) {
|
|
143
|
+
let dir = packageDir;
|
|
144
|
+
for (;;) {
|
|
145
|
+
if (existsSync(join(dir, "collection.json"))) {
|
|
146
|
+
return dir;
|
|
147
|
+
}
|
|
148
|
+
const parent = dirname(dir);
|
|
149
|
+
if (parent === dir) {
|
|
150
|
+
throw new AuthoringError({
|
|
151
|
+
verb: undefined,
|
|
152
|
+
path: undefined,
|
|
153
|
+
reason: "invalid-input",
|
|
154
|
+
appliedCount: 0,
|
|
155
|
+
message: missingPackageRootMessage(packageDir),
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
dir = parent;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
// Author-vocabulary description of a non-ENOENT read failure — never the raw errno
|
|
162
|
+
// message (no-echo). ENOENT is handled by its own opt-out branch and never reaches this.
|
|
163
|
+
function describeReadFailure(err) {
|
|
164
|
+
if (isErrnoException(err)) {
|
|
165
|
+
if (err.code === "EACCES" || err.code === "EPERM")
|
|
166
|
+
return "permission denied";
|
|
167
|
+
if (err.code === "EISDIR")
|
|
168
|
+
return "is a directory, not a file";
|
|
169
|
+
}
|
|
170
|
+
return "unreadable";
|
|
171
|
+
}
|
|
172
|
+
// RBV-05.1 runtime literal (slices load-bearing literals, design §4.4): ONE literal covers
|
|
173
|
+
// both present-but-unparseable AND invalid-shape schemas, `<problem>` distinguishing them;
|
|
174
|
+
// also reused (with no locator) for non-ENOENT read failures (constraint 4) — same
|
|
175
|
+
// "could not be read" vocabulary, since both are "the run boundary could not establish
|
|
176
|
+
// what this factory's schema contract is" failures.
|
|
177
|
+
function malformedSchemaMessage(packageDir, problem, line, column) {
|
|
178
|
+
return `[pbuilder] factory at ${relativeDir(packageDir)}: schema.json could not be read: ${problem} ${formatLocator(line, column)}`;
|
|
179
|
+
}
|
|
180
|
+
function noSchemaWarning(packageDir) {
|
|
181
|
+
return `[pbuilder] factory at ${relativeDir(packageDir)}: no schema.json found — running WITHOUT schema-derived input validation`;
|
|
182
|
+
}
|
|
183
|
+
function emptySchemaWarning(packageDir) {
|
|
184
|
+
return `[pbuilder] factory at ${relativeDir(packageDir)}: schema.json declares zero properties — no input validation performed`;
|
|
185
|
+
}
|
|
186
|
+
// Pre-`als.run` schema-conformance check (ADR-0029, REQ-RBV-01/03/05): validates BEFORE
|
|
187
|
+
// RunContext is built, so a rejection throws with nothing buffered — all-or-nothing holds
|
|
188
|
+
// trivially and the rejection never reaches the emit seam. Bare `defineFactory(fn)` (no
|
|
189
|
+
// `options`) skips this entirely — the untyped opt-out (REQ-TFO-02) stays byte-for-byte
|
|
190
|
+
// unchanged. Read-path posture (SEC-3, constraint 4): ONLY ENOENT maps to the opt-out;
|
|
191
|
+
// every other read/parse failure fails closed as a plain Error — deliberately NOT an
|
|
192
|
+
// AuthoringError: the closed reason enum (authoring-error-contract V3) has no member for
|
|
193
|
+
// a corrupt/unreadable schema file, only for author-input rejections (invalid-input /
|
|
194
|
+
// reserved-name). A parsed-but-empty schema (zero declared properties) is distinct from no
|
|
195
|
+
// schema at all (REQ-RBV-05.2) — it warns and skips validation, it does not opt out.
|
|
196
|
+
function validateAtRunBoundary(packageDir, input) {
|
|
197
|
+
const schemaPath = schemaPathFor(packageDir);
|
|
198
|
+
let raw;
|
|
199
|
+
try {
|
|
200
|
+
raw = readFileSync(schemaPath, "utf-8");
|
|
201
|
+
}
|
|
202
|
+
catch (err) {
|
|
203
|
+
if (isErrnoException(err) && err.code === "ENOENT") {
|
|
204
|
+
console.warn(noSchemaWarning(packageDir));
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
throw new Error(malformedSchemaMessage(packageDir, describeReadFailure(err), undefined, undefined));
|
|
208
|
+
}
|
|
209
|
+
let schema;
|
|
210
|
+
try {
|
|
211
|
+
schema = parseSchema(raw);
|
|
212
|
+
}
|
|
213
|
+
catch (err) {
|
|
214
|
+
if (err instanceof SchemaParseFailure) {
|
|
215
|
+
throw new Error(malformedSchemaMessage(packageDir, err.problem, err.line, err.column));
|
|
216
|
+
}
|
|
217
|
+
throw err;
|
|
218
|
+
}
|
|
219
|
+
if (schema.properties.length === 0) {
|
|
220
|
+
console.warn(emptySchemaWarning(packageDir));
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
const findings = validateInput(schema, input);
|
|
224
|
+
const [firstFinding] = findings;
|
|
225
|
+
if (firstFinding !== undefined) {
|
|
226
|
+
throw rejectionFor(firstFinding);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
// Reserved-lifecycle-name enforcement (S-004, ADR-0028, REQ-RLN-01/02): resolves
|
|
230
|
+
// reserved-name status from the factory package's OWN MODULE STRUCTURE only — never from
|
|
231
|
+
// resolved run-time inputs (that is REQ-RBV-01.5's territory) or from `schema.json` field
|
|
232
|
+
// names (REQ-RLN-01.4). Non-ENOENT scan failures fail closed, same read-path posture as
|
|
233
|
+
// `validateAtRunBoundary` (constraint 4).
|
|
234
|
+
function checkReservedNames(packageDir) {
|
|
235
|
+
let reserved;
|
|
236
|
+
try {
|
|
237
|
+
reserved = findReservedSibling(packageDir);
|
|
238
|
+
}
|
|
239
|
+
catch (err) {
|
|
240
|
+
throw new Error(`[pbuilder] factory at ${relativeDir(packageDir)}: could not scan for reserved lifecycle names: ${describeReadFailure(err)}`);
|
|
241
|
+
}
|
|
242
|
+
if (reserved !== undefined) {
|
|
243
|
+
throw rejectionForReservedName(reserved);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Builds a run-context and runs the factory inside it, flushing buffered
|
|
248
|
+
* directives at run end (REQ-KIT-05) — a write-only factory still emits.
|
|
249
|
+
*
|
|
250
|
+
* All-or-nothing contract (ADR-01): on success the full directive batch is committed;
|
|
251
|
+
* if `fn` throws (or the run-end flush rejects), the staged set is discarded and the
|
|
252
|
+
* engine commits NOTHING. The original (or attributed) error propagates to the caller —
|
|
253
|
+
* a thrown factory never leaves a partial set of mutations committed.
|
|
254
|
+
*
|
|
255
|
+
* `options.packageDir` (pass `import.meta.dir`, never `import.meta.url`) opts a factory
|
|
256
|
+
* into schema-derived run-boundary validation against its adjacent `schema.json`; a bare
|
|
257
|
+
* `defineFactory(fn)` call is the untyped opt-out and runs exactly as before this option
|
|
258
|
+
* existed (REQ-TFO-02).
|
|
259
|
+
*
|
|
260
|
+
* @internal Sanctioned callers only — `src/core/**`, `src/testing/**`, and
|
|
261
|
+
* `src/conformance/**` (enforced by `test/fitness/fit-29-sanctioned-definefactory-caller.test.ts`).
|
|
262
|
+
* Author code never imports this directly; it calls `runFactoryForTest` (test-time) or the
|
|
263
|
+
* future production runner instead — both wrap this SAME seam internally.
|
|
264
|
+
*
|
|
265
|
+
* @param fn - the authoring logic; receives the resolved, schema-validated input.
|
|
266
|
+
* @param options.packageDir - opts into schema-derived input validation and reserved-name
|
|
267
|
+
* enforcement (both structural checks against this package's `schema.json`/sibling files).
|
|
268
|
+
* Pass `import.meta.dir` (a directory) — NOT `import.meta.url` (a file URL; a common
|
|
269
|
+
* misuse). Two opt-out tiers: omit `options` entirely for the untyped, unvalidated escape
|
|
270
|
+
* hatch (REQ-TFO-02); pass `{ packageDir }` with no adjacent `schema.json` to opt into the
|
|
271
|
+
* flow loudly-schemaless (a warning fires on every run, REQ-RBV-03).
|
|
272
|
+
*
|
|
273
|
+
* @remarks
|
|
274
|
+
* A factory package must never declare a sibling module named `pre-execute` or
|
|
275
|
+
* `post-execute` (file or directory form, case-insensitive) — these are reserved lifecycle
|
|
276
|
+
* names for future SDK use and are rejected at this boundary (the `reserved-lifecycle-names`
|
|
277
|
+
* domain). `add`/`remove` are NOT reserved by this check (collection-level naming, deferred
|
|
278
|
+
* to a future L2 scope).
|
|
279
|
+
*
|
|
280
|
+
* @example
|
|
281
|
+
* // 1. Generate the typed Input from schema.json:
|
|
282
|
+
* // pbuilder-codegen <package-dir>
|
|
283
|
+
* import type { Input } from "./schema.generated.ts";
|
|
284
|
+
*
|
|
285
|
+
* // 2. Internal: wrap a bare author fn into a client-driven runner:
|
|
286
|
+
* const bareFactory = (input: Input) => {
|
|
287
|
+
* create("server.config.ts", {
|
|
288
|
+
* template: "export const port = {{port}};",
|
|
289
|
+
* options: { port: input.port },
|
|
290
|
+
* });
|
|
291
|
+
* };
|
|
292
|
+
*
|
|
293
|
+
* const runner = defineFactory<Input>(bareFactory, { packageDir: import.meta.dir });
|
|
294
|
+
* await runner(input, { client });
|
|
295
|
+
*/
|
|
296
|
+
export function defineFactory(fn, options) {
|
|
297
|
+
const wrapped = async (o, { client }) => {
|
|
298
|
+
let packageAnchors;
|
|
299
|
+
if (options?.packageDir !== undefined) {
|
|
300
|
+
const resolvedDir = resolvePackageDir(options.packageDir);
|
|
301
|
+
checkReservedNames(resolvedDir);
|
|
302
|
+
validateAtRunBoundary(resolvedDir, o);
|
|
303
|
+
// ADR-0046 / REQ-RBV-06: the containment-ceiling walk shares the SAME pre-`als.run`
|
|
304
|
+
// chokepoint as schema/reserved-name validation, not a separate, uncoordinated read
|
|
305
|
+
// site — a missing ancestor fails closed here, before `fn` ever runs (REQ-RBV-06.1).
|
|
306
|
+
packageAnchors = { packageDir: resolvedDir, packageRoot: resolvePackageRoot(resolvedDir) };
|
|
307
|
+
}
|
|
308
|
+
const ctx = {
|
|
309
|
+
session: new Session(client),
|
|
310
|
+
factory: new DirectiveFactory(),
|
|
311
|
+
dialects: new DialectRegistryImpl(),
|
|
312
|
+
packageAnchors,
|
|
313
|
+
};
|
|
314
|
+
// ADR-01: no `finally` — success (commit) and failure (discard) are distinct paths.
|
|
315
|
+
// The final flush is INSIDE the try, so a flush-time emit rejection (already an
|
|
316
|
+
// AuthoringError via Session.flush) skips commit() and routes to discard + re-throw.
|
|
317
|
+
//
|
|
318
|
+
// ADR-0037: the dialect-handle drain runs BETWEEN `als.run` and `session.flush()` — an
|
|
319
|
+
// unawaited dialect chain (forgotten `await`) still completes and commits; a drain
|
|
320
|
+
// rejection (an unawaited chain that threw) routes through the SAME catch below as a
|
|
321
|
+
// flush rejection already does.
|
|
322
|
+
try {
|
|
323
|
+
await getRunAls().run(ctx, () => fn(o));
|
|
324
|
+
await ctx.dialects.drain();
|
|
325
|
+
await ctx.session.flush();
|
|
326
|
+
await ctx.session.commit();
|
|
327
|
+
}
|
|
328
|
+
catch (err) {
|
|
329
|
+
// REQ-10: double-fault preservation. A discard() rejection (E2) must never replace
|
|
330
|
+
// or swallow the factory's original error (E1) — attach it as cause and re-throw E1.
|
|
331
|
+
try {
|
|
332
|
+
await ctx.session.discard();
|
|
333
|
+
}
|
|
334
|
+
catch (discardErr) {
|
|
335
|
+
// Never clobber a pre-existing cause chain on E1, and never let a frozen/sealed
|
|
336
|
+
// E1 throw on assignment replace E1 itself — either way E1 must survive unchanged.
|
|
337
|
+
if (err instanceof Error && err.cause === undefined) {
|
|
338
|
+
try {
|
|
339
|
+
err.cause = discardErr;
|
|
340
|
+
}
|
|
341
|
+
catch {
|
|
342
|
+
// E1 rejected the assignment (frozen/sealed) — propagate E1 unchanged.
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
throw err;
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
Object.defineProperty(wrapped, DEFINE_FACTORY_BRAND, {
|
|
350
|
+
value: true,
|
|
351
|
+
enumerable: false,
|
|
352
|
+
configurable: false,
|
|
353
|
+
writable: false,
|
|
354
|
+
});
|
|
355
|
+
return wrapped;
|
|
356
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function deepEqual(a: unknown, b: unknown): boolean;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// S-000: kit-internal shared structural-equality helper (row-146, ADR-0012 amendment clause
|
|
2
|
+
// 4). Sibling of ./dialect-error.ts — same kit-internal-shared-in-core pattern, one decision
|
|
3
|
+
// covers both, no separate ADR. Not re-exported from src/core/index.ts, no barrel/subpath:
|
|
4
|
+
// no public symbol. src/conformance/index.ts and src/testing/contract-fake.ts each carry
|
|
5
|
+
// their OWN duplicated copy today (FIT-17 forbids ./conformance -> ./testing); extracting
|
|
6
|
+
// both onto this shared module is S-005's task, not this one's.
|
|
7
|
+
function isKeyedObject(value) {
|
|
8
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
9
|
+
}
|
|
10
|
+
// Object.is-based structural equality (not `===`): callers that round-trip a value through
|
|
11
|
+
// JSON.stringify/JSON.parse need to detect the cases `===` gets wrong (NaN, -0 vs 0) and the
|
|
12
|
+
// cases JSON silently drops (a key holding undefined) rather than tolerates.
|
|
13
|
+
export function deepEqual(a, b) {
|
|
14
|
+
if (Object.is(a, b))
|
|
15
|
+
return true;
|
|
16
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
17
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
|
|
18
|
+
return false;
|
|
19
|
+
return a.every((value, index) => deepEqual(value, b[index]));
|
|
20
|
+
}
|
|
21
|
+
if (isKeyedObject(a) && isKeyedObject(b)) {
|
|
22
|
+
const aKeys = Object.keys(a);
|
|
23
|
+
const bKeys = Object.keys(b);
|
|
24
|
+
if (aKeys.length !== bKeys.length)
|
|
25
|
+
return false;
|
|
26
|
+
return aKeys.every((key) => key in b && deepEqual(a[key], b[key]));
|
|
27
|
+
}
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { ReadOps } from "./base-handle.ts";
|
|
2
|
+
export type Op<Ast = any> = (ast: Ast, ...args: never[]) => void;
|
|
3
|
+
export type OpPack<Ast = any> = Record<string, Op<Ast>>;
|
|
4
|
+
export interface DialectDescriptor<Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> {
|
|
5
|
+
extensions: string[];
|
|
6
|
+
ast: {
|
|
7
|
+
parse(source: string): Ast;
|
|
8
|
+
print(ast: Ast): string;
|
|
9
|
+
};
|
|
10
|
+
ops: Ops;
|
|
11
|
+
}
|
|
12
|
+
type Bound<Ast, F> = F extends (ast: Ast, ...rest: infer R) => void ? (...rest: R) => void : never;
|
|
13
|
+
type Edited<Ast, Ops extends OpPack<Ast>> = Handle<"writable", Ast, Ops>;
|
|
14
|
+
type OpMethods<Ast, Ops extends OpPack<Ast>> = {
|
|
15
|
+
[K in keyof Ops]: (...a: Parameters<Bound<Ast, Ops[K]>>) => Edited<Ast, Ops>;
|
|
16
|
+
};
|
|
17
|
+
type DialectWriteOps<Ast, Ops extends OpPack<Ast>> = {
|
|
18
|
+
replaceContent(content: string): Edited<Ast, Ops>;
|
|
19
|
+
rename(newName: string, opts?: {
|
|
20
|
+
force?: boolean;
|
|
21
|
+
}): Edited<Ast, Ops>;
|
|
22
|
+
move(toDir: string, opts?: {
|
|
23
|
+
force?: boolean;
|
|
24
|
+
}): Edited<Ast, Ops>;
|
|
25
|
+
copy(to: string, opts?: {
|
|
26
|
+
force?: boolean;
|
|
27
|
+
}): Edited<Ast, Ops>;
|
|
28
|
+
};
|
|
29
|
+
export type Handle<State extends "found" | "writable" = "found", Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> = ReadOps & DialectWriteOps<Ast, Ops> & {
|
|
30
|
+
modify(fn: (ast: Ast) => void): Edited<Ast, Ops>;
|
|
31
|
+
} & OpMethods<Ast, Ops> & (State extends "found" ? {
|
|
32
|
+
remove(): void;
|
|
33
|
+
} : {}) & PromiseLike<void>;
|
|
34
|
+
export interface Dialect<Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> {
|
|
35
|
+
readonly extensions: readonly string[];
|
|
36
|
+
readonly ast: {
|
|
37
|
+
parse(source: string): Ast;
|
|
38
|
+
print(ast: Ast): string;
|
|
39
|
+
};
|
|
40
|
+
readonly ops: Ops;
|
|
41
|
+
find(path: string): Handle<"found", Ast, Ops>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Declares a named collection of ops over one AST type — usable standalone (REQ-DG-02.3),
|
|
45
|
+
* e.g. shareable across two dialects targeting the same AST type, before any `withOps`
|
|
46
|
+
* composition occurs.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* const addImportPack = defineOpPack<SourceFile, { addImport(ast: SourceFile, name: string, from: string): void }>({
|
|
50
|
+
* addImport(ast, name, from) { ast.addImportDeclaration({ namedImports: [name], moduleSpecifier: from }); },
|
|
51
|
+
* });
|
|
52
|
+
*/
|
|
53
|
+
export declare function defineOpPack<Ast, Ops extends OpPack<Ast>>(ops: Ops): Ops;
|
|
54
|
+
/**
|
|
55
|
+
* Assembles a `Dialect` from its frozen descriptor (extensions, an AST parse/print pair,
|
|
56
|
+
* and an op-pack). `find` is the dialect's ONLY entry verb into a run (REQ-DG-01.2) — it
|
|
57
|
+
* returns an open, coalescing `Handle`.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* const myDialect = defineDialect({
|
|
61
|
+
* extensions: [".ts"],
|
|
62
|
+
* ast: { parse: (s) => project.addSourceFileAtPath(s), print: (ast) => ast.getFullText() },
|
|
63
|
+
* ops: {},
|
|
64
|
+
* });
|
|
65
|
+
*/
|
|
66
|
+
export declare function defineDialect<Ast, Ops extends OpPack<Ast>>(d: DialectDescriptor<Ast, Ops>): Dialect<Ast, Ops>;
|
|
67
|
+
type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
|
|
68
|
+
/**
|
|
69
|
+
* The base handle's own vocabulary (REQ-DG-02, ADR-0010 amendment) — an op-pack op sharing
|
|
70
|
+
* any of these names would silently shadow a base verb; `then` in particular would break the
|
|
71
|
+
* handle's `PromiseLike` join. `raw` stays reserved even though the verb itself is retired
|
|
72
|
+
* (ADR-0050) — a muscle-memory guardrail against authors reaching for the old name. Exported,
|
|
73
|
+
* ordered array (REQ-DG-02.7 pins this exact order via `toEqual`); `assertNoCompositionCollision`
|
|
74
|
+
* below consumes it through the derived, non-exported `RESERVED_SET`.
|
|
75
|
+
*
|
|
76
|
+
* @internal Exported for test/conformance observability only (so collision/exact-set tests can
|
|
77
|
+
* import it instead of hand-typing a second literal) — NOT a supported public API member, not
|
|
78
|
+
* semver-covered beyond the FIT-04 baseline pin it already sits inside (ORCHESTRATOR RULING R2).
|
|
79
|
+
*/
|
|
80
|
+
export declare const RESERVED_HANDLE_NAMES: readonly ["then", "read", "raw", "modify", "replaceContent", "rename", "move", "copy", "remove"];
|
|
81
|
+
/**
|
|
82
|
+
* Composes additional op-packs onto a base dialect. The resulting handle type is the
|
|
83
|
+
* INTERSECTION of the base's ops and every attached pack's ops (ADR-0010) — an op from an
|
|
84
|
+
* unattached pack, or a typo, is a compile error (REQ-DG-02.1). At composition time, an
|
|
85
|
+
* eager RUNTIME check (REQ-DG-02.2–02.5, ADR-0010 amendment) throws synchronously on a
|
|
86
|
+
* cross-pack op-name duplicate (or a collision against `base.ops`) or a reserved-vocabulary
|
|
87
|
+
* collision — composition never silently resolves to whichever pack happened to be spread
|
|
88
|
+
* last.
|
|
89
|
+
*
|
|
90
|
+
* @example
|
|
91
|
+
* const tsDialect = withOps(baseTsDialect, addImportPack);
|
|
92
|
+
*/
|
|
93
|
+
export declare function withOps<Ast, B extends OpPack<Ast>, P extends OpPack<Ast>[]>(base: Dialect<Ast, B>, ...packs: P): Dialect<Ast, B & UnionToIntersection<P[number]>>;
|
|
94
|
+
export {};
|