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

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.
Files changed (145) hide show
  1. package/README.md +30 -7
  2. package/dist/emit/cli/commands.js +25 -5
  3. package/dist/emit/cli/flags.js +7 -3
  4. package/dist/emit/cli/skills.js +5 -1
  5. package/dist/emit/csharp/realtime.d.ts +1 -8
  6. package/dist/emit/csharp/realtime.js +25 -25
  7. package/dist/emit/csharp/sdk-answer.d.ts +10 -2
  8. package/dist/emit/csharp/sdk-method.js +9 -2
  9. package/dist/emit/csharp/sse.d.ts +0 -11
  10. package/dist/emit/csharp/sse.js +91 -10
  11. package/dist/emit/csharp/transport.js +3 -3
  12. package/dist/emit/csharp/types-messages.d.ts +47 -0
  13. package/dist/emit/csharp/types-messages.js +172 -0
  14. package/dist/emit/csharp/types-names.js +3 -2
  15. package/dist/emit/csharp/ws.d.ts +0 -15
  16. package/dist/emit/csharp/ws.js +26 -5
  17. package/dist/emit/go/sdk-answer.d.ts +24 -1
  18. package/dist/emit/go/sdk-method.d.ts +3 -0
  19. package/dist/emit/go/sdk-method.js +16 -10
  20. package/dist/emit/go/sse.d.ts +2 -10
  21. package/dist/emit/go/sse.js +87 -12
  22. package/dist/emit/go/types-union.d.ts +3 -2
  23. package/dist/emit/go/types-union.js +2 -0
  24. package/dist/emit/go/types.d.ts +6 -0
  25. package/dist/emit/go/types.js +12 -1
  26. package/dist/emit/go/ws.d.ts +4 -11
  27. package/dist/emit/go/ws.js +214 -58
  28. package/dist/emit/java/json.d.ts +3 -0
  29. package/dist/emit/java/layout-ast.d.ts +4 -1
  30. package/dist/emit/java/layout-types.js +1 -1
  31. package/dist/emit/java/models-names.d.ts +2 -0
  32. package/dist/emit/java/models-names.js +1 -0
  33. package/dist/emit/java/models-union.d.ts +12 -1
  34. package/dist/emit/java/models-union.js +11 -5
  35. package/dist/emit/java/models.d.ts +5 -0
  36. package/dist/emit/java/models.js +22 -7
  37. package/dist/emit/java/realtime.d.ts +29 -9
  38. package/dist/emit/java/realtime.js +45 -10
  39. package/dist/emit/java/sdk-mirror.js +6 -5
  40. package/dist/emit/java/sdk-op.js +1 -1
  41. package/dist/emit/java/sse.d.ts +11 -10
  42. package/dist/emit/java/sse.js +104 -5
  43. package/dist/emit/java/ws.d.ts +46 -7
  44. package/dist/emit/java/ws.js +89 -4
  45. package/dist/emit/mcp/output-schema.d.ts +4 -2
  46. package/dist/emit/mcp/output-schema.js +56 -12
  47. package/dist/emit/python/realtime.d.ts +9 -6
  48. package/dist/emit/python/realtime.js +21 -19
  49. package/dist/emit/python/sdk-answer.d.ts +5 -1
  50. package/dist/emit/python/sdk-method.d.ts +1 -1
  51. package/dist/emit/python/sdk-method.js +33 -6
  52. package/dist/emit/python/sdk.js +22 -2
  53. package/dist/emit/python/sse.d.ts +0 -5
  54. package/dist/emit/python/sse.js +35 -5
  55. package/dist/emit/python/types.d.ts +7 -0
  56. package/dist/emit/python/types.js +20 -3
  57. package/dist/emit/python/ws.d.ts +20 -6
  58. package/dist/emit/python/ws.js +67 -1
  59. package/dist/emit/rust/realtime.d.ts +7 -5
  60. package/dist/emit/rust/realtime.js +14 -17
  61. package/dist/emit/rust/sdk-method.js +1 -1
  62. package/dist/emit/rust/sse.d.ts +11 -7
  63. package/dist/emit/rust/sse.js +52 -6
  64. package/dist/emit/rust/types-union.d.ts +9 -1
  65. package/dist/emit/rust/types-union.js +4 -0
  66. package/dist/emit/rust/types.d.ts +9 -0
  67. package/dist/emit/rust/types.js +13 -7
  68. package/dist/emit/rust/ws.d.ts +22 -4
  69. package/dist/emit/rust/ws.js +57 -7
  70. package/dist/emit/ts/route-tree.d.ts +1 -1
  71. package/dist/emit/ts/route-tree.js +0 -11
  72. package/dist/emit/ts/sdk-types-preamble.js +4 -0
  73. package/dist/emit/ts/sdk-types.js +49 -10
  74. package/dist/emit/ts/sdk.js +2 -2
  75. package/dist/emit/ts/service-map.d.ts +8 -2
  76. package/dist/emit/ts/service-map.js +30 -2
  77. package/dist/emit/ts/type-gen.d.ts +4 -3
  78. package/dist/emit/ts/type-gen.js +83 -40
  79. package/dist/extract/chain.d.ts +10 -6
  80. package/dist/extract/chain.js +5 -19
  81. package/dist/extract/extract.d.ts +2 -2
  82. package/dist/extract/extract.js +37 -23
  83. package/dist/extract/walk.d.ts +15 -4
  84. package/dist/extract/walk.js +159 -15
  85. package/dist/ir/build.js +4 -0
  86. package/dist/ir/model.d.ts +16 -0
  87. package/dist/ir/sdk-model.d.ts +25 -1
  88. package/dist/ir/sdk-model.js +35 -5
  89. package/dist/ir/slots.d.ts +1 -1
  90. package/dist/ir/slots.js +11 -3
  91. package/dist/ir/streams.d.ts +16 -0
  92. package/dist/ir/streams.js +40 -0
  93. package/dist/runtime/cli/socket.go +107 -13
  94. package/dist/runtime/cli/stream.go +18 -11
  95. package/dist/runtime/csharp/Adapters.cs +12 -11
  96. package/dist/runtime/csharp/Events.cs +22 -17
  97. package/dist/runtime/csharp/Realtime.cs +50 -23
  98. package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
  99. package/dist/runtime/csharp/TransportSse.cs +3 -3
  100. package/dist/runtime/csharp/Ws.cs +1 -1
  101. package/dist/runtime/csharp/WsDial.cs +19 -1
  102. package/dist/runtime/csharp/WsTyped.cs +109 -0
  103. package/dist/runtime/go/realtime.go +125 -41
  104. package/dist/runtime/go/realtime_loop.go +21 -18
  105. package/dist/runtime/go/result.go +2 -1
  106. package/dist/runtime/go/sse.go +11 -0
  107. package/dist/runtime/go/stream.go +29 -13
  108. package/dist/runtime/go/transport.go +15 -21
  109. package/dist/runtime/go/transport_longpoll.go +3 -4
  110. package/dist/runtime/go/transport_sse.go +6 -6
  111. package/dist/runtime/go/ws.go +157 -61
  112. package/dist/runtime/java/EventStream.java +47 -29
  113. package/dist/runtime/java/Exchange.java +5 -5
  114. package/dist/runtime/java/Flight.java +3 -3
  115. package/dist/runtime/java/Realtime.java +45 -11
  116. package/dist/runtime/java/ResumableConnection.java +77 -32
  117. package/dist/runtime/java/Socket.java +8 -4
  118. package/dist/runtime/java/SseAdapter.java +1 -1
  119. package/dist/runtime/java/TypedWebSocket.java +81 -24
  120. package/dist/runtime/java/WsAdapter.java +4 -2
  121. package/dist/runtime/java/WsDial.java +12 -5
  122. package/dist/runtime/python/events.py +25 -11
  123. package/dist/runtime/python/operation.py +6 -1
  124. package/dist/runtime/python/realtime.py +47 -33
  125. package/dist/runtime/python/send_async.py +1 -0
  126. package/dist/runtime/python/transport_sse.py +2 -2
  127. package/dist/runtime/python/transport_ws.py +1 -1
  128. package/dist/runtime/python/ws.py +100 -39
  129. package/dist/runtime/rust/events.rs +64 -41
  130. package/dist/runtime/rust/realtime.rs +80 -34
  131. package/dist/runtime/rust/realtime_loop.rs +37 -12
  132. package/dist/runtime/rust/sse.rs +3 -2
  133. package/dist/runtime/rust/transport_sse.rs +1 -1
  134. package/dist/runtime/rust/transport_ws.rs +3 -2
  135. package/dist/runtime/rust/ws.rs +122 -50
  136. package/dist/runtime/ts/realtime-connection.ts +22 -0
  137. package/dist/runtime/ts/realtime-transports.ts +13 -4
  138. package/dist/runtime/ts/realtime.ts +27 -3
  139. package/dist/runtime/ts/sdk-realtime.ts +1 -1
  140. package/dist/runtime/ts/sdk-sse.ts +31 -14
  141. package/dist/runtime/ts/sdk-ws.ts +2 -1
  142. package/dist/runtime/ts/sdk.ts +9 -2
  143. package/dist/runtime/ts/sse.ts +8 -0
  144. package/dist/runtime/ts/ws.ts +88 -50
  145. package/package.json +3 -61
