@temps-sdk/plugin 0.1.0-beta.1 → 0.1.0-beta.3

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 (58) hide show
  1. package/README.md +43 -117
  2. package/dist/ai.d.ts +32 -0
  3. package/dist/ai.d.ts.map +1 -0
  4. package/dist/ai.js +38 -0
  5. package/dist/ai.js.map +1 -0
  6. package/dist/client.d.ts +41 -10
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +146 -89
  9. package/dist/client.js.map +1 -1
  10. package/dist/context.d.ts +21 -12
  11. package/dist/context.d.ts.map +1 -1
  12. package/dist/context.js +25 -36
  13. package/dist/context.js.map +1 -1
  14. package/dist/errors.d.ts +0 -23
  15. package/dist/errors.d.ts.map +1 -1
  16. package/dist/errors.js +0 -46
  17. package/dist/errors.js.map +1 -1
  18. package/dist/index.d.ts +38 -8
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +43 -6
  21. package/dist/index.js.map +1 -1
  22. package/dist/launch.d.ts +9 -0
  23. package/dist/launch.d.ts.map +1 -0
  24. package/dist/launch.js +96 -0
  25. package/dist/launch.js.map +1 -0
  26. package/dist/manifest-builder.d.ts +4 -9
  27. package/dist/manifest-builder.d.ts.map +1 -1
  28. package/dist/manifest-builder.js +7 -26
  29. package/dist/manifest-builder.js.map +1 -1
  30. package/dist/protocol.d.ts +28 -14
  31. package/dist/protocol.d.ts.map +1 -1
  32. package/dist/protocol.js +50 -94
  33. package/dist/protocol.js.map +1 -1
  34. package/dist/runtime.d.ts +21 -12
  35. package/dist/runtime.d.ts.map +1 -1
  36. package/dist/runtime.js +318 -426
  37. package/dist/runtime.js.map +1 -1
  38. package/dist/tools.d.ts +22 -0
  39. package/dist/tools.d.ts.map +1 -0
  40. package/dist/tools.js +239 -0
  41. package/dist/tools.js.map +1 -0
  42. package/dist/types.d.ts +149 -150
  43. package/dist/types.d.ts.map +1 -1
  44. package/dist/types.js +1 -4
  45. package/dist/types.js.map +1 -1
  46. package/dist/ui.d.ts.map +1 -1
  47. package/dist/ui.js +7 -26
  48. package/dist/ui.js.map +1 -1
  49. package/package.json +21 -22
  50. package/LICENSE +0 -21
  51. package/dist/api.d.ts +0 -33
  52. package/dist/api.d.ts.map +0 -1
  53. package/dist/api.js +0 -96
  54. package/dist/api.js.map +0 -1
  55. package/dist/auth.d.ts +0 -41
  56. package/dist/auth.d.ts.map +0 -1
  57. package/dist/auth.js +0 -102
  58. package/dist/auth.js.map +0 -1
package/dist/runtime.js CHANGED
@@ -1,511 +1,403 @@
1
1
  // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
2
  // SPDX-License-Identifier: MIT OR Apache-2.0
3
- import { chmodSync, existsSync, mkdirSync, unlinkSync } from "node:fs";
3
+ import { Readable } from "node:stream";
4
+ /**
5
+ * Plugin runtime -- handles the full lifecycle of a Temps external plugin.
6
+ *
7
+ * Mirrors: crates/temps-plugin-sdk/src/runtime.rs
8
+ *
9
+ * Built for Bun -- compiled to a single binary via `bun build --compile`.
10
+ *
11
+ * Lifecycle:
12
+ * 1. Parse non-secret CLI arguments (--socket-path, --data-dir)
13
+ * 2. Emit protocol-2 hello and receive private launch configuration on stdin
14
+ * 3. Start Bun.serve on Unix domain socket
15
+ * 4. Emit ready to stdout (handshake phase 2)
16
+ * 5. Accept WebSocket connection from host on /_temps/channel
17
+ * 6. Create PluginContext with TempsClient
18
+ * 7. Call plugin.onStart()
19
+ * 8. Serve plugin routes, health, events, and embedded UI
20
+ * 9. Handle SIGTERM for graceful shutdown
21
+ */
22
+ import { existsSync, mkdirSync, unlinkSync } from "node:fs";
4
23
  import { dirname } from "node:path";
5
- import { attachVerifiedCaller, verifyProxyHeaders, } from "./auth.js";
6
24
  import { TempsClient } from "./client.js";
7
25
  import { PluginContext } from "./context.js";
8
- import { ArgsError, InitializationError, RequestBodyTooLargeError, ResponseBodyTooLargeError, } from "./errors.js";
9
- import { emitHello, emitReady, PLUGIN_CHANNEL_PATH, PLUGIN_EVENTS_PATH, readLaunchConfig, } from "./protocol.js";
10
- import { MAX_PLUGIN_REQUEST_BODY_BYTES, MAX_PLUGIN_RESPONSE_BODY_BYTES, } from "./types.js";
11
- import { createEmbeddedUiHandler, createUiHandler } from "./ui.js";
12
- const CHANNEL_TIMEOUT_MS = 30_000;
13
- /** Run a TypeScript Temps plugin under Bun or as a Bun-compiled executable. */
26
+ import { emitManifest, emitReady, PLUGIN_CHANNEL_PATH, extractAuthContext, } from "./protocol.js";
27
+ import { createEmbeddedUiHandler } from "./ui.js";
28
+ import { ArgsError, InitializationError } from "./errors.js";
29
+ import { readLaunchConfig, authenticatedHostRequest, requiresHostAuthentication, validateHealthPath, } from "./launch.js";
30
+ /**
31
+ * Run a Temps plugin. This is the main entry point.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * import { runPlugin, createManifest } from "@temps-sdk/plugin";
36
+ *
37
+ * runPlugin({
38
+ * manifest: () => createManifest("my-plugin", "0.1.0")
39
+ * .displayName("My Plugin")
40
+ * .addNav("Dashboard", "layout-dashboard", "/dashboard")
41
+ * .build(),
42
+ *
43
+ * handler: (ctx) => async (req, res) => {
44
+ * res.writeHead(200, { "Content-Type": "application/json" });
45
+ * res.end(JSON.stringify({ hello: "world" }));
46
+ * },
47
+ * });
48
+ * ```
49
+ */
14
50
  export async function runPlugin(plugin) {
15
- const args = parsePluginArgs(process.argv.slice(2));
16
- const manifest = plugin.manifest();
17
- validateManifest(manifest.name, manifest.health_path);
18
- // Stage 1: identify the protocol and requested privileges before receiving secrets.
19
- emitHello(manifest);
20
- const launch = await readLaunchConfig(manifest);
51
+ // 1. Parse CLI arguments
52
+ const args = parseArgs(process.argv.slice(2));
53
+ // Ensure data directory exists
21
54
  mkdirSync(args.dataDir, { recursive: true });
22
- mkdirSync(dirname(args.socketPath), { recursive: true });
23
- removeSocket(args.socketPath);
55
+ const manifest = plugin.manifest();
56
+ validateHealthPath(manifest.health_path, manifest.name);
57
+ // 2. Emit manifest (handshake phase 1)
58
+ emitManifest(manifest);
59
+ const launch = await readLaunchConfig(Bun.stdin.stream(), manifest.name);
60
+ // Ensure socket directory exists and clean up stale socket
61
+ const socketDir = dirname(args.socketPath);
62
+ mkdirSync(socketDir, { recursive: true });
63
+ if (existsSync(args.socketPath)) {
64
+ unlinkSync(args.socketPath);
65
+ }
66
+ // Channel connection promise -- resolved when the host connects
24
67
  let resolveChannel;
25
- let rejectChannel;
26
- const channelReady = new Promise((resolve, reject) => {
68
+ const channelReady = new Promise((resolve) => {
27
69
  resolveChannel = resolve;
28
- rejectChannel = reject;
29
70
  });
30
- const messageListeners = new Map();
31
- const closeListeners = new Map();
32
- const errorListeners = new Map();
33
- let channelClaimed = false;
71
+ // Track state
34
72
  let currentContext;
35
- let pluginFetch;
36
- let shuttingDown = false;
73
+ let pluginReady = false;
74
+ let channelAccepted = false;
75
+ // Embedded UI
37
76
  const embeddedAssets = plugin.embeddedUiAssets?.();
38
- const uiDistPath = plugin.uiDistPath?.();
77
+ const hasUi = embeddedAssets !== undefined || plugin.uiDistPath?.() !== undefined;
78
+ // Build embedded UI handler if available
39
79
  const embeddedUiHandler = embeddedAssets
40
80
  ? createEmbeddedUiHandler(embeddedAssets)
41
81
  : undefined;
42
- const filesystemUiHandler = uiDistPath ? createUiHandler(uiDistPath) : undefined;
43
- const hasUi = embeddedUiHandler !== undefined || filesystemUiHandler !== undefined;
82
+ // Active plugin fetch handler -- set once plugin is initialized
83
+ let pluginFetch;
84
+ // Bun WebSocket adapter plumbing
85
+ const wsMessageListeners = new Map();
86
+ const wsCloseListeners = new Map();
87
+ // 3. Start Bun.serve on Unix socket
44
88
  const server = Bun.serve({
45
89
  unix: args.socketPath,
46
- async fetch(request, bunServer) {
47
- const url = new URL(request.url);
90
+ fetch(req, server) {
91
+ const url = new URL(req.url);
92
+ // Health discloses no caller data. Every other route, including public
93
+ // plugin routes forwarded by Temps, must carry the host assertion.
94
+ if (requiresHostAuthentication(url.pathname, manifest.health_path) &&
95
+ !authenticatedHostRequest(req.headers, launch.auth_secret)) {
96
+ return new Response("Unauthorized", { status: 401 });
97
+ }
98
+ // WebSocket upgrade for platform channel
48
99
  if (url.pathname === PLUGIN_CHANNEL_PATH) {
49
- const verification = verifyProxyHeaders(request.headers, launch.auth_secret);
50
- if (!verification.verified) {
51
- log("warn", "Rejected unauthenticated platform channel attempt", {
52
- plugin: manifest.name,
53
- });
54
- return new Response("Unauthorized", { status: 401 });
55
- }
56
- if (channelClaimed)
100
+ if (channelAccepted)
57
101
  return new Response("Channel already connected", { status: 409 });
58
- channelClaimed = true;
59
- if (bunServer.upgrade(request))
102
+ if (server.upgrade(req)) {
103
+ channelAccepted = true;
60
104
  return undefined;
61
- channelClaimed = false;
105
+ }
62
106
  return new Response("WebSocket upgrade failed", { status: 500 });
63
107
  }
64
- // Health remains available before channel initialization, matching the Rust SDK.
65
- if (url.pathname === manifest.health_path) {
108
+ // Health endpoint -- always available
109
+ if (url.pathname === manifest.health_path || url.pathname === "/health") {
66
110
  return Response.json({ status: "ok", plugin: manifest.name });
67
111
  }
68
- if (!pluginFetch || !currentContext) {
112
+ // Event delivery endpoint
113
+ if (url.pathname === "/_events" && req.method === "POST") {
114
+ return handleEventDelivery(req, plugin, currentContext);
115
+ }
116
+ // Not initialized yet
117
+ if (!pluginReady || !pluginFetch) {
69
118
  return new Response("Plugin initializing", { status: 503 });
70
119
  }
71
- if (manifest.events.length > 0 &&
72
- url.pathname === PLUGIN_EVENTS_PATH &&
73
- request.method === "POST") {
74
- const verification = verifyProxyHeaders(request.headers, launch.auth_secret);
75
- if (!verification.verified)
76
- return authenticationRequired();
77
- return handleEventDelivery(request, plugin, currentContext);
120
+ // Try embedded UI
121
+ if (embeddedUiHandler) {
122
+ const uiResponse = handleEmbeddedUi(url, embeddedAssets);
123
+ if (uiResponse)
124
+ return uiResponse;
78
125
  }
79
- const verification = verifyProxyHeaders(request.headers, launch.auth_secret);
80
- if (!verification.verified)
81
- return authenticationRequired();
82
- return pluginFetch(request, verification.caller);
126
+ // Delegate to plugin
127
+ return pluginFetch(req);
83
128
  },
84
129
  websocket: {
85
- open(socket) {
86
- messageListeners.set(socket, new Set());
87
- closeListeners.set(socket, new Set());
88
- errorListeners.set(socket, new Set());
89
- resolveChannel?.(new TempsClient(createWsAdapter(socket, messageListeners, closeListeners, errorListeners)));
90
- resolveChannel = undefined;
91
- rejectChannel = undefined;
130
+ open(ws) {
131
+ wsMessageListeners.set(ws, new Set());
132
+ wsCloseListeners.set(ws, new Set());
133
+ const adapter = createWsAdapter(ws, wsMessageListeners, wsCloseListeners);
134
+ const client = new TempsClient(adapter);
135
+ resolveChannel?.(client);
92
136
  },
93
- message(socket, message) {
94
- for (const listener of messageListeners.get(socket) ?? [])
95
- listener(message);
137
+ message(ws, message) {
138
+ const msgStr = typeof message === "string" ? message : message.toString();
139
+ const listeners = wsMessageListeners.get(ws);
140
+ if (listeners) {
141
+ for (const fn of listeners)
142
+ fn(msgStr);
143
+ }
96
144
  },
97
- close(socket) {
98
- for (const listener of closeListeners.get(socket) ?? [])
99
- listener();
100
- messageListeners.delete(socket);
101
- closeListeners.delete(socket);
102
- errorListeners.delete(socket);
145
+ close(ws) {
146
+ const listeners = wsCloseListeners.get(ws);
147
+ if (listeners) {
148
+ for (const fn of listeners)
149
+ fn();
150
+ }
151
+ wsMessageListeners.delete(ws);
152
+ wsCloseListeners.delete(ws);
103
153
  },
104
154
  },
105
155
  });
156
+ // 4. Emit ready (handshake phase 2)
157
+ emitReady(hasUi, plugin.openapi?.());
158
+ // 5. Wait for the host to connect via WebSocket channel (with timeout)
159
+ const channelTimeoutMs = 30_000;
160
+ let client;
106
161
  try {
107
- chmodSync(args.socketPath, 0o600);
108
- // Stage 2: only report ready after the socket is bound.
109
- emitReady({ hasUi, openapi: plugin.openapiSchema?.() });
110
- const client = await withTimeout(channelReady, CHANNEL_TIMEOUT_MS, new InitializationError(manifest.name, `Platform channel connection timed out after ${CHANNEL_TIMEOUT_MS}ms`));
111
- const context = new PluginContext({
112
- pluginName: manifest.name,
113
- dataDir: args.dataDir,
114
- databaseUrl: launch.database_url ?? undefined,
115
- hostDataDir: launch.host_data_dir ?? undefined,
116
- hostApiUrl: args.hostApiUrl,
117
- authSecret: launch.auth_secret,
118
- client,
119
- });
120
- currentContext = context;
121
- client.onEvent(async (event) => {
122
- try {
123
- await plugin.onEvent?.(context, event);
124
- }
125
- catch (error) {
126
- log("error", "Plugin event handler failed", {
127
- plugin: manifest.name,
128
- event_type: event.event_type,
129
- reason: errorMessage(error),
130
- });
131
- }
162
+ client = await Promise.race([
163
+ channelReady,
164
+ new Promise((_, reject) => setTimeout(() => reject(new Error("Channel connection timeout")), channelTimeoutMs)),
165
+ ]);
166
+ }
167
+ catch {
168
+ console.error("[temps-plugin] Warning: platform channel not connected, running without platform data access");
169
+ client = null;
170
+ }
171
+ // 6. Create PluginContext
172
+ const ctx = new PluginContext({
173
+ pluginName: manifest.name,
174
+ dataDir: args.dataDir,
175
+ authSecret: launch.auth_secret,
176
+ client,
177
+ });
178
+ currentContext = ctx;
179
+ if (client) {
180
+ client.onEvent((event) => {
181
+ plugin.onEvent?.(ctx, event);
132
182
  });
183
+ }
184
+ // 7. Call plugin.onStart()
185
+ try {
186
+ await plugin.onStart?.(ctx);
187
+ }
188
+ catch (err) {
189
+ throw new InitializationError(manifest.name, err instanceof Error ? err.message : String(err));
190
+ }
191
+ // 8. Mount the plugin handler
192
+ const nodeHandler = await plugin.handler(ctx);
193
+ // Wrap the Node-style (req, res) handler into a Bun fetch handler
194
+ pluginFetch = (req) => nodeRequestBridge(req, nodeHandler);
195
+ pluginReady = true;
196
+ // 9. Graceful shutdown
197
+ const shutdown = async () => {
198
+ console.error(`[temps-plugin] Shutting down ${manifest.name}...`);
133
199
  try {
134
- await plugin.onStart?.(context);
200
+ await plugin.onShutdown?.();
135
201
  }
136
- catch (error) {
137
- throw new InitializationError(manifest.name, errorMessage(error));
202
+ catch (err) {
203
+ console.error("[temps-plugin] Error during shutdown:", err);
138
204
  }
139
- const handler = await plugin.handler(context);
140
- pluginFetch = (request, caller) => nodeRequestBridge(request, handler, caller, manifest.name, [
141
- embeddedUiHandler,
142
- filesystemUiHandler,
143
- ]);
144
- const shutdown = async (signal) => {
145
- if (shuttingDown)
146
- return;
147
- shuttingDown = true;
148
- log("info", "Shutting down plugin", { plugin: manifest.name, signal });
205
+ client?.close();
206
+ server.stop();
207
+ if (existsSync(args.socketPath)) {
149
208
  try {
150
- await plugin.onShutdown?.();
209
+ unlinkSync(args.socketPath);
151
210
  }
152
- catch (error) {
153
- log("error", "Plugin shutdown hook failed", {
154
- plugin: manifest.name,
155
- reason: errorMessage(error),
156
- });
211
+ catch {
212
+ /* ignore */
157
213
  }
158
- client.close();
159
- server.stop(true);
160
- removeSocket(args.socketPath);
161
- };
162
- process.once("SIGTERM", () => void shutdown("SIGTERM"));
163
- process.once("SIGINT", () => void shutdown("SIGINT"));
164
- log("info", "Plugin fully initialized", {
165
- plugin: manifest.name,
166
- version: manifest.version,
167
- socket_path: args.socketPath,
214
+ }
215
+ process.exit(0);
216
+ };
217
+ process.on("SIGTERM", shutdown);
218
+ process.on("SIGINT", shutdown);
219
+ console.error(`[temps-plugin] ${manifest.display_name ?? manifest.name} v${manifest.version} running on ${args.socketPath}`);
220
+ }
221
+ // ---------------------------------------------------------------------------
222
+ // Embedded UI serving (pure Bun Response)
223
+ // ---------------------------------------------------------------------------
224
+ function handleEmbeddedUi(url, assets) {
225
+ const pathname = url.pathname;
226
+ // Redirect /ui to /ui/
227
+ if (pathname === "/ui") {
228
+ return new Response(null, {
229
+ status: 302,
230
+ headers: { Location: "/ui/" },
168
231
  });
169
232
  }
170
- catch (error) {
171
- rejectChannel?.(error instanceof Error ? error : new Error(String(error)));
172
- server.stop(true);
173
- removeSocket(args.socketPath);
174
- throw error;
233
+ if (!pathname.startsWith("/ui/")) {
234
+ return undefined;
175
235
  }
176
- }
177
- export function parsePluginArgs(argv) {
178
- const values = new Map();
179
- const supported = new Set(["--socket-path", "--data-dir", "--host-api-url"]);
180
- for (let index = 0; index < argv.length; index += 2) {
181
- const flag = argv[index];
182
- const value = argv[index + 1];
183
- if (!flag || !supported.has(flag)) {
184
- throw new ArgsError(`unexpected argument: ${flag ?? "<missing>"}`);
185
- }
186
- if (!value || value.startsWith("--")) {
187
- throw new ArgsError(`${flag} requires a value`);
236
+ const relativePath = pathname.slice("/ui/".length) || "index.html";
237
+ if (relativePath.includes("..")) {
238
+ return new Response("Forbidden", { status: 403 });
239
+ }
240
+ // Exact match
241
+ const file = assets.get(relativePath);
242
+ if (file) {
243
+ return new Response(new Uint8Array(file.content), {
244
+ headers: {
245
+ "Content-Type": file.contentType,
246
+ "Content-Length": String(file.content.byteLength),
247
+ "Cache-Control": file.immutable
248
+ ? "public, max-age=31536000, immutable"
249
+ : "no-cache, no-store, must-revalidate",
250
+ },
251
+ });
252
+ }
253
+ // SPA fallback for paths without file extensions
254
+ const hasExt = (relativePath.split("/").pop() ?? "").includes(".");
255
+ if (!hasExt) {
256
+ const index = assets.get("index.html");
257
+ if (index) {
258
+ return new Response(new Uint8Array(index.content), {
259
+ headers: {
260
+ "Content-Type": index.contentType,
261
+ "Content-Length": String(index.content.byteLength),
262
+ "Cache-Control": "no-cache, no-store, must-revalidate",
263
+ },
264
+ });
188
265
  }
189
- values.set(flag, value);
190
266
  }
191
- const socketPath = values.get("--socket-path");
192
- const dataDir = values.get("--data-dir");
193
- if (!socketPath)
194
- throw new ArgsError("--socket-path is required");
195
- if (!dataDir)
196
- throw new ArgsError("--data-dir is required");
197
- return {
198
- socketPath,
199
- dataDir,
200
- ...(values.has("--host-api-url")
201
- ? { hostApiUrl: values.get("--host-api-url") }
202
- : {}),
203
- };
267
+ return new Response("Not Found", { status: 404 });
204
268
  }
205
- function createWsAdapter(socket, messageListeners, closeListeners, errorListeners) {
269
+ // ---------------------------------------------------------------------------
270
+ // Bun WebSocket -> WsLike adapter
271
+ // ---------------------------------------------------------------------------
272
+ function createWsAdapter(ws, messageListeners, closeListeners) {
206
273
  return {
207
- on(event, listener) {
274
+ on(event, fn) {
208
275
  if (event === "message") {
209
- messageListeners.get(socket)?.add(listener);
276
+ messageListeners.get(ws)?.add(fn);
210
277
  }
211
- if (event === "close") {
212
- closeListeners.get(socket)?.add(listener);
213
- }
214
- if (event === "error") {
215
- errorListeners.get(socket)?.add(listener);
278
+ else if (event === "close") {
279
+ closeListeners.get(ws)?.add(fn);
216
280
  }
217
281
  },
218
- send(data, callback) {
282
+ send(data, cb) {
219
283
  try {
220
- socket.send(data);
221
- callback?.();
284
+ ws.send(data);
285
+ cb?.();
222
286
  }
223
- catch (error) {
224
- callback?.(error instanceof Error ? error : new Error(String(error)));
287
+ catch (err) {
288
+ cb?.(err);
225
289
  }
226
290
  },
227
291
  close() {
228
- socket.close();
292
+ ws.close();
229
293
  },
230
294
  };
231
295
  }
232
- async function nodeRequestBridge(request, handler, caller, pluginName, uiHandlers) {
233
- const url = new URL(request.url);
234
- let body;
235
- try {
236
- body = await readRequestBody(request);
237
- }
238
- catch (error) {
239
- if (error instanceof RequestBodyTooLargeError)
240
- return payloadTooLarge(error);
241
- throw error;
242
- }
296
+ async function nodeRequestBridge(req, handler) {
297
+ const url = new URL(req.url);
243
298
  return new Promise((resolve) => {
244
- const incoming = Object.create(null);
245
- incoming.url = `${url.pathname}${url.search}`;
246
- incoming.method = request.method;
247
- const incomingHeaders = {};
248
- request.headers.forEach((value, name) => {
249
- incomingHeaders[name] = value;
250
- });
251
- incoming.headers = incomingHeaders;
252
- attachVerifiedCaller(incoming, caller);
253
- const dataListeners = [];
254
- const endListeners = [];
255
- incoming.on = ((event, listener) => {
256
- if (event === "data")
257
- dataListeners.push(listener);
258
- if (event === "end")
259
- endListeners.push(listener);
260
- return incoming;
261
- });
262
- let status = 200;
263
- let ended = false;
264
- const headers = {};
265
- const responseBody = new ResponseBodyAccumulator();
266
- const response = Object.create(null);
267
- const failOversizedResponse = (error) => {
268
- if (ended)
299
+ // A real readable supports both event-based plugins and async iteration.
300
+ const fakeReq = Readable.from((async function* () {
301
+ const reader = req.body?.getReader();
302
+ if (!reader)
269
303
  return;
270
- ended = true;
271
- log("error", "Plugin response exceeded the runtime body limit", {
272
- plugin: pluginName,
273
- actual_bytes: error.actualBytes,
274
- maximum_bytes: error.maximumBytes,
275
- });
276
- resolve(responseTooLarge(error));
277
- };
278
- Object.defineProperty(response, "statusCode", {
279
- get: () => status,
280
- set: (value) => {
281
- status = value;
282
- },
283
- });
284
- response.setHeader = ((name, value) => {
285
- headers[name] = Array.isArray(value) ? value.join(", ") : String(value);
286
- return response;
287
- });
288
- response.getHeader = ((name) => headers[name]);
289
- response.writeHead = ((code, values) => {
290
- status = code;
291
- if (values)
292
- Object.assign(headers, values);
293
- return response;
294
- });
295
- response.write = ((value) => {
296
- if (ended)
297
- return false;
298
304
  try {
299
- responseBody.append(value);
300
- return true;
301
- }
302
- catch (error) {
303
- if (error instanceof ResponseBodyTooLargeError) {
304
- failOversizedResponse(error);
305
- return false;
305
+ while (true) {
306
+ const { done, value } = await reader.read();
307
+ if (done)
308
+ break;
309
+ yield Buffer.from(value);
306
310
  }
307
- throw error;
308
311
  }
309
- });
310
- response.end = ((value) => {
311
- if (ended)
312
- return response;
313
- try {
314
- if (value)
315
- responseBody.append(value);
316
- }
317
- catch (error) {
318
- if (error instanceof ResponseBodyTooLargeError) {
319
- failOversizedResponse(error);
320
- return response;
321
- }
322
- throw error;
312
+ finally {
313
+ reader.releaseLock();
323
314
  }
324
- ended = true;
325
- const body = responseBody.toBuffer();
326
- resolve(new Response(body.length === 0 ? null : body, {
327
- status,
328
- headers,
315
+ })());
316
+ fakeReq.url = url.pathname + url.search;
317
+ fakeReq.method = req.method;
318
+ fakeReq.headers = {};
319
+ req.headers.forEach((value, name) => {
320
+ fakeReq.headers[name] = value;
321
+ });
322
+ fakeReq.on("error", () => resolve(new Response("Plugin request failed", { status: 500 })));
323
+ // Response collector shim
324
+ let statusCode = 200;
325
+ const resHeaders = {};
326
+ const chunks = [];
327
+ const fakeRes = Object.create(null);
328
+ fakeRes.writeHead = ((code, h) => {
329
+ statusCode = code;
330
+ if (h)
331
+ Object.assign(resHeaders, h);
332
+ return fakeRes;
333
+ });
334
+ fakeRes.end = ((data) => {
335
+ if (data)
336
+ chunks.push(typeof data === "string" ? Buffer.from(data) : data);
337
+ const body = Buffer.concat(chunks);
338
+ resolve(new Response(body.length > 0 ? body : null, {
339
+ status: statusCode,
340
+ headers: resHeaders,
329
341
  }));
330
- return response;
331
342
  });
332
- const uiHandled = uiHandlers.some((uiHandler) => uiHandler?.(incoming, response));
333
- if (!uiHandled) {
334
- void Promise.resolve(handler(incoming, response)).catch((error) => {
335
- if (ended)
336
- return;
337
- log("error", "Plugin request handler failed", {
338
- plugin: pluginName,
339
- reason: errorMessage(error),
340
- });
341
- status = 500;
342
- headers["Content-Type"] = "application/problem+json";
343
- response.end(JSON.stringify({
344
- type: "https://temps.sh/problems/plugin-handler-failed",
345
- title: "Plugin Handler Failed",
346
- status: 500,
347
- detail: "The plugin could not complete this request.",
348
- }));
349
- });
350
- }
351
- queueMicrotask(() => {
352
- if (body.length > 0)
353
- for (const listener of dataListeners)
354
- listener(body);
355
- for (const listener of endListeners)
356
- listener();
343
+ fakeRes.write = ((data) => {
344
+ chunks.push(typeof data === "string" ? Buffer.from(data) : data);
345
+ return true;
346
+ });
347
+ // Catch asynchronous plugin failures as well as synchronous exceptions.
348
+ Promise.resolve()
349
+ .then(() => handler(fakeReq, fakeRes))
350
+ .catch(() => {
351
+ resolve(new Response("Plugin handler failed", { status: 500 }));
357
352
  });
358
353
  });
359
354
  }
360
- async function handleEventDelivery(request, plugin, context) {
361
- let event;
355
+ // ---------------------------------------------------------------------------
356
+ // Event delivery handler (POST /_events)
357
+ // ---------------------------------------------------------------------------
358
+ async function handleEventDelivery(req, plugin, ctx) {
362
359
  try {
363
- const body = await readRequestBody(request);
364
- event = JSON.parse(body.toString("utf8"));
365
- if (typeof event.id !== "string" ||
366
- typeof event.event_type !== "string" ||
367
- typeof event.timestamp !== "string" ||
368
- typeof event.data !== "object" ||
369
- event.data === null) {
370
- throw new Error("event is missing required fields");
360
+ const event = (await req.json());
361
+ if (ctx) {
362
+ plugin.onEvent?.(ctx, event);
371
363
  }
364
+ return Response.json({ ok: true });
372
365
  }
373
- catch (error) {
374
- if (error instanceof RequestBodyTooLargeError)
375
- return payloadTooLarge(error);
366
+ catch (err) {
376
367
  return Response.json({
377
- type: "https://temps.sh/problems/plugin-event-invalid",
378
- title: "Invalid Plugin Event",
379
- status: 400,
380
- detail: "The event payload is not valid.",
368
+ error: "Invalid event payload",
369
+ detail: err instanceof Error ? err.message : String(err),
381
370
  }, { status: 400 });
382
371
  }
383
- try {
384
- await plugin.onEvent?.(context, event);
385
- return new Response(null, { status: 200 });
386
- }
387
- catch (error) {
388
- log("error", "Plugin event handler failed", {
389
- plugin: context.pluginName,
390
- event_type: event.event_type,
391
- reason: errorMessage(error),
392
- });
393
- return Response.json({
394
- type: "https://temps.sh/problems/plugin-event-handler-failed",
395
- title: "Plugin Event Handler Failed",
396
- status: 500,
397
- detail: "The plugin could not process this event.",
398
- }, { status: 500 });
399
- }
400
372
  }
401
- /** @internal Read a plugin request without allowing unbounded process memory growth. */
402
- export async function readRequestBody(request, maximumBytes = MAX_PLUGIN_REQUEST_BODY_BYTES) {
403
- const declaredLength = request.headers.get("content-length");
404
- if (declaredLength !== null) {
405
- const parsedLength = Number(declaredLength);
406
- if (Number.isFinite(parsedLength) && parsedLength > maximumBytes) {
407
- throw new RequestBodyTooLargeError(parsedLength, maximumBytes);
373
+ // ---------------------------------------------------------------------------
374
+ // CLI argument parsing
375
+ // ---------------------------------------------------------------------------
376
+ function parseArgs(argv) {
377
+ const args = {};
378
+ for (let i = 0; i < argv.length; i++) {
379
+ const arg = argv[i];
380
+ const next = argv[i + 1];
381
+ switch (arg) {
382
+ case "--socket-path":
383
+ args.socketPath = next;
384
+ i++;
385
+ break;
386
+ case "--database-url":
387
+ case "--auth-secret":
388
+ throw new ArgsError("Privileged launch values must arrive over the protocol 2 stdin handshake; update Temps");
389
+ case "--data-dir":
390
+ args.dataDir = next;
391
+ i++;
392
+ break;
408
393
  }
409
394
  }
410
- if (!request.body)
411
- return Buffer.alloc(0);
412
- const reader = request.body.getReader();
413
- const chunks = [];
414
- let totalBytes = 0;
415
- while (true) {
416
- const { done, value } = await reader.read();
417
- if (done)
418
- break;
419
- totalBytes += value.byteLength;
420
- if (totalBytes > maximumBytes) {
421
- await reader.cancel("plugin request body limit exceeded");
422
- throw new RequestBodyTooLargeError(totalBytes, maximumBytes);
423
- }
424
- chunks.push(Buffer.from(value));
425
- }
426
- return Buffer.concat(chunks, totalBytes);
427
- }
428
- /** @internal Bounded response collector used by the Node-compatible bridge. */
429
- export class ResponseBodyAccumulator {
430
- #maximumBytes;
431
- #chunks = [];
432
- #totalBytes = 0;
433
- constructor(maximumBytes = MAX_PLUGIN_RESPONSE_BODY_BYTES) {
434
- this.#maximumBytes = maximumBytes;
435
- }
436
- append(value) {
437
- const chunk = typeof value === "string" ? Buffer.from(value) : value;
438
- const nextTotal = this.#totalBytes + chunk.byteLength;
439
- if (nextTotal > this.#maximumBytes) {
440
- throw new ResponseBodyTooLargeError(nextTotal, this.#maximumBytes);
441
- }
442
- this.#chunks.push(chunk);
443
- this.#totalBytes = nextTotal;
444
- }
445
- toBuffer() {
446
- return Buffer.concat(this.#chunks, this.#totalBytes);
447
- }
448
- }
449
- function authenticationRequired() {
450
- return Response.json({
451
- type: "https://temps.sh/problems/plugin-authentication-required",
452
- title: "Authentication Required",
453
- status: 401,
454
- detail: "This plugin route requires a request asserted by Temps.",
455
- }, { status: 401, headers: { "Content-Type": "application/problem+json" } });
456
- }
457
- function payloadTooLarge(error) {
458
- return Response.json({
459
- type: "https://temps.sh/problems/plugin-request-body-too-large",
460
- title: "Plugin Request Body Too Large",
461
- status: 413,
462
- detail: error.message,
463
- maximum_bytes: error.maximumBytes,
464
- }, { status: 413, headers: { "Content-Type": "application/problem+json" } });
465
- }
466
- function responseTooLarge(error) {
467
- return Response.json({
468
- type: "https://temps.sh/problems/plugin-response-body-too-large",
469
- title: "Plugin Response Body Too Large",
470
- status: 502,
471
- detail: "The plugin produced a response larger than the runtime limit.",
472
- maximum_bytes: error.maximumBytes,
473
- }, { status: 502, headers: { "Content-Type": "application/problem+json" } });
474
- }
475
- function validateManifest(name, healthPath) {
476
- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) {
477
- throw new InitializationError(name, "Plugin name must be lowercase kebab-case");
478
- }
479
- if (!healthPath.startsWith("/") || healthPath.includes("..")) {
480
- throw new InitializationError(name, `Invalid health path: ${healthPath}`);
481
- }
482
- }
483
- function withTimeout(promise, milliseconds, error) {
484
- return new Promise((resolve, reject) => {
485
- const timer = setTimeout(() => reject(error), milliseconds);
486
- promise.then((value) => {
487
- clearTimeout(timer);
488
- resolve(value);
489
- }, (reason) => {
490
- clearTimeout(timer);
491
- reject(reason);
492
- });
493
- });
494
- }
495
- function removeSocket(path) {
496
- if (!existsSync(path))
497
- return;
498
- try {
499
- unlinkSync(path);
395
+ if (!args.socketPath) {
396
+ throw new ArgsError("--socket-path is required");
500
397
  }
501
- catch (error) {
502
- throw new InitializationError(path, `Failed to remove Unix socket: ${errorMessage(error)}`);
398
+ if (!args.dataDir) {
399
+ throw new ArgsError("--data-dir is required");
503
400
  }
504
- }
505
- function log(level, message, fields) {
506
- process.stderr.write(`${JSON.stringify({ timestamp: new Date().toISOString(), level, message, ...fields })}\n`);
507
- }
508
- function errorMessage(error) {
509
- return error instanceof Error ? error.message : String(error);
401
+ return { socketPath: args.socketPath, dataDir: args.dataDir };
510
402
  }
511
403
  //# sourceMappingURL=runtime.js.map