cf-workers-native 0.1.4 → 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 (296) hide show
  1. package/README.md +2 -2
  2. package/dist/browser/documents/page-source.js +1 -1
  3. package/dist/browser/fetch/host-call.js +6 -1
  4. package/dist/browser/fetch/native-network.d.ts +1 -1
  5. package/dist/browser/fetch/relay.js +2 -0
  6. package/dist/browser/headers/index.d.ts +2 -0
  7. package/dist/browser/headers/index.js +5 -0
  8. package/dist/browser/isolated/transport.js +3 -2
  9. package/dist/browser/request/index.js +3 -2
  10. package/dist/browser/response/index.d.ts +2 -0
  11. package/dist/browser/response/index.js +11 -3
  12. package/dist/browser/structured-clone/index.d.ts +3 -0
  13. package/dist/browser/structured-clone/index.js +75 -7
  14. package/dist/browser/websocket/attachment-size.d.ts +3 -0
  15. package/dist/browser/websocket/attachment-size.js +336 -0
  16. package/dist/browser/websocket/brand.d.ts +4 -0
  17. package/dist/browser/websocket/brand.js +16 -0
  18. package/dist/browser/websocket/close-event.d.ts +7 -0
  19. package/dist/browser/websocket/close-event.js +30 -0
  20. package/dist/browser/websocket/compression.d.ts +5 -0
  21. package/dist/browser/websocket/compression.js +124 -0
  22. package/dist/browser/websocket/conversion.d.ts +2 -0
  23. package/dist/browser/websocket/conversion.js +13 -0
  24. package/dist/browser/websocket/endpoint.d.ts +39 -0
  25. package/dist/browser/websocket/endpoint.js +379 -0
  26. package/dist/browser/websocket/frames.d.ts +21 -0
  27. package/dist/browser/websocket/frames.js +121 -0
  28. package/dist/browser/websocket/native.d.ts +14 -0
  29. package/dist/browser/websocket/native.js +226 -0
  30. package/dist/cloudflare/apis/cloudflare-node/index.js +11 -23
  31. package/dist/cloudflare/workers/worker-runtime.js +2 -1
  32. package/dist/compat/console/index.d.ts +35 -0
  33. package/dist/compat/console/index.js +92 -0
  34. package/dist/compat/crypto/LICENSE-3RD-PARTY.md +39 -0
  35. package/dist/compat/crypto/LICENSE-APACHE +177 -0
  36. package/dist/compat/crypto/LICENSE.boringssl +238 -0
  37. package/dist/compat/crypto/LICENSE.emscripten +102 -0
  38. package/dist/compat/crypto/LICENSE.musl +193 -0
  39. package/dist/compat/crypto/LICENSE.ncrypto +21 -0
  40. package/dist/compat/crypto/LICENSE.openssl +177 -0
  41. package/dist/compat/crypto/asymmetric.d.ts +13 -0
  42. package/dist/compat/crypto/asymmetric.js +312 -0
  43. package/dist/compat/crypto/brorand.cjs +74 -0
  44. package/dist/compat/crypto/brorand.d.cts +6 -0
  45. package/dist/compat/crypto/certificate.d.ts +14 -0
  46. package/dist/compat/crypto/certificate.js +66 -0
  47. package/dist/compat/crypto/cipher-handle.d.ts +27 -0
  48. package/dist/compat/crypto/cipher-handle.js +239 -0
  49. package/dist/compat/crypto/cipher-info.d.ts +12 -0
  50. package/dist/compat/crypto/cipher-info.js +324 -0
  51. package/dist/compat/crypto/constants.d.ts +62 -0
  52. package/dist/compat/crypto/constants.js +68 -0
  53. package/dist/compat/crypto/dh-handle.d.ts +17 -0
  54. package/dist/compat/crypto/dh-handle.js +180 -0
  55. package/dist/compat/crypto/dh.d.ts +53 -0
  56. package/dist/compat/crypto/dh.js +138 -0
  57. package/dist/compat/crypto/digest-stream.d.ts +15 -0
  58. package/dist/compat/crypto/digest-stream.js +213 -0
  59. package/dist/compat/crypto/digests.d.ts +3 -0
  60. package/dist/compat/crypto/digests.js +32 -0
  61. package/dist/compat/crypto/ecdh.d.ts +25 -0
  62. package/dist/compat/crypto/ecdh.js +109 -0
  63. package/dist/compat/crypto/hash-handle.d.ts +23 -0
  64. package/dist/compat/crypto/hash-handle.js +70 -0
  65. package/dist/compat/crypto/hash.d.ts +37 -0
  66. package/dist/compat/crypto/hash.js +218 -0
  67. package/dist/compat/crypto/hkdf.d.ts +2 -0
  68. package/dist/compat/crypto/hkdf.js +78 -0
  69. package/dist/compat/crypto/index.cjs +2 -0
  70. package/dist/compat/crypto/index.d.cts +169 -0
  71. package/dist/compat/crypto/index.d.ts +213 -0
  72. package/dist/compat/crypto/index.js +96 -0
  73. package/dist/compat/crypto/key-errors.d.ts +10 -0
  74. package/dist/compat/crypto/key-errors.js +17 -0
  75. package/dist/compat/crypto/key-export.d.ts +8 -0
  76. package/dist/compat/crypto/key-export.js +49 -0
  77. package/dist/compat/crypto/key-formats.d.ts +7 -0
  78. package/dist/compat/crypto/key-formats.js +251 -0
  79. package/dist/compat/crypto/key-options.d.ts +1 -0
  80. package/dist/compat/crypto/key-options.js +74 -0
  81. package/dist/compat/crypto/key-state.d.ts +10 -0
  82. package/dist/compat/crypto/key-state.js +4 -0
  83. package/dist/compat/crypto/keys.d.ts +58 -0
  84. package/dist/compat/crypto/keys.js +278 -0
  85. package/dist/compat/crypto/metadata.d.ts +13 -0
  86. package/dist/compat/crypto/metadata.js +109 -0
  87. package/dist/compat/crypto/native-cipher.d.ts +17 -0
  88. package/dist/compat/crypto/native-cipher.js +192 -0
  89. package/dist/compat/crypto/native-crypto.d.ts +81 -0
  90. package/dist/compat/crypto/native-crypto.js +681 -0
  91. package/dist/compat/crypto/pbkdf2-handle.d.ts +4 -0
  92. package/dist/compat/crypto/pbkdf2-handle.js +26 -0
  93. package/dist/compat/crypto/pbkdf2.d.ts +5 -0
  94. package/dist/compat/crypto/pbkdf2.js +60 -0
  95. package/dist/compat/crypto/prime.d.ts +19 -0
  96. package/dist/compat/crypto/prime.js +146 -0
  97. package/dist/compat/crypto/random.d.ts +18 -0
  98. package/dist/compat/crypto/random.js +203 -0
  99. package/dist/compat/crypto/rsa.d.ts +21 -0
  100. package/dist/compat/crypto/rsa.js +177 -0
  101. package/dist/compat/crypto/scrypt.d.ts +25 -0
  102. package/dist/compat/crypto/scrypt.js +152 -0
  103. package/dist/compat/crypto/sign-errors.d.ts +8 -0
  104. package/dist/compat/crypto/sign-errors.js +13 -0
  105. package/dist/compat/crypto/sign-handle.d.ts +22 -0
  106. package/dist/compat/crypto/sign-handle.js +149 -0
  107. package/dist/compat/crypto/signatures.d.ts +34 -0
  108. package/dist/compat/crypto/signatures.js +252 -0
  109. package/dist/compat/crypto/subtle-digest.d.ts +1 -0
  110. package/dist/compat/crypto/subtle-digest.js +56 -0
  111. package/dist/compat/crypto/symmetric.d.ts +45 -0
  112. package/dist/compat/crypto/symmetric.js +239 -0
  113. package/dist/compat/crypto/validation.d.ts +7 -0
  114. package/dist/compat/crypto/validation.js +46 -0
  115. package/dist/compat/crypto/webcrypto.d.ts +13 -0
  116. package/dist/compat/crypto/webcrypto.js +51 -0
  117. package/dist/compat/crypto/x509.d.ts +30 -0
  118. package/dist/compat/crypto/x509.js +407 -0
  119. package/dist/compat/events/errors.d.ts +8 -0
  120. package/dist/compat/events/errors.js +39 -0
  121. package/dist/compat/events/index.cjs +2 -0
  122. package/dist/compat/events/index.d.cts +2 -0
  123. package/dist/compat/events/index.d.ts +64 -0
  124. package/dist/compat/events/index.js +792 -0
  125. package/dist/compat/events/intrinsics.d.ts +1 -0
  126. package/dist/compat/events/intrinsics.js +2 -0
  127. package/dist/compat/fs/LICENSE-3RD-PARTY.md +11 -0
  128. package/dist/compat/fs/LICENSE-APACHE +177 -0
  129. package/dist/compat/fs/directory-backend.d.ts +6 -0
  130. package/dist/compat/fs/directory-backend.js +51 -0
  131. package/dist/compat/fs/directory.d.ts +37 -0
  132. package/dist/compat/fs/directory.js +137 -0
  133. package/dist/compat/fs/embedded.d.ts +85 -0
  134. package/dist/compat/fs/embedded.js +260 -0
  135. package/dist/compat/fs/file-handle.d.ts +75 -0
  136. package/dist/compat/fs/file-handle.js +226 -0
  137. package/dist/compat/fs/glob-internal.d.ts +15 -0
  138. package/dist/compat/fs/glob-internal.js +417 -0
  139. package/dist/compat/fs/glob.d.ts +10 -0
  140. package/dist/compat/fs/glob.js +71 -0
  141. package/dist/compat/fs/index.d.ts +8 -82
  142. package/dist/compat/fs/index.js +736 -238
  143. package/dist/compat/fs/io-validation.d.ts +14 -0
  144. package/dist/compat/fs/io-validation.js +130 -0
  145. package/dist/compat/fs/io.d.ts +1 -0
  146. package/dist/compat/fs/io.js +282 -0
  147. package/dist/compat/fs/mode.d.ts +1 -0
  148. package/dist/compat/fs/mode.js +13 -0
  149. package/dist/compat/fs/promises/index.d.ts +3 -1
  150. package/dist/compat/fs/promises/index.js +1 -1
  151. package/dist/compat/fs/public-types.d.ts +120 -0
  152. package/dist/compat/fs/public-types.js +1 -0
  153. package/dist/compat/fs/stream-errors.d.ts +6 -0
  154. package/dist/compat/fs/stream-errors.js +8 -0
  155. package/dist/compat/fs/stream-utils.d.ts +16 -0
  156. package/dist/compat/fs/stream-utils.js +29 -0
  157. package/dist/compat/fs/streams.d.ts +104 -0
  158. package/dist/compat/fs/streams.js +794 -0
  159. package/dist/compat/fs/writable.d.ts +14 -0
  160. package/dist/compat/fs/writable.js +532 -0
  161. package/dist/compat/http/index.d.ts +11 -28
  162. package/dist/compat/http/index.js +81 -125
  163. package/dist/compat/http/server-options.d.ts +1 -0
  164. package/dist/compat/http/server-options.js +87 -0
  165. package/dist/compat/http/symbols.d.ts +5 -0
  166. package/dist/compat/http/symbols.js +9 -0
  167. package/dist/compat/http/unique-headers.d.ts +1 -0
  168. package/dist/compat/http/unique-headers.js +21 -0
  169. package/dist/compat/http-common/index.d.ts +37 -0
  170. package/dist/compat/http-common/index.js +43 -0
  171. package/dist/compat/http-outgoing/index.d.ts +14 -0
  172. package/dist/compat/http-outgoing/index.js +17 -0
  173. package/dist/compat/http-server/index.d.ts +18 -0
  174. package/dist/compat/http-server/index.js +26 -0
  175. package/dist/compat/https/index.d.ts +4 -2
  176. package/dist/compat/module/builtins.d.ts +1 -0
  177. package/dist/compat/module/builtins.js +101 -0
  178. package/dist/compat/module/index.d.ts +4 -2
  179. package/dist/compat/module/index.js +22 -17
  180. package/dist/compat/module/metadata.d.ts +44 -0
  181. package/dist/compat/module/metadata.js +127 -0
  182. package/dist/compat/net/internal-net.js +4 -0
  183. package/dist/compat/net/sockets.d.ts +5 -0
  184. package/dist/compat/net/sockets.js +153 -14
  185. package/dist/compat/net/validators.d.ts +1 -0
  186. package/dist/compat/net/validators.js +8 -0
  187. package/dist/compat/process/configuration.d.ts +113 -0
  188. package/dist/compat/process/configuration.js +115 -0
  189. package/dist/compat/process/directory.d.ts +4 -0
  190. package/dist/compat/process/directory.js +28 -0
  191. package/dist/compat/process/files.d.ts +3 -0
  192. package/dist/compat/process/files.js +10 -0
  193. package/dist/compat/process/index.cjs +2 -0
  194. package/dist/compat/process/index.d.cts +4 -0
  195. package/dist/compat/process/index.d.ts +20 -0
  196. package/dist/compat/process/index.js +113 -0
  197. package/dist/compat/process/metadata.d.ts +135 -0
  198. package/dist/compat/process/metadata.js +251 -0
  199. package/dist/compat/process/scheduling.d.ts +2 -0
  200. package/dist/compat/process/scheduling.js +60 -0
  201. package/dist/compat/process/state.d.ts +4 -0
  202. package/dist/compat/process/state.js +5 -0
  203. package/dist/compat/process/stdio.d.ts +18 -0
  204. package/dist/compat/process/stdio.js +66 -0
  205. package/dist/compat/stream/destroy.d.ts +1 -0
  206. package/dist/compat/stream/destroy.js +21 -1
  207. package/dist/compat/stream/readable.js +10 -2
  208. package/dist/compat/stream-web/LICENSE +22 -0
  209. package/dist/compat/stream-web/ponyfill.d.ts +1 -1
  210. package/dist/compat/stream-web/ponyfill.js +2369 -1775
  211. package/dist/compat/stream-web/runtime.d.ts +1 -1
  212. package/dist/compat/stream-web/runtime.js +3 -2
  213. package/dist/compat/stream-wrap/LICENSE-3RD-PARTY.md +11 -0
  214. package/dist/compat/stream-wrap/LICENSE-APACHE +177 -0
  215. package/dist/compat/stream-wrap/index.d.ts +1 -0
  216. package/dist/compat/stream-wrap/index.js +1 -0
  217. package/dist/compat/tls/LICENSE-3RD-PARTY.md +11 -0
  218. package/dist/compat/tls/LICENSE-APACHE +177 -0
  219. package/dist/compat/tls/constants.d.ts +7 -0
  220. package/dist/compat/tls/constants.js +14 -0
  221. package/dist/compat/tls/errors.d.ts +35 -0
  222. package/dist/compat/tls/errors.js +68 -0
  223. package/dist/compat/tls/helpers.d.ts +9 -0
  224. package/dist/compat/tls/helpers.js +207 -0
  225. package/dist/compat/tls/index.d.ts +26 -0
  226. package/dist/compat/tls/index.js +50 -0
  227. package/dist/compat/tls/jsstream.d.ts +19 -0
  228. package/dist/compat/tls/jsstream.js +196 -0
  229. package/dist/compat/tls/native-session.d.ts +3 -0
  230. package/dist/compat/tls/native-session.js +187 -0
  231. package/dist/compat/tls/wrap.d.ts +65 -0
  232. package/dist/compat/tls/wrap.js +541 -0
  233. package/dist/compat/tls-wrap/LICENSE-3RD-PARTY.md +11 -0
  234. package/dist/compat/tls-wrap/LICENSE-APACHE +177 -0
  235. package/dist/compat/tls-wrap/index.d.ts +7 -0
  236. package/dist/compat/tls-wrap/index.js +3 -0
  237. package/dist/compat/util/index.js +43 -1
  238. package/dist/compat/util/inspect.js +5 -1
  239. package/dist/compat/util/types/index.d.ts +3 -0
  240. package/dist/compat/util/types/index.js +5 -0
  241. package/dist/compat/zlib/LICENSE-3RD-PARTY.md +11 -0
  242. package/dist/compat/zlib/LICENSE-APACHE +177 -0
  243. package/dist/compat/zlib/LICENSE.brotli +19 -0
  244. package/dist/compat/zlib/LICENSE.emscripten +102 -0
  245. package/dist/compat/zlib/LICENSE.musl +193 -0
  246. package/dist/compat/zlib/LICENSE.zlib +22 -0
  247. package/dist/compat/zlib/LICENSE.zstd +30 -0
  248. package/dist/compat/zlib/classic-base.cjs +600 -0
  249. package/dist/compat/zlib/classic-base.d.cts +39 -0
  250. package/dist/compat/zlib/classic-binding.d.ts +28 -0
  251. package/dist/compat/zlib/classic-binding.js +105 -0
  252. package/dist/compat/zlib/classic.d.ts +44 -0
  253. package/dist/compat/zlib/classic.js +199 -0
  254. package/dist/compat/zlib/codec-binding.d.ts +33 -0
  255. package/dist/compat/zlib/codec-binding.js +141 -0
  256. package/dist/compat/zlib/compression.d.ts +26 -0
  257. package/dist/compat/zlib/compression.js +170 -0
  258. package/dist/compat/zlib/constants.d.ts +172 -0
  259. package/dist/compat/zlib/constants.js +173 -0
  260. package/dist/compat/zlib/errors.d.ts +21 -0
  261. package/dist/compat/zlib/errors.js +32 -0
  262. package/dist/compat/zlib/index.d.ts +544 -0
  263. package/dist/compat/zlib/index.js +194 -0
  264. package/dist/compat/zlib/input.d.ts +16 -0
  265. package/dist/compat/zlib/input.js +132 -0
  266. package/dist/compat/zlib/native-codecs.d.ts +24 -0
  267. package/dist/compat/zlib/native-codecs.js +180 -0
  268. package/dist/compat/zlib/native-zlib.d.ts +5 -0
  269. package/dist/compat/zlib/native-zlib.js +52 -0
  270. package/dist/compat/zlib/public-types.d.ts +48 -0
  271. package/dist/compat/zlib/public-types.js +1 -0
  272. package/dist/compat/zlib/validators.d.ts +3 -0
  273. package/dist/compat/zlib/validators.js +18 -0
  274. package/dist/shared/buffer-source.d.ts +5 -0
  275. package/dist/shared/buffer-source.js +70 -0
  276. package/dist/shared/globals/inject.d.ts +2 -1
  277. package/dist/shared/globals/inject.js +2 -1
  278. package/dist/shared/globals/platform.d.ts +8 -0
  279. package/dist/shared/globals/platform.js +1 -0
  280. package/dist/shared/globals/runtime.d.ts +1 -2
  281. package/dist/shared/globals/runtime.js +1 -2
  282. package/dist/shared/globals/web.js +5 -0
  283. package/dist/shared/request-context.d.ts +2 -0
  284. package/dist/shared/request-context.js +11 -0
  285. package/dist/shared/request-scope.d.ts +4 -0
  286. package/dist/shared/request-scope.js +14 -0
  287. package/dist/tooling/async.js +36 -14
  288. package/dist/tooling/shared.d.ts +1 -0
  289. package/dist/tooling/shared.js +26 -1
  290. package/dist/tooling/vite.js +8 -3
  291. package/native/android/src/main/java/jp/rdlabo/workerscapacitor/WorkerSockets.java +92 -13
  292. package/native/android/src/main/java/jp/rdlabo/workerscapacitor/WorkersCapacitorPlugin.java +4 -2
  293. package/native/ios/NetworkBridge.swift +11 -1
  294. package/native/ios/SocketBridge.swift +37 -2
  295. package/native/ios/WorkersCapacitorPlugin.swift +4 -0
  296. package/package.json +4 -2
@@ -1,255 +1,753 @@
1
- // Read-only in-memory filesystem for bundled worker assets. Build
2
- // integrations register file contents at startup; bundled server code such
3
- // as OpenNext's traced manifests then reads them through the node:fs
4
- // surface. Mutating calls and real device filesystem access are not
5
- // provided.
6
- const encoder = new TextEncoder();
7
- const files = new Map();
8
- function normalize(path) {
9
- if (typeof path !== "string")
10
- throw new TypeError("path must be a string");
11
- const raw = path.startsWith("file://") ? new URL(path).pathname : path;
12
- const parts = [];
13
- for (const segment of raw.split("/")) {
14
- if (segment === "" || segment === ".")
15
- continue;
16
- if (segment === "..")
17
- parts.pop();
18
- else
19
- parts.push(segment);
20
- }
21
- return "/" + parts.join("/");
22
- }
23
- /** Called by generated bundle code; consumers do not invoke this directly. */
24
- export function registerVirtualFiles(entries) {
25
- for (const [path, contents] of Object.entries(entries)) {
26
- const key = normalize(path);
27
- files.set(key, typeof contents === "string"
28
- ? encoder.encode(contents)
29
- : contents instanceof Uint8Array
30
- ? contents
31
- : Uint8Array.from(atob(contents.base64), (c) => c.charCodeAt(0)));
32
- }
33
- }
34
- /** Test/reset helper. */
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";
7
+ import { fileMode } from "./mode.js";
8
+ import { validateInteger } from "../crypto/validation.js";
9
+ import * as embedded from "./embedded.js";
10
+ import { temporary, retainTemporaryFiles, temporaryPath, clearTemporaryFiles, writablePath, pathOf, readonlyFile, embeddedStat, } from "./writable.js";
11
+ import { Buffer } from "node:buffer";
12
+ import { validateFunction, validateObject, validateBoolean, validateUint32, } from "../net/validators.js";
13
+ import { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE } from "../net/errors.js";
14
+ export const registerVirtualFiles = embedded.registerVirtualFiles;
35
15
  export function clearVirtualFiles() {
36
- files.clear();
37
- }
38
- function fileEntry(path) {
39
- const direct = files.get(path);
40
- if (direct !== undefined)
41
- return direct;
42
- // Bundled runtimes resolve relative to an empty dirname; treat relative
43
- // and absolute lookups uniformly, then fall back to a suffix match so a
44
- // build-absolute path resolves against a registered relative one.
45
- for (const [key, contents] of files)
46
- if (key === path || key.endsWith(path) || path.endsWith(key))
47
- return contents;
48
- return undefined;
49
- }
50
- function dirEntries(path) {
51
- const prefix = path.endsWith("/") ? path : path + "/";
52
- const names = new Set();
53
- for (const key of files.keys()) {
54
- if (!key.startsWith(prefix))
55
- continue;
56
- const rest = key.slice(prefix.length);
57
- names.add(rest.split("/")[0]);
58
- }
59
- return [...names].sort();
60
- }
61
- function exists(path) {
62
- return fileEntry(path) !== undefined || dirEntries(path).length > 0;
63
- }
64
- function enoent(syscall, path) {
65
- const error = new Error(`ENOENT: no such file or directory, ${syscall} '${path}'`);
66
- error.code = "ENOENT";
67
- error.errno = -2;
68
- error.syscall = syscall;
69
- error.path = path;
70
- return error;
71
- }
72
- export class Stats {
73
- #size;
74
- #directory;
75
- #mtime;
76
- constructor(size, directory, mtime) {
77
- this.#size = size;
78
- this.#directory = directory;
79
- this.#mtime = mtime;
80
- }
81
- isFile() {
82
- return !this.#directory;
83
- }
84
- isDirectory() {
85
- return this.#directory;
86
- }
87
- isSymbolicLink() {
88
- return false;
89
- }
90
- isBlockDevice() {
91
- return false;
92
- }
93
- isCharacterDevice() {
94
- return false;
95
- }
96
- isFIFO() {
97
- return false;
98
- }
99
- isSocket() {
100
- return false;
101
- }
102
- get size() {
103
- return this.#size;
104
- }
105
- get mtime() {
106
- return this.#mtime;
107
- }
108
- get mtimeMs() {
109
- return this.#mtime.getTime();
110
- }
111
- get birthtime() {
112
- return this.#mtime;
113
- }
114
- get birthtimeMs() {
115
- return this.#mtime.getTime();
116
- }
117
- get ctime() {
118
- return this.#mtime;
16
+ embedded.clearVirtualFiles();
17
+ clearTemporaryFiles();
18
+ }
19
+ const reads = new Set([
20
+ "readFileSync",
21
+ "readFile",
22
+ "readdirSync",
23
+ "readdir",
24
+ "statSync",
25
+ "stat",
26
+ "lstatSync",
27
+ "realpathSync",
28
+ "existsSync",
29
+ ]);
30
+ const api = { ...temporary };
31
+ for (const name of Object.keys(api))
32
+ if (typeof api[name] === "function" && /^[a-z]/.test(name))
33
+ api[name] = (...args) => temporary[name](...args);
34
+ for (const name of [
35
+ "ReadStream",
36
+ "WriteStream",
37
+ "FileReadStream",
38
+ "FileWriteStream",
39
+ ]) {
40
+ api[name] = new Proxy(api[name], {
41
+ construct(_target, args) {
42
+ if (name === "ReadStream" || name === "FileReadStream")
43
+ return temporary.createReadStream(...args);
44
+ args[0] = writablePath(args[0], name);
45
+ return temporary.createWriteStream(...args);
46
+ },
47
+ });
48
+ }
49
+ for (const name of reads) {
50
+ const old = embedded[name];
51
+ api[name] = (...args) => temporaryPath(args[0]) ? temporary[name](...args) : old(...args);
52
+ }
53
+ for (const name of ["watch", "watchFile", "unwatchFile"])
54
+ api[name] = () => {
55
+ throw Object.assign(new Error("The operation is not supported"), {
56
+ code: "ERR_UNSUPPORTED_OPERATION",
57
+ });
58
+ };
59
+ // Workers reports the byte count from these synchronous operations.
60
+ for (const name of ["writeFileSync", "appendFileSync"])
61
+ api[name] = (...args) => {
62
+ temporary[name](...args);
63
+ const encoding = typeof args[2] === "string" ? args[2] : args[2]?.encoding;
64
+ return typeof args[1] === "string"
65
+ ? Buffer.byteLength(args[1], encoding)
66
+ : args[1].byteLength;
67
+ };
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);
72
+ for (const name of [
73
+ "readFile",
74
+ "readdir",
75
+ "stat",
76
+ "lstat",
77
+ "realpath",
78
+ "access",
79
+ ]) {
80
+ const old = embedded.promises[name];
81
+ promiseImpl[name] = async (...args) => temporaryPath(args[0]) ? temporary.promises[name](...args) : old(...args);
82
+ }
83
+ // Keep all writes inside the memory volume, including FileHandle operations.
84
+ for (const name of [
85
+ "appendFile",
86
+ "writeFile",
87
+ "mkdir",
88
+ "mkdtemp",
89
+ "rm",
90
+ "rmdir",
91
+ "unlink",
92
+ "truncate",
93
+ "utimes",
94
+ "lutimes",
95
+ "chmod",
96
+ "chown",
97
+ "lchmod",
98
+ "lchown",
99
+ "rename",
100
+ "copyFile",
101
+ "symlink",
102
+ ]) {
103
+ promiseImpl[name] = async (...args) => {
104
+ if (name === "symlink") {
105
+ return new Promise((resolve, reject) => temporary.symlink(...args, (error) => error ? reject(error) : resolve(undefined)));
106
+ }
107
+ const indexes = ["rename", "copyFile", "cp", "link"].includes(name)
108
+ ? [0, 1]
109
+ : [0];
110
+ for (const i of indexes)
111
+ if (typeof args[i] !== "object" ||
112
+ args[i] instanceof URL ||
113
+ Buffer.isBuffer(args[i])) {
114
+ if (!temporaryPath(args[i]))
115
+ throw Object.assign(new Error("operation not permitted"), {
116
+ code: "EPERM",
117
+ });
118
+ }
119
+ return temporary.promises[name](...args);
120
+ };
121
+ }
122
+ promiseImpl.watch = function () {
123
+ throw new Error("Not implemented");
124
+ };
125
+ // Workers validates ownership/permission requests but has no mutable Unix
126
+ // ownership or permissions. These operations must not change the memory VFS.
127
+ function installOperation(name, handler, promise = true) {
128
+ api[name + "Sync"] = handler;
129
+ api[name] = (...args) => {
130
+ const callback = args.pop();
131
+ validateFunction(callback, "callback");
132
+ Promise.resolve()
133
+ .then(() => handler(...args))
134
+ .then((value) => callback(null, value), (error) => callback(error));
135
+ };
136
+ if (promise)
137
+ promiseImpl[name] = async (...args) => handler(...args);
138
+ }
139
+ function temporaryStats(stat, readonly = false) {
140
+ if (stat == null)
141
+ return stat;
142
+ const bigint = typeof stat.mode === "bigint";
143
+ const mode = (Number(stat.mode) & ~0o777) |
144
+ (readonly || stat.isSymbolicLink() ? 0o444 : 0o666);
145
+ stat.mode = bigint ? BigInt(mode) : mode;
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;
119
167
  }
120
- get ctimeMs() {
121
- return this.#mtime.getTime();
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
+ }
175
+ return stat;
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;
122
199
  }
123
- get atime() {
124
- return this.#mtime;
200
+ const args = accessArgs(path, mode);
201
+ validateFunction(callback, "callback");
202
+ let failure = null;
203
+ try {
204
+ checkAccess(args);
125
205
  }
126
- get atimeMs() {
127
- return this.#mtime.getTime();
206
+ catch (error) {
207
+ failure = error;
128
208
  }
129
- get mode() {
130
- return this.#directory ? 0o40755 : 0o100644;
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
+ }
218
+ for (const name of ["stat", "lstat"])
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);
230
+ for (const name of ["chmod", "lchmod", "fchmod", "chown", "lchown", "fchown"]) {
231
+ const count = name.endsWith("chmod") ? 2 : 3;
232
+ const prepare = (args) => {
233
+ const [path, value, gid] = args;
234
+ if (name.endsWith("chmod"))
235
+ fileMode(value);
236
+ else {
237
+ validateInteger(value, "uid", -1, 0xffffffff);
238
+ validateInteger(gid, "gid", -1, 0xffffffff);
239
+ }
240
+ if (typeof path === "number" || name.startsWith("f"))
241
+ validateInteger(path, "fd", 0, 2147483647);
242
+ else
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));
274
+ }
275
+ installOperation("statfs", (path, options = {}) => {
276
+ pathOf(path);
277
+ validateObject(options, "options");
278
+ const bigint = options.bigint ?? false;
279
+ validateBoolean(bigint, "options.bigint");
280
+ const value = bigint ? 0n : 0;
281
+ return {
282
+ type: value,
283
+ bsize: value,
284
+ blocks: value,
285
+ bfree: value,
286
+ bavail: value,
287
+ files: value,
288
+ ffree: value,
289
+ };
290
+ });
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 });
325
+ };
326
+ // Copy an embedded bundle file into request-local /tmp without granting any
327
+ // write access to its source volume.
328
+ const temporaryCopyFile = api.copyFileSync;
329
+ installOperation("copyFile", (source, destination, mode = 0) => {
330
+ if (![0, 1, 2, 4].includes(mode))
331
+ throw Object.assign(new TypeError("Invalid copy mode"), {
332
+ code: "ERR_INVALID_ARG_VALUE",
333
+ });
334
+ if (mode === 4)
335
+ throw Object.assign(new Error("The operation is not supported"), {
336
+ code: "ERR_UNSUPPORTED_OPERATION",
337
+ });
338
+ if (temporaryPath(source))
339
+ return temporaryCopyFile(source, destination, mode);
340
+ writablePath(destination, "copyFile");
341
+ if (mode === 1 && api.existsSync(destination))
342
+ throw Object.assign(new Error("File already exists"), { code: "EEXIST" });
343
+ temporary.writeFileSync(destination, embedded.readFileSync(pathOf(source)));
344
+ });
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
+ });
131
433
  }
132
- get dev() {
133
- return 0;
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 = {};
134
448
  }
135
- get ino() {
136
- return 0;
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);
137
476
  }
138
- get nlink() {
139
- return 1;
477
+ catch (cause) {
478
+ error = cause;
140
479
  }
141
- get uid() {
142
- return 0;
480
+ queueMicrotask(() => callback(error ?? null));
481
+ };
482
+ api.promises = promiseImpl;
483
+ const promises = promiseImpl;
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
+ }
143
525
  }
144
- get gid() {
145
- return 0;
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
+ }
146
549
  }
147
- get rdev() {
148
- return 0;
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);
149
581
  }
150
- get blksize() {
151
- return 4096;
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);
152
689
  }
153
- get blocks() {
154
- return Math.ceil(this.#size / 512);
690
+ catch (failure) {
691
+ error = failure;
155
692
  }
156
- }
157
- function statFor(path, syscall) {
158
- const data = fileEntry(path);
159
- if (data !== undefined)
160
- return new Stats(data.length, false, new Date(0));
161
- if (dirEntries(path).length > 0 || path === "/")
162
- return new Stats(0, true, new Date(0));
163
- throw enoent(syscall, path);
164
- }
165
- function toPath(input) {
166
- if (input instanceof URL)
167
- return normalize(input.href);
168
- if (typeof input !== "string" && !(input instanceof String))
169
- throw new TypeError("path must be a string or URL");
170
- return normalize(String(input));
171
- }
172
- function decode(data, encoding) {
173
- if (encoding === "utf8" || encoding === "utf-8" || encoding == null)
174
- return new TextDecoder().decode(data);
175
- throw new Error(`Unsupported encoding '${encoding}'`);
176
- }
177
- export function readFileSync(path, options) {
178
- const p = toPath(path);
179
- const data = fileEntry(p);
180
- if (data === undefined)
181
- throw enoent("open", p);
182
- const encoding = typeof options === "string"
183
- ? options
184
- : options?.encoding;
185
- return encoding ? decode(data, encoding) : data;
186
- }
187
- export function readFile(path, options, callback) {
188
- const cb = (typeof options === "function" ? options : callback);
189
- const promise = Promise.resolve().then(() => readFileSync(path, options));
190
- if (cb)
191
- promise.then((data) => cb(null, data), (error) => cb(error));
192
- }
193
- export function readdirSync(path) {
194
- const p = toPath(path);
195
- const entries = dirEntries(p);
196
- if (entries.length === 0 && fileEntry(p) === undefined && p !== "/")
197
- throw enoent("scandir", p);
198
- return entries;
199
- }
200
- export function readdir(path, callback) {
201
- Promise.resolve()
202
- .then(() => readdirSync(path))
203
- .then((entries) => callback(null, entries), (error) => callback(error));
204
- }
205
- export function existsSync(path) {
206
- return exists(toPath(path));
207
- }
208
- export function statSync(path) {
209
- return statFor(toPath(path), "stat");
210
- }
211
- export function lstatSync(path) {
212
- return statSync(path);
213
- }
214
- export function stat(path, callback) {
215
- Promise.resolve()
216
- .then(() => statSync(path))
217
- .then((stats) => callback(null, stats), (error) => callback(error));
218
- }
219
- export function realpathSync(path) {
220
- const p = toPath(path);
221
- if (!exists(p))
222
- throw enoent("realpath", p);
223
- return p;
224
- }
225
- export const promises = {
226
- readFile: (path, options) => Promise.resolve().then(() => readFileSync(path, options)),
227
- readdir: (path) => Promise.resolve().then(() => readdirSync(path)),
228
- stat: (path) => Promise.resolve().then(() => statSync(path)),
229
- lstat: (path) => Promise.resolve().then(() => lstatSync(path)),
230
- realpath: (path) => Promise.resolve().then(() => realpathSync(path)),
231
- access: (path) => Promise.resolve().then(() => {
232
- if (!exists(toPath(path)))
233
- throw enoent("access", toPath(path));
234
- }),
693
+ queueMicrotask(() => callback(error));
235
694
  };
236
- export const constants = {
237
- F_OK: 0,
238
- R_OK: 4,
239
- W_OK: 2,
240
- X_OK: 1,
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 });
241
712
  };
242
- export default {
243
- readFileSync,
244
- readFile,
245
- readdirSync,
246
- readdir,
247
- existsSync,
248
- statSync,
249
- lstatSync,
250
- stat,
251
- realpathSync,
252
- promises,
253
- constants,
254
- Stats,
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);
255
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);
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;
753
+ export default api;