@bytecodealliance/preview2-shim 0.19.0 → 0.20.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.
package/README.md CHANGED
@@ -15,8 +15,8 @@ An default instantiation object can be used via the `WASIShim` class in `@byteco
15
15
  ```typescript
16
16
  import { WASIShim } from "@bytecodealliance/preview2-shim/instantiation";
17
17
  import type {
18
- VersionedWASIImportObject,
19
- WASIImportObject,
18
+ VersionedWASIImportObject,
19
+ WASIImportObject,
20
20
  } from "@bytecodealliance/preview2-shim/instantiation";
21
21
 
22
22
  const shim = new WASIShim();
@@ -27,7 +27,7 @@ unversioned satisfies WASIImportObject;
27
27
  unversioned satisfies VersionedWASIImportObject<"">;
28
28
 
29
29
  const versioned: VersionedWASIImportObject<"0.2.3"> = shim.getImportObject({
30
- asVersion: "0.2.3",
30
+ asVersion: "0.2.3",
31
31
  });
32
32
  //console.log('versioned', versioned);
33
33
  versioned satisfies VersionedWASIImportObject<"0.2.3">;
@@ -66,23 +66,23 @@ import { WASIShim } from "@bytecodealliance/preview2-shim/instantiation";
66
66
 
67
67
  // Fully sandboxed - no filesystem, network, or env access
68
68
  const sandboxedShim = new WASIShim({
69
- sandbox: {
70
- preopens: {}, // No filesystem access
71
- env: {}, // No environment variables
72
- args: ["arg1"], // Custom arguments
73
- enableNetwork: false, // Disable network access
74
- },
69
+ sandbox: {
70
+ preopens: {}, // No filesystem access
71
+ env: {}, // No environment variables
72
+ args: ["arg1"], // Custom arguments
73
+ enableNetwork: false, // Disable network access
74
+ },
75
75
  });
76
76
 
77
77
  // Limited filesystem access - map virtual paths to host paths
78
78
  const limitedShim = new WASIShim({
79
- sandbox: {
80
- preopens: {
81
- "/data": "/tmp/guest-data", // Guest sees /data, maps to /tmp/guest-data
82
- "/config": "/etc/app", // Guest sees /config, maps to /etc/app
79
+ sandbox: {
80
+ preopens: {
81
+ "/data": "/tmp/guest-data", // Guest sees /data, maps to /tmp/guest-data
82
+ "/config": "/etc/app", // Guest sees /config, maps to /etc/app
83
+ },
84
+ env: { ENV1: "42" }, // Only expose specific env vars
83
85
  },
84
- env: { ENV1: "42" }, // Only expose specific env vars
85
- },
86
86
  });
87
87
 
88
88
  const component = await instantiate(loader, sandboxedShim.getImportObject());
@@ -74,6 +74,21 @@ function getSource(fileEntry) {
74
74
  }
75
75
  return fileEntry.source;
76
76
  }
77
+ // Keep spare capacity separate so FileDataEntry.source always reflects the logical file size.
78
+ const fileWriteBuffers = new WeakMap();
79
+ function getFileWriteBuffer(entry, source, requiredLength) {
80
+ let buffer = fileWriteBuffers.get(entry);
81
+ if (!buffer || buffer.buffer !== source.buffer || buffer.byteOffset !== source.byteOffset) {
82
+ buffer = source;
83
+ }
84
+ if (requiredLength <= buffer.byteLength) {
85
+ return buffer;
86
+ }
87
+ const newBuffer = new Uint8Array(Math.max(requiredLength, source.byteLength * 2));
88
+ newBuffer.set(source);
89
+ fileWriteBuffers.set(entry, newBuffer);
90
+ return newBuffer;
91
+ }
77
92
  class DirectoryEntryStream {
78
93
  idx = 0;
79
94
  entries = [];
@@ -130,15 +145,24 @@ class Descriptor {
130
145
  }
131
146
  writeViaStream(_offset) {
132
147
  const entry = this.#entry;
133
- let offset = Number(_offset);
148
+ let offset = coerceToSafeIntegerNumber(_offset);
134
149
  return outputStreamCreate({
135
150
  write(buf) {
136
- const src = entry.source;
137
- const newSource = new Uint8Array(buf.byteLength + src.byteLength);
138
- newSource.set(src, 0);
139
- newSource.set(buf, offset);
140
- offset += buf.byteLength;
141
- entry.source = newSource;
151
+ if (buf.byteLength === 0) {
152
+ return;
153
+ }
154
+ const source = getSource(entry);
155
+ const end = offset + buf.byteLength;
156
+ if (!Number.isSafeInteger(end)) {
157
+ throw new TypeError(`excessively large number: ${end}`);
158
+ }
159
+ const buffer = getFileWriteBuffer(entry, source, end);
160
+ if (offset > source.byteLength) {
161
+ buffer.fill(0, source.byteLength, offset);
162
+ }
163
+ buffer.set(buf, offset);
164
+ entry.source = buffer.subarray(0, Math.max(source.byteLength, end));
165
+ offset = end;
142
166
  },
143
167
  });
144
168
  }
@@ -509,7 +509,7 @@ class FutureTrailers {
509
509
  tag: "ok",
510
510
  val: {
511
511
  tag: "ok",
512
- val: undefined,
512
+ val: fieldsLock(fieldsFromEntriesChecked([])),
513
513
  },
514
514
  };
515
515
  }
