@pbuilder/sdk 0.17.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -3
- package/dist/acl/irwire/stdio-engine-client.d.ts +1 -1
- package/dist/acl/irwire/stdio-engine-client.js +3 -2
- package/dist/bin/pbuilder-codegen.js +59 -1
- package/dist/bin/pbuilder-conformance.d.ts +2 -0
- package/dist/bin/pbuilder-conformance.js +45 -0
- package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.d.ts +12 -3
- package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.js +23 -9
- package/dist/bounded-contexts/authoring/application/usecases/scaffold/expander.js +4 -4
- package/dist/bounded-contexts/authoring/domain/aggregates/session/session.d.ts +2 -1
- package/dist/bounded-contexts/authoring/domain/aggregates/session/session.js +56 -6
- package/dist/bounded-contexts/authoring/domain/entities/dialect-handle.d.ts +2 -1
- package/dist/bounded-contexts/authoring/domain/entities/dialect-handle.js +108 -30
- package/dist/bounded-contexts/authoring/domain/ports/engine-client.d.ts +1 -1
- package/dist/bounded-contexts/authoring/domain/services/define-dialect.d.ts +48 -10
- package/dist/bounded-contexts/authoring/domain/services/define-dialect.js +37 -9
- package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.d.ts +1 -0
- package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.js +4 -0
- package/dist/bounded-contexts/authoring/domain/services/schema/schema-parse.d.ts +3 -2
- package/dist/bounded-contexts/authoring/domain/services/schema/schema-parse.js +46 -4
- package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.d.ts +16 -1
- package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.js +125 -0
- package/dist/bounded-contexts/authoring/domain/valueobjects/authoring-error.d.ts +3 -2
- package/dist/bounded-contexts/authoring/domain/valueobjects/authoring-error.js +2 -0
- package/dist/bounded-contexts/authoring/domain/valueobjects/schema-model.d.ts +17 -0
- package/dist/bounded-contexts/authoring/domain/valueobjects/schema-model.js +1 -0
- package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.d.ts +1 -0
- package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.js +23 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.js +2 -2
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.d.ts +8 -5
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.js +7 -4
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.d.ts +1 -1
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.js +20 -7
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.d.ts +20 -2
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.js +19 -3
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.d.ts +5 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.js +89 -20
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.js +2 -2
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/ast.d.ts +2 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/ast.js +4 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.js +3 -3
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/ast.d.ts +2 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/ast.js +4 -0
- package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.js +2 -2
- package/dist/bounded-contexts/authoring/testing/conformance/index.d.ts +10 -12
- package/dist/bounded-contexts/authoring/testing/conformance/index.js +17 -2
- package/dist/bounded-contexts/authoring/testing/conformance/run-package.d.ts +37 -0
- package/dist/bounded-contexts/authoring/testing/conformance/run-package.js +209 -0
- package/dist/bounded-contexts/authoring/testing/harness/index.d.ts +13 -4
- package/dist/bounded-contexts/authoring/testing/harness/index.js +10 -4
- package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.d.ts +3 -0
- package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.js +2 -0
- package/dist/bounded-contexts/runner-hosting/infrastructure/in/runner.js +69 -3
- package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.d.ts +24 -0
- package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.js +34 -1
- package/dist/conformance/index.d.ts +1 -0
- package/dist/conformance/index.js +1 -0
- package/dist/dialect/index.d.ts +2 -0
- package/dist/dialect/index.js +3 -0
- package/dist/runner-manifest.json +12 -12
- package/package.json +8 -2
|
@@ -62,3 +62,128 @@ export function validateInput(schema, input) {
|
|
|
62
62
|
}
|
|
63
63
|
return findings;
|
|
64
64
|
}
|
|
65
|
+
/** E-40: the largest JSON encoding of a Result, in UTF-8 bytes; exactly at it is allowed. */
|
|
66
|
+
export const RESULT_CEILING_BYTES = 1048576;
|
|
67
|
+
/**
|
|
68
|
+
* Checks `value` as the Result of a factory whose declaration is `declared`. Without a
|
|
69
|
+
* declaration only `undefined`, no Result, passes. A Result that passes comes back as a copy
|
|
70
|
+
* parsed from its JSON encoding, so what is committed is exactly what was checked. The
|
|
71
|
+
* declaration is a parameter so a Result shape a role imposes can be checked the same way as
|
|
72
|
+
* one read from `schema.json`.
|
|
73
|
+
*/
|
|
74
|
+
export function checkResult(declared, value) {
|
|
75
|
+
if (declared === undefined) {
|
|
76
|
+
return value === undefined ? { result: undefined } : { problem: "the factory declares no Result in schema.json but returned a value" };
|
|
77
|
+
}
|
|
78
|
+
let encoded;
|
|
79
|
+
try {
|
|
80
|
+
const problem = jsonProblem(value, "Result", new Set());
|
|
81
|
+
if (problem !== undefined)
|
|
82
|
+
return { problem };
|
|
83
|
+
encoded = JSON.stringify(value);
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
// A getter or proxy that throws, or nesting too deep to walk; what it threw is not echoed.
|
|
87
|
+
return { problem: err instanceof RangeError ? "the Result is nested too deeply" : "the Result could not be read" };
|
|
88
|
+
}
|
|
89
|
+
const result = JSON.parse(encoded);
|
|
90
|
+
const problem = shapeProblem(declared, result, "Result");
|
|
91
|
+
if (problem !== undefined)
|
|
92
|
+
return { problem };
|
|
93
|
+
const bytes = Buffer.byteLength(encoded, "utf8");
|
|
94
|
+
return bytes > RESULT_CEILING_BYTES
|
|
95
|
+
? { problem: `the JSON encoding of the Result is ${bytes} bytes, past the 1 MiB ceiling (${RESULT_CEILING_BYTES} bytes)` }
|
|
96
|
+
: { result };
|
|
97
|
+
}
|
|
98
|
+
// JSON.stringify drops or rewrites what is not JSON (undefined, functions, NaN, a Date's
|
|
99
|
+
// toJSON) instead of failing, so the walk refuses each of them explicitly.
|
|
100
|
+
function jsonProblem(value, where, ancestors) {
|
|
101
|
+
switch (typeof value) {
|
|
102
|
+
case "string":
|
|
103
|
+
case "boolean":
|
|
104
|
+
return undefined;
|
|
105
|
+
case "number":
|
|
106
|
+
// NaN and ±Infinity are the numbers for which this is not 0 (the runner closure admits no Number.isFinite).
|
|
107
|
+
return value - value === 0 ? undefined : `${where} is a non-finite number`;
|
|
108
|
+
case "undefined":
|
|
109
|
+
case "function":
|
|
110
|
+
case "bigint":
|
|
111
|
+
case "symbol":
|
|
112
|
+
return `${where} is ${typeof value === "undefined" ? "undefined" : `a ${typeof value}`}`;
|
|
113
|
+
}
|
|
114
|
+
if (value === null)
|
|
115
|
+
return undefined;
|
|
116
|
+
const object = value;
|
|
117
|
+
if (ancestors.has(object))
|
|
118
|
+
return `${where} is a cycle`;
|
|
119
|
+
if (!Array.isArray(object)) {
|
|
120
|
+
const prototype = Object.getPrototypeOf(object);
|
|
121
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
122
|
+
return `${where} is ${object instanceof Date ? "a Date" : object instanceof Map ? "a Map" : "a class instance"}`;
|
|
123
|
+
}
|
|
124
|
+
if (typeof object.toJSON === "function")
|
|
125
|
+
return `${where} has a toJSON method`;
|
|
126
|
+
}
|
|
127
|
+
// Ancestors only, so a value shared twice without a cycle is accepted, as JSON.stringify does.
|
|
128
|
+
ancestors.add(object);
|
|
129
|
+
try {
|
|
130
|
+
const entries = [];
|
|
131
|
+
if (Array.isArray(object)) {
|
|
132
|
+
for (let index = 0; index < object.length; index++)
|
|
133
|
+
entries.push([`${where}[${index}]`, object[index]]);
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
for (const key of Object.keys(object))
|
|
137
|
+
entries.push([`${where}.${key}`, object[key]]);
|
|
138
|
+
}
|
|
139
|
+
for (const [at, item] of entries) {
|
|
140
|
+
const problem = jsonProblem(item, at, ancestors);
|
|
141
|
+
if (problem !== undefined)
|
|
142
|
+
return problem;
|
|
143
|
+
}
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
finally {
|
|
147
|
+
ancestors.delete(object);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function kindOf(value) {
|
|
151
|
+
if (value === null)
|
|
152
|
+
return "null";
|
|
153
|
+
if (Array.isArray(value))
|
|
154
|
+
return "array";
|
|
155
|
+
return typeof value;
|
|
156
|
+
}
|
|
157
|
+
// Runs on the parsed copy, so every value here is JSON.
|
|
158
|
+
function shapeProblem(declared, value, where) {
|
|
159
|
+
const kind = kindOf(value);
|
|
160
|
+
if (!declared.types.includes(kind))
|
|
161
|
+
return `${where} must be ${declared.types.join(" or ")}`;
|
|
162
|
+
if (kind === "array" && declared.items !== undefined) {
|
|
163
|
+
const items = declared.items;
|
|
164
|
+
for (const [index, item] of value.entries()) {
|
|
165
|
+
const problem = shapeProblem(items, item, `${where}[${index}]`);
|
|
166
|
+
if (problem !== undefined)
|
|
167
|
+
return problem;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (kind === "object" && declared.properties !== undefined) {
|
|
171
|
+
const record = value;
|
|
172
|
+
const required = new Set(declared.required);
|
|
173
|
+
for (const { key, schema } of declared.properties) {
|
|
174
|
+
if (!Object.hasOwn(record, key)) {
|
|
175
|
+
if (required.has(key))
|
|
176
|
+
return `${where}.${key} must be ${schema.types.join(" or ")}`;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
const problem = shapeProblem(schema, record[key], `${where}.${key}`);
|
|
180
|
+
if (problem !== undefined)
|
|
181
|
+
return problem;
|
|
182
|
+
}
|
|
183
|
+
const declaredKeys = new Set(declared.properties.map((property) => property.key));
|
|
184
|
+
const extra = Object.keys(record).find((key) => !declaredKeys.has(key));
|
|
185
|
+
if (extra !== undefined)
|
|
186
|
+
return `${where}.${extra} is not declared`;
|
|
187
|
+
}
|
|
188
|
+
return undefined;
|
|
189
|
+
}
|
|
@@ -52,11 +52,12 @@ export type AuthoringVerb = "create" | "modify" | "remove" | "rename" | "move" |
|
|
|
52
52
|
* case "source-not-found":
|
|
53
53
|
* case "source-not-regular-file":
|
|
54
54
|
* case "source-unreadable":
|
|
55
|
+
* case "invalid-result":
|
|
55
56
|
* console.error(err.message);
|
|
56
57
|
* break;
|
|
57
58
|
* }
|
|
58
59
|
*/
|
|
59
|
-
export type AuthoringReason = "path-collision" | "path-not-found" | "unrepresentable-content" | "changes-too-large" | "outside-session" | "unknown" | "invalid-input" | "reserved-name" | "source-not-found" | "source-not-regular-file" | "source-unreadable";
|
|
60
|
+
export type AuthoringReason = "path-collision" | "path-not-found" | "unrepresentable-content" | "changes-too-large" | "outside-session" | "unknown" | "invalid-input" | "reserved-name" | "source-not-found" | "source-not-regular-file" | "source-unreadable" | "invalid-result";
|
|
60
61
|
/**
|
|
61
62
|
* Distinguishes an engine-refused write from an SDK-side misuse (2.4, ADR-0021) —
|
|
62
63
|
* DERIVED from `reason`, never producer-set.
|
|
@@ -106,7 +107,7 @@ export declare class AuthoringError extends Error {
|
|
|
106
107
|
appliedCount: number;
|
|
107
108
|
/**
|
|
108
109
|
* Overrides the derived message. REQUIRED for `reason: "invalid-input"` /
|
|
109
|
-
* `"reserved-name"` (REQ-AEC-09) — their templates interpolate caller-known data
|
|
110
|
+
* `"reserved-name"` (REQ-AEC-09) / `"invalid-result"` (A-14) — their templates interpolate caller-known data
|
|
110
111
|
* (`{field}`, `{expectedType}`, `{name}`) `messageFor` cannot derive from `verb`/`path`
|
|
111
112
|
* alone. Optional for every other reason, which derive their message from `reason` +
|
|
112
113
|
* `verb` + `path` as before.
|
|
@@ -36,6 +36,7 @@ function originFor(reason) {
|
|
|
36
36
|
case "source-not-found":
|
|
37
37
|
case "source-not-regular-file":
|
|
38
38
|
case "source-unreadable":
|
|
39
|
+
case "invalid-result":
|
|
39
40
|
return "authoring-rejected";
|
|
40
41
|
default: {
|
|
41
42
|
const _exhaustive = reason;
|
|
@@ -121,6 +122,7 @@ function messageFor(reason, verb, path) {
|
|
|
121
122
|
return `source file unreadable: ${path} could not be read`;
|
|
122
123
|
case "invalid-input":
|
|
123
124
|
case "reserved-name":
|
|
125
|
+
case "invalid-result":
|
|
124
126
|
throw new Error(`messageFor: reason "${reason}" has no default template (REQ-AEC-09) — construct AuthoringError with an explicit \`message\``);
|
|
125
127
|
// Parity with originFor: noImplicitReturns is off, so without this arm a 13th reason
|
|
126
128
|
// would fall through to an implicit `undefined` return instead of a build break.
|
|
@@ -8,8 +8,25 @@ export interface SchemaProperty {
|
|
|
8
8
|
required?: boolean;
|
|
9
9
|
description?: string;
|
|
10
10
|
}
|
|
11
|
+
export type ResultKind = "string" | "number" | "boolean" | "null" | "object" | "array";
|
|
12
|
+
export declare const RESULT_KINDS: ReadonlySet<string>;
|
|
13
|
+
/**
|
|
14
|
+
* The Result a schematic declares under `result` in `schema.json` (A-14): a subset of JSON
|
|
15
|
+
* Schema. `properties` closes an object to the keys it names; without it any JSON object fits.
|
|
16
|
+
*/
|
|
17
|
+
export interface ResultSchema {
|
|
18
|
+
types: ResultKind[];
|
|
19
|
+
properties?: Array<{
|
|
20
|
+
key: string;
|
|
21
|
+
schema: ResultSchema;
|
|
22
|
+
}>;
|
|
23
|
+
required?: string[];
|
|
24
|
+
items?: ResultSchema;
|
|
25
|
+
}
|
|
11
26
|
export interface Schema {
|
|
12
27
|
properties: SchemaProperty[];
|
|
28
|
+
/** Absent when the schematic declares no Result, so its factory must return nothing. */
|
|
29
|
+
result?: ResultSchema;
|
|
13
30
|
}
|
|
14
31
|
export declare const RESERVED_LIFECYCLE_NAMES: readonly ["pre-execute", "post-execute"];
|
|
15
32
|
export declare const FORBIDDEN_KEYS: Set<string>;
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// This is a DISTINCT shape from the on-disk wire contract (ADR-0027): the wire form is a
|
|
5
5
|
// wrapped `{ "properties": { "<key>": {...} } }` map (the SDK<->Go-CLI cross-repo contract);
|
|
6
6
|
// schema-parse.ts lifts that map into this array, `key` becoming an explicit field.
|
|
7
|
+
export const RESULT_KINDS = new Set(["string", "number", "boolean", "null", "object", "array"]);
|
|
7
8
|
// Cross-repo lifecycle tokens (2026-07-06 engine handoff) — schematic-level, kebab-case,
|
|
8
9
|
// case-insensitive matching lives in the reserved-name scan (S-004, ADR-0028).
|
|
9
10
|
export const RESERVED_LIFECYCLE_NAMES = ["pre-execute", "post-execute"];
|
|
@@ -4,4 +4,5 @@ export declare class UnrecognizedPropertyTypeError extends Error {
|
|
|
4
4
|
readonly field: string;
|
|
5
5
|
constructor(field: string);
|
|
6
6
|
}
|
|
7
|
+
/** The Input type, and the Result type when the schema declares a Result (A-15). */
|
|
7
8
|
export declare function emitInputType(schema: Schema, digest: string): string;
|
|
@@ -54,6 +54,28 @@ function emitProperty(property) {
|
|
|
54
54
|
: "";
|
|
55
55
|
return `${doc} ${key}${optional}: ${type};`;
|
|
56
56
|
}
|
|
57
|
+
// A-15: the declared Result as a type. Kinds come from the closed set parseSchema checked,
|
|
58
|
+
// and keys go through emitPropertyKey, so no schema text reaches the output unquoted.
|
|
59
|
+
function emitResult(result) {
|
|
60
|
+
return result.types
|
|
61
|
+
.map((kind) => {
|
|
62
|
+
switch (kind) {
|
|
63
|
+
case "array":
|
|
64
|
+
return `Array<${result.items === undefined ? "unknown" : emitResult(result.items)}>`;
|
|
65
|
+
case "object": {
|
|
66
|
+
if (result.properties === undefined)
|
|
67
|
+
return "{ [key: string]: unknown }";
|
|
68
|
+
const required = new Set(result.required);
|
|
69
|
+
const members = result.properties.map(({ key, schema }) => `${emitPropertyKey(key)}${required.has(key) ? "" : "?"}: ${emitResult(schema)}`);
|
|
70
|
+
return members.length === 0 ? "Record<string, never>" : `{ ${members.join("; ")} }`;
|
|
71
|
+
}
|
|
72
|
+
default:
|
|
73
|
+
return kind;
|
|
74
|
+
}
|
|
75
|
+
})
|
|
76
|
+
.join(" | ");
|
|
77
|
+
}
|
|
78
|
+
/** The Input type, and the Result type when the schema declares a Result (A-15). */
|
|
57
79
|
export function emitInputType(schema, digest) {
|
|
58
80
|
const members = schema.properties.map(emitProperty).join("\n");
|
|
59
81
|
return [
|
|
@@ -63,6 +85,7 @@ export function emitInputType(schema, digest) {
|
|
|
63
85
|
"export type Input = {",
|
|
64
86
|
members,
|
|
65
87
|
"};",
|
|
88
|
+
...(schema.result === undefined ? [] : ["", `export type Result = ${emitResult(schema.result)};`]),
|
|
66
89
|
"",
|
|
67
90
|
].join("\n");
|
|
68
91
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { defineDialect, defineOpPack, withOps } from "../../../../domain/services/define-dialect.js";
|
|
2
|
-
import { parse, print } from "../typescript/ast.js";
|
|
2
|
+
import { parse, print, retire } from "../typescript/ast.js";
|
|
3
3
|
import { typescriptOps } from "../typescript/pack.js";
|
|
4
4
|
import { addBootstrap, addComponentImport, addComponentProvider, addComputed, addDeclaration, addInjection, addInput, addLazyRoute, addModel, addNgModuleExport, addNgModuleImport, addNgModuleProvider, addOutput, addRootProvider, addRoute, addSignal, } from "./ops.js";
|
|
5
5
|
export * as astLibrary from "ts-morph";
|
|
@@ -23,7 +23,7 @@ const angularOps = defineOpPack({
|
|
|
23
23
|
});
|
|
24
24
|
const baseDialect = defineDialect({
|
|
25
25
|
extensions: [".ts"],
|
|
26
|
-
ast: { parse, print },
|
|
26
|
+
ast: { parse, print, retire },
|
|
27
27
|
ops: {},
|
|
28
28
|
});
|
|
29
29
|
const angularDialect = withOps(baseDialect, typescriptOps, angularOps);
|
|
@@ -7,23 +7,26 @@ export { language } from "../csharp/ast.ts";
|
|
|
7
7
|
export type { CsharpDocument, FromOptions, UsingOptions } from "../csharp/index.ts";
|
|
8
8
|
export type { Lifetime, ServiceOptions };
|
|
9
9
|
type ServiceOps = {
|
|
10
|
-
addService: (ast: CsharpDocument, lifetime: Lifetime, service: string, implementation
|
|
10
|
+
addService: (ast: CsharpDocument, lifetime: Lifetime, service: string, implementation?: string, options?: ServiceOptions) => void;
|
|
11
11
|
};
|
|
12
12
|
type AspnetOps = CsharpOps & ServiceOps;
|
|
13
13
|
/**
|
|
14
14
|
* Opens a `.cs` file of an ASP.NET Core application. The handle carries every
|
|
15
15
|
* `@pbuilder/sdk/csharp` op plus `addService`, chained on one handle and written once.
|
|
16
16
|
*
|
|
17
|
-
* `addService(lifetime, service, implementation
|
|
17
|
+
* `addService(lifetime, service, implementation?, { serviceFrom?, implementationFrom?, method? })`
|
|
18
18
|
* writes `<receiver>.Add<lifetime><service, implementation>();` once, `lifetime` being
|
|
19
|
-
* `"Singleton"`, `"Scoped"` or `"Transient"
|
|
19
|
+
* `"Singleton"`, `"Scoped"` or `"Transient"`; when `implementation` is left out or equals
|
|
20
|
+
* `service`, it writes `<receiver>.Add<lifetime><service>();`. Without `method` it edits the top-level statements
|
|
20
21
|
* of `Program.cs`: the receiver is `<builder>.Services` of the one variable initialized by
|
|
21
22
|
* `WebApplication.CreateBuilder` (or `CreateSlimBuilder`, `CreateEmptyBuilder`), and the line
|
|
22
23
|
* goes just before the statement that calls `<builder>.Build()`. With `method` it edits the one
|
|
23
24
|
* static method of that name whose first parameter is `this IServiceCollection`, before its
|
|
24
25
|
* `return`. `serviceFrom` and `implementationFrom` add the `using` of each type unless the file
|
|
25
|
-
* already sees it. The same registration already there
|
|
26
|
-
*
|
|
26
|
+
* already sees it. The same registration already there, called with no arguments, changes
|
|
27
|
+
* nothing (`Add<L><S>()` and `Add<L><S, S>()` are the same registration); the same pair with
|
|
28
|
+
* another lifetime or with arguments such as a factory, or a file with no such place, rejects and
|
|
29
|
+
* leaves the file as it is.
|
|
27
30
|
*
|
|
28
31
|
* @example
|
|
29
32
|
* import * as aspnet from "@pbuilder/sdk/aspnet";
|
|
@@ -10,16 +10,19 @@ const aspnetDialect = withOps(defineDialect({ extensions: [".cs"], ast: { parse,
|
|
|
10
10
|
* Opens a `.cs` file of an ASP.NET Core application. The handle carries every
|
|
11
11
|
* `@pbuilder/sdk/csharp` op plus `addService`, chained on one handle and written once.
|
|
12
12
|
*
|
|
13
|
-
* `addService(lifetime, service, implementation
|
|
13
|
+
* `addService(lifetime, service, implementation?, { serviceFrom?, implementationFrom?, method? })`
|
|
14
14
|
* writes `<receiver>.Add<lifetime><service, implementation>();` once, `lifetime` being
|
|
15
|
-
* `"Singleton"`, `"Scoped"` or `"Transient"
|
|
15
|
+
* `"Singleton"`, `"Scoped"` or `"Transient"`; when `implementation` is left out or equals
|
|
16
|
+
* `service`, it writes `<receiver>.Add<lifetime><service>();`. Without `method` it edits the top-level statements
|
|
16
17
|
* of `Program.cs`: the receiver is `<builder>.Services` of the one variable initialized by
|
|
17
18
|
* `WebApplication.CreateBuilder` (or `CreateSlimBuilder`, `CreateEmptyBuilder`), and the line
|
|
18
19
|
* goes just before the statement that calls `<builder>.Build()`. With `method` it edits the one
|
|
19
20
|
* static method of that name whose first parameter is `this IServiceCollection`, before its
|
|
20
21
|
* `return`. `serviceFrom` and `implementationFrom` add the `using` of each type unless the file
|
|
21
|
-
* already sees it. The same registration already there
|
|
22
|
-
*
|
|
22
|
+
* already sees it. The same registration already there, called with no arguments, changes
|
|
23
|
+
* nothing (`Add<L><S>()` and `Add<L><S, S>()` are the same registration); the same pair with
|
|
24
|
+
* another lifetime or with arguments such as a factory, or a file with no such place, rejects and
|
|
25
|
+
* leaves the file as it is.
|
|
23
26
|
*
|
|
24
27
|
* @example
|
|
25
28
|
* import * as aspnet from "@pbuilder/sdk/aspnet";
|
|
@@ -8,4 +8,4 @@ export interface ServiceOptions {
|
|
|
8
8
|
/** Edits the one `static` method of this name whose first parameter is `this IServiceCollection`. */
|
|
9
9
|
method?: string;
|
|
10
10
|
}
|
|
11
|
-
export declare function addService(doc: CsharpDocument, lifetime: Lifetime, service: string, implementation
|
|
11
|
+
export declare function addService(doc: CsharpDocument, lifetime: Lifetime, service: string, implementation?: string, options?: ServiceOptions): void;
|
|
@@ -5,7 +5,7 @@ import { importNamespace } from "../csharp/ops.js";
|
|
|
5
5
|
import { endOfNode, indentAt, indentUnit, isTrivia, lineEnding, splice } from "../csharp/syntax.js";
|
|
6
6
|
const LIFETIMES = ["Singleton", "Scoped", "Transient"];
|
|
7
7
|
const BUILDER_FACTORIES = new Set(["CreateBuilder", "CreateSlimBuilder", "CreateEmptyBuilder"]);
|
|
8
|
-
/** `<receiver>.Add<Lifetime><Service, Implementation>()
|
|
8
|
+
/** `<receiver>.Add<Lifetime><Service>(...)` or `<receiver>.Add<Lifetime><Service, Implementation>(...)` as a registration, or `undefined`. */
|
|
9
9
|
function registration(statement, receiver) {
|
|
10
10
|
if (statement.type !== "expression_statement")
|
|
11
11
|
return undefined;
|
|
@@ -16,9 +16,15 @@ function registration(statement, receiver) {
|
|
|
16
16
|
const generic = callee.childForFieldName("name");
|
|
17
17
|
const lifetime = /^Add(Singleton|Scoped|Transient)$/.exec(generic.namedChildren[0]?.text ?? "")?.[1];
|
|
18
18
|
const types = generic.namedChildren[1]?.namedChildren ?? [];
|
|
19
|
-
if (generic.type !== "generic_name" || lifetime === undefined || types.length !== 2)
|
|
19
|
+
if (generic.type !== "generic_name" || lifetime === undefined || (types.length !== 1 && types.length !== 2))
|
|
20
20
|
return undefined;
|
|
21
|
-
|
|
21
|
+
const service = compact(types[0].text);
|
|
22
|
+
return {
|
|
23
|
+
lifetime,
|
|
24
|
+
service,
|
|
25
|
+
implementation: types.length === 2 ? compact(types[1].text) : service,
|
|
26
|
+
passesArguments: (call.childForFieldName("arguments")?.namedChildren.length ?? 0) > 0,
|
|
27
|
+
};
|
|
22
28
|
}
|
|
23
29
|
function isBuilderCall(value) {
|
|
24
30
|
const callee = value?.type === "invocation_expression" ? value.childForFieldName("function") : null;
|
|
@@ -99,7 +105,10 @@ export function addService(doc, lifetime, service, implementation, options) {
|
|
|
99
105
|
throw dialectError(`${op} — \`lifetime\` ${JSON.stringify(lifetime)} is not a lifetime; use "Singleton", "Scoped" or "Transient"`);
|
|
100
106
|
}
|
|
101
107
|
assertType(op, "service", service);
|
|
102
|
-
|
|
108
|
+
if (implementation !== undefined)
|
|
109
|
+
assertType(op, "implementation", implementation);
|
|
110
|
+
const implementationType = implementation ?? service;
|
|
111
|
+
const singleType = compact(implementationType) === compact(service);
|
|
103
112
|
const opts = assertOptions(op, options, ["serviceFrom", "implementationFrom", "method"]);
|
|
104
113
|
if (opts.serviceFrom !== undefined)
|
|
105
114
|
assertNamespace(op, "serviceFrom", opts.serviceFrom);
|
|
@@ -112,13 +121,17 @@ export function addService(doc, lifetime, service, implementation, options) {
|
|
|
112
121
|
const receiver = compact(place.receiver);
|
|
113
122
|
const existing = place.statements
|
|
114
123
|
.map((statement) => registration(statement, receiver))
|
|
115
|
-
.find((r) => r !== undefined && r.service === compact(service) && r.implementation === compact(
|
|
124
|
+
.find((r) => r !== undefined && r.service === compact(service) && r.implementation === compact(implementationType));
|
|
125
|
+
if (existing?.passesArguments) {
|
|
126
|
+
throw dialectError(`${op}(${JSON.stringify(service)}) — \`${service}\` is already registered with \`${implementationType}\` by a call that passes arguments; edit it with .modify()`);
|
|
127
|
+
}
|
|
116
128
|
if (existing?.lifetime === lifetime)
|
|
117
129
|
return undefined;
|
|
118
130
|
if (existing !== undefined) {
|
|
119
|
-
throw dialectError(`${op}(${JSON.stringify(service)}) — \`${service}\` is already registered with \`${
|
|
131
|
+
throw dialectError(`${op}(${JSON.stringify(service)}) — \`${service}\` is already registered with \`${implementationType}\` as ${existing.lifetime}, not ${lifetime}`);
|
|
120
132
|
}
|
|
121
|
-
|
|
133
|
+
const types = singleType ? service.trim() : `${service.trim()}, ${implementationType.trim()}`;
|
|
134
|
+
return place.insert(doc.text, `${place.receiver}.Add${lifetime}<${types}>();`);
|
|
122
135
|
});
|
|
123
136
|
if (edited === undefined)
|
|
124
137
|
return;
|
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
import { type Handle } from "../../../../domain/services/define-dialect.ts";
|
|
2
2
|
import { type MsbuildDocument } from "./ast.ts";
|
|
3
|
+
import { type ProjectOptions } from "./ops.ts";
|
|
3
4
|
export * as astLibrary from "saxes";
|
|
4
|
-
export type { MsbuildDocument };
|
|
5
|
+
export type { MsbuildDocument, ProjectOptions };
|
|
5
6
|
type MsbuildOps = {
|
|
6
7
|
addProjectReference: (ast: MsbuildDocument, path: string) => void;
|
|
8
|
+
addProject: (ast: MsbuildDocument, path: string, options?: ProjectOptions) => void;
|
|
7
9
|
};
|
|
8
10
|
/**
|
|
9
|
-
* Opens a `.csproj`, `.props`, `.targets` or `.slnx` file
|
|
11
|
+
* Opens a `.csproj`, `.props`, `.targets` or `.slnx` file. `addProjectReference(path)` edits a
|
|
12
|
+
* file whose root element is `Project`; `addProject(path, { folder? })` adds a project to a `.slnx`
|
|
13
|
+
* `<Solution>`, in the solution folder `folder` (such as `/src/`) when given. The
|
|
10
14
|
* dialect edits the XML text and changes only the bytes it must: the XML declaration, comments,
|
|
11
15
|
* attribute quotes, indentation, line endings, a BOM, and the final newline survive. The classic
|
|
12
16
|
* `.sln` format and any other extension throw synchronously with the `dialect operation failed: `
|
|
@@ -33,5 +37,19 @@ type MsbuildOps = {
|
|
|
33
37
|
* // -> <ProjectReference Include="../Shop.Application/Shop.Application.csproj" />
|
|
34
38
|
* // -> </ItemGroup>
|
|
35
39
|
* // -> </Project>
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* import * as msbuild from "@pbuilder/sdk/msbuild";
|
|
43
|
+
*
|
|
44
|
+
* // Shop.slnx before:
|
|
45
|
+
* // <Solution>\n</Solution>\n
|
|
46
|
+
* export const run = async () => {
|
|
47
|
+
* await msbuild.find("Shop.slnx").addProject("src/Shop.Api/Shop.Api.csproj", { folder: "/src/" });
|
|
48
|
+
* };
|
|
49
|
+
* // -> <Solution>
|
|
50
|
+
* // -> <Folder Name="/src/">
|
|
51
|
+
* // -> <Project Path="src/Shop.Api/Shop.Api.csproj" />
|
|
52
|
+
* // -> </Folder>
|
|
53
|
+
* // -> </Solution>
|
|
36
54
|
*/
|
|
37
55
|
export declare function find(path: string): Handle<"found", MsbuildDocument, MsbuildOps>;
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { defineDialect, defineOpPack, withOps } from "../../../../domain/services/define-dialect.js";
|
|
2
2
|
import { parse, print } from "./ast.js";
|
|
3
|
-
import { addProjectReference } from "./ops.js";
|
|
3
|
+
import { addProject, addProjectReference } from "./ops.js";
|
|
4
4
|
export * as astLibrary from "saxes";
|
|
5
|
-
const opsPack = defineOpPack({ addProjectReference });
|
|
5
|
+
const opsPack = defineOpPack({ addProjectReference, addProject });
|
|
6
6
|
const msbuildDialect = withOps(defineDialect({ extensions: [".csproj", ".props", ".targets", ".slnx"], ast: { parse, print }, ops: {} }), opsPack);
|
|
7
7
|
/**
|
|
8
|
-
* Opens a `.csproj`, `.props`, `.targets` or `.slnx` file
|
|
8
|
+
* Opens a `.csproj`, `.props`, `.targets` or `.slnx` file. `addProjectReference(path)` edits a
|
|
9
|
+
* file whose root element is `Project`; `addProject(path, { folder? })` adds a project to a `.slnx`
|
|
10
|
+
* `<Solution>`, in the solution folder `folder` (such as `/src/`) when given. The
|
|
9
11
|
* dialect edits the XML text and changes only the bytes it must: the XML declaration, comments,
|
|
10
12
|
* attribute quotes, indentation, line endings, a BOM, and the final newline survive. The classic
|
|
11
13
|
* `.sln` format and any other extension throw synchronously with the `dialect operation failed: `
|
|
@@ -32,6 +34,20 @@ const msbuildDialect = withOps(defineDialect({ extensions: [".csproj", ".props",
|
|
|
32
34
|
* // -> <ProjectReference Include="../Shop.Application/Shop.Application.csproj" />
|
|
33
35
|
* // -> </ItemGroup>
|
|
34
36
|
* // -> </Project>
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* import * as msbuild from "@pbuilder/sdk/msbuild";
|
|
40
|
+
*
|
|
41
|
+
* // Shop.slnx before:
|
|
42
|
+
* // <Solution>\n</Solution>\n
|
|
43
|
+
* export const run = async () => {
|
|
44
|
+
* await msbuild.find("Shop.slnx").addProject("src/Shop.Api/Shop.Api.csproj", { folder: "/src/" });
|
|
45
|
+
* };
|
|
46
|
+
* // -> <Solution>
|
|
47
|
+
* // -> <Folder Name="/src/">
|
|
48
|
+
* // -> <Project Path="src/Shop.Api/Shop.Api.csproj" />
|
|
49
|
+
* // -> </Folder>
|
|
50
|
+
* // -> </Solution>
|
|
35
51
|
*/
|
|
36
52
|
export function find(path) {
|
|
37
53
|
return msbuildDialect.find(path);
|
|
@@ -1,2 +1,7 @@
|
|
|
1
1
|
import type { MsbuildDocument } from "./ast.ts";
|
|
2
|
+
export interface ProjectOptions {
|
|
3
|
+
/** The solution folder that holds the project, such as `/src/`; it is created when missing. */
|
|
4
|
+
folder?: string;
|
|
5
|
+
}
|
|
2
6
|
export declare const addProjectReference: (ast: MsbuildDocument, path: string) => void;
|
|
7
|
+
export declare const addProject: (ast: MsbuildDocument, path: string, options?: ProjectOptions | undefined) => void;
|
|
@@ -2,16 +2,32 @@ import { dialectError } from "../../../../domain/valueobjects/dialect-error.js";
|
|
|
2
2
|
import { validatedOp } from "../../../../domain/services/identifier-names.js";
|
|
3
3
|
import { readElements } from "./xml.js";
|
|
4
4
|
const OP = "addProjectReference";
|
|
5
|
+
const ADD_PROJECT = "addProject";
|
|
5
6
|
const DEFAULT_UNIT = " ";
|
|
6
|
-
function assertPath(path) {
|
|
7
|
+
function assertPath(op, path) {
|
|
7
8
|
const rule = "a relative path whose file name ends in `proj`";
|
|
8
9
|
if (typeof path !== "string")
|
|
9
|
-
throw dialectError(`${
|
|
10
|
+
throw dialectError(`${op} — \`path\` must be ${rule}.`);
|
|
10
11
|
const fileName = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
|
|
11
12
|
if (/^([/\\]|[A-Za-z]:)/.test(path) || !fileName.endsWith("proj")) {
|
|
12
|
-
throw dialectError(`${
|
|
13
|
+
throw dialectError(`${op} — \`path\` ${JSON.stringify(path)} is not ${rule}.`);
|
|
13
14
|
}
|
|
14
15
|
}
|
|
16
|
+
/** The root element of `doc`, rejecting malformed XML and any root not named `name`. */
|
|
17
|
+
function readRoot(doc, op, path, name) {
|
|
18
|
+
let root;
|
|
19
|
+
try {
|
|
20
|
+
root = readElements(doc.text);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
throw dialectError(`${op}(${JSON.stringify(path)}) — the file is not well-formed XML.`);
|
|
24
|
+
}
|
|
25
|
+
if (root?.name !== name) {
|
|
26
|
+
const found = root === undefined ? "the file has no root element" : `the root element is \`${root.name}\``;
|
|
27
|
+
throw dialectError(`${op}(${JSON.stringify(path)}) — ${found}; it needs \`${name}\`.`);
|
|
28
|
+
}
|
|
29
|
+
return root;
|
|
30
|
+
}
|
|
15
31
|
function escapeAttribute(value) {
|
|
16
32
|
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
17
33
|
}
|
|
@@ -45,18 +61,23 @@ function* descendants(element) {
|
|
|
45
61
|
function splice(doc, from, to, insert) {
|
|
46
62
|
doc.text = doc.text.slice(0, from) + insert + doc.text.slice(to);
|
|
47
63
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
64
|
+
/** Puts `block`, already indented one unit deeper than `element`, inside an `element` with no children. */
|
|
65
|
+
function openEmpty(doc, element, block, eol) {
|
|
66
|
+
const text = doc.text;
|
|
67
|
+
const indent = lineIndent(text, element.start) ?? "";
|
|
68
|
+
if (element.selfClosing) {
|
|
69
|
+
let cut = text.lastIndexOf("/", element.end - 1);
|
|
70
|
+
while (/\s/.test(text[cut - 1]))
|
|
71
|
+
cut--;
|
|
72
|
+
splice(doc, cut, element.end, `>${eol}${block}${eol}${indent}</${element.name}>`);
|
|
55
73
|
}
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
74
|
+
else {
|
|
75
|
+
const closeOnOwnLine = text.slice(element.openEnd, element.closeStart).includes("\n");
|
|
76
|
+
splice(doc, element.openEnd, element.openEnd, `${eol}${block}${closeOnOwnLine ? "" : eol + indent}`);
|
|
59
77
|
}
|
|
78
|
+
}
|
|
79
|
+
export const addProjectReference = validatedOp(([path]) => assertPath(OP, path), (doc, path) => {
|
|
80
|
+
const project = readRoot(doc, OP, path, "Project");
|
|
60
81
|
for (const element of descendants(project)) {
|
|
61
82
|
const include = element.attributes.get("Include");
|
|
62
83
|
if (element.name === "ProjectReference" && include !== undefined && sameReference(include, path))
|
|
@@ -80,14 +101,62 @@ export const addProjectReference = validatedOp(([path]) => assertPath(path), (do
|
|
|
80
101
|
if (last !== undefined) {
|
|
81
102
|
splice(doc, last.end, last.end, `${eol}${eol}${block}`);
|
|
82
103
|
}
|
|
83
|
-
else
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
104
|
+
else {
|
|
105
|
+
openEmpty(doc, project, block, eol);
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
function assertFolder(folder) {
|
|
109
|
+
if (typeof folder !== "string" || !/^\/([^/]+\/)+$/.test(folder)) {
|
|
110
|
+
throw dialectError(`${ADD_PROJECT} — \`options.folder\` ${JSON.stringify(folder)} is not a solution folder name: \`/\` followed by one or more non-empty segments that each end in \`/\`, such as "/src/" or "/src/Core/".`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const isProject = (element) => element.name === "Project";
|
|
114
|
+
export const addProject = validatedOp(([path, options]) => {
|
|
115
|
+
assertPath(ADD_PROJECT, path);
|
|
116
|
+
if (options === undefined)
|
|
117
|
+
return;
|
|
118
|
+
if (typeof options !== "object" || options === null || Array.isArray(options) || Object.keys(options).some((key) => key !== "folder")) {
|
|
119
|
+
throw dialectError(`${ADD_PROJECT} — \`options\` must be an object holding only \`folder\`.`);
|
|
120
|
+
}
|
|
121
|
+
if (options.folder !== undefined)
|
|
122
|
+
assertFolder(options.folder);
|
|
123
|
+
}, (doc, path, options) => {
|
|
124
|
+
const solution = readRoot(doc, ADD_PROJECT, path, "Solution");
|
|
125
|
+
const folderName = options?.folder;
|
|
126
|
+
const folder = folderName === undefined ? solution : solution.children.find((c) => c.name === "Folder" && c.attributes.get("Name") === folderName);
|
|
127
|
+
const samePath = (element) => {
|
|
128
|
+
const projectPath = element.attributes.get("Path");
|
|
129
|
+
return isProject(element) && projectPath !== undefined && sameReference(projectPath, path);
|
|
130
|
+
};
|
|
131
|
+
if (folder?.children.some(samePath))
|
|
132
|
+
return;
|
|
133
|
+
if ([...descendants(solution)].some(samePath)) {
|
|
134
|
+
throw dialectError(`${ADD_PROJECT}(${JSON.stringify(path)}) — the solution already holds this project at another place; move it with .modify().`);
|
|
135
|
+
}
|
|
136
|
+
const text = doc.text;
|
|
137
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
138
|
+
const unit = indentUnit(text, solution);
|
|
139
|
+
const entry = `<Project Path="${escapeAttribute(path)}" />`;
|
|
140
|
+
/** `line` indented under `parent`, after its child `after`, or as its only child. */
|
|
141
|
+
const append = (parent, after, line) => {
|
|
142
|
+
const indent = (after && lineIndent(text, after.start)) ?? (lineIndent(text, parent.start) ?? "") + unit;
|
|
143
|
+
if (after === undefined)
|
|
144
|
+
openEmpty(doc, parent, line(indent), eol);
|
|
145
|
+
else
|
|
146
|
+
splice(doc, after.end, after.end, `${eol}${line(indent)}`);
|
|
147
|
+
};
|
|
148
|
+
if (folder !== undefined) {
|
|
149
|
+
append(folder, folder.children.filter(isProject).at(-1) ?? folder.children.at(-1), (indent) => `${indent}${entry}`);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const block = (indent) => `${indent}<Folder Name="${escapeAttribute(folderName)}">${eol}${indent}${unit}${entry}${eol}${indent}</Folder>`;
|
|
153
|
+
const lastFolder = solution.children.filter((c) => c.name === "Folder").at(-1);
|
|
154
|
+
const first = solution.children[0];
|
|
155
|
+
const firstIndent = first && lineIndent(text, first.start);
|
|
156
|
+
if (lastFolder !== undefined || first === undefined || firstIndent === undefined) {
|
|
157
|
+
append(solution, lastFolder ?? solution.children.at(-1), block);
|
|
88
158
|
}
|
|
89
159
|
else {
|
|
90
|
-
|
|
91
|
-
splice(doc, project.openEnd, project.openEnd, `${eol}${block}${closeOnOwnLine ? "" : eol + projectIndent}`);
|
|
160
|
+
splice(doc, first.start, first.start, `${block(firstIndent).slice(firstIndent.length)}${eol}${firstIndent}`);
|
|
92
161
|
}
|
|
93
162
|
});
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { defineDialect, defineOpPack, withOps } from "../../../../domain/services/define-dialect.js";
|
|
2
|
-
import { parse, print } from "../typescript/ast.js";
|
|
2
|
+
import { parse, print, retire } from "../typescript/ast.js";
|
|
3
3
|
import { typescriptOps } from "../typescript/pack.js";
|
|
4
4
|
import { addController, addExport, addModuleImport, addProvider } from "./ops.js";
|
|
5
5
|
export * as astLibrary from "ts-morph";
|
|
6
6
|
const moduleOps = defineOpPack({ addProvider, addController, addModuleImport, addExport });
|
|
7
7
|
const baseDialect = defineDialect({
|
|
8
8
|
extensions: [".ts"],
|
|
9
|
-
ast: { parse, print },
|
|
9
|
+
ast: { parse, print, retire },
|
|
10
10
|
ops: {},
|
|
11
11
|
});
|
|
12
12
|
const nestjsDialect = withOps(baseDialect, typescriptOps, moduleOps);
|