@bytecodealliance/preview2-shim 0.18.1 → 0.19.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 (81) hide show
  1. package/dist/browser/cli.d.ts +16 -0
  2. package/dist/browser/cli.js +109 -0
  3. package/dist/browser/clocks.d.ts +3 -0
  4. package/dist/browser/clocks.js +36 -0
  5. package/dist/browser/config.d.ts +2 -0
  6. package/{lib → dist}/browser/config.js +2 -4
  7. package/dist/browser/environment.d.ts +5 -0
  8. package/dist/browser/environment.js +24 -0
  9. package/dist/browser/filesystem.d.ts +132 -0
  10. package/dist/browser/filesystem.js +464 -0
  11. package/dist/browser/http.d.ts +4 -0
  12. package/dist/browser/http.js +643 -0
  13. package/dist/browser/index.d.ts +7 -0
  14. package/dist/browser/index.js +7 -0
  15. package/dist/browser/io.d.ts +58 -0
  16. package/dist/browser/io.js +205 -0
  17. package/dist/browser/random.d.ts +4 -0
  18. package/dist/browser/random.js +49 -0
  19. package/dist/browser/sockets.d.ts +8 -0
  20. package/dist/browser/sockets.js +66 -0
  21. package/dist/common/instantiation.d.ts +97 -0
  22. package/dist/common/instantiation.js +227 -0
  23. package/dist/io/calls.d.ts +91 -0
  24. package/{lib → dist}/io/calls.js +4 -19
  25. package/dist/io/worker-http.d.ts +17 -0
  26. package/dist/io/worker-http.js +192 -0
  27. package/dist/io/worker-io.d.ts +84 -0
  28. package/dist/io/worker-io.js +375 -0
  29. package/dist/io/worker-socket-tcp.d.ts +34 -0
  30. package/dist/io/worker-socket-tcp.js +251 -0
  31. package/dist/io/worker-socket-udp.d.ts +54 -0
  32. package/dist/io/worker-socket-udp.js +492 -0
  33. package/dist/io/worker-sockets.d.ts +32 -0
  34. package/dist/io/worker-sockets.js +265 -0
  35. package/dist/io/worker-thread.d.ts +73 -0
  36. package/dist/io/worker-thread.js +791 -0
  37. package/dist/nodejs/cli.d.ts +30 -0
  38. package/dist/nodejs/cli.js +86 -0
  39. package/dist/nodejs/clocks.d.ts +3 -0
  40. package/dist/nodejs/clocks.js +61 -0
  41. package/dist/nodejs/filesystem.d.ts +113 -0
  42. package/dist/nodejs/filesystem.js +758 -0
  43. package/dist/nodejs/http.d.ts +82 -0
  44. package/dist/nodejs/http.js +674 -0
  45. package/dist/nodejs/index.d.ts +7 -0
  46. package/dist/nodejs/index.js +7 -0
  47. package/dist/nodejs/io.d.ts +1 -0
  48. package/dist/nodejs/io.js +1 -0
  49. package/dist/nodejs/random.d.ts +4 -0
  50. package/dist/nodejs/random.js +42 -0
  51. package/dist/nodejs/sockets.d.ts +21 -0
  52. package/dist/nodejs/sockets.js +482 -0
  53. package/dist/synckit/index.d.ts +2 -0
  54. package/dist/synckit/index.js +117 -0
  55. package/package.json +26 -13
  56. package/types/instantiation.d.ts +7 -7
  57. package/lib/browser/cli.js +0 -135
  58. package/lib/browser/clocks.js +0 -39
  59. package/lib/browser/environment.js +0 -29
  60. package/lib/browser/filesystem.js +0 -503
  61. package/lib/browser/http.js +0 -707
  62. package/lib/browser/index.js +0 -9
  63. package/lib/browser/io.js +0 -262
  64. package/lib/browser/random.js +0 -56
  65. package/lib/browser/sockets.js +0 -88
  66. package/lib/common/instantiation.js +0 -253
  67. package/lib/io/worker-http.js +0 -206
  68. package/lib/io/worker-io.js +0 -468
  69. package/lib/io/worker-socket-tcp.js +0 -331
  70. package/lib/io/worker-socket-udp.js +0 -587
  71. package/lib/io/worker-sockets.js +0 -364
  72. package/lib/io/worker-thread.js +0 -1051
  73. package/lib/nodejs/cli.js +0 -109
  74. package/lib/nodejs/clocks.js +0 -67
  75. package/lib/nodejs/filesystem.js +0 -829
  76. package/lib/nodejs/http.js +0 -764
  77. package/lib/nodejs/index.js +0 -9
  78. package/lib/nodejs/io.js +0 -1
  79. package/lib/nodejs/random.js +0 -49
  80. package/lib/nodejs/sockets.js +0 -565
  81. package/lib/synckit/index.js +0 -127
@@ -0,0 +1,758 @@
1
+ import { earlyDispose, inputStreamCreate, ioCall, outputStreamCreate, registerDispose, } from "../io/worker-io.js";
2
+ import { FILE, INPUT_STREAM_CREATE, OUTPUT_STREAM_CREATE } from "../io/calls.js";
3
+ import { closeSync, constants, fdatasyncSync, fstatSync, fsyncSync, ftruncateSync, futimesSync, linkSync, lstatSync, lutimesSync, mkdirSync, opendirSync, openSync, readlinkSync, readSync, renameSync, rmdirSync, statSync, symlinkSync, unlinkSync, utimesSync, writeSync, } from "node:fs";
4
+ import { platform } from "node:process";
5
+ const symbolDispose = Symbol.dispose || Symbol.for("dispose");
6
+ const isWindows = platform === "win32";
7
+ const isMac = platform === "darwin";
8
+ const nsMagnitude = 1000000000n;
9
+ function nsToDateTime(ns) {
10
+ const seconds = ns / nsMagnitude;
11
+ const nanoseconds = Number(ns % nsMagnitude);
12
+ return { seconds, nanoseconds };
13
+ }
14
+ function lookupType(obj) {
15
+ if (obj.isFile()) {
16
+ return "regular-file";
17
+ }
18
+ else if (obj.isSocket()) {
19
+ return "socket";
20
+ }
21
+ else if (obj.isSymbolicLink()) {
22
+ return "symbolic-link";
23
+ }
24
+ else if (obj.isFIFO()) {
25
+ return "fifo";
26
+ }
27
+ else if (obj.isDirectory()) {
28
+ return "directory";
29
+ }
30
+ else if (obj.isCharacterDevice()) {
31
+ return "character-device";
32
+ }
33
+ else if (obj.isBlockDevice()) {
34
+ return "block-device";
35
+ }
36
+ return "unknown";
37
+ }
38
+ // Note: This should implement per-segment semantics of openAt, but we cannot
39
+ // currently due to the lack of support for openat() in Node.js.
40
+ // Tracking issue: https://github.com/libuv/libuv/issues/4167
41
+ /**
42
+ * @implements {DescriptorProps}
43
+ */
44
+ class Descriptor {
45
+ #hostPreopen;
46
+ #fd;
47
+ #finalizer;
48
+ #mode;
49
+ #fullPath;
50
+ _id = 0;
51
+ static _createPreopen(hostPreopen) {
52
+ const descriptor = new Descriptor();
53
+ descriptor.#hostPreopen = hostPreopen.endsWith("/")
54
+ ? hostPreopen.slice(0, -1) || "/"
55
+ : hostPreopen;
56
+ // Windows requires UNC paths at minimum
57
+ if (isWindows) {
58
+ descriptor.#hostPreopen = descriptor.#hostPreopen.replace(/\\/g, "/");
59
+ if (descriptor.#hostPreopen === "/") {
60
+ descriptor.#hostPreopen = "//";
61
+ }
62
+ }
63
+ return descriptor;
64
+ }
65
+ static _create(fd, mode, fullPath) {
66
+ const descriptor = new Descriptor();
67
+ descriptor.#fd = fd;
68
+ descriptor.#finalizer = registerDispose(descriptor, null, fd, closeSync);
69
+ descriptor.#mode = mode;
70
+ descriptor.#fullPath = fullPath;
71
+ return descriptor;
72
+ }
73
+ [symbolDispose]() {
74
+ if (this.#finalizer) {
75
+ earlyDispose(this.#finalizer);
76
+ this.#finalizer = null;
77
+ }
78
+ }
79
+ readViaStream(offset) {
80
+ if (this.#hostPreopen) {
81
+ throw "is-directory";
82
+ }
83
+ return inputStreamCreate(FILE, ioCall(INPUT_STREAM_CREATE | FILE, null, {
84
+ fd: this.#fd,
85
+ offset,
86
+ }));
87
+ }
88
+ writeViaStream(offset) {
89
+ if (this.#hostPreopen) {
90
+ throw "is-directory";
91
+ }
92
+ return outputStreamCreate(FILE, ioCall(OUTPUT_STREAM_CREATE | FILE, null, { fd: this.#fd, offset }));
93
+ }
94
+ appendViaStream() {
95
+ return this.writeViaStream(this.stat().size);
96
+ }
97
+ advise(_offset, _length, _advice) {
98
+ if (this.getType() === "directory") {
99
+ throw "bad-descriptor";
100
+ }
101
+ }
102
+ syncData() {
103
+ if (this.#hostPreopen) {
104
+ throw "invalid";
105
+ }
106
+ try {
107
+ fdatasyncSync(this.#fd);
108
+ }
109
+ catch (e) {
110
+ if (e.code === "EPERM") {
111
+ return;
112
+ }
113
+ throw convertFsError(e);
114
+ }
115
+ }
116
+ getFlags() {
117
+ return this.#mode;
118
+ }
119
+ getType() {
120
+ if (this.#hostPreopen) {
121
+ return "directory";
122
+ }
123
+ const stats = fstatSync(this.#fd);
124
+ return lookupType(stats);
125
+ }
126
+ setSize(size) {
127
+ if (this.#hostPreopen) {
128
+ throw "is-directory";
129
+ }
130
+ try {
131
+ ftruncateSync(this.#fd, Number(size));
132
+ }
133
+ catch (e) {
134
+ if (isWindows && e.code === "EPERM") {
135
+ throw "access";
136
+ }
137
+ throw convertFsError(e);
138
+ }
139
+ }
140
+ setTimes(dataAccessTimestamp, dataModificationTimestamp) {
141
+ if (this.#hostPreopen) {
142
+ throw "invalid";
143
+ }
144
+ let stats;
145
+ if (dataAccessTimestamp.tag === "no-change" || dataModificationTimestamp.tag === "no-change") {
146
+ stats = this.stat();
147
+ }
148
+ const atime = this.#getNewTimestamp(dataAccessTimestamp, dataAccessTimestamp.tag === "no-change" && stats.dataAccessTimestamp);
149
+ const mtime = this.#getNewTimestamp(dataModificationTimestamp, dataModificationTimestamp.tag === "no-change" && stats.dataModificationTimestamp);
150
+ try {
151
+ futimesSync(this.#fd, atime, mtime);
152
+ }
153
+ catch (e) {
154
+ throw convertFsError(e);
155
+ }
156
+ }
157
+ #getNewTimestamp(newTimestamp, maybeNow) {
158
+ switch (newTimestamp.tag) {
159
+ case "no-change":
160
+ return timestampToMs(maybeNow);
161
+ case "timestamp":
162
+ return timestampToMs(newTimestamp.val);
163
+ default:
164
+ return Math.floor(Date.now() / 1e3);
165
+ }
166
+ }
167
+ read(length, offset) {
168
+ if (!this.#fullPath) {
169
+ throw "bad-descriptor";
170
+ }
171
+ const buf = new Uint8Array(Number(length));
172
+ const bytesRead = readSync(this.#fd, buf, 0, Number(length), Number(offset));
173
+ const out = new Uint8Array(buf.buffer, 0, bytesRead);
174
+ return [out, bytesRead === 0];
175
+ }
176
+ write(buffer, offset) {
177
+ if (!this.#fullPath) {
178
+ throw "bad-descriptor";
179
+ }
180
+ return BigInt(writeSync(this.#fd, buffer, 0, buffer.byteLength, Number(offset)));
181
+ }
182
+ readDirectory() {
183
+ if (!this.#fullPath) {
184
+ throw "bad-descriptor";
185
+ }
186
+ try {
187
+ const dir = opendirSync(this.#fullPath);
188
+ return directoryEntryStreamCreate(dir);
189
+ }
190
+ catch (e) {
191
+ throw convertFsError(e);
192
+ }
193
+ }
194
+ sync() {
195
+ if (this.#hostPreopen) {
196
+ throw "invalid";
197
+ }
198
+ try {
199
+ fsyncSync(this.#fd);
200
+ }
201
+ catch (e) {
202
+ if (e.code === "EPERM") {
203
+ return;
204
+ }
205
+ throw convertFsError(e);
206
+ }
207
+ }
208
+ createDirectoryAt(path) {
209
+ const fullPath = this.#getFullPath(path, undefined);
210
+ try {
211
+ mkdirSync(fullPath);
212
+ }
213
+ catch (e) {
214
+ throw convertFsError(e);
215
+ }
216
+ }
217
+ stat() {
218
+ if (this.#hostPreopen) {
219
+ throw "invalid";
220
+ }
221
+ let stats;
222
+ try {
223
+ stats = fstatSync(this.#fd, { bigint: true });
224
+ }
225
+ catch (e) {
226
+ throw convertFsError(e);
227
+ }
228
+ const type = lookupType(stats);
229
+ return {
230
+ type,
231
+ linkCount: stats.nlink,
232
+ size: stats.size,
233
+ dataAccessTimestamp: nsToDateTime(stats.atimeNs),
234
+ dataModificationTimestamp: nsToDateTime(stats.mtimeNs),
235
+ statusChangeTimestamp: nsToDateTime(stats.ctimeNs),
236
+ };
237
+ }
238
+ statAt(pathFlags, path) {
239
+ const fullPath = this.#getFullPath(path, false);
240
+ let stats;
241
+ try {
242
+ stats = (pathFlags.symlinkFollow ? statSync : lstatSync)(fullPath, {
243
+ bigint: true,
244
+ });
245
+ }
246
+ catch (e) {
247
+ throw convertFsError(e);
248
+ }
249
+ const type = lookupType(stats);
250
+ return {
251
+ type,
252
+ linkCount: stats.nlink,
253
+ size: stats.size,
254
+ dataAccessTimestamp: nsToDateTime(stats.atimeNs),
255
+ dataModificationTimestamp: nsToDateTime(stats.mtimeNs),
256
+ statusChangeTimestamp: nsToDateTime(stats.ctimeNs),
257
+ };
258
+ }
259
+ setTimesAt(pathFlags, path, dataAccessTimestamp, dataModificationTimestamp) {
260
+ const fullPath = this.#getFullPath(path, false);
261
+ let stats;
262
+ if (dataAccessTimestamp.tag === "no-change" || dataModificationTimestamp.tag === "no-change") {
263
+ stats = this.stat();
264
+ }
265
+ const atime = this.#getNewTimestamp(dataAccessTimestamp, dataAccessTimestamp.tag === "no-change" && stats.dataAccessTimestamp);
266
+ const mtime = this.#getNewTimestamp(dataModificationTimestamp, dataModificationTimestamp.tag === "no-change" && stats.dataModificationTimestamp);
267
+ if (!pathFlags.symlinkFollow && !lutimesSync) {
268
+ throw new Error("Changing the timestamps of symlinks isn't supported");
269
+ }
270
+ let metadataSetFn = pathFlags.symlinkFollow ? lutimesSync : utimesSync;
271
+ try {
272
+ metadataSetFn(fullPath, atime / 1000, mtime / 1000);
273
+ }
274
+ catch (e) {
275
+ throw convertFsError(e);
276
+ }
277
+ }
278
+ linkAt(oldPathFlags, oldPath, newDescriptor, newPath) {
279
+ const oldFullPath = this.#getFullPath(oldPath, oldPathFlags.symlinkFollow);
280
+ const newFullPath = newDescriptor.#getFullPath(newPath, false);
281
+ // Windows doesn't automatically fail on trailing slashes
282
+ if (isWindows && newFullPath.endsWith("/")) {
283
+ throw "no-entry";
284
+ }
285
+ try {
286
+ linkSync(oldFullPath, newFullPath);
287
+ }
288
+ catch (e) {
289
+ throw convertFsError(e);
290
+ }
291
+ }
292
+ openAt(pathFlags, path, openFlags, descriptorFlags) {
293
+ if (preopenEntries.length === 0) {
294
+ throw "access";
295
+ }
296
+ const fullPath = this.#getFullPath(path, pathFlags.symlinkFollow);
297
+ let fsOpenFlags = 0x0;
298
+ if (openFlags.create) {
299
+ fsOpenFlags |= constants.O_CREAT;
300
+ }
301
+ if (openFlags.directory) {
302
+ fsOpenFlags |= constants.O_DIRECTORY;
303
+ }
304
+ if (openFlags.exclusive) {
305
+ fsOpenFlags |= constants.O_EXCL;
306
+ }
307
+ if (openFlags.truncate) {
308
+ fsOpenFlags |= constants.O_TRUNC;
309
+ }
310
+ if (descriptorFlags.read && descriptorFlags.write) {
311
+ fsOpenFlags |= constants.O_RDWR;
312
+ }
313
+ else if (descriptorFlags.write) {
314
+ fsOpenFlags |= constants.O_WRONLY;
315
+ }
316
+ else if (descriptorFlags.read) {
317
+ fsOpenFlags |= constants.O_RDONLY;
318
+ }
319
+ if (descriptorFlags.fileIntegritySync) {
320
+ fsOpenFlags |= constants.O_SYNC;
321
+ }
322
+ if (descriptorFlags.dataIntegritySync) {
323
+ fsOpenFlags |= constants.O_DSYNC;
324
+ }
325
+ if (!pathFlags.symlinkFollow) {
326
+ fsOpenFlags |= constants.O_NOFOLLOW;
327
+ }
328
+ if (descriptorFlags.requestedWriteSync || descriptorFlags.mutateDirectory) {
329
+ throw "unsupported";
330
+ }
331
+ // Currently throw to match Wasmtime
332
+ if (descriptorFlags.fileIntegritySync || descriptorFlags.dataIntegritySync) {
333
+ throw "unsupported";
334
+ }
335
+ if (isWindows) {
336
+ if (!pathFlags.symlinkFollow && !openFlags.create) {
337
+ let isSymlink = false;
338
+ try {
339
+ isSymlink = lstatSync(fullPath).isSymbolicLink();
340
+ }
341
+ catch {
342
+ //
343
+ }
344
+ if (isSymlink) {
345
+ throw openFlags.directory ? "not-directory" : "loop";
346
+ }
347
+ }
348
+ if (pathFlags.symlinkFollow && openFlags.directory) {
349
+ let isFile = false;
350
+ try {
351
+ isFile = !statSync(fullPath).isDirectory();
352
+ }
353
+ catch {
354
+ //
355
+ }
356
+ if (isFile) {
357
+ throw "not-directory";
358
+ }
359
+ }
360
+ }
361
+ try {
362
+ const fd = openSync(fullPath.endsWith("/") ? fullPath.slice(0, -1) : fullPath, fsOpenFlags);
363
+ const descriptor = descriptorCreate(fd, descriptorFlags, fullPath);
364
+ if (fullPath.endsWith("/") && descriptor.getType() !== "directory") {
365
+ descriptor[symbolDispose]();
366
+ throw "not-directory";
367
+ }
368
+ return descriptor;
369
+ }
370
+ catch (e) {
371
+ if (e.code === "ERR_INVALID_ARG_VALUE") {
372
+ throw isWindows ? "no-entry" : "invalid";
373
+ }
374
+ throw convertFsError(e);
375
+ }
376
+ }
377
+ readlinkAt(path) {
378
+ const fullPath = this.#getFullPath(path, false);
379
+ try {
380
+ return readlinkSync(fullPath);
381
+ }
382
+ catch (e) {
383
+ throw convertFsError(e);
384
+ }
385
+ }
386
+ removeDirectoryAt(path) {
387
+ const fullPath = this.#getFullPath(path, false);
388
+ try {
389
+ rmdirSync(fullPath);
390
+ }
391
+ catch (e) {
392
+ if (isWindows && e.code === "ENOENT") {
393
+ throw "not-directory";
394
+ }
395
+ throw convertFsError(e);
396
+ }
397
+ }
398
+ renameAt(oldPath, newDescriptor, newPath) {
399
+ const oldFullPath = this.#getFullPath(oldPath, false);
400
+ const newFullPath = newDescriptor.#getFullPath(newPath, false);
401
+ try {
402
+ renameSync(oldFullPath, newFullPath);
403
+ }
404
+ catch (e) {
405
+ if (isWindows && e.code === "EPERM") {
406
+ throw "access";
407
+ }
408
+ throw convertFsError(e);
409
+ }
410
+ }
411
+ symlinkAt(target, path) {
412
+ const fullPath = this.#getFullPath(path, false);
413
+ if (target.startsWith("/")) {
414
+ throw "not-permitted";
415
+ }
416
+ try {
417
+ symlinkSync(target, fullPath);
418
+ }
419
+ catch (e) {
420
+ if (fullPath.endsWith("/") && e.code === "EEXIST") {
421
+ let isDir = false;
422
+ try {
423
+ isDir = statSync(fullPath).isDirectory();
424
+ }
425
+ catch {
426
+ //
427
+ }
428
+ if (!isDir) {
429
+ throw isWindows ? "no-entry" : "not-directory";
430
+ }
431
+ }
432
+ if (isWindows) {
433
+ if (e.code === "EPERM" || e.code === "EEXIST") {
434
+ throw "no-entry";
435
+ }
436
+ }
437
+ throw convertFsError(e);
438
+ }
439
+ }
440
+ unlinkFileAt(path) {
441
+ const fullPath = this.#getFullPath(path, false);
442
+ try {
443
+ if (fullPath.endsWith("/")) {
444
+ let isDir = false;
445
+ try {
446
+ isDir = statSync(fullPath).isDirectory();
447
+ }
448
+ catch {
449
+ //
450
+ }
451
+ throw isDir
452
+ ? isWindows
453
+ ? "access"
454
+ : isMac
455
+ ? "not-permitted"
456
+ : "is-directory"
457
+ : "not-directory";
458
+ }
459
+ unlinkSync(fullPath);
460
+ }
461
+ catch (e) {
462
+ if (isWindows && e.code === "EPERM") {
463
+ throw "access";
464
+ }
465
+ throw convertFsError(e);
466
+ }
467
+ }
468
+ isSameObject(other) {
469
+ return other === this;
470
+ }
471
+ metadataHash() {
472
+ if (this.#hostPreopen) {
473
+ return { upper: 0n, lower: BigInt(this._id) };
474
+ }
475
+ try {
476
+ const stats = fstatSync(this.#fd, { bigint: true });
477
+ return { upper: stats.mtimeNs, lower: stats.ino };
478
+ }
479
+ catch (e) {
480
+ throw convertFsError(e);
481
+ }
482
+ }
483
+ metadataHashAt(pathFlags, path) {
484
+ const fullPath = this.#getFullPath(path, false);
485
+ try {
486
+ const stats = (pathFlags.symlinkFollow ? statSync : lstatSync)(fullPath, {
487
+ bigint: true,
488
+ });
489
+ return { upper: stats.mtimeNs, lower: stats.ino };
490
+ }
491
+ catch (e) {
492
+ throw convertFsError(e);
493
+ }
494
+ }
495
+ // TODO: support followSymlinks
496
+ #getFullPath(subpath, _followSymlinks) {
497
+ let descriptor = this;
498
+ if (subpath.indexOf("\\") !== -1) {
499
+ subpath = subpath.replace(/\\/g, "/");
500
+ }
501
+ if (subpath.indexOf("//") !== -1) {
502
+ subpath = subpath.replace(/\/\/+/g, "/");
503
+ }
504
+ if (subpath[0] === "/") {
505
+ throw "not-permitted";
506
+ }
507
+ // segment resolution
508
+ const segments = [];
509
+ let segmentIndex = -1;
510
+ for (let i = 0; i < subpath.length; i++) {
511
+ // busy reading a segment - only terminate on '/'
512
+ if (segmentIndex !== -1) {
513
+ if (subpath[i] === "/") {
514
+ segments.push(subpath.slice(segmentIndex, i + 1));
515
+ segmentIndex = -1;
516
+ }
517
+ continue;
518
+ }
519
+ // new segment - check if it is relative
520
+ else if (subpath[i] === ".") {
521
+ // ../ segment
522
+ if (subpath[i + 1] === "." && (subpath[i + 2] === "/" || i + 2 === subpath.length)) {
523
+ if (segments.pop() === undefined) {
524
+ throw "not-permitted";
525
+ }
526
+ i += 2;
527
+ continue;
528
+ }
529
+ // ./ segment
530
+ else if (subpath[i + 1] === "/" || i + 1 === subpath.length) {
531
+ i += 1;
532
+ continue;
533
+ }
534
+ }
535
+ // it is the start of a new segment
536
+ while (subpath[i] === "/") {
537
+ i++;
538
+ }
539
+ segmentIndex = i;
540
+ }
541
+ // finish reading out the last segment
542
+ if (segmentIndex !== -1) {
543
+ segments.push(subpath.slice(segmentIndex));
544
+ }
545
+ subpath = segments.join("");
546
+ if (descriptor.#hostPreopen) {
547
+ return (descriptor.#hostPreopen +
548
+ (descriptor.#hostPreopen.endsWith("/") ? "" : subpath.length > 0 ? "/" : "") +
549
+ subpath);
550
+ }
551
+ return descriptor.#fullPath + (subpath.length > 0 ? "/" : "") + subpath;
552
+ }
553
+ }
554
+ const descriptorCreatePreopen = Descriptor._createPreopen;
555
+ // @ts-expect-error - Deleting static method
556
+ delete Descriptor._createPreopen;
557
+ const descriptorCreate = Descriptor._create;
558
+ // @ts-expect-error - Deleting static method
559
+ delete Descriptor._create;
560
+ class DirectoryEntryStream {
561
+ #dir;
562
+ #finalizer;
563
+ readDirectoryEntry() {
564
+ let entry;
565
+ try {
566
+ entry = this.#dir.readSync();
567
+ }
568
+ catch (e) {
569
+ throw convertFsError(e);
570
+ }
571
+ if (entry === null) {
572
+ return undefined;
573
+ }
574
+ const name = entry.name;
575
+ const type = lookupType(entry);
576
+ return { name, type };
577
+ }
578
+ static _create(dir) {
579
+ const dirStream = new DirectoryEntryStream();
580
+ dirStream.#finalizer = registerDispose(dirStream, null, 0, dir.closeSync.bind(dir));
581
+ dirStream.#dir = dir;
582
+ return dirStream;
583
+ }
584
+ [symbolDispose]() {
585
+ if (this.#finalizer) {
586
+ earlyDispose(this.#finalizer);
587
+ this.#finalizer = null;
588
+ }
589
+ }
590
+ }
591
+ const directoryEntryStreamCreate = DirectoryEntryStream._create;
592
+ // @ts-expect-error Deleting static method
593
+ delete DirectoryEntryStream._create;
594
+ let preopenEntries = [];
595
+ export const preopens = {
596
+ getDirectories() {
597
+ return preopenEntries;
598
+ },
599
+ };
600
+ _addPreopen("/", isWindows ? "//" : "/");
601
+ export const types = {
602
+ Descriptor,
603
+ DirectoryEntryStream,
604
+ filesystemErrorCode(err) {
605
+ return convertFsError(err.payload);
606
+ },
607
+ };
608
+ /**
609
+ * Replace all preopens with the given set.
610
+ * @param {Record<string, string>} preopens - Map of virtual paths to host paths
611
+ */
612
+ export function _setPreopens(preopens) {
613
+ preopenEntries = [];
614
+ for (const [virtualPath, hostPreopen] of Object.entries(preopens)) {
615
+ _addPreopen(virtualPath, hostPreopen);
616
+ }
617
+ }
618
+ /**
619
+ * Add a single preopen mapping.
620
+ * @param {string} virtualPath - The virtual path visible to the guest
621
+ * @param {string} hostPreopen - The host filesystem path
622
+ */
623
+ export function _addPreopen(virtualPath, hostPreopen) {
624
+ const preopenEntry = [descriptorCreatePreopen(hostPreopen), virtualPath];
625
+ preopenEntries.push(preopenEntry);
626
+ }
627
+ /**
628
+ * Clear all preopens, giving the guest no filesystem access.
629
+ * Call this immediately after import to disable default full filesystem access.
630
+ *
631
+ * @example
632
+ * import { _clearPreopens } from '@bytecodealliance/preview2-shim/filesystem';
633
+ * _clearPreopens(); // Now guest has no filesystem access by default
634
+ */
635
+ export function _clearPreopens() {
636
+ preopenEntries = [];
637
+ }
638
+ /**
639
+ * Get current preopens configuration.
640
+ * @returns {Array<[Descriptor, string]>} Array of [descriptor, virtualPath] pairs
641
+ */
642
+ export function _getPreopens() {
643
+ return [...preopenEntries];
644
+ }
645
+ /**
646
+ * Create a preopen descriptor for a host path.
647
+ * This is used internally to create isolated preopen instances.
648
+ * @param hostPreopen - The host filesystem path
649
+ * @returns A preopen descriptor
650
+ */
651
+ export function _createPreopenDescriptor(hostPreopen) {
652
+ return descriptorCreatePreopen(hostPreopen);
653
+ }
654
+ function convertFsError(e) {
655
+ switch (e.code) {
656
+ case "EACCES":
657
+ return "access";
658
+ case "EAGAIN":
659
+ case "EWOULDBLOCK":
660
+ return "would-block";
661
+ case "EALREADY":
662
+ return "already";
663
+ case "EBADF":
664
+ return "bad-descriptor";
665
+ case "EBUSY":
666
+ return "busy";
667
+ case "EDEADLK":
668
+ return "deadlock";
669
+ case "EDQUOT":
670
+ return "quota";
671
+ case "EEXIST":
672
+ return "exist";
673
+ case "EFBIG":
674
+ return "file-too-large";
675
+ case "EILSEQ":
676
+ return "illegal-byte-sequence";
677
+ case "EINPROGRESS":
678
+ return "in-progress";
679
+ case "EINTR":
680
+ return "interrupted";
681
+ case "EINVAL":
682
+ return "invalid";
683
+ case "EIO":
684
+ return "io";
685
+ case "EISDIR":
686
+ return "is-directory";
687
+ case "ELOOP":
688
+ return "loop";
689
+ case "EMLINK":
690
+ return "too-many-links";
691
+ case "EMSGSIZE":
692
+ return "message-size";
693
+ case "ENAMETOOLONG":
694
+ return "name-too-long";
695
+ case "ENODEV":
696
+ return "no-device";
697
+ case "ENOENT":
698
+ return "no-entry";
699
+ case "ENOLCK":
700
+ return "no-lock";
701
+ case "ENOMEM":
702
+ return "insufficient-memory";
703
+ case "ENOSPC":
704
+ return "insufficient-space";
705
+ case "ENOTDIR":
706
+ case "ERR_FS_EISDIR":
707
+ return "not-directory";
708
+ case "ENOTEMPTY":
709
+ return "not-empty";
710
+ case "ENOTRECOVERABLE":
711
+ return "not-recoverable";
712
+ case "ENOTSUP":
713
+ return "unsupported";
714
+ case "ENOTTY":
715
+ return "no-tty";
716
+ // windows gives this error for badly structured `//` reads
717
+ // this seems like a slightly better error than unknown given
718
+ // that it's a common footgun
719
+ case -4094:
720
+ case "ENXIO":
721
+ return "no-such-device";
722
+ case "EOVERFLOW":
723
+ return "overflow";
724
+ case "EPERM":
725
+ return "not-permitted";
726
+ case "EPIPE":
727
+ return "pipe";
728
+ case "EROFS":
729
+ return "read-only";
730
+ case "ESPIPE":
731
+ return "invalid-seek";
732
+ case "ETXTBSY":
733
+ return "text-file-busy";
734
+ case "EXDEV":
735
+ return "cross-device";
736
+ case "UNKNOWN":
737
+ switch (e.errno) {
738
+ case -4094:
739
+ return "no-such-device";
740
+ default:
741
+ throw e;
742
+ }
743
+ default:
744
+ throw e;
745
+ }
746
+ }
747
+ function timestampToMs(timestamp) {
748
+ let secondsInMillis = timestamp.seconds * 1000n;
749
+ if (secondsInMillis > Number.MAX_SAFE_INTEGER) {
750
+ throw new Error(`cannot represent millisecond amount as Number [${{ secondsInMillis }}]`);
751
+ }
752
+ if (timestamp.nanoseconds > Number.MAX_SAFE_INTEGER) {
753
+ throw new Error(`cannot represent millisecond amount as Number [${{ secondsInMillis }}]`);
754
+ }
755
+ let remainderFractionalMillis = timestamp.nanoseconds / 1_000_000;
756
+ const res = Number(secondsInMillis) + remainderFractionalMillis;
757
+ return res;
758
+ }