@@ -164,7 +164,8 @@ export class WASIShim {
164
164
  obj[`wasi:sockets/tcp-create-socket${versionSuffix}`] = this.#sockets.tcpCreateSocket;
165
165
  obj[`wasi:sockets/udp${versionSuffix}`] = this.#sockets.udp;
166
166
  obj[`wasi:sockets/udp-create-socket${versionSuffix}`] = this.#sockets.udpCreateSocket;
167
- obj[`wasi:filesystem/preopens${versionSuffix}`] = this.#preopens ?? this.#filesystem.preopens;
167
+ obj[`wasi:filesystem/preopens${versionSuffix}`] =
168
+ this.#preopens ?? this.#filesystem.preopens;
168
169
  obj[`wasi:filesystem/types${versionSuffix}`] = this.#filesystem.types;
169
170
  obj[`wasi:io/error${versionSuffix}`] = this.#io.error;
170
171
  obj[`wasi:io/poll${versionSuffix}`] = this.#io.poll;
@@ -13,7 +13,11 @@ export function registerIncomingHttpHandler(id, handler) {
13
13
  }
14
14
  const instanceId = Math.round(Math.random() * 1000).toString();
15
15
  const DEBUG_DEFAULT = false;
16
- const DEBUG = env.PREVIEW2_SHIM_DEBUG === "0" ? false : env.PREVIEW2_SHIM_DEBUG === "1" ? true : DEBUG_DEFAULT;
16
+ const DEBUG = env.PREVIEW2_SHIM_DEBUG === "0"
17
+ ? false
18
+ : env.PREVIEW2_SHIM_DEBUG === "1"
19
+ ? true
20
+ : DEBUG_DEFAULT;
17
21
  /**
18
22
  * @type {(call: number, id: number | null, payload: any) -> any}
19
23
  */
@@ -148,7 +152,8 @@ class InputStream {
148
152
  disposeFn = httpInputStreamDispose;
149
153
  break;
150
154
  default:
151
- throw new Error("wasi-io trap: Dispose function not created for stream type " + reverseMap[streamType]);
155
+ throw new Error("wasi-io trap: Dispose function not created for stream type " +
156
+ reverseMap[streamType]);
152
157
  }
153
158
  stream.#finalizer = registerDispose(stream, null, id, disposeFn);
154
159
  return stream;
@@ -253,7 +258,8 @@ class OutputStream {
253
258
  case HTTP:
254
259
  return stream;
255
260
  default:
256
- throw new Error("wasi-io trap: Dispose function not created for stream type " + reverseMap[streamType]);
261
+ throw new Error("wasi-io trap: Dispose function not created for stream type " +
262
+ reverseMap[streamType]);
257
263
  }
258
264
  stream.#finalizer = registerDispose(stream, null, id, disposeFn);
259
265
  return stream;
@@ -406,7 +406,8 @@ export async function socketOutgoingDatagramStreamSend(id, datagrams) {
406
406
  function doSendBatch() {
407
407
  return new Promise((resolve, reject) => {
408
408
  if (socket.remoteAddress) {
409
- if (sendQueueAddress !== socket.remoteAddress || sendQueuePort !== socket.remotePort) {
409
+ if (sendQueueAddress !== socket.remoteAddress ||
410
+ sendQueuePort !== socket.remotePort) {
410
411
  return void reject("invalid-argument");
411
412
  }
412
413
  udpSocket.send(sendQueue, handler);
@@ -444,7 +444,8 @@ function handle(call, id, payload) {
444
444
  if (stream.flushPromise) {
445
445
  return stream.flushPromise.then(() => handle(call, id, payload));
446
446
  }
447
- if (payload.byteLength > stream.stream.writableHighWaterMark - stream.stream.writableLength) {
447
+ if (payload.byteLength >
448
+ stream.stream.writableHighWaterMark - stream.stream.writableLength) {
448
449
  throw new Error("wasi-io trap: Cannot write more than permitted writable length");
449
450
  }
450
451
  stream.pollState.ready = false;
@@ -570,7 +571,9 @@ function handle(call, id, payload) {
570
571
  let resolve, reject;
571
572
  if (outputStream.stream.writableNeedDrain) {
572
573
  promise = new Promise((_resolve, _reject) => {
573
- outputStream.stream.once("drain", (resolve = _resolve)).once("error", (reject = _reject));
574
+ outputStream.stream
575
+ .once("drain", (resolve = _resolve))
576
+ .once("error", (reject = _reject));
574
577
  }).then(() => {
575
578
  outputStream.stream.off("error", reject);
576
579
  }, (err) => {
@@ -142,7 +142,8 @@ class Descriptor {
142
142
  throw "invalid";
143
143
  }
144
144
  let stats;
145
- if (dataAccessTimestamp.tag === "no-change" || dataModificationTimestamp.tag === "no-change") {
145
+ if (dataAccessTimestamp.tag === "no-change" ||
146
+ dataModificationTimestamp.tag === "no-change") {
146
147
  stats = this.stat();
147
148
  }
148
149
  const atime = this.#getNewTimestamp(dataAccessTimestamp, dataAccessTimestamp.tag === "no-change" && stats.dataAccessTimestamp);
@@ -259,7 +260,8 @@ class Descriptor {
259
260
  setTimesAt(pathFlags, path, dataAccessTimestamp, dataModificationTimestamp) {
260
261
  const fullPath = this.#getFullPath(path, false);
261
262
  let stats;
262
- if (dataAccessTimestamp.tag === "no-change" || dataModificationTimestamp.tag === "no-change") {
263
+ if (dataAccessTimestamp.tag === "no-change" ||
264
+ dataModificationTimestamp.tag === "no-change") {
263
265
  stats = this.stat();
264
266
  }
265
267
  const atime = this.#getNewTimestamp(dataAccessTimestamp, dataAccessTimestamp.tag === "no-change" && stats.dataAccessTimestamp);
@@ -519,7 +521,8 @@ class Descriptor {
519
521
  // new segment - check if it is relative
520
522
  else if (subpath[i] === ".") {
521
523
  // ../ segment
522
- if (subpath[i + 1] === "." && (subpath[i + 2] === "/" || i + 2 === subpath.length)) {
524
+ if (subpath[i + 1] === "." &&
525
+ (subpath[i + 2] === "/" || i + 2 === subpath.length)) {
523
526
  if (segments.pop() === undefined) {
524
527
  throw "not-permitted";
525
528
  }
@@ -1,6 +1,6 @@
1
1
  import { FUTURE_DISPOSE, FUTURE_SUBSCRIBE, FUTURE_TAKE_VALUE, HTTP_CREATE_REQUEST, HTTP_OUTGOING_BODY_DISPOSE, HTTP_OUTPUT_STREAM_FINISH, HTTP_SERVER_CLEAR_OUTGOING_RESPONSE, HTTP_SERVER_SET_OUTGOING_RESPONSE, HTTP_SERVER_START, HTTP_SERVER_STOP, HTTP_SERVER_GET_ADDRESS, OUTPUT_STREAM_CREATE, OUTPUT_STREAM_DISPOSE, } from "../io/calls.js";
2
- import { earlyDispose, inputStreamCreate, ioCall, outputStreamCreate, pollableCreate, registerDispose, registerIncomingHttpHandler, } from "../io/worker-io.js";
3
- import { HTTP } from "../io/calls.js";
2
+ import { earlyDispose, inputStreamCreate, ioCall, outputStreamCreate, pollableCreate, createPoll, registerDispose, registerIncomingHttpHandler, } from "../io/worker-io.js";
3
+ import { CLOCKS_DURATION_SUBSCRIBE, HTTP } from "../io/calls.js";
4
4
  import * as http from "node:http";
5
5
  const { validateHeaderName = () => { }, validateHeaderValue = () => { } } = http;
6
6
  const symbolDispose = Symbol.dispose || Symbol.for("dispose");
@@ -76,7 +76,7 @@ delete IncomingRequest._create;
76
76
  class FutureTrailers {
77
77
  #requested = false;
78
78
  subscribe() {
79
- return pollableCreate(0, this);
79
+ return createPoll(CLOCKS_DURATION_SUBSCRIBE, null, 0n);
80
80
  }
81
81
  get() {
82
82
  if (this.#requested) {
@@ -87,7 +87,7 @@ class FutureTrailers {
87
87
  tag: "ok",
88
88
  val: {
89
89
  tag: "ok",
90
- val: undefined,
90
+ val: fieldsLock(fieldsFromEntriesChecked([])),
91
91
  },
92
92
  };
93
93
  }
@@ -1,26 +1,26 @@
1
1
  // Based on: https://github.com/un-ts/synckit
2
2
  /*
3
- MIT License
3
+ MIT License
4
4
 
5
- Copyright (c) 2021 UnTS
5
+ Copyright (c) 2021 UnTS
6
6
 
7
- Permission is hereby granted, free of charge, to any person obtaining a copy
8
- of this software and associated documentation files (the "Software"), to deal
9
- in the Software without restriction, including without limitation the rights
10
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- copies of the Software, and to permit persons to whom the Software is
12
- furnished to do so, subject to the following conditions:
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
13
 
14
- The above copyright notice and this permission notice shall be included in all
15
- copies or substantial portions of the Software.
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
16
 
17
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
- SOFTWARE.
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
24
  */
25
25
  import path from "node:path";
26
26
  import { MessageChannel, Worker, receiveMessageOnPort, workerData, parentPort, } from "node:worker_threads";
@@ -62,7 +62,7 @@ export function createSyncFn(workerPath, debug, callbackHandler) {
62
62
  if (!["ok", "not-equal"].includes(status)) {
63
63
  throw new Error("Internal error: Atomics.wait() failed: " + status);
64
64
  }
65
- const { cid: cid2, result, error, properties } = receiveMessageOnPort(mainPort)?.message ?? {};
65
+ const { cid: cid2, result, error, properties, } = receiveMessageOnPort(mainPort)?.message ?? {};
66
66
  if (cid !== cid2) {
67
67
  throw new Error(`Internal error: Expected id ${cid} but got id ${cid2}`);
68
68
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bytecodealliance/preview2-shim",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "WASI Preview2 shim for JS environments",
5
5
  "homepage": "https://github.com/bytecodealliance/jco#readme",
6
6
  "bugs": {
@@ -48,7 +48,7 @@
48
48
  "default": "./dist/browser/*.js"
49
49
  },
50
50
  "./instantiation": {
51
- "types": "./types/instantiation.d.ts",
51
+ "types": "./dist/common/*.d.ts",
52
52
  "node": "./dist/common/instantiation.js",
53
53
  "default": "./dist/common/instantiation.js"
54
54
  },
@@ -57,8 +57,8 @@
57
57
  }
58
58
  },
59
59
  "devDependencies": {
60
- "@bytecodealliance/componentize-js": "0.21.0",
61
- "@bytecodealliance/jco": "1.20.0",
60
+ "@bytecodealliance/componentize-js": "0.22.0",
61
+ "@bytecodealliance/jco": "1.25.2",
62
62
  "@types/node": "^24.12.4",
63
63
  "mime": "^4.0.7",
64
64
  "puppeteer": "^25.1.0",