ziex 0.1.0-dev.1367 → 0.1.0-dev.1381

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 (38) hide show
  1. package/aws-lambda/index.js +20 -29
  2. package/build.zig.zon +10 -3
  3. package/cloudflare/index.js +1635 -1854
  4. package/index.js +155 -216
  5. package/{pkg/ziex/src/react → jsx}/dom.d.ts +5 -9
  6. package/{pkg/ziex/src/react → jsx}/index.d.ts +1 -1
  7. package/{react → jsx}/index.js +19 -25
  8. package/{pkg/ziex/src/react → jsx}/types.d.ts +14 -9
  9. package/package.json +6 -14
  10. package/vercel/index.js +0 -15
  11. package/wasm/index.js +253 -261
  12. package/wasm/init.dev.js +242 -189
  13. package/wasm/init.js +3 -3
  14. package/pkg/ziex/src/zx.d.ts +0 -1
  15. package/vendor/jsz/js/src/index.d.ts +0 -1
  16. package/vendor/jsz/js/src/zigjs.d.ts +0 -107
  17. /package/{pkg/ziex/src/app.d.ts → app.d.ts} +0 -0
  18. /package/{pkg/ziex/src/aws-lambda → aws-lambda}/index.d.ts +0 -0
  19. /package/{pkg/ziex/src/browser → browser}/kv.d.ts +0 -0
  20. /package/{pkg/ziex/src/cloudflare → cloudflare}/app.d.ts +0 -0
  21. /package/{pkg/ziex/src/cloudflare → cloudflare}/db.d.ts +0 -0
  22. /package/{pkg/ziex/src/cloudflare → cloudflare}/do.d.ts +0 -0
  23. /package/{pkg/ziex/src/cloudflare → cloudflare}/index.d.ts +0 -0
  24. /package/{pkg/ziex/src/cloudflare → cloudflare}/kv.d.ts +0 -0
  25. /package/{pkg/ziex/src/cloudflare → cloudflare}/worker.d.ts +0 -0
  26. /package/{pkg/ziex/src/db.d.ts → db.d.ts} +0 -0
  27. /package/{pkg/ziex/src/fetch.d.ts → fetch.d.ts} +0 -0
  28. /package/{pkg/ziex/src/index.d.ts → index.d.ts} +0 -0
  29. /package/{pkg/ziex/src/kv.d.ts → kv.d.ts} +0 -0
  30. /package/{pkg/ziex/src/runtime.d.ts → runtime.d.ts} +0 -0
  31. /package/{pkg/ziex/src/vercel → vercel}/index.d.ts +0 -0
  32. /package/{pkg/ziex/src/wasi.d.ts → wasi.d.ts} +0 -0
  33. /package/{pkg/ziex/src/wasm → wasm}/core.d.ts +0 -0
  34. /package/{pkg/ziex/src/wasm → wasm}/dom.d.ts +0 -0
  35. /package/{pkg/ziex/src/wasm → wasm}/index.d.ts +0 -0
  36. /package/{pkg/ziex/src/wasm → wasm}/init.d.ts +0 -0
  37. /package/{pkg/ziex/src/wasm → wasm}/types.d.ts +0 -0
  38. /package/{pkg/ziex/src/wasm → wasm}/wasi.d.ts +0 -0
package/index.js CHANGED
@@ -1,36 +1,13 @@
1
- var __defProp = Object.defineProperty;
2
- var __returnValue = (v) => v;
3
- function __exportSetter(name, newValue) {
4
- this[name] = __returnValue.bind(null, newValue);
5
- }
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, {
9
- get: all[name],
10
- enumerable: true,
11
- configurable: true,
12
- set: __exportSetter.bind(all, name)
13
- });
14
- };
15
-
16
- // src/runtime.ts
17
- var exports_runtime = {};
18
- __export(exports_runtime, {
19
- run: () => run,
20
- buildWsImports: () => buildWsImports,
21
- attachWebSocket: () => attachWebSocket
22
- });
23
-
24
1
  // src/wasm/wasi.ts
