react-smart-copy 1.19.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/files.js ADDED
@@ -0,0 +1,932 @@
1
+
2
+ import { n as copyFailure } from "./chunks/errors-9h8sdFFX.js";
3
+ //#region src/files/detect.ts
4
+ /** How many leading bytes {@link detectFileType} reads: enough for every signature and a text sniff. */
5
+ const FILE_SNIFF_BYTES = 8192;
6
+ const type = (mime, family, extensions, parent = null) => Object.freeze({
7
+ mime,
8
+ family,
9
+ extensions: Object.freeze(extensions),
10
+ parent
11
+ });
12
+ const ZIP = "application/zip";
13
+ const TEXT = "text/plain";
14
+ /** Every type this module recognises, by MIME type. */
15
+ const FILE_TYPES = {
16
+ pdf: type("application/pdf", "document", ["pdf"]),
17
+ png: type("image/png", "image", ["png", "apng"]),
18
+ jpeg: type("image/jpeg", "image", [
19
+ "jpg",
20
+ "jpeg",
21
+ "jpe",
22
+ "jfif"
23
+ ]),
24
+ gif: type("image/gif", "image", ["gif"]),
25
+ webp: type("image/webp", "image", ["webp"]),
26
+ avif: type("image/avif", "image", ["avif"]),
27
+ heic: type("image/heic", "image", ["heic", "heif"]),
28
+ bmp: type("image/bmp", "image", ["bmp", "dib"]),
29
+ ico: type("image/x-icon", "image", ["ico", "cur"]),
30
+ tiff: type("image/tiff", "image", [
31
+ "tif",
32
+ "tiff",
33
+ "dng",
34
+ "cr2",
35
+ "nef",
36
+ "arw"
37
+ ]),
38
+ psd: type("image/vnd.adobe.photoshop", "image", ["psd"]),
39
+ svg: type("image/svg+xml", "image", ["svg", "svgz"], TEXT),
40
+ mp3: type("audio/mpeg", "audio", ["mp3"]),
41
+ wav: type("audio/wav", "audio", ["wav"]),
42
+ flac: type("audio/flac", "audio", ["flac"]),
43
+ ogg: type("audio/ogg", "audio", [
44
+ "ogg",
45
+ "oga",
46
+ "ogv",
47
+ "opus",
48
+ "spx"
49
+ ]),
50
+ m4a: type("audio/mp4", "audio", ["m4a", "m4b"], "video/mp4"),
51
+ mp4: type("video/mp4", "video", [
52
+ "mp4",
53
+ "m4v",
54
+ "m4a",
55
+ "mov"
56
+ ]),
57
+ mov: type("video/quicktime", "video", ["mov", "qt"], "video/mp4"),
58
+ threegp: type("video/3gpp", "video", ["3gp", "3g2"], "video/mp4"),
59
+ webm: type("video/webm", "video", ["webm", "weba"]),
60
+ mkv: type("video/x-matroska", "video", [
61
+ "mkv",
62
+ "mka",
63
+ "webm"
64
+ ]),
65
+ avi: type("video/x-msvideo", "video", ["avi"]),
66
+ zip: type(ZIP, "archive", ["zip"]),
67
+ docx: type("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "document", [
68
+ "docx",
69
+ "docm",
70
+ "dotx",
71
+ "dotm"
72
+ ], ZIP),
73
+ xlsx: type("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "document", [
74
+ "xlsx",
75
+ "xlsm",
76
+ "xltx",
77
+ "xltm"
78
+ ], ZIP),
79
+ pptx: type("application/vnd.openxmlformats-officedocument.presentationml.presentation", "document", [
80
+ "pptx",
81
+ "pptm",
82
+ "potx",
83
+ "potm",
84
+ "ppsx",
85
+ "ppsm"
86
+ ], ZIP),
87
+ odt: type("application/vnd.oasis.opendocument.text", "document", ["odt"], ZIP),
88
+ ods: type("application/vnd.oasis.opendocument.spreadsheet", "document", ["ods"], ZIP),
89
+ odp: type("application/vnd.oasis.opendocument.presentation", "document", ["odp"], ZIP),
90
+ epub: type("application/epub+zip", "document", ["epub"], ZIP),
91
+ jar: type("application/java-archive", "executable", [
92
+ "jar",
93
+ "war",
94
+ "ear"
95
+ ], ZIP),
96
+ apk: type("application/vnd.android.package-archive", "executable", ["apk", "aab"], ZIP),
97
+ ole: type("application/x-ole-storage", "document", [
98
+ "doc",
99
+ "xls",
100
+ "ppt",
101
+ "msg",
102
+ "msi",
103
+ "dot",
104
+ "xlt",
105
+ "pps"
106
+ ]),
107
+ rtf: type("application/rtf", "document", ["rtf"], TEXT),
108
+ gzip: type("application/gzip", "archive", ["gz", "tgz"]),
109
+ bzip2: type("application/x-bzip2", "archive", ["bz2", "tbz2"]),
110
+ xz: type("application/x-xz", "archive", ["xz", "txz"]),
111
+ zstd: type("application/zstd", "archive", ["zst"]),
112
+ sevenZip: type("application/x-7z-compressed", "archive", ["7z"]),
113
+ rar: type("application/vnd.rar", "archive", ["rar"]),
114
+ tar: type("application/x-tar", "archive", ["tar"]),
115
+ sqlite: type("application/vnd.sqlite3", "data", ["sqlite", "sqlite3"]),
116
+ woff: type("font/woff", "font", ["woff"]),
117
+ woff2: type("font/woff2", "font", ["woff2"]),
118
+ otf: type("font/otf", "font", ["otf"]),
119
+ ttf: type("font/ttf", "font", ["ttf", "ttc"]),
120
+ exe: type("application/vnd.microsoft.portable-executable", "executable", [
121
+ "exe",
122
+ "dll",
123
+ "sys",
124
+ "scr",
125
+ "com",
126
+ "cpl",
127
+ "ocx",
128
+ "efi"
129
+ ]),
130
+ elf: type("application/x-elf", "executable", [
131
+ "so",
132
+ "run",
133
+ "elf"
134
+ ]),
135
+ macho: type("application/x-mach-binary", "executable", ["dylib", "bundle"]),
136
+ wasm: type("application/wasm", "executable", ["wasm"]),
137
+ shortcut: type("application/x-ms-shortcut", "executable", ["lnk"]),
138
+ script: type("text/x-shellscript", "executable", [
139
+ "sh",
140
+ "bash",
141
+ "zsh",
142
+ "command",
143
+ "py",
144
+ "pl",
145
+ "rb"
146
+ ], TEXT),
147
+ html: type("text/html", "text", [
148
+ "html",
149
+ "htm",
150
+ "xhtml",
151
+ "xht",
152
+ "shtml",
153
+ "mht",
154
+ "mhtml"
155
+ ], TEXT),
156
+ xml: type("application/xml", "text", [
157
+ "xml",
158
+ "xsl",
159
+ "xslt",
160
+ "rss",
161
+ "atom",
162
+ "kml",
163
+ "gpx"
164
+ ], TEXT),
165
+ json: type("application/json", "text", [
166
+ "json",
167
+ "geojson",
168
+ "jsonld",
169
+ "webmanifest",
170
+ "map"
171
+ ], TEXT),
172
+ text: type(TEXT, "text", ["txt"])
173
+ };
174
+ /** Bounds-checked reads: past the end is never a match. */
175
+ var Head = class {
176
+ constructor(bytes) {
177
+ this.bytes = bytes;
178
+ }
179
+ at(index) {
180
+ return index < this.bytes.length ? this.bytes[index] : -1;
181
+ }
182
+ is(offset, ...values) {
183
+ return values.every((value, index) => this.at(offset + index) === value);
184
+ }
185
+ ascii(offset, length) {
186
+ let out = "";
187
+ for (let index = offset; index < offset + length && index < this.bytes.length; index += 1) out += String.fromCharCode(this.bytes[index]);
188
+ return out;
189
+ }
190
+ u16le(offset) {
191
+ return this.at(offset) + (this.at(offset + 1) << 8);
192
+ }
193
+ u32le(offset) {
194
+ return (this.at(offset) | this.at(offset + 1) << 8 | this.at(offset + 2) << 16 | this.at(offset + 3) << 24) >>> 0;
195
+ }
196
+ };
197
+ /** ISO base media (MP4, MOV, HEIC, AVIF, 3GP): `ftyp` with its major brand. */
198
+ function isoMedia(head) {
199
+ if (head.ascii(4, 4) !== "ftyp") return null;
200
+ const brand = head.ascii(8, 4);
201
+ if (brand === "avif" || brand === "avis") return FILE_TYPES.avif;
202
+ if ([
203
+ "heic",
204
+ "heix",
205
+ "heim",
206
+ "heis",
207
+ "hevc",
208
+ "hevx",
209
+ "mif1",
210
+ "msf1"
211
+ ].includes(brand)) return FILE_TYPES.heic;
212
+ if (brand === "qt ") return FILE_TYPES.mov;
213
+ if (brand.startsWith("M4A") || brand.startsWith("M4B")) return FILE_TYPES.m4a;
214
+ if (brand.startsWith("3g")) return FILE_TYPES.threegp;
215
+ return FILE_TYPES.mp4;
216
+ }
217
+ /** RIFF containers: WebP, WAV, AVI. */
218
+ function riff(head) {
219
+ if (head.ascii(0, 4) !== "RIFF") return null;
220
+ const form = head.ascii(8, 4);
221
+ if (form === "WEBP") return FILE_TYPES.webp;
222
+ if (form === "WAVE") return FILE_TYPES.wav;
223
+ if (form === "AVI ") return FILE_TYPES.avi;
224
+ return null;
225
+ }
226
+ /** A ZIP, and what it packages: Office, OpenDocument, EPUB, Java and Android archives. */
227
+ function zip(head) {
228
+ if (!head.is(0, 80, 75) || !(head.is(2, 3, 4) || head.is(2, 5, 6) || head.is(2, 7, 8))) return null;
229
+ if (head.ascii(30, 8) === "mimetype") {
230
+ const declared = head.ascii(38, head.u32le(18) > 0 && head.u32le(18) < 100 ? head.u32le(18) : 80);
231
+ for (const candidate of [
232
+ FILE_TYPES.epub,
233
+ FILE_TYPES.odt,
234
+ FILE_TYPES.ods,
235
+ FILE_TYPES.odp
236
+ ]) if (declared.startsWith(candidate.mime)) return {
237
+ type: candidate,
238
+ macros: false
239
+ };
240
+ }
241
+ const names = head.ascii(0, head.bytes.length);
242
+ const macros = names.includes("vbaProject.bin");
243
+ if (names.includes("AndroidManifest.xml") || names.includes("classes.dex")) return {
244
+ type: FILE_TYPES.apk,
245
+ macros
246
+ };
247
+ if (names.includes("META-INF/MANIFEST.MF")) return {
248
+ type: FILE_TYPES.jar,
249
+ macros
250
+ };
251
+ if (names.includes("word/")) return {
252
+ type: FILE_TYPES.docx,
253
+ macros
254
+ };
255
+ if (names.includes("xl/")) return {
256
+ type: FILE_TYPES.xlsx,
257
+ macros
258
+ };
259
+ if (names.includes("ppt/")) return {
260
+ type: FILE_TYPES.pptx,
261
+ macros
262
+ };
263
+ return {
264
+ type: FILE_TYPES.zip,
265
+ macros
266
+ };
267
+ }
268
+ /** Binary formats, recognised by their signatures. */
269
+ function binary(head) {
270
+ if (head.ascii(0, 5) === "%PDF-") return FILE_TYPES.pdf;
271
+ if (head.is(0, 137, 80, 78, 71, 13, 10, 26, 10)) return FILE_TYPES.png;
272
+ if (head.is(0, 255, 216, 255)) return FILE_TYPES.jpeg;
273
+ if (head.ascii(0, 6) === "GIF87a" || head.ascii(0, 6) === "GIF89a") return FILE_TYPES.gif;
274
+ if (head.ascii(0, 2) === "BM" && [
275
+ 12,
276
+ 40,
277
+ 52,
278
+ 56,
279
+ 64,
280
+ 108,
281
+ 124
282
+ ].includes(head.u32le(14))) return FILE_TYPES.bmp;
283
+ if (head.is(0, 0, 0, 1, 0) || head.is(0, 0, 0, 2, 0)) {
284
+ const count = head.u16le(4);
285
+ if (count > 0 && count <= 256 && head.at(9) === 0) return FILE_TYPES.ico;
286
+ }
287
+ if (head.is(0, 73, 73, 42, 0) || head.is(0, 77, 77, 0, 42)) return FILE_TYPES.tiff;
288
+ if (head.ascii(0, 4) === "8BPS") return FILE_TYPES.psd;
289
+ const media = isoMedia(head) ?? riff(head);
290
+ if (media) return media;
291
+ if (head.ascii(0, 3) === "ID3" || head.at(0) === 255 && [
292
+ 251,
293
+ 243,
294
+ 242
295
+ ].includes(head.at(1))) return FILE_TYPES.mp3;
296
+ if (head.ascii(0, 4) === "fLaC") return FILE_TYPES.flac;
297
+ if (head.ascii(0, 4) === "OggS") return FILE_TYPES.ogg;
298
+ if (head.is(0, 26, 69, 223, 163)) return head.ascii(0, 64).includes("webm") ? FILE_TYPES.webm : FILE_TYPES.mkv;
299
+ if (head.is(0, 31, 139)) return FILE_TYPES.gzip;
300
+ if (head.ascii(0, 3) === "BZh") return FILE_TYPES.bzip2;
301
+ if (head.is(0, 253, 55, 122, 88, 90, 0)) return FILE_TYPES.xz;
302
+ if (head.is(0, 40, 181, 47, 253)) return FILE_TYPES.zstd;
303
+ if (head.is(0, 55, 122, 188, 175, 39, 28)) return FILE_TYPES.sevenZip;
304
+ if (head.is(0, 82, 97, 114, 33, 26, 7)) return FILE_TYPES.rar;
305
+ if (head.ascii(257, 5) === "ustar") return FILE_TYPES.tar;
306
+ if (head.is(0, 208, 207, 17, 224, 161, 177, 26, 225)) return FILE_TYPES.ole;
307
+ if (head.ascii(0, 5) === "{\\rtf") return FILE_TYPES.rtf;
308
+ if (head.ascii(0, 15) === "SQLite format 3" && head.at(15) === 0) return FILE_TYPES.sqlite;
309
+ if (head.ascii(0, 4) === "wOFF") return FILE_TYPES.woff;
310
+ if (head.ascii(0, 4) === "wOF2") return FILE_TYPES.woff2;
311
+ if (head.ascii(0, 4) === "OTTO") return FILE_TYPES.otf;
312
+ if (head.is(0, 0, 1, 0, 0, 0) || head.ascii(0, 4) === "true" || head.ascii(0, 4) === "ttcf") return FILE_TYPES.ttf;
313
+ if (head.ascii(0, 2) === "MZ") return FILE_TYPES.exe;
314
+ if (head.is(0, 127, 69, 76, 70)) return FILE_TYPES.elf;
315
+ if ([
316
+ 4277009102,
317
+ 4277009103,
318
+ 3472551422,
319
+ 3489328638,
320
+ 3405691582,
321
+ 3199925962
322
+ ].includes(head.u32le(0))) return FILE_TYPES.macho;
323
+ if (head.is(0, 0, 97, 115, 109)) return FILE_TYPES.wasm;
324
+ if (head.is(0, 76, 0, 0, 0, 1, 20, 2, 0)) return FILE_TYPES.shortcut;
325
+ return null;
326
+ }
327
+ /** UTF-8 (valid, with no NUL), or UTF-16 with its byte order mark: the bytes are text. */
328
+ function decodeText(bytes, complete) {
329
+ if (bytes.length >= 2 && (bytes[0] === 255 && bytes[1] === 254 || bytes[0] === 254 && bytes[1] === 255)) return new TextDecoder(bytes[0] === 255 ? "utf-16le" : "utf-16be").decode(bytes.subarray(2));
330
+ if (bytes.includes(0)) return null;
331
+ try {
332
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes, { stream: !complete });
333
+ } catch {
334
+ return null;
335
+ }
336
+ }
337
+ /** Elements that start an HTML document. Case-insensitive, though it is given lowercase text. */
338
+ const HTML_START = /^<(?:!doctype\s+html|html|head|body|script|iframe|frame|object|embed|meta|title|link|style|base|form|div|p|a|img|table)[\s/>]/i;
339
+ /** Text formats, recognised from their start. */
340
+ function textType(text, complete) {
341
+ const start = text.replace(/^\uFEFF/, "").trimStart();
342
+ const lower = start.slice(0, 1024).toLowerCase();
343
+ if (start.startsWith("#!")) return FILE_TYPES.script;
344
+ if (lower.startsWith("{\\rtf")) return FILE_TYPES.rtf;
345
+ if (lower.startsWith("<")) {
346
+ const body = lower.replace(/^(?:<\?[\s\S]*?\?>|<!--[\s\S]*?-->|<!doctype\s+(?!html)[^>]*>|\s+)*/, "");
347
+ if (body.startsWith("<svg")) return FILE_TYPES.svg;
348
+ if (HTML_START.test(body)) return FILE_TYPES.html;
349
+ return lower.startsWith("<?xml") || /^<[a-z_][\w.:-]*[\s/>]/.test(body) ? FILE_TYPES.xml : FILE_TYPES.text;
350
+ }
351
+ if (complete && (start.startsWith("{") || start.startsWith("["))) try {
352
+ JSON.parse(start);
353
+ return FILE_TYPES.json;
354
+ } catch {
355
+ return FILE_TYPES.text;
356
+ }
357
+ return FILE_TYPES.text;
358
+ }
359
+ const ACTIVE_XML = /<script|<\?xml-stylesheet|xmlns(?::[\w.-]+)?\s*=\s*["']http:\/\/www\.w3\.org\/1999\/xhtml/i;
360
+ /**
361
+ * What `bytes` (the start of a file, {@link FILE_SNIFF_BYTES} or all of it) are.
362
+ * `complete` says whether they are the whole file, which some text formats need (JSON).
363
+ */
364
+ function detect(bytes, complete) {
365
+ const head = new Head(bytes);
366
+ const packaged = zip(head);
367
+ if (packaged) return {
368
+ type: packaged.type,
369
+ macros: packaged.macros,
370
+ active: false
371
+ };
372
+ const found = binary(head);
373
+ if (found) return {
374
+ type: found,
375
+ macros: false,
376
+ active: false
377
+ };
378
+ const text = bytes.length === 0 ? null : decodeText(bytes, complete);
379
+ if (text === null) return {
380
+ type: null,
381
+ macros: false,
382
+ active: false
383
+ };
384
+ const kind = textType(text, complete);
385
+ return {
386
+ type: kind,
387
+ macros: false,
388
+ active: kind === FILE_TYPES.html || kind === FILE_TYPES.svg || kind === FILE_TYPES.xml && ACTIVE_XML.test(text)
389
+ };
390
+ }
391
+ /**
392
+ * The type of a file's content, from its leading bytes: never from its name or claimed type.
393
+ * Reads at most {@link FILE_SNIFF_BYTES}. `null` when the content is not a recognised type.
394
+ */
395
+ function detectFileType(bytes, options = {}) {
396
+ return detect(bytes.subarray(0, FILE_SNIFF_BYTES), options.complete ?? bytes.length <= 8192).type;
397
+ }
398
+ //#endregion
399
+ //#region src/files/name.ts
400
+ /** File names: making them safe to show and store, and what they say about the file. */
401
+ /**
402
+ * Extensions the operating system runs, or mounts, when the file is opened: Windows, macOS
403
+ * and Linux programs, scripts and installers, shortcuts, and disk images (which can carry
404
+ * programs past download warnings).
405
+ */
406
+ const EXECUTABLE_EXTENSIONS = /* @__PURE__ */ new Set("exe com scr pif bat cmd ps1 ps1xml ps2 psc1 psm1 psd1 vb vbs vbe js jse mjs cjs ws wsf wsc wsh hta msi msp mst msc dll ocx sys cpl drv efi lnk url scf inf reg appref-ms application gadget xbap jar war ear class apk aab xapk ipa app command tool sh bash zsh csh ksh fish run py pyc pyw pl rb php elf so dylib bundle deb rpm pkg mpkg dmg iso img vhd vhdx appx appxbundle msix msixbundle wasm settingcontent-ms library-ms search-ms chm hlp".split(" "));
407
+ /** Extensions of documents, images and media: the decoy in front of an executable one (`invoice.pdf.exe`). */
408
+ const DECOY_EXTENSIONS = /* @__PURE__ */ new Set("pdf doc docx xls xlsx ppt pptx odt ods odp rtf txt csv md jpg jpeg png gif webp heic bmp tif tiff svg mp3 mp4 mov avi wav m4a zip rar 7z html htm eml msg".split(" "));
409
+ /** Extensions of Office files that can hold macros. */
410
+ const MACRO_EXTENSIONS = /* @__PURE__ */ new Set([
411
+ "docm",
412
+ "dotm",
413
+ "xlsm",
414
+ "xltm",
415
+ "xlam",
416
+ "pptm",
417
+ "potm",
418
+ "ppsm",
419
+ "ppam",
420
+ "sldm"
421
+ ]);
422
+ /** Extensions of active content: it runs script when a browser opens it from your origin. */
423
+ const ACTIVE_EXTENSIONS = /* @__PURE__ */ new Set([
424
+ "html",
425
+ "htm",
426
+ "xhtml",
427
+ "xht",
428
+ "shtml",
429
+ "mht",
430
+ "mhtml",
431
+ "svg",
432
+ "svgz"
433
+ ]);
434
+ /**
435
+ * Bidirectional controls, invisible and control characters, and other characters that make
436
+ * a name display as something else, or break where it is stored.
437
+ */
438
+ const HIDDEN_SOURCE = String.raw`[\u0000-\u001f\u007f-\u009f\u00AD\u061C\u115F\u1160\u17B4\u17B5\u180B-\u180F\u200B-\u200F\u202A-\u202E\u2060-\u206F\u3164\uFE00-\uFE0F\uFEFF\uFFA0\uFFF0-\uFFFB]|[\u{e0000}-\u{e0fff}]`;
439
+ const HIDDEN = /* @__PURE__ */ new RegExp(HIDDEN_SOURCE, "u");
440
+ const HIDDEN_ALL = /* @__PURE__ */ new RegExp(HIDDEN_SOURCE, "gu");
441
+ /** Whether `name` holds characters that hide or reorder what it shows. */
442
+ function hasHiddenCharacters(name) {
443
+ return HIDDEN.test(name);
444
+ }
445
+ /** The last extension of `name`, lowercase, without the dot; `null` for none (`README`, `.env`). */
446
+ function extensionOf(name) {
447
+ const base = name.slice(Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")) + 1).replace(/[\s.]+$/u, "");
448
+ const dot = base.lastIndexOf(".");
449
+ if (dot <= 0) return null;
450
+ return base.slice(dot + 1).trim().toLowerCase();
451
+ }
452
+ /**
453
+ * A document or image extension followed by an executable one, as in `invoice.pdf.exe`, or
454
+ * an executable extension pushed out of view by a run of spaces (`invoice.pdf .exe`).
455
+ */
456
+ function hasDoubleExtension(name) {
457
+ const cleaned = name.replace(HIDDEN_ALL, "");
458
+ const last = extensionOf(cleaned);
459
+ if (last === null || !EXECUTABLE_EXTENSIONS.has(last)) return false;
460
+ const rest = cleaned.slice(0, cleaned.toLowerCase().lastIndexOf(`.${last}`));
461
+ if (/\s{3,}$/u.test(rest)) return true;
462
+ const previous = extensionOf(rest);
463
+ return previous !== null && DECOY_EXTENSIONS.has(previous);
464
+ }
465
+ const WINDOWS_RESERVED = /^(?:con|prn|aux|nul|com[0-9\u00B9\u00B2\u00B3]|lpt[0-9\u00B9\u00B2\u00B3]|conin\$|conout\$)$/i;
466
+ const encoder = /* @__PURE__ */ new TextEncoder();
467
+ /** Cuts `text` to at most `bytes` UTF-8 bytes, never inside a character. */
468
+ function cutToBytes(text, bytes) {
469
+ let out = "";
470
+ let used = 0;
471
+ for (const char of text) {
472
+ const size = encoder.encode(char).length;
473
+ if (used + size > bytes) break;
474
+ out += char;
475
+ used += size;
476
+ }
477
+ return out;
478
+ }
479
+ /** A replacement that can itself be in a file name (up to 4 characters), or `_`. */
480
+ const safeReplacement = (value) => /^[^<>:"/\\|?*\s.]{0,4}$/u.test(value) && !hasHiddenCharacters(value) ? value : "_";
481
+ /**
482
+ * `name` made safe to show and to store on any operating system:
483
+ *
484
+ * - only the last path segment is kept, so `../../etc/passwd` becomes `passwd`;
485
+ * - bidirectional controls, invisible and control characters are removed (tabs and line breaks become spaces);
486
+ * - characters Windows, macOS or Linux reject (`<>:"/\|?*`) become `replacement`;
487
+ * - runs of whitespace become one space, and leading dots and spaces and trailing dots and
488
+ * spaces are removed (no hidden files, nothing Windows would change);
489
+ * - Windows device names (`CON`, `NUL`, `COM1`, ...) are prefixed with `replacement`;
490
+ * - the result is at most `maxBytes` long in UTF-8, keeping the extension; Unicode is NFC.
491
+ *
492
+ * Never empty: `fallback` is used when nothing is left. Idempotent.
493
+ */
494
+ function safeFileName(name, options = {}) {
495
+ const replacement = safeReplacement(options.replacement ?? "_");
496
+ const fallback = options.fallback ?? "file";
497
+ const maxBytes = Math.max(16, Math.floor(options.maxBytes ?? 255));
498
+ let safe = name.replace(/[\t\n\v\f\r]/gu, " ").replace(HIDDEN_ALL, "").normalize("NFC");
499
+ safe = safe.slice(Math.max(safe.lastIndexOf("/"), safe.lastIndexOf("\\")) + 1);
500
+ safe = safe.replace(/[<>:"|?*]/gu, replacement).replace(/\s+/gu, " ").replace(/^[\s.]+/u, "").replace(/[\s.]+$/u, "");
501
+ if (safe === "") return fallback;
502
+ const prefix = replacement === "" ? "_" : replacement;
503
+ const reserved = (text) => WINDOWS_RESERVED.test((text.includes(".") ? text.slice(0, text.indexOf(".")) : text).trim());
504
+ if (reserved(safe)) safe = `${prefix}${safe}`;
505
+ if (encoder.encode(safe).length <= maxBytes) return safe;
506
+ const extension = extensionOf(safe);
507
+ const kept = extension === null ? "" : `.${extension}`;
508
+ const suffix = kept !== "" && encoder.encode(kept).length <= Math.min(17, maxBytes - 8) ? kept : "";
509
+ const budget = maxBytes - encoder.encode(suffix).length;
510
+ const cut = (bytes) => cutToBytes(safe.slice(0, safe.length - suffix.length), bytes).replace(/[\s.]+$/u, "");
511
+ const result = `${cut(budget)}${suffix}`;
512
+ return reserved(result) ? `${prefix}${cut(budget - encoder.encode(prefix).length)}${suffix}` : result;
513
+ }
514
+ //#endregion
515
+ //#region src/files/types.ts
516
+ /** Every risk, in a stable order. */
517
+ const FILE_RISKS = Object.freeze([
518
+ "executable",
519
+ "active-content",
520
+ "macros",
521
+ "type-mismatch",
522
+ "double-extension",
523
+ "hidden-characters",
524
+ "empty"
525
+ ]);
526
+ //#endregion
527
+ //#region src/files/inspect.ts
528
+ /** Content types that any text extension may hold (`.csv`, `.md`, `.log`, ...). */
529
+ const PLAIN_TEXT = /* @__PURE__ */ new Set([
530
+ FILE_TYPES.text.mime,
531
+ FILE_TYPES.json.mime,
532
+ FILE_TYPES.xml.mime
533
+ ]);
534
+ /** Extensions of text formats this module doesn't tell apart: any plain text content fits them. */
535
+ const TEXT_EXTENSIONS = /* @__PURE__ */ new Set("txt text csv tsv md markdown mdx rst adoc org tex bib log ini cfg conf toml yaml yml env properties ics vcf vcard sql srt vtt sub css scss sass less js mjs cjs jsx ts tsx mts cts vue svelte astro py rb pl php go rs java kt kts c h cc cpp hpp cs swift m sh bash zsh bat cmd ps1 r lua dart scala clj ex exs erl hs ml fs diff patch gitignore editorconfig".split(" "));
536
+ /** MIME types of text formats known by their extension, for `accept` lists such as `text/csv`. */
537
+ const TEXT_MIME_BY_EXTENSION = {
538
+ csv: ["text/csv"],
539
+ tsv: ["text/tab-separated-values"],
540
+ md: ["text/markdown"],
541
+ markdown: ["text/markdown"],
542
+ yaml: ["application/yaml", "text/yaml"],
543
+ yml: ["application/yaml", "text/yaml"],
544
+ ics: ["text/calendar"],
545
+ vcf: ["text/vcard"],
546
+ css: ["text/css"],
547
+ js: ["text/javascript"],
548
+ mjs: ["text/javascript"],
549
+ vtt: ["text/vtt"],
550
+ srt: ["application/x-subrip"],
551
+ json: ["application/json"],
552
+ xml: ["application/xml", "text/xml"]
553
+ };
554
+ let byExtension = null;
555
+ /** Every type saved with `extension`. Built on first use. */
556
+ function typesFor(extension) {
557
+ if (byExtension === null) {
558
+ const map = /* @__PURE__ */ new Map();
559
+ for (const type of Object.values(FILE_TYPES)) for (const ext of type.extensions) map.set(ext, [...map.get(ext) ?? [], type]);
560
+ byExtension = map;
561
+ }
562
+ return byExtension.get(extension) ?? [];
563
+ }
564
+ /** Whether `extension` is saved for text: a known text format, or a type that is text inside. */
565
+ function isTextExtension(extension) {
566
+ return TEXT_EXTENSIONS.has(extension) || typesFor(extension).some((type) => type.parent === FILE_TYPES.text.mime || type === FILE_TYPES.text);
567
+ }
568
+ /**
569
+ * Whether the content contradicts the extension. An unknown extension never does; a known one
570
+ * does when the content is another type (a container and what it packages are the same family:
571
+ * `.zip` and a Word document), or is not recognised at all.
572
+ */
573
+ function contradicts(extension, detected) {
574
+ if (extension === null) return false;
575
+ const expected = typesFor(extension);
576
+ const text = isTextExtension(extension);
577
+ if (expected.length === 0 && !text) return false;
578
+ if (detected === null) return true;
579
+ const related = (child, parent) => child.parent === parent.mime && parent !== FILE_TYPES.text;
580
+ if (expected.some((type) => type.mime === detected.mime || related(detected, type) || related(type, detected))) return false;
581
+ return !(text && PLAIN_TEXT.has(detected.mime));
582
+ }
583
+ /** The type to store a file as: the detected one, made precise by the extension for plain text (`text/csv`). */
584
+ function typeOf(detected, extension, mismatch) {
585
+ if (detected === null) return "application/octet-stream";
586
+ const named = extension === null || mismatch ? void 0 : TEXT_MIME_BY_EXTENSION[extension]?.[0];
587
+ return named !== void 0 && PLAIN_TEXT.has(detected.mime) ? named : detected.mime;
588
+ }
589
+ /** An inspection of `bytes`, the start of a file (all of it when `complete`). */
590
+ function inspectBytes(bytes, name, declaredType, size, complete, names = {}) {
591
+ const extension = extensionOf(name);
592
+ const detection = detect(bytes, complete);
593
+ const detected = detection.type;
594
+ const mismatch = size > 0 && contradicts(extension, detected);
595
+ const found = /* @__PURE__ */ new Set();
596
+ if (detected?.family === "executable" || extension !== null && EXECUTABLE_EXTENSIONS.has(extension)) found.add("executable");
597
+ if (detection.active || extension !== null && ACTIVE_EXTENSIONS.has(extension)) found.add("active-content");
598
+ if (detection.macros || extension !== null && MACRO_EXTENSIONS.has(extension)) found.add("macros");
599
+ if (mismatch) found.add("type-mismatch");
600
+ if (hasDoubleExtension(name)) found.add("double-extension");
601
+ if (hasHiddenCharacters(name)) found.add("hidden-characters");
602
+ if (size === 0) found.add("empty");
603
+ return {
604
+ name,
605
+ safeName: safeFileName(name, names),
606
+ extension,
607
+ size,
608
+ declaredType,
609
+ detected,
610
+ type: typeOf(detected, extension, mismatch),
611
+ mismatch,
612
+ risks: FILE_RISKS.filter((risk) => found.has(risk))
613
+ };
614
+ }
615
+ /** Reads the first `bytes` of `blob`. */
616
+ async function readHead(blob, bytes) {
617
+ const candidate = blob;
618
+ if (typeof candidate !== "object" || candidate === null || typeof candidate.slice !== "function") throw copyFailure("invalid-payload", "Expected a Blob or File.");
619
+ return new Uint8Array(await blob.slice(0, bytes).arrayBuffer());
620
+ }
621
+ /**
622
+ * What a file really is, and why it may be unsafe to accept: its type from its content (never
623
+ * its name or claimed type), whether that contradicts its extension, and its risks.
624
+ * Reads only the first {@link FILE_SNIFF_BYTES} bytes, so it is fast for any size. Server-safe.
625
+ *
626
+ * @throws {CopyFailure} `invalid-payload` when `file` is not a Blob.
627
+ */
628
+ async function inspectFile(file, options = {}) {
629
+ return inspectBytes(await readHead(file, FILE_SNIFF_BYTES), options.name ?? file.name ?? "", options.declaredType ?? file.type, file.size, file.size <= FILE_SNIFF_BYTES, options.names);
630
+ }
631
+ //#endregion
632
+ //#region src/files/accept.ts
633
+ /** The tokens of an `accept` list, as in `<input type="file" accept>`: `.pdf`, `image/*`, `text/csv`. Lowercase. */
634
+ function parseAccept(accept) {
635
+ return (typeof accept === "string" ? accept.split(",") : accept).map((token) => token.trim().toLowerCase()).filter((token) => /^(?:\.[^\s,/\\]+|\*|\*\/\*|[a-z0-9!#$&^_.+-]+\/(?:\*|[a-z0-9!#$&^_.+-]+))$/.test(token));
636
+ }
637
+ /**
638
+ * Whether a file fits an `accept` list, judged by its content. An extension token (`.pdf`)
639
+ * matches the name, when the content does not contradict it. A MIME token (`application/pdf`,
640
+ * `image/*`) matches the detected type or its container; plain text also matches the type its
641
+ * extension names (`text/csv` for `data.csv`). The claimed type is never used. An empty list
642
+ * accepts everything.
643
+ */
644
+ function matchesAccept(inspection, accept) {
645
+ const tokens = parseAccept(accept);
646
+ if (tokens.length === 0) return true;
647
+ const name = inspection.name.toLowerCase();
648
+ const types = [inspection.type];
649
+ if (inspection.detected?.parent) types.push(inspection.detected.parent);
650
+ if (inspection.detected?.family === "text" && !inspection.mismatch && inspection.extension !== null) types.push(...TEXT_MIME_BY_EXTENSION[inspection.extension] ?? []);
651
+ return tokens.some((token) => {
652
+ if (token === "*" || token === "*/*") return true;
653
+ if (token.startsWith(".")) return name.endsWith(token) && !inspection.mismatch;
654
+ if (token.endsWith("/*")) return inspection.detected !== null && types.some((type) => type.startsWith(token.slice(0, -1)));
655
+ return types.includes(token);
656
+ });
657
+ }
658
+ //#endregion
659
+ //#region src/files/collect.ts
660
+ const DEFAULT_MAX_FILES = 100;
661
+ const DEFAULT_MAX_FILE_BYTES = 104857600;
662
+ const DEFAULT_MAX_TOTAL_BYTES = 1073741824;
663
+ const DEFAULT_MAX_FOLDER_DEPTH = 8;
664
+ function readEntries(directory) {
665
+ const reader = directory.createReader();
666
+ return (async function* batches() {
667
+ for (;;) {
668
+ const batch = await new Promise((resolve, reject) => {
669
+ reader.readEntries(resolve, reject);
670
+ });
671
+ if (batch.length === 0) return;
672
+ yield* batch;
673
+ }
674
+ })();
675
+ }
676
+ const entryFile = (entry) => new Promise((resolve, reject) => {
677
+ entry.file(resolve, reject);
678
+ });
679
+ function isDataTransfer(value) {
680
+ return "files" in value && "types" in value;
681
+ }
682
+ /**
683
+ * The dropped items, read at once: a `DataTransfer` is emptied when its event ends, so this
684
+ * runs before anything is awaited. Dropped files are taken as files (`getAsFile`), which every
685
+ * engine gives; entries are used only to walk folders.
686
+ */
687
+ function roots(source, folders) {
688
+ const candidate = source;
689
+ const transfer = isDataTransfer(source) ? source : candidate.dataTransfer ?? candidate.clipboardData;
690
+ if (transfer === void 0) {
691
+ const list = source;
692
+ return Array.from(Symbol.iterator in Object(list) ? list : list, (file) => ({ file }));
693
+ }
694
+ if (transfer === null) return [];
695
+ const found = [];
696
+ for (const item of Array.from(transfer.items ?? [])) {
697
+ if (item.kind !== "file") continue;
698
+ const getEntry = item.webkitGetAsEntry;
699
+ const entry = folders && getEntry ? getEntry.call(item) : null;
700
+ if (entry?.isDirectory) {
701
+ found.push({ entry });
702
+ continue;
703
+ }
704
+ const file = item.getAsFile();
705
+ if (file) found.push({ file });
706
+ }
707
+ return found.length > 0 ? found : Array.from(transfer.files, (file) => ({ file }));
708
+ }
709
+ async function* walk(roots, maxDepth, names) {
710
+ const safe = (name, fallback) => safeFileName(name, {
711
+ ...names,
712
+ fallback
713
+ });
714
+ async function* visit(entry, parent, depth) {
715
+ const name = safe(entry.name, entry.isDirectory ? "folder" : "file");
716
+ const path = parent === "" ? name : `${parent}/${name}`;
717
+ if (entry.isFile) {
718
+ try {
719
+ yield {
720
+ kind: "file",
721
+ file: await entryFile(entry),
722
+ path,
723
+ name
724
+ };
725
+ } catch {
726
+ yield {
727
+ kind: "skipped",
728
+ reason: "unreadable",
729
+ path,
730
+ name
731
+ };
732
+ }
733
+ return;
734
+ }
735
+ if (!entry.isDirectory) return;
736
+ if (depth >= maxDepth) {
737
+ yield {
738
+ kind: "skipped",
739
+ reason: "too-deep",
740
+ path,
741
+ name
742
+ };
743
+ return;
744
+ }
745
+ try {
746
+ for await (const child of readEntries(entry)) yield* visit(child, path, depth + 1);
747
+ } catch {
748
+ yield {
749
+ kind: "skipped",
750
+ reason: "unreadable",
751
+ path,
752
+ name
753
+ };
754
+ }
755
+ }
756
+ for (const root of roots) if ("entry" in root) yield* visit(root.entry, "", 0);
757
+ else {
758
+ const name = safe(root.file.name ?? "", "file");
759
+ yield {
760
+ kind: "file",
761
+ file: root.file,
762
+ path: name,
763
+ name
764
+ };
765
+ }
766
+ }
767
+ const UNITS = [
768
+ "bytes",
769
+ "KB",
770
+ "MB",
771
+ "GB",
772
+ "TB"
773
+ ];
774
+ /** `1048576` as `1 MB`. */
775
+ function formatBytes(bytes) {
776
+ let value = bytes;
777
+ let unit = 0;
778
+ while (value >= 1024 && unit < UNITS.length - 1) {
779
+ value /= 1024;
780
+ unit += 1;
781
+ }
782
+ return `${String(unit === 0 ? value : Math.round(value * 10) / 10)} ${UNITS[unit]}`;
783
+ }
784
+ const RISK_MESSAGES = {
785
+ executable: (name) => `${name} is a program or script, which can't be added.`,
786
+ "active-content": (name) => `${name} is a web page or SVG that can run scripts, so it can't be added.`,
787
+ macros: (name) => `${name} can contain macros, so it can't be added.`,
788
+ "type-mismatch": (name) => `${name} is not the type of file its name says.`,
789
+ "double-extension": (name) => `${name} hides its real type behind a second extension.`,
790
+ "hidden-characters": (name) => `${name} has hidden characters in its name.`,
791
+ empty: (name) => `${name} is empty.`
792
+ };
793
+ async function sha256(blob) {
794
+ const digest = await crypto.subtle.digest("SHA-256", await blob.arrayBuffer());
795
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
796
+ }
797
+ function positive(value, fallback, name) {
798
+ if (value === void 0) return fallback;
799
+ if (!(value >= 0)) throw copyFailure("invalid-payload", `${name} must be a number of at least 0.`);
800
+ return value;
801
+ }
802
+ /**
803
+ * Takes the files from a paste, a drop (folders included), a file input or a list, and
804
+ * decides for each whether it is safe and wanted: its type is read from its content, its
805
+ * name made safe, and the limits applied. Nothing is uploaded or read whole (except with
806
+ * `digest`): only each file's first 8 KiB.
807
+ *
808
+ * Call it from the event handler, before anything is awaited: a `DataTransfer` is emptied
809
+ * when its event ends. Folders are read through `webkitGetAsEntry` (every current browser).
810
+ *
811
+ * ```ts
812
+ * onDrop={(event) => {
813
+ * event.preventDefault();
814
+ * void acceptFiles(event, { accept: '.pdf,image/*', maxFileBytes: 20e6 }).then(({ accepted, rejected }) => { ... });
815
+ * }}
816
+ * ```
817
+ *
818
+ * @throws {CopyFailure} `aborted` when `signal` aborts; `unsupported` for `digest` without Web Crypto;
819
+ * `invalid-payload` for a negative limit.
820
+ */
821
+ async function acceptFiles(source, options = {}) {
822
+ const found = roots(source, options.folders ?? true);
823
+ const maxFiles = positive(options.maxFiles, 100, "maxFiles");
824
+ const maxFileBytes = positive(options.maxFileBytes, DEFAULT_MAX_FILE_BYTES, "maxFileBytes");
825
+ const maxTotalBytes = positive(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES, "maxTotalBytes");
826
+ const maxDepth = positive(options.maxDepth, 8, "maxDepth");
827
+ const block = new Set(options.block ?? FILE_RISKS);
828
+ const digest = options.digest === true;
829
+ if (digest && (typeof crypto === "undefined" || typeof crypto.subtle === "undefined")) throw copyFailure("unsupported", "digest needs Web Crypto (crypto.subtle): a secure page, or Node.js 20+ (on 18, set globalThis.crypto to webcrypto from node:crypto).");
830
+ const signal = options.signal;
831
+ const checkAborted = () => {
832
+ if (signal?.aborted) throw copyFailure("aborted", "Adding files was aborted.", signal.reason);
833
+ };
834
+ checkAborted();
835
+ const accepted = [];
836
+ const rejected = [];
837
+ const seen = /* @__PURE__ */ new Map();
838
+ let totalBytes = 0;
839
+ let count = 0;
840
+ let truncated = false;
841
+ const reject = (file, name, path, reason, message, risks = []) => {
842
+ rejected.push({
843
+ file,
844
+ name,
845
+ path,
846
+ reason,
847
+ risks,
848
+ message
849
+ });
850
+ };
851
+ for await (const item of walk(found, maxDepth, options.names ?? {})) {
852
+ checkAborted();
853
+ if (item.kind === "skipped") {
854
+ reject(null, item.name, item.path, item.reason, item.reason === "too-deep" ? `${item.path} was not read: it is more than ${String(maxDepth)} folders deep.` : `${item.path} could not be read.`);
855
+ continue;
856
+ }
857
+ const { file, name, path } = item;
858
+ count += 1;
859
+ if (count > maxFiles) {
860
+ truncated = true;
861
+ reject(file, name, path, "too-many", `${name} and any files after it were not added: at most ${String(maxFiles)} files can be added at once.`);
862
+ break;
863
+ }
864
+ if (file.size > maxFileBytes) {
865
+ reject(file, name, path, "too-large", `${name} is larger than ${formatBytes(maxFileBytes)}.`);
866
+ continue;
867
+ }
868
+ let inspection;
869
+ try {
870
+ inspection = inspectBytes(await readHead(file, FILE_SNIFF_BYTES), file.name ?? "", file.type, file.size, file.size <= FILE_SNIFF_BYTES, options.names);
871
+ } catch {
872
+ checkAborted();
873
+ reject(file, name, path, "unreadable", `${name} could not be read.`);
874
+ continue;
875
+ }
876
+ checkAborted();
877
+ const blocked = inspection.risks.find((risk) => block.has(risk));
878
+ if (blocked !== void 0) {
879
+ reject(file, name, path, "blocked", RISK_MESSAGES[blocked](name), inspection.risks);
880
+ continue;
881
+ }
882
+ if (options.accept !== void 0 && !matchesAccept(inspection, options.accept)) {
883
+ reject(file, name, path, "not-accepted", `${name} is not a type of file that can be added here.`, inspection.risks);
884
+ continue;
885
+ }
886
+ if (totalBytes + file.size > maxTotalBytes) {
887
+ reject(file, name, path, "total-too-large", `${name} was not added: the files together would be larger than ${formatBytes(maxTotalBytes)}.`, inspection.risks);
888
+ continue;
889
+ }
890
+ let hash = null;
891
+ if (digest) {
892
+ try {
893
+ hash = await sha256(file);
894
+ } catch {
895
+ checkAborted();
896
+ reject(file, name, path, "unreadable", `${name} could not be read.`, inspection.risks);
897
+ continue;
898
+ }
899
+ checkAborted();
900
+ const original = seen.get(hash);
901
+ if (original !== void 0) {
902
+ reject(file, name, path, "duplicate", `${name} is the same file as ${original}.`, inspection.risks);
903
+ continue;
904
+ }
905
+ seen.set(hash, path);
906
+ }
907
+ totalBytes += file.size;
908
+ accepted.push({
909
+ file,
910
+ upload: typeof File === "function" ? new File([file], name, {
911
+ type: inspection.type,
912
+ lastModified: file.lastModified ?? Date.now()
913
+ }) : new Blob([file], { type: inspection.type }),
914
+ name,
915
+ path,
916
+ size: file.size,
917
+ type: inspection.type,
918
+ inspection,
919
+ sha256: hash
920
+ });
921
+ }
922
+ return {
923
+ accepted,
924
+ rejected,
925
+ totalBytes,
926
+ truncated
927
+ };
928
+ }
929
+ //#endregion
930
+ export { DEFAULT_MAX_FILES, DEFAULT_MAX_FILE_BYTES, DEFAULT_MAX_FOLDER_DEPTH, DEFAULT_MAX_TOTAL_BYTES, EXECUTABLE_EXTENSIONS, FILE_RISKS, FILE_SNIFF_BYTES, FILE_TYPES, acceptFiles, detectFileType, extensionOf, formatBytes, inspectFile, matchesAccept, parseAccept, safeFileName };
931
+
932
+ //# sourceMappingURL=files.js.map