@meetploy/emulator 1.20.0 → 1.22.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 (53) hide show
  1. package/dist/ai-binding.d.ts +2 -0
  2. package/dist/ai-binding.js +122 -0
  3. package/dist/ai-binding.js.map +1 -0
  4. package/dist/ai-binding.spec.d.ts +1 -0
  5. package/dist/ai-binding.spec.js +112 -0
  6. package/dist/ai-binding.spec.js.map +1 -0
  7. package/dist/bundler/bundler.js +11 -15
  8. package/dist/bundler/bundler.js.map +1 -1
  9. package/dist/dashboard-dist/assets/main-5M4qXaue.js +359 -0
  10. package/dist/dashboard-dist/index.html +1 -1
  11. package/dist/emulator.js +0 -3
  12. package/dist/emulator.js.map +1 -1
  13. package/dist/nextjs-dev.d.ts +1 -0
  14. package/dist/nextjs-dev.js +268 -13
  15. package/dist/nextjs-dev.js.map +1 -1
  16. package/dist/runtime/ai-runtime.d.ts +1 -0
  17. package/dist/runtime/ai-runtime.js +158 -0
  18. package/dist/runtime/ai-runtime.js.map +1 -0
  19. package/dist/runtime/db-runtime.spec.d.ts +1 -0
  20. package/dist/runtime/db-runtime.spec.js +147 -0
  21. package/dist/runtime/db-runtime.spec.js.map +1 -0
  22. package/dist/runtime/state-runtime.d.ts +1 -1
  23. package/dist/runtime/state-runtime.js +214 -5
  24. package/dist/runtime/state-runtime.js.map +1 -1
  25. package/dist/runtime/state-runtime.spec.d.ts +1 -0
  26. package/dist/runtime/state-runtime.spec.js +158 -0
  27. package/dist/runtime/state-runtime.spec.js.map +1 -0
  28. package/dist/services/dashboard-routes.js +0 -39
  29. package/dist/services/dashboard-routes.js.map +1 -1
  30. package/dist/services/db-service.d.ts +9 -0
  31. package/dist/services/db-service.js +23 -7
  32. package/dist/services/db-service.js.map +1 -1
  33. package/dist/services/db-service.spec.d.ts +1 -0
  34. package/dist/services/db-service.spec.js +69 -0
  35. package/dist/services/db-service.spec.js.map +1 -0
  36. package/dist/services/mock-server.js +2 -7
  37. package/dist/services/mock-server.js.map +1 -1
  38. package/dist/services/state-service.d.ts +25 -0
  39. package/dist/services/state-service.js +81 -6
  40. package/dist/services/state-service.js.map +1 -1
  41. package/dist/services/state-service.spec.d.ts +1 -0
  42. package/dist/services/state-service.spec.js +131 -0
  43. package/dist/services/state-service.spec.js.map +1 -0
  44. package/dist/utils/sqlite.js +19 -0
  45. package/dist/utils/sqlite.js.map +1 -1
  46. package/package.json +1 -1
  47. package/dist/dashboard-dist/assets/main-B6aGGsJM.js +0 -364
  48. package/dist/runtime/cache-runtime.d.ts +0 -1
  49. package/dist/runtime/cache-runtime.js +0 -54
  50. package/dist/runtime/cache-runtime.js.map +0 -1
  51. package/dist/services/cache-service.d.ts +0 -13
  52. package/dist/services/cache-service.js +0 -31
  53. package/dist/services/cache-service.js.map +0 -1
