cf-workers-native 0.1.5 → 0.1.6

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 (197) hide show
  1. package/README.md +2 -2
  2. package/dist/browser/documents/page-source.js +1 -1
  3. package/dist/browser/headers/index.d.ts +2 -0
  4. package/dist/browser/headers/index.js +5 -0
  5. package/dist/browser/response/index.d.ts +2 -0
  6. package/dist/browser/response/index.js +11 -3
  7. package/dist/browser/structured-clone/index.d.ts +3 -0
  8. package/dist/browser/structured-clone/index.js +75 -7
  9. package/dist/browser/websocket/attachment-size.d.ts +3 -0
  10. package/dist/browser/websocket/attachment-size.js +336 -0
  11. package/dist/browser/websocket/brand.d.ts +4 -0
  12. package/dist/browser/websocket/brand.js +16 -0
  13. package/dist/browser/websocket/close-event.d.ts +7 -0
  14. package/dist/browser/websocket/close-event.js +30 -0
  15. package/dist/browser/websocket/compression.d.ts +5 -0
  16. package/dist/browser/websocket/compression.js +124 -0
  17. package/dist/browser/websocket/conversion.d.ts +2 -0
  18. package/dist/browser/websocket/conversion.js +13 -0
  19. package/dist/browser/websocket/endpoint.d.ts +39 -0
  20. package/dist/browser/websocket/endpoint.js +379 -0
  21. package/dist/browser/websocket/frames.d.ts +21 -0
  22. package/dist/browser/websocket/frames.js +121 -0
  23. package/dist/browser/websocket/native.d.ts +14 -0
  24. package/dist/browser/websocket/native.js +226 -0
  25. package/dist/cloudflare/apis/cloudflare-node/index.js +11 -23
  26. package/dist/compat/crypto/LICENSE-3RD-PARTY.md +20 -0
  27. package/dist/compat/crypto/LICENSE.boringssl +238 -0
  28. package/dist/compat/crypto/LICENSE.ncrypto +21 -0
  29. package/dist/compat/crypto/asymmetric.js +141 -68
  30. package/dist/compat/crypto/cipher-handle.d.ts +27 -0
  31. package/dist/compat/crypto/cipher-handle.js +239 -0
  32. package/dist/compat/crypto/cipher-info.d.ts +12 -0
  33. package/dist/compat/crypto/cipher-info.js +324 -0
  34. package/dist/compat/crypto/constants.d.ts +62 -0
  35. package/dist/compat/crypto/constants.js +68 -0
  36. package/dist/compat/crypto/dh-handle.d.ts +17 -0
  37. package/dist/compat/crypto/dh-handle.js +180 -0
  38. package/dist/compat/crypto/dh.d.ts +53 -0
  39. package/dist/compat/crypto/dh.js +138 -0
  40. package/dist/compat/crypto/digest-stream.d.ts +15 -0
  41. package/dist/compat/crypto/digest-stream.js +213 -0
  42. package/dist/compat/crypto/digests.d.ts +3 -0
  43. package/dist/compat/crypto/digests.js +32 -0
  44. package/dist/compat/crypto/ecdh.d.ts +16 -6
  45. package/dist/compat/crypto/hash-handle.d.ts +23 -0
  46. package/dist/compat/crypto/hash-handle.js +70 -0
  47. package/dist/compat/crypto/hash.d.ts +37 -0
  48. package/dist/compat/crypto/hash.js +218 -0
  49. package/dist/compat/crypto/hkdf.js +40 -14
  50. package/dist/compat/crypto/index.d.cts +168 -1
  51. package/dist/compat/crypto/index.d.ts +191 -8
  52. package/dist/compat/crypto/index.js +36 -23
  53. package/dist/compat/crypto/key-errors.d.ts +10 -0
  54. package/dist/compat/crypto/key-errors.js +17 -0
  55. package/dist/compat/crypto/key-export.d.ts +8 -0
  56. package/dist/compat/crypto/key-export.js +49 -0
  57. package/dist/compat/crypto/key-formats.d.ts +2 -1
  58. package/dist/compat/crypto/key-formats.js +162 -31
  59. package/dist/compat/crypto/key-options.d.ts +1 -0
  60. package/dist/compat/crypto/key-options.js +74 -0
  61. package/dist/compat/crypto/key-state.d.ts +1 -0
  62. package/dist/compat/crypto/keys.d.ts +20 -12
  63. package/dist/compat/crypto/keys.js +125 -56
  64. package/dist/compat/crypto/metadata.d.ts +9 -0
  65. package/dist/compat/crypto/metadata.js +89 -2
  66. package/dist/compat/crypto/native-cipher.d.ts +17 -0
  67. package/dist/compat/crypto/native-cipher.js +192 -0
  68. package/dist/compat/crypto/native-crypto.d.ts +14 -1
  69. package/dist/compat/crypto/native-crypto.js +118 -6
  70. package/dist/compat/crypto/pbkdf2-handle.d.ts +4 -0
  71. package/dist/compat/crypto/pbkdf2-handle.js +26 -0
  72. package/dist/compat/crypto/pbkdf2.d.ts +5 -0
  73. package/dist/compat/crypto/pbkdf2.js +60 -0
  74. package/dist/compat/crypto/prime.js +4 -4
  75. package/dist/compat/crypto/random.d.ts +11 -0
  76. package/dist/compat/crypto/random.js +86 -6
  77. package/dist/compat/crypto/rsa.d.ts +17 -1
  78. package/dist/compat/crypto/rsa.js +8 -4
  79. package/dist/compat/crypto/scrypt.d.ts +3 -3
  80. package/dist/compat/crypto/scrypt.js +25 -23
  81. package/dist/compat/crypto/sign-handle.d.ts +3 -3
  82. package/dist/compat/crypto/sign-handle.js +55 -11
  83. package/dist/compat/crypto/signatures.d.ts +17 -11
  84. package/dist/compat/crypto/subtle-digest.d.ts +1 -0
  85. package/dist/compat/crypto/subtle-digest.js +56 -0
  86. package/dist/compat/crypto/symmetric.d.ts +40 -24
  87. package/dist/compat/crypto/symmetric.js +229 -94
  88. package/dist/compat/crypto/validation.d.ts +4 -0
  89. package/dist/compat/crypto/validation.js +29 -2
  90. package/dist/compat/crypto/webcrypto.d.ts +13 -0
  91. package/dist/compat/crypto/webcrypto.js +51 -0
  92. package/dist/compat/crypto/x509.js +2 -1
  93. package/dist/compat/events/index.js +1 -1
  94. package/dist/compat/fs/LICENSE-3RD-PARTY.md +11 -0
  95. package/dist/compat/fs/LICENSE-APACHE +177 -0
  96. package/dist/compat/fs/directory-backend.d.ts +6 -0
  97. package/dist/compat/fs/directory-backend.js +51 -0
  98. package/dist/compat/fs/directory.d.ts +37 -0
  99. package/dist/compat/fs/directory.js +137 -0
  100. package/dist/compat/fs/embedded.d.ts +1 -1
  101. package/dist/compat/fs/embedded.js +7 -2
  102. package/dist/compat/fs/file-handle.d.ts +75 -0
  103. package/dist/compat/fs/file-handle.js +226 -0
  104. package/dist/compat/fs/glob-internal.d.ts +15 -0
  105. package/dist/compat/fs/glob-internal.js +417 -0
  106. package/dist/compat/fs/glob.d.ts +10 -0
  107. package/dist/compat/fs/glob.js +71 -0
  108. package/dist/compat/fs/index.d.ts +6 -3
  109. package/dist/compat/fs/index.js +582 -50
  110. package/dist/compat/fs/io-validation.d.ts +14 -0
  111. package/dist/compat/fs/io-validation.js +130 -0
  112. package/dist/compat/fs/io.d.ts +1 -0
  113. package/dist/compat/fs/io.js +282 -0
  114. package/dist/compat/fs/promises/index.d.ts +3 -1
  115. package/dist/compat/fs/public-types.d.ts +120 -0
  116. package/dist/compat/fs/public-types.js +1 -0
  117. package/dist/compat/fs/stream-errors.d.ts +6 -0
  118. package/dist/compat/fs/stream-errors.js +8 -0
  119. package/dist/compat/fs/stream-utils.d.ts +16 -0
  120. package/dist/compat/fs/stream-utils.js +29 -0
  121. package/dist/compat/fs/streams.d.ts +104 -0
  122. package/dist/compat/fs/streams.js +794 -0
  123. package/dist/compat/fs/writable.d.ts +8 -0
  124. package/dist/compat/fs/writable.js +412 -22
  125. package/dist/compat/http/index.d.ts +11 -28
  126. package/dist/compat/http/index.js +81 -125
  127. package/dist/compat/http/server-options.d.ts +1 -0
  128. package/dist/compat/http/server-options.js +87 -0
  129. package/dist/compat/http/unique-headers.d.ts +1 -0
  130. package/dist/compat/http/unique-headers.js +21 -0
  131. package/dist/compat/http-outgoing/index.d.ts +2 -1
  132. package/dist/compat/http-outgoing/index.js +2 -17
  133. package/dist/compat/http-server/index.d.ts +2 -2
  134. package/dist/compat/http-server/index.js +4 -85
  135. package/dist/compat/https/index.d.ts +4 -2
  136. package/dist/compat/net/sockets.js +98 -20
  137. package/dist/compat/net/validators.d.ts +1 -0
  138. package/dist/compat/net/validators.js +8 -0
  139. package/dist/compat/process/configuration.d.ts +113 -0
  140. package/dist/compat/process/configuration.js +115 -0
  141. package/dist/compat/process/directory.d.ts +4 -0
  142. package/dist/compat/process/directory.js +28 -0
  143. package/dist/compat/process/files.d.ts +3 -0
  144. package/dist/compat/process/files.js +10 -0
  145. package/dist/compat/process/index.d.ts +15 -13
  146. package/dist/compat/process/index.js +47 -74
  147. package/dist/compat/process/scheduling.d.ts +2 -0
  148. package/dist/compat/process/scheduling.js +60 -0
  149. package/dist/compat/process/state.js +1 -0
  150. package/dist/compat/process/stdio.d.ts +18 -0
  151. package/dist/compat/process/stdio.js +66 -0
  152. package/dist/compat/stream/destroy.d.ts +1 -0
  153. package/dist/compat/stream/destroy.js +21 -1
  154. package/dist/compat/stream/readable.js +10 -2
  155. package/dist/compat/tls/jsstream.js +16 -6
  156. package/dist/compat/tls/wrap.d.ts +1 -1
  157. package/dist/compat/tls/wrap.js +0 -3
  158. package/dist/compat/util/inspect.js +5 -1
  159. package/dist/compat/zlib/LICENSE-3RD-PARTY.md +11 -0
  160. package/dist/compat/zlib/LICENSE-APACHE +177 -0
  161. package/dist/compat/zlib/LICENSE.zlib +22 -0
  162. package/dist/compat/zlib/classic-base.cjs +600 -0
  163. package/dist/compat/zlib/classic-base.d.cts +39 -0
  164. package/dist/compat/zlib/classic-binding.d.ts +28 -0
  165. package/dist/compat/zlib/classic-binding.js +105 -0
  166. package/dist/compat/zlib/classic.d.ts +44 -0
  167. package/dist/compat/zlib/classic.js +199 -0
  168. package/dist/compat/zlib/codec-binding.d.ts +33 -0
  169. package/dist/compat/zlib/codec-binding.js +141 -0
  170. package/dist/compat/zlib/compression.d.ts +22 -51
  171. package/dist/compat/zlib/compression.js +129 -218
  172. package/dist/compat/zlib/errors.d.ts +21 -0
  173. package/dist/compat/zlib/errors.js +32 -0
  174. package/dist/compat/zlib/index.d.ts +367 -3
  175. package/dist/compat/zlib/index.js +28 -11
  176. package/dist/compat/zlib/input.d.ts +16 -0
  177. package/dist/compat/zlib/input.js +132 -0
  178. package/dist/compat/zlib/native-codecs.d.ts +7 -0
  179. package/dist/compat/zlib/native-codecs.js +22 -10
  180. package/dist/compat/zlib/native-zlib.d.ts +5 -0
  181. package/dist/compat/zlib/native-zlib.js +52 -0
  182. package/dist/compat/zlib/public-types.d.ts +48 -0
  183. package/dist/compat/zlib/public-types.js +1 -0
  184. package/dist/compat/zlib/validators.d.ts +3 -0
  185. package/dist/compat/zlib/validators.js +18 -0
  186. package/dist/shared/buffer-source.d.ts +5 -0
  187. package/dist/shared/buffer-source.js +70 -0
  188. package/dist/shared/globals/platform.d.ts +8 -0
  189. package/dist/shared/globals/platform.js +1 -0
  190. package/dist/shared/globals/web.js +5 -0
  191. package/dist/shared/request-context.d.ts +2 -0
  192. package/dist/shared/request-context.js +11 -0
  193. package/dist/shared/request-scope.js +4 -1
  194. package/dist/tooling/shared.js +6 -0
  195. package/dist/tooling/vite.js +4 -0
  196. package/native/android/src/main/java/jp/rdlabo/workerscapacitor/WorkerSockets.java +38 -7
  197. package/package.json +2 -2
@@ -1,9 +1,16 @@
1
+ import { createFileHandle, FileHandle } from "./file-handle.js";
2
+ import { installIo } from "./io.js";
3
+ import * as fileStreams from "./streams.js";
4
+ import { Dir as WorkersDir, Dirent as WorkersDirent } from "./directory.js";
5
+ import { readDirectory } from "./directory-backend.js";
6
+ import { globSync as workersGlob } from "./glob.js";
1
7
  import { fileMode } from "./mode.js";
2
8
  import { validateInteger } from "../crypto/validation.js";
3
9
  import * as embedded from "./embedded.js";
4
- import { temporary, temporaryPath, clearTemporaryFiles, writablePath, pathOf, } from "./writable.js";
10
+ import { temporary, retainTemporaryFiles, temporaryPath, clearTemporaryFiles, writablePath, pathOf, readonlyFile, embeddedStat, } from "./writable.js";
5
11
  import { Buffer } from "node:buffer";
6
- import { validateFunction, validateObject, validateBoolean, } from "../net/validators.js";
12
+ import { validateFunction, validateObject, validateBoolean, validateUint32, } from "../net/validators.js";
13
+ import { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE } from "../net/errors.js";
7
14
  export const registerVirtualFiles = embedded.registerVirtualFiles;
8
15
  export function clearVirtualFiles() {
9
16
  embedded.clearVirtualFiles();
@@ -32,8 +39,10 @@ for (const name of [
32
39
  ]) {
33
40
  api[name] = new Proxy(api[name], {
34
41
  construct(_target, args) {
42
+ if (name === "ReadStream" || name === "FileReadStream")
43
+ return temporary.createReadStream(...args);
35
44
  args[0] = writablePath(args[0], name);
36
- return Reflect.construct(temporary[name], args);
45
+ return temporary.createWriteStream(...args);
37
46
  },
38
47
  });
39
48
  }
@@ -56,10 +65,10 @@ for (const name of ["writeFileSync", "appendFileSync"])
56
65
  ? Buffer.byteLength(args[1], encoding)
57
66
  : args[1].byteLength;
58
67
  };
59
- const promises = { ...temporary.promises };
60
- for (const name of Object.keys(promises))
61
- if (typeof promises[name] === "function" && /^[a-z]/.test(name))
62
- promises[name] = (...args) => temporary.promises[name](...args);
68
+ const promiseImpl = { ...temporary.promises };
69
+ for (const name of Object.keys(promiseImpl))
70
+ if (typeof promiseImpl[name] === "function" && /^[a-z]/.test(name))
71
+ promiseImpl[name] = (...args) => temporary.promises[name](...args);
63
72
  for (const name of [
64
73
  "readFile",
65
74
  "readdir",
@@ -69,7 +78,7 @@ for (const name of [
69
78
  "access",
70
79
  ]) {
71
80
  const old = embedded.promises[name];
72
- promises[name] = (...args) => temporaryPath(args[0]) ? temporary.promises[name](...args) : old(...args);
81
+ promiseImpl[name] = async (...args) => temporaryPath(args[0]) ? temporary.promises[name](...args) : old(...args);
73
82
  }
74
83
  // Keep all writes inside the memory volume, including FileHandle operations.
75
84
  for (const name of [
@@ -87,14 +96,11 @@ for (const name of [
87
96
  "chown",
88
97
  "lchmod",
89
98
  "lchown",
90
- "open",
91
99
  "rename",
92
100
  "copyFile",
93
- "cp",
94
- "link",
95
101
  "symlink",
96
102
  ]) {
97
- promises[name] = async (...args) => {
103
+ promiseImpl[name] = async (...args) => {
98
104
  if (name === "symlink") {
99
105
  return new Promise((resolve, reject) => temporary.symlink(...args, (error) => error ? reject(error) : resolve(undefined)));
100
106
  }
@@ -106,15 +112,15 @@ for (const name of [
106
112
  args[i] instanceof URL ||
107
113
  Buffer.isBuffer(args[i])) {
108
114
  if (!temporaryPath(args[i]))
109
- throw Object.assign(new Error("EROFS: read-only file system"), {
110
- code: "EROFS",
115
+ throw Object.assign(new Error("operation not permitted"), {
116
+ code: "EPERM",
111
117
  });
112
118
  }
113
119
  return temporary.promises[name](...args);
114
120
  };
115
121
  }
116
- promises.watch = async function* () {
117
- api.watch();
122
+ promiseImpl.watch = function () {
123
+ throw new Error("Not implemented");
118
124
  };
119
125
  // Workers validates ownership/permission requests but has no mutable Unix
120
126
  // ownership or permissions. These operations must not change the memory VFS.
@@ -128,39 +134,143 @@ function installOperation(name, handler, promise = true) {
128
134
  .then((value) => callback(null, value), (error) => callback(error));
129
135
  };
130
136
  if (promise)
131
- promises[name] = async (...args) => handler(...args);
137
+ promiseImpl[name] = async (...args) => handler(...args);
132
138
  }
133
- function temporaryStats(stat) {
139
+ function temporaryStats(stat, readonly = false) {
134
140
  if (stat == null)
135
141
  return stat;
136
142
  const bigint = typeof stat.mode === "bigint";
137
- const mode = (Number(stat.mode) & ~0o777) | 0o666;
143
+ const mode = (Number(stat.mode) & ~0o777) |
144
+ (readonly || stat.isSymbolicLink() ? 0o444 : 0o666);
138
145
  stat.mode = bigint ? BigInt(mode) : mode;
139
- stat.uid = stat.gid = bigint ? 0n : 0;
146
+ for (const name of [
147
+ "dev",
148
+ "ino",
149
+ "uid",
150
+ "gid",
151
+ "rdev",
152
+ "blksize",
153
+ "blocks",
154
+ "atimeMs",
155
+ ])
156
+ stat[name] = bigint ? 0n : 0;
157
+ stat.dev = bigint
158
+ ? BigInt(stat.isCharacterDevice())
159
+ : Number(stat.isCharacterDevice());
160
+ stat.nlink = bigint ? 1n : 1;
161
+ stat.atime = new Date(0);
162
+ stat.ctime = stat.mtime;
163
+ stat.ctimeMs = stat.mtimeMs;
164
+ if (bigint) {
165
+ stat.atimeNs = 0n;
166
+ stat.ctimeNs = stat.mtimeNs;
167
+ }
168
+ if (readonly)
169
+ for (const name of ["mtime", "ctime", "birthtime"]) {
170
+ stat[name] = new Date(0);
171
+ stat[name + "Ms"] = bigint ? 0n : 0;
172
+ if (bigint)
173
+ stat[name + "Ns"] = 0n;
174
+ }
140
175
  return stat;
141
176
  }
177
+ // Workers has no executable files. Read-only bundle files also report ENOENT
178
+ // for W_OK rather than exposing host-style permission bits.
179
+ function accessArgs(path, mode = 0) {
180
+ const normalized = pathOf(path);
181
+ mode ??= 0;
182
+ validateInteger(mode, "mode", 0, 7);
183
+ return { path: normalized, mode: mode };
184
+ }
185
+ function checkAccess({ path, mode }) {
186
+ if (mode & 1 || (mode & 2 && readonlyFile(path)) || !api.existsSync(path))
187
+ throw Object.assign(new Error(`ENOENT: no such file or directory, access '${path}'`), {
188
+ code: "ENOENT",
189
+ errno: -2,
190
+ syscall: "access",
191
+ path,
192
+ });
193
+ }
194
+ api.accessSync = (path, mode) => checkAccess(accessArgs(path, mode));
195
+ api.access = (path, mode, callback) => {
196
+ if (typeof mode === "function") {
197
+ callback = mode;
198
+ mode = undefined;
199
+ }
200
+ const args = accessArgs(path, mode);
201
+ validateFunction(callback, "callback");
202
+ let failure = null;
203
+ try {
204
+ checkAccess(args);
205
+ }
206
+ catch (error) {
207
+ failure = error;
208
+ }
209
+ queueMicrotask(() => callback(failure));
210
+ };
211
+ promiseImpl.access = async (path, mode) => checkAccess(accessArgs(path, mode));
212
+ function statOptions(options = {}) {
213
+ validateObject(options, "options");
214
+ validateBoolean(options.bigint ?? false, "options.bigint");
215
+ validateBoolean(options.throwIfNoEntry ?? true, "options.throwIfNoEntry");
216
+ return options;
217
+ }
142
218
  for (const name of ["stat", "lstat"])
143
- installOperation(name, (path, options) => temporaryPath(path)
144
- ? temporaryStats(temporary[name + "Sync"](path, options))
145
- : embedded.statSync(path));
146
- installOperation("fstat", (...args) => temporaryStats(temporary.fstatSync(...args)), false);
219
+ installOperation(name, (path, options = {}) => {
220
+ statOptions(options);
221
+ return temporaryPath(path)
222
+ ? temporaryStats(temporary[name + "Sync"](path, options), readonlyFile(path, name !== "lstat"))
223
+ : temporaryStats(embeddedStat(path, options), true);
224
+ });
225
+ installOperation("fstat", (fd, options = {}) => {
226
+ statOptions(options);
227
+ validateInteger(fd, "fd", 0, 2147483647);
228
+ return temporaryStats(temporary.fstatSync(fd, options), readonlyFile(fd));
229
+ }, false);
147
230
  for (const name of ["chmod", "lchmod", "fchmod", "chown", "lchown", "fchown"]) {
148
- installOperation(name, (path, value, gid) => {
231
+ const count = name.endsWith("chmod") ? 2 : 3;
232
+ const prepare = (args) => {
233
+ const [path, value, gid] = args;
149
234
  if (name.endsWith("chmod"))
150
235
  fileMode(value);
151
236
  else {
152
237
  validateInteger(value, "uid", -1, 0xffffffff);
153
238
  validateInteger(gid, "gid", -1, 0xffffffff);
154
239
  }
155
- if (name.startsWith("f")) {
240
+ if (typeof path === "number" || name.startsWith("f"))
156
241
  validateInteger(path, "fd", 0, 2147483647);
157
- temporary.fstatSync(path);
158
- }
159
- else if (name.startsWith("l") && temporaryPath(path))
160
- temporary.lstatSync(path);
161
242
  else
162
- api.statSync(path);
163
- }, !name.startsWith("f"));
243
+ pathOf(path);
244
+ return path;
245
+ };
246
+ const operation = (path) => {
247
+ try {
248
+ if (typeof path === "number")
249
+ temporary.fstatSync(path);
250
+ else
251
+ api[name.startsWith("l") ? "lstatSync" : "statSync"](path);
252
+ }
253
+ catch (error) {
254
+ if (error.code === "ENOENT")
255
+ error.syscall = name;
256
+ throw error;
257
+ }
258
+ };
259
+ api[name + "Sync"] = (...args) => operation(prepare(args));
260
+ api[name] = (...args) => {
261
+ const path = prepare(args), callback = args[count];
262
+ validateFunction(callback, "callback");
263
+ let error = null;
264
+ try {
265
+ operation(path);
266
+ }
267
+ catch (failure) {
268
+ error = failure;
269
+ }
270
+ queueMicrotask(() => callback(error));
271
+ };
272
+ if (!name.startsWith("f"))
273
+ promiseImpl[name] = async (...args) => operation(prepare(args));
164
274
  }
165
275
  installOperation("statfs", (path, options = {}) => {
166
276
  pathOf(path);
@@ -178,23 +288,40 @@ installOperation("statfs", (path, options = {}) => {
178
288
  ffree: value,
179
289
  };
180
290
  });
181
- const openPromise = promises.open;
182
- promises.open = async (...args) => {
183
- fileMode(args[2], 0o666);
184
- args[2] = 0o666;
185
- const handle = await openPromise(...args);
186
- const stat = handle.stat.bind(handle);
187
- handle.stat = async (...options) => temporaryStats(await stat(...options));
188
- handle.chmod = async (mode) => {
189
- fileMode(mode);
190
- await stat();
191
- };
192
- handle.chown = async (uid, gid) => {
193
- validateInteger(uid, "uid", -1, 0xffffffff);
194
- validateInteger(gid, "gid", -1, 0xffffffff);
195
- await stat();
196
- };
197
- return handle;
291
+ // Workers interprets numeric timestamps as milliseconds and does not change
292
+ // metadata belonging to embedded files. Convert before the memfs boundary.
293
+ function fileTime(value) {
294
+ let date;
295
+ if (value instanceof Date)
296
+ date = value;
297
+ else if (typeof value === "number" || typeof value === "string")
298
+ date = new Date(value);
299
+ else if (typeof value === "bigint")
300
+ date = new Date(Number(value));
301
+ else
302
+ throw new ERR_INVALID_ARG_TYPE("time", ["string", "number", "bigint", "Date"], value);
303
+ if (!Number.isFinite(date.getTime()))
304
+ throw new TypeError("The value cannot be converted because it is not an integer.");
305
+ return date;
306
+ }
307
+ for (const name of ["utimes", "lutimes", "futimes"]) {
308
+ installOperation(name, (path, atime, mtime) => {
309
+ const access = fileTime(atime), modified = fileTime(mtime);
310
+ if (name === "futimes") {
311
+ validateInteger(path, "fd", 0, 2147483647);
312
+ api.fstatSync(path);
313
+ }
314
+ else
315
+ api[name === "lutimes" ? "lstatSync" : "statSync"](path);
316
+ if (!readonlyFile(path, name !== "lutimes"))
317
+ temporary[name + "Sync"](path, access, modified);
318
+ }, name !== "futimes");
319
+ }
320
+ promiseImpl.FileHandle = FileHandle;
321
+ promiseImpl.open = async (path, flags, mode) => {
322
+ const run = retainTemporaryFiles();
323
+ const fd = api.openSync(path, flags, mode);
324
+ return createFileHandle({ fd, run, api });
198
325
  };
199
326
  // Copy an embedded bundle file into request-local /tmp without granting any
200
327
  // write access to its source volume.
@@ -215,7 +342,412 @@ installOperation("copyFile", (source, destination, mode = 0) => {
215
342
  throw Object.assign(new Error("File already exists"), { code: "EEXIST" });
216
343
  temporary.writeFileSync(destination, embedded.readFileSync(pathOf(source)));
217
344
  });
218
- api.promises = promises;
345
+ const copyTree = (source, destination, options) => {
346
+ const fail = (code) => {
347
+ throw Object.assign(new Error(code), { code, syscall: "cp" });
348
+ };
349
+ source = pathOf(source);
350
+ destination = pathOf(destination);
351
+ if (source === destination)
352
+ throw new Error("Source and destination paths must not be the same");
353
+ if (destination.startsWith(source + "/"))
354
+ fail("ERR_FS_CP_EINVAL");
355
+ const lookup = (path, follow) => {
356
+ try {
357
+ return api[follow ? "statSync" : "lstatSync"](path);
358
+ }
359
+ catch (error) {
360
+ if (error.code !== "ENOENT")
361
+ throw error;
362
+ }
363
+ };
364
+ const visit = (src, dst, nested = false) => {
365
+ const stat = lookup(src, nested ? false : options.dereference);
366
+ if (!stat)
367
+ fail("ENOENT");
368
+ const target = lookup(dst, options.dereference);
369
+ if (stat.isDirectory()) {
370
+ if (!options.recursive)
371
+ fail("ERR_FS_EISDIR");
372
+ if (target && !target.isDirectory())
373
+ fail(target.isSymbolicLink()
374
+ ? nested
375
+ ? "EISDIR"
376
+ : "ENOTDIR"
377
+ : nested
378
+ ? "ENOTDIR"
379
+ : "ERR_FS_CP_DIR_TO_NON_DIR");
380
+ const entries = api.readdirSync(src);
381
+ api.mkdirSync(dst, { recursive: true });
382
+ for (const name of entries)
383
+ visit(src + "/" + name, dst + "/" + name, true);
384
+ return;
385
+ }
386
+ if (target?.isDirectory())
387
+ fail(nested
388
+ ? "EISDIR"
389
+ : stat.isSymbolicLink()
390
+ ? "ENOTDIR"
391
+ : "ERR_FS_CP_NON_DIR_TO_DIR");
392
+ if (target && !options.force) {
393
+ if (options.errorOnExist)
394
+ fail(nested ? "EEXIST" : "ERR_FS_CP_EEXIST");
395
+ return;
396
+ }
397
+ const data = stat.isSymbolicLink()
398
+ ? api.readlinkSync(src)
399
+ : api.readFileSync(src);
400
+ api.mkdirSync(dst.slice(0, dst.lastIndexOf("/")) || "/", {
401
+ recursive: true,
402
+ });
403
+ if (lookup(dst, false))
404
+ api.unlinkSync(dst);
405
+ if (stat.isSymbolicLink())
406
+ api.symlinkSync(data, dst);
407
+ else
408
+ api.writeFileSync(dst, data);
409
+ };
410
+ visit(source, destination);
411
+ };
412
+ installOperation("cp", (source, destination, options = {}) => {
413
+ validateObject(options, "options");
414
+ const { dereference = false, errorOnExist = false, force = true, preserveTimestamps = false, recursive = false, verbatimSymlinks = false, mode = 0, } = options;
415
+ for (const [key, value] of Object.entries({
416
+ dereference,
417
+ errorOnExist,
418
+ force,
419
+ preserveTimestamps,
420
+ recursive,
421
+ verbatimSymlinks,
422
+ }))
423
+ validateBoolean(value, "options." + key);
424
+ validateUint32(mode, "options.mode");
425
+ if (mode & 4)
426
+ throw new ERR_INVALID_ARG_VALUE("options.mode", "COPYFILE_FICLONE_FORCE is not supported");
427
+ if (options.filter !== undefined) {
428
+ if (typeof options.filter !== "function")
429
+ throw new ERR_INVALID_ARG_TYPE("options.filter", "function", options.filter);
430
+ throw Object.assign(new Error("The requested operation is unsupported"), {
431
+ code: "ERR_UNSUPPORTED_OPERATION",
432
+ });
433
+ }
434
+ return copyTree(source, destination, {
435
+ dereference,
436
+ errorOnExist,
437
+ force,
438
+ recursive,
439
+ verbatimSymlinks: false,
440
+ preserveTimestamps: false,
441
+ mode: 0,
442
+ });
443
+ });
444
+ api.cp = (source, destination, options, callback) => {
445
+ if (typeof options === "function") {
446
+ callback = options;
447
+ options = {};
448
+ }
449
+ validateObject(options ?? {}, "options");
450
+ for (const key of [
451
+ "dereference",
452
+ "errorOnExist",
453
+ "force",
454
+ "preserveTimestamps",
455
+ "recursive",
456
+ "verbatimSymlinks",
457
+ ])
458
+ if (options?.[key] !== undefined)
459
+ validateBoolean(options[key], "options." + key);
460
+ if (options?.mode !== undefined)
461
+ validateUint32(options.mode, "options.mode");
462
+ if (options?.filter !== undefined && typeof options.filter !== "function")
463
+ throw new ERR_INVALID_ARG_TYPE("options.filter", "function", options.filter);
464
+ if (options?.filter !== undefined)
465
+ throw Object.assign(new Error("The requested operation is unsupported"), {
466
+ code: "ERR_UNSUPPORTED_OPERATION",
467
+ });
468
+ if (options?.mode & 4)
469
+ throw new ERR_INVALID_ARG_VALUE("options.mode", "COPYFILE_FICLONE_FORCE is not supported");
470
+ pathOf(source);
471
+ pathOf(destination);
472
+ validateFunction(callback, "callback");
473
+ let error;
474
+ try {
475
+ api.cpSync(source, destination, options);
476
+ }
477
+ catch (cause) {
478
+ error = cause;
479
+ }
480
+ queueMicrotask(() => callback(error ?? null));
481
+ };
482
+ api.promises = promiseImpl;
483
+ const promises = promiseImpl;
219
484
  export { promises };
485
+ // Validate public directory arguments before scheduling their callbacks.
486
+ function directoryOperation(name, prepare, operation) {
487
+ api[name + "Sync"] = (path, options = {}) => operation(prepare(path, options));
488
+ api[name] = (path, options, callback) => {
489
+ if (typeof options === "function") {
490
+ callback = options;
491
+ options = {};
492
+ }
493
+ const args = prepare(path, options === undefined ? {} : options);
494
+ validateFunction(callback, "callback");
495
+ let value, error = null;
496
+ try {
497
+ value = operation(args);
498
+ }
499
+ catch (failure) {
500
+ error = failure;
501
+ }
502
+ queueMicrotask(() => callback(error, value));
503
+ };
504
+ promiseImpl[name] = async (path, options = {}) => operation(prepare(path, options));
505
+ }
506
+ directoryOperation("mkdir", (path, options) => {
507
+ if (typeof options === "number")
508
+ options = { mode: options };
509
+ validateObject(options, "options");
510
+ const { recursive = false, mode = 0o777 } = options;
511
+ validateBoolean(recursive, "options.recursive");
512
+ fileMode(mode);
513
+ return { path: pathOf(path), recursive };
514
+ }, ({ path, recursive }) => {
515
+ writablePath(path, "mkdir");
516
+ if (temporary.existsSync(path) && temporary.statSync(path).isDirectory())
517
+ return;
518
+ let created = path;
519
+ if (recursive) {
520
+ let parent = created.slice(0, created.lastIndexOf("/")) || "/";
521
+ while (!temporary.existsSync(parent)) {
522
+ created = parent;
523
+ parent = created.slice(0, created.lastIndexOf("/")) || "/";
524
+ }
525
+ }
526
+ temporary.mkdirSync(path, { recursive, mode: 0o777 });
527
+ return recursive ? created : undefined;
528
+ });
529
+ directoryOperation("mkdtemp", (path, options) => {
530
+ if (typeof options === "string" || options == null)
531
+ options = { encoding: options };
532
+ validateObject(options, "options");
533
+ const { encoding = "utf8" } = options;
534
+ if (encoding !== "buffer" && !Buffer.isEncoding(encoding))
535
+ throw new ERR_INVALID_ARG_VALUE("options.encoding", encoding);
536
+ return { path: pathOf(path) };
537
+ }, ({ path }) => {
538
+ writablePath(path, "mkdtemp");
539
+ for (;;) {
540
+ const name = path + globalThis.crypto.getRandomValues(new Uint32Array(1))[0];
541
+ try {
542
+ temporary.mkdirSync(name);
543
+ return name;
544
+ }
545
+ catch (error) {
546
+ if (error.code !== "EEXIST")
547
+ throw error;
548
+ }
549
+ }
550
+ });
551
+ for (const name of ["rm", "rmdir"])
552
+ directoryOperation(name, (path, options) => {
553
+ validateObject(options, "options");
554
+ const { recursive = false, force = false, maxRetries = 0, retryDelay = 0, } = options;
555
+ if (name === "rm")
556
+ validateBoolean(force, "options.force");
557
+ validateUint32(maxRetries, "options.maxRetries");
558
+ validateBoolean(recursive, "options.recursive");
559
+ validateUint32(retryDelay, "options.retryDelay");
560
+ return { path: pathOf(path), recursive, force };
561
+ }, ({ path, recursive, force }) => {
562
+ if (name === "rm" &&
563
+ !recursive &&
564
+ temporary.existsSync(path) &&
565
+ temporary.lstatSync(path).isDirectory())
566
+ return temporary.rmdirSync(path);
567
+ return temporary[name + "Sync"](path, { recursive, force });
568
+ });
569
+ const statFilesystem = api.statfsSync;
570
+ directoryOperation("statfs", (path, options) => {
571
+ pathOf(path);
572
+ validateObject(options, "options");
573
+ validateBoolean(options.bigint ?? false, "options.bigint");
574
+ return { path, options };
575
+ }, ({ path, options }) => statFilesystem(path, options));
576
+ api.exists = (path, callback) => {
577
+ validateFunction(callback, "callback");
578
+ let exists = false;
579
+ try {
580
+ exists = api.existsSync(path);
581
+ }
582
+ catch { }
583
+ queueMicrotask(() => callback(exists));
584
+ };
585
+ for (const name of ["link", "symlink"]) {
586
+ const prepare = (source, destination, type = null) => {
587
+ if (name === "symlink" && !["dir", "file", "junction", null].includes(type))
588
+ throw new ERR_INVALID_ARG_VALUE("type", type);
589
+ const src = pathOf(source), dest = pathOf(destination);
590
+ const raw = destination instanceof URL
591
+ ? destination.pathname
592
+ : Buffer.isBuffer(destination)
593
+ ? destination.toString()
594
+ : destination;
595
+ return { src, dest, type, trailing: raw.endsWith("/") };
596
+ };
597
+ const operation = ({ src, dest, type, trailing }) => {
598
+ if (trailing)
599
+ throw Object.assign(new Error("Invalid path"), { code: "EINVAL" });
600
+ if (name === "link") {
601
+ let stat;
602
+ try {
603
+ stat = api.statSync(src);
604
+ }
605
+ catch (error) {
606
+ if (error.code === "ENOTDIR")
607
+ error.code = "ENOENT";
608
+ throw error;
609
+ }
610
+ if (stat.isDirectory())
611
+ throw Object.assign(new Error("operation not permitted"), {
612
+ code: "EPERM",
613
+ });
614
+ }
615
+ const parent = dest.slice(0, dest.lastIndexOf("/")) || "/";
616
+ try {
617
+ const parentStat = api.statSync(parent);
618
+ if (!parentStat.isDirectory())
619
+ throw Object.assign(new Error("Invalid path"), { code: "EINVAL" });
620
+ }
621
+ catch (error) {
622
+ if (error.code === "ENOTDIR")
623
+ error.code = "EINVAL";
624
+ throw error;
625
+ }
626
+ try {
627
+ return temporary[name + "Sync"](src, dest, type ?? undefined);
628
+ }
629
+ catch (error) {
630
+ if (error.code === "ENOTDIR")
631
+ error.code = api.existsSync(parent) ? "EINVAL" : "ENOENT";
632
+ throw error;
633
+ }
634
+ };
635
+ api[name + "Sync"] = (source, destination, type) => operation(prepare(source, destination, type));
636
+ api[name] = (source, destination, type, callback) => {
637
+ if (typeof type === "function") {
638
+ callback = type;
639
+ type = null;
640
+ }
641
+ const args = prepare(source, destination, type);
642
+ validateFunction(callback, "callback");
643
+ let error = null;
644
+ try {
645
+ operation(args);
646
+ }
647
+ catch (failure) {
648
+ error = failure;
649
+ }
650
+ queueMicrotask(() => callback(error));
651
+ };
652
+ promiseImpl[name] = async (source, destination, type) => operation(prepare(source, destination, type));
653
+ }
654
+ for (const name of ["readlink", "realpath"])
655
+ directoryOperation(name, (path, options) => {
656
+ if (typeof options === "string" || options == null)
657
+ options = { encoding: options };
658
+ validateObject(options, "options");
659
+ const { encoding = "utf8" } = options;
660
+ if (encoding !== "buffer" && !Buffer.isEncoding(encoding))
661
+ throw new ERR_INVALID_ARG_VALUE("options.encoding", encoding);
662
+ return { path: pathOf(path), encoding };
663
+ }, ({ path, encoding }) => {
664
+ const stat = api.lstatSync(path);
665
+ let target = path;
666
+ if (stat.isSymbolicLink())
667
+ target = temporary.readlinkSync(path);
668
+ else if (name === "readlink")
669
+ throw Object.assign(new Error("invalid argument"), { code: "EINVAL" });
670
+ return Buffer.from(target).toString(encoding);
671
+ });
672
+ api.realpathSync.native = api.realpathSync;
673
+ api.realpath.native = api.realpath;
674
+ const unlinkFile = (path) => temporary.unlinkSync(path);
675
+ api.unlinkSync = (path) => {
676
+ path = pathOf(path);
677
+ if (api.lstatSync(path).isDirectory())
678
+ throw Object.assign(new Error("illegal operation on a directory"), {
679
+ code: "EISDIR",
680
+ });
681
+ return unlinkFile(path);
682
+ };
683
+ api.unlink = (path, callback) => {
684
+ path = pathOf(path);
685
+ validateFunction(callback, "callback");
686
+ let error = null;
687
+ try {
688
+ api.unlinkSync(path);
689
+ }
690
+ catch (failure) {
691
+ error = failure;
692
+ }
693
+ queueMicrotask(() => callback(error));
694
+ };
695
+ promiseImpl.unlink = async (path) => api.unlinkSync(path);
696
+ api.ReadStream = api.FileReadStream = fileStreams.ReadStream;
697
+ api.WriteStream = api.FileWriteStream = fileStreams.WriteStream;
698
+ api.createReadStream = fileStreams.createReadStream;
699
+ api.createWriteStream = fileStreams.createWriteStream;
700
+ api.openAsBlob = (path, options = {}) => {
701
+ const normalized = pathOf(path);
702
+ validateObject(options, "options");
703
+ const { type = "" } = options;
704
+ if (typeof type !== "string")
705
+ throw new ERR_INVALID_ARG_TYPE("options.type", "string", type);
706
+ if (api.statSync(normalized).isDirectory())
707
+ throw Object.assign(new Error("illegal operation on a directory"), {
708
+ code: "EISDIR",
709
+ });
710
+ const data = api.readFileSync(normalized);
711
+ return new Blob([data], { type });
712
+ };
713
+ api.Dir = WorkersDir;
714
+ api.Dirent = WorkersDirent;
715
+ installOperation("glob", workersGlob, false);
716
+ promiseImpl.glob = async function* (pattern, options) {
717
+ yield* workersGlob(pattern, options);
718
+ };
719
+ function directoryOptions(options, open) {
720
+ if (!open && (typeof options === "string" || options == null))
721
+ options = { encoding: options };
722
+ validateObject(options, "options");
723
+ const { encoding = "utf8", recursive = false, withFileTypes = false, bufferSize = 32, } = options;
724
+ if (encoding !== "buffer" && !Buffer.isEncoding(encoding))
725
+ throw new ERR_INVALID_ARG_VALUE("options.encoding", encoding);
726
+ validateBoolean(recursive, "options.recursive");
727
+ if (open)
728
+ validateUint32(bufferSize, "options.bufferSize");
729
+ else
730
+ validateBoolean(withFileTypes, "options.withFileTypes");
731
+ return { encoding, recursive, withFileTypes };
732
+ }
733
+ directoryOperation("readdir", (path, options) => ({
734
+ ...directoryOptions(options, false),
735
+ path: pathOf(path),
736
+ }), ({ path, encoding, recursive, withFileTypes }) => {
737
+ const entries = readDirectory(path, recursive);
738
+ return entries.map((entry) => withFileTypes
739
+ ? new WorkersDirent(encoding === "buffer" ? Buffer.from(entry.name) : entry.name, entry.type, entry.parentPath)
740
+ : encoding === "buffer"
741
+ ? Buffer.from(entry.name)
742
+ : Buffer.from(entry.name).toString(encoding));
743
+ });
744
+ directoryOperation("opendir", (path, options) => {
745
+ const opts = directoryOptions(options, true);
746
+ pathOf(path);
747
+ return { ...opts, path };
748
+ }, ({ path, encoding, recursive }) => {
749
+ return new WorkersDir(readDirectory(path, recursive), path, { encoding });
750
+ });
751
+ installIo(api, promiseImpl);
220
752
  export const { Dir, Dirent, F_OK, FileReadStream, FileWriteStream, R_OK, ReadStream, Stats, W_OK, WriteStream, X_OK, access, accessSync, appendFile, appendFileSync, chmod, chmodSync, chown, chownSync, close, closeSync, constants, copyFile, copyFileSync, cp, cpSync, createReadStream, createWriteStream, exists, existsSync, fchmod, fchmodSync, fchown, fchownSync, fdatasync, fdatasyncSync, fstat, fstatSync, fsync, fsyncSync, ftruncate, ftruncateSync, futimes, futimesSync, glob, globSync, lchmod, lchmodSync, lchown, lchownSync, link, linkSync, lstat, lstatSync, lutimes, lutimesSync, mkdir, mkdirSync, mkdtemp, mkdtempSync, open, openAsBlob, openSync, opendir, opendirSync, read, readFile, readFileSync, readSync, readdir, readdirSync, readlink, readlinkSync, readv, readvSync, realpath, realpathSync, rename, renameSync, rm, rmSync, rmdir, rmdirSync, stat, statSync, statfs, statfsSync, symlink, symlinkSync, truncate, truncateSync, unlink, unlinkSync, unwatchFile, utimes, utimesSync, watch, watchFile, write, writeFile, writeFileSync, writeSync, writev, writevSync, } = api;
221
753
  export default api;