@@ -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
  }
package/dist/ir/build.js CHANGED
@@ -7,6 +7,7 @@ import { compareCodeUnits, pascalWords } from "../emit/shared/lang.js";
7
7
  import { schemaToIR } from "./schema.js";
8
8
  import { buildResourceTree } from "./resource-tree.js";
9
9
  import { eventOf, extensionsOf, paramsOf, parseOpenApiPath, requestBodies, responsesOf, } from "./slots.js";
10
+ import { websocketMessagesOf } from "./streams.js";
10
11
  const METHODS = ["get", "post", "put", "patch", "delete", "head", "options"];
11
12
  /** A stable id for an operation without one: `GET /users/{id}` → `getUsersById`, `GET /` → `getRoot`. */
12
13
  export function deriveOperationId(method, path) {
@@ -42,6 +43,9 @@ function operationOf(id, op, { components, item, method, path }) {
42
43
  operation.description = op.description;
43
44
  if (typeof op.summary === "string")
44
45
  operation.summary = op.summary;
46
+ const messages = websocketMessagesOf(op["x-websocket"]);
47
+ if (messages !== undefined)
48
+ operation.messages = messages;
45
49
  return operation;
46
50
  }
47
51
  /**
@@ -102,6 +102,16 @@ export type IRBody = {
102
102
  /** the whole form, for emitters that type it as one value */
103
103
  schema: IRSchema;
104
104
  };
105
+ /** One named event an SSE response streams (an OpenAPI 3.2 `itemSchema` member): `message` when it names none. */
106
+ export type IRSseEvent = {
107
+ name: string;
108
+ data: IRSchema;
109
+ };
110
+ /** A WebSocket's message schemas from the rich `x-websocket`, named from the server's side: what it receives and sends. */
111
+ export type IRWebSocketMessages = {
112
+ receive?: IRSchema;
113
+ send?: IRSchema;
114
+ };
105
115
  export type IRResponse = {
106
116
  /** the status key as written: `200`, `4XX`, `default` */
107
117
  status: string;
@@ -121,8 +131,12 @@ export type IRResponse = {
121
131
  }[];
122
132
  /** a response a declared error produces (`x-backend-error`), never a declared output */
123
133
  error?: true;
134
+ /** the named events an SSE response's `itemSchema` declares, in order */
135
+ events?: IRSseEvent[];
124
136
  };
125
137
  export type IROperationExtensions = {
138
+ /** the id the route declared, when the document renamed its operationId (`x-backend-declared-id`) */
139
+ declaredId?: string;
126
140
  deprecated?: true;
127
141
  /** every declared error key (`x-backend-errors`): its status, null when it has none, and its own schema */
128
142
  errors?: Record<string, {
@@ -159,6 +173,8 @@ export type IROperation = {
159
173
  bodies?: IRBody[];
160
174
  responses: Record<string, IRResponse>;
161
175
  extensions: IROperationExtensions;
176
+ /** the rich `x-websocket` object's messages, on a websocket or realtime operation */
177
+ messages?: IRWebSocketMessages;
162
178
  };
163
179
  export type IRTreeEntry = {
164
180
  kind: "method";
@@ -1,4 +1,4 @@
1
- import { type IR, type IRMultipartPart, type IROperation, type IRParam, type IRSchema } from "./model.ts";
1
+ import { type IR, type IRDiscriminator, type IRMultipartPart, type IROperation, type IRParam, type IRSchema, type IRSseEvent } from "./model.ts";
2
2
  import { type IRPathSegment } from "./slots.ts";
3
3
  export type SdkBody = {
4
4
  kind: "json";
@@ -70,6 +70,30 @@ export type SdkModel = {
70
70
  export declare function mediaEssence(contentType: string): string;
71
71
  export declare function isJsonMedia(contentType: string): boolean;
72
72
  export declare function isTextMedia(contentType: string): boolean;
73
+ /** The named events an SSE op's `itemSchema` declares (D7), in order; none for a stream of one `schema`. */
74
+ export declare function sseEvents(op: IROperation): readonly IRSseEvent[] | undefined;
75
+ /** Whether an event's `data` of `schema` is JSON on the wire: anything but text, which core sends as is. */
76
+ export declare const isJsonEventData: (schema: IRSchema, resolve: (schema: IRSchema) => IRSchema) => boolean;
77
+ /** A message union keyed on one field (D9): the union, the field, and each variant beside its string const there. */
78
+ export type Dispatch = {
79
+ readonly union: Extract<IRSchema, {
80
+ kind: "union";
81
+ }> & {
82
+ readonly discriminator: IRDiscriminator;
83
+ };
84
+ readonly key: string;
85
+ readonly members: readonly {
86
+ readonly variant: IRSchema;
87
+ readonly value: string;
88
+ }[];
89
+ };
90
+ /**
91
+ * How a message union dispatches (D9): on its discriminator's `propertyName` when every variant is an object whose
92
+ * field there is a string const; none for any other schema.
93
+ */
94
+ export declare function dispatchOf(schema: IRSchema, resolve: (schema: IRSchema) => IRSchema): Dispatch | undefined;
95
+ /** The field a message union dispatches on (D9); none for a schema that does not dispatch. */
96
+ export declare const dispatchKey: (schema: IRSchema, resolve: (schema: IRSchema) => IRSchema) => string | undefined;
73
97
  /**
74
98
  * The schema an SSE op declares for its events' `data`, when it is not a string: such events are
75
99
  * JSON (core JSON-encodes an object `data`) and the client parses them.
@@ -84,16 +84,46 @@ function streamOf(op) {
84
84
  /* a string-typed schema: a scalar string, or a string const or enum */
85
85
  const isStringSchema = (schema) => (schema.kind === "scalar" && schema.type === "string") ||
86
86
  (schema.kind === "const" && typeof schema.value === "string");
87
+ /** The SSE response of `op`: its `text/event-stream` answer, if any. */
88
+ const sseResponse = (op) => Object.values(op.responses).find(({ contentType }) => contentType !== undefined && mediaEssence(contentType) === "text/event-stream");
89
+ /** The named events an SSE op's `itemSchema` declares (D7), in order; none for a stream of one `schema`. */
90
+ export function sseEvents(op) {
91
+ const events = sseResponse(op)?.events;
92
+ return events === undefined || events.length === 0 ? undefined : events;
93
+ }
94
+ /** Whether an event's `data` of `schema` is JSON on the wire: anything but text, which core sends as is. */
95
+ export const isJsonEventData = (schema, resolve) => {
96
+ const resolved = resolve(schema);
97
+ return resolved.kind !== "unknown" && !isStringSchema(resolved);
98
+ };
99
+ /**
100
+ * How a message union dispatches (D9): on its discriminator's `propertyName` when every variant is an object whose
101
+ * field there is a string const; none for any other schema.
102
+ */
103
+ export function dispatchOf(schema, resolve) {
104
+ const union = resolve(schema);
105
+ if (union.kind !== "union" || union.discriminator === undefined)
106
+ return undefined;
107
+ const { discriminator } = union;
108
+ const key = discriminator.propertyName;
109
+ const members = union.variants.map((variant) => {
110
+ const object = resolve(variant);
111
+ const field = object.kind === "object" ? object.fields.find(({ name }) => name === key) : undefined;
112
+ const value = field === undefined ? undefined : resolve(field.schema);
113
+ return { value: value?.kind === "const" && typeof value.value === "string" ? value.value : undefined, variant };
114
+ });
115
+ const keyed = members.every((member) => member.value !== undefined);
116
+ return keyed ? { key, members, union: { ...union, discriminator } } : undefined;
117
+ }
118
+ /** The field a message union dispatches on (D9); none for a schema that does not dispatch. */
119
+ export const dispatchKey = (schema, resolve) => dispatchOf(schema, resolve)?.key;
87
120
  /**
88
121
  * The schema an SSE op declares for its events' `data`, when it is not a string: such events are
89
122
  * JSON (core JSON-encodes an object `data`) and the client parses them.
90
123
  */
91
124
  export function sseEventSchema(op, resolve) {
92
- const response = Object.values(op.responses).find(({ contentType }) => contentType !== undefined && mediaEssence(contentType) === "text/event-stream");
93
- if (response?.schema === undefined)
94
- return undefined;
95
- const resolved = resolve(response.schema);
96
- return resolved.kind === "unknown" || isStringSchema(resolved) ? undefined : response.schema;
125
+ const schema = sseResponse(op)?.schema;
126
+ return schema !== undefined && isJsonEventData(schema, resolve) ? schema : undefined;
97
127
  }
98
128
  function opOf(op, resolve) {
99
129
  const errorStatuses = Object.keys(op.responses)
@@ -31,7 +31,7 @@ export declare function responsesOf(op: Json, components: Components): {
31
31
  responses: Record<string, IRResponse>;
32
32
  sse: boolean;
33
33
  };
34
- /** The backend extensions: each only when it is literally `true`; invalidation targets as strings. */
34
+ /** The backend extensions: each only when it is literally `true` (`x-websocket` also as its rich object); invalidation targets as strings. */
35
35
  export declare function extensionsOf(op: Json, sse: boolean): IROperationExtensions;
36
36
  /**
37
37
  * The Standard Webhooks event the webhook `name` declares through `x-backend-webhook`, from its JSON
package/dist/ir/slots.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { schemaToIR } from "./schema.js";
2
+ import { sseEventsOf, websocketMessagesOf } from "./streams.js";
2
3
  import { compareCodeUnits } from "../emit/shared/lang.js";
3
4
  /** Splits an OpenAPI path template into literal text and `{param}` pieces. */
4
5
  export function parseOpenApiPath(path) {
@@ -159,8 +160,13 @@ export function responsesOf(op, components) {
159
160
  const type = ordered(content)[0];
160
161
  const out = { status };
161
162
  if (type !== undefined) {
162
- if (Object.keys(content).some((key) => essenceOf(key) === "text/event-stream"))
163
+ const stream = Object.keys(content).find((key) => essenceOf(key) === "text/event-stream");
164
+ if (stream !== undefined) {
163
165
  sse = true;
166
+ const events = sseEventsOf(content[stream]?.itemSchema, (value) => deref(value, components));
167
+ if (events !== undefined)
168
+ out.events = events;
169
+ }
164
170
  out.contentType = type;
165
171
  const schema = content[type]?.schema;
166
172
  if (schema !== undefined)
@@ -179,10 +185,10 @@ export function responsesOf(op, components) {
179
185
  }
180
186
  return { responses, sse };
181
187
  }
182
- /** The backend extensions: each only when it is literally `true`; invalidation targets as strings. */
188
+ /** The backend extensions: each only when it is literally `true` (`x-websocket` also as its rich object); invalidation targets as strings. */
183
189
  export function extensionsOf(op, sse) {
184
190
  const out = {};
185
- if (op["x-websocket"] === true)
191
+ if (op["x-websocket"] === true || websocketMessagesOf(op["x-websocket"]) !== undefined)
186
192
  out.websocket = true;
187
193
  if (op["x-realtime"] === true)
188
194
  out.realtime = true;
@@ -196,6 +202,8 @@ export function extensionsOf(op, sse) {
196
202
  out.mcp = true;
197
203
  if (typeof op["x-backend-route"] === "string")
198
204
  out.route = op["x-backend-route"];
205
+ if (typeof op["x-backend-declared-id"] === "string")
206
+ out.declaredId = op["x-backend-declared-id"];
199
207
  const invalidate = op["x-invalidate"];
200
208
  if (Array.isArray(invalidate))
201
209
  out.invalidates = invalidate.filter((target) => typeof target === "string");
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The typed stream shapes an operation declares: an OpenAPI 3.2 SSE `itemSchema`'s named events, and the
3
+ * rich `x-websocket` object's `receive` and `send` messages (realtime operations carry the same object).
4
+ * Both read any document, so a malformed shape is left out, never refused.
5
+ */
6
+ import type { IRSseEvent, IRWebSocketMessages } from "./model.ts";
7
+ type Json = Record<string, unknown>;
8
+ /**
9
+ * The events an SSE `itemSchema` declares, in order: one event object, or a `oneOf`/`anyOf` of them, each
10
+ * followed through `follow`. A member is named by its `event` const, `message` when it has none; its data
11
+ * is its `data`'s `contentSchema` when it has one, else the `data` schema. None for a non-object itemSchema.
12
+ */
13
+ export declare function sseEventsOf(itemSchema: unknown, follow: (value: unknown) => Json | undefined): IRSseEvent[] | undefined;
14
+ /** The rich `x-websocket` object's message schemas, each direction only when it is an object; none for any other value. */
15
+ export declare function websocketMessagesOf(raw: unknown): IRWebSocketMessages | undefined;
16
+ export {};