@loozo/angular-launch 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,90 @@
1
+ import { inject } from "@angular/core";
2
+ import { HttpClient, HttpContext, HttpContextToken, HttpErrorResponse } from "@angular/common/http";
3
+ import { RpcError, recognizedError } from "./client.js";
4
+ import { serializeJson } from "./json.js";
5
+ export const RPC_CALL = new HttpContextToken(() => false);
6
+ const errorOwners = new WeakMap();
7
+ function call(http, group, method, input, { signal, transferCache = true } = {}) {
8
+ return new Promise((resolve, reject) => {
9
+ let subscription;
10
+ let settled = false;
11
+ function cleanup() {
12
+ signal?.removeEventListener("abort", abort);
13
+ subscription?.unsubscribe();
14
+ }
15
+ function abort() {
16
+ if (settled) {
17
+ return;
18
+ }
19
+ settled = true;
20
+ cleanup();
21
+ reject(new DOMException("RPC call aborted", "AbortError"));
22
+ }
23
+ if (signal?.aborted) {
24
+ abort();
25
+ return;
26
+ }
27
+ const envelope = JSON.parse(serializeJson({ input }));
28
+ signal?.addEventListener("abort", abort, { once: true });
29
+ if (method.kind === "mutation") {
30
+ transferCache = false;
31
+ }
32
+ subscription = http
33
+ .post(`/_rpc/${group}/${method.name}`, envelope, {
34
+ context: new HttpContext().set(RPC_CALL, true),
35
+ transferCache,
36
+ })
37
+ .subscribe({
38
+ next(value) {
39
+ settled = true;
40
+ cleanup();
41
+ resolve(value);
42
+ },
43
+ error(error) {
44
+ settled = true;
45
+ cleanup();
46
+ if (error instanceof HttpErrorResponse) {
47
+ const frame = recognizedError(error.error, error.status, method.errors);
48
+ if (frame) {
49
+ const converted = new RpcError(frame.code, error.status, frame.data, frame.message);
50
+ errorOwners.set(converted, { group, method: method.name });
51
+ reject(converted);
52
+ return;
53
+ }
54
+ }
55
+ reject(error);
56
+ },
57
+ });
58
+ if (settled) {
59
+ cleanup();
60
+ }
61
+ });
62
+ }
63
+ export function injectClient(groups) {
64
+ const http = inject(HttpClient);
65
+ const result = Object.create(null);
66
+ for (const [namespace, group] of Object.entries(groups)) {
67
+ const methods = Object.create(null);
68
+ for (const method of group.methods) {
69
+ let invoke;
70
+ if (method.input) {
71
+ invoke = (input, options) => call(http, group.id, method, input, options);
72
+ }
73
+ else {
74
+ invoke = (options) => call(http, group.id, method, null, options);
75
+ }
76
+ methods[method.name] = Object.assign(invoke, {
77
+ kind: method.kind,
78
+ isError: (error) => {
79
+ if (typeof error !== "object" || error === null) {
80
+ return false;
81
+ }
82
+ const owner = errorOwners.get(error);
83
+ return owner?.group === group.id && owner.method === method.name;
84
+ },
85
+ });
86
+ }
87
+ result[namespace] = methods;
88
+ }
89
+ return result;
90
+ }
@@ -0,0 +1,13 @@
1
+ export interface GenerationOptions {
2
+ tsconfig: string;
3
+ scanDirectories: string[];
4
+ outDirectory: string;
5
+ check?: boolean;
6
+ }
7
+ export interface GenerationSession {
8
+ generate(options?: Pick<GenerationOptions, "check">, stopped?: () => boolean): Promise<void>;
9
+ dispose(): Promise<void>;
10
+ }
11
+ export declare function generate(workspace: string, options: GenerationOptions, stopped?: () => boolean): Promise<void>;
12
+ /** Owns compiler reuse for one explicitly sequenced application-generation lifetime. */
13
+ export declare function createGenerationSession(workspace: string, { tsconfig, scanDirectories, outDirectory }: Omit<GenerationOptions, "check">): GenerationSession;
@@ -0,0 +1,563 @@
1
+ import ts from "typescript";
2
+ import { frameworkFailures } from "../client.js";
3
+ import { createHash } from "node:crypto";
4
+ import { readFile, realpath } from "node:fs/promises";
5
+ import { dirname, resolve, relative, sep } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { prepareLaunchRoutes, createValidationProgram, validateRoutes, planOutputs, publish, walk, auditPath, launchMarkers, fail, properties, namedImport, genuineImport, specifier, CompilerState, AnchorState, } from "@loozo/angular-router/_generation";
8
+ function directCall(node, label) {
9
+ if (!ts.isCallExpression(node) || node.typeArguments?.length) {
10
+ fail(node, `${label} requires a direct nongeneric factory call`);
11
+ }
12
+ return node;
13
+ }
14
+ function guards(node) {
15
+ if (node && (!ts.isArrayLiteralExpression(node) || node.elements.some(ts.isSpreadElement))) {
16
+ fail(node, "canActivate must be an explicit inline array without spreads");
17
+ }
18
+ }
19
+ function onlyKeys(fields, allowed, node) {
20
+ for (const key of fields.keys()) {
21
+ if (!allowed.includes(key)) {
22
+ fail(node, `Unsupported Launch option: ${key}`);
23
+ }
24
+ }
25
+ }
26
+ function errorMetadata(node) {
27
+ const result = [];
28
+ if (!node) {
29
+ return result;
30
+ }
31
+ for (const [code, value] of properties(node, "Declared RPC errors")) {
32
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(code) ||
33
+ code === "__proto__" ||
34
+ Object.hasOwn(frameworkFailures, code)) {
35
+ fail(value, `Invalid or reserved declared RPC error code: ${code}`);
36
+ }
37
+ const fields = properties(value, "Declared RPC error");
38
+ onlyKeys(fields, ["status", "message", "data"], value);
39
+ const status = fields.get("status");
40
+ const message = fields.get("message");
41
+ if (!status ||
42
+ !ts.isNumericLiteral(status) ||
43
+ !Number.isInteger(Number(status.text)) ||
44
+ Number(status.text) < 400 ||
45
+ Number(status.text) > 599 ||
46
+ !message ||
47
+ !ts.isStringLiteral(message) ||
48
+ message.text.length === 0 ||
49
+ !fields.has("data")) {
50
+ fail(value, "Declared errors require literal integer status 400–599, nonempty message and data schema");
51
+ }
52
+ result.push({ code, status: Number(status.text), message: message.text });
53
+ }
54
+ return result;
55
+ }
56
+ function hasNonConcreteSchemaBranch(type) {
57
+ if (type.isUnion()) {
58
+ return type.types.some(hasNonConcreteSchemaBranch);
59
+ }
60
+ return ((type.flags &
61
+ (ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !==
62
+ 0);
63
+ }
64
+ function add(desired, path, text) {
65
+ if (desired.has(path)) {
66
+ throw new Error(`Duplicate desired output path: ${path}`);
67
+ }
68
+ desired.set(path, text);
69
+ }
70
+ async function groupsOf(sources) {
71
+ const launch = sources.launch;
72
+ const contexts = launch.declarations.filter((value) => value.kind === "defineContext");
73
+ if (contexts.length !== 1) {
74
+ throw new Error(`Launch requires exactly one default defineContext per application; found ${contexts.length}`);
75
+ }
76
+ const context = contexts[0];
77
+ if (context.call.arguments.length !== 1 || context.call.typeArguments?.length) {
78
+ fail(context.call, "defineContext requires exactly one factory");
79
+ }
80
+ const groups = [];
81
+ const owners = new Set();
82
+ for (const declaration of launch.declarations) {
83
+ if (declaration.kind !== "defineRpc") {
84
+ continue;
85
+ }
86
+ const owner = sources.declarations.find((route) => dirname(route.file) === dirname(declaration.file));
87
+ if (!owner || !owner.retained || owner.target) {
88
+ fail(declaration.call, "RPC requires a colocated retained ordinary route owner");
89
+ }
90
+ if (owners.has(owner)) {
91
+ fail(declaration.call, "Only one RPC group per route owner is supported");
92
+ }
93
+ owners.add(owner);
94
+ const call = directCall(declaration.call, "defineRpc");
95
+ const [namespace, methodsNode, options] = call.arguments;
96
+ if (call.arguments.length < 2 ||
97
+ call.arguments.length > 3 ||
98
+ !namespace ||
99
+ !ts.isStringLiteral(namespace) ||
100
+ !/^[A-Za-z_][A-Za-z0-9_]*$/.test(namespace.text) ||
101
+ !methodsNode) {
102
+ fail(call, "defineRpc requires a literal identifier namespace, inline methods and optional inline options");
103
+ }
104
+ if (namespace.text === "__proto__") {
105
+ fail(namespace, "RPC namespace '__proto__' is reserved");
106
+ }
107
+ if (options) {
108
+ const fields = properties(options, "RPC group options");
109
+ onlyKeys(fields, ["canActivate"], options);
110
+ guards(fields.get("canActivate"));
111
+ }
112
+ const methods = [];
113
+ for (const [name, value] of properties(methodsNode, "RPC methods")) {
114
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
115
+ fail(value, "RPC methods must be identifier names");
116
+ }
117
+ if (name === "__proto__") {
118
+ fail(value, "RPC procedure '__proto__' is reserved");
119
+ }
120
+ const procedure = directCall(value, "query/mutation");
121
+ let kind;
122
+ for (const candidate of ["query", "mutation"]) {
123
+ const imported = namedImport(value.getSourceFile(), procedure.expression, candidate);
124
+ if (imported && (await genuineImport(imported, launch.typeEntry, sources.parsed.options))) {
125
+ kind = candidate;
126
+ }
127
+ }
128
+ if (!kind) {
129
+ fail(procedure, "Procedure must directly call a genuine named query import or mutation import");
130
+ }
131
+ if (procedure.arguments.length !== 1) {
132
+ fail(procedure, `${kind} requires one inline options object`);
133
+ }
134
+ const fields = properties(procedure.arguments[0], "Procedure options");
135
+ onlyKeys(fields, ["handler", "input", "canActivate", "errors"], procedure);
136
+ if (!fields.has("handler")) {
137
+ fail(procedure, `${kind} requires handler`);
138
+ }
139
+ guards(fields.get("canActivate"));
140
+ methods.push({
141
+ name,
142
+ input: fields.has("input"),
143
+ kind,
144
+ errors: errorMetadata(fields.get("errors")),
145
+ call: procedure,
146
+ });
147
+ }
148
+ const identity = relative(dirname(sources.configFile), declaration.file).split(sep).join("/");
149
+ const id = createHash("sha256").update(`launch-v1\0${identity}`).digest("hex").slice(0, 24);
150
+ groups.push({ declaration, owner, namespace: namespace.text, id, methods });
151
+ }
152
+ return { context, groups };
153
+ }
154
+ function emitLaunch(sources, desired, context, groups, appId) {
155
+ const payloads = [];
156
+ function payloadImport(from, target, local, typeOnly = false) {
157
+ payloads.push({ from, target, local });
158
+ let keyword = "import";
159
+ if (typeOnly) {
160
+ keyword += " type";
161
+ }
162
+ return `${keyword} ${local} from ${JSON.stringify(specifier(from, target))};`;
163
+ }
164
+ const registration = resolve(sources.output, "context.generated.d.ts");
165
+ add(desired, registration, `${launchMarkers["context.generated.d.ts"]}\nimport type { ContextOf } from '@loozo/angular-launch/server';\n${payloadImport(registration, context.file, "context", true)}\ndeclare module '@loozo/angular-launch/server' { interface Register { context: ContextOf<typeof context>; } }\n`);
166
+ const registry = resolve(sources.output, "server.generated.ts");
167
+ const server = [
168
+ launchMarkers["server.generated.ts"],
169
+ payloadImport(registry, context.file, "context"),
170
+ `import { createRequestScope, handleRpc, provideLaunchServer } from '@loozo/angular-launch/server';`,
171
+ ];
172
+ for (let index = 0; index < groups.length; index += 1) {
173
+ server.push(payloadImport(registry, groups[index].declaration.file, `group${index}`));
174
+ }
175
+ server.push(`export const registry = { ${groups.map((group, index) => `${JSON.stringify(group.id)}: group${index}`).join(", ")} };`, `export const appBinding = { id: ${JSON.stringify(appId)}, context };`, `export const createContext = (request: Request) => createRequestScope(appBinding, request);`, `export const handleRequest = (request: Request) => handleRpc(registry, appBinding, request);`, `export const provideServer = () => provideLaunchServer(registry, appBinding);`, "");
176
+ add(desired, registry, server.join("\n"));
177
+ const byOwner = new Map(groups.map((group) => [group.owner, group]));
178
+ for (const owner of sources.declarations) {
179
+ if (!owner.retained) {
180
+ continue;
181
+ }
182
+ const available = [];
183
+ const namespaces = new Set();
184
+ let current = owner;
185
+ while (current) {
186
+ const group = byOwner.get(current);
187
+ if (group) {
188
+ if (namespaces.has(group.namespace)) {
189
+ fail(group.declaration.call, `Duplicate RPC namespace in ancestry: ${group.namespace}`);
190
+ }
191
+ namespaces.add(group.namespace);
192
+ available.unshift(group);
193
+ }
194
+ current = current.parent;
195
+ }
196
+ const file = resolve(dirname(owner.file), "rpc.generated.ts");
197
+ const lines = [
198
+ launchMarkers["rpc.generated.ts"],
199
+ `import { injectClient } from '@loozo/angular-launch/_generated';`,
200
+ `import type { Client } from '@loozo/angular-launch';`,
201
+ ];
202
+ const metadata = Object.create(null);
203
+ for (let index = 0; index < available.length; index += 1) {
204
+ const group = available[index];
205
+ lines.push(payloadImport(file, group.declaration.file, `group${index}`, true));
206
+ metadata[group.namespace] = {
207
+ id: group.id,
208
+ methods: group.methods.map(({ name, input, kind, errors }) => ({
209
+ name,
210
+ input,
211
+ kind,
212
+ errors,
213
+ })),
214
+ };
215
+ }
216
+ lines.push(`export type Rpc = { ${available.map((group, index) => `readonly ${JSON.stringify(group.namespace)}: Client<typeof group${index}>`).join("; ")} };`, `export function injectRpc(): Rpc { return injectClient(${JSON.stringify(metadata)} as const) as Rpc; }`, "");
217
+ add(desired, file, lines.join("\n"));
218
+ }
219
+ return payloads;
220
+ }
221
+ function unalias(checker, symbol) {
222
+ if (symbol && symbol.flags & ts.SymbolFlags.Alias) {
223
+ return checker.getAliasedSymbol(symbol);
224
+ }
225
+ return symbol;
226
+ }
227
+ async function validatePayloadImports(validation, payloads) {
228
+ const { program, host } = validation;
229
+ const checker = program.getTypeChecker();
230
+ for (const payload of payloads) {
231
+ const source = program.getSourceFile(payload.from);
232
+ const statement = source.statements.find((node) => ts.isImportDeclaration(node) && node.importClause?.name?.text === payload.local);
233
+ const name = statement.moduleSpecifier;
234
+ const resolved = ts.resolveModuleName(name.text, source.fileName, program.getCompilerOptions(), host, undefined, undefined, program.getModeForUsageLocation(source, name)).resolvedModule;
235
+ if (!resolved ||
236
+ (await realpath(resolved.resolvedFileName)) !== (await realpath(payload.target))) {
237
+ fail(statement, `Generated payload import must resolve to its discovered declaration: ${payload.target}`);
238
+ }
239
+ const target = program.getSourceFile(payload.target);
240
+ const module = checker.getSymbolAtLocation(target);
241
+ const expected = unalias(checker, checker.getExportsOfModule(module).find((symbol) => symbol.name === "default"));
242
+ const actual = unalias(checker, checker.getSymbolAtLocation(statement.importClause.name));
243
+ if (!expected?.declarations?.length ||
244
+ actual !== expected ||
245
+ expected.declarations.some((node) => node.getSourceFile() !== target)) {
246
+ fail(statement, "Generated payload import does not bind the discovered default declaration");
247
+ }
248
+ }
249
+ }
250
+ async function validateBindings(sources, validation, context, groups, compiler) {
251
+ const { program, host } = validation;
252
+ const checker = program.getTypeChecker();
253
+ const entryFile = sources.launch.typeEntry;
254
+ const canonicalOptions = {
255
+ ...sources.parsed.options,
256
+ paths: undefined,
257
+ baseUrl: undefined,
258
+ skipLibCheck: false,
259
+ };
260
+ const anchor = await (compiler?.launchAnchor ?? new AnchorState()).anchor(entryFile, ["defineContext", "defineRpc", "query", "mutation"], canonicalOptions);
261
+ const actualEntry = program.getSourceFile(entryFile);
262
+ const actualModule = checker.getSymbolAtLocation(actualEntry);
263
+ const expectedCalls = new Map();
264
+ function key(node) {
265
+ return `${node.getSourceFile().fileName}:${node.pos}`;
266
+ }
267
+ expectedCalls.set(key(context.call), "defineContext");
268
+ for (const group of groups) {
269
+ expectedCalls.set(key(group.declaration.call), "defineRpc");
270
+ for (const method of group.methods) {
271
+ expectedCalls.set(key(method.call), method.kind);
272
+ }
273
+ }
274
+ const promises = [];
275
+ for (const source of program.getSourceFiles()) {
276
+ if (!sources.parsed.fileNames.includes(source.fileName)) {
277
+ continue;
278
+ }
279
+ function visit(node) {
280
+ if (ts.isCallExpression(node)) {
281
+ const expected = expectedCalls.get(key(node));
282
+ let spelling;
283
+ const invoked = unalias(checker, checker.getSymbolAtLocation(node.expression));
284
+ for (const name of ["defineContext", "defineRpc", "query", "mutation"]) {
285
+ const exported = unalias(checker, checker.getExportsOfModule(actualModule).find((symbol) => symbol.name === name));
286
+ if (invoked && invoked === exported) {
287
+ spelling = name;
288
+ }
289
+ if (expected && namedImport(source, node.expression, name)) {
290
+ spelling = name;
291
+ }
292
+ }
293
+ if (expected || spelling) {
294
+ if (!expected || spelling !== expected) {
295
+ fail(node, "Launch factory calls must be default declarations or inline group procedures");
296
+ }
297
+ const imported = namedImport(source, node.expression, expected);
298
+ promises.push((async () => {
299
+ if (!(await genuineImport(imported, entryFile, sources.parsed.options, host))) {
300
+ fail(node, "Launch factory import provenance is not concrete");
301
+ }
302
+ const actual = unalias(checker, checker.getSymbolAtLocation(node.expression));
303
+ const exported = unalias(checker, checker.getExportsOfModule(actualModule).find((symbol) => symbol.name === expected));
304
+ const anchored = anchor.get(expected);
305
+ if (!actual?.declarations?.length ||
306
+ actual !== exported ||
307
+ actual.declarations.length !== anchored?.length) {
308
+ fail(node, "Launch factory binding is not the concrete canonical export");
309
+ }
310
+ for (let index = 0; index < actual.declarations.length; index += 1) {
311
+ const a = actual.declarations[index];
312
+ const b = anchored[index];
313
+ if ((await realpath(a.getSourceFile().fileName)) !== b.file ||
314
+ a.pos !== b.pos ||
315
+ a.end !== b.end ||
316
+ a.kind !== b.kind) {
317
+ fail(node, "Launch factory underlying declaration was redirected");
318
+ }
319
+ }
320
+ })());
321
+ }
322
+ }
323
+ ts.forEachChild(node, visit);
324
+ }
325
+ visit(source);
326
+ }
327
+ await Promise.all(promises);
328
+ for (const group of groups) {
329
+ const source = program.getSourceFile(group.declaration.file);
330
+ const assignment = source.statements.find(ts.isExportAssignment);
331
+ const call = assignment.expression;
332
+ for (const expression of properties(call.arguments[1], "RPC methods").values()) {
333
+ const procedure = expression;
334
+ const fields = properties(procedure.arguments[0], "Procedure options");
335
+ const input = fields.get("input");
336
+ if (input && hasNonConcreteSchemaBranch(checker.getTypeAtLocation(input))) {
337
+ fail(input, "Explicit query input must have a concrete Standard Schema type (also required for mutations)");
338
+ }
339
+ const errors = fields.get("errors");
340
+ if (errors) {
341
+ for (const value of properties(errors, "Declared RPC errors").values()) {
342
+ const data = properties(value, "Declared RPC error").get("data");
343
+ if (hasNonConcreteSchemaBranch(checker.getTypeAtLocation(data))) {
344
+ fail(data, "Declared error data must have a concrete Standard Schema type");
345
+ }
346
+ }
347
+ }
348
+ }
349
+ }
350
+ }
351
+ function moduleReferences(source) {
352
+ const references = [];
353
+ function visit(node) {
354
+ let specifier;
355
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
356
+ specifier = node.moduleSpecifier;
357
+ }
358
+ else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
359
+ specifier = node.arguments[0];
360
+ }
361
+ else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
362
+ specifier = node.argument.literal;
363
+ }
364
+ else if (ts.isImportEqualsDeclaration(node) &&
365
+ ts.isExternalModuleReference(node.moduleReference)) {
366
+ specifier = node.moduleReference.expression;
367
+ }
368
+ if (specifier && ts.isStringLiteralLike(specifier)) {
369
+ references.push(specifier);
370
+ }
371
+ ts.forEachChild(node, visit);
372
+ }
373
+ visit(source);
374
+ return references;
375
+ }
376
+ // Check generation's own domain before publication: generated outputs, discovered
377
+ // route/Launch declarations and application TypeScript files that directly import
378
+ // a generated output (import/export-from, import(), import types, import =). Other
379
+ // application files and dependencies are left to the application's own build.
380
+ function checkGeneratedDomain(sources, validation, generated) {
381
+ const { program, host } = validation;
382
+ const options = program.getCompilerOptions();
383
+ const selected = new Set(generated.keys());
384
+ for (const declaration of sources.declarations) {
385
+ selected.add(declaration.file);
386
+ }
387
+ for (const declaration of sources.launch.declarations) {
388
+ selected.add(declaration.file);
389
+ }
390
+ const cache = ts.createModuleResolutionCache(program.getCurrentDirectory(), (file) => host.getCanonicalFileName(file), options);
391
+ for (const source of program.getSourceFiles()) {
392
+ const file = resolve(source.fileName);
393
+ if (selected.has(file) ||
394
+ source.fileName.includes("/node_modules/") ||
395
+ program.isSourceFileFromExternalLibrary(source) ||
396
+ program.isSourceFileDefaultLibrary(source)) {
397
+ continue;
398
+ }
399
+ for (const specifier of moduleReferences(source)) {
400
+ const resolved = ts.resolveModuleName(specifier.text, source.fileName, options, host, cache, undefined, program.getModeForUsageLocation(source, specifier)).resolvedModule;
401
+ if (resolved && generated.has(resolve(resolved.resolvedFileName))) {
402
+ selected.add(file);
403
+ break;
404
+ }
405
+ }
406
+ }
407
+ const declarationEmit = options.declaration || options.composite;
408
+ const diagnostics = [...program.getOptionsDiagnostics()];
409
+ for (const file of selected) {
410
+ const source = program.getSourceFile(file);
411
+ diagnostics.push(...program.getSyntacticDiagnostics(source), ...program.getSemanticDiagnostics(source));
412
+ if (declarationEmit && !source.isDeclarationFile) {
413
+ diagnostics.push(...program.getDeclarationDiagnostics(source));
414
+ }
415
+ }
416
+ // Global diagnostics can surface while checking the selected files.
417
+ diagnostics.push(...program.getGlobalDiagnostics());
418
+ const unique = ts.sortAndDeduplicateDiagnostics(diagnostics);
419
+ if (unique.length > 0) {
420
+ throw new Error(ts.formatDiagnosticsWithColorAndContext(unique, {
421
+ getCanonicalFileName: (name) => name,
422
+ getCurrentDirectory: () => dirname(sources.configFile),
423
+ getNewLine: () => "\n",
424
+ }));
425
+ }
426
+ }
427
+ async function runGeneration(workspace, options, stopped, compiler) {
428
+ const root = fileURLToPath(new URL("../../", import.meta.url));
429
+ const manifest = JSON.parse(await readFile(resolve(root, "package.json"), "utf8"));
430
+ const typeEntry = await realpath(resolve(root, manifest.exports["./server"].types));
431
+ const application = await realpath(workspace);
432
+ function requireInside(file) {
433
+ const suffix = relative(application, file);
434
+ if (suffix === ".." || suffix.startsWith(`..${sep}`) || resolve(application, suffix) !== file) {
435
+ throw new Error(`Launch source/output escapes application workspace: ${file}`);
436
+ }
437
+ }
438
+ const config = resolve(application, options.tsconfig);
439
+ requireInside(config);
440
+ requireInside(resolve(application, options.outDirectory));
441
+ for (const directory of options.scanDirectories) {
442
+ requireInside(resolve(dirname(config), directory));
443
+ }
444
+ const { sources, desired } = await prepareLaunchRoutes(application, options, typeEntry, compiler?.discovery);
445
+ for (const file of sources.parsed.fileNames) {
446
+ requireInside(file);
447
+ }
448
+ // TS 6 defaults strict checking on, but each explicit false overrides it.
449
+ // Match its getStrictOptionValue rule without relying on an untyped internal API.
450
+ for (const flag of [
451
+ "noImplicitAny",
452
+ "strictNullChecks",
453
+ "strictFunctionTypes",
454
+ "strictBindCallApply",
455
+ "strictPropertyInitialization",
456
+ "strictBuiltinIteratorReturn",
457
+ "noImplicitThis",
458
+ "useUnknownInCatchVariables",
459
+ ]) {
460
+ const enabled = sources.parsed.options[flag] ?? sources.parsed.options.strict ?? true;
461
+ if (!enabled) {
462
+ throw new Error(`Launch generation requires effective strict TypeScript checking: ${flag} is disabled`);
463
+ }
464
+ }
465
+ if (sources.parsed.options.noCheck) {
466
+ throw new Error("Launch generation requires effective strict TypeScript checking: noCheck must be false");
467
+ }
468
+ const { context, groups } = await groupsOf(sources);
469
+ const appManifest = JSON.parse(await readFile(resolve(application, "package.json"), "utf8"));
470
+ if (typeof appManifest.name !== "string" || appManifest.name.length === 0) {
471
+ throw new Error("Launch application package.json requires a name for generated app identity");
472
+ }
473
+ const appId = createHash("sha256")
474
+ .update("launch-app-v1\0")
475
+ .update(appManifest.name)
476
+ .update("\0")
477
+ .update(relative(application, sources.configFile).split(sep).join("/"))
478
+ .update("\0")
479
+ .update(relative(application, context.file).split(sep).join("/"))
480
+ .update("\0")
481
+ .update(context.call.getSourceFile().text)
482
+ .digest("hex");
483
+ const payloads = emitLaunch(sources, desired, context, groups, appId);
484
+ await auditPath(sources.output);
485
+ const outputInventory = await walk(sources.output);
486
+ const globals = [
487
+ "routes.generated.ts",
488
+ "destinations.generated.ts",
489
+ "context.generated.d.ts",
490
+ "server.generated.ts",
491
+ ].map((name) => resolve(sources.output, name));
492
+ const plan = await planOutputs(desired, [...sources.encountered, ...outputInventory], globals, "router-and-launch");
493
+ const validation = createValidationProgram(sources, desired, plan.stale, compiler?.overlay);
494
+ await validateRoutes(sources, desired, validation, compiler?.routerAnchor);
495
+ await validatePayloadImports(validation, payloads);
496
+ await validateBindings(sources, validation, context, groups, compiler);
497
+ checkGeneratedDomain(sources, validation, desired);
498
+ publish(plan, options.check === true, stopped, new Map(), new Set());
499
+ }
500
+ export function generate(workspace, options, stopped = () => false) {
501
+ return runGeneration(workspace, options, stopped);
502
+ }
503
+ /** Owns compiler reuse for one explicitly sequenced application-generation lifetime. */
504
+ export function createGenerationSession(workspace, { tsconfig, scanDirectories, outDirectory }) {
505
+ const application = resolve(workspace);
506
+ const fixed = { tsconfig, scanDirectories: [...scanDirectories], outDirectory };
507
+ const compiler = {
508
+ discovery: new CompilerState(),
509
+ overlay: new CompilerState(),
510
+ routerAnchor: new AnchorState(),
511
+ launchAnchor: new AnchorState(),
512
+ };
513
+ let closed = false;
514
+ let active;
515
+ function clear() {
516
+ for (const slot of Object.values(compiler)) {
517
+ slot.clear();
518
+ }
519
+ }
520
+ return {
521
+ async generate({ check = false } = {}, stopped = () => false) {
522
+ if (closed) {
523
+ throw new Error("Generation session is disposed");
524
+ }
525
+ if (active) {
526
+ throw new Error("Generation session requires sequential calls");
527
+ }
528
+ let interrupted = false;
529
+ function isStopped() {
530
+ if (closed) {
531
+ interrupted = true;
532
+ return true;
533
+ }
534
+ const requested = stopped();
535
+ if (closed || requested) {
536
+ interrupted = true;
537
+ return true;
538
+ }
539
+ return false;
540
+ }
541
+ const work = runGeneration(application, { ...fixed, check }, isStopped, compiler);
542
+ active = work;
543
+ try {
544
+ await work;
545
+ }
546
+ catch (error) {
547
+ clear();
548
+ throw error;
549
+ }
550
+ finally {
551
+ active = undefined;
552
+ if (closed || interrupted) {
553
+ clear();
554
+ }
555
+ }
556
+ },
557
+ async dispose() {
558
+ closed = true;
559
+ await active?.catch(() => undefined);
560
+ clear();
561
+ },
562
+ };
563
+ }
package/dist/json.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export type Json = null | boolean | number | string | readonly Json[] | {
2
+ readonly [key: string]: Json;
3
+ };
4
+ export type JsonShape<Value> = Value extends null | boolean | number | string ? Value : Value extends (...args: never[]) => unknown ? never : Value extends readonly (infer Element)[] ? readonly JsonShape<Element>[] : Value extends object ? {
5
+ readonly [Key in keyof Value]-?: Key extends string | number ? JsonShape<Value[Key]> : never;
6
+ } : never;
7
+ export declare function serializeJson(value: unknown): string;