cf-workers-native 0.1.5 → 0.1.7

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 +129 -59
  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 +182 -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 +249 -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 +596 -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 +283 -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
@@ -0,0 +1,249 @@
1
+ // FileHandle's public contract follows workerd 5358e3d337336eaf696a48bc1563d808b10feba5.
2
+ // The filesystem backend and its request scope remain private.
3
+ import { Buffer } from "node:buffer";
4
+ import { EventEmitter } from "node:events";
5
+ import { ReadableStream } from "../stream-web/runtime.js";
6
+ import { asyncDispose, installResourceSymbols, } from "../../shared/globals/symbols.js";
7
+ import { validateObject, validateBoolean, validateUint32, } from "../net/validators.js";
8
+ import { validatePosition } from "./io-validation.js";
9
+ import { createReadStream, createWriteStream } from "./streams.js";
10
+ import { registerFileHandle } from "./stream-utils.js";
11
+ installResourceSymbols(globalThis.Symbol);
12
+ const badge = Symbol("FileHandle constructor");
13
+ const kFileHandle = Symbol("kFileHandle");
14
+ const handleScopes = new WeakMap();
15
+ const released = new FinalizationRegistry((close) => close());
16
+ function badDescriptor() {
17
+ return Object.assign(new Error("Bad file descriptor"), {
18
+ code: "EBADF",
19
+ syscall: "stat",
20
+ });
21
+ }
22
+ export class FileHandle extends EventEmitter {
23
+ #fd;
24
+ #backend;
25
+ [kFileHandle] = true;
26
+ constructor(token, backend) {
27
+ if (token !== badge)
28
+ throw new TypeError("Illegal constructor");
29
+ super();
30
+ this.#fd = backend.fd;
31
+ this.#backend = backend;
32
+ released.register(this, () => backend.run(() => backend.api.closeSync(backend.fd)), this);
33
+ registerFileHandle(this);
34
+ handleScopes.set(this, backend.run);
35
+ }
36
+ get fd() {
37
+ return this.#fd;
38
+ }
39
+ #invoke(name, ...args) {
40
+ if (this.#fd === undefined)
41
+ throw badDescriptor();
42
+ const fd = this.#fd;
43
+ const backend = this.#backend;
44
+ return backend.run(() => backend.api[name](fd, ...args));
45
+ }
46
+ async appendFile(data, options = {}) {
47
+ await this.#invoke("appendFileSync", data, options);
48
+ }
49
+ async chmod(mode) {
50
+ await this.#invoke("fchmodSync", mode);
51
+ }
52
+ async chown(uid, gid) {
53
+ await this.#invoke("fchownSync", uid, gid);
54
+ }
55
+ async datasync() {
56
+ await this.#invoke("fdatasyncSync");
57
+ }
58
+ async sync() {
59
+ await this.#invoke("fsyncSync");
60
+ }
61
+ read(bufferOrOptions = {}, offsetOrOptions = {}, length, position = null) {
62
+ try {
63
+ if (this.#fd === undefined)
64
+ throw badDescriptor();
65
+ let options;
66
+ if (ArrayBuffer.isView(bufferOrOptions))
67
+ options =
68
+ typeof offsetOrOptions === "number"
69
+ ? {
70
+ buffer: bufferOrOptions,
71
+ offset: offsetOrOptions,
72
+ length: length ?? bufferOrOptions.byteLength - offsetOrOptions,
73
+ position: position ?? null,
74
+ }
75
+ : { buffer: bufferOrOptions, ...offsetOrOptions };
76
+ else
77
+ options = bufferOrOptions;
78
+ const { buffer = Buffer.alloc(16384), offset = 0, length: count = buffer.byteLength - offset, position: at = null, } = options;
79
+ validateUint32(offset, "offset");
80
+ validateUint32(count, "length");
81
+ validatePosition(at, "position");
82
+ const bytesRead = this.#invoke("readSync", buffer, offset, count, at);
83
+ return Promise.resolve({ bytesRead, buffer });
84
+ }
85
+ catch (error) {
86
+ return Promise.reject(error);
87
+ }
88
+ }
89
+ readv(buffers, position = null) {
90
+ try {
91
+ return Promise.resolve({
92
+ bytesRead: this.#invoke("readvSync", buffers, position),
93
+ buffers,
94
+ });
95
+ }
96
+ catch (error) {
97
+ return Promise.reject(error);
98
+ }
99
+ }
100
+ async readFile(options = {}) {
101
+ return await this.#invoke("readFileSync", options);
102
+ }
103
+ readLines(_options = {}) {
104
+ if (this.#fd === undefined)
105
+ throw badDescriptor();
106
+ throw new Error("not implemented");
107
+ }
108
+ async stat(options = {}) {
109
+ return await this.#invoke("fstatSync", options);
110
+ }
111
+ async truncate(length = 0) {
112
+ await this.#invoke("ftruncateSync", length);
113
+ }
114
+ async utimes(atime, mtime) {
115
+ await this.#invoke("futimesSync", atime, mtime);
116
+ }
117
+ write(buffer, offsetPositionOrOptions = null, lengthOrEncoding, position = null) {
118
+ try {
119
+ if (this.#fd === undefined)
120
+ throw badDescriptor();
121
+ if (typeof buffer === "string")
122
+ buffer = Buffer.from(buffer, lengthOrEncoding);
123
+ const bytesWritten = this.#invoke("writeSync", buffer, offsetPositionOrOptions, lengthOrEncoding, position);
124
+ return Promise.resolve({ bytesWritten, buffer });
125
+ }
126
+ catch (error) {
127
+ return Promise.reject(error);
128
+ }
129
+ }
130
+ writev(buffers, position = null) {
131
+ try {
132
+ return Promise.resolve({
133
+ bytesWritten: this.#invoke("writevSync", buffers, position),
134
+ buffers,
135
+ });
136
+ }
137
+ catch (error) {
138
+ return Promise.reject(error);
139
+ }
140
+ }
141
+ writeFile(data, options = {}) {
142
+ try {
143
+ const bytesWritten = this.#invoke("writeFileSync", data, options);
144
+ return Promise.resolve({
145
+ bytesWritten,
146
+ buffer: ArrayBuffer.isView(data) ? data : Buffer.from(data, options),
147
+ });
148
+ }
149
+ catch (error) {
150
+ return Promise.reject(error);
151
+ }
152
+ }
153
+ close() {
154
+ try {
155
+ if (this.#fd !== undefined)
156
+ this.#invoke("closeSync");
157
+ this.#fd = undefined;
158
+ this.#backend = undefined;
159
+ handleScopes.delete(this);
160
+ released.unregister(this);
161
+ this.emit("close");
162
+ return Promise.resolve();
163
+ }
164
+ catch (error) {
165
+ return Promise.reject(error);
166
+ }
167
+ }
168
+ async [asyncDispose]() {
169
+ await this.close();
170
+ }
171
+ readableWebStream(options = {}) {
172
+ if (this.#fd === undefined)
173
+ throw badDescriptor();
174
+ validateObject(options, "options");
175
+ const { autoClose = true } = options;
176
+ validateBoolean(autoClose, "options.autoClose");
177
+ const handle = this;
178
+ const read = this.read.bind(this);
179
+ let controller, ended = false, failed = false, closingAtEof = false;
180
+ const finish = () => {
181
+ if (failed)
182
+ throw new TypeError("This ReadableStream is closed.");
183
+ if (ended && !closingAtEof)
184
+ throw new TypeError("This ReadableStream is closed.");
185
+ if (!ended) {
186
+ ended = true;
187
+ const request = controller.byobRequest;
188
+ controller.close();
189
+ request?.respond(0);
190
+ }
191
+ };
192
+ const stream = new ReadableStream({
193
+ type: "bytes",
194
+ autoAllocateChunkSize: 16384,
195
+ start(c) {
196
+ controller = c;
197
+ },
198
+ async pull(c) {
199
+ const request = c.byobRequest, view = request.view;
200
+ let bytesRead;
201
+ try {
202
+ ({ bytesRead } = await read(view, view.byteOffset, view.byteLength));
203
+ }
204
+ catch (error) {
205
+ failed = true;
206
+ throw error;
207
+ }
208
+ if (ended)
209
+ return;
210
+ if (bytesRead === 0) {
211
+ finish();
212
+ if (autoClose) {
213
+ closingAtEof = true;
214
+ try {
215
+ await handle.close();
216
+ }
217
+ finally {
218
+ closingAtEof = false;
219
+ }
220
+ }
221
+ }
222
+ if (!ended)
223
+ request.respond(bytesRead);
224
+ },
225
+ async cancel() {
226
+ ended = true;
227
+ if (autoClose)
228
+ await handle.close();
229
+ },
230
+ });
231
+ this.once("close", finish);
232
+ return stream;
233
+ }
234
+ createReadStream(options = {}) {
235
+ const run = handleScopes.get(this) ?? ((fn) => fn());
236
+ return run(() => createReadStream("", { ...options, fd: this }));
237
+ }
238
+ createWriteStream(options = {}) {
239
+ const run = handleScopes.get(this) ?? ((fn) => fn());
240
+ return run(() => createWriteStream("", { ...options, fd: this }));
241
+ }
242
+ }
243
+ Object.defineProperty(FileHandle, "name", {
244
+ value: "FileHandle",
245
+ configurable: true,
246
+ });
247
+ export function createFileHandle(backend) {
248
+ return new FileHandle(badge, backend);
249
+ }
@@ -0,0 +1,15 @@
1
+ import type { DirEntryHandle } from "./directory-backend.js";
2
+ export declare function expandBraces(pattern: string): string[];
3
+ export declare function normalizePattern(pattern: string): string;
4
+ export declare function segmentToRegex(segment: string): RegExp;
5
+ export declare function globToRegex(pattern: string): RegExp;
6
+ export declare function compileExcludePatterns(exclude: readonly string[]): (path: string) => boolean;
7
+ type EntryCache = Map<string, DirEntryHandle[]>;
8
+ export interface GlobResult {
9
+ relativePath: string;
10
+ handle: DirEntryHandle | null;
11
+ }
12
+ export declare function collapseGlobstars(segments: string[]): string[];
13
+ export declare function precompileSegmentRegexes(segments: string[]): (RegExp | null)[];
14
+ export declare function walkGlob(cwd: string, segments: string[], segIdx: number, currentAbsPath: string, relativePath: string, results: Map<string, GlobResult>, cache: EntryCache, segmentRegexes: (RegExp | null)[], visitedGlobstar?: Set<string>, depth?: number): void;
15
+ export {};
@@ -0,0 +1,417 @@
1
+ // Copyright (c) 2026 Cloudflare, Inc.
2
+ // Licensed under the Apache 2.0 license found in the LICENSE file or at:
3
+ // https://opensource.org/licenses/Apache-2.0
4
+ // Ported from workerd@5358e3d337336eaf696a48bc1563d808b10feba5 internal_fs_glob.ts.
5
+ // Adapted filesystem boundary; pattern matching and traversal retain the pinned upstream implementation.
6
+ import { readDirectory } from "./directory-backend.js";
7
+ // UV_DIRENT_DIR constant from internal_fs_constants
8
+ const UV_DIRENT_DIR = 2;
9
+ // Maximum recursion depth to prevent stack overflow on deeply nested VFS
10
+ const MAX_WALK_DEPTH = 256;
11
+ // ============================================================================
12
+ // Brace Expansion
13
+ // ============================================================================
14
+ // Splits a string by top-level occurrences of a separator character,
15
+ // respecting nested braces/parens and backslash escapes.
16
+ function splitTopLevel(str, sep) {
17
+ const parts = [];
18
+ let depth = 0;
19
+ let current = "";
20
+ for (let i = 0; i < str.length; i++) {
21
+ const c = str.charAt(i);
22
+ if (c === "\\" && i + 1 < str.length) {
23
+ current += c + str.charAt(i + 1);
24
+ i++;
25
+ }
26
+ else if (c === "{" || c === "(") {
27
+ depth++;
28
+ current += c;
29
+ }
30
+ else if (c === "}" || c === ")") {
31
+ depth--;
32
+ current += c;
33
+ }
34
+ else if (c === sep && depth === 0) {
35
+ parts.push(current);
36
+ current = "";
37
+ }
38
+ else {
39
+ current += c;
40
+ }
41
+ }
42
+ parts.push(current);
43
+ return parts;
44
+ }
45
+ // Expands brace expressions in a glob pattern into multiple patterns.
46
+ export function expandBraces(pattern) {
47
+ let depth = 0;
48
+ let braceStart = -1;
49
+ for (let i = 0; i < pattern.length; i++) {
50
+ const c = pattern[i];
51
+ if (c === "\\" && i + 1 < pattern.length) {
52
+ i++;
53
+ continue;
54
+ }
55
+ if (c === "{") {
56
+ if (depth === 0)
57
+ braceStart = i;
58
+ depth++;
59
+ }
60
+ else if (c === "}") {
61
+ depth--;
62
+ if (depth === 0 && braceStart !== -1) {
63
+ const prefix = pattern.slice(0, braceStart);
64
+ const body = pattern.slice(braceStart + 1, i);
65
+ const suffix = pattern.slice(i + 1);
66
+ const alternatives = splitTopLevel(body, ",");
67
+ if (alternatives.length === 1) {
68
+ return [pattern];
69
+ }
70
+ const results = [];
71
+ for (const alt of alternatives) {
72
+ for (const expanded of expandBraces(prefix + alt + suffix)) {
73
+ results.push(expanded);
74
+ }
75
+ }
76
+ return results;
77
+ }
78
+ }
79
+ }
80
+ return [pattern];
81
+ }
82
+ // ============================================================================
83
+ // Pattern Normalization
84
+ // ============================================================================
85
+ export function normalizePattern(pattern) {
86
+ // Strip leading ./
87
+ if (pattern.startsWith("./")) {
88
+ pattern = pattern.slice(2);
89
+ }
90
+ // Collapse multiple slashes to single
91
+ pattern = pattern.replace(/\/\/+/g, "/");
92
+ // Strip trailing slash
93
+ if (pattern.endsWith("/") && pattern.length > 1) {
94
+ pattern = pattern.slice(0, -1);
95
+ }
96
+ return pattern;
97
+ }
98
+ // ============================================================================
99
+ // Segment-Level Regex (with extglob support)
100
+ // ============================================================================
101
+ // Converts a single path segment pattern to a RegExp.
102
+ // Supports: *, ?, [...], [!...], @(...), *(...), +(...), ?(...), !(...)
103
+ export function segmentToRegex(segment) {
104
+ const regex = segmentToRegexStr(segment);
105
+ return new RegExp("^" + regex + "$");
106
+ }
107
+ function segmentToRegexStr(segment) {
108
+ let regex = "";
109
+ let i = 0;
110
+ let inCharClass = false;
111
+ while (i < segment.length) {
112
+ const c = segment[i] ?? "";
113
+ // Handle escape sequences
114
+ if (c === "\\" && i + 1 < segment.length) {
115
+ regex += "\\" + escapeRegexChar(segment[i + 1] ?? "");
116
+ i += 2;
117
+ continue;
118
+ }
119
+ // Inside character classes, most chars are literal
120
+ if (inCharClass) {
121
+ if (c === "]") {
122
+ regex += "]";
123
+ inCharClass = false;
124
+ }
125
+ else {
126
+ regex += c;
127
+ }
128
+ i++;
129
+ continue;
130
+ }
131
+ // Check for extglob: @(...), *(...), +(...), ?(...), !(...)
132
+ if ((c === "@" || c === "*" || c === "+" || c === "?" || c === "!") &&
133
+ i + 1 < segment.length &&
134
+ segment[i + 1] === "(") {
135
+ const closeIdx = findMatchingParen(segment, i + 1);
136
+ if (closeIdx !== -1) {
137
+ const inner = segment.slice(i + 2, closeIdx);
138
+ // Convert pipe-separated alternatives, each may contain glob chars
139
+ const alts = splitTopLevel(inner, "|");
140
+ const altRegexes = alts.map((a) => segmentToRegexStr(a));
141
+ const group = altRegexes.join("|");
142
+ switch (c) {
143
+ case "@": // exactly one
144
+ regex += "(?:" + group + ")";
145
+ break;
146
+ case "*": // zero or more
147
+ regex += "(?:" + group + ")*";
148
+ break;
149
+ case "+": // one or more
150
+ regex += "(?:" + group + ")+";
151
+ break;
152
+ case "?": // zero or one
153
+ regex += "(?:" + group + ")?";
154
+ break;
155
+ case "!": // none of (negative lookahead)
156
+ regex += "(?!(?:" + group + ")$)[^/]*";
157
+ break;
158
+ }
159
+ i = closeIdx + 1;
160
+ continue;
161
+ }
162
+ }
163
+ switch (c) {
164
+ case "[":
165
+ inCharClass = true;
166
+ regex += "[";
167
+ if (i + 1 < segment.length && segment[i + 1] === "!") {
168
+ regex += "^";
169
+ i++;
170
+ }
171
+ break;
172
+ case "*":
173
+ regex += "[^/]*";
174
+ break;
175
+ case "?":
176
+ regex += "[^/]";
177
+ break;
178
+ case ".":
179
+ case "+":
180
+ case "^":
181
+ case "$":
182
+ case "|":
183
+ case "(":
184
+ case ")":
185
+ case "{":
186
+ case "}":
187
+ regex += "\\" + c;
188
+ break;
189
+ default:
190
+ regex += c;
191
+ break;
192
+ }
193
+ i++;
194
+ }
195
+ return regex;
196
+ }
197
+ function findMatchingParen(str, openIdx) {
198
+ let depth = 0;
199
+ for (let i = openIdx; i < str.length; i++) {
200
+ if (str[i] === "\\" && i + 1 < str.length) {
201
+ i++;
202
+ continue;
203
+ }
204
+ if (str[i] === "(")
205
+ depth++;
206
+ else if (str[i] === ")") {
207
+ depth--;
208
+ if (depth === 0)
209
+ return i;
210
+ }
211
+ }
212
+ return -1;
213
+ }
214
+ function escapeRegexChar(c) {
215
+ if (".+*?^$|()[]{}\\".includes(c)) {
216
+ return "\\" + c;
217
+ }
218
+ return c;
219
+ }
220
+ // ============================================================================
221
+ // Full-Path Regex (used for exclude pattern matching)
222
+ // ============================================================================
223
+ // Converts a full glob pattern (with /) to a single RegExp for exclude matching.
224
+ export function globToRegex(pattern) {
225
+ const normalized = normalizePattern(pattern);
226
+ const segments = normalized.split("/").filter((s) => s !== "");
227
+ const parts = [];
228
+ for (const seg of segments) {
229
+ if (seg === "**") {
230
+ // ** matches zero or more path segments
231
+ // We handle this by inserting a special marker
232
+ parts.push("**");
233
+ }
234
+ else if (seg === ".") {
235
+ // skip
236
+ }
237
+ else if (seg === "..") {
238
+ parts.pop();
239
+ }
240
+ else {
241
+ parts.push(segmentToRegexStr(seg));
242
+ }
243
+ }
244
+ // Now build regex from parts, handling ** markers
245
+ let regex = "";
246
+ for (let i = 0; i < parts.length; i++) {
247
+ const part = parts[i] ?? "";
248
+ const prevPart = i > 0 ? (parts[i - 1] ?? "") : "";
249
+ if (part === "**") {
250
+ if (parts.length === 1) {
251
+ // ** alone: match everything
252
+ regex = ".*";
253
+ }
254
+ else if (i === 0) {
255
+ // ** at start: match zero or more leading segments
256
+ regex += "(?:.*\\/)?";
257
+ }
258
+ else if (i === parts.length - 1) {
259
+ // ** at end: match zero or more trailing segments
260
+ regex += "(?:\\/.*)?";
261
+ }
262
+ else {
263
+ // ** in middle: match zero or more middle segments
264
+ regex += "(?:\\/[^/]+)*(?:\\/)?";
265
+ }
266
+ }
267
+ else {
268
+ if (i > 0 && prevPart !== "**") {
269
+ regex += "\\/";
270
+ }
271
+ regex += part;
272
+ }
273
+ }
274
+ return new RegExp("^" + regex + "$");
275
+ }
276
+ // ============================================================================
277
+ // Exclude Compiler
278
+ // ============================================================================
279
+ // Compiles an array of glob patterns into an exclude function.
280
+ // Only accepts string arrays — user-provided functions are handled
281
+ // separately in globSync to preserve their (string | Dirent) signature.
282
+ export function compileExcludePatterns(exclude) {
283
+ const regexes = [];
284
+ for (const pat of exclude) {
285
+ for (const expanded of expandBraces(pat)) {
286
+ regexes.push(globToRegex(expanded));
287
+ }
288
+ }
289
+ return (path) => {
290
+ for (const re of regexes) {
291
+ if (re.test(path))
292
+ return true;
293
+ }
294
+ return false;
295
+ };
296
+ }
297
+ function getDirectoryEntries(absPath, cache) {
298
+ const cached = cache.get(absPath);
299
+ if (cached !== undefined)
300
+ return cached;
301
+ try {
302
+ const entries = readDirectory(absPath, false);
303
+ cache.set(absPath, entries);
304
+ return entries;
305
+ }
306
+ catch {
307
+ const empty = [];
308
+ cache.set(absPath, empty);
309
+ return empty;
310
+ }
311
+ }
312
+ function isDirectory(entry) {
313
+ return entry.type === UV_DIRENT_DIR;
314
+ }
315
+ // Collapses consecutive '**' segments to prevent exponential blowup.
316
+ export function collapseGlobstars(segments) {
317
+ const result = [];
318
+ for (const seg of segments) {
319
+ if (seg === "**" && result[result.length - 1] === "**")
320
+ continue;
321
+ result.push(seg);
322
+ }
323
+ return result;
324
+ }
325
+ // Precompiles segment regexes for all non-special segments.
326
+ export function precompileSegmentRegexes(segments) {
327
+ return segments.map((seg) => {
328
+ if (seg === "**" || seg === "." || seg === "..")
329
+ return null;
330
+ return segmentToRegex(seg);
331
+ });
332
+ }
333
+ export function walkGlob(cwd, segments, segIdx, currentAbsPath, relativePath, results, cache, segmentRegexes, visitedGlobstar, depth = 0) {
334
+ // Guard against excessive recursion depth
335
+ if (depth >= MAX_WALK_DEPTH)
336
+ return;
337
+ // All segments consumed: this path is a match
338
+ if (segIdx >= segments.length) {
339
+ if (!results.has(relativePath)) {
340
+ // Resolve handle for the matched path by reading the parent directory
341
+ const lastSlash = currentAbsPath.lastIndexOf("/");
342
+ const parentDir = lastSlash > 0 ? currentAbsPath.slice(0, lastSlash) : currentAbsPath;
343
+ const basename = relativePath.split("/").pop() ?? "";
344
+ const entries = getDirectoryEntries(parentDir, cache);
345
+ const handle = entries.find((e) => e.name === basename) ?? null;
346
+ results.set(relativePath, { relativePath, handle });
347
+ }
348
+ return;
349
+ }
350
+ const seg = segments[segIdx] ?? "";
351
+ // Handle '.' — stay in current directory
352
+ if (seg === ".") {
353
+ walkGlob(cwd, segments, segIdx + 1, currentAbsPath, relativePath, results, cache, segmentRegexes, visitedGlobstar, depth);
354
+ return;
355
+ }
356
+ // Handle '..' — go up one directory (but don't escape cwd)
357
+ if (seg === "..") {
358
+ if (currentAbsPath === cwd || !currentAbsPath.startsWith(cwd + "/")) {
359
+ return;
360
+ }
361
+ const lastSlash = currentAbsPath.lastIndexOf("/");
362
+ const newAbs = lastSlash > 0 ? currentAbsPath.slice(0, lastSlash) : "/";
363
+ const relParts = relativePath.split("/").filter(Boolean);
364
+ relParts.pop();
365
+ const newRel = relParts.join("/");
366
+ walkGlob(cwd, segments, segIdx + 1, newAbs, newRel, results, cache, segmentRegexes, visitedGlobstar, depth);
367
+ return;
368
+ }
369
+ // Handle '**' — match zero or more directory levels
370
+ if (seg === "**") {
371
+ const gsKey = `${currentAbsPath}:${String(segIdx)}`;
372
+ if (visitedGlobstar === undefined) {
373
+ visitedGlobstar = new Set();
374
+ }
375
+ if (visitedGlobstar.has(gsKey))
376
+ return;
377
+ visitedGlobstar.add(gsKey);
378
+ // Zero levels: advance to next segment at current path
379
+ walkGlob(cwd, segments, segIdx + 1, currentAbsPath, relativePath, results, cache, segmentRegexes, visitedGlobstar, depth);
380
+ // One or more levels: enumerate children
381
+ const entries = getDirectoryEntries(currentAbsPath, cache);
382
+ for (const entry of entries) {
383
+ const childAbs = currentAbsPath + "/" + entry.name;
384
+ const childRel = relativePath
385
+ ? relativePath + "/" + entry.name
386
+ : entry.name;
387
+ // Try matching next segment against this child
388
+ walkGlob(cwd, segments, segIdx + 1, childAbs, childRel, results, cache, segmentRegexes, visitedGlobstar, depth + 1);
389
+ // If directory, recurse ** deeper
390
+ if (isDirectory(entry)) {
391
+ walkGlob(cwd, segments, segIdx, childAbs, childRel, results, cache, segmentRegexes, visitedGlobstar, depth + 1);
392
+ }
393
+ }
394
+ return;
395
+ }
396
+ // Regular segment: match against precompiled regex
397
+ const segRegex = segmentRegexes[segIdx] ?? segmentToRegex(seg);
398
+ const entries = getDirectoryEntries(currentAbsPath, cache);
399
+ for (const entry of entries) {
400
+ if (segRegex.test(entry.name)) {
401
+ const childAbs = currentAbsPath + "/" + entry.name;
402
+ const childRel = relativePath
403
+ ? relativePath + "/" + entry.name
404
+ : entry.name;
405
+ if (segIdx + 1 >= segments.length) {
406
+ // This is the last segment — record match
407
+ if (!results.has(childRel)) {
408
+ results.set(childRel, { relativePath: childRel, handle: entry });
409
+ }
410
+ }
411
+ else {
412
+ // More segments to match — recurse
413
+ walkGlob(cwd, segments, segIdx + 1, childAbs, childRel, results, cache, segmentRegexes, visitedGlobstar, depth + 1);
414
+ }
415
+ }
416
+ }
417
+ }
@@ -0,0 +1,10 @@
1
+ import { Dirent } from "./directory.js";
2
+ type GlobOptions = {
3
+ cwd?: string | URL;
4
+ withFileTypes?: boolean;
5
+ exclude?: string[] | ((path: any) => boolean);
6
+ };
7
+ type GlobOptionsWithFileTypes = GlobOptions;
8
+ type GlobOptionsWithoutFileTypes = GlobOptions;
9
+ export declare function globSync(pattern: string | readonly string[], options?: GlobOptions | GlobOptionsWithFileTypes | GlobOptionsWithoutFileTypes): string[] | Dirent[];
10
+ export {};