ziex 0.0.1-dev.7 → 0.1.0-dev.1014

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.
package/index.js CHANGED
@@ -1,31 +1,939 @@
1
- // src/index.ts
2
- var zx = {
3
- name: "zx",
4
- version: "0.0.1-dev.270",
5
- description: "ZX is a framework for building web applications with Zig.",
6
- repository: "https://github.com/nurulhudaapon/zx",
7
- fingerprint: 14616285862371232000,
8
- minimum_zig_version: "0.15.2",
9
- dependencies: {
10
- httpz: {
11
- url: "git+https://github.com/nurulhudaapon/httpz.git#7268154f43f5827bf78668e8e79a00f2ebe4db13",
12
- hash: "httpz-0.0.0-PNVzrBgtBwCVkSJyophIX6WHwDR0r8XhBGQr96Kk-1El"
13
- },
14
- zli: {
15
- url: "git+https://github.com/nurulhudaapon/cliz.git#aff3b54879e7514afaf8c87f1abe22121b8992d4",
16
- hash: "zli-4.3.0-LeUjpu_fAABOSVASSCW2fFh8SFVNHrxQGDXGPNzcSE_i"
17
- },
18
- zig_js: {
19
- url: "git+https://github.com/nurulhudaapon/jsz.git#04db83c617da1956ac5adc1cb9ba1e434c1cb6fd",
20
- hash: "zig_js-0.0.0-rjCAV-6GAADxFug7rDmPH-uM_XcnJ5NmuAMJCAscMjhi"
21
- }
22
- },
23
- paths: [
24
- "build.zig",
25
- "build.zig.zon",
26
- "src"
27
- ]
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
+ });
28
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
+ // src/wasm/wasi.ts
25
+ var decoder = new TextDecoder;
26
+ var encoder = new TextEncoder;
27
+
28
+ class ZxWasiBridge {
29
+ #alloc;
30
+ #fetchCompleteHandler;
31
+ #memory;
32
+ #cb;
33
+ #intervals = new Map;
34
+ #memView = null;
35
+ #memBuf = null;
36
+ constructor(exports) {
37
+ this.#memory = exports.memory;
38
+ this.#alloc = exports.__zx_alloc;
39
+ this.#fetchCompleteHandler = exports.__zx_fetch_complete;
40
+ this.#cb = exports.__zx_cb;
41
+ }
42
+ #view() {
43
+ const buf = this.#memory.buffer;
44
+ if (buf !== this.#memBuf) {
45
+ this.#memBuf = buf;
46
+ this.#memView = new Uint8Array(buf);
47
+ }
48
+ return this.#memView;
49
+ }
50
+ #readString(ptr, len) {
51
+ return decoder.decode(this.#view().subarray(ptr, ptr + len));
52
+ }
53
+ #writeBytes(ptr, data) {
54
+ this.#view().set(data, ptr);
55
+ }
56
+ log(level, ptr, len) {
57
+ const msg = decoder.decode(this.#view().subarray(ptr, ptr + len));
58
+ switch (level) {
59
+ case 0:
60
+ console.error(msg);
61
+ break;
62
+ case 1:
63
+ console.warn(msg);
64
+ break;
65
+ case 3:
66
+ console.debug(msg);
67
+ break;
68
+ default:
69
+ console.log(msg);
70
+ break;
71
+ }
72
+ }
73
+ fetchAsync(urlPtr, urlLen, methodPtr, methodLen, headersPtr, headersLen, bodyPtr, bodyLen, timeoutMs, fetchId) {
74
+ const url = this.#readString(urlPtr, urlLen);
75
+ const method = methodLen > 0 ? this.#readString(methodPtr, methodLen) : "GET";
76
+ const headersJson = headersLen > 0 ? this.#readString(headersPtr, headersLen) : "{}";
77
+ const body = bodyLen > 0 ? this.#readString(bodyPtr, bodyLen) : undefined;
78
+ let headers = {};
79
+ try {
80
+ headers = JSON.parse(headersJson);
81
+ } catch {
82
+ for (const line of headersJson.split(`
83
+ `)) {
84
+ const i = line.indexOf(":");
85
+ if (i > 0)
86
+ headers[line.slice(0, i)] = line.slice(i + 1);
87
+ }
88
+ }
89
+ const controller = new AbortController;
90
+ const timeout = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : null;
91
+ fetch(url, {
92
+ method,
93
+ headers: Object.keys(headers).length > 0 ? headers : undefined,
94
+ body: method !== "GET" && method !== "HEAD" ? body : undefined,
95
+ signal: controller.signal
96
+ }).then(async (res) => {
97
+ if (timeout)
98
+ clearTimeout(timeout);
99
+ this.#notifyFetchComplete(fetchId, res.status, await res.text(), false);
100
+ }).catch((err) => {
101
+ if (timeout)
102
+ clearTimeout(timeout);
103
+ const msg = err.name === "AbortError" ? "Request timeout" : err.message ?? "Fetch failed";
104
+ this.#notifyFetchComplete(fetchId, 0, msg, true);
105
+ });
106
+ }
107
+ #notifyFetchComplete(fetchId, status, body, isError) {
108
+ const encoded = encoder.encode(body);
109
+ const ptr = this.#alloc(encoded.length);
110
+ this.#writeBytes(ptr, encoded);
111
+ this.#fetchCompleteHandler(fetchId, status, ptr, encoded.length, isError ? 1 : 0);
112
+ }
113
+ setTimeout(callbackId, delayMs) {
114
+ setTimeout(() => this.#cb?.(3, callbackId, 0n), delayMs);
115
+ }
116
+ setInterval(callbackId, intervalMs) {
117
+ const handle = setInterval(() => this.#cb?.(4, callbackId, 0n), intervalMs);
118
+ this.#intervals.set(callbackId, handle);
119
+ }
120
+ clearInterval(callbackId) {
121
+ const handle = this.#intervals.get(callbackId);
122
+ if (handle !== undefined) {
123
+ clearInterval(handle);
124
+ this.#intervals.delete(callbackId);
125
+ }
126
+ }
127
+ static createImportObject(bridgeRef) {
128
+ return {
129
+ __zx: {
130
+ _log: (level, ptr, len) => {
131
+ bridgeRef.current?.log(level, ptr, len);
132
+ },
133
+ _fetchAsync: (urlPtr, urlLen, methodPtr, methodLen, headersPtr, headersLen, bodyPtr, bodyLen, timeoutMs, fetchId) => {
134
+ bridgeRef.current?.fetchAsync(urlPtr, urlLen, methodPtr, methodLen, headersPtr, headersLen, bodyPtr, bodyLen, timeoutMs, fetchId);
135
+ },
136
+ _setTimeout: (callbackId, delayMs) => {
137
+ bridgeRef.current?.setTimeout(callbackId, delayMs);
138
+ },
139
+ _setInterval: (callbackId, intervalMs) => {
140
+ bridgeRef.current?.setInterval(callbackId, intervalMs);
141
+ },
142
+ _clearInterval: (callbackId) => {
143
+ bridgeRef.current?.clearInterval(callbackId);
144
+ }
145
+ }
146
+ };
147
+ }
148
+ }
149
+
150
+ // src/kv.ts
151
+ var exports_kv = {};
152
+ __export(exports_kv, {
153
+ createMemoryKV: () => createMemoryKV,
154
+ createKVImports: () => createKVImports
155
+ });
156
+ function createMemoryKV() {
157
+ const store = new Map;
158
+ return {
159
+ async get(key) {
160
+ return store.get(key) ?? null;
161
+ },
162
+ async put(key, value) {
163
+ store.set(key, value);
164
+ },
165
+ async delete(key) {
166
+ store.delete(key);
167
+ },
168
+ async list(options) {
169
+ const keys = [...store.keys()].filter((k) => !options?.prefix || k.startsWith(options.prefix)).map((name) => ({ name }));
170
+ return { keys };
171
+ }
172
+ };
173
+ }
174
+ function isSyncKVNamespace(binding) {
175
+ const candidate = binding;
176
+ return typeof candidate.getSync === "function" && typeof candidate.putSync === "function" && typeof candidate.deleteSync === "function" && typeof candidate.listSync === "function";
177
+ }
178
+ function createKVImports(bindings, getMemory) {
179
+ const encoder2 = new TextEncoder;
180
+ const decoder2 = new TextDecoder;
181
+ function readStr(ptr, len) {
182
+ return decoder2.decode(new Uint8Array(getMemory().buffer, ptr, len));
183
+ }
184
+ function writeBytes(buf_ptr, buf_max, data) {
185
+ if (data.length > buf_max)
186
+ return -2;
187
+ new Uint8Array(getMemory().buffer, buf_ptr, data.length).set(data);
188
+ return data.length;
189
+ }
190
+ function binding(ns) {
191
+ return bindings[ns] ?? bindings["default"] ?? null;
192
+ }
193
+ const Suspending = WebAssembly.Suspending;
194
+ if (typeof Suspending !== "function") {
195
+ let syncBinding = function(ns) {
196
+ const candidate = binding(ns);
197
+ return candidate && isSyncKVNamespace(candidate) ? candidate : null;
198
+ };
199
+ return {
200
+ kv_get: (ns_ptr, ns_len, key_ptr, key_len, buf_ptr, buf_max) => {
201
+ const b = syncBinding(readStr(ns_ptr, ns_len));
202
+ if (!b)
203
+ return -1;
204
+ const value = b.getSync(readStr(key_ptr, key_len));
205
+ if (value === null)
206
+ return -1;
207
+ return writeBytes(buf_ptr, buf_max, encoder2.encode(value));
208
+ },
209
+ kv_put: (ns_ptr, ns_len, key_ptr, key_len, val_ptr, val_len) => {
210
+ const b = syncBinding(readStr(ns_ptr, ns_len));
211
+ if (!b)
212
+ return 0;
213
+ b.putSync(readStr(key_ptr, key_len), readStr(val_ptr, val_len));
214
+ return 0;
215
+ },
216
+ kv_delete: (ns_ptr, ns_len, key_ptr, key_len) => {
217
+ const b = syncBinding(readStr(ns_ptr, ns_len));
218
+ if (!b)
219
+ return 0;
220
+ b.deleteSync(readStr(key_ptr, key_len));
221
+ return 0;
222
+ },
223
+ kv_list: (ns_ptr, ns_len, pfx_ptr, pfx_len, buf_ptr, buf_max) => {
224
+ const b = syncBinding(readStr(ns_ptr, ns_len));
225
+ if (!b)
226
+ return writeBytes(buf_ptr, buf_max, encoder2.encode("[]"));
227
+ const prefix = readStr(pfx_ptr, pfx_len);
228
+ const result = b.listSync(prefix.length > 0 ? { prefix } : undefined);
229
+ return writeBytes(buf_ptr, buf_max, encoder2.encode(JSON.stringify(result.keys.map((k) => k.name))));
230
+ }
231
+ };
232
+ }
233
+ return {
234
+ kv_get: new Suspending(async (ns_ptr, ns_len, key_ptr, key_len, buf_ptr, buf_max) => {
235
+ const b = binding(readStr(ns_ptr, ns_len));
236
+ if (!b)
237
+ return -1;
238
+ const value = await b.get(readStr(key_ptr, key_len));
239
+ if (value === null)
240
+ return -1;
241
+ return writeBytes(buf_ptr, buf_max, encoder2.encode(value));
242
+ }),
243
+ kv_put: new Suspending(async (ns_ptr, ns_len, key_ptr, key_len, val_ptr, val_len) => {
244
+ const b = binding(readStr(ns_ptr, ns_len));
245
+ if (!b)
246
+ return -1;
247
+ await b.put(readStr(key_ptr, key_len), readStr(val_ptr, val_len));
248
+ return 0;
249
+ }),
250
+ kv_delete: new Suspending(async (ns_ptr, ns_len, key_ptr, key_len) => {
251
+ const b = binding(readStr(ns_ptr, ns_len));
252
+ if (!b)
253
+ return -1;
254
+ await b.delete(readStr(key_ptr, key_len));
255
+ return 0;
256
+ }),
257
+ kv_list: new Suspending(async (ns_ptr, ns_len, prefix_ptr, prefix_len, buf_ptr, buf_max) => {
258
+ const b = binding(readStr(ns_ptr, ns_len));
259
+ if (!b)
260
+ return writeBytes(buf_ptr, buf_max, encoder2.encode("[]"));
261
+ const prefix = readStr(prefix_ptr, prefix_len);
262
+ const result = await b.list(prefix.length > 0 ? { prefix } : undefined);
263
+ return writeBytes(buf_ptr, buf_max, encoder2.encode(JSON.stringify(result.keys.map((k) => k.name))));
264
+ })
265
+ };
266
+ }
267
+
268
+ // src/db.ts
269
+ function decodeBlob(base64) {
270
+ const binary = atob(base64);
271
+ const bytes = new Uint8Array(binary.length);
272
+ for (let i = 0;i < binary.length; i++)
273
+ bytes[i] = binary.charCodeAt(i);
274
+ return bytes;
275
+ }
276
+ function toD1Value(value) {
277
+ switch (value.kind) {
278
+ case "null":
279
+ return null;
280
+ case "integer":
281
+ return value.integer;
282
+ case "float":
283
+ return value.float;
284
+ case "text":
285
+ return value.text;
286
+ case "blob":
287
+ return decodeBlob(value.blob);
288
+ case "boolean":
289
+ return value.boolean;
290
+ }
291
+ }
292
+ function toPositionalBindings(json) {
293
+ switch (json.kind) {
294
+ case "none":
295
+ return [];
296
+ case "positional":
297
+ return json.values.map(toD1Value);
298
+ case "named":
299
+ throw new Error("Cloudflare D1 adapter does not support named bindings yet");
300
+ }
301
+ }
302
+ function toWireValue(value) {
303
+ if (value === null || value === undefined)
304
+ return { kind: "null" };
305
+ if (typeof value === "string")
306
+ return { kind: "text", text: value };
307
+ if (typeof value === "boolean")
308
+ return { kind: "boolean", boolean: value };
309
+ if (typeof value === "number") {
310
+ return Number.isInteger(value) ? { kind: "integer", integer: value } : { kind: "float", float: value };
311
+ }
312
+ if (value instanceof ArrayBuffer) {
313
+ const bytes = new Uint8Array(value);
314
+ let binary = "";
315
+ for (const byte of bytes)
316
+ binary += String.fromCharCode(byte);
317
+ return { kind: "blob", blob: btoa(binary) };
318
+ }
319
+ if (ArrayBuffer.isView(value)) {
320
+ const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
321
+ let binary = "";
322
+ for (const byte of bytes)
323
+ binary += String.fromCharCode(byte);
324
+ return { kind: "blob", blob: btoa(binary) };
325
+ }
326
+ return { kind: "text", text: String(value) };
327
+ }
328
+ function objectToWireRow(record) {
329
+ return {
330
+ fields: Object.entries(record).map(([name, value]) => ({
331
+ name,
332
+ value: toWireValue(value)
333
+ }))
334
+ };
335
+ }
336
+ function valuesToWireRows(rows) {
337
+ return rows.map((row) => row.map((value) => toWireValue(value)));
338
+ }
339
+ function createD1Imports(bindings, getMemory) {
340
+ const encoder2 = new TextEncoder;
341
+ const decoder2 = new TextDecoder;
342
+ function readStr(ptr, len) {
343
+ return decoder2.decode(new Uint8Array(getMemory().buffer, ptr, len));
344
+ }
345
+ function writeJson(buf_ptr, buf_max, value) {
346
+ const data = encoder2.encode(JSON.stringify(value));
347
+ if (data.length > buf_max)
348
+ return -2;
349
+ new Uint8Array(getMemory().buffer, buf_ptr, data.length).set(data);
350
+ return data.length;
351
+ }
352
+ function binding(ns) {
353
+ return bindings[ns] ?? bindings["default"] ?? null;
354
+ }
355
+ async function statement(ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len) {
356
+ const database = binding(readStr(ns_ptr, ns_len));
357
+ if (!database)
358
+ return null;
359
+ const sql = readStr(sql_ptr, sql_len);
360
+ const bindingsJson = JSON.parse(readStr(bindings_ptr, bindings_len));
361
+ return database.prepare(sql).bind(...toPositionalBindings(bindingsJson));
362
+ }
363
+ const Suspending = WebAssembly.Suspending;
364
+ if (typeof Suspending !== "function") {
365
+ return {
366
+ db_open: (_ns, _ns_len) => -1,
367
+ db_run: (_a, _b, _c, _d, _e, _f, _g, _h) => -1,
368
+ db_get: (_a, _b, _c, _d, _e, _f, _g, _h) => -1,
369
+ db_all: (_a, _b, _c, _d, _e, _f, _g, _h) => -1,
370
+ db_values: (_a, _b, _c, _d, _e, _f, _g, _h) => -1
371
+ };
372
+ }
373
+ return {
374
+ db_open: (ns_ptr, ns_len) => binding(readStr(ns_ptr, ns_len)) ? 0 : -1,
375
+ db_run: new Suspending(async (ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len, buf_ptr, buf_max) => {
376
+ const stmt = await statement(ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len);
377
+ if (!stmt)
378
+ return -1;
379
+ const result = await stmt.run();
380
+ return writeJson(buf_ptr, buf_max, {
381
+ last_insert_rowid: result.meta?.last_row_id ?? 0,
382
+ changes: result.meta?.changes ?? 0
383
+ });
384
+ }),
385
+ db_get: new Suspending(async (ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len, buf_ptr, buf_max) => {
386
+ const stmt = await statement(ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len);
387
+ if (!stmt)
388
+ return -1;
389
+ const row = await stmt.first();
390
+ if (!row)
391
+ return 0;
392
+ return writeJson(buf_ptr, buf_max, [objectToWireRow(row)]);
393
+ }),
394
+ db_all: new Suspending(async (ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len, buf_ptr, buf_max) => {
395
+ const stmt = await statement(ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len);
396
+ if (!stmt)
397
+ return -1;
398
+ const result = await stmt.all();
399
+ return writeJson(buf_ptr, buf_max, (result.results ?? []).map(objectToWireRow));
400
+ }),
401
+ db_values: new Suspending(async (ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len, buf_ptr, buf_max) => {
402
+ const stmt = await statement(ns_ptr, ns_len, sql_ptr, sql_len, bindings_ptr, bindings_len);
403
+ if (!stmt)
404
+ return -1;
405
+ const rows = await stmt.raw();
406
+ return writeJson(buf_ptr, buf_max, valuesToWireRows(rows));
407
+ })
408
+ };
409
+ }
410
+
411
+ // src/wasi.ts
412
+ class ProcExit extends Error {
413
+ code;
414
+ constructor(code) {
415
+ super(`proc_exit(${code})`);
416
+ this.code = code;
417
+ }
418
+ }
419
+ function createWasiImports({
420
+ request,
421
+ stdinData,
422
+ onStdout
423
+ }) {
424
+ const encoder2 = new TextEncoder;
425
+ const url = new URL(request.url);
426
+ const argStrings = [
427
+ "wasm",
428
+ "--pathname",
429
+ url.pathname,
430
+ "--method",
431
+ request.method,
432
+ "--search",
433
+ url.search
434
+ ];
435
+ request.headers.forEach((value, name) => {
436
+ if (value)
437
+ argStrings.push("--header", `${name}:${value}`);
438
+ });
439
+ const encodedArgs = argStrings.map((a) => encoder2.encode(a + "\x00"));
440
+ const argBufSize = encodedArgs.reduce((s, a) => s + a.length, 0);
441
+ let wasmMemory = null;
442
+ const setMemory = (m2) => {
443
+ wasmMemory = m2;
444
+ };
445
+ const stdoutChunks = [];
446
+ let stderrMeta = "";
447
+ let stderrPartial = "";
448
+ const stderrDecoder = new TextDecoder("utf-8", { fatal: false, ignoreBOM: true });
449
+ function processStderrChunk(chunk) {
450
+ const text = stderrDecoder.decode(chunk, { stream: true });
451
+ const lines = (stderrPartial + text).split(`
452
+ `);
453
+ stderrPartial = lines.pop() ?? "";
454
+ for (const line of lines) {
455
+ if (line.startsWith("__EDGE_META__:")) {
456
+ stderrMeta += line + `
457
+ `;
458
+ } else if (line.length > 0) {
459
+ console.error("[ziex]", line);
460
+ }
461
+ }
462
+ }
463
+ let stdinOffset = 0;
464
+ function v() {
465
+ return new DataView(wasmMemory.buffer);
466
+ }
467
+ function m() {
468
+ return new Uint8Array(wasmMemory.buffer);
469
+ }
470
+ const wasiImport = {
471
+ args_sizes_get(argc_ptr, argv_buf_size_ptr) {
472
+ v().setUint32(argc_ptr, encodedArgs.length, true);
473
+ v().setUint32(argv_buf_size_ptr, argBufSize, true);
474
+ return 0;
475
+ },
476
+ args_get(argv_ptr, argv_buf_ptr) {
477
+ const dv = v();
478
+ const mem = m();
479
+ let offset = argv_buf_ptr;
480
+ for (const arg of encodedArgs) {
481
+ dv.setUint32(argv_ptr, offset, true);
482
+ mem.set(arg, offset);
483
+ argv_ptr += 4;
484
+ offset += arg.length;
485
+ }
486
+ return 0;
487
+ },
488
+ environ_sizes_get(count_ptr, buf_size_ptr) {
489
+ v().setUint32(count_ptr, 0, true);
490
+ v().setUint32(buf_size_ptr, 0, true);
491
+ return 0;
492
+ },
493
+ environ_get(_environ_ptr, _environ_buf_ptr) {
494
+ return 0;
495
+ },
496
+ fd_write(fd, iovs_ptr, iovs_len, nwritten_ptr) {
497
+ const dv = v();
498
+ const mem = m();
499
+ let written = 0;
500
+ for (let i = 0;i < iovs_len; i++) {
501
+ const buf_ptr = dv.getUint32(iovs_ptr + i * 8, true);
502
+ const buf_len = dv.getUint32(iovs_ptr + i * 8 + 4, true);
503
+ const chunk = mem.slice(buf_ptr, buf_ptr + buf_len);
504
+ if (fd === 1) {
505
+ if (onStdout)
506
+ onStdout(chunk);
507
+ else
508
+ stdoutChunks.push(chunk);
509
+ } else if (fd === 2)
510
+ processStderrChunk(chunk);
511
+ written += buf_len;
512
+ }
513
+ dv.setUint32(nwritten_ptr, written, true);
514
+ return 0;
515
+ },
516
+ fd_read(fd, iovs_ptr, iovs_len, nread_ptr) {
517
+ const dv = v();
518
+ const mem = m();
519
+ const stdin = stdinData ?? new Uint8Array(0);
520
+ let totalRead = 0;
521
+ for (let i = 0;i < iovs_len; i++) {
522
+ const buf_ptr = dv.getUint32(iovs_ptr + i * 8, true);
523
+ const buf_len = dv.getUint32(iovs_ptr + i * 8 + 4, true);
524
+ if (fd === 0 && stdinOffset < stdin.length) {
525
+ const toRead = Math.min(buf_len, stdin.length - stdinOffset);
526
+ mem.set(stdin.subarray(stdinOffset, stdinOffset + toRead), buf_ptr);
527
+ stdinOffset += toRead;
528
+ totalRead += toRead;
529
+ }
530
+ }
531
+ dv.setUint32(nread_ptr, totalRead, true);
532
+ return 0;
533
+ },
534
+ fd_fdstat_get(_fd, fdstat_ptr) {
535
+ const dv = v();
536
+ dv.setUint8(fdstat_ptr, 2);
537
+ dv.setUint8(fdstat_ptr + 1, 0);
538
+ dv.setUint16(fdstat_ptr + 2, 0, true);
539
+ dv.setUint32(fdstat_ptr + 4, 0, true);
540
+ dv.setBigUint64(fdstat_ptr + 8, 0n, true);
541
+ dv.setBigUint64(fdstat_ptr + 16, 0n, true);
542
+ return 0;
543
+ },
544
+ fd_prestat_get(_fd, _bufptr) {
545
+ return 8;
546
+ },
547
+ fd_prestat_dir_name(_fd, _path, _path_len) {
548
+ return 8;
549
+ },
550
+ fd_close(_fd) {
551
+ return 0;
552
+ },
553
+ fd_pread(_fd, _iovs, _iovs_len, _offset, nread_ptr) {
554
+ v().setUint32(nread_ptr, 0, true);
555
+ return 0;
556
+ },
557
+ fd_pwrite(_fd, _iovs, _iovs_len, _offset, nwritten_ptr) {
558
+ v().setUint32(nwritten_ptr, 0, true);
559
+ return 0;
560
+ },
561
+ fd_filestat_get(_fd, filestat_ptr) {
562
+ const dv = v();
563
+ dv.setBigUint64(filestat_ptr, 0n, true);
564
+ dv.setBigUint64(filestat_ptr + 8, 0n, true);
565
+ dv.setUint8(filestat_ptr + 16, 2);
566
+ dv.setBigUint64(filestat_ptr + 24, 1n, true);
567
+ dv.setBigUint64(filestat_ptr + 32, 0n, true);
568
+ dv.setBigUint64(filestat_ptr + 40, 0n, true);
569
+ dv.setBigUint64(filestat_ptr + 48, 0n, true);
570
+ dv.setBigUint64(filestat_ptr + 56, 0n, true);
571
+ return 0;
572
+ },
573
+ fd_seek(_fd, _offset, _whence, newoffset_ptr) {
574
+ v().setBigInt64(newoffset_ptr, 0n, true);
575
+ return 0;
576
+ },
577
+ proc_exit(code) {
578
+ throw new ProcExit(code);
579
+ },
580
+ sched_yield() {
581
+ return 0;
582
+ },
583
+ clock_time_get(_id, _precision, time_ptr) {
584
+ v().setBigUint64(time_ptr, BigInt(Date.now()) * 1000000n, true);
585
+ return 0;
586
+ },
587
+ random_get(buf_ptr, buf_len) {
588
+ crypto.getRandomValues(new Uint8Array(wasmMemory.buffer, buf_ptr, buf_len));
589
+ return 0;
590
+ },
591
+ path_open(_fd, _dirflags, _path, _path_len, _oflags, _rights_base, _rights_inheriting, _fdflags, opened_fd_ptr) {
592
+ v().setInt32(opened_fd_ptr, -1, true);
593
+ return 76;
594
+ },
595
+ path_create_directory(_fd, _path, _path_len) {
596
+ return 76;
597
+ },
598
+ path_unlink_file(_fd, _path, _path_len) {
599
+ return 76;
600
+ },
601
+ path_remove_directory(_fd, _path, _path_len) {
602
+ return 76;
603
+ },
604
+ path_rename(_fd, _old_path, _old_path_len, _new_fd, _new_path, _new_path_len) {
605
+ return 76;
606
+ },
607
+ path_filestat_get(_fd, _flags, _path, _path_len, filestat_ptr) {
608
+ new Uint8Array(wasmMemory.buffer, filestat_ptr, 64).fill(0);
609
+ return 76;
610
+ },
611
+ path_readlink(_fd, _path, _path_len, _buf, _buf_len, nread_ptr) {
612
+ v().setUint32(nread_ptr, 0, true);
613
+ return 76;
614
+ },
615
+ fd_readdir(_fd, _buf, _buf_len, _cookie, bufused_ptr) {
616
+ v().setUint32(bufused_ptr, 0, true);
617
+ return 76;
618
+ },
619
+ poll_oneoff(_in, _out, _nsubscriptions, nevents_ptr) {
620
+ v().setUint32(nevents_ptr, 0, true);
621
+ return 0;
622
+ }
623
+ };
624
+ function collectOutput() {
625
+ const remaining = stderrDecoder.decode(undefined, { stream: false });
626
+ const tail = stderrPartial + remaining;
627
+ if (tail.length > 0) {
628
+ if (tail.startsWith("__EDGE_META__:"))
629
+ stderrMeta += tail;
630
+ else
631
+ console.error("[ziex]", tail);
632
+ stderrPartial = "";
633
+ }
634
+ return {
635
+ stdout: mergeUint8Arrays(stdoutChunks),
636
+ stderrText: stderrMeta
637
+ };
638
+ }
639
+ return { wasiImport, setMemory, collectOutput };
640
+ }
641
+ function mergeUint8Arrays(arrays) {
642
+ const totalLen = arrays.reduce((sum, arr) => sum + arr.length, 0);
643
+ const result = new Uint8Array(totalLen);
644
+ let offset = 0;
645
+ for (const arr of arrays) {
646
+ result.set(arr, offset);
647
+ offset += arr.length;
648
+ }
649
+ return result;
650
+ }
651
+
652
+ // src/runtime.ts
653
+ function buildWsImports(Suspending, mem, decoder2, ws) {
654
+ const readStr = (ptr, len) => decoder2.decode(new Uint8Array(mem().buffer, ptr, len));
655
+ return {
656
+ ws_upgrade: () => {
657
+ ws.upgraded = true;
658
+ },
659
+ ws_write: (ptr, len) => {
660
+ const data = new Uint8Array(mem().buffer, ptr, len).slice();
661
+ if (!ws.server) {
662
+ ws.pendingWrites.push(data);
663
+ } else {
664
+ ws.server.send(data);
665
+ }
666
+ },
667
+ ws_close: (code, reason_ptr, reason_len) => {
668
+ ws.server?.close(code, decoder2.decode(new Uint8Array(mem().buffer, reason_ptr, reason_len)));
669
+ },
670
+ ws_recv: Suspending ? new Suspending(async (buf_ptr, buf_max) => {
671
+ if (ws._resolveFirstSuspend) {
672
+ const fn = ws._resolveFirstSuspend;
673
+ ws._resolveFirstSuspend = undefined;
674
+ fn();
675
+ }
676
+ const deliver = (bytes) => {
677
+ if (bytes === null)
678
+ return -1;
679
+ const n = Math.min(bytes.length, buf_max);
680
+ new Uint8Array(mem().buffer, buf_ptr, n).set(bytes.subarray(0, n));
681
+ return n;
682
+ };
683
+ if (ws.messageQueue.length > 0)
684
+ return deliver(ws.messageQueue.shift());
685
+ return new Promise((resolve) => {
686
+ ws.recvResolve = (bytes) => resolve(deliver(bytes));
687
+ });
688
+ }) : (_buf_ptr, _buf_max) => -1,
689
+ ws_subscribe: (ptr, len) => {
690
+ ws.subscribe?.(readStr(ptr, len));
691
+ },
692
+ ws_unsubscribe: (ptr, len) => {
693
+ ws.unsubscribe?.(readStr(ptr, len));
694
+ },
695
+ ws_publish: (topic_ptr, topic_len, data_ptr, data_len) => {
696
+ const topic = readStr(topic_ptr, topic_len);
697
+ const data = new Uint8Array(mem().buffer, data_ptr, data_len).slice();
698
+ return ws.publish?.(topic, data) ?? 0;
699
+ },
700
+ ws_is_subscribed: (ptr, len) => ws.isSubscribed?.(readStr(ptr, len)) ? 1 : 0
701
+ };
702
+ }
703
+ function attachWebSocket(ws) {
704
+ const WebSocketPairCtor = globalThis.WebSocketPair;
705
+ const pair = new WebSocketPairCtor;
706
+ const client = pair[0];
707
+ const server = pair[1];
708
+ ws.server = server;
709
+ server.accept();
710
+ for (const data of ws.pendingWrites)
711
+ server.send(data);
712
+ ws.pendingWrites = [];
713
+ server.addEventListener("message", (event) => {
714
+ const data = typeof event.data === "string" ? new TextEncoder().encode(event.data) : new Uint8Array(event.data);
715
+ if (ws.recvResolve) {
716
+ const res = ws.recvResolve;
717
+ ws.recvResolve = null;
718
+ res(data);
719
+ } else {
720
+ ws.messageQueue.push(data);
721
+ }
722
+ });
723
+ server.addEventListener("close", () => {
724
+ if (ws.recvResolve) {
725
+ const res = ws.recvResolve;
726
+ ws.recvResolve = null;
727
+ res(null);
728
+ }
729
+ });
730
+ return { client };
731
+ }
732
+ function buildSysImports(jspi, Suspending) {
733
+ return {
734
+ sleep_ms: jspi ? new Suspending(async (ms) => new Promise((r) => setTimeout(r, ms))) : (_ms) => {}
735
+ };
736
+ }
737
+ function executeWasm(instance, jspi, Suspending, wsState) {
738
+ if (!jspi) {
739
+ try {
740
+ instance.exports._start();
741
+ } catch (e) {
742
+ if (!(e instanceof ProcExit))
743
+ throw e;
744
+ }
745
+ return Promise.resolve();
746
+ }
747
+ const start = WebAssembly.promising(instance.exports._start);
748
+ return start().catch((e) => {
749
+ if (e instanceof Error && e.message.startsWith("proc_exit"))
750
+ return;
751
+ throw e;
752
+ }).finally(() => {
753
+ if (wsState.recvResolve) {
754
+ const res = wsState.recvResolve;
755
+ wsState.recvResolve = null;
756
+ res(null);
757
+ }
758
+ });
759
+ }
760
+ function parseEdgeMeta(stderrText) {
761
+ const meta = { status: 200, headers: new Headers, streaming: false };
762
+ const metaPrefix = "__EDGE_META__:";
763
+ const metaLine = stderrText.split(`
764
+ `).find((line) => line.startsWith(metaPrefix));
765
+ if (metaLine) {
766
+ try {
767
+ const parsed = JSON.parse(metaLine.slice(metaPrefix.length));
768
+ if (parsed.status)
769
+ meta.status = parsed.status;
770
+ if (parsed.streaming === true)
771
+ meta.streaming = true;
772
+ if (Array.isArray(parsed.headers)) {
773
+ for (const [name, value] of parsed.headers) {
774
+ meta.headers.append(name, value);
775
+ }
776
+ }
777
+ } catch {}
778
+ }
779
+ return meta;
780
+ }
781
+ async function run({
782
+ request,
783
+ env,
784
+ ctx,
785
+ module,
786
+ kv: kvBindings,
787
+ db: dbBindings,
788
+ imports,
789
+ wasi,
790
+ websocket: doNamespace
791
+ }) {
792
+ if (doNamespace && request.headers.get("upgrade")?.toLowerCase() === "websocket") {
793
+ const id = doNamespace.idFromName(new URL(request.url).pathname);
794
+ return doNamespace.get(id).fetch(request);
795
+ }
796
+ const stdinData = request.body ? new Uint8Array(await request.arrayBuffer()) : undefined;
797
+ const stdoutChunks = [];
798
+ let streamWriter = null;
799
+ const { wasiImport, setMemory, collectOutput } = createWasiImports({
800
+ request,
801
+ stdinData,
802
+ onStdout: (chunk) => {
803
+ if (streamWriter)
804
+ streamWriter.write(chunk);
805
+ else
806
+ stdoutChunks.push(chunk);
807
+ }
808
+ });
809
+ let wasmMemory = null;
810
+ const mem = () => wasmMemory;
811
+ const bridgeRef = { current: null };
812
+ const Suspending = WebAssembly.Suspending;
813
+ const jspi = typeof Suspending === "function";
814
+ const wsState = {
815
+ upgraded: false,
816
+ server: null,
817
+ pendingWrites: [],
818
+ messageQueue: [],
819
+ recvResolve: null
820
+ };
821
+ const instance = new WebAssembly.Instance(module, {
822
+ wasi_snapshot_preview1: { ...wasi?.wasiImport, ...wasiImport },
823
+ __zx_sys: buildSysImports(jspi, Suspending),
824
+ __zx_ws: buildWsImports(jspi ? Suspending : null, mem, new TextDecoder, wsState),
825
+ __zx_kv: createKVImports(kvBindings ?? { default: createMemoryKV() }, mem),
826
+ __zx_db: createD1Imports(dbBindings ?? {}, mem),
827
+ ...imports ? imports(mem) : {},
828
+ ...ZxWasiBridge.createImportObject(bridgeRef)
829
+ });
830
+ wasmMemory = instance.exports.memory;
831
+ setMemory(wasmMemory);
832
+ bridgeRef.current = new ZxWasiBridge(instance.exports);
833
+ const wasmPromise = executeWasm(instance, jspi, Suspending, wsState);
834
+ if (wsState.upgraded) {
835
+ const server = attachWebSocket(wsState);
836
+ ctx?.waitUntil(wasmPromise);
837
+ return new Response(null, { status: 101, webSocket: server.client });
838
+ }
839
+ const { stderrText: earlyStderrText } = collectOutput();
840
+ const earlyMeta = parseEdgeMeta(earlyStderrText);
841
+ if (earlyMeta.streaming) {
842
+ const { readable, writable } = new TransformStream;
843
+ streamWriter = writable.getWriter();
844
+ for (const chunk of stdoutChunks)
845
+ streamWriter.write(chunk);
846
+ stdoutChunks.length = 0;
847
+ wasmPromise.finally(() => streamWriter?.close());
848
+ return new Response(readable, { status: earlyMeta.status, headers: earlyMeta.headers });
849
+ }
850
+ await wasmPromise;
851
+ const { stderrText } = collectOutput();
852
+ const meta = parseEdgeMeta(stderrText);
853
+ const body = mergeUint8Arrays(stdoutChunks);
854
+ meta.headers.delete("transfer-encoding");
855
+ if (!meta.headers.has("content-length"))
856
+ meta.headers.set("content-length", String(body.byteLength));
857
+ return new Response(body.buffer, { status: meta.status, headers: meta.headers });
858
+ }
859
+
860
+ // src/app.ts
861
+ async function resolveModule(input) {
862
+ if (typeof input === "string") {
863
+ if (input.startsWith("http://") || input.startsWith("https://")) {
864
+ return WebAssembly.compileStreaming(fetch(input));
865
+ }
866
+ const url = input.startsWith("/") ? `file://${input}` : input;
867
+ return WebAssembly.compile(await fetch(url).then((r) => r.arrayBuffer()));
868
+ }
869
+ if (input instanceof URL) {
870
+ return WebAssembly.compileStreaming(fetch(input));
871
+ }
872
+ if (input instanceof Response) {
873
+ return WebAssembly.compileStreaming(input);
874
+ }
875
+ if (input instanceof ArrayBuffer) {
876
+ return WebAssembly.compile(input);
877
+ }
878
+ if (ArrayBuffer.isView(input)) {
879
+ return WebAssembly.compile(input.buffer);
880
+ }
881
+ return input;
882
+ }
883
+
884
+ class Ziex {
885
+ options;
886
+ resolved = null;
887
+ constructor(options) {
888
+ this.options = options;
889
+ }
890
+ async getModule() {
891
+ if (!this.resolved)
892
+ this.resolved = await resolveModule(this.options.module);
893
+ return this.resolved;
894
+ }
895
+ resolveKV(env) {
896
+ const { kv } = this.options;
897
+ if (kv === undefined)
898
+ return;
899
+ if (typeof kv === "object" && kv !== null) {
900
+ const result = {};
901
+ for (const [name, key] of Object.entries(kv)) {
902
+ result[name] = env[key];
903
+ }
904
+ return result;
905
+ }
906
+ return { default: env[kv] };
907
+ }
908
+ resolveDB(env) {
909
+ const { db } = this.options;
910
+ if (db === undefined)
911
+ return;
912
+ if (typeof db === "object" && db !== null) {
913
+ const result = {};
914
+ for (const [name, key] of Object.entries(db)) {
915
+ result[name] = env[key];
916
+ }
917
+ return result;
918
+ }
919
+ return { default: env[db] };
920
+ }
921
+ fetch = async (request, env, ctx) => {
922
+ const module = await this.getModule();
923
+ const { wasi, imports, websocket } = this.options;
924
+ return run({
925
+ request,
926
+ env,
927
+ ctx,
928
+ module,
929
+ wasi,
930
+ imports,
931
+ kv: this.resolveKV(env),
932
+ db: this.resolveDB(env),
933
+ websocket: websocket !== undefined ? env[websocket] : undefined
934
+ });
935
+ };
936
+ }
29
937
  export {
30
- zx
938
+ Ziex
31
939
  };