25
- var decoder = new TextDecoder;
26
- var encoder = new TextEncoder;
27
-
28
- class ZxWasiBridge {
2
+ var decoder = new TextDecoder();
3
+ var encoder = new TextEncoder();
4
+ var ZxWasiBridge = class {
29
5
  #alloc;
30
6
  #fetchCompleteHandler;
31
7
  #memory;
32
8
  #cb;
33
- #intervals = new Map;
9
+ #intervals = /* @__PURE__ */ new Map();
10
+ // Cached memory view - invalidated when the WASM buffer grows.
34
11
  #memView = null;
35
12
  #memBuf = null;
36
13
  constructor(exports) {
@@ -74,33 +51,29 @@ class ZxWasiBridge {
74
51
  const url = this.#readString(urlPtr, urlLen);
75
52
  const method = methodLen > 0 ? this.#readString(methodPtr, methodLen) : "GET";
76
53
  const headersJson = headersLen > 0 ? this.#readString(headersPtr, headersLen) : "{}";
77
- const body = bodyLen > 0 ? this.#view().subarray(bodyPtr, bodyPtr + bodyLen) : undefined;
54
+ const body = bodyLen > 0 ? this.#view().subarray(bodyPtr, bodyPtr + bodyLen) : void 0;
78
55
  let headers = {};
79
56
  try {
80
57
  headers = JSON.parse(headersJson);
81
58
  } catch {
82
- for (const line of headersJson.split(`
83
- `)) {
59
+ for (const line of headersJson.split("\n")) {
84
60
  const i = line.indexOf(":");
85
- if (i > 0)
86
- headers[line.slice(0, i)] = line.slice(i + 1);
61
+ if (i > 0) headers[line.slice(0, i)] = line.slice(i + 1);
87
62
  }
88
63
  }
89
- const controller = new AbortController;
64
+ const controller = new AbortController();
90
65
  const timeout = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : null;
91
66
  fetch(url, {
92
67
  method,
93
- headers: Object.keys(headers).length > 0 ? headers : undefined,
94
- body: method !== "GET" && method !== "HEAD" ? body : undefined,
68
+ headers: Object.keys(headers).length > 0 ? headers : void 0,
69
+ body: method !== "GET" && method !== "HEAD" ? body : void 0,
95
70
  signal: controller.signal
96
71
  }).then(async (res) => {
97
- if (timeout)
98
- clearTimeout(timeout);
72
+ if (timeout) clearTimeout(timeout);
99
73
  const bytes = new Uint8Array(await res.arrayBuffer());
100
74
  this.#notifyFetchComplete(fetchId, res.status, bytes, false);
101
75
  }).catch((err) => {
102
- if (timeout)
103
- clearTimeout(timeout);
76
+ if (timeout) clearTimeout(timeout);
104
77
  const msg = err.name === "AbortError" ? "Request timeout" : err.message ?? "Fetch failed";
105
78
  this.#notifyFetchComplete(fetchId, 0, msg, true);
106
79
  });
@@ -120,11 +93,17 @@ class ZxWasiBridge {
120
93
  }
121
94
  clearInterval(callbackId) {
122
95
  const handle = this.#intervals.get(callbackId);
123
- if (handle !== undefined) {
96
+ if (handle !== void 0) {
124
97
  clearInterval(handle);
125
98
  this.#intervals.delete(callbackId);
126
99
  }
127
100
  }
101
+ /**
102
+ * Create the WASI import object for WASM instantiation.
103
+ *
104
+ * Returns only the `__zx` namespace (log, fetch, timers).
105
+ * Does NOT include jsz.importObject() - the server binary does not use jsz.
106
+ */
128
107
  static createImportObject(bridgeRef) {
129
108
  return {
130
109
  __zx: {
@@ -132,7 +111,18 @@ class ZxWasiBridge {
132
111
  bridgeRef.current?.log(level, ptr, len);
133
112
  },
134
113
  _fetchAsync: (urlPtr, urlLen, methodPtr, methodLen, headersPtr, headersLen, bodyPtr, bodyLen, timeoutMs, fetchId) => {
135
- bridgeRef.current?.fetchAsync(urlPtr, urlLen, methodPtr, methodLen, headersPtr, headersLen, bodyPtr, bodyLen, timeoutMs, fetchId);
114
+ bridgeRef.current?.fetchAsync(
115
+ urlPtr,
116
+ urlLen,
117
+ methodPtr,
118
+ methodLen,
119
+ headersPtr,
120
+ headersLen,
121
+ bodyPtr,
122
+ bodyLen,
123
+ timeoutMs,
124
+ fetchId
125
+ );
136
126
  },
137
127
  _setTimeout: (callbackId, delayMs) => {
138
128
  bridgeRef.current?.setTimeout(callbackId, delayMs);
@@ -146,26 +136,19 @@ class ZxWasiBridge {
146
136
  }
147
137
  };
148
138
  }
149
- }
139
+ };
150
140
 
151
141
  // src/kv.ts
152
- var exports_kv = {};
153
- __export(exports_kv, {
154
- createMemoryKV: () => createMemoryKV,
155
- createKVImports: () => createKVImports
156
- });
157
142
  function putOptions(ttlSeconds) {
158
- if (ttlSeconds < 60)
159
- return;
143
+ if (ttlSeconds < 60) return void 0;
160
144
  return { expirationTtl: ttlSeconds };
161
145
  }
162
146
  function createMemoryKV() {
163
- const store = new Map;
147
+ const store = /* @__PURE__ */ new Map();
164
148
  function read(key) {
165
149
  const entry = store.get(key);
166
- if (!entry)
167
- return null;
168
- if (entry.expiresAt !== undefined && Date.now() >= entry.expiresAt) {
150
+ if (!entry) return null;
151
+ if (entry.expiresAt !== void 0 && Date.now() >= entry.expiresAt) {
169
152
  store.delete(key);
170
153
  return null;
171
154
  }
@@ -173,10 +156,10 @@ function createMemoryKV() {
173
156
  }
174
157
  function write(key, value, options) {
175
158
  let expiresAt;
176
- if (options?.expiration !== undefined) {
177
- expiresAt = options.expiration * 1000;
178
- } else if (options?.expirationTtl !== undefined) {
179
- expiresAt = Date.now() + options.expirationTtl * 1000;
159
+ if (options?.expiration !== void 0) {
160
+ expiresAt = options.expiration * 1e3;
161
+ } else if (options?.expirationTtl !== void 0) {
162
+ expiresAt = Date.now() + options.expirationTtl * 1e3;
180
163
  }
181
164
  store.set(key, { value, expiresAt });
182
165
  }
@@ -192,8 +175,7 @@ function createMemoryKV() {
192
175
  },
193
176
  async list(options) {
194
177
  const keys = [...store.keys()].filter((k) => {
195
- if (options?.prefix && !k.startsWith(options.prefix))
196
- return false;
178
+ if (options?.prefix && !k.startsWith(options.prefix)) return false;
197
179
  return read(k) !== null;
198
180
  }).map((name) => ({ name }));
199
181
  return { keys };
@@ -205,14 +187,13 @@ function isSyncKVNamespace(binding) {
205
187
  return typeof candidate.getSync === "function" && typeof candidate.putSync === "function" && typeof candidate.deleteSync === "function" && typeof candidate.listSync === "function";
206
188
  }
207
189
  function createKVImports(bindings, getMemory) {
208
- const encoder2 = new TextEncoder;
209
- const decoder2 = new TextDecoder;
190
+ const encoder2 = new TextEncoder();
191
+ const decoder2 = new TextDecoder();
210
192
  function readStr(ptr, len) {
211
193
  return decoder2.decode(new Uint8Array(getMemory().buffer, ptr, len));
212
194
  }
213
195
  function writeBytes(buf_ptr, buf_max, data) {
214
- if (data.length > buf_max)
215
- return -2;
196
+ if (data.length > buf_max) return -2;
216
197
  new Uint8Array(getMemory().buffer, buf_ptr, data.length).set(data);
217
198
  return data.length;
218
199
  }
@@ -221,40 +202,36 @@ function createKVImports(bindings, getMemory) {
221
202
  }
222
203
  const Suspending = WebAssembly.Suspending;
223
204
  if (typeof Suspending !== "function") {
224
- let syncBinding = function(ns) {
205
+ let syncBinding2 = function(ns) {
225
206
  const candidate = binding(ns);
226
207
  return candidate && isSyncKVNamespace(candidate) ? candidate : null;
227
208
  };
209
+ var syncBinding = syncBinding2;
228
210
  return {
229
211
  kv_get: (ns_ptr, ns_len, key_ptr, key_len, buf_ptr, buf_max) => {
230
- const b = syncBinding(readStr(ns_ptr, ns_len));
231
- if (!b)
232
- return -1;
212
+ const b = syncBinding2(readStr(ns_ptr, ns_len));
213
+ if (!b) return -1;
233
214
  const value = b.getSync(readStr(key_ptr, key_len));
234
- if (value === null)
235
- return -1;
215
+ if (value === null) return -1;
236
216
  return writeBytes(buf_ptr, buf_max, encoder2.encode(value));
237
217
  },
238
218
  kv_put: (ns_ptr, ns_len, key_ptr, key_len, val_ptr, val_len, ttl_seconds) => {
239
- const b = syncBinding(readStr(ns_ptr, ns_len));
240
- if (!b)
241
- return 0;
219
+ const b = syncBinding2(readStr(ns_ptr, ns_len));
220
+ if (!b) return 0;
242
221
  b.putSync(readStr(key_ptr, key_len), readStr(val_ptr, val_len), putOptions(ttl_seconds));
243
222
  return 0;
244
223
  },
245
224
  kv_delete: (ns_ptr, ns_len, key_ptr, key_len) => {
246
- const b = syncBinding(readStr(ns_ptr, ns_len));
247
- if (!b)
248
- return 0;
225
+ const b = syncBinding2(readStr(ns_ptr, ns_len));
226
+ if (!b) return 0;
249
227
  b.deleteSync(readStr(key_ptr, key_len));
250
228
  return 0;
251
229
  },
252
230
  kv_list: (ns_ptr, ns_len, pfx_ptr, pfx_len, buf_ptr, buf_max) => {
253
- const b = syncBinding(readStr(ns_ptr, ns_len));
254
- if (!b)
255
- return writeBytes(buf_ptr, buf_max, encoder2.encode("[]"));
231
+ const b = syncBinding2(readStr(ns_ptr, ns_len));
232
+ if (!b) return writeBytes(buf_ptr, buf_max, encoder2.encode("[]"));
256
233
  const prefix = readStr(pfx_ptr, pfx_len);
257
- const result = b.listSync(prefix.length > 0 ? { prefix } : undefined);
234
+ const result = b.listSync(prefix.length > 0 ? { prefix } : void 0);
258
235
  return writeBytes(buf_ptr, buf_max, encoder2.encode(JSON.stringify(result.keys.map((k) => k.name))));
259
236
  }
260
237
  };
@@ -262,33 +239,28 @@ function createKVImports(bindings, getMemory) {
262
239
  return {
263
240
  kv_get: new Suspending(async (ns_ptr, ns_len, key_ptr, key_len, buf_ptr, buf_max) => {
264
241
  const b = binding(readStr(ns_ptr, ns_len));
265
- if (!b)
266
- return -1;
242
+ if (!b) return -1;
267
243
  const value = await b.get(readStr(key_ptr, key_len));
268
- if (value === null)
269
- return -1;
244
+ if (value === null) return -1;
270
245
  return writeBytes(buf_ptr, buf_max, encoder2.encode(value));
271
246
  }),
272
247
  kv_put: new Suspending(async (ns_ptr, ns_len, key_ptr, key_len, val_ptr, val_len, ttl_seconds) => {
273
248
  const b = binding(readStr(ns_ptr, ns_len));
274
- if (!b)
275
- return -1;
249
+ if (!b) return -1;
276
250
  await b.put(readStr(key_ptr, key_len), readStr(val_ptr, val_len), putOptions(ttl_seconds));
277
251
  return 0;
278
252
  }),
279
253
  kv_delete: new Suspending(async (ns_ptr, ns_len, key_ptr, key_len) => {
280
254
  const b = binding(readStr(ns_ptr, ns_len));
281
- if (!b)
282
- return -1;
255
+ if (!b) return -1;
283
256
  await b.delete(readStr(key_ptr, key_len));
284
257
  return 0;
285
258
  }),
286
259
  kv_list: new Suspending(async (ns_ptr, ns_len, prefix_ptr, prefix_len, buf_ptr, buf_max) => {
287
260
  const b = binding(readStr(ns_ptr, ns_len));
288
- if (!b)
289
- return writeBytes(buf_ptr, buf_max, encoder2.encode("[]"));
261
+ if (!b) return writeBytes(buf_ptr, buf_max, encoder2.encode("[]"));
290
262
  const prefix = readStr(prefix_ptr, prefix_len);
291
- const result = await b.list(prefix.length > 0 ? { prefix } : undefined);
263
+ const result = await b.list(prefix.length > 0 ? { prefix } : void 0);
292
264
  return writeBytes(buf_ptr, buf_max, encoder2.encode(JSON.stringify(result.keys.map((k) => k.name))));
293
265
  })
294
266
  };
@@ -296,14 +268,13 @@ function createKVImports(bindings, getMemory) {
296
268
 
297
269
  // src/fetch.ts
298
270
  function createFetchImports(getMemory) {
299
- const encoder2 = new TextEncoder;
300
- const decoder2 = new TextDecoder;
271
+ const encoder2 = new TextEncoder();
272
+ const decoder2 = new TextDecoder();
301
273
  function readStr(ptr, len) {
302
274
  return decoder2.decode(new Uint8Array(getMemory().buffer, ptr, len));
303
275
  }
304
276
  function writeBytes(buf_ptr, buf_max, data) {
305
- if (data.length > buf_max)
306
- return -2;
277
+ if (data.length > buf_max) return -2;
307
278
  new Uint8Array(getMemory().buffer, buf_ptr, data.length).set(data);
308
279
  return data.length;
309
280
  }
@@ -315,8 +286,7 @@ function createFetchImports(getMemory) {
315
286
  try {
316
287
  headers = JSON.parse(headersJson);
317
288
  } catch {
318
- for (const line of headersJson.split(`
319
- `)) {
289
+ for (const line of headersJson.split("\n")) {
320
290
  const colonIdx = line.indexOf(":");
321
291
  if (colonIdx > 0) {
322
292
  headers[line.slice(0, colonIdx)] = line.slice(colonIdx + 1);
@@ -329,25 +299,23 @@ function createFetchImports(getMemory) {
329
299
  const url = readStr(url_ptr, url_len);
330
300
  const method = method_len > 0 ? readStr(method_ptr, method_len) : "GET";
331
301
  const headersJson = headers_len > 0 ? readStr(headers_ptr, headers_len) : "{}";
332
- const body = body_len > 0 ? readBytes(body_ptr, body_len) : undefined;
302
+ const body = body_len > 0 ? readBytes(body_ptr, body_len) : void 0;
333
303
  const headers = parseHeaders(headersJson);
334
- const controller = new AbortController;
304
+ const controller = new AbortController();
335
305
  const timeout = timeout_ms > 0 ? setTimeout(() => controller.abort(), timeout_ms) : null;
336
306
  try {
337
307
  const response = await fetch(url, {
338
308
  method,
339
- headers: Object.keys(headers).length > 0 ? headers : undefined,
340
- body: method !== "GET" && method !== "HEAD" ? body : undefined,
309
+ headers: Object.keys(headers).length > 0 ? headers : void 0,
310
+ body: method !== "GET" && method !== "HEAD" ? body : void 0,
341
311
  signal: controller.signal
342
312
  });
343
- if (timeout)
344
- clearTimeout(timeout);
313
+ if (timeout) clearTimeout(timeout);
345
314
  new DataView(getMemory().buffer).setUint16(status_out, response.status, true);
346
315
  const bytes = new Uint8Array(await response.arrayBuffer());
347
316
  return writeBytes(buf_ptr, buf_max, bytes);
348
317
  } catch (err) {
349
- if (timeout)
350
- clearTimeout(timeout);
318
+ if (timeout) clearTimeout(timeout);
351
319
  const msg = err instanceof Error ? err.message : String(err);
352
320
  console.error(`wasm fetch failed: ${url} (${msg})`);
353
321
  return -1;
@@ -368,8 +336,7 @@ function createFetchImports(getMemory) {
368
336
  function decodeBlob(base64) {
369
337
  const binary = atob(base64);
370
338
  const bytes = new Uint8Array(binary.length);
371
- for (let i = 0;i < binary.length; i++)
372
- bytes[i] = binary.charCodeAt(i);
339
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
373
340
  return bytes;
374
341
  }
375
342
  function toD1Value(value) {
@@ -399,27 +366,22 @@ function toPositionalBindings(json) {
399
366
  }
400
367
  }
401
368
  function toWireValue(value) {
402
- if (value === null || value === undefined)
403
- return { kind: "null" };
404
- if (typeof value === "string")
405
- return { kind: "text", text: value };
406
- if (typeof value === "boolean")
407
- return { kind: "boolean", boolean: value };
369
+ if (value === null || value === void 0) return { kind: "null" };
370
+ if (typeof value === "string") return { kind: "text", text: value };
371
+ if (typeof value === "boolean") return { kind: "boolean", boolean: value };
408
372
  if (typeof value === "number") {
409
373
  return Number.isInteger(value) ? { kind: "integer", integer: value } : { kind: "float", float: value };
410
374
  }
411
375
  if (value instanceof ArrayBuffer) {
412
376
  const bytes = new Uint8Array(value);
413
377
  let binary = "";
414
- for (const byte of bytes)
415
- binary += String.fromCharCode(byte);
378
+ for (const byte of bytes) binary += String.fromCharCode(byte);
416
379
  return { kind: "blob", blob: btoa(binary) };
417
380
  }
418
381
  if (ArrayBuffer.isView(value)) {
419
382
  const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
420
383
  let binary = "";
421
- for (const byte of bytes)
422
- binary += String.fromCharCode(byte);
384
+ for (const byte of bytes) binary += String.fromCharCode(byte);
423
385
  return { kind: "blob", blob: btoa(binary) };
424
386
  }
425
387
  return { kind: "text", text: String(value) };
@@ -436,15 +398,14 @@ function valuesToWireRows(rows) {
436
398
  return rows.map((row) => row.map((value) => toWireValue(value)));
437
399
  }
438
400
  function createD1Imports(bindings, getMemory) {
439
- const encoder2 = new TextEncoder;
440
- const decoder2 = new TextDecoder;
401
+ const encoder2 = new TextEncoder();
402
+ const decoder2 = new TextDecoder();
441
403
  function readStr(ptr, len) {
442
404
  return decoder2.decode(new Uint8Array(getMemory().buffer, ptr, len));
443
405
  }
444
406
  function writeJson(buf_ptr, buf_max, value) {
445
407
  const data = encoder2.encode(JSON.stringify(value));
446
- if (data.length > buf_max)
447
- return -2;
408
+ if (data.length > buf_max) return -2;
448
409
  new Uint8Array(getMemory().buffer, buf_ptr, data.length).set(data);
449
410
  return data.length;
450
411
  }
@@ -453,8 +414,7 @@ function createD1Imports(bindings, getMemory) {
453
414
  }
454
415
  async function statement(ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len) {
455
416
  const database = binding(readStr(ns_ptr, ns_len));
456
- if (!database)
457
- return null;
417
+ if (!database) return null;
458
418
  const sql = readStr(sql_ptr, sql_len);
459
419
  const bindingsJson = JSON.parse(readStr(bindings_ptr, bindings_len));
460
420
  return database.prepare(sql).bind(...toPositionalBindings(bindingsJson));
@@ -473,8 +433,7 @@ function createD1Imports(bindings, getMemory) {
473
433
  db_open: (ns_ptr, ns_len) => binding(readStr(ns_ptr, ns_len)) ? 0 : -1,
474
434
  db_run: new Suspending(async (ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len, buf_ptr, buf_max) => {
475
435
  const stmt = await statement(ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len);
476
- if (!stmt)
477
- return -1;
436
+ if (!stmt) return -1;
478
437
  const result = await stmt.run();
479
438
  return writeJson(buf_ptr, buf_max, {
480
439
  last_insert_rowid: result.meta?.last_row_id ?? 0,
@@ -483,24 +442,20 @@ function createD1Imports(bindings, getMemory) {
483
442
  }),
484
443
  db_get: new Suspending(async (ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len, buf_ptr, buf_max) => {
485
444
  const stmt = await statement(ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len);
486
- if (!stmt)
487
- return -1;
445
+ if (!stmt) return -1;
488
446
  const row = await stmt.first();
489
- if (!row)
490
- return 0;
447
+ if (!row) return 0;
491
448
  return writeJson(buf_ptr, buf_max, [objectToWireRow(row)]);
492
449
  }),
493
450
  db_all: new Suspending(async (ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len, buf_ptr, buf_max) => {
494
451
  const stmt = await statement(ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len);
495
- if (!stmt)
496
- return -1;
452
+ if (!stmt) return -1;
497
453
  const result = await stmt.all();
498
454
  return writeJson(buf_ptr, buf_max, (result.results ?? []).map(objectToWireRow));
499
455
  }),
500
456
  db_values: new Suspending(async (ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len, buf_ptr, buf_max) => {
501
457
  const stmt = await statement(ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len);
502
- if (!stmt)
503
- return -1;
458
+ if (!stmt) return -1;
504
459
  const rows = await stmt.raw();
505
460
  return writeJson(buf_ptr, buf_max, valuesToWireRows(rows));
506
461
  })
@@ -508,19 +463,18 @@ function createD1Imports(bindings, getMemory) {
508
463
  }
509
464
 
510
465
  // src/wasi.ts
511
- class ProcExit extends Error {
512
- code;
466
+ var ProcExit = class extends Error {
513
467
  constructor(code) {
514
468
  super(`proc_exit(${code})`);
515
469
  this.code = code;
516
470
  }
517
- }
471
+ };
518
472
  function createWasiImports({
519
473
  request,
520
474
  stdinData,
521
475
  onStdout
522
476
  }) {
523
- const encoder2 = new TextEncoder;
477
+ const encoder2 = new TextEncoder();
524
478
  const url = new URL(request.url);
525
479
  const argStrings = [
526
480
  "wasm",
@@ -534,10 +488,9 @@ function createWasiImports({
534
488
  url.href
535
489
  ];
536
490
  request.headers.forEach((value, name) => {
537
- if (value)
538
- argStrings.push("--header", `${name}:${value}`);
491
+ if (value) argStrings.push("--header", `${name}:${value}`);
539
492
  });
540
- const encodedArgs = argStrings.map((a) => encoder2.encode(a + "\x00"));
493
+ const encodedArgs = argStrings.map((a) => encoder2.encode(a + "\0"));
541
494
  const argBufSize = encodedArgs.reduce((s, a) => s + a.length, 0);
542
495
  let wasmMemory = null;
543
496
  const setMemory = (m2) => {
@@ -549,13 +502,11 @@ function createWasiImports({
549
502
  const stderrDecoder = new TextDecoder("utf-8", { fatal: false, ignoreBOM: true });
550
503
  function processStderrChunk(chunk) {
551
504
  const text = stderrDecoder.decode(chunk, { stream: true });
552
- const lines = (stderrPartial + text).split(`
553
- `);
505
+ const lines = (stderrPartial + text).split("\n");
554
506
  stderrPartial = lines.pop() ?? "";
555
507
  for (const line of lines) {
556
508
  if (line.startsWith("__ZIEX_META__:")) {
557
- stderrMeta += line + `
558
- `;
509
+ stderrMeta += line + "\n";
559
510
  } else if (line.length > 0) {
560
511
  console.error("[ziex]", line);
561
512
  }
@@ -598,17 +549,14 @@ function createWasiImports({
598
549
  const dv = v();
599
550
  const mem = m();
600
551
  let written = 0;
601
- for (let i = 0;i < iovs_len; i++) {
552
+ for (let i = 0; i < iovs_len; i++) {
602
553
  const buf_ptr = dv.getUint32(iovs_ptr + i * 8, true);
603
554
  const buf_len = dv.getUint32(iovs_ptr + i * 8 + 4, true);
604
555
  const chunk = mem.slice(buf_ptr, buf_ptr + buf_len);
605
556
  if (fd === 1) {
606
- if (onStdout)
607
- onStdout(chunk);
608
- else
609
- stdoutChunks.push(chunk);
610
- } else if (fd === 2)
611
- processStderrChunk(chunk);
557
+ if (onStdout) onStdout(chunk);
558
+ else stdoutChunks.push(chunk);
559
+ } else if (fd === 2) processStderrChunk(chunk);
612
560
  written += buf_len;
613
561
  }
614
562
  dv.setUint32(nwritten_ptr, written, true);
@@ -619,7 +567,7 @@ function createWasiImports({
619
567
  const mem = m();
620
568
  const stdin = stdinData ?? new Uint8Array(0);
621
569
  let totalRead = 0;
622
- for (let i = 0;i < iovs_len; i++) {
570
+ for (let i = 0; i < iovs_len; i++) {
623
571
  const buf_ptr = dv.getUint32(iovs_ptr + i * 8, true);
624
572
  const buf_len = dv.getUint32(iovs_ptr + i * 8 + 4, true);
625
573
  if (fd === 0 && stdinOffset < stdin.length) {
@@ -776,19 +724,18 @@ function createWasiImports({
776
724
  v().setUint32(bufused_ptr, 0, true);
777
725
  return 76;
778
726
  },
727
+ // Stub for poll_oneoff - no blocking I/O in edge runtimes.
779
728
  poll_oneoff(_in, _out, _nsubscriptions, nevents_ptr) {
780
729
  v().setUint32(nevents_ptr, 0, true);
781
730
  return 0;
782
731
  }
783
732
  };
784
733
  function collectOutput() {
785
- const remaining = stderrDecoder.decode(undefined, { stream: false });
734
+ const remaining = stderrDecoder.decode(void 0, { stream: false });
786
735
  const tail = stderrPartial + remaining;
787
736
  if (tail.length > 0) {
788
- if (tail.startsWith("__ZIEX_META__:"))
789
- stderrMeta += tail;
790
- else
791
- console.error("[ziex]", tail);
737
+ if (tail.startsWith("__ZIEX_META__:")) stderrMeta += tail;
738
+ else console.error("[ziex]", tail);
792
739
  stderrPartial = "";
793
740
  }
794
741
  return {
@@ -830,22 +777,21 @@ function buildWsImports(Suspending, mem, decoder2, ws) {
830
777
  ws_recv: Suspending ? new Suspending(async (buf_ptr, buf_max) => {
831
778
  if (ws._resolveFirstSuspend) {
832
779
  const fn = ws._resolveFirstSuspend;
833
- ws._resolveFirstSuspend = undefined;
780
+ ws._resolveFirstSuspend = void 0;
834
781
  fn();
835
782
  }
836
783
  const deliver = (bytes) => {
837
- if (bytes === null)
838
- return -1;
784
+ if (bytes === null) return -1;
839
785
  const n = Math.min(bytes.length, buf_max);
840
786
  new Uint8Array(mem().buffer, buf_ptr, n).set(bytes.subarray(0, n));
841
787
  return n;
842
788
  };
843
- if (ws.messageQueue.length > 0)
844
- return deliver(ws.messageQueue.shift());
789
+ if (ws.messageQueue.length > 0) return deliver(ws.messageQueue.shift());
845
790
  return new Promise((resolve) => {
846
791
  ws.recvResolve = (bytes) => resolve(deliver(bytes));
847
792
  });
848
793
  }) : (_buf_ptr, _buf_max) => -1,
794
+ // Pub/sub - delegates to optional callbacks (real in DO, no-ops otherwise)
849
795
  ws_subscribe: (ptr, len) => {
850
796
  ws.subscribe?.(readStr(ptr, len));
851
797
  },
@@ -862,13 +808,12 @@ function buildWsImports(Suspending, mem, decoder2, ws) {
862
808
  }
863
809
  function attachWebSocket(ws) {
864
810
  const WebSocketPairCtor = globalThis.WebSocketPair;
865
- const pair = new WebSocketPairCtor;
811
+ const pair = new WebSocketPairCtor();
866
812
  const client = pair[0];
867
813
  const server = pair[1];
868
814
  ws.server = server;
869
815
  server.accept();
870
- for (const data of ws.pendingWrites)
871
- server.send(data);
816
+ for (const data of ws.pendingWrites) server.send(data);
872
817
  ws.pendingWrites = [];
873
818
  server.addEventListener("message", (event) => {
874
819
  const data = typeof event.data === "string" ? new TextEncoder().encode(event.data) : new Uint8Array(event.data);
@@ -891,7 +836,8 @@ function attachWebSocket(ws) {
891
836
  }
892
837
  function buildSysImports(jspi, Suspending) {
893
838
  return {
894
- sleep_ms: jspi ? new Suspending(async (ms) => new Promise((r) => setTimeout(r, ms))) : (_ms) => {}
839
+ sleep_ms: jspi ? new Suspending(async (ms) => new Promise((r) => setTimeout(r, ms))) : (_ms) => {
840
+ }
895
841
  };
896
842
  }
897
843
  function executeWasm(instance, jspi, Suspending, wsState) {
@@ -899,15 +845,13 @@ function executeWasm(instance, jspi, Suspending, wsState) {
899
845
  try {
900
846
  instance.exports._start();
901
847
  } catch (e) {
902
- if (!(e instanceof ProcExit))
903
- throw e;
848
+ if (!(e instanceof ProcExit)) throw e;
904
849
  }
905
850
  return Promise.resolve();
906
851
  }
907
852
  const start = WebAssembly.promising(instance.exports._start);
908
853
  return start().catch((e) => {
909
- if (e instanceof Error && e.message.startsWith("proc_exit"))
910
- return;
854
+ if (e instanceof Error && e.message.startsWith("proc_exit")) return;
911
855
  throw e;
912
856
  }).finally(() => {
913
857
  if (wsState.recvResolve) {
@@ -918,23 +862,21 @@ function executeWasm(instance, jspi, Suspending, wsState) {
918
862
  });
919
863
  }
920
864
  function parseZiexMeta(stderrText) {
921
- const meta = { status: 200, headers: new Headers, streaming: false };
865
+ const meta = { status: 200, headers: new Headers(), streaming: false };
922
866
  const metaPrefix = "__ZIEX_META__:";
923
- const metaLine = stderrText.split(`
924
- `).find((line) => line.startsWith(metaPrefix));
867
+ const metaLine = stderrText.split("\n").find((line) => line.startsWith(metaPrefix));
925
868
  if (metaLine) {
926
869
  try {
927
870
  const parsed = JSON.parse(metaLine.slice(metaPrefix.length));
928
- if (parsed.status)
929
- meta.status = parsed.status;
930
- if (parsed.streaming === true)
931
- meta.streaming = true;
871
+ if (parsed.status) meta.status = parsed.status;
872
+ if (parsed.streaming === true) meta.streaming = true;
932
873
  if (Array.isArray(parsed.headers)) {
933
874
  for (const [name, value] of parsed.headers) {
934
875
  meta.headers.append(name, value);
935
876
  }
936
877
  }
937
- } catch {}
878
+ } catch {
879
+ }
938
880
  }
939
881
  return meta;
940
882
  }
@@ -953,17 +895,15 @@ async function run({
953
895
  const id = doNamespace.idFromName(new URL(request.url).pathname);
954
896
  return doNamespace.get(id).fetch(request);
955
897
  }
956
- const stdinData = request.body ? new Uint8Array(await request.arrayBuffer()) : undefined;
898
+ const stdinData = request.body ? new Uint8Array(await request.arrayBuffer()) : void 0;
957
899
  const stdoutChunks = [];
958
900
  let streamWriter = null;
959
901
  const { wasiImport, setMemory, collectOutput } = createWasiImports({
960
902
  request,
961
903
  stdinData,
962
904
  onStdout: (chunk) => {
963
- if (streamWriter)
964
- streamWriter.write(chunk);
965
- else
966
- stdoutChunks.push(chunk);
905
+ if (streamWriter) void streamWriter.write(chunk);
906
+ else stdoutChunks.push(chunk);
967
907
  }
968
908
  });
969
909
  let wasmMemory = null;
@@ -981,7 +921,7 @@ async function run({
981
921
  const instance = new WebAssembly.Instance(module, {
982
922
  wasi_snapshot_preview1: { ...wasi?.wasiImport, ...wasiImport },
983
923
  __zx_sys: buildSysImports(jspi, Suspending),
984
- __zx_ws: buildWsImports(jspi ? Suspending : null, mem, new TextDecoder, wsState),
924
+ __zx_ws: buildWsImports(jspi ? Suspending : null, mem, new TextDecoder(), wsState),
985
925
  __zx_kv: createKVImports(kvBindings ?? { default: createMemoryKV() }, mem),
986
926
  __zx_db: createD1Imports(dbBindings ?? {}, mem),
987
927
  __zx_net: createFetchImports(mem),
@@ -1000,12 +940,11 @@ async function run({
1000
940
  const { stderrText: earlyStderrText } = collectOutput();
1001
941
  const earlyMeta = parseZiexMeta(earlyStderrText);
1002
942
  if (earlyMeta.streaming) {
1003
- const { readable, writable } = new TransformStream;
943
+ const { readable, writable } = new TransformStream();
1004
944
  streamWriter = writable.getWriter();
1005
- for (const chunk of stdoutChunks)
1006
- streamWriter.write(chunk);
945
+ for (const chunk of stdoutChunks) void streamWriter.write(chunk);
1007
946
  stdoutChunks.length = 0;
1008
- wasmPromise.finally(() => streamWriter?.close());
947
+ void wasmPromise.finally(() => streamWriter?.close());
1009
948
  return new Response(readable, { status: earlyMeta.status, headers: earlyMeta.headers });
1010
949
  }
1011
950
  await wasmPromise;
@@ -1018,8 +957,7 @@ async function run({
1018
957
  meta.headers.delete("content-length");
1019
958
  return new Response(null, { status: meta.status, headers: meta.headers });
1020
959
  }
1021
- if (!meta.headers.has("content-length"))
1022
- meta.headers.set("content-length", String(body.byteLength));
960
+ if (!meta.headers.has("content-length")) meta.headers.set("content-length", String(body.byteLength));
1023
961
  return new Response(body.buffer, { status: meta.status, headers: meta.headers });
1024
962
  }
1025
963
 
@@ -1046,22 +984,39 @@ async function resolveModule(input) {
1046
984
  }
1047
985
  return input;
1048
986
  }
1049
-
1050
- class Ziex {
1051
- options;
1052
- resolved = null;
987
+ var Ziex = class {
1053
988
  constructor(options) {
989
+ this.resolved = null;
990
+ /**
991
+ * Fetch handler called by the runtime on every request.
992
+ *
993
+ * Arrow function so `this` is always the class instance, even when the
994
+ * runtime extracts `fetch` from the exported object (e.g. Bun).
995
+ */
996
+ this.fetch = async (request, env, ctx) => {
997
+ const module = await this.getModule();
998
+ const { wasi, imports, websocket } = this.options;
999
+ return run({
1000
+ request,
1001
+ env,
1002
+ ctx,
1003
+ module,
1004
+ wasi,
1005
+ imports,
1006
+ kv: this.resolveKV(env),
1007
+ db: this.resolveDB(env),
1008
+ websocket: websocket !== void 0 ? env[websocket] : void 0
1009
+ });
1010
+ };
1054
1011
  this.options = options;
1055
1012
  }
1056
1013
  async getModule() {
1057
- if (!this.resolved)
1058
- this.resolved = await resolveModule(this.options.module);
1014
+ if (!this.resolved) this.resolved = await resolveModule(this.options.module);
1059
1015
  return this.resolved;
1060
1016
  }
1061
1017
  resolveKV(env) {
1062
1018
  const { kv } = this.options;
1063
- if (kv === undefined)
1064
- return;
1019
+ if (kv === void 0) return void 0;
1065
1020
  if (typeof kv === "object" && kv !== null) {
1066
1021
  const result = {};
1067
1022
  for (const [name, key] of Object.entries(kv)) {
@@ -1073,8 +1028,7 @@ class Ziex {
1073
1028
  }
1074
1029
  resolveDB(env) {
1075
1030
  const { db } = this.options;
1076
- if (db === undefined)
1077
- return;
1031
+ if (db === void 0) return void 0;
1078
1032
  if (typeof db === "object" && db !== null) {
1079
1033
  const result = {};
1080
1034
  for (const [name, key] of Object.entries(db)) {
@@ -1084,22 +1038,7 @@ class Ziex {
1084
1038
  }
1085
1039
  return { default: env[db] };
1086
1040
  }
1087
- fetch = async (request, env, ctx) => {
1088
- const module = await this.getModule();
1089
- const { wasi, imports, websocket } = this.options;
1090
- return run({
1091
- request,
1092
- env,
1093
- ctx,
1094
- module,
1095
- wasi,
1096
- imports,
1097
- kv: this.resolveKV(env),
1098
- db: this.resolveDB(env),
1099
- websocket: websocket !== undefined ? env[websocket] : undefined
1100
- });
1101
- };
1102
- }
1041
+ };
1103
1042
  export {
1104
1043
  Ziex
1105
1044
  };