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

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 (54) hide show
  1. package/dist/ai.d.ts +32 -0
  2. package/dist/ai.d.ts.map +1 -0
  3. package/dist/ai.js +38 -0
  4. package/dist/ai.js.map +1 -0
  5. package/dist/client.d.ts +41 -10
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/client.js +146 -89
  8. package/dist/client.js.map +1 -1
  9. package/dist/context.d.ts +21 -12
  10. package/dist/context.d.ts.map +1 -1
  11. package/dist/context.js +25 -36
  12. package/dist/context.js.map +1 -1
  13. package/dist/errors.d.ts +0 -23
  14. package/dist/errors.d.ts.map +1 -1
  15. package/dist/errors.js +0 -46
  16. package/dist/errors.js.map +1 -1
  17. package/dist/index.d.ts +36 -8
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +42 -6
  20. package/dist/index.js.map +1 -1
  21. package/dist/launch.d.ts +9 -0
  22. package/dist/launch.d.ts.map +1 -0
  23. package/dist/launch.js +96 -0
  24. package/dist/launch.js.map +1 -0
  25. package/dist/manifest-builder.d.ts +4 -9
  26. package/dist/manifest-builder.d.ts.map +1 -1
  27. package/dist/manifest-builder.js +7 -26
  28. package/dist/manifest-builder.js.map +1 -1
  29. package/dist/protocol.d.ts +28 -14
  30. package/dist/protocol.d.ts.map +1 -1
  31. package/dist/protocol.js +49 -94
  32. package/dist/protocol.js.map +1 -1
  33. package/dist/runtime.d.ts +21 -12
  34. package/dist/runtime.d.ts.map +1 -1
  35. package/dist/runtime.js +318 -426
  36. package/dist/runtime.js.map +1 -1
  37. package/dist/types.d.ts +147 -151
  38. package/dist/types.d.ts.map +1 -1
  39. package/dist/types.js +1 -4
  40. package/dist/types.js.map +1 -1
  41. package/dist/ui.d.ts.map +1 -1
  42. package/dist/ui.js +7 -26
  43. package/dist/ui.js.map +1 -1
  44. package/package.json +10 -19
  45. package/LICENSE +0 -21
  46. package/README.md +0 -123
  47. package/dist/api.d.ts +0 -33
  48. package/dist/api.d.ts.map +0 -1
  49. package/dist/api.js +0 -96
  50. package/dist/api.js.map +0 -1
  51. package/dist/auth.d.ts +0 -41
  52. package/dist/auth.d.ts.map +0 -1
  53. package/dist/auth.js +0 -102
  54. 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
+ /**
4
+ * Plugin runtime -- handles the full lifecycle of a Temps external plugin.
5
+ *
6
+ * Mirrors: crates/temps-plugin-sdk/src/runtime.rs
7
+ *
8
+ * Built for Bun -- compiled to a single binary via `bun build --compile`.
9
+ *
10
+ * Lifecycle:
11
+ * 1. Parse non-secret CLI arguments (--socket-path, --data-dir)
12
+ * 2. Emit protocol-2 hello and receive private launch configuration on stdin
13
+ * 3. Start Bun.serve on Unix domain socket
14
+ * 4. Emit ready to stdout (handshake phase 2)
15
+ * 5. Accept WebSocket connection from host on /_temps/channel
16
+ * 6. Create PluginContext with TempsClient
17
+ * 7. Call plugin.onStart()
18
+ * 8. Serve plugin routes, health, events, and embedded UI
19
+ * 9. Handle SIGTERM for graceful shutdown
20
+ */
21
+ import { existsSync, mkdirSync, unlinkSync } from "node:fs";
4
22
  import { dirname } from "node:path";
5
- import { attachVerifiedCaller, verifyProxyHeaders, } from "./auth.js";
6
23
  import { TempsClient } from "./client.js";
7
24
  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. */
25
+ import { emitManifest, emitReady, PLUGIN_CHANNEL_PATH, extractAuthContext } from "./protocol.js";
26
+ import { createEmbeddedUiHandler } from "./ui.js";
27
+ import { ArgsError, InitializationError } from "./errors.js";
28
+ import { readLaunchConfig, authenticatedHostRequest, requiresHostAuthentication, validateHealthPath } from "./launch.js";
29
+ /**
30
+ * Run a Temps plugin. This is the main entry point.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * import { runPlugin, createManifest } from "@temps-sdk/plugin";
35
+ *
36
+ * runPlugin({
37
+ * manifest: () => createManifest("my-plugin", "0.1.0")
38
+ * .displayName("My Plugin")
39
+ * .addNav("Dashboard", "layout-dashboard", "/dashboard")
40
+ * .build(),
41
+ *
42
+ * handler: (ctx) => async (req, res) => {
43
+ * res.writeHead(200, { "Content-Type": "application/json" });
44
+ * res.end(JSON.stringify({ hello: "world" }));
45
+ * },
46
+ * });
47
+ * ```
48
+ */
14
49
  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);
50
+ // 1. Parse CLI arguments
51
+ const args = parseArgs(process.argv.slice(2));
52
+ // Ensure data directory exists
21
53
  mkdirSync(args.dataDir, { recursive: true });
22
- mkdirSync(dirname(args.socketPath), { recursive: true });
23
- removeSocket(args.socketPath);
54
+ const manifest = plugin.manifest();
55
+ validateHealthPath(manifest.health_path, manifest.name);
56
+ // 2. Emit manifest (handshake phase 1)
57
+ emitManifest(manifest);
58
+ const launch = await readLaunchConfig(Bun.stdin.stream(), manifest.name);
59
+ // Ensure socket directory exists and clean up stale socket
60
+ const socketDir = dirname(args.socketPath);
61
+ mkdirSync(socketDir, { recursive: true });
62
+ if (existsSync(args.socketPath)) {
63
+ unlinkSync(args.socketPath);
64
+ }
65
+ // Channel connection promise -- resolved when the host connects
24
66
  let resolveChannel;
25
- let rejectChannel;
26
- const channelReady = new Promise((resolve, reject) => {
67
+ const channelReady = new Promise((resolve) => {
27
68
  resolveChannel = resolve;
28
- rejectChannel = reject;
29
69
  });
30
- const messageListeners = new Map();
31
- const closeListeners = new Map();
32
- const errorListeners = new Map();
33
- let channelClaimed = false;
70
+ // Track state
34
71
  let currentContext;
35
- let pluginFetch;
36
- let shuttingDown = false;
72
+ let pluginReady = false;
73
+ let channelAccepted = false;
74
+ // Embedded UI
37
75
  const embeddedAssets = plugin.embeddedUiAssets?.();
38
- const uiDistPath = plugin.uiDistPath?.();
76
+ const hasUi = embeddedAssets !== undefined || plugin.uiDistPath?.() !== undefined;
77
+ // Build embedded UI handler if available
39
78
  const embeddedUiHandler = embeddedAssets
40
79
  ? createEmbeddedUiHandler(embeddedAssets)
41
80
  : undefined;
42
- const filesystemUiHandler = uiDistPath ? createUiHandler(uiDistPath) : undefined;
43
- const hasUi = embeddedUiHandler !== undefined || filesystemUiHandler !== undefined;
81
+ // Active plugin fetch handler -- set once plugin is initialized
82
+ let pluginFetch;
83
+ // Bun WebSocket adapter plumbing
84
+ const wsMessageListeners = new Map();
85
+ const wsCloseListeners = new Map();
86
+ // 3. Start Bun.serve on Unix socket
44
87
  const server = Bun.serve({
45
88
  unix: args.socketPath,
46
- async fetch(request, bunServer) {
47
- const url = new URL(request.url);
89
+ fetch(req, server) {
90
+ const url = new URL(req.url);
91
+ // Health discloses no caller data. Every other route, including public
92
+ // plugin routes forwarded by Temps, must carry the host assertion.
93
+ if (requiresHostAuthentication(url.pathname, manifest.health_path) &&
94
+ !authenticatedHostRequest(req.headers, launch.auth_secret)) {
95
+ return new Response("Unauthorized", { status: 401 });
96
+ }
97
+ // WebSocket upgrade for platform channel
48
98
  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)
99
+ if (channelAccepted)
57
100
  return new Response("Channel already connected", { status: 409 });
58
- channelClaimed = true;
59
- if (bunServer.upgrade(request))
101
+ if (server.upgrade(req)) {
102
+ channelAccepted = true;
60
103
  return undefined;
61
- channelClaimed = false;
104
+ }
62
105
  return new Response("WebSocket upgrade failed", { status: 500 });
63
106
  }
64
- // Health remains available before channel initialization, matching the Rust SDK.
65
- if (url.pathname === manifest.health_path) {
107
+ // Health endpoint -- always available
108
+ if (url.pathname === manifest.health_path || url.pathname === "/health") {
66
109
  return Response.json({ status: "ok", plugin: manifest.name });
67
110
  }
68
- if (!pluginFetch || !currentContext) {
111
+ // Event delivery endpoint
112
+ if (url.pathname === "/_events" && req.method === "POST") {
113
+ return handleEventDelivery(req, plugin, currentContext);
114
+ }
115
+ // Not initialized yet
116
+ if (!pluginReady || !pluginFetch) {
69
117
  return new Response("Plugin initializing", { status: 503 });
70
118
  }
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);
119
+ // Try embedded UI
120
+ if (embeddedUiHandler) {
121
+ const uiResponse = handleEmbeddedUi(url, embeddedAssets);
122
+ if (uiResponse)
123
+ return uiResponse;
78
124
  }
79
- const verification = verifyProxyHeaders(request.headers, launch.auth_secret);
80
- if (!verification.verified)
81
- return authenticationRequired();
82
- return pluginFetch(request, verification.caller);
125
+ // Delegate to plugin
126
+ return pluginFetch(req);
83
127
  },
84
128
  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;
129
+ open(ws) {
130
+ wsMessageListeners.set(ws, new Set());
131
+ wsCloseListeners.set(ws, new Set());
132
+ const adapter = createWsAdapter(ws, wsMessageListeners, wsCloseListeners);
133
+ const client = new TempsClient(adapter);
134
+ resolveChannel?.(client);
92
135
  },
93
- message(socket, message) {
94
- for (const listener of messageListeners.get(socket) ?? [])
95
- listener(message);
136
+ message(ws, message) {
137
+ const msgStr = typeof message === "string" ? message : message.toString();
138
+ const listeners = wsMessageListeners.get(ws);
139
+ if (listeners) {
140
+ for (const fn of listeners)
141
+ fn(msgStr);
142
+ }
96
143
  },
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);
144
+ close(ws) {
145
+ const listeners = wsCloseListeners.get(ws);
146
+ if (listeners) {
147
+ for (const fn of listeners)
148
+ fn();
149
+ }
150
+ wsMessageListeners.delete(ws);
151
+ wsCloseListeners.delete(ws);
103
152
  },
104
153
  },
105
154
  });
155
+ // 4. Emit ready (handshake phase 2)
156
+ emitReady(hasUi);
157
+ // 5. Wait for the host to connect via WebSocket channel (with timeout)
158
+ const channelTimeoutMs = 30_000;
159
+ let client;
106
160
  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
- }
161
+ client = await Promise.race([
162
+ channelReady,
163
+ new Promise((_, reject) => setTimeout(() => reject(new Error("Channel connection timeout")), channelTimeoutMs)),
164
+ ]);
165
+ }
166
+ catch {
167
+ console.error("[temps-plugin] Warning: platform channel not connected, running without platform data access");
168
+ client = null;
169
+ }
170
+ // 6. Create PluginContext
171
+ const ctx = new PluginContext({
172
+ pluginName: manifest.name,
173
+ dataDir: args.dataDir,
174
+ authSecret: launch.auth_secret,
175
+ client,
176
+ });
177
+ currentContext = ctx;
178
+ if (client) {
179
+ client.onEvent((event) => {
180
+ plugin.onEvent?.(ctx, event);
132
181
  });
182
+ }
183
+ // 7. Call plugin.onStart()
184
+ try {
185
+ await plugin.onStart?.(ctx);
186
+ }
187
+ catch (err) {
188
+ throw new InitializationError(manifest.name, err instanceof Error ? err.message : String(err));
189
+ }
190
+ // 8. Mount the plugin handler
191
+ const nodeHandler = await plugin.handler(ctx);
192
+ // Wrap the Node-style (req, res) handler into a Bun fetch handler
193
+ pluginFetch = (req) => nodeRequestBridge(req, nodeHandler);
194
+ pluginReady = true;
195
+ // 9. Graceful shutdown
196
+ const shutdown = async () => {
197
+ console.error(`[temps-plugin] Shutting down ${manifest.name}...`);
133
198
  try {
134
- await plugin.onStart?.(context);
199
+ await plugin.onShutdown?.();
135
200
  }
136
- catch (error) {
137
- throw new InitializationError(manifest.name, errorMessage(error));
201
+ catch (err) {
202
+ console.error("[temps-plugin] Error during shutdown:", err);
138
203
  }
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 });
204
+ client?.close();
205
+ server.stop();
206
+ if (existsSync(args.socketPath)) {
149
207
  try {
150
- await plugin.onShutdown?.();
151
- }
152
- catch (error) {
153
- log("error", "Plugin shutdown hook failed", {
154
- plugin: manifest.name,
155
- reason: errorMessage(error),
156
- });
208
+ unlinkSync(args.socketPath);
157
209
  }
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,
210
+ catch { /* ignore */ }
211
+ }
212
+ process.exit(0);
213
+ };
214
+ process.on("SIGTERM", shutdown);
215
+ process.on("SIGINT", shutdown);
216
+ console.error(`[temps-plugin] ${manifest.display_name ?? manifest.name} v${manifest.version} running on ${args.socketPath}`);
217
+ }
218
+ // ---------------------------------------------------------------------------
219
+ // Embedded UI serving (pure Bun Response)
220
+ // ---------------------------------------------------------------------------
221
+ function handleEmbeddedUi(url, assets) {
222
+ const pathname = url.pathname;
223
+ // Redirect /ui to /ui/
224
+ if (pathname === "/ui") {
225
+ return new Response(null, {
226
+ status: 302,
227
+ headers: { Location: "/ui/" },
168
228
  });
169
229
  }
170
- catch (error) {
171
- rejectChannel?.(error instanceof Error ? error : new Error(String(error)));
172
- server.stop(true);
173
- removeSocket(args.socketPath);
174
- throw error;
230
+ if (!pathname.startsWith("/ui/")) {
231
+ return undefined;
175
232
  }
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`);
233
+ const relativePath = pathname.slice("/ui/".length) || "index.html";
234
+ if (relativePath.includes("..")) {
235
+ return new Response("Forbidden", { status: 403 });
236
+ }
237
+ // Exact match
238
+ const file = assets.get(relativePath);
239
+ if (file) {
240
+ return new Response(new Uint8Array(file.content), {
241
+ headers: {
242
+ "Content-Type": file.contentType,
243
+ "Content-Length": String(file.content.byteLength),
244
+ "Cache-Control": file.immutable
245
+ ? "public, max-age=31536000, immutable"
246
+ : "no-cache, no-store, must-revalidate",
247
+ },
248
+ });
249
+ }
250
+ // SPA fallback for paths without file extensions
251
+ const hasExt = (relativePath.split("/").pop() ?? "").includes(".");
252
+ if (!hasExt) {
253
+ const index = assets.get("index.html");
254
+ if (index) {
255
+ return new Response(new Uint8Array(index.content), {
256
+ headers: {
257
+ "Content-Type": index.contentType,
258
+ "Content-Length": String(index.content.byteLength),
259
+ "Cache-Control": "no-cache, no-store, must-revalidate",
260
+ },
261
+ });
188
262
  }
189
- values.set(flag, value);
190
263
  }
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
- };
264
+ return new Response("Not Found", { status: 404 });
204
265
  }
205
- function createWsAdapter(socket, messageListeners, closeListeners, errorListeners) {
266
+ // ---------------------------------------------------------------------------
267
+ // Bun WebSocket -> WsLike adapter
268
+ // ---------------------------------------------------------------------------
269
+ function createWsAdapter(ws, messageListeners, closeListeners) {
206
270
  return {
207
- on(event, listener) {
271
+ on(event, fn) {
208
272
  if (event === "message") {
209
- messageListeners.get(socket)?.add(listener);
273
+ messageListeners.get(ws)?.add(fn);
210
274
  }
211
- if (event === "close") {
212
- closeListeners.get(socket)?.add(listener);
213
- }
214
- if (event === "error") {
215
- errorListeners.get(socket)?.add(listener);
275
+ else if (event === "close") {
276
+ closeListeners.get(ws)?.add(fn);
216
277
  }
217
278
  },
218
- send(data, callback) {
279
+ send(data, cb) {
219
280
  try {
220
- socket.send(data);
221
- callback?.();
281
+ ws.send(data);
282
+ cb?.();
222
283
  }
223
- catch (error) {
224
- callback?.(error instanceof Error ? error : new Error(String(error)));
284
+ catch (err) {
285
+ cb?.(err);
225
286
  }
226
287
  },
227
288
  close() {
228
- socket.close();
289
+ ws.close();
229
290
  },
230
291
  };
231
292
  }
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;
293
+ async function nodeRequestBridge(req, handler) {
294
+ const url = new URL(req.url);
295
+ // Read body upfront
296
+ let bodyBuffer = Buffer.alloc(0);
297
+ if (req.body) {
298
+ bodyBuffer = Buffer.from(await req.arrayBuffer());
242
299
  }
243
300
  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) => {
301
+ // Build a minimal IncomingMessage shim
302
+ const fakeReq = Object.create(null);
303
+ fakeReq.url = url.pathname + url.search;
304
+ fakeReq.method = req.method;
305
+ const hdrs = {};
306
+ req.headers.forEach((v, k) => { hdrs[k] = v; });
307
+ fakeReq.headers = hdrs;
308
+ // Body event emitter shim
309
+ const dataFns = [];
310
+ const endFns = [];
311
+ fakeReq.on = ((event, fn) => {
256
312
  if (event === "data")
257
- dataListeners.push(listener);
313
+ dataFns.push(fn);
258
314
  if (event === "end")
259
- endListeners.push(listener);
260
- return incoming;
315
+ endFns.push(fn);
316
+ return fakeReq;
261
317
  });
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)
269
- 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;
318
+ // Response collector shim
319
+ let statusCode = 200;
320
+ const resHeaders = {};
321
+ const chunks = [];
322
+ const fakeRes = Object.create(null);
323
+ fakeRes.writeHead = ((code, h) => {
324
+ statusCode = code;
325
+ if (h)
326
+ Object.assign(resHeaders, h);
327
+ return fakeRes;
294
328
  });
295
- response.write = ((value) => {
296
- if (ended)
297
- return false;
298
- try {
299
- responseBody.append(value);
300
- return true;
301
- }
302
- catch (error) {
303
- if (error instanceof ResponseBodyTooLargeError) {
304
- failOversizedResponse(error);
305
- return false;
306
- }
307
- throw error;
308
- }
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;
323
- }
324
- ended = true;
325
- const body = responseBody.toBuffer();
326
- resolve(new Response(body.length === 0 ? null : body, {
327
- status,
328
- headers,
329
+ fakeRes.end = ((data) => {
330
+ if (data)
331
+ chunks.push(typeof data === "string" ? Buffer.from(data) : data);
332
+ const body = Buffer.concat(chunks);
333
+ resolve(new Response(body.length > 0 ? body : null, {
334
+ status: statusCode,
335
+ headers: resHeaders,
329
336
  }));
330
- return response;
331
337
  });
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
- }
338
+ fakeRes.write = ((data) => {
339
+ chunks.push(typeof data === "string" ? Buffer.from(data) : data);
340
+ return true;
341
+ });
342
+ // Call the handler
343
+ handler(fakeReq, fakeRes);
344
+ // Deliver body
351
345
  queueMicrotask(() => {
352
- if (body.length > 0)
353
- for (const listener of dataListeners)
354
- listener(body);
355
- for (const listener of endListeners)
356
- listener();
346
+ if (bodyBuffer.length > 0) {
347
+ for (const fn of dataFns)
348
+ fn(bodyBuffer);
349
+ }
350
+ for (const fn of endFns)
351
+ fn();
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