@loozo/angular-launch 0.0.0-stage → 0.0.2
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 +546 -2
- package/client.d.ts +232 -0
- package/client.js +169 -0
- package/generated.d.ts +13 -0
- package/generated.js +90 -0
- package/generation/index.d.ts +116 -0
- package/generation/index.js +634 -0
- package/index.d.ts +2 -0
- package/index.js +1 -0
- package/json.d.ts +13 -0
- package/json.js +48 -0
- package/package.json +48 -4
- package/server/backend.d.ts +58 -0
- package/server/backend.js +166 -0
- package/server/definitions.d.ts +486 -0
- package/server/definitions.js +170 -0
- package/server/dispatch.d.ts +140 -0
- package/server/dispatch.js +249 -0
- package/server/errors.d.ts +21 -0
- package/server/errors.js +32 -0
- package/server/generated.d.ts +2 -0
- package/server/generated.js +3 -0
- package/server/index.d.ts +6 -0
- package/server/index.js +2 -0
|
@@ -0,0 +1,634 @@
|
|
|
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
|
+
// The built package root (dist/ in the workspace, the tarball root when installed).
|
|
429
|
+
const root = fileURLToPath(new URL("../", import.meta.url));
|
|
430
|
+
const manifest = JSON.parse(await readFile(resolve(root, "package.json"), "utf8"));
|
|
431
|
+
const typeEntry = await realpath(resolve(root, manifest.exports["./server"].types));
|
|
432
|
+
const application = await realpath(workspace);
|
|
433
|
+
function requireInside(file) {
|
|
434
|
+
const suffix = relative(application, file);
|
|
435
|
+
if (suffix === ".." || suffix.startsWith(`..${sep}`) || resolve(application, suffix) !== file) {
|
|
436
|
+
throw new Error(`Launch source/output escapes application workspace: ${file}`);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
const config = resolve(application, options.tsconfig);
|
|
440
|
+
requireInside(config);
|
|
441
|
+
requireInside(resolve(application, options.outDirectory));
|
|
442
|
+
for (const directory of options.scanDirectories) {
|
|
443
|
+
requireInside(resolve(dirname(config), directory));
|
|
444
|
+
}
|
|
445
|
+
const { sources, desired } = await prepareLaunchRoutes(application, options, typeEntry, compiler?.discovery);
|
|
446
|
+
for (const file of sources.parsed.fileNames) {
|
|
447
|
+
requireInside(file);
|
|
448
|
+
}
|
|
449
|
+
// TS 6 defaults strict checking on, but each explicit false overrides it.
|
|
450
|
+
// Match its getStrictOptionValue rule without relying on an untyped internal API.
|
|
451
|
+
for (const flag of [
|
|
452
|
+
"noImplicitAny",
|
|
453
|
+
"strictNullChecks",
|
|
454
|
+
"strictFunctionTypes",
|
|
455
|
+
"strictBindCallApply",
|
|
456
|
+
"strictPropertyInitialization",
|
|
457
|
+
"strictBuiltinIteratorReturn",
|
|
458
|
+
"noImplicitThis",
|
|
459
|
+
"useUnknownInCatchVariables",
|
|
460
|
+
]) {
|
|
461
|
+
const enabled = sources.parsed.options[flag] ?? sources.parsed.options.strict ?? true;
|
|
462
|
+
if (!enabled) {
|
|
463
|
+
throw new Error(`Launch generation requires effective strict TypeScript checking: ${flag} is disabled`);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
if (sources.parsed.options.noCheck) {
|
|
467
|
+
throw new Error("Launch generation requires effective strict TypeScript checking: noCheck must be false");
|
|
468
|
+
}
|
|
469
|
+
const { context, groups } = await groupsOf(sources);
|
|
470
|
+
const appManifest = JSON.parse(await readFile(resolve(application, "package.json"), "utf8"));
|
|
471
|
+
if (typeof appManifest.name !== "string" || appManifest.name.length === 0) {
|
|
472
|
+
throw new Error("Launch application package.json requires a name for generated app identity");
|
|
473
|
+
}
|
|
474
|
+
const appId = createHash("sha256")
|
|
475
|
+
.update("launch-app-v1\0")
|
|
476
|
+
.update(appManifest.name)
|
|
477
|
+
.update("\0")
|
|
478
|
+
.update(relative(application, sources.configFile).split(sep).join("/"))
|
|
479
|
+
.update("\0")
|
|
480
|
+
.update(relative(application, context.file).split(sep).join("/"))
|
|
481
|
+
.update("\0")
|
|
482
|
+
.update(context.call.getSourceFile().text)
|
|
483
|
+
.digest("hex");
|
|
484
|
+
const payloads = emitLaunch(sources, desired, context, groups, appId);
|
|
485
|
+
await auditPath(sources.output);
|
|
486
|
+
const outputInventory = await walk(sources.output);
|
|
487
|
+
const globals = [
|
|
488
|
+
"routes.generated.ts",
|
|
489
|
+
"destinations.generated.ts",
|
|
490
|
+
"context.generated.d.ts",
|
|
491
|
+
"server.generated.ts",
|
|
492
|
+
].map((name) => resolve(sources.output, name));
|
|
493
|
+
const plan = await planOutputs(desired, [...sources.encountered, ...outputInventory], globals, "router-and-launch");
|
|
494
|
+
const validation = createValidationProgram(sources, desired, plan.stale, compiler?.overlay);
|
|
495
|
+
await validateRoutes(sources, desired, validation, compiler?.routerAnchor);
|
|
496
|
+
await validatePayloadImports(validation, payloads);
|
|
497
|
+
await validateBindings(sources, validation, context, groups, compiler);
|
|
498
|
+
checkGeneratedDomain(sources, validation, desired);
|
|
499
|
+
publish(plan, options.check === true, stopped, new Map(), new Set());
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Generates the router's and Launch's files for an application, or checks them.
|
|
503
|
+
*
|
|
504
|
+
* @remarks
|
|
505
|
+
* Node-only. Generation reads your sources without running them. Besides the router's
|
|
506
|
+
* files, it writes an `rpc.generated.ts` beside each route that gets a
|
|
507
|
+
* `route.generated.ts`, and `context.generated.d.ts` and `server.generated.ts` in the
|
|
508
|
+
* output directory. Run it before the Angular build.
|
|
509
|
+
*
|
|
510
|
+
* Everything is validated, including a type check of the generated files with
|
|
511
|
+
* `skipLibCheck: false`, before anything is written, so a failed run changes nothing.
|
|
512
|
+
* Files are then written one at a time without rollback; a write error partway through
|
|
513
|
+
* can leave some files updated, which the next successful run repairs. Generation only
|
|
514
|
+
* replaces or removes files carrying its ownership marker, and removes stale ones.
|
|
515
|
+
*
|
|
516
|
+
* @example
|
|
517
|
+
* ```js
|
|
518
|
+
* import { generate } from "@loozo/angular-launch/generation";
|
|
519
|
+
*
|
|
520
|
+
* await generate(import.meta.dirname, {
|
|
521
|
+
* tsconfig: "tsconfig.app.json",
|
|
522
|
+
* scanDirectories: ["src/routes"],
|
|
523
|
+
* outDirectory: "generated",
|
|
524
|
+
* check: process.argv.includes("--check"),
|
|
525
|
+
* });
|
|
526
|
+
* ```
|
|
527
|
+
*
|
|
528
|
+
* @param workspace - The absolute path of the application directory, which contains
|
|
529
|
+
* its `package.json`. The tsconfig, scanned directory, sources and output directory
|
|
530
|
+
* must all be inside it.
|
|
531
|
+
* @param options - The generation options.
|
|
532
|
+
* @param stopped - Called once just before writing; returning `true` skips writing and
|
|
533
|
+
* resolves. Defaults to never stopping.
|
|
534
|
+
* @returns A promise that resolves when generation finishes.
|
|
535
|
+
* @throws Rejects when a path escapes the workspace, the tsconfig disables strict
|
|
536
|
+
* checking or enables `noCheck`, the application's `package.json` has no `name`, the
|
|
537
|
+
* sources or generated files fail validation, a file to replace lacks the ownership
|
|
538
|
+
* marker, or, with `check`, a generated file is out of date.
|
|
539
|
+
*/
|
|
540
|
+
export function generate(workspace, options, stopped = () => false) {
|
|
541
|
+
return runGeneration(workspace, options, stopped);
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Creates a generation session that reuses compiler work between sequential calls.
|
|
545
|
+
*
|
|
546
|
+
* @remarks
|
|
547
|
+
* Node-only. For long-running tools that regenerate repeatedly, such as after file
|
|
548
|
+
* changes. A session doesn't watch files; you decide when to call `generate`. Edits
|
|
549
|
+
* inside the application are picked up by the next call. Create a new session after
|
|
550
|
+
* moving the application directory or changing dependencies. Don't run two sessions or
|
|
551
|
+
* generators against the same output at once.
|
|
552
|
+
*
|
|
553
|
+
* @example
|
|
554
|
+
* ```js
|
|
555
|
+
* const session = createGenerationSession(workspace, {
|
|
556
|
+
* tsconfig: "tsconfig.app.json",
|
|
557
|
+
* scanDirectories: ["src/routes"],
|
|
558
|
+
* outDirectory: "generated",
|
|
559
|
+
* });
|
|
560
|
+
*
|
|
561
|
+
* try {
|
|
562
|
+
* await session.generate();
|
|
563
|
+
* await session.generate({ check: true });
|
|
564
|
+
* } finally {
|
|
565
|
+
* await session.dispose();
|
|
566
|
+
* }
|
|
567
|
+
* ```
|
|
568
|
+
*
|
|
569
|
+
* @param workspace - The absolute path of the application directory, as for
|
|
570
|
+
* {@link generate}.
|
|
571
|
+
* @param options - The generation options, fixed for the session's lifetime; `check` is
|
|
572
|
+
* passed per call instead.
|
|
573
|
+
* @returns The session. Dispose it when done.
|
|
574
|
+
*/
|
|
575
|
+
export function createGenerationSession(workspace, { tsconfig, scanDirectories, outDirectory }) {
|
|
576
|
+
const application = resolve(workspace);
|
|
577
|
+
const fixed = { tsconfig, scanDirectories: [...scanDirectories], outDirectory };
|
|
578
|
+
const compiler = {
|
|
579
|
+
discovery: new CompilerState(),
|
|
580
|
+
overlay: new CompilerState(),
|
|
581
|
+
routerAnchor: new AnchorState(),
|
|
582
|
+
launchAnchor: new AnchorState(),
|
|
583
|
+
};
|
|
584
|
+
let closed = false;
|
|
585
|
+
let active;
|
|
586
|
+
function clear() {
|
|
587
|
+
for (const slot of Object.values(compiler)) {
|
|
588
|
+
slot.clear();
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
return {
|
|
592
|
+
async generate({ check = false } = {}, stopped = () => false) {
|
|
593
|
+
if (closed) {
|
|
594
|
+
throw new Error("Generation session is disposed");
|
|
595
|
+
}
|
|
596
|
+
if (active) {
|
|
597
|
+
throw new Error("Generation session requires sequential calls");
|
|
598
|
+
}
|
|
599
|
+
let interrupted = false;
|
|
600
|
+
function isStopped() {
|
|
601
|
+
if (closed) {
|
|
602
|
+
interrupted = true;
|
|
603
|
+
return true;
|
|
604
|
+
}
|
|
605
|
+
const requested = stopped();
|
|
606
|
+
if (closed || requested) {
|
|
607
|
+
interrupted = true;
|
|
608
|
+
return true;
|
|
609
|
+
}
|
|
610
|
+
return false;
|
|
611
|
+
}
|
|
612
|
+
const work = runGeneration(application, { ...fixed, check }, isStopped, compiler);
|
|
613
|
+
active = work;
|
|
614
|
+
try {
|
|
615
|
+
await work;
|
|
616
|
+
}
|
|
617
|
+
catch (error) {
|
|
618
|
+
clear();
|
|
619
|
+
throw error;
|
|
620
|
+
}
|
|
621
|
+
finally {
|
|
622
|
+
active = undefined;
|
|
623
|
+
if (closed || interrupted) {
|
|
624
|
+
clear();
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
},
|
|
628
|
+
async dispose() {
|
|
629
|
+
closed = true;
|
|
630
|
+
await active?.catch(() => undefined);
|
|
631
|
+
clear();
|
|
632
|
+
},
|
|
633
|
+
};
|
|
634
|
+
}
|
package/index.d.ts
ADDED
package/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { RpcError, frameworkFailures } from "./client.js";
|
package/json.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The strict JSON shape of `Value`: `never` wherever `Value` isn't strict JSON.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* Procedure inputs, results and error data must satisfy it. Functions become `never`;
|
|
6
|
+
* arrays and objects are checked element by element.
|
|
7
|
+
*
|
|
8
|
+
* @typeParam Value - The type to check.
|
|
9
|
+
*/
|
|
10
|
+
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 ? {
|
|
11
|
+
readonly [Key in keyof Value]-?: Key extends string | number ? JsonShape<Value[Key]> : never;
|
|
12
|
+
} : never;
|
|
13
|
+
export declare function serializeJson(value: unknown): string;
|