@slotform/api 0.0.0-stage → 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.
Files changed (151) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/dist/client.d.ts +16 -0
  4. package/dist/client.d.ts.map +1 -0
  5. package/dist/client.js +98 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/error.d.ts +2 -0
  8. package/dist/error.d.ts.map +1 -0
  9. package/dist/error.js +2 -0
  10. package/dist/error.js.map +1 -0
  11. package/dist/index.d.ts +153 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +640 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/lib/chosen.d.ts +12 -0
  16. package/dist/lib/chosen.d.ts.map +1 -0
  17. package/dist/lib/chosen.js +18 -0
  18. package/dist/lib/chosen.js.map +1 -0
  19. package/dist/lib/cursor.d.ts +68 -0
  20. package/dist/lib/cursor.d.ts.map +1 -0
  21. package/dist/lib/cursor.js +220 -0
  22. package/dist/lib/cursor.js.map +1 -0
  23. package/dist/lib/limits.d.ts +4 -0
  24. package/dist/lib/limits.d.ts.map +1 -0
  25. package/dist/lib/limits.js +10 -0
  26. package/dist/lib/limits.js.map +1 -0
  27. package/dist/lib/local-origin.d.ts +2 -0
  28. package/dist/lib/local-origin.d.ts.map +1 -0
  29. package/dist/lib/local-origin.js +17 -0
  30. package/dist/lib/local-origin.js.map +1 -0
  31. package/dist/lib/slugify.d.ts +4 -0
  32. package/dist/lib/slugify.d.ts.map +1 -0
  33. package/dist/lib/slugify.js +26 -0
  34. package/dist/lib/slugify.js.map +1 -0
  35. package/dist/lib/window.d.ts +52 -0
  36. package/dist/lib/window.d.ts.map +1 -0
  37. package/dist/lib/window.js +70 -0
  38. package/dist/lib/window.js.map +1 -0
  39. package/dist/mcp-path.d.ts +2 -0
  40. package/dist/mcp-path.d.ts.map +1 -0
  41. package/dist/mcp-path.js +3 -0
  42. package/dist/mcp-path.js.map +1 -0
  43. package/dist/mcp.d.ts +15 -0
  44. package/dist/mcp.d.ts.map +1 -0
  45. package/dist/mcp.js +5 -0
  46. package/dist/mcp.js.map +1 -0
  47. package/dist/node/barrel.d.ts +3 -0
  48. package/dist/node/barrel.d.ts.map +1 -0
  49. package/dist/node/barrel.js +70 -0
  50. package/dist/node/barrel.js.map +1 -0
  51. package/dist/node/codegen.d.ts +10 -0
  52. package/dist/node/codegen.d.ts.map +1 -0
  53. package/dist/node/codegen.js +132 -0
  54. package/dist/node/codegen.js.map +1 -0
  55. package/dist/node/procedure-codegen.d.ts +14 -0
  56. package/dist/node/procedure-codegen.d.ts.map +1 -0
  57. package/dist/node/procedure-codegen.js +95 -0
  58. package/dist/node/procedure-codegen.js.map +1 -0
  59. package/dist/node/schema-child.d.ts +2 -0
  60. package/dist/node/schema-child.d.ts.map +1 -0
  61. package/dist/node/schema-child.js +31 -0
  62. package/dist/node/schema-child.js.map +1 -0
  63. package/dist/node/schema-source.d.ts +3 -0
  64. package/dist/node/schema-source.d.ts.map +1 -0
  65. package/dist/node/schema-source.js +33 -0
  66. package/dist/node/schema-source.js.map +1 -0
  67. package/dist/node/server-client.d.ts +19 -0
  68. package/dist/node/server-client.d.ts.map +1 -0
  69. package/dist/node/server-client.js +45 -0
  70. package/dist/node/server-client.js.map +1 -0
  71. package/dist/node/types.d.ts +42 -0
  72. package/dist/node/types.d.ts.map +1 -0
  73. package/dist/node/types.js +13 -0
  74. package/dist/node/types.js.map +1 -0
  75. package/dist/not-found.d.ts +2 -0
  76. package/dist/not-found.d.ts.map +1 -0
  77. package/dist/not-found.js +6 -0
  78. package/dist/not-found.js.map +1 -0
  79. package/dist/procedure.d.ts +188 -0
  80. package/dist/procedure.d.ts.map +1 -0
  81. package/dist/procedure.js +392 -0
  82. package/dist/procedure.js.map +1 -0
  83. package/dist/query-invalidation.d.ts +20 -0
  84. package/dist/query-invalidation.d.ts.map +1 -0
  85. package/dist/query-invalidation.js +66 -0
  86. package/dist/query-invalidation.js.map +1 -0
  87. package/dist/schema.d.ts +32 -0
  88. package/dist/schema.d.ts.map +1 -0
  89. package/dist/schema.js +103 -0
  90. package/dist/schema.js.map +1 -0
  91. package/dist/types.d.ts +30 -0
  92. package/dist/types.d.ts.map +1 -0
  93. package/dist/types.js +2 -0
  94. package/dist/types.js.map +1 -0
  95. package/dist/wire.d.ts +11 -0
  96. package/dist/wire.d.ts.map +1 -0
  97. package/dist/wire.js +26 -0
  98. package/dist/wire.js.map +1 -0
  99. package/dist/worker/guards.d.ts +6 -0
  100. package/dist/worker/guards.d.ts.map +1 -0
  101. package/dist/worker/guards.js +29 -0
  102. package/dist/worker/guards.js.map +1 -0
  103. package/dist/worker/index.d.ts +57 -0
  104. package/dist/worker/index.d.ts.map +1 -0
  105. package/dist/worker/index.js +418 -0
  106. package/dist/worker/index.js.map +1 -0
  107. package/dist/worker/mcp.d.ts +28 -0
  108. package/dist/worker/mcp.d.ts.map +1 -0
  109. package/dist/worker/mcp.js +361 -0
  110. package/dist/worker/mcp.js.map +1 -0
  111. package/dist/worker/request-log.d.ts +10 -0
  112. package/dist/worker/request-log.d.ts.map +1 -0
  113. package/dist/worker/request-log.js +37 -0
  114. package/dist/worker/request-log.js.map +1 -0
  115. package/guide/add-a-procedure.md +42 -0
  116. package/guide/background.md +86 -0
  117. package/guide/client.md +93 -0
  118. package/guide/config.md +85 -0
  119. package/guide/mcp.md +68 -0
  120. package/guide/middleware.md +79 -0
  121. package/guide/procedures.md +95 -0
  122. package/guide/utilities.md +135 -0
  123. package/package.json +120 -3
  124. package/src/client.ts +129 -0
  125. package/src/error.ts +1 -0
  126. package/src/index.ts +787 -0
  127. package/src/lib/chosen.ts +31 -0
  128. package/src/lib/cursor.ts +354 -0
  129. package/src/lib/limits.ts +10 -0
  130. package/src/lib/local-origin.ts +18 -0
  131. package/src/lib/slugify.ts +29 -0
  132. package/src/lib/window.ts +155 -0
  133. package/src/mcp-path.ts +2 -0
  134. package/src/mcp.ts +30 -0
  135. package/src/node/barrel.ts +77 -0
  136. package/src/node/codegen.ts +173 -0
  137. package/src/node/procedure-codegen.ts +131 -0
  138. package/src/node/schema-child.ts +31 -0
  139. package/src/node/schema-source.ts +45 -0
  140. package/src/node/server-client.ts +67 -0
  141. package/src/node/types.ts +64 -0
  142. package/src/not-found.ts +6 -0
  143. package/src/procedure.ts +935 -0
  144. package/src/query-invalidation.ts +106 -0
  145. package/src/schema.ts +133 -0
  146. package/src/types.ts +72 -0
  147. package/src/wire.ts +34 -0
  148. package/src/worker/guards.ts +37 -0
  149. package/src/worker/index.ts +681 -0
  150. package/src/worker/mcp.ts +470 -0
  151. package/src/worker/request-log.ts +50 -0
@@ -0,0 +1,77 @@
1
+ import { readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { ROUTES_DIR } from "./types.ts";
4
+
5
+ const GENERATED_HEADER = "// Generated by @slotform/api — do not edit.";
6
+
7
+ // Route directory layout rules: docs/architecture/plugins/api.md, "Routes barrel".
8
+ function isRouteFile(file: string): boolean {
9
+ if (!(file.endsWith(".ts") || file.endsWith(".tsx"))) return false;
10
+ if (file.endsWith(".d.ts")) return false;
11
+ if (file.endsWith(".test.ts") || file.endsWith(".test.tsx")) return false;
12
+ if (file === "index.ts" || file === "index.tsx") return false;
13
+ return true;
14
+ }
15
+
16
+ function basenameWithoutExt(file: string): string {
17
+ return file.replace(/\.tsx?$/, "");
18
+ }
19
+
20
+ // A missing routes directory (or a file standing where a parent directory
21
+ // should be) is an app with no routes; any other read failure is not.
22
+ function routeFiles(cwd: string): string[] {
23
+ try {
24
+ // `withFileTypes: false` (the default) — we only want top-level
25
+ // regular files. Nested directories appear here as plain names and
26
+ // are filtered out by the extension check.
27
+ return readdirSync(join(cwd, ROUTES_DIR)).filter(isRouteFile);
28
+ } catch (error) {
29
+ if (
30
+ typeof error === "object" &&
31
+ error !== null &&
32
+ "code" in error &&
33
+ (error.code === "ENOENT" || error.code === "ENOTDIR")
34
+ ) {
35
+ return [];
36
+ }
37
+ throw error;
38
+ }
39
+ }
40
+
41
+ export function generateRouteBarrel(cwd: string): string {
42
+ const entries = routeFiles(cwd);
43
+
44
+ const byBasename = new Map<string, string[]>();
45
+ for (const entry of entries) {
46
+ const base = basenameWithoutExt(entry);
47
+ const bucket = byBasename.get(base);
48
+ if (bucket) bucket.push(entry);
49
+ else byBasename.set(base, [entry]);
50
+ }
51
+ const collisions = [...byBasename.entries()].filter(
52
+ ([, files]) => files.length > 1,
53
+ );
54
+ if (collisions.length > 0) {
55
+ const detail = collisions
56
+ .map(([base, files]) => `${base} (${files.sort().join(" + ")})`)
57
+ .join(", ");
58
+ throw new Error(
59
+ `generateRouteBarrel: ambiguous route basename(s) — ${detail}. ` +
60
+ "Pick one of .ts or .tsx per route name.",
61
+ );
62
+ }
63
+
64
+ // Full filename re-export: docs/architecture/plugins/api.md, "Routes barrel".
65
+ const exports = [...byBasename.entries()]
66
+ .sort(([a], [b]) => a.localeCompare(b))
67
+ .map(([, files]) => `export * from "./${files[0]}";`)
68
+ .join("\n");
69
+
70
+ return `${GENERATED_HEADER}\n${exports ? `${exports}\n` : ""}`;
71
+ }
72
+
73
+ // Whether the routes directory holds a routable file: `routeBarrelSource` and
74
+ // `routesHandler` are null without one.
75
+ export function hasRoutableFiles(cwd: string): boolean {
76
+ return routeFiles(cwd).length > 0;
77
+ }
@@ -0,0 +1,173 @@
1
+ import {
2
+ dedupeImports,
3
+ type MiddlewareSpec,
4
+ renderTsSourceFile,
5
+ type TsExpression,
6
+ type TsImportSpec,
7
+ type TsSourceFile,
8
+ } from "@slotform/cli/ast";
9
+ import type {
10
+ CallbackSpec,
11
+ MiddlewareCall,
12
+ PluginRuntimeEntry,
13
+ WorkerPayload,
14
+ } from "./types.ts";
15
+
16
+ // `<base>.use(<rt1>(opts))...use(<mw1>)...`, the chain `.slotform/worker.ts` and
17
+ // `.slotform/procedure.ts` both build, with each runtime's callback spliced into
18
+ // its options: docs/architecture/runtime.md, "Chain order".
19
+ export function runtimeChain(
20
+ base: TsExpression,
21
+ runtimes: readonly PluginRuntimeEntry[],
22
+ middlewareChain: readonly MiddlewareCall[],
23
+ callbacks: Readonly<Record<string, CallbackSpec>>,
24
+ ): { chain: TsExpression; imports: TsImportSpec[] } {
25
+ let chain = base;
26
+ const runtimeImports: TsImportSpec[] = [];
27
+ const callbackImports: TsImportSpec[] = [];
28
+ for (const rt of runtimes) {
29
+ runtimeImports.push(rt.import);
30
+ const properties = Object.entries(rt.options).map(([key, value]) => ({
31
+ key,
32
+ value,
33
+ }));
34
+ const callback = callbacks[rt.plugin];
35
+ if (callback) {
36
+ properties.push({
37
+ key: "callbacks",
38
+ value: { kind: "identifier", name: callback.identifier },
39
+ });
40
+ callbackImports.push(callback.import);
41
+ }
42
+ chain = {
43
+ kind: "call",
44
+ callee: { kind: "member", object: chain, property: "use" },
45
+ args: [
46
+ {
47
+ kind: "call",
48
+ callee: { kind: "identifier", name: rt.identifier },
49
+ args: [{ kind: "object", properties }],
50
+ },
51
+ ],
52
+ };
53
+ }
54
+ for (const mw of middlewareChain) {
55
+ chain = {
56
+ kind: "call",
57
+ callee: { kind: "member", object: chain, property: mw.method },
58
+ args: [mw.call],
59
+ };
60
+ }
61
+ return { chain, imports: [...runtimeImports, ...callbackImports] };
62
+ }
63
+
64
+ // The `.slotform/worker.ts` source, the `workerSource` slot's: docs/architecture/plugins/api.md, "Generated files".
65
+ export function aggregateWorker(payload: WorkerPayload): string {
66
+ const { chain, imports } = runtimeChain(
67
+ payload.base,
68
+ payload.pluginRuntimes,
69
+ payload.middlewareChain,
70
+ payload.callbacks,
71
+ );
72
+
73
+ // The mount object: `mcp` (with the server's name), `queue`, `scheduled`,
74
+ // each key only when its file is there.
75
+ const mount: Array<{ key: string; value: TsExpression }> = [];
76
+ if (payload.mcp) {
77
+ mount.push(
78
+ {
79
+ key: "mcp",
80
+ value: { kind: "identifier", name: payload.mcp.identifier },
81
+ },
82
+ { key: "name", value: { kind: "string", value: payload.mcp.name } },
83
+ );
84
+ }
85
+ if (payload.queue) {
86
+ mount.push({
87
+ key: "queue",
88
+ value: { kind: "identifier", name: payload.queue.identifier },
89
+ });
90
+ }
91
+ if (payload.scheduled) {
92
+ mount.push({
93
+ key: "scheduled",
94
+ value: { kind: "identifier", name: payload.scheduled.identifier },
95
+ });
96
+ }
97
+ const args: TsExpression[] = [];
98
+ if (payload.handler || mount.length > 0) {
99
+ // A worker with plugins but no routes still takes a mount: the routes
100
+ // argument is then an empty object.
101
+ args.push(
102
+ payload.handler
103
+ ? { kind: "identifier", name: payload.handler.identifier }
104
+ : { kind: "object", properties: [] },
105
+ );
106
+ }
107
+ if (mount.length > 0) args.push({ kind: "object", properties: mount });
108
+
109
+ const spec: TsSourceFile = {
110
+ imports: dedupeImports([...payload.imports, ...imports]),
111
+ statements: [
112
+ {
113
+ kind: "const",
114
+ name: "worker",
115
+ value: {
116
+ kind: "call",
117
+ callee: { kind: "member", object: chain, property: "handler" },
118
+ args,
119
+ },
120
+ },
121
+ {
122
+ kind: "export-type",
123
+ name: "AppRouter",
124
+ // `typeof <expr>` isn't a first-class TsTypeRef kind; rendering as a
125
+ // bare `reference` pastes the text verbatim which is what we want.
126
+ type: { kind: "reference", name: "typeof worker._router" },
127
+ },
128
+ // Loads `procedure.ts`, and so its `Register` merge (see
129
+ // `./procedure-codegen.ts`), into any program that reads the router type.
130
+ { kind: "export-type-ref", source: "./procedure.ts", names: ["Entity"] },
131
+ {
132
+ kind: "export-default",
133
+ value: { kind: "identifier", name: "worker" },
134
+ },
135
+ ],
136
+ };
137
+ return renderTsSourceFile(spec);
138
+ }
139
+
140
+ const MIDDLEWARE_PHASE_ORDER: Record<MiddlewareSpec["phase"], number> = {
141
+ "before-cors": 0,
142
+ "after-cors": 1,
143
+ "before-routes": 2,
144
+ "after-routes": 3,
145
+ "after-context": 4,
146
+ };
147
+
148
+ // Mount order: phase, then `order`, then contribution order (the sort is
149
+ // stable): docs/architecture/runtime.md, "Middleware".
150
+ function mountOrder(entries: readonly MiddlewareSpec[]): MiddlewareSpec[] {
151
+ return [...entries].sort(
152
+ (a, b) =>
153
+ MIDDLEWARE_PHASE_ORDER[a.phase] - MIDDLEWARE_PHASE_ORDER[b.phase] ||
154
+ a.order - b.order,
155
+ );
156
+ }
157
+
158
+ // The `middlewareCalls` slot: each call with the builder method that mounts it.
159
+ export function middlewareCallsOf(
160
+ entries: readonly MiddlewareSpec[],
161
+ ): MiddlewareCall[] {
162
+ return mountOrder(entries).map((entry) => ({
163
+ call: entry.call,
164
+ method: entry.phase === "after-context" ? "useAfterContext" : "use",
165
+ }));
166
+ }
167
+
168
+ // The `middlewareImports` slot: the imports the calls name.
169
+ export function middlewareImportsOf(
170
+ entries: readonly MiddlewareSpec[],
171
+ ): TsImportSpec[] {
172
+ return dedupeImports(mountOrder(entries).flatMap((entry) => entry.imports));
173
+ }
@@ -0,0 +1,131 @@
1
+ import {
2
+ dedupeImports,
3
+ renderTsSourceFile,
4
+ type TsExpression,
5
+ type TsImportSpec,
6
+ } from "@slotform/cli/ast";
7
+ import { runtimeChain } from "./codegen.ts";
8
+ import type { MiddlewareCall, PluginRuntimeEntry } from "./types.ts";
9
+
10
+ // Renders `.slotform/procedure.ts`, the `virtual:slotform-procedure` target: docs/architecture/runtime.md, "The rebuilt chain".
11
+ interface ProcedurePayload {
12
+ // Same `workerBase` (`createWorker({...})` call) the real worker uses.
13
+ base: TsExpression;
14
+ // Same `pluginRuntimes` the real worker uses, in the same (sorted) order.
15
+ runtimes: PluginRuntimeEntry[];
16
+ // `workerImports` without the consumer files that import this one back: docs/architecture/runtime.md, "The rebuilt chain".
17
+ imports: TsImportSpec[];
18
+ // Same `middlewareCalls` the real worker's chain mounts, in the same order.
19
+ middlewareChain: MiddlewareCall[];
20
+ // The imports the middleware calls name, without the same files as `imports`.
21
+ middlewareImports: TsImportSpec[];
22
+ // RBAC statements from `api.slots.rbacStatements`: docs/architecture/slot-catalog.md, "`api.slots.*` (the `api` plugin)".
23
+ statements: Record<string, readonly string[]> | null;
24
+ // The entity vocabulary from `api.slots.entities`: docs/architecture/plugins/api.md, "Entities".
25
+ entities: readonly string[];
26
+ }
27
+
28
+ const APP_BUILDER_IMPORT: TsImportSpec = {
29
+ source: "@slotform/api/runtime",
30
+ named: ["AppBuilder"],
31
+ typeOnly: true,
32
+ };
33
+
34
+ const CREATE_PROCEDURE_IMPORT: TsImportSpec = {
35
+ source: "@slotform/api/procedure",
36
+ named: ["createJobs", "createProcedure"],
37
+ };
38
+
39
+ const IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
40
+
41
+ // The statements record as an inline type literal: docs/architecture/slot-catalog.md, "`api.slots.*` (the `api` plugin)".
42
+ function renderStatementsType(
43
+ statements: Record<string, readonly string[]> | null,
44
+ ): string {
45
+ if (statements === null) return "Record<never, never>";
46
+ const entries = Object.entries(statements).map(([key, actions]) => {
47
+ const keyText = IDENT_RE.test(key) ? key : JSON.stringify(key);
48
+ const tuple = actions.map((a) => JSON.stringify(a)).join(", ");
49
+ return `\t${keyText}: readonly [${tuple}];`;
50
+ });
51
+ if (entries.length === 0) return "Record<never, never>";
52
+ return `{\n${entries.join("\n")}\n}`;
53
+ }
54
+
55
+ // The entity vocabulary (sorted and unique, as the slot holds it) as an inline
56
+ // string-literal union, plain data like `renderStatementsType`; `string` when
57
+ // the app names none.
58
+ function renderEntityType(entities: readonly string[]): string {
59
+ if (entities.length === 0) return "string";
60
+ return entities.map((name) => JSON.stringify(name)).join(" | ");
61
+ }
62
+
63
+ export function aggregateProcedure(payload: ProcedurePayload): string {
64
+ const { chain, imports: runtimeImports } = runtimeChain(
65
+ payload.base,
66
+ payload.runtimes,
67
+ payload.middlewareChain,
68
+ {},
69
+ );
70
+
71
+ const importsText = renderTsSourceFile({
72
+ imports: dedupeImports([
73
+ ...payload.imports,
74
+ ...runtimeImports,
75
+ ...payload.middlewareImports,
76
+ APP_BUILDER_IMPORT,
77
+ CREATE_PROCEDURE_IMPORT,
78
+ ]),
79
+ statements: [{ kind: "const", name: "__chain", value: chain }],
80
+ });
81
+
82
+ const statementsType = renderStatementsType(payload.statements);
83
+ const entityType = renderEntityType(payload.entities);
84
+
85
+ return `${importsText}
86
+ // Type-only: \`__chain\` mirrors the runtime plugin composition in
87
+ // .slotform/worker.ts so \`WorkerContext\` matches the real request context
88
+ // without re-deriving each runtime factory's generics by hand. Never
89
+ // exported or called further — only its type is used below.
90
+ type ContextOf<B> = B extends AppBuilder<infer C> ? C : never;
91
+ // Exported so post-context middleware can type \`slotformContext<WorkerContext>(c)\`.
92
+ // Import it type-only: this module imports the middleware file back, and only
93
+ // erasure keeps that from being a real cycle.
94
+ export type WorkerContext = ContextOf<typeof __chain>;
95
+ type RbacStatements = ${statementsType};
96
+ export type Entity = ${entityType};
97
+
98
+ // Types the client's \`invalidateForWrites\` and a query's \`meta.reads\` over
99
+ // \`Entity\` (type-only: nothing reaches the bundle). \`worker.ts\` re-exports
100
+ // \`Entity\`, so an app's program loads this file with the router type. The
101
+ // import puts the module in the program, which an augmentation alone does not.
102
+ import type {} from "@slotform/api/query-invalidation";
103
+ declare module "@slotform/api/query-invalidation" {
104
+ interface Register {
105
+ entity: Entity;
106
+ }
107
+ }
108
+
109
+ // What a queue or cron handler and a node service's \`jobContext()\` receive: a
110
+ // request's context without the request (no \`httpRequest\`, headers or user). A
111
+ // mapped type, not \`Omit\`: the base context's index signature would make
112
+ // \`Omit\` drop every named key.
113
+ export type JobContext = {
114
+ [K in keyof WorkerContext as string extends K
115
+ ? never
116
+ : K extends "httpRequest" | "reqHeaders" | "resHeaders"
117
+ ? never
118
+ : K]: WorkerContext[K];
119
+ };
120
+ export const { defineQueue, defineScheduled } = createJobs<JobContext>();
121
+
122
+ // Types a node service's \`jobContext()\`, which imports nothing of the app.
123
+ declare module "@slotform/api/procedure" {
124
+ interface Register {
125
+ jobContext: JobContext;
126
+ }
127
+ }
128
+
129
+ export const procedure = createProcedure<WorkerContext, RbacStatements, Entity>();
130
+ `;
131
+ }
@@ -0,0 +1,31 @@
1
+ import { registerHooks } from "node:module";
2
+ import { join } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { routerSchema } from "../schema.ts";
5
+ import { PROCEDURE_FILE, WORKER_FILE } from "./types.ts";
6
+
7
+ // The child `slotform generate` runs to read the router: docs/architecture/plugins/api.md, "Schema".
8
+ // It prints the schema as JSON; a failure prints to stderr and exits 1.
9
+ const [cwd] = process.argv.slice(2);
10
+ if (cwd === undefined) throw new Error("schema-child: no project directory");
11
+
12
+ const procedure = pathToFileURL(join(cwd, PROCEDURE_FILE)).href;
13
+ registerHooks({
14
+ resolve: (specifier, context, next) =>
15
+ next(
16
+ specifier === "virtual:slotform-procedure" ? procedure : specifier,
17
+ context,
18
+ ),
19
+ });
20
+
21
+ try {
22
+ const { default: worker } = (await import(
23
+ pathToFileURL(join(cwd, WORKER_FILE)).href
24
+ )) as { default: { _router: unknown } };
25
+ process.stdout.write(JSON.stringify(routerSchema(worker._router)));
26
+ } catch (error) {
27
+ process.stderr.write(
28
+ error instanceof Error ? (error.stack ?? error.message) : String(error),
29
+ );
30
+ process.exit(1);
31
+ }
@@ -0,0 +1,45 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { promisify } from "node:util";
6
+ import { PROCEDURE_FILE, ROUTES_BARREL, WORKER_FILE } from "./types.ts";
7
+
8
+ const run = promisify(execFile);
9
+
10
+ // The child ships beside this module, as the same kind of file (`.js` from
11
+ // `dist/`, `.ts` when the plugin runs from source).
12
+ const CHILD = fileURLToPath(
13
+ new URL(
14
+ `./schema-child${import.meta.url.slice(import.meta.url.lastIndexOf("."))}`,
15
+ import.meta.url,
16
+ ),
17
+ );
18
+
19
+ /** The source of `.slotform/schema.ts` (null for a project without routes): every procedure of the app's router (the runtime plugins' routes too) with its input as JSON Schema, its kind and its scope key, which the client reads. The router loads in a child node process, so a long-lived `slotform dev` never writes a stale schema; a procedure that fails to load or convert fails `generate`, naming its path. */
20
+ export async function schemaSource(
21
+ cwd: string,
22
+ env: NodeJS.ProcessEnv,
23
+ ): Promise<string | null> {
24
+ if (
25
+ !existsSync(join(cwd, PROCEDURE_FILE)) ||
26
+ !existsSync(join(cwd, WORKER_FILE)) ||
27
+ !existsSync(join(cwd, ROUTES_BARREL))
28
+ ) {
29
+ return null;
30
+ }
31
+ let schema: unknown;
32
+ try {
33
+ const { stdout } = await run(process.execPath, [CHILD, cwd], {
34
+ maxBuffer: 256 * 1024 * 1024,
35
+ env,
36
+ });
37
+ schema = JSON.parse(stdout);
38
+ } catch (error) {
39
+ const detail =
40
+ (error as { stderr?: string }).stderr ??
41
+ (error instanceof Error ? error.message : String(error));
42
+ throw new Error(`generate: could not read the router's schema.\n${detail}`);
43
+ }
44
+ return `// Generated by \`slotform generate\`: each procedure's input as JSON Schema, its kind and its scope key.\nexport const SCHEMA = ${JSON.stringify(schema, null, "\t")} as const;\n`;
45
+ }
@@ -0,0 +1,67 @@
1
+ import { posix } from "node:path";
2
+ import type { ContributionCtx } from "@slotform/cli";
3
+ import { GENERATED_DIR } from "@slotform/cli";
4
+ import { z } from "zod";
5
+
6
+ // Client-only apps: docs/architecture/plugins/api.md, "Client-only apps".
7
+ export const SERVER_SCHEMA = `${GENERATED_DIR}/schema.ts`;
8
+ export const SERVER_MANIFEST = `${GENERATED_DIR}/server.json`;
9
+ export const SERVER_TYPES = `${GENERATED_DIR}/server.ts`;
10
+ // The router declaration the server's `tsc -b` emits for its `.slotform/worker.ts`.
11
+ const SERVER_ROUTER_TYPES = `${GENERATED_DIR}/types/${GENERATED_DIR}/worker.d.ts`;
12
+
13
+ // The server manifest: docs/architecture/plugins/api.md, "Client-only apps".
14
+ const serverManifestSchema = z.object({ auth: z.boolean() });
15
+ type ServerManifest = z.infer<typeof serverManifestSchema>;
16
+
17
+ type FileCtx = Pick<ContributionCtx, "fileExists" | "readFile">;
18
+
19
+ /** Reads a file the server app generated, or fails naming what to run there. */
20
+ export async function readServerFile(
21
+ ctx: FileCtx,
22
+ server: string,
23
+ file: string,
24
+ ): Promise<string> {
25
+ const path = posix.join(posix.normalize(server), file);
26
+ if (!(await ctx.fileExists(path))) {
27
+ throw new Error(
28
+ `api: \`server: "${server}"\` has no ${file}. Run \`slotform generate\` in ${posix.normalize(server)} first.`,
29
+ );
30
+ }
31
+ return ctx.readFile(path);
32
+ }
33
+
34
+ export async function readServerManifest(
35
+ ctx: FileCtx,
36
+ server: string,
37
+ ): Promise<ServerManifest> {
38
+ const text = await readServerFile(ctx, server, SERVER_MANIFEST);
39
+ const parsed = serverManifestSchema.safeParse(JSON.parse(text));
40
+ if (!parsed.success) {
41
+ throw new Error(
42
+ `api: ${posix.join(posix.normalize(server), SERVER_MANIFEST)} is not a server manifest (${parsed.error.message}). Run \`slotform generate\` in ${posix.normalize(server)} again.`,
43
+ );
44
+ }
45
+ return parsed.data;
46
+ }
47
+
48
+ /** The checks a client app passes at generate time: the server app generated everything the client reads, including the router's declaration. */
49
+ export async function checkServer(ctx: FileCtx, server: string): Promise<void> {
50
+ await readServerManifest(ctx, server);
51
+ for (const file of [SERVER_SCHEMA, SERVER_ROUTER_TYPES]) {
52
+ if (!(await ctx.fileExists(posix.join(posix.normalize(server), file)))) {
53
+ throw new Error(
54
+ `api: \`server: "${server}"\` has no ${file}. Run \`slotform generate\` in ${posix.normalize(server)} first.`,
55
+ );
56
+ }
57
+ }
58
+ }
59
+
60
+ /** `.slotform/server.ts` of a client app: the server's `AppRouter` type, re-exported type-only from the declaration the server's `tsc -b` emits, so no server code enters the bundle and the app never type-checks the server's sources. */
61
+ export function serverTypesSource(server: string): string {
62
+ return [
63
+ "// Generated by @slotform/api. Do not edit.",
64
+ `export type { AppRouter } from ${JSON.stringify(`../${posix.normalize(server)}/${SERVER_ROUTER_TYPES.replace(/\.d\.ts$/, "")}`)};`,
65
+ "",
66
+ ].join("\n");
67
+ }
@@ -0,0 +1,64 @@
1
+ import { GENERATED_DIR } from "@slotform/cli";
2
+ import type { TsExpression, TsImportSpec } from "@slotform/cli/ast";
3
+
4
+ // The generated files: docs/architecture/plugins/api.md, "Generated files".
5
+ export const WORKER_FILE = `${GENERATED_DIR}/worker.ts`;
6
+ export const PROCEDURE_FILE = `${GENERATED_DIR}/procedure.ts`;
7
+
8
+ // The route barrel: docs/architecture/plugins/api.md, "Routes barrel".
9
+ export const ROUTES_DIR = "src/worker/routes";
10
+ export const ROUTES_BARREL = `${ROUTES_DIR}/index.ts`;
11
+
12
+ // How a file generated into `.slotform/` imports a consumer source file.
13
+ export function importSource(file: string): string {
14
+ return `../${file}`;
15
+ }
16
+
17
+ export const ROUTES_BARREL_IMPORT_SOURCE = importSource(ROUTES_BARREL);
18
+
19
+ // A plugin's runtime contribution to the worker chain. Captured structurally
20
+ // so the worker derivation can attach callbacks and render options uniformly.
21
+ //
22
+ // `options` is keyed (insertion-ordered) so contributors can construct them
23
+ // without caring about rendering order; the aggregator emits one `{ key: value }`
24
+ // entry per pair.
25
+ export interface PluginRuntimeEntry {
26
+ plugin: string;
27
+ // Runtime package import. Must be a `default` import (the factory is the
28
+ // default export of `@slotform/<name>/runtime` by convention).
29
+ import: TsImportSpec;
30
+ // Identifier used as the call callee. Derived from `import.default`; kept
31
+ // explicit so the aggregator doesn't re-narrow the import union.
32
+ identifier: string;
33
+ options: Record<string, TsExpression>;
34
+ }
35
+
36
+ // Callback attachment: docs/architecture/plugins/api.md, "Callbacks".
37
+ export interface CallbackSpec {
38
+ import: TsImportSpec;
39
+ identifier: string;
40
+ }
41
+
42
+ // The input type of the `aggregateWorker` pure function.
43
+ export interface WorkerPayload {
44
+ imports: TsImportSpec[];
45
+ base: TsExpression;
46
+ pluginRuntimes: PluginRuntimeEntry[];
47
+ middlewareChain: MiddlewareCall[];
48
+ handler: { identifier: string } | null;
49
+ // `src/worker/mcp.ts`'s default export and the server name, passed to
50
+ // `.handler(routes, { mcp, name })`; null without the file.
51
+ mcp: { identifier: string; name: string } | null;
52
+ // `src/worker/queue.ts` and `src/worker/scheduled.ts`'s default exports,
53
+ // passed as `queue` and `scheduled` beside `mcp`; null without the file.
54
+ queue: { identifier: string } | null;
55
+ scheduled: { identifier: string } | null;
56
+ // Keyed by plugin name, matching `PluginRuntimeEntry.plugin`.
57
+ callbacks: Record<string, CallbackSpec>;
58
+ }
59
+
60
+ // A middleware call and the builder method that mounts it: docs/architecture/runtime.md, "Middleware".
61
+ export interface MiddlewareCall {
62
+ call: TsExpression;
63
+ method: "use" | "useAfterContext";
64
+ }
@@ -0,0 +1,6 @@
1
+ import { ORPCError } from "@orpc/client";
2
+
3
+ // Not found: docs/architecture/plugins/api.md, "Not found".
4
+ export function isNotFound(error: unknown): boolean {
5
+ return error instanceof ORPCError && error.code === "NOT_FOUND";
6
+ }