@loozo/angular-launch 0.0.5 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1068 -187
- package/builders/application.js +32 -3
- package/builders/channel-forwarding.d.ts +15 -0
- package/builders/channel-forwarding.js +61 -0
- package/builders/options.d.ts +6 -2
- package/builders/options.js +16 -5
- package/builders/serve.js +198 -140
- package/channel.d.ts +55 -0
- package/channel.js +232 -0
- package/client.d.ts +63 -33
- package/connect.d.ts +201 -0
- package/connect.js +148 -0
- package/generation/index.d.ts +2 -123
- package/generation/index.js +3 -669
- package/generation/redirects.d.ts +14 -0
- package/generation/redirects.js +43 -0
- package/generation/run.d.ts +168 -0
- package/generation/run.js +659 -0
- package/index.d.ts +8 -1
- package/index.js +3 -0
- package/json.d.ts +9 -0
- package/json.js +24 -0
- package/launch-queries.d.ts +16 -0
- package/launch-queries.js +3 -0
- package/navigation.d.ts +36 -0
- package/navigation.js +47 -0
- package/node/index.d.ts +60 -0
- package/node/index.js +178 -0
- package/node/upgrade-listener-slot.d.ts +1 -0
- package/node/upgrade-listener-slot.js +4 -0
- package/outcomes.d.ts +71 -0
- package/outcomes.js +146 -0
- package/package.json +21 -11
- package/redirect-translation.d.ts +53 -0
- package/redirect-translation.js +141 -0
- package/{generated.d.ts → remote-client.d.ts} +1 -1
- package/remote-client.js +179 -0
- package/route-types.d.ts +130 -0
- package/route-types.js +1 -0
- package/route.d.ts +45 -0
- package/route.js +113 -0
- package/schemas/application.json +19 -3
- package/schemas/serve.json +3 -3
- package/server/application.d.ts +107 -0
- package/server/application.js +108 -0
- package/server/backend.d.ts +62 -31
- package/server/backend.js +149 -55
- package/server/channel-messages.d.ts +54 -0
- package/server/channel-messages.js +84 -0
- package/server/channel-socket.d.ts +67 -0
- package/server/channel-socket.js +322 -0
- package/server/definitions.d.ts +270 -294
- package/server/definitions.js +35 -115
- package/server/dispatch.d.ts +121 -66
- package/server/dispatch.js +267 -87
- package/server/event-stream.d.ts +63 -0
- package/server/event-stream.js +173 -0
- package/server/generated.d.ts +3 -1
- package/server/generated.js +3 -1
- package/server/index.d.ts +6 -3
- package/server/index.js +3 -2
- package/server/outcomes.d.ts +64 -2
- package/server/outcomes.js +85 -4
- package/server/read-cookies.d.ts +19 -0
- package/server/read-cookies.js +39 -0
- package/server/response-effects.d.ts +105 -0
- package/server/response-effects.js +78 -0
- package/server/stages.d.ts +62 -0
- package/server/stages.js +51 -0
- package/server/upgrade.d.ts +57 -0
- package/server/upgrade.js +116 -0
- package/source-text.d.ts +1 -0
- package/source-text.js +56 -0
- package/stream.d.ts +34 -0
- package/stream.js +161 -0
- package/tanstack-query/README.md +113 -21
- package/tanstack-query/create-queries.d.ts +2 -0
- package/tanstack-query/{generated.js → create-queries.js} +13 -11
- package/tanstack-query/hydration-window.d.ts +11 -0
- package/tanstack-query/hydration-window.js +9 -0
- package/tanstack-query/hydration.d.ts +4 -14
- package/tanstack-query/hydration.js +9 -12
- package/tanstack-query/index.d.ts +1 -1
- package/tanstack-query/queries.d.ts +50 -33
- package/testing/call-procedure.d.ts +154 -0
- package/testing/call-procedure.js +97 -0
- package/testing/index.d.ts +2 -0
- package/testing/index.js +1 -0
- package/generated.js +0 -90
- package/generation/context-file.d.ts +0 -2
- package/generation/context-file.js +0 -3
- package/tanstack-query/generated.d.ts +0 -5
package/generation/index.js
CHANGED
|
@@ -1,669 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
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
|
-
import { contextFiles } from "./context-file.js";
|
|
9
|
-
function directCall(node, label) {
|
|
10
|
-
if (!ts.isCallExpression(node) || node.typeArguments?.length) {
|
|
11
|
-
fail(node, `${label} requires a direct nongeneric factory call`);
|
|
12
|
-
}
|
|
13
|
-
return node;
|
|
14
|
-
}
|
|
15
|
-
const builderShape = "defineRpc requires an arrow function destructuring query and/or mutation, returning a parenthesized object of procedures";
|
|
16
|
-
// `({ query, mutation }) => ({ ... })`: the builder names it binds and its procedures.
|
|
17
|
-
function builderCallback(node) {
|
|
18
|
-
if (!ts.isArrowFunction(node) ||
|
|
19
|
-
node.modifiers?.length ||
|
|
20
|
-
node.typeParameters?.length ||
|
|
21
|
-
node.type ||
|
|
22
|
-
node.parameters.length !== 1) {
|
|
23
|
-
fail(node, builderShape);
|
|
24
|
-
}
|
|
25
|
-
const [parameter] = node.parameters;
|
|
26
|
-
if (!ts.isObjectBindingPattern(parameter.name) ||
|
|
27
|
-
parameter.type ||
|
|
28
|
-
parameter.initializer ||
|
|
29
|
-
parameter.dotDotDotToken) {
|
|
30
|
-
fail(parameter, builderShape);
|
|
31
|
-
}
|
|
32
|
-
const bound = new Set();
|
|
33
|
-
for (const element of parameter.name.elements) {
|
|
34
|
-
if (element.propertyName ||
|
|
35
|
-
element.initializer ||
|
|
36
|
-
element.dotDotDotToken ||
|
|
37
|
-
!ts.isIdentifier(element.name) ||
|
|
38
|
-
(element.name.text !== "query" && element.name.text !== "mutation") ||
|
|
39
|
-
bound.has(element.name.text)) {
|
|
40
|
-
fail(element, "defineRpc's callback may only destructure query and mutation, without renaming");
|
|
41
|
-
}
|
|
42
|
-
bound.add(element.name.text);
|
|
43
|
-
}
|
|
44
|
-
if (!ts.isParenthesizedExpression(node.body)) {
|
|
45
|
-
fail(node.body, builderShape);
|
|
46
|
-
}
|
|
47
|
-
return { bound, procedures: properties(node.body.expression, "RPC procedures") };
|
|
48
|
-
}
|
|
49
|
-
function onlyKeys(fields, allowed, node) {
|
|
50
|
-
for (const key of fields.keys()) {
|
|
51
|
-
if (!allowed.includes(key)) {
|
|
52
|
-
fail(node, `Unsupported Launch option: ${key}`);
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
function errorMetadata(node) {
|
|
57
|
-
const result = [];
|
|
58
|
-
if (!node) {
|
|
59
|
-
return result;
|
|
60
|
-
}
|
|
61
|
-
for (const [code, value] of properties(node, "Declared RPC errors")) {
|
|
62
|
-
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(code) ||
|
|
63
|
-
code === "__proto__" ||
|
|
64
|
-
Object.hasOwn(frameworkFailures, code)) {
|
|
65
|
-
fail(value, `Invalid or reserved declared RPC error code: ${code}`);
|
|
66
|
-
}
|
|
67
|
-
const fields = properties(value, "Declared RPC error");
|
|
68
|
-
onlyKeys(fields, ["status", "message", "data"], value);
|
|
69
|
-
const status = fields.get("status");
|
|
70
|
-
const message = fields.get("message");
|
|
71
|
-
if (!status ||
|
|
72
|
-
!ts.isNumericLiteral(status) ||
|
|
73
|
-
!Number.isInteger(Number(status.text)) ||
|
|
74
|
-
Number(status.text) < 400 ||
|
|
75
|
-
Number(status.text) > 599 ||
|
|
76
|
-
!message ||
|
|
77
|
-
!ts.isStringLiteral(message) ||
|
|
78
|
-
message.text.length === 0 ||
|
|
79
|
-
!fields.has("data")) {
|
|
80
|
-
fail(value, "Declared errors require literal integer status 400–599, nonempty message and data schema");
|
|
81
|
-
}
|
|
82
|
-
result.push({ code, status: Number(status.text), message: message.text });
|
|
83
|
-
}
|
|
84
|
-
return result;
|
|
85
|
-
}
|
|
86
|
-
function hasNonConcreteSchemaBranch(type) {
|
|
87
|
-
if (type.isUnion()) {
|
|
88
|
-
return type.types.some(hasNonConcreteSchemaBranch);
|
|
89
|
-
}
|
|
90
|
-
return ((type.flags &
|
|
91
|
-
(ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !==
|
|
92
|
-
0);
|
|
93
|
-
}
|
|
94
|
-
function add(desired, path, text) {
|
|
95
|
-
if (desired.has(path)) {
|
|
96
|
-
throw new Error(`Duplicate desired output path: ${path}`);
|
|
97
|
-
}
|
|
98
|
-
desired.set(path, text);
|
|
99
|
-
}
|
|
100
|
-
async function groupsOf(sources) {
|
|
101
|
-
const launch = sources.launch;
|
|
102
|
-
const contexts = launch.declarations.filter((value) => value.kind === "defineContext");
|
|
103
|
-
if (contexts.length !== 1) {
|
|
104
|
-
throw new Error(`Launch requires exactly one default defineContext per application; found ${contexts.length}`);
|
|
105
|
-
}
|
|
106
|
-
const context = contexts[0];
|
|
107
|
-
if (context.call.arguments.length !== 1 || context.call.typeArguments?.length) {
|
|
108
|
-
fail(context.call, "defineContext requires exactly one factory");
|
|
109
|
-
}
|
|
110
|
-
const groups = [];
|
|
111
|
-
const owners = new Set();
|
|
112
|
-
const namespaces = new Map();
|
|
113
|
-
for (const declaration of launch.declarations) {
|
|
114
|
-
if (declaration.kind !== "defineRpc") {
|
|
115
|
-
continue;
|
|
116
|
-
}
|
|
117
|
-
const owner = sources.declarations.find((route) => dirname(route.file) === dirname(declaration.file));
|
|
118
|
-
if (!owner || !owner.retained || owner.target) {
|
|
119
|
-
fail(declaration.call, "RPC requires a colocated retained ordinary route owner");
|
|
120
|
-
}
|
|
121
|
-
if (owners.has(owner)) {
|
|
122
|
-
fail(declaration.call, "Only one RPC group per route owner is supported");
|
|
123
|
-
}
|
|
124
|
-
owners.add(owner);
|
|
125
|
-
const call = directCall(declaration.call, "defineRpc");
|
|
126
|
-
const [namespace, build, options] = call.arguments;
|
|
127
|
-
if (call.arguments.length < 2 ||
|
|
128
|
-
call.arguments.length > 3 ||
|
|
129
|
-
!namespace ||
|
|
130
|
-
!ts.isStringLiteral(namespace) ||
|
|
131
|
-
!/^[A-Za-z_][A-Za-z0-9_]*$/.test(namespace.text) ||
|
|
132
|
-
!build) {
|
|
133
|
-
fail(call, "defineRpc requires a literal identifier namespace, a procedure callback and optional inline options");
|
|
134
|
-
}
|
|
135
|
-
if (namespace.text === "__proto__") {
|
|
136
|
-
fail(namespace, "RPC namespace '__proto__' is reserved");
|
|
137
|
-
}
|
|
138
|
-
const previous = namespaces.get(namespace.text);
|
|
139
|
-
if (previous) {
|
|
140
|
-
fail(namespace, `Duplicate RPC namespace: ${namespace.text}; also defined in ${previous.file}`);
|
|
141
|
-
}
|
|
142
|
-
namespaces.set(namespace.text, declaration);
|
|
143
|
-
if (options) {
|
|
144
|
-
const fields = properties(options, "RPC group options");
|
|
145
|
-
onlyKeys(fields, ["use"], options);
|
|
146
|
-
}
|
|
147
|
-
const { bound, procedures } = builderCallback(build);
|
|
148
|
-
const methods = [];
|
|
149
|
-
for (const [name, value] of procedures) {
|
|
150
|
-
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
151
|
-
fail(value, "RPC methods must be identifier names");
|
|
152
|
-
}
|
|
153
|
-
if (name === "__proto__") {
|
|
154
|
-
fail(value, "RPC procedure '__proto__' is reserved");
|
|
155
|
-
}
|
|
156
|
-
const procedure = directCall(value, "query/mutation");
|
|
157
|
-
// The callback's own binding: its body is an object literal, so nothing can shadow it.
|
|
158
|
-
if (!ts.isIdentifier(procedure.expression) || !bound.has(procedure.expression.text)) {
|
|
159
|
-
fail(procedure, "Procedure must directly call the callback's query or mutation");
|
|
160
|
-
}
|
|
161
|
-
const kind = procedure.expression.text;
|
|
162
|
-
if (procedure.arguments.length !== 1) {
|
|
163
|
-
fail(procedure, `${kind} requires one inline options object`);
|
|
164
|
-
}
|
|
165
|
-
const fields = properties(procedure.arguments[0], "Procedure options");
|
|
166
|
-
onlyKeys(fields, ["handler", "input", "use", "errors"], procedure);
|
|
167
|
-
if (!fields.has("handler")) {
|
|
168
|
-
fail(procedure, `${kind} requires handler`);
|
|
169
|
-
}
|
|
170
|
-
methods.push({
|
|
171
|
-
name,
|
|
172
|
-
input: fields.has("input"),
|
|
173
|
-
kind,
|
|
174
|
-
errors: errorMetadata(fields.get("errors")),
|
|
175
|
-
});
|
|
176
|
-
}
|
|
177
|
-
groups.push({ declaration, owner, namespace: namespace.text, methods });
|
|
178
|
-
}
|
|
179
|
-
return { context, groups };
|
|
180
|
-
}
|
|
181
|
-
function emitLaunch(sources, desired, context, groups, appId, tanstackQuery) {
|
|
182
|
-
const payloads = [];
|
|
183
|
-
function payloadImport(from, target, local, typeOnly = false) {
|
|
184
|
-
payloads.push({ from, target, local });
|
|
185
|
-
let keyword = "import";
|
|
186
|
-
if (typeOnly) {
|
|
187
|
-
keyword += " type";
|
|
188
|
-
}
|
|
189
|
-
return `${keyword} ${local} from ${JSON.stringify(specifier(from, target))};`;
|
|
190
|
-
}
|
|
191
|
-
const registration = resolve(sources.output, "context.generated.d.ts");
|
|
192
|
-
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`);
|
|
193
|
-
const registry = resolve(sources.output, "server.generated.ts");
|
|
194
|
-
const server = [
|
|
195
|
-
launchMarkers["server.generated.ts"],
|
|
196
|
-
payloadImport(registry, context.file, "context"),
|
|
197
|
-
`import type { HandleOptions } from '@loozo/angular-launch/server';`,
|
|
198
|
-
`import { createRequestScope, handleRpc, provideLaunchServer } from '@loozo/angular-launch/_server';`,
|
|
199
|
-
];
|
|
200
|
-
for (let index = 0; index < groups.length; index += 1) {
|
|
201
|
-
server.push(payloadImport(registry, groups[index].declaration.file, `group${index}`));
|
|
202
|
-
}
|
|
203
|
-
server.push(`export const registry = { ${groups.map((group, index) => `${JSON.stringify(group.namespace)}: group${index}`).join(", ")} };`, `export const appBinding = { id: ${JSON.stringify(appId)}, context };`, `export const createContext = (request: Request) => createRequestScope(appBinding, request);`, `export const handleRequest = (request: Request, options: HandleOptions) => handleRpc(registry, appBinding, request, options);`, `export const provideServer = () => provideLaunchServer(registry, appBinding);`, "");
|
|
204
|
-
add(desired, registry, server.join("\n"));
|
|
205
|
-
const byOwner = new Map(groups.map((group) => [group.owner, group]));
|
|
206
|
-
for (const owner of sources.declarations) {
|
|
207
|
-
if (!owner.retained) {
|
|
208
|
-
continue;
|
|
209
|
-
}
|
|
210
|
-
const available = [];
|
|
211
|
-
let current = owner;
|
|
212
|
-
while (current) {
|
|
213
|
-
const group = byOwner.get(current);
|
|
214
|
-
if (group) {
|
|
215
|
-
available.unshift(group);
|
|
216
|
-
}
|
|
217
|
-
current = current.parent;
|
|
218
|
-
}
|
|
219
|
-
const file = resolve(dirname(owner.file), "rpc.generated.ts");
|
|
220
|
-
const lines = [
|
|
221
|
-
launchMarkers["rpc.generated.ts"],
|
|
222
|
-
`import { injectClient } from '@loozo/angular-launch/_generated';`,
|
|
223
|
-
`import type { Client } from '@loozo/angular-launch';`,
|
|
224
|
-
];
|
|
225
|
-
if (tanstackQuery) {
|
|
226
|
-
lines.push(`import { createQueries } from '@loozo/angular-launch/_tanstack-query';`, `import type { RpcQueries } from '@loozo/angular-launch/tanstack-query';`);
|
|
227
|
-
}
|
|
228
|
-
const metadata = Object.create(null);
|
|
229
|
-
const queriesMetadata = Object.create(null);
|
|
230
|
-
for (let index = 0; index < available.length; index += 1) {
|
|
231
|
-
const group = available[index];
|
|
232
|
-
lines.push(payloadImport(file, group.declaration.file, `group${index}`, true));
|
|
233
|
-
metadata[group.namespace] = {
|
|
234
|
-
methods: group.methods.map(({ name, input, kind, errors }) => ({
|
|
235
|
-
name,
|
|
236
|
-
input,
|
|
237
|
-
kind,
|
|
238
|
-
errors,
|
|
239
|
-
})),
|
|
240
|
-
};
|
|
241
|
-
queriesMetadata[group.namespace] = Object.create(null);
|
|
242
|
-
for (const { name, kind, input } of group.methods) {
|
|
243
|
-
queriesMetadata[group.namespace][name] = { kind, input };
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
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; }`);
|
|
247
|
-
if (tanstackQuery) {
|
|
248
|
-
lines.push(`export type Queries = { ${available.map((group, index) => `readonly ${JSON.stringify(group.namespace)}: RpcQueries<typeof group${index}>`).join("; ")} };`, `export function injectQueries(): Queries { return createQueries(injectRpc(), ${JSON.stringify(queriesMetadata)} as const) as Queries; }`);
|
|
249
|
-
}
|
|
250
|
-
lines.push("");
|
|
251
|
-
add(desired, file, lines.join("\n"));
|
|
252
|
-
}
|
|
253
|
-
return payloads;
|
|
254
|
-
}
|
|
255
|
-
function unalias(checker, symbol) {
|
|
256
|
-
if (symbol && symbol.flags & ts.SymbolFlags.Alias) {
|
|
257
|
-
return checker.getAliasedSymbol(symbol);
|
|
258
|
-
}
|
|
259
|
-
return symbol;
|
|
260
|
-
}
|
|
261
|
-
async function validatePayloadImports(validation, payloads) {
|
|
262
|
-
const { program, host } = validation;
|
|
263
|
-
const checker = program.getTypeChecker();
|
|
264
|
-
for (const payload of payloads) {
|
|
265
|
-
const source = program.getSourceFile(payload.from);
|
|
266
|
-
const statement = source.statements.find((node) => ts.isImportDeclaration(node) && node.importClause?.name?.text === payload.local);
|
|
267
|
-
const name = statement.moduleSpecifier;
|
|
268
|
-
const resolved = ts.resolveModuleName(name.text, source.fileName, program.getCompilerOptions(), host, undefined, undefined, program.getModeForUsageLocation(source, name)).resolvedModule;
|
|
269
|
-
if (!resolved ||
|
|
270
|
-
(await realpath(resolved.resolvedFileName)) !== (await realpath(payload.target))) {
|
|
271
|
-
fail(statement, `Generated payload import must resolve to its discovered declaration: ${payload.target}`);
|
|
272
|
-
}
|
|
273
|
-
const target = program.getSourceFile(payload.target);
|
|
274
|
-
const module = checker.getSymbolAtLocation(target);
|
|
275
|
-
const expected = unalias(checker, checker.getExportsOfModule(module).find((symbol) => symbol.name === "default"));
|
|
276
|
-
const actual = unalias(checker, checker.getSymbolAtLocation(statement.importClause.name));
|
|
277
|
-
if (!expected?.declarations?.length ||
|
|
278
|
-
actual !== expected ||
|
|
279
|
-
expected.declarations.some((node) => node.getSourceFile() !== target)) {
|
|
280
|
-
fail(statement, "Generated payload import does not bind the discovered default declaration");
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
async function validateBindings(sources, validation, context, groups, compiler) {
|
|
285
|
-
const { program, host } = validation;
|
|
286
|
-
const checker = program.getTypeChecker();
|
|
287
|
-
const entryFile = sources.launch.typeEntry;
|
|
288
|
-
const canonicalOptions = {
|
|
289
|
-
...sources.parsed.options,
|
|
290
|
-
paths: undefined,
|
|
291
|
-
baseUrl: undefined,
|
|
292
|
-
skipLibCheck: false,
|
|
293
|
-
};
|
|
294
|
-
const anchor = await (compiler?.launchAnchor ?? new AnchorState()).anchor(entryFile, ["defineContext", "defineRpc"], canonicalOptions);
|
|
295
|
-
const actualEntry = program.getSourceFile(entryFile);
|
|
296
|
-
const actualModule = checker.getSymbolAtLocation(actualEntry);
|
|
297
|
-
const expectedCalls = new Map();
|
|
298
|
-
function key(node) {
|
|
299
|
-
return `${node.getSourceFile().fileName}:${node.pos}`;
|
|
300
|
-
}
|
|
301
|
-
expectedCalls.set(key(context.call), "defineContext");
|
|
302
|
-
for (const group of groups) {
|
|
303
|
-
expectedCalls.set(key(group.declaration.call), "defineRpc");
|
|
304
|
-
}
|
|
305
|
-
const promises = [];
|
|
306
|
-
for (const source of program.getSourceFiles()) {
|
|
307
|
-
if (!sources.parsed.fileNames.includes(source.fileName)) {
|
|
308
|
-
continue;
|
|
309
|
-
}
|
|
310
|
-
function visit(node) {
|
|
311
|
-
if (ts.isCallExpression(node)) {
|
|
312
|
-
const expected = expectedCalls.get(key(node));
|
|
313
|
-
let spelling;
|
|
314
|
-
const invoked = unalias(checker, checker.getSymbolAtLocation(node.expression));
|
|
315
|
-
for (const name of ["defineContext", "defineRpc"]) {
|
|
316
|
-
const exported = unalias(checker, checker.getExportsOfModule(actualModule).find((symbol) => symbol.name === name));
|
|
317
|
-
if (invoked && invoked === exported) {
|
|
318
|
-
spelling = name;
|
|
319
|
-
}
|
|
320
|
-
if (expected && namedImport(source, node.expression, name)) {
|
|
321
|
-
spelling = name;
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
if (expected || spelling) {
|
|
325
|
-
if (!expected || spelling !== expected) {
|
|
326
|
-
fail(node, "defineContext and defineRpc calls must be default declarations");
|
|
327
|
-
}
|
|
328
|
-
const imported = namedImport(source, node.expression, expected);
|
|
329
|
-
promises.push((async () => {
|
|
330
|
-
if (!(await genuineImport(imported, entryFile, sources.parsed.options, host))) {
|
|
331
|
-
fail(node, "Launch factory import provenance is not concrete");
|
|
332
|
-
}
|
|
333
|
-
const actual = unalias(checker, checker.getSymbolAtLocation(node.expression));
|
|
334
|
-
const exported = unalias(checker, checker.getExportsOfModule(actualModule).find((symbol) => symbol.name === expected));
|
|
335
|
-
const anchored = anchor.get(expected);
|
|
336
|
-
if (!actual?.declarations?.length ||
|
|
337
|
-
actual !== exported ||
|
|
338
|
-
actual.declarations.length !== anchored?.length) {
|
|
339
|
-
fail(node, "Launch factory binding is not the concrete canonical export");
|
|
340
|
-
}
|
|
341
|
-
for (let index = 0; index < actual.declarations.length; index += 1) {
|
|
342
|
-
const a = actual.declarations[index];
|
|
343
|
-
const b = anchored[index];
|
|
344
|
-
if ((await realpath(a.getSourceFile().fileName)) !== b.file ||
|
|
345
|
-
a.pos !== b.pos ||
|
|
346
|
-
a.end !== b.end ||
|
|
347
|
-
a.kind !== b.kind) {
|
|
348
|
-
fail(node, "Launch factory underlying declaration was redirected");
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
})());
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
ts.forEachChild(node, visit);
|
|
355
|
-
}
|
|
356
|
-
visit(source);
|
|
357
|
-
}
|
|
358
|
-
await Promise.all(promises);
|
|
359
|
-
for (const group of groups) {
|
|
360
|
-
const source = program.getSourceFile(group.declaration.file);
|
|
361
|
-
const assignment = source.statements.find(ts.isExportAssignment);
|
|
362
|
-
const call = assignment.expression;
|
|
363
|
-
for (const expression of builderCallback(call.arguments[1]).procedures.values()) {
|
|
364
|
-
const procedure = expression;
|
|
365
|
-
const fields = properties(procedure.arguments[0], "Procedure options");
|
|
366
|
-
const input = fields.get("input");
|
|
367
|
-
if (input && hasNonConcreteSchemaBranch(checker.getTypeAtLocation(input))) {
|
|
368
|
-
fail(input, "Explicit query input must have a concrete Standard Schema type (also required for mutations)");
|
|
369
|
-
}
|
|
370
|
-
const errors = fields.get("errors");
|
|
371
|
-
if (errors) {
|
|
372
|
-
for (const value of properties(errors, "Declared RPC errors").values()) {
|
|
373
|
-
const data = properties(value, "Declared RPC error").get("data");
|
|
374
|
-
if (hasNonConcreteSchemaBranch(checker.getTypeAtLocation(data))) {
|
|
375
|
-
fail(data, "Declared error data must have a concrete Standard Schema type");
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
function moduleReferences(source) {
|
|
383
|
-
const references = [];
|
|
384
|
-
function visit(node) {
|
|
385
|
-
let specifier;
|
|
386
|
-
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
|
|
387
|
-
specifier = node.moduleSpecifier;
|
|
388
|
-
}
|
|
389
|
-
else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
|
|
390
|
-
specifier = node.arguments[0];
|
|
391
|
-
}
|
|
392
|
-
else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
|
|
393
|
-
specifier = node.argument.literal;
|
|
394
|
-
}
|
|
395
|
-
else if (ts.isImportEqualsDeclaration(node) &&
|
|
396
|
-
ts.isExternalModuleReference(node.moduleReference)) {
|
|
397
|
-
specifier = node.moduleReference.expression;
|
|
398
|
-
}
|
|
399
|
-
if (specifier && ts.isStringLiteralLike(specifier)) {
|
|
400
|
-
references.push(specifier);
|
|
401
|
-
}
|
|
402
|
-
ts.forEachChild(node, visit);
|
|
403
|
-
}
|
|
404
|
-
visit(source);
|
|
405
|
-
return references;
|
|
406
|
-
}
|
|
407
|
-
// Check generation's own domain before publication: generated outputs, discovered
|
|
408
|
-
// route/Launch declarations and application TypeScript files that directly import
|
|
409
|
-
// a generated output (import/export-from, import(), import types, import =). Other
|
|
410
|
-
// application files and dependencies are left to the application's own build.
|
|
411
|
-
function checkGeneratedDomain(sources, validation, generated) {
|
|
412
|
-
const { program, host } = validation;
|
|
413
|
-
const options = program.getCompilerOptions();
|
|
414
|
-
const selected = new Set(generated.keys());
|
|
415
|
-
for (const declaration of sources.declarations) {
|
|
416
|
-
selected.add(declaration.file);
|
|
417
|
-
}
|
|
418
|
-
for (const declaration of sources.launch.declarations) {
|
|
419
|
-
selected.add(declaration.file);
|
|
420
|
-
}
|
|
421
|
-
const cache = ts.createModuleResolutionCache(program.getCurrentDirectory(), (file) => host.getCanonicalFileName(file), options);
|
|
422
|
-
for (const source of program.getSourceFiles()) {
|
|
423
|
-
const file = resolve(source.fileName);
|
|
424
|
-
if (selected.has(file) ||
|
|
425
|
-
source.fileName.includes("/node_modules/") ||
|
|
426
|
-
program.isSourceFileFromExternalLibrary(source) ||
|
|
427
|
-
program.isSourceFileDefaultLibrary(source)) {
|
|
428
|
-
continue;
|
|
429
|
-
}
|
|
430
|
-
for (const specifier of moduleReferences(source)) {
|
|
431
|
-
const resolved = ts.resolveModuleName(specifier.text, source.fileName, options, host, cache, undefined, program.getModeForUsageLocation(source, specifier)).resolvedModule;
|
|
432
|
-
if (resolved && generated.has(resolve(resolved.resolvedFileName))) {
|
|
433
|
-
selected.add(file);
|
|
434
|
-
break;
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
const declarationEmit = options.declaration || options.composite;
|
|
439
|
-
const diagnostics = [...program.getOptionsDiagnostics()];
|
|
440
|
-
for (const file of selected) {
|
|
441
|
-
const source = program.getSourceFile(file);
|
|
442
|
-
diagnostics.push(...program.getSyntacticDiagnostics(source), ...program.getSemanticDiagnostics(source));
|
|
443
|
-
if (declarationEmit && !source.isDeclarationFile) {
|
|
444
|
-
diagnostics.push(...program.getDeclarationDiagnostics(source));
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
// Global diagnostics can surface while checking the selected files.
|
|
448
|
-
diagnostics.push(...program.getGlobalDiagnostics());
|
|
449
|
-
const unique = ts.sortAndDeduplicateDiagnostics(diagnostics);
|
|
450
|
-
if (unique.length > 0) {
|
|
451
|
-
throw new Error(ts.formatDiagnosticsWithColorAndContext(unique, {
|
|
452
|
-
getCanonicalFileName: (name) => name,
|
|
453
|
-
getCurrentDirectory: () => dirname(sources.configFile),
|
|
454
|
-
getNewLine: () => "\n",
|
|
455
|
-
}));
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
async function runGeneration(workspace, options, stopped, compiler, discovered = () => undefined) {
|
|
459
|
-
// The built package root (dist/ in the workspace, the tarball root when installed).
|
|
460
|
-
const root = fileURLToPath(new URL("../", import.meta.url));
|
|
461
|
-
const manifest = JSON.parse(await readFile(resolve(root, "package.json"), "utf8"));
|
|
462
|
-
const typeEntry = await realpath(resolve(root, manifest.exports["./server"].types));
|
|
463
|
-
const application = await realpath(workspace);
|
|
464
|
-
function requireInside(file) {
|
|
465
|
-
const suffix = relative(application, file);
|
|
466
|
-
if (suffix === ".." || suffix.startsWith(`..${sep}`) || resolve(application, suffix) !== file) {
|
|
467
|
-
throw new Error(`Launch source/output escapes application workspace: ${file}`);
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
const config = resolve(application, options.tsconfig);
|
|
471
|
-
requireInside(config);
|
|
472
|
-
requireInside(resolve(application, options.outDirectory));
|
|
473
|
-
for (const directory of options.scanDirectories) {
|
|
474
|
-
requireInside(resolve(dirname(config), directory));
|
|
475
|
-
}
|
|
476
|
-
const { sources, desired } = await prepareLaunchRoutes(application, options, typeEntry, compiler?.discovery);
|
|
477
|
-
for (const file of sources.parsed.fileNames) {
|
|
478
|
-
requireInside(file);
|
|
479
|
-
}
|
|
480
|
-
// TS 6 defaults strict checking on, but each explicit false overrides it.
|
|
481
|
-
// Match its getStrictOptionValue rule without relying on an untyped internal API.
|
|
482
|
-
for (const flag of [
|
|
483
|
-
"noImplicitAny",
|
|
484
|
-
"strictNullChecks",
|
|
485
|
-
"strictFunctionTypes",
|
|
486
|
-
"strictBindCallApply",
|
|
487
|
-
"strictPropertyInitialization",
|
|
488
|
-
"strictBuiltinIteratorReturn",
|
|
489
|
-
"noImplicitThis",
|
|
490
|
-
"useUnknownInCatchVariables",
|
|
491
|
-
]) {
|
|
492
|
-
const enabled = sources.parsed.options[flag] ?? sources.parsed.options.strict ?? true;
|
|
493
|
-
if (!enabled) {
|
|
494
|
-
throw new Error(`Launch generation requires effective strict TypeScript checking: ${flag} is disabled`);
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
if (sources.parsed.options.noCheck) {
|
|
498
|
-
throw new Error("Launch generation requires effective strict TypeScript checking: noCheck must be false");
|
|
499
|
-
}
|
|
500
|
-
const { context, groups } = await groupsOf(sources);
|
|
501
|
-
discovered(context.file);
|
|
502
|
-
const appManifest = JSON.parse(await readFile(resolve(application, "package.json"), "utf8"));
|
|
503
|
-
if (typeof appManifest.name !== "string" || appManifest.name.length === 0) {
|
|
504
|
-
throw new Error("Launch application package.json requires a name for generated app identity");
|
|
505
|
-
}
|
|
506
|
-
const appId = createHash("sha256")
|
|
507
|
-
.update("launch-app-v1\0")
|
|
508
|
-
.update(appManifest.name)
|
|
509
|
-
.update("\0")
|
|
510
|
-
.update(relative(application, sources.configFile).split(sep).join("/"))
|
|
511
|
-
.update("\0")
|
|
512
|
-
.update(relative(application, context.file).split(sep).join("/"))
|
|
513
|
-
.update("\0")
|
|
514
|
-
.update(context.call.getSourceFile().text)
|
|
515
|
-
.digest("hex");
|
|
516
|
-
const payloads = emitLaunch(sources, desired, context, groups, appId, options.tanstackQuery === true);
|
|
517
|
-
await auditPath(sources.output);
|
|
518
|
-
const outputInventory = await walk(sources.output);
|
|
519
|
-
const globals = [
|
|
520
|
-
"routes.generated.ts",
|
|
521
|
-
"destinations.generated.ts",
|
|
522
|
-
"context.generated.d.ts",
|
|
523
|
-
"server.generated.ts",
|
|
524
|
-
].map((name) => resolve(sources.output, name));
|
|
525
|
-
const plan = await planOutputs(desired, [...sources.encountered, ...outputInventory], globals, "router-and-launch");
|
|
526
|
-
const validation = createValidationProgram(sources, desired, plan.stale, compiler?.overlay);
|
|
527
|
-
await validateRoutes(sources, desired, validation, compiler?.routerAnchor);
|
|
528
|
-
await validatePayloadImports(validation, payloads);
|
|
529
|
-
await validateBindings(sources, validation, context, groups, compiler);
|
|
530
|
-
checkGeneratedDomain(sources, validation, desired);
|
|
531
|
-
publish(plan, options.check === true, stopped, new Map(), new Set());
|
|
532
|
-
}
|
|
533
|
-
/**
|
|
534
|
-
* Generates the router's and Launch's files for an application, or checks them.
|
|
535
|
-
*
|
|
536
|
-
* @remarks
|
|
537
|
-
* Node-only. Generation reads your sources without running them. Besides the router's
|
|
538
|
-
* files, it writes an `rpc.generated.ts` beside each route that gets a
|
|
539
|
-
* `route.generated.ts`, and `context.generated.d.ts` and `server.generated.ts` in the
|
|
540
|
-
* output directory. Run it before the Angular build.
|
|
541
|
-
*
|
|
542
|
-
* Everything is validated, including a type check of the generated files with
|
|
543
|
-
* `skipLibCheck: false`, before anything is written, so a failed run changes nothing.
|
|
544
|
-
* Files are then written one at a time without rollback; a write error partway through
|
|
545
|
-
* can leave some files updated, which the next successful run repairs. Generation only
|
|
546
|
-
* replaces or removes files carrying its ownership marker, and removes stale ones.
|
|
547
|
-
*
|
|
548
|
-
* @example
|
|
549
|
-
* ```js
|
|
550
|
-
* import { generate } from "@loozo/angular-launch/generation";
|
|
551
|
-
*
|
|
552
|
-
* await generate(import.meta.dirname, {
|
|
553
|
-
* tsconfig: "tsconfig.app.json",
|
|
554
|
-
* scanDirectories: ["src/routes"],
|
|
555
|
-
* outDirectory: "generated",
|
|
556
|
-
* check: process.argv.includes("--check"),
|
|
557
|
-
* });
|
|
558
|
-
* ```
|
|
559
|
-
*
|
|
560
|
-
* @param workspace - The absolute path of the application directory, which contains
|
|
561
|
-
* its `package.json`. The tsconfig, scanned directory, sources and output directory
|
|
562
|
-
* must all be inside it.
|
|
563
|
-
* @param options - The generation options.
|
|
564
|
-
* @param stopped - Called once just before writing; returning `true` skips writing and
|
|
565
|
-
* resolves. Defaults to never stopping.
|
|
566
|
-
* @returns A promise that resolves when generation finishes.
|
|
567
|
-
* @throws Rejects when a path escapes the workspace, the tsconfig disables strict
|
|
568
|
-
* checking or enables `noCheck`, the application's `package.json` has no `name`, the
|
|
569
|
-
* sources or generated files fail validation, a file to replace lacks the ownership
|
|
570
|
-
* marker, or, with `check`, a generated file is out of date.
|
|
571
|
-
*/
|
|
572
|
-
export function generate(workspace, options, stopped = () => false) {
|
|
573
|
-
return runGeneration(workspace, options, stopped);
|
|
574
|
-
}
|
|
575
|
-
/**
|
|
576
|
-
* Creates a generation session that reuses compiler work between sequential calls.
|
|
577
|
-
*
|
|
578
|
-
* @remarks
|
|
579
|
-
* Node-only. For long-running tools that regenerate repeatedly, such as after file
|
|
580
|
-
* changes. A session doesn't watch files; you decide when to call `generate`. Edits
|
|
581
|
-
* inside the application are picked up by the next call. Create a new session after
|
|
582
|
-
* moving the application directory or changing dependencies. Don't run two sessions or
|
|
583
|
-
* generators against the same output at once.
|
|
584
|
-
*
|
|
585
|
-
* @example
|
|
586
|
-
* ```js
|
|
587
|
-
* const session = createGenerationSession(workspace, {
|
|
588
|
-
* tsconfig: "tsconfig.app.json",
|
|
589
|
-
* scanDirectories: ["src/routes"],
|
|
590
|
-
* outDirectory: "generated",
|
|
591
|
-
* });
|
|
592
|
-
*
|
|
593
|
-
* try {
|
|
594
|
-
* await session.generate();
|
|
595
|
-
* await session.generate({ check: true });
|
|
596
|
-
* } finally {
|
|
597
|
-
* await session.dispose();
|
|
598
|
-
* }
|
|
599
|
-
* ```
|
|
600
|
-
*
|
|
601
|
-
* @param workspace - The absolute path of the application directory, as for
|
|
602
|
-
* {@link generate}.
|
|
603
|
-
* @param options - The generation options, fixed for the session's lifetime; `check` is
|
|
604
|
-
* passed per call instead.
|
|
605
|
-
* @returns The session. Dispose it when done.
|
|
606
|
-
*/
|
|
607
|
-
export function createGenerationSession(workspace, { tsconfig, scanDirectories, outDirectory, tanstackQuery }) {
|
|
608
|
-
const application = resolve(workspace);
|
|
609
|
-
const fixed = { tsconfig, scanDirectories: [...scanDirectories], outDirectory, tanstackQuery };
|
|
610
|
-
const compiler = {
|
|
611
|
-
discovery: new CompilerState(),
|
|
612
|
-
overlay: new CompilerState(),
|
|
613
|
-
routerAnchor: new AnchorState(),
|
|
614
|
-
launchAnchor: new AnchorState(),
|
|
615
|
-
};
|
|
616
|
-
let closed = false;
|
|
617
|
-
let active;
|
|
618
|
-
function clear() {
|
|
619
|
-
for (const slot of Object.values(compiler)) {
|
|
620
|
-
slot.clear();
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
const session = {
|
|
624
|
-
async generate({ check = false } = {}, stopped = () => false) {
|
|
625
|
-
if (closed) {
|
|
626
|
-
throw new Error("Generation session is disposed");
|
|
627
|
-
}
|
|
628
|
-
if (active) {
|
|
629
|
-
throw new Error("Generation session requires sequential calls");
|
|
630
|
-
}
|
|
631
|
-
let interrupted = false;
|
|
632
|
-
function isStopped() {
|
|
633
|
-
if (closed) {
|
|
634
|
-
interrupted = true;
|
|
635
|
-
return true;
|
|
636
|
-
}
|
|
637
|
-
const requested = stopped();
|
|
638
|
-
if (closed || requested) {
|
|
639
|
-
interrupted = true;
|
|
640
|
-
return true;
|
|
641
|
-
}
|
|
642
|
-
return false;
|
|
643
|
-
}
|
|
644
|
-
const work = runGeneration(application, { ...fixed, check }, isStopped, compiler, (file) => {
|
|
645
|
-
contextFiles.set(session, file);
|
|
646
|
-
});
|
|
647
|
-
active = work;
|
|
648
|
-
try {
|
|
649
|
-
await work;
|
|
650
|
-
}
|
|
651
|
-
catch (error) {
|
|
652
|
-
clear();
|
|
653
|
-
throw error;
|
|
654
|
-
}
|
|
655
|
-
finally {
|
|
656
|
-
active = undefined;
|
|
657
|
-
if (closed || interrupted) {
|
|
658
|
-
clear();
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
|
-
},
|
|
662
|
-
async dispose() {
|
|
663
|
-
closed = true;
|
|
664
|
-
await active?.catch(() => undefined);
|
|
665
|
-
clear();
|
|
666
|
-
},
|
|
667
|
-
};
|
|
668
|
-
return session;
|
|
669
|
-
}
|
|
1
|
+
// The public `@loozo/angular-launch/generation` entry. The builders use run.ts directly, whose
|
|
2
|
+
// calls also resolve to the locale words.
|
|
3
|
+
export { generate, createGenerationSession } from "./run.js";
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type Sources } from "@loozo/angular-router/_generation";
|
|
2
|
+
/**
|
|
3
|
+
* The text of `redirects.generated.ts`: every distinct canonical static word of every route,
|
|
4
|
+
* with the router's own message for it, so each localized build swaps a redirect's words into
|
|
5
|
+
* its language exactly as its destination copies translate them.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* A declaration's local static segments cover every effective one, since each effective static
|
|
9
|
+
* is some declaration's local static. Words are sorted by code unit, so the bytes don't depend
|
|
10
|
+
* on the machine's locale. The tags sit inside the table function: nothing evaluates them
|
|
11
|
+
* until a client in a localized application needs the table, and the module imports no
|
|
12
|
+
* destination, so lazy children stay lazy.
|
|
13
|
+
*/
|
|
14
|
+
export declare function emitRedirects(sources: Sources): string;
|