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