@workerstack/clients 1.0.0-rc.27 → 1.0.0-rc.28

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.
@@ -36,7 +36,7 @@ export type RouteEntry = {
36
36
  es?: Readonly<Record<string, string>>;
37
37
  /** The live handler record; present in a snapshot of a running app, never written. */
38
38
  h?: unknown;
39
- /** Set on an internal route (spec, docs, manifest): it is left out of the route selectors. */
39
+ /** Set on an internal route (spec, docs, manifest): it is left out of the document. */
40
40
  i?: 1 | true;
41
41
  /** What the route's `.input()` declares; a live value, never written. */
42
42
  iv?: unknown;
@@ -200,16 +200,6 @@ function N(s: Record<string, TreeNode> = S({}), m: Record<string, string> | null
200
200
  return { d, m, s, w, ws }
201
201
  }
202
202
  `;
203
- /** The exported selectors: every HTTP route that is neither internal nor marked internal by its meta. */
204
- function selectorType(routes, intern) {
205
- const ids = routes
206
- .filter((route) => !route.id.startsWith("WS ") && route.i === null && route.mt?.internal !== true)
207
- .map((route) => route.id)
208
- .sort(compareCodeUnits);
209
- if (ids.length === 0)
210
- return "";
211
- return `\nexport type RouteSelector = ${ids.map((id) => `typeof ${intern.id(id)}`).join(" | ")}\n`;
212
- }
213
203
  /** The route-tree module for `tree` (a snapshot or a merged tree); throws on anything it cannot carry. */
214
204
  export function generateRouteTree(tree) {
215
205
  if (tree.v !== 2)
@@ -231,7 +221,6 @@ export function generateRouteTree(tree) {
231
221
  /* S typed by its entry: inferred from the literals, the union of entries would give each es the others' keys */
232
222
  `export const routes: RouteTree["routes"] = S<RouteTree["routes"][string]>({\n${routes.map((route) => routeLine(route, intern)).join(",\n")}\n})\n`,
233
223
  shape ?? "",
234
- selectorType(routes, intern),
235
224
  meta.length > 0 ? `export const meta: ${metaType} = S({\n${meta.join(",\n")}\n})\n` : "",
236
225
  `export const routeTree: RouteTree = { v: 2, root: tree, routes, ${meta.length > 0 ? "meta" : "meta: {}"} }\n`,
237
226
  ]
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * `generateTypes` (F3): an app's `_gen/types.gen.d.ts` — the `Routes` map, each route's ctx,
3
- * input, output, errors and meta, the route selectors with the `HttpCodegen` augmentation, and
4
- * `BaseCtx`. Read from the app's OpenAPI document (the IR), its route tree (meta, O1) and the
5
- * extracted ctx types (middleware, env, taps, parsed inputs, O3), joined on `x-backend-route`.
3
+ * input, output, errors and meta, the `HttpCodegen` `operationId` slot mapping each declared id
4
+ * to its context, and `BaseCtx`. Read from the app's OpenAPI document (the IR), its route tree
5
+ * (meta, O1) and the extracted ctx types (middleware, env, parsed inputs, O3), joined on
6
+ * `x-backend-route`.
6
7
  */
7
8
  import type { ExtractedTypes } from "../../extract/extract.ts";
8
9
  import type { RouteTree } from "./route-tree.ts";
@@ -8,22 +8,10 @@ import { statusKeyOf } from "../shared/status-keys.js";
8
8
  import { irToTs } from "../shared/type-emitter.js";
9
9
  import { componentNames } from "./sdk-types.js";
10
10
  /* the names the file declares, which a component schema never takes */
11
- const RESERVED = [
12
- "HttpContext",
13
- "HttpError",
14
- "HttpMeta",
15
- "Omit",
16
- "Partial",
17
- "Readonly",
18
- "Record",
19
- "Routes",
20
- "RouteSelector",
21
- "TapMap",
22
- ];
11
+ const RESERVED = ["HttpContext", "HttpError", "HttpMeta", "Omit", "Partial", "Readonly", "Record", "Routes"];
23
12
  /* the v1 error-factory signature of a key without a schema (core errors.ts ErrorFactoryOpts) */
24
13
  const STANDARD_FACTORY = "(opts?: { cause?: unknown; fields?: Record<string, { error_key: string; message: string; path: string }[]>; headers?: Record<string, string>; vars?: Record<string, number | string> }) => HttpError";
25
14
  const EXTRACTORS = [
26
- ["RouteCtx", "ctx"],
27
15
  ["RouteInput", "input"],
28
16
  ["RouteOutput", "output"],
29
17
  ["RouteErrors", "errors"],
@@ -148,15 +136,29 @@ function errorsOf(op, ctx) {
148
136
  * Without an extracted declaration (no ts-morph, or an app that declares no meta) the literals are all there is.
149
137
  */
150
138
  function ctxMeta(extracted, literal) {
151
- const declared = extracted?.meta ?? null;
139
+ /* with nothing extracted, the tree's literals are all there is */
140
+ if (extracted === null || extracted === undefined)
141
+ return literal;
152
142
  /* the OpenAPI keys the declared meta does not redefine: a consumer that types `security` its own way holds
153
- that type in the handler, and intersecting backend's would conflict with it */
154
- return declared === null ? literal : `Partial<Omit<HttpMeta, keyof ${declared}>> & ${declared}`;
143
+ that type in the handler, and intersecting backend's would conflict with it. An app that declares none
144
+ holds them all, each widened by \`.meta()\` */
145
+ const declared = extracted.meta;
146
+ return declared === null ? "Partial<HttpMeta>" : `Partial<Omit<HttpMeta, keyof ${declared}>> & ${declared}`;
155
147
  }
156
148
  /** `ctx.params`: the type a param schema gives it as extracted, else each of the pattern's params a string. */
157
149
  function ctxParams(extracted, id, pattern) {
158
150
  return extracted?.params[id] ?? objectText(paramsOf(pattern));
159
151
  }
152
+ /**
153
+ * The ctx's `meta` and `routePattern`. A mounted route's handler types the path it was registered at, never the one
154
+ * it is served at, so its ctx keeps the base's `string` and that handler's own ctx still fits.
155
+ */
156
+ function routeFields(extracted, id, literal) {
157
+ const fields = [["readonly meta", `Readonly<${ctxMeta(extracted, literal)}>`]];
158
+ if (!extracted?.mounted.includes(id))
159
+ fields.push(["readonly routePattern", tsString(id.slice(id.indexOf(" ") + 1))]);
160
+ return fields;
161
+ }
160
162
  /** One `Routes[pattern][method]` entry. */
161
163
  function routeEntry(id, op, options, ctx) {
162
164
  const pattern = id.slice(id.indexOf(" ") + 1);
@@ -168,7 +170,6 @@ function routeEntry(id, op, options, ctx) {
168
170
  const mt = options.tree.routes[id]?.mt;
169
171
  /* the values the tree carries, as literals: what a consumer reads a route's configuration from */
170
172
  const literal = mt && Object.keys(mt).length > 0 ? literalType(mt) : "{}";
171
- const meta = ctxMeta(extracted, literal);
172
173
  const output = outputOf(op, ctx);
173
174
  const own = [];
174
175
  if (input !== "{}")
@@ -177,7 +178,7 @@ function routeEntry(id, op, options, ctx) {
177
178
  own.push(["readonly params", params]);
178
179
  if (factories.length > 0)
179
180
  own.push(["readonly errors", objectText(factories)]);
180
- own.push(["readonly meta", `Readonly<${meta}>`], ["readonly routePattern", tsString(pattern)]);
181
+ own.push(...routeFields(extracted, id, literal));
181
182
  const base = options.baseCtxName ?? "BaseCtx";
182
183
  const parts = [factories.length > 0 ? `Omit<${base}, "errors">` : base];
183
184
  const adds = extracted?.routes[id];
@@ -193,18 +194,65 @@ function routeEntry(id, op, options, ctx) {
193
194
  ];
194
195
  return entry.map(([key, type]) => `\t\t\t${key}: ${type}`).join("\n");
195
196
  }
196
- /** `BaseCtx`: the app's context over its env, the middleware's additions and its typed taps. */
197
+ /** `BaseCtx`: the app's context over its env, with the middleware's additions. */
197
198
  function baseCtx(extracted, name) {
198
- const env = extracted?.env ?? "Record<string, unknown>";
199
- const taps = extracted?.taps ?? null;
200
- const parts = [taps === null ? `HttpContext<${env}>` : `Omit<HttpContext<${env}>, "tap">`];
199
+ const parts = [`HttpContext<${extracted?.env ?? "Record<string, unknown>"}>`];
201
200
  const middleware = extracted?.middleware ?? [];
202
201
  if (middleware.length > 0)
203
202
  parts.push(propsText(middleware));
204
- if (taps !== null)
205
- parts.push("{ tap<K extends keyof TapMap>(key: K, payload: TapMap[K]): void }");
206
- const lines = taps === null ? [] : [`type TapMap = ${taps}`];
207
- return [...lines, `export type ${name} = ${parts.join(" & ")}`];
203
+ return `export type ${name} = ${parts.join(" & ")}`;
204
+ }
205
+ /**
206
+ * A WebSocket route's ctx, as core's `WSRouteCtx` types its callbacks: the base with the pattern's params, and the
207
+ * search input `.input()` declares. Extracted additions are keyed by HTTP routes only, so none join here.
208
+ */
209
+ function wsCtx(op, id, options, ctx) {
210
+ const own = [];
211
+ const search = wireInput(op, ctx).find(([key]) => key === "search");
212
+ if (search !== undefined)
213
+ own.push(["readonly input", objectText([search])]);
214
+ const params = ctxParams(options.extracted, id, pathOf(id));
215
+ if (params !== "{}")
216
+ own.push(["readonly params", params]);
217
+ const base = options.baseCtxName ?? "BaseCtx";
218
+ return own.length === 0 ? base : `${base} & ${objectText(own)}`;
219
+ }
220
+ /**
221
+ * The `HttpCodegen` augmentation: each declared id (the route's own, before core's suffix) to its kind and ctx, in
222
+ * code-unit order. An HTTP id names its `Routes` entry's ctx, a declared id over several routes its first route's in
223
+ * code-unit order (D3: no union of contexts). An operation without `x-backend-route` has no entry: `routesOf`
224
+ * reports an HTTP one, this a WebSocket one. Null with no operations, so core's plain string ids apply.
225
+ */
226
+ function operationSlot(ir, options, ctx) {
227
+ const routeIds = new Map();
228
+ const missing = [];
229
+ for (const op of ir.operations) {
230
+ const route = op.extensions.route;
231
+ if (route === undefined) {
232
+ if (op.extensions.websocket === true)
233
+ missing.push(`${op.method} ${op.path}: no x-backend-route; left out of the operationId slot`);
234
+ continue;
235
+ }
236
+ const declared = op.extensions.declaredId ?? op.id;
237
+ const entry = routeIds.get(declared) ?? { op, routes: [] };
238
+ if (!entry.routes.includes(route))
239
+ entry.routes.push(route);
240
+ routeIds.set(declared, entry);
241
+ }
242
+ for (const message of missing.sort(compareCodeUnits))
243
+ options.report(message);
244
+ if (routeIds.size === 0)
245
+ return null;
246
+ const entries = [...routeIds].sort(([a], [b]) => compareCodeUnits(a, b));
247
+ const lines = entries.map(([declared, { op, routes }]) => {
248
+ const id = routes.sort(compareCodeUnits)[0];
249
+ const method = id.slice(0, id.indexOf(" ")).toLowerCase();
250
+ const entry = op.extensions.websocket === true
251
+ ? `kind: "ws"; ctx: ${wsCtx(op, id, options, ctx)}`
252
+ : `kind: "http"; ctx: Routes[${tsString(pathOf(id))}][${tsString(method)}]["ctx"]`;
253
+ return `\t\t\t${tsString(declared)}: { ${entry} }`;
254
+ });
255
+ return `declare module "@workerstack/backend/http" {\n\tinterface HttpCodegen {\n\t\toperationId: {\n${lines.join("\n")}\n\t\t}\n\t}\n}`;
208
256
  }
209
257
  /** A route id's path: `GET /a` → `/a`. */
210
258
  const pathOf = (id) => id.slice(id.indexOf(" ") + 1);
@@ -231,21 +279,14 @@ export function generateTypes(options) {
231
279
  const names = { refName: componentNames(ir, [...RESERVED, name]) };
232
280
  const ctx = { names, resolve: (schema) => irToTs(schema, names) };
233
281
  const hasErrors = [...routes.values()].some((op) => Object.keys(op.extensions.errors ?? {}).length > 0);
234
- const selectors = [...routes.keys()].sort(compareCodeUnits);
235
- /* HttpMeta only when a declared meta is emitted: the ctx's meta is that type and the keys a route may add */
236
- const declaredMeta = options.extracted?.meta ?? null;
237
- const imports = [
238
- "HttpContext",
239
- "WithOutput",
240
- ...(hasErrors ? ["HttpError"] : []),
241
- ...(declaredMeta === null ? [] : ["HttpMeta"]),
242
- ];
282
+ /* HttpMeta once a route's ctx reads it: with anything extracted, the ctx's meta is built from its keys */
283
+ const readsMeta = options.extracted !== null && options.extracted !== undefined && routes.size > 0;
284
+ const imports = ["HttpContext", "WithOutput", ...(hasErrors ? ["HttpError"] : []), ...(readsMeta ? ["HttpMeta"] : [])];
243
285
  const out = [`import type { ${imports.join(", ")} } from "@workerstack/backend/http"`];
244
- out.push(...baseCtx(options.extracted, name));
245
- if (selectors.length > 0) {
246
- out.push(`export type RouteSelector = ${selectors.map(tsString).join(" | ")}`);
247
- out.push('declare module "@workerstack/backend/http" {\n\tinterface HttpCodegen {\n\t\trouteSelector: RouteSelector\n\t}\n}');
248
- }
286
+ out.push(baseCtx(options.extracted, name));
287
+ const slot = operationSlot(ir, options, ctx);
288
+ if (slot !== null)
289
+ out.push(slot);
249
290
  for (const schema of Object.keys(ir.schemas).sort(compareCodeUnits))
250
291
  out.push(`type ${names.refName?.(schema)} = ${ctx.resolve(ir.schemas[schema])}`);
251
292
  out.push(routesType(routes, options, ctx));
@@ -7,6 +7,12 @@
7
7
  import type { ts } from "ts-morph";
8
8
  import { type Serializer } from "./serialize.ts";
9
9
  import type { Registration } from "./walk.ts";
10
+ /** A registration with the route ids its methods and paths give: the router's, never guessed. */
11
+ export type Routed = Registration & {
12
+ ids: string[];
13
+ /** the ids among `ids` served through a mount, at a path other than `own` */
14
+ mounted: string[];
15
+ };
10
16
  /** One property on `ctx` that the framework's context class does not declare: what the middleware added. */
11
17
  export type ExtractedProp = {
12
18
  /** Its name on `ctx`. */
@@ -25,10 +31,8 @@ export type RouteOptions = {
25
31
  base: ReadonlySet<string>;
26
32
  owner: ts.Node | undefined;
27
33
  report: (message: string) => void;
28
- routeId: (method: string, path: string) => string;
29
34
  };
30
- /**
31
- * Each route's own additions by route id. A route whose path is no literal, or one the router
32
- * refuses, is skipped; an id two registrations give different additions is dropped, never guessed.
33
- */
34
- export declare function routeAdditions(found: readonly Registration[], ser: Serializer, options: RouteOptions): Record<string, ExtractedProp[]>;
35
+ /** What a skip says of the route it skips. */
36
+ export declare const SKIPPED = "its ctx is not extracted";
37
+ /** Each route's own additions by route id. An id two registrations give different additions is dropped, never guessed. */
38
+ export declare function routeAdditions(found: readonly Routed[], ser: Serializer, options: RouteOptions): Record<string, ExtractedProp[]>;
@@ -42,28 +42,14 @@ export function addedProps(ctx, owner, ser) {
42
42
  return { name: p.getName(), optional, type: ref ?? (optional ? ser.optional(type) : ser.text(type)) };
43
43
  });
44
44
  }
45
- const SKIPPED = "its ctx is not extracted";
46
- /**
47
- * Each route's own additions by route id. A route whose path is no literal, or one the router
48
- * refuses, is skipped; an id two registrations give different additions is dropped, never guessed.
49
- */
45
+ /** What a skip says of the route it skips. */
46
+ export const SKIPPED = "its ctx is not extracted";
47
+ /** Each route's own additions by route id. An id two registrations give different additions is dropped, never guessed. */
50
48
  export function routeAdditions(found, ser, options) {
51
- const { base, owner, report, routeId } = options;
49
+ const { base, owner, report } = options;
52
50
  const byId = new Map();
53
51
  const conflicted = new Set();
54
- for (const { at, ctx, methods, path } of found) {
55
- if (path === null) {
56
- report(`${at}: the route's path is not a literal type; ${SKIPPED}`);
57
- continue;
58
- }
59
- let ids;
60
- try {
61
- ids = methods.map((method) => routeId(method, path));
62
- }
63
- catch (error) {
64
- report(`${at}: the router refuses ${JSON.stringify(path)} (${error.message}); ${SKIPPED}`);
65
- continue;
66
- }
52
+ for (const { ctx, ids } of found) {
67
53
  const props = addedProps(ctx, owner, ser).filter((p) => !base.has(p.name));
68
54
  const key = JSON.stringify(props);
69
55
  for (const id of ids) {
@@ -30,10 +30,10 @@ export type ExtractedTypes = {
30
30
  params: Record<string, string>;
31
31
  /** the meta type the app declares (`metaType<AppMeta>()`), or null when it declares none */
32
32
  meta: string | null;
33
+ /** the route ids served through a mount, at a path other than the one their handler's ctx types; code-unit sorted */
34
+ mounted: string[];
33
35
  /** per route id, what the route's middleware added beyond `middleware`; a route that added nothing has none */
34
36
  routes: Record<string, ExtractedProp[]>;
35
- /** the declared tap payloads, or null when none are */
36
- taps: string | null;
37
37
  };
38
38
  /** ts-morph, the optional peer, when installed; else undefined, which `extractTypes` reports once. */
39
39
  export declare function loadTsMorph(specifier?: string): Promise<TsMorph | undefined>;
@@ -8,17 +8,18 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
8
8
  };
9
9
  /**
10
10
  * Extract the types a generated file needs from the app's source: its env, what its middleware
11
- * added (the app's own, and each route's beyond them), and its taps. Written inline, so the
11
+ * added (the app's own, and each route's beyond them), its parsed inputs and meta. Written inline, so the
12
12
  * generated file imports nothing from the app but the named types it references by `import()`,
13
13
  * each through a specifier the output can resolve. ts-morph is the caller's, passed in.
14
14
  */
15
15
  import { existsSync, readFileSync } from "node:fs";
16
16
  import { dirname, join, relative, sep } from "node:path";
17
- import { addedProps, frameworkClass, routeAdditions } from "./chain.js";
17
+ import { compareCodeUnits } from "../emit/shared/lang.js";
18
+ import { addedProps, frameworkClass, routeAdditions, SKIPPED } from "./chain.js";
18
19
  import { Serializer } from "./serialize.js";
19
20
  import { loadEntry, registrations } from "./walk.js";
20
21
  /* the type-only members every backend app carries */
21
- const APP_MEMBERS = ["$ctx", "$env", "$taps"];
22
+ const APP_MEMBERS = ["$ctx", "$env"];
22
23
  /* the declared meta, read when the app carries it: an app from an older backend has no $meta and still extracts */
23
24
  const META_MEMBER = "$meta";
24
25
  /** The nearest named package.json above `file` (one without a name only marks a module type). */
@@ -112,26 +113,40 @@ function moduleSpecifier(file, outputDir, cache) {
112
113
  function resolvable(text, outputDir, cache) {
113
114
  return text.replace(/import\("([^"]+)"\)\./g, (_, file) => `import("${moduleSpecifier(file, outputDir, cache)}").`);
114
115
  }
116
+ /**
117
+ * Each registration with its route ids, methods by paths. A registration whose path is no literal, or a path the
118
+ * router refuses, is said once and gives no id.
119
+ */
120
+ function routed(found, routeId, report) {
121
+ return found.map((registration) => {
122
+ const { at, methods, paths } = registration;
123
+ if (paths === null) {
124
+ report(`${at}: the route's path is not a literal type; ${SKIPPED}`);
125
+ return { ...registration, ids: [], mounted: [] };
126
+ }
127
+ const served = paths.map((path) => {
128
+ try {
129
+ return { ids: methods.map((method) => routeId(method, path)), moved: path !== registration.own };
130
+ }
131
+ catch (error) {
132
+ report(`${at}: the router refuses ${JSON.stringify(path)} (${error.message}); ${SKIPPED}`);
133
+ return { ids: [], moved: false };
134
+ }
135
+ });
136
+ const ids = served.flatMap((s) => s.ids);
137
+ return { ...registration, ids, mounted: served.flatMap((s) => (s.moved ? s.ids : [])) };
138
+ });
139
+ }
115
140
  /** Each route's `pick` type (its parsed `ctx.input`, its `ctx.params`) as text by route id; an id two registrations type differently is left out. */
116
- function routeTypes(found, pick, serialize, routeId) {
141
+ function routeTypes(found, pick, serialize) {
117
142
  const byId = new Map();
118
143
  for (const registration of found) {
119
- const { methods, path } = registration;
120
144
  const type = pick(registration);
121
- if (type === null || path === null)
145
+ if (type === null)
122
146
  continue;
123
147
  const text = serialize(type);
124
- for (const method of methods) {
125
- let id;
126
- try {
127
- id = routeId(method, path);
128
- }
129
- catch {
130
- /* the router refuses the path: routeAdditions said so once */
131
- continue;
132
- }
148
+ for (const id of registration.ids)
133
149
  byId.set(id, byId.has(id) && byId.get(id) !== text ? null : text);
134
- }
135
150
  }
136
151
  return Object.fromEntries([...byId].filter((entry) => entry[1] !== null));
137
152
  }
@@ -164,15 +179,14 @@ export function extractTypes(options) {
164
179
  const missing = APP_MEMBERS.filter((_, index) => members[index] === undefined);
165
180
  throw new Error(`Export "${exportName}" is not a backend app: it carries no ${missing.join(", ")}`);
166
181
  }
167
- const [ctx, env, tapsType] = members;
182
+ const [ctx, env] = members;
168
183
  const metaSym = appType.getProperty(META_MEMBER);
169
184
  const metaType = metaSym === undefined ? undefined : checker.getTypeOfSymbol(metaSym);
170
185
  const owner = frameworkClass(ctx, compiler);
171
186
  const middleware = addedProps(ctx, owner, ser);
172
187
  const base = new Set(middleware.map((p) => p.name));
173
- const found = registrations(entry);
174
- const routes = routeAdditions(found, ser, { base, owner, report, routeId });
175
- const taps = ser.serialize(tapsType);
188
+ const found = routed(registrations(entry, report), routeId, report);
189
+ const routes = routeAdditions(found, ser, { base, owner, report });
176
190
  /* what `metaType<AppMeta>()` declared, written out: the ctx's meta is this and the OpenAPI keys, never the tree's
177
191
  literal values, so a handler may pass its own ctx to a function typed with the generated ctx (bit 22 a) */
178
192
  const meta = metaType === undefined ? "{}" : ser.shape(metaType);
@@ -181,11 +195,11 @@ export function extractTypes(options) {
181
195
  const props = (list) => list.map((p) => ({ ...p, type: text(p.type) }));
182
196
  return {
183
197
  env: text(ser.serialize(env)),
184
- inputs: routeTypes(found, (r) => r.input, (type) => text(ser.shape(type)), routeId),
198
+ inputs: routeTypes(found, (r) => r.input, (type) => text(ser.shape(type))),
185
199
  meta: meta === "{}" ? null : text(meta),
186
200
  middleware: props(middleware),
187
- params: routeTypes(found, (r) => r.params, (type) => text(ser.shape(type)), routeId),
201
+ mounted: [...new Set(found.flatMap((r) => r.mounted))].sort(compareCodeUnits),
202
+ params: routeTypes(found, (r) => r.params, (type) => text(ser.shape(type))),
188
203
  routes: Object.fromEntries(Object.entries(routes).map(([id, list]) => [id, props(list)])),
189
- taps: taps === "{}" ? null : text(taps),
190
204
  };
191
205
  }
@@ -15,13 +15,15 @@ export type EntryOptions = {
15
15
  tsconfigPath?: string;
16
16
  };
17
17
  export type LoadedEntry = {
18
+ /** the exported declaration: a variable, or for `export default <expr>` the expression */
19
+ appNode: ts.Node;
18
20
  /** the app's type */
19
21
  appType: ts.Type;
20
22
  checker: ts.TypeChecker;
21
23
  compiler: Compiler;
22
24
  project: Project;
23
25
  };
24
- /** One route a `.handler()` call registers: where, its methods, its full path (null if not a literal) and its ctx. */
26
+ /** One route a `.handler()` call registers: where, its methods, the full paths it is served at and its ctx. */
25
27
  export type Registration = {
26
28
  at: string;
27
29
  ctx: ts.Type;
@@ -30,7 +32,13 @@ export type Registration = {
30
32
  /** `ctx.params` as the handler receives it, or null when every param is the path's string */
31
33
  params: ts.Type | null;
32
34
  methods: string[];
33
- path: string | null;
35
+ /**
36
+ * the full paths the route is served at: under each chain of mounts that carries its app, else the path it was
37
+ * registered at; null when that path is not a literal. Code-unit sorted, without duplicates.
38
+ */
39
+ paths: string[] | null;
40
+ /** the full path its own app registered it at, the one its handler's `ctx.routePattern` types; null as `paths` */
41
+ own: string | null;
34
42
  };
35
43
  /**
36
44
  * The tsconfig that governs `fromPath`: the nearest one walking up, but never past the project root
@@ -43,5 +51,8 @@ export declare function findTsConfig(fromPath: string): string | undefined;
43
51
  * `include` names (wrangler's `worker-configuration.d.ts`) declares globals the app's types use, as under `tsc -p`.
44
52
  */
45
53
  export declare function loadEntry(tsMorph: TsMorph, options: EntryOptions): LoadedEntry;
46
- /** Every route the program's own files register (not declaration files, not packages), in file order then source order. */
47
- export declare function registrations(entry: LoadedEntry): Registration[];
54
+ /**
55
+ * Every route the program's own files register (not declaration files, not packages), in file order then source order,
56
+ * at the paths the program's mounts serve it at. A mount whose path is no literal is said through `report`.
57
+ */
58
+ export declare function registrations(entry: LoadedEntry, report: (message: string) => void): Registration[];
@@ -1,13 +1,17 @@
1
1
  /**
2
2
  * The program an app is read from: its tsconfig, the exported app, and every route registration in
3
3
  * the program's own files. A registration is a `.handler()` call on a route builder, recognized by
4
- * the type-only `$ctx`, `$method` and `$path` it carries, whatever method or helper started it.
4
+ * the type-only `$ctx`, `$method` and `$path` it carries, whatever method or helper started it. Its
5
+ * path is the one its own app gives it; a `.route()` mount serves it under the mount's prefix, so its
6
+ * paths follow every chain of mounts that carries that app.
5
7
  */
6
8
  import { existsSync } from "node:fs";
7
9
  import { dirname, resolve } from "node:path";
8
10
  import { compareCodeUnits } from "../emit/shared/lang.js";
9
11
  /* the type-only members every route builder carries */
10
12
  const BUILDER_MEMBERS = ["$ctx", "$method", "$path"];
13
+ /* the type-only members every app carries */
14
+ const APP_MEMBERS = ["$ctx", "$env"];
11
15
  /**
12
16
  * The tsconfig that governs `fromPath`: the nearest one walking up, but never past the project root
13
17
  * (the nearest directory with a package.json); a stray tsconfig above it is not this project's.
@@ -45,12 +49,136 @@ export function loadEntry(tsMorph, options) {
45
49
  throw new Error(`Export "${options.exportName}" not found in ${options.entryPath}`);
46
50
  const checker = project.getTypeChecker().compilerObject;
47
51
  /* for `export default <expr>` the declaration is the expression itself */
48
- return { appType: checker.getTypeAtLocation(decl.compilerNode), checker, compiler: tsMorph.ts, project };
52
+ return {
53
+ appNode: decl.compilerNode,
54
+ appType: checker.getTypeAtLocation(decl.compilerNode),
55
+ checker,
56
+ compiler: tsMorph.ts,
57
+ project,
58
+ };
49
59
  }
50
60
  /** The string literal values among `type` (itself, or a union's members). */
51
61
  function literals(type) {
52
62
  return (type.isUnion() ? type.types : [type]).filter((t) => t.isStringLiteral()).map((t) => t.value);
53
63
  }
64
+ /** Core's `MergePath`: `"/"` gives the other side, anything else is joined as is (the router normalizes the result). */
65
+ const mergePath = (a, b) => (a === "/" ? b : b === "/" ? a : `${a}${b}`);
66
+ /** `file:line` of a node, as reports name a place. */
67
+ function placeOf(node) {
68
+ const file = node.getSourceFile();
69
+ return `${file.fileName}:${file.getLineAndCharacterOfPosition(node.getStart(file)).line + 1}`;
70
+ }
71
+ /** The single string literal `type` is, or null. */
72
+ function literalOf(type) {
73
+ const values = literals(type);
74
+ return values.length === 1 && !type.isUnion() ? values[0] : null;
75
+ }
76
+ /**
77
+ * The origin of each app expression. A handle (`use`, `basePath`, a route builder, `.handler()`, `.route()`) is its
78
+ * receiver's app; a variable, an import or an object's property is what it was bound to; anything else, `httpApp()` or
79
+ * a factory's call, makes its own app.
80
+ */
81
+ function appOrigins(entry) {
82
+ const { checker, compiler } = entry;
83
+ const memo = new Map();
84
+ const carries = (node) => checker.getTypeAtLocation(node).getProperty("$ctx") !== undefined;
85
+ const bound = (symbol, at) => {
86
+ if (symbol === undefined)
87
+ return at;
88
+ const target = symbol.flags & compiler.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
89
+ const decl = target.valueDeclaration;
90
+ if (decl !== undefined && compiler.isShorthandPropertyAssignment(decl))
91
+ return bound(checker.getShorthandAssignmentValueSymbol(decl), decl);
92
+ const init = decl !== undefined && (compiler.isVariableDeclaration(decl) || compiler.isPropertyAssignment(decl))
93
+ ? decl.initializer
94
+ : undefined;
95
+ return init === undefined ? target : origin(init);
96
+ };
97
+ const step = (expr) => {
98
+ if (compiler.isParenthesizedExpression(expr) ||
99
+ compiler.isAsExpression(expr) ||
100
+ compiler.isSatisfiesExpression(expr) ||
101
+ compiler.isNonNullExpression(expr))
102
+ return origin(expr.expression);
103
+ if (compiler.isIdentifier(expr))
104
+ return bound(checker.getSymbolAtLocation(expr), expr);
105
+ if (compiler.isPropertyAccessExpression(expr))
106
+ return bound(checker.getSymbolAtLocation(expr.name), expr);
107
+ const callee = compiler.isCallExpression(expr) ? expr.expression : undefined;
108
+ if (callee !== undefined &&
109
+ compiler.isPropertyAccessExpression(callee) &&
110
+ carries(callee.expression) &&
111
+ carries(expr))
112
+ return origin(callee.expression);
113
+ return expr;
114
+ };
115
+ const origin = (expr) => {
116
+ const known = memo.get(expr);
117
+ if (known !== undefined)
118
+ return known;
119
+ /* a binding that reads itself ends at the expression */
120
+ memo.set(expr, expr);
121
+ const found = step(expr);
122
+ memo.set(expr, found);
123
+ return found;
124
+ };
125
+ return origin;
126
+ }
127
+ /** The receiver's base path: its `HttpApp` type argument `TBasePath`, when that is one literal. */
128
+ function basePathOf(entry, app) {
129
+ const { checker, compiler } = entry;
130
+ /* a class's instance type is a reference to it: its type arguments are the app's */
131
+ const decl = app.getSymbol()?.declarations?.find((d) => compiler.isClassDeclaration(d));
132
+ const index = decl?.typeParameters?.findIndex((p) => p.name.text === "TBasePath") ?? -1;
133
+ const arg = index < 0 ? undefined : checker.getTypeArguments(app)[index];
134
+ return arg === undefined ? null : literalOf(arg);
135
+ }
136
+ /** The mount a call is, if it is `<app>.route(sub)` or `<app>.route(prefix, sub)`; a path no literal is said, never guessed. */
137
+ function mountOf(entry, call, origin, report) {
138
+ const { checker, compiler } = entry;
139
+ if (!compiler.isPropertyAccessExpression(call.expression) || call.expression.name.text !== "route")
140
+ return null;
141
+ const receiver = call.expression.expression;
142
+ const app = checker.getTypeAtLocation(receiver);
143
+ const sub = call.arguments.at(-1);
144
+ if (sub === undefined || call.arguments.length > 2 || APP_MEMBERS.some((m) => app.getProperty(m) === undefined))
145
+ return null;
146
+ /* core mounts nothing when the sub is the receiver's own app (`register.ts` `mount`): the groups that share one
147
+ app keep their own ids */
148
+ const [into, from] = [origin(receiver), origin(sub)];
149
+ if (into === from)
150
+ return null;
151
+ const base = basePathOf(entry, app);
152
+ const first = call.arguments[0];
153
+ const prefix = call.arguments.length === 1 ? "/" : literalOf(checker.getTypeAtLocation(first));
154
+ if (base === null || prefix === null) {
155
+ report(`${placeOf(call)}: the mount's path is not a literal type; the routes it mounts keep their own paths`);
156
+ return null;
157
+ }
158
+ return { prefix: mergePath(base, prefix), receiver: into, sub: from };
159
+ }
160
+ /**
161
+ * The prefixes an app is served under: `"/"` when no mount takes it as a sub, or when it is the export; else the
162
+ * mount's prefix under each of its receiver's. An app mounted only inside a cycle is served nowhere.
163
+ */
164
+ function servedPrefixes(mounts, exported) {
165
+ const bySub = new Map();
166
+ for (const mount of mounts)
167
+ bySub.set(mount.sub, [...(bySub.get(mount.sub) ?? []), mount]);
168
+ const visiting = new Set();
169
+ const prefixes = (node) => {
170
+ const edges = bySub.get(node) ?? [];
171
+ if (edges.length === 0)
172
+ return ["/"];
173
+ if (visiting.has(node))
174
+ return [];
175
+ visiting.add(node);
176
+ const out = edges.flatMap((m) => prefixes(m.receiver).map((outer) => mergePath(outer, m.prefix)));
177
+ visiting.delete(node);
178
+ return node === exported ? [...out, "/"] : out;
179
+ };
180
+ return prefixes;
181
+ }
54
182
  /** The registration a call is, if it is `<route builder>.handler(…)`. */
55
183
  function registrationOf(entry, call) {
56
184
  const { checker, compiler } = entry;
@@ -75,27 +203,35 @@ function registrationOf(entry, call) {
75
203
  const typed = paramsType
76
204
  ?.getProperties()
77
205
  .some((key) => !(checker.getTypeOfSymbol(key).flags & compiler.TypeFlags.String));
78
- const file = call.getSourceFile();
79
- const line = file.getLineAndCharacterOfPosition(call.getStart(file)).line + 1;
80
- const paths = literals(path);
81
206
  return {
82
- at: `${file.fileName}:${line}`,
207
+ at: placeOf(call),
208
+ builder: receiver,
83
209
  ctx: ctx,
84
210
  input: input ? checker.getTypeOfSymbol(input) : null,
85
211
  params: typed === true ? paramsType : null,
86
212
  /* `.on()`'s methods are literals by its signature; a path is one only as a single literal */
87
213
  methods: literals(method),
88
- path: paths.length === 1 && !path.isUnion() ? paths[0] : null,
214
+ path: literalOf(path),
89
215
  };
90
216
  }
91
- /** Every route the program's own files register (not declaration files, not packages), in file order then source order. */
92
- export function registrations(entry) {
93
- const { compiler } = entry;
94
- const out = [];
217
+ /**
218
+ * Every route the program's own files register (not declaration files, not packages), in file order then source order,
219
+ * at the paths the program's mounts serve it at. A mount whose path is no literal is said through `report`.
220
+ */
221
+ export function registrations(entry, report) {
222
+ const { appNode, compiler } = entry;
223
+ const origin = appOrigins(entry);
224
+ const found = [];
225
+ const mounts = [];
95
226
  const visit = (node) => {
96
- const found = compiler.isCallExpression(node) ? registrationOf(entry, node) : null;
97
- if (found !== null)
98
- out.push(found);
227
+ if (compiler.isCallExpression(node)) {
228
+ const registration = registrationOf(entry, node);
229
+ if (registration !== null)
230
+ found.push(registration);
231
+ const mount = registration === null ? mountOf(entry, node, origin, report) : null;
232
+ if (mount !== null)
233
+ mounts.push(mount);
234
+ }
99
235
  compiler.forEachChild(node, visit);
100
236
  };
101
237
  const files = entry.project
@@ -105,5 +241,13 @@ export function registrations(entry) {
105
241
  .sort((a, b) => compareCodeUnits(a.fileName, b.fileName));
106
242
  for (const file of files)
107
243
  visit(file);
108
- return out;
244
+ /* the export resolves as any binding of it does: through its name, or as the default export's expression */
245
+ const prefixes = servedPrefixes(mounts, origin(compiler.isVariableDeclaration(appNode) ? appNode.name : appNode));
246
+ return found.map(({ builder, path, ...registration }) => ({
247
+ ...registration,
248
+ own: path,
249
+ paths: path === null
250
+ ? null
251
+ : [...new Set(prefixes(origin(builder)).map((prefix) => mergePath(prefix, path)))].sort(compareCodeUnits),
252
+ }));
109
253
  }
@@ -123,6 +123,8 @@ export type IRResponse = {
123
123
  error?: true;
124
124
  };
125
125
  export type IROperationExtensions = {
126
+ /** the id the route declared, when the document renamed its operationId (`x-backend-declared-id`) */
127
+ declaredId?: string;
126
128
  deprecated?: true;
127
129
  /** every declared error key (`x-backend-errors`): its status, null when it has none, and its own schema */
128
130
  errors?: Record<string, {
package/dist/ir/slots.js CHANGED
@@ -196,6 +196,8 @@ export function extensionsOf(op, sse) {
196
196
  out.mcp = true;
197
197
  if (typeof op["x-backend-route"] === "string")
198
198
  out.route = op["x-backend-route"];
199
+ if (typeof op["x-backend-declared-id"] === "string")
200
+ out.declaredId = op["x-backend-declared-id"];
199
201
  const invalidate = op["x-invalidate"];
200
202
  if (Array.isArray(invalidate))
201
203
  out.invalidates = invalidate.filter((target) => typeof target === "string");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workerstack/clients",
3
- "version": "1.0.0-rc.27",
3
+ "version": "1.0.0-rc.28",
4
4
  "description": "Generates SDKs (TypeScript, Go, Rust, Python, C#, Java), a CLI and an MCP server from any OpenAPI 3.x document.",
5
5
  "keywords": [
6
6
  "codegen",
@@ -87,33 +87,6 @@
87
87
  "oxc-transform": "0.155.0",
88
88
  "zod": "4.3.6"
89
89
  },
90
- "devDependencies": {
91
- "@clack/prompts": "^0.11.0",
92
- "@commitlint/cli": "21.2.4",
93
- "@commitlint/config-conventional": "21.2.4",
94
- "@lovrozagar/grunt": "0.16.1",
95
- "@tanstack/query-core": "5.104.5",
96
- "@total-typescript/ts-reset": "0.6.1",
97
- "@types/node": "26.1.1",
98
- "@vitest/coverage-v8": "4.1.10",
99
- "@workerstack/backend": "file:vendor/workerstack-backend-1.0.0-rc.26.tgz",
100
- "@workerstack/system": "0.3.0",
101
- "ajv": "8.20.0",
102
- "ajv-formats": "3.0.1",
103
- "js-yaml": "5.3.0",
104
- "lefthook": "2.2.2",
105
- "miniflare": "4.20260730.0",
106
- "oxc-parser": "0.152.0",
107
- "oxfmt": "0.78.0",
108
- "oxlint": "1.93.0",
109
- "rulesync": "16.17.0",
110
- "smol-toml": "^1.8.0",
111
- "standardwebhooks": "1.1.1",
112
- "ts-morph": "28.0.0",
113
- "typescript": "7.0.2",
114
- "vite": "8.1.4",
115
- "vitest": "4.1.10"
116
- },
117
90
  "peerDependencies": {
118
91
  "oxfmt": ">=0.63.0",
119
92
  "ts-morph": ">=28.0.0"