@@ -0,0 +1,158 @@
1
+ export const AI_RUNTIME_CODE = `
2
+ function __ployCreateAiErrorMessage(_status, bodyText, fallback) {
3
+ if (!bodyText) {
4
+ return fallback;
5
+ }
6
+
7
+ try {
8
+ const parsed = JSON.parse(bodyText);
9
+ if (typeof parsed?.error === "string") {
10
+ return parsed.error;
11
+ }
12
+ if (typeof parsed?.error?.message === "string") {
13
+ return parsed.error.message;
14
+ }
15
+ if (typeof parsed?.message === "string") {
16
+ return parsed.message;
17
+ }
18
+ } catch {
19
+ // Fall back to the raw text below.
20
+ }
21
+
22
+ return bodyText;
23
+ }
24
+
25
+ function __ployParseAiErrorPayload(bodyText) {
26
+ if (!bodyText) {
27
+ return undefined;
28
+ }
29
+
30
+ try {
31
+ return JSON.parse(bodyText);
32
+ } catch {
33
+ return undefined;
34
+ }
35
+ }
36
+
37
+ function __ployCreateAiRunError(status, bodyText, fallback) {
38
+ const error = new Error(__ployCreateAiErrorMessage(status, bodyText, fallback));
39
+ error.status = status;
40
+ error.bodyText = bodyText;
41
+ const payload = __ployParseAiErrorPayload(bodyText);
42
+ if (payload !== undefined) {
43
+ error.payload = payload;
44
+ }
45
+ return error;
46
+ }
47
+
48
+ function __ployNormalizeAiRunBody(model, inputs, options) {
49
+ const body = {
50
+ model,
51
+ ...inputs,
52
+ };
53
+
54
+ if ("prompt" in body && !("messages" in body)) {
55
+ body.messages = [{ role: "user", content: body.prompt }];
56
+ delete body.prompt;
57
+ }
58
+
59
+ if (options?.prefix !== undefined) {
60
+ body.prefix = options.prefix;
61
+ }
62
+
63
+ return body;
64
+ }
65
+
66
+ function __ployGetAiRunUrl(baseUrl) {
67
+ const runBaseUrl = baseUrl.replace(/\\/?v1\\/?$/, "/");
68
+ return new URL(
69
+ "run",
70
+ runBaseUrl.endsWith("/") ? runBaseUrl : runBaseUrl + "/",
71
+ ).toString();
72
+ }
73
+
74
+ function __ployGetAiExtraHeaders(options) {
75
+ return Object.fromEntries(
76
+ Object.entries(options?.extraHeaders ?? {}).filter(([key]) => {
77
+ const lowerKey = key.toLowerCase();
78
+ return lowerKey !== "authorization" && lowerKey !== "content-type";
79
+ }),
80
+ );
81
+ }
82
+
83
+ function __ployAssertSupportedAiRunOptions(options) {
84
+ if (options?.queueRequest === true) {
85
+ throw new Error("env.AI.run() does not support queueRequest in Ploy.");
86
+ }
87
+
88
+ if (options?.gateway !== undefined) {
89
+ throw new Error(
90
+ "env.AI.run() does not support gateway overrides in Ploy. Use env.AI.gateway() when available.",
91
+ );
92
+ }
93
+
94
+ if ((options?.tags?.length ?? 0) > 0) {
95
+ throw new Error("env.AI.run() does not support tags in Ploy.");
96
+ }
97
+ }
98
+
99
+ export function initializeAI(baseUrl, token) {
100
+ return {
101
+ aiGatewayLogId: null,
102
+ gateway(gatewayId) {
103
+ return {
104
+ async run() {
105
+ throw new Error(
106
+ "env.AI.gateway(" +
107
+ JSON.stringify(gatewayId) +
108
+ ").run() is not implemented in Ploy.",
109
+ );
110
+ },
111
+ };
112
+ },
113
+ async run(model, inputs, options) {
114
+ __ployAssertSupportedAiRunOptions(options);
115
+ const response = await fetch(__ployGetAiRunUrl(baseUrl), {
116
+ method: "POST",
117
+ headers: {
118
+ ...__ployGetAiExtraHeaders(options),
119
+ "Content-Type": "application/json",
120
+ Authorization: "Bearer " + token,
121
+ },
122
+ body: JSON.stringify(__ployNormalizeAiRunBody(model, inputs, options)),
123
+ });
124
+
125
+ if (options?.returnRawResponse || options?.websocket) {
126
+ return response;
127
+ }
128
+
129
+ if (inputs?.stream === true) {
130
+ if (!response.ok) {
131
+ const errorText = await response.text();
132
+ throw __ployCreateAiRunError(
133
+ response.status,
134
+ errorText,
135
+ "AI run failed with status " + String(response.status),
136
+ );
137
+ }
138
+ if (!response.body) {
139
+ throw new Error("AI stream response body was empty");
140
+ }
141
+ return response.body;
142
+ }
143
+
144
+ const responseText = await response.text();
145
+ if (!response.ok) {
146
+ throw __ployCreateAiRunError(
147
+ response.status,
148
+ responseText,
149
+ "AI run failed with status " + String(response.status),
150
+ );
151
+ }
152
+
153
+ return JSON.parse(responseText);
154
+ },
155
+ };
156
+ }
157
+ `;
158
+ //# sourceMappingURL=ai-runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-runtime.js","sourceRoot":"","sources":["../../src/runtime/ai-runtime.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,eAAe,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4J9B,CAAC"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,147 @@
1
+ import { transform } from "esbuild";
2
+ import { Hono } from "hono";
3
+ import { beforeEach, describe, expect, test } from "vitest";
4
+ import { DB_RUNTIME_CODE, DB_RUNTIME_CODE_PRODUCTION, } from "./db-runtime.js";
5
+ import { createDbHandler } from "../services/db-service.js";
6
+ import { openDatabase } from "../utils/sqlite-db.js";
7
+ async function loadRuntimeModule() {
8
+ const transformed = await transform(DB_RUNTIME_CODE, {
9
+ loader: "ts",
10
+ format: "esm",
11
+ target: "es2022",
12
+ });
13
+ return (await import(`data:text/javascript;charset=utf-8,${encodeURIComponent(transformed.code)}`));
14
+ }
15
+ async function loadProductionRuntimeModule() {
16
+ const transformed = await transform(DB_RUNTIME_CODE_PRODUCTION, {
17
+ loader: "ts",
18
+ format: "esm",
19
+ target: "es2022",
20
+ });
21
+ return (await import(`data:text/javascript;charset=utf-8,${encodeURIComponent(transformed.code)}`));
22
+ }
23
+ describe("db runtime D1 compatibility", () => {
24
+ let db;
25
+ let app;
26
+ beforeEach(() => {
27
+ db = openDatabase(":memory:");
28
+ db.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)`);
29
+ app = new Hono();
30
+ app.post("/db", createDbHandler(() => db));
31
+ });
32
+ test("supports exec with Cloudflare-style result metadata", async () => {
33
+ const { initializeDB } = await loadRuntimeModule();
34
+ const binding = initializeDB("DB", "https://mock/db");
35
+ const originalFetch = globalThis.fetch;
36
+ globalThis.fetch = async (input, init) => {
37
+ const url = typeof input === "string" ? input : input.toString();
38
+ return await app.request(new URL(url).pathname, init);
39
+ };
40
+ try {
41
+ const result = await binding.exec("CREATE TABLE audit (id INTEGER PRIMARY KEY); INSERT INTO audit DEFAULT VALUES;");
42
+ expect(result.count).toBe(2);
43
+ expect(result.duration).toBeGreaterThanOrEqual(0);
44
+ }
45
+ finally {
46
+ globalThis.fetch = originalFetch;
47
+ }
48
+ });
49
+ test("supports prepared batches and raw columnNames responses", async () => {
50
+ const { initializeDB } = await loadRuntimeModule();
51
+ const binding = initializeDB("DB", "https://mock/db");
52
+ const originalFetch = globalThis.fetch;
53
+ globalThis.fetch = async (input, init) => {
54
+ const url = typeof input === "string" ? input : input.toString();
55
+ return await app.request(new URL(url).pathname, init);
56
+ };
57
+ try {
58
+ const insert = binding
59
+ .prepare("INSERT INTO users (name) VALUES (?)")
60
+ .bind("Ada");
61
+ const select = binding.prepare("SELECT id, name FROM users ORDER BY id ASC");
62
+ const batch = await binding.batch([insert, select]);
63
+ expect(batch[0]?.meta.changes).toBe(1);
64
+ expect(batch[1]?.results).toEqual([{ id: 1, name: "Ada" }]);
65
+ const rows = await binding
66
+ .prepare("SELECT id, name FROM users ORDER BY id ASC")
67
+ .raw({ columnNames: true });
68
+ expect(rows).toEqual([
69
+ ["id", "name"],
70
+ [1, "Ada"],
71
+ ]);
72
+ }
73
+ finally {
74
+ globalThis.fetch = originalFetch;
75
+ }
76
+ });
77
+ test("throws for missing columns in first(columnName)", async () => {
78
+ const { initializeDB } = await loadRuntimeModule();
79
+ const binding = initializeDB("DB", "https://mock/db");
80
+ const originalFetch = globalThis.fetch;
81
+ globalThis.fetch = async (input, init) => {
82
+ const url = typeof input === "string" ? input : input.toString();
83
+ return await app.request(new URL(url).pathname, init);
84
+ };
85
+ try {
86
+ await binding
87
+ .prepare("INSERT INTO users (name) VALUES (?)")
88
+ .bind("Ada")
89
+ .run();
90
+ await expect(binding
91
+ .prepare("SELECT id, name FROM users LIMIT 1")
92
+ .first("missing_column")).rejects.toThrow("D1_ERROR: no such column: missing_column");
93
+ }
94
+ finally {
95
+ globalThis.fetch = originalFetch;
96
+ }
97
+ });
98
+ test("supports withSession prepare, batch, first, and bookmarks", async () => {
99
+ const { initializeDB } = await loadRuntimeModule();
100
+ const binding = initializeDB("DB", "https://mock/db");
101
+ const originalFetch = globalThis.fetch;
102
+ globalThis.fetch = async (input, init) => {
103
+ const url = typeof input === "string" ? input : input.toString();
104
+ return await app.request(new URL(url).pathname, init);
105
+ };
106
+ try {
107
+ const session = binding.withSession("first-primary");
108
+ const insert = session
109
+ .prepare("INSERT INTO users (name) VALUES (?)")
110
+ .bind("Grace");
111
+ const batch = await session.batch([insert]);
112
+ expect(batch[0]?.meta.changes).toBe(1);
113
+ const user = await session
114
+ .prepare("SELECT id, name FROM users WHERE name = ?")
115
+ .bind("Grace")
116
+ .first();
117
+ expect(user).toEqual({ id: 1, name: "Grace" });
118
+ expect(session.getBookmark()).toBeNull();
119
+ }
120
+ finally {
121
+ globalThis.fetch = originalFetch;
122
+ }
123
+ });
124
+ test("keeps production runtime failure modes aligned with emulator runtime", async () => {
125
+ const { initializeDB } = await loadProductionRuntimeModule();
126
+ const binding = initializeDB("db_123", "org_123", "https://mock/db");
127
+ const originalFetch = globalThis.fetch;
128
+ globalThis.fetch = async (input, init) => {
129
+ const url = typeof input === "string" ? input : input.toString();
130
+ return await app.request(new URL(url).pathname, init);
131
+ };
132
+ try {
133
+ await binding
134
+ .prepare("INSERT INTO users (name) VALUES (?)")
135
+ .bind("Ada")
136
+ .run();
137
+ await expect(binding.batch([{ bind: () => ({}) }])).rejects.toThrow("DB batch failed: statement is missing bound query data");
138
+ await expect(binding
139
+ .prepare("SELECT id, name FROM users LIMIT 1")
140
+ .first("missing_column")).rejects.toThrow("D1_ERROR: no such column: missing_column");
141
+ }
142
+ finally {
143
+ globalThis.fetch = originalFetch;
144
+ }
145
+ });
146
+ });
147
+ //# sourceMappingURL=db-runtime.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db-runtime.spec.js","sourceRoot":"","sources":["../../src/runtime/db-runtime.spec.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAE5D,OAAO,EACN,eAAe,EACf,0BAA0B,GAC1B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAuB,MAAM,sBAAsB,CAAC;AAuCzE,KAAK,UAAU,iBAAiB;IAC/B,MAAM,WAAW,GAAG,MAAM,SAAS,CAAC,eAAe,EAAE;QACpD,MAAM,EAAE,IAAI;QAC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AqC,CAAC;iBAC9C,IAAI,CAAC,KAAK,CAAC;iBACX,GAAG,EAAE,CAAC;YAER,MAAM,MAAM,CACX,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EAA8B,CAAC,CAAC,CACjE,CAAC,OAAO,CAAC,OAAO,CAChB,wDAAwD,CACxD,CAAC;YAEF,MAAM,MAAM,CACX,OAAO;iBACL,OAAO,CAAC,oCAAoC,CAAC;iBAC7C,KAAK,CAAC,gBAAgB,CAAC,CACzB,CAAC,OAAO,CAAC,OAAO,CAAC,0CAA0C,CAAC,CAAC;QAC/D,CAAC;gBAAS,CAAC;YACV,UAAU,CAAC,KAAK,GAAG,aAAa,CAAC;QAClC,CAAC;IACF,CAAC,CAAC,CAAC;AACJ,CAAC,CAAC,CAAC"}
@@ -1 +1 @@
1
- export declare const STATE_RUNTIME_CODE = "\ninterface StateUpdateDoc {\n $set?: Record<string, unknown>;\n $unset?: Record<string, unknown>;\n $inc?: Record<string, number>;\n $push?: Record<string, unknown>;\n $pop?: Record<string, 1 | -1>;\n}\n\ninterface StateBinding {\n get: (key: string) => Promise<string | null>;\n set: (key: string, value: string) => Promise<void>;\n delete: (key: string) => Promise<void>;\n update: (key: string, update: StateUpdateDoc) => Promise<void>;\n}\n\nfunction getErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction createStateRequestError(action: string, endpoint: string, error: unknown): Error {\n const message = \"State \" + action + \" failed while calling \" + endpoint + \": \" + getErrorMessage(error);\n if (error instanceof Error) {\n return new Error(message, { cause: error });\n }\n return new Error(message);\n}\n\nasync function requestState(action: string, serviceUrl: string, payload: Record<string, unknown>): Promise<Response> {\n const endpoint = serviceUrl + \"/state/\" + action;\n let response: Response;\n\n try {\n response = await fetch(endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n });\n } catch (error) {\n throw createStateRequestError(action, endpoint, error);\n }\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n \"State \" + action + \" failed (status \" + response.status + \" \" + response.statusText + \") from \" + endpoint + \": \" + (errorText || \"empty response body\"),\n );\n }\n\n return response;\n}\n\nexport function initializeState(stateName: string, serviceUrl: string): StateBinding {\n return {\n async get(key: string): Promise<string | null> {\n const response = await requestState(\"get\", serviceUrl, { stateName, key });\n const result = await response.json();\n return result.value ?? null;\n },\n\n async set(key: string, value: string): Promise<void> {\n await requestState(\"set\", serviceUrl, { stateName, key, value });\n },\n\n async delete(key: string): Promise<void> {\n await requestState(\"delete\", serviceUrl, { stateName, key });\n },\n\n async update(key: string, update: StateUpdateDoc): Promise<void> {\n await requestState(\"update\", serviceUrl, { stateName, key, update });\n },\n };\n}\n";
1
+ export declare const STATE_RUNTIME_CODE = "\ninterface StateUpdateDoc {\n $set?: Record<string, unknown>;\n $unset?: Record<string, unknown>;\n $inc?: Record<string, number>;\n $push?: Record<string, unknown>;\n $pop?: Record<string, 1 | -1>;\n}\n\ninterface KVNamespaceListOptions {\n prefix?: string;\n limit?: number;\n cursor?: string;\n}\n\ninterface KVNamespacePutOptions {\n expiration?: number;\n expirationTtl?: number;\n metadata?: unknown;\n}\n\ninterface KVNamespaceGetMethodOptions {\n type?: \"text\" | \"json\" | \"arrayBuffer\" | \"stream\";\n cacheTtl?: number;\n}\n\ninterface StateBinding {\n get(key: string, type?: \"text\" | KVNamespaceGetMethodOptions): Promise<string | null>;\n get<T = unknown>(key: string, type: \"json\" | (KVNamespaceGetMethodOptions & { type: \"json\" })): Promise<T | null>;\n get(key: string, type: \"arrayBuffer\" | (KVNamespaceGetMethodOptions & { type: \"arrayBuffer\" })): Promise<ArrayBuffer | null>;\n get(key: string, type: \"stream\" | (KVNamespaceGetMethodOptions & { type: \"stream\" })): Promise<ReadableStream | null>;\n get(keys: string[], type?: \"text\" | KVNamespaceGetMethodOptions): Promise<Map<string, string | null>>;\n get<T = unknown>(keys: string[], type: \"json\" | (KVNamespaceGetMethodOptions & { type: \"json\" })): Promise<Map<string, T | null>>;\n get(keys: string[], type: \"arrayBuffer\" | (KVNamespaceGetMethodOptions & { type: \"arrayBuffer\" })): Promise<Map<string, ArrayBuffer | null>>;\n get(keys: string[], type: \"stream\" | (KVNamespaceGetMethodOptions & { type: \"stream\" })): Promise<Map<string, ReadableStream | null>>;\n getWithMetadata(key: string, type?: \"text\" | KVNamespaceGetMethodOptions): Promise<{ value: string | null; metadata: unknown | null }>;\n getWithMetadata<T = unknown>(key: string, type: \"json\" | (KVNamespaceGetMethodOptions & { type: \"json\" })): Promise<{ value: T | null; metadata: unknown | null }>;\n getWithMetadata(key: string, type: \"arrayBuffer\" | (KVNamespaceGetMethodOptions & { type: \"arrayBuffer\" })): Promise<{ value: ArrayBuffer | null; metadata: unknown | null }>;\n getWithMetadata(key: string, type: \"stream\" | (KVNamespaceGetMethodOptions & { type: \"stream\" })): Promise<{ value: ReadableStream | null; metadata: unknown | null }>;\n put: (key: string, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions) => Promise<void>;\n set: (key: string, value: string) => Promise<void>;\n delete: (key: string) => Promise<void>;\n list: (options?: KVNamespaceListOptions) => Promise<{ keys: Array<{ name: string; expiration?: number; metadata?: unknown }>; list_complete: boolean; cursor?: string }>;\n update: (key: string, update: StateUpdateDoc) => Promise<void>;\n}\n\ninterface EncodedStateValue {\n value: string;\n encoding: \"text\" | \"base64\";\n}\n\nfunction getErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction createStateRequestError(action: string, endpoint: string, error: unknown): Error {\n const message = \"State \" + action + \" failed while calling \" + endpoint + \": \" + getErrorMessage(error);\n if (error instanceof Error) {\n return new Error(message, { cause: error });\n }\n return new Error(message);\n}\n\nasync function requestState(action: string, serviceUrl: string, payload: Record<string, unknown>): Promise<Response> {\n const endpoint = serviceUrl + \"/state/\" + action;\n let response: Response;\n\n try {\n response = await fetch(endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n });\n } catch (error) {\n throw createStateRequestError(action, endpoint, error);\n }\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n \"State \" + action + \" failed (status \" + response.status + \" \" + response.statusText + \") from \" + endpoint + \": \" + (errorText || \"empty response body\"),\n );\n }\n\n return response;\n}\n\nfunction createStreamFromArrayBuffer(buffer: ArrayBuffer): ReadableStream {\n return new ReadableStream({\n start(controller) {\n controller.enqueue(new Uint8Array(buffer));\n controller.close();\n },\n });\n}\n\nfunction base64Encode(bytes: Uint8Array): string {\n let binary = \"\";\n for (let index = 0; index < bytes.length; index += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));\n }\n return btoa(binary);\n}\n\nfunction base64Decode(value: string): Uint8Array {\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\nasync function encodeStateValue(value: string | ArrayBuffer | ArrayBufferView | ReadableStream): Promise<EncodedStateValue> {\n if (typeof value === \"string\") {\n return { value, encoding: \"text\" };\n }\n\n if (value instanceof ArrayBuffer) {\n return { value: base64Encode(new Uint8Array(value)), encoding: \"base64\" };\n }\n\n if (ArrayBuffer.isView(value)) {\n return {\n value: base64Encode(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)),\n encoding: \"base64\",\n };\n }\n\n const reader = value.getReader();\n const chunks: Uint8Array[] = [];\n let totalLength = 0;\n\n while (true) {\n const result = await reader.read();\n if (result.done) {\n break;\n }\n\n const chunk = result.value instanceof Uint8Array ? result.value : new Uint8Array(result.value);\n chunks.push(chunk);\n totalLength += chunk.byteLength;\n }\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n merged.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return { value: base64Encode(merged), encoding: \"base64\" };\n}\n\nfunction decodeStateValue(\n storedValue: string | null,\n encoding: string,\n type: \"text\" | \"json\" | \"arrayBuffer\" | \"stream\"\n): unknown | null {\n if (storedValue === null) {\n return null;\n }\n\n const bytes = encoding === \"base64\" ? base64Decode(storedValue) : new TextEncoder().encode(storedValue);\n\n if (type === \"arrayBuffer\") {\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n }\n\n if (type === \"stream\") {\n return createStreamFromArrayBuffer(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));\n }\n\n const text = encoding === \"base64\" ? new TextDecoder().decode(bytes) : storedValue;\n if (type === \"json\") {\n return JSON.parse(text);\n }\n\n return text;\n}\n\nfunction resolveExpiration(options?: KVNamespacePutOptions): number | null {\n if (!options) {\n return null;\n }\n\n if (options.expiration !== undefined && options.expirationTtl !== undefined) {\n throw new Error(\"KV put failed: specify either expiration or expirationTtl, not both\");\n }\n\n if (options.expiration !== undefined) {\n return options.expiration;\n }\n\n if (options.expirationTtl !== undefined) {\n return Math.floor(Date.now() / 1000) + options.expirationTtl;\n }\n\n return null;\n}\n\nfunction resolveGetType(options?: \"text\" | \"json\" | \"arrayBuffer\" | \"stream\" | KVNamespaceGetMethodOptions): \"text\" | \"json\" | \"arrayBuffer\" | \"stream\" {\n if (!options) {\n return \"text\";\n }\n\n if (typeof options === \"string\") {\n return options;\n }\n\n return options.type ?? \"text\";\n}\n\nexport function initializeState(stateName: string, serviceUrl: string): StateBinding {\n return {\n async get(keyOrKeys: string | string[], options?: \"text\" | \"json\" | \"arrayBuffer\" | \"stream\" | KVNamespaceGetMethodOptions): Promise<unknown> {\n const type = resolveGetType(options);\n if (Array.isArray(keyOrKeys)) {\n const entries = await Promise.all(\n keyOrKeys.map(async (key) => {\n const value = await this.get(key, type);\n return [key, value] as const;\n }),\n );\n return new Map(entries);\n }\n\n const response = await requestState(\"get\", serviceUrl, { stateName, key: keyOrKeys });\n const result = await response.json();\n return decodeStateValue(result.value ?? null, result.encoding ?? \"text\", type);\n },\n\n async getWithMetadata(key: string, options?: \"text\" | \"json\" | \"arrayBuffer\" | \"stream\" | KVNamespaceGetMethodOptions): Promise<{ value: unknown | null; metadata: unknown | null }> {\n const type = resolveGetType(options);\n const response = await requestState(\"get-with-metadata\", serviceUrl, { stateName, key });\n const result = await response.json();\n return {\n value: decodeStateValue(result.value ?? null, result.encoding ?? \"text\", type),\n metadata: result.metadata ?? null,\n };\n },\n\n async put(key: string, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise<void> {\n const encoded = await encodeStateValue(value);\n await requestState(\"set\", serviceUrl, {\n stateName,\n key,\n value: encoded.value,\n encoding: encoded.encoding,\n metadata: options?.metadata ?? null,\n expiration: resolveExpiration(options),\n });\n },\n\n async set(key: string, value: string): Promise<void> {\n await this.put(key, value);\n },\n\n async delete(key: string): Promise<void> {\n await requestState(\"delete\", serviceUrl, { stateName, key });\n },\n\n async list(options?: KVNamespaceListOptions): Promise<{ keys: Array<{ name: string; expiration?: number; metadata?: unknown }>; list_complete: boolean; cursor?: string }> {\n const response = await requestState(\"list\", serviceUrl, {\n stateName,\n prefix: options?.prefix,\n limit: options?.limit,\n cursor: options?.cursor,\n });\n const result = await response.json();\n return {\n keys: result.keys,\n list_complete: result.list_complete,\n cursor: result.cursor || undefined,\n };\n },\n\n async update(key: string, update: StateUpdateDoc): Promise<void> {\n await requestState(\"update\", serviceUrl, { stateName, key, update });\n },\n };\n}\n";
@@ -7,13 +7,48 @@ interface StateUpdateDoc {
7
7
  $pop?: Record<string, 1 | -1>;
8
8
  }
9
9
 
10
+ interface KVNamespaceListOptions {
11
+ prefix?: string;
12
+ limit?: number;
13
+ cursor?: string;
14
+ }
15
+
16
+ interface KVNamespacePutOptions {
17
+ expiration?: number;
18
+ expirationTtl?: number;
19
+ metadata?: unknown;
20
+ }
21
+
22
+ interface KVNamespaceGetMethodOptions {
23
+ type?: "text" | "json" | "arrayBuffer" | "stream";
24
+ cacheTtl?: number;
25
+ }
26
+
10
27
  interface StateBinding {
11
- get: (key: string) => Promise<string | null>;
28
+ get(key: string, type?: "text" | KVNamespaceGetMethodOptions): Promise<string | null>;
29
+ get<T = unknown>(key: string, type: "json" | (KVNamespaceGetMethodOptions & { type: "json" })): Promise<T | null>;
30
+ get(key: string, type: "arrayBuffer" | (KVNamespaceGetMethodOptions & { type: "arrayBuffer" })): Promise<ArrayBuffer | null>;
31
+ get(key: string, type: "stream" | (KVNamespaceGetMethodOptions & { type: "stream" })): Promise<ReadableStream | null>;
32
+ get(keys: string[], type?: "text" | KVNamespaceGetMethodOptions): Promise<Map<string, string | null>>;
33
+ get<T = unknown>(keys: string[], type: "json" | (KVNamespaceGetMethodOptions & { type: "json" })): Promise<Map<string, T | null>>;
34
+ get(keys: string[], type: "arrayBuffer" | (KVNamespaceGetMethodOptions & { type: "arrayBuffer" })): Promise<Map<string, ArrayBuffer | null>>;
35
+ get(keys: string[], type: "stream" | (KVNamespaceGetMethodOptions & { type: "stream" })): Promise<Map<string, ReadableStream | null>>;
36
+ getWithMetadata(key: string, type?: "text" | KVNamespaceGetMethodOptions): Promise<{ value: string | null; metadata: unknown | null }>;
37
+ getWithMetadata<T = unknown>(key: string, type: "json" | (KVNamespaceGetMethodOptions & { type: "json" })): Promise<{ value: T | null; metadata: unknown | null }>;
38
+ getWithMetadata(key: string, type: "arrayBuffer" | (KVNamespaceGetMethodOptions & { type: "arrayBuffer" })): Promise<{ value: ArrayBuffer | null; metadata: unknown | null }>;
39
+ getWithMetadata(key: string, type: "stream" | (KVNamespaceGetMethodOptions & { type: "stream" })): Promise<{ value: ReadableStream | null; metadata: unknown | null }>;
40
+ put: (key: string, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions) => Promise<void>;
12
41
  set: (key: string, value: string) => Promise<void>;
13
42
  delete: (key: string) => Promise<void>;
43
+ list: (options?: KVNamespaceListOptions) => Promise<{ keys: Array<{ name: string; expiration?: number; metadata?: unknown }>; list_complete: boolean; cursor?: string }>;
14
44
  update: (key: string, update: StateUpdateDoc) => Promise<void>;
15
45
  }
16
46
 
47
+ interface EncodedStateValue {
48
+ value: string;
49
+ encoding: "text" | "base64";
50
+ }
51
+
17
52
  function getErrorMessage(error: unknown): string {
18
53
  return error instanceof Error ? error.message : String(error);
19
54
  }
@@ -50,22 +85,196 @@ async function requestState(action: string, serviceUrl: string, payload: Record<
50
85
  return response;
51
86
  }
52
87
 
88
+ function createStreamFromArrayBuffer(buffer: ArrayBuffer): ReadableStream {
89
+ return new ReadableStream({
90
+ start(controller) {
91
+ controller.enqueue(new Uint8Array(buffer));
92
+ controller.close();
93
+ },
94
+ });
95
+ }
96
+
97
+ function base64Encode(bytes: Uint8Array): string {
98
+ let binary = "";
99
+ for (let index = 0; index < bytes.length; index += 0x8000) {
100
+ binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
101
+ }
102
+ return btoa(binary);
103
+ }
104
+
105
+ function base64Decode(value: string): Uint8Array {
106
+ const binary = atob(value);
107
+ const bytes = new Uint8Array(binary.length);
108
+ for (let index = 0; index < binary.length; index++) {
109
+ bytes[index] = binary.charCodeAt(index);
110
+ }
111
+ return bytes;
112
+ }
113
+
114
+ async function encodeStateValue(value: string | ArrayBuffer | ArrayBufferView | ReadableStream): Promise<EncodedStateValue> {
115
+ if (typeof value === "string") {
116
+ return { value, encoding: "text" };
117
+ }
118
+
119
+ if (value instanceof ArrayBuffer) {
120
+ return { value: base64Encode(new Uint8Array(value)), encoding: "base64" };
121
+ }
122
+
123
+ if (ArrayBuffer.isView(value)) {
124
+ return {
125
+ value: base64Encode(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)),
126
+ encoding: "base64",
127
+ };
128
+ }
129
+
130
+ const reader = value.getReader();
131
+ const chunks: Uint8Array[] = [];
132
+ let totalLength = 0;
133
+
134
+ while (true) {
135
+ const result = await reader.read();
136
+ if (result.done) {
137
+ break;
138
+ }
139
+
140
+ const chunk = result.value instanceof Uint8Array ? result.value : new Uint8Array(result.value);
141
+ chunks.push(chunk);
142
+ totalLength += chunk.byteLength;
143
+ }
144
+
145
+ const merged = new Uint8Array(totalLength);
146
+ let offset = 0;
147
+ for (const chunk of chunks) {
148
+ merged.set(chunk, offset);
149
+ offset += chunk.byteLength;
150
+ }
151
+
152
+ return { value: base64Encode(merged), encoding: "base64" };
153
+ }
154
+
155
+ function decodeStateValue(
156
+ storedValue: string | null,
157
+ encoding: string,
158
+ type: "text" | "json" | "arrayBuffer" | "stream"
159
+ ): unknown | null {
160
+ if (storedValue === null) {
161
+ return null;
162
+ }
163
+
164
+ const bytes = encoding === "base64" ? base64Decode(storedValue) : new TextEncoder().encode(storedValue);
165
+
166
+ if (type === "arrayBuffer") {
167
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
168
+ }
169
+
170
+ if (type === "stream") {
171
+ return createStreamFromArrayBuffer(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
172
+ }
173
+
174
+ const text = encoding === "base64" ? new TextDecoder().decode(bytes) : storedValue;
175
+ if (type === "json") {
176
+ return JSON.parse(text);
177
+ }
178
+
179
+ return text;
180
+ }
181
+
182
+ function resolveExpiration(options?: KVNamespacePutOptions): number | null {
183
+ if (!options) {
184
+ return null;
185
+ }
186
+
187
+ if (options.expiration !== undefined && options.expirationTtl !== undefined) {
188
+ throw new Error("KV put failed: specify either expiration or expirationTtl, not both");
189
+ }
190
+
191
+ if (options.expiration !== undefined) {
192
+ return options.expiration;
193
+ }
194
+
195
+ if (options.expirationTtl !== undefined) {
196
+ return Math.floor(Date.now() / 1000) + options.expirationTtl;
197
+ }
198
+
199
+ return null;
200
+ }
201
+
202
+ function resolveGetType(options?: "text" | "json" | "arrayBuffer" | "stream" | KVNamespaceGetMethodOptions): "text" | "json" | "arrayBuffer" | "stream" {
203
+ if (!options) {
204
+ return "text";
205
+ }
206
+
207
+ if (typeof options === "string") {
208
+ return options;
209
+ }
210
+
211
+ return options.type ?? "text";
212
+ }
213
+
53
214
  export function initializeState(stateName: string, serviceUrl: string): StateBinding {
54
215
  return {
55
- async get(key: string): Promise<string | null> {
56
- const response = await requestState("get", serviceUrl, { stateName, key });
216
+ async get(keyOrKeys: string | string[], options?: "text" | "json" | "arrayBuffer" | "stream" | KVNamespaceGetMethodOptions): Promise<unknown> {
217
+ const type = resolveGetType(options);
218
+ if (Array.isArray(keyOrKeys)) {
219
+ const entries = await Promise.all(
220
+ keyOrKeys.map(async (key) => {
221
+ const value = await this.get(key, type);
222
+ return [key, value] as const;
223
+ }),
224
+ );
225
+ return new Map(entries);
226
+ }
227
+
228
+ const response = await requestState("get", serviceUrl, { stateName, key: keyOrKeys });
57
229
  const result = await response.json();
58
- return result.value ?? null;
230
+ return decodeStateValue(result.value ?? null, result.encoding ?? "text", type);
231
+ },
232
+
233
+ async getWithMetadata(key: string, options?: "text" | "json" | "arrayBuffer" | "stream" | KVNamespaceGetMethodOptions): Promise<{ value: unknown | null; metadata: unknown | null }> {
234
+ const type = resolveGetType(options);
235
+ const response = await requestState("get-with-metadata", serviceUrl, { stateName, key });
236
+ const result = await response.json();
237
+ return {
238
+ value: decodeStateValue(result.value ?? null, result.encoding ?? "text", type),
239
+ metadata: result.metadata ?? null,
240
+ };
241
+ },
242
+
243
+ async put(key: string, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise<void> {
244
+ const encoded = await encodeStateValue(value);
245
+ await requestState("set", serviceUrl, {
246
+ stateName,
247
+ key,
248
+ value: encoded.value,
249
+ encoding: encoded.encoding,
250
+ metadata: options?.metadata ?? null,
251
+ expiration: resolveExpiration(options),
252
+ });
59
253
  },
60
254
 
61
255
  async set(key: string, value: string): Promise<void> {
62
- await requestState("set", serviceUrl, { stateName, key, value });
256
+ await this.put(key, value);
63
257
  },
64
258
 
65
259
  async delete(key: string): Promise<void> {
66
260
  await requestState("delete", serviceUrl, { stateName, key });
67
261
  },
68
262
 
263
+ async list(options?: KVNamespaceListOptions): Promise<{ keys: Array<{ name: string; expiration?: number; metadata?: unknown }>; list_complete: boolean; cursor?: string }> {
264
+ const response = await requestState("list", serviceUrl, {
265
+ stateName,
266
+ prefix: options?.prefix,
267
+ limit: options?.limit,
268
+ cursor: options?.cursor,
269
+ });
270
+ const result = await response.json();
271
+ return {
272
+ keys: result.keys,
273
+ list_complete: result.list_complete,
274
+ cursor: result.cursor || undefined,
275
+ };
276
+ },
277
+
69
278
  async update(key: string, update: StateUpdateDoc): Promise<void> {
70
279
  await requestState("update", serviceUrl, { stateName, key, update });
71
280
  },
@@ -1 +1 @@
1
- {"version":3,"file":"state-runtime.js","sourceRoot":"","sources":["../../src/runtime/state-runtime.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,kBAAkB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyEjC,CAAC"}
1
+ {"version":3,"file":"state-runtime.js","sourceRoot":"","sources":["../../src/runtime/state-runtime.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,kBAAkB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0RjC,CAAC"}
@@ -0,0 +1 @@
1
+ export {};