@d0paminedriven/fs 7.1.0 → 7.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +104 -51
  2. package/dist/chunk-2IRCHZCF.js +75 -0
  3. package/dist/{chunk-LFHV4PPA.js → chunk-2XQ44ZWR.js} +339 -3
  4. package/dist/{chunk-IUGBPDQJ.js → chunk-6HHKXBIM.js} +5 -2
  5. package/dist/chunk-HPM4IQQR.js +69 -0
  6. package/dist/{chunk-3WB2TSBO.js → chunk-KNLXF622.js} +2 -2
  7. package/dist/chunk-KOKPGEU4.js +69 -0
  8. package/dist/chunk-LQP2FYMK.js +237 -0
  9. package/dist/chunk-NHYRCNMW.js +107 -0
  10. package/dist/chunk-NOOFSAF4.js +165 -0
  11. package/dist/chunk-PTXZQBLV.js +367 -0
  12. package/dist/{chunk-RJ2YQE3C.js → chunk-R63XI7FS.js} +1 -1
  13. package/dist/{chunk-QBG7TFHM.js → chunk-UW52DMHT.js} +2 -2
  14. package/dist/chunk-Z2WZLZC4.js +75 -0
  15. package/dist/fs/index.d.ts +18 -282
  16. package/dist/fs/index.js +13 -6
  17. package/dist/fs-atomic/index.d.ts +38 -0
  18. package/dist/fs-atomic/index.js +14 -0
  19. package/dist/fs-base/index.d.ts +112 -0
  20. package/dist/fs-base/index.js +13 -0
  21. package/dist/fs-core/index.d.ts +24 -0
  22. package/dist/fs-core/index.js +17 -0
  23. package/dist/fs-fetch/index.d.ts +64 -0
  24. package/dist/fs-fetch/index.js +19 -0
  25. package/dist/fs-size/index.d.ts +30 -0
  26. package/dist/fs-size/index.js +16 -0
  27. package/dist/fs-tmp/index.d.ts +194 -0
  28. package/dist/fs-tmp/index.js +18 -0
  29. package/dist/image/index.d.ts +35 -1
  30. package/dist/image/index.js +5 -4
  31. package/dist/index.d.ts +12 -2
  32. package/dist/index.js +36 -8
  33. package/dist/ld/index.d.ts +14 -0
  34. package/dist/ld/index.js +8 -0
  35. package/dist/mime/index.d.ts +1 -0
  36. package/dist/mime/index.js +4 -3
  37. package/dist/types/index.d.ts +12 -12
  38. package/dist/types/index.js +1 -1
  39. package/dist/types/stream.d.ts +9 -0
  40. package/dist/types/stream.js +1 -0
  41. package/dist/url/index.d.ts +1 -0
  42. package/dist/url/index.js +3 -2
  43. package/dist/utils/index.d.ts +2 -1
  44. package/dist/utils/index.js +2 -1
  45. package/package.json +37 -5
  46. package/dist/chunk-3REIEDSC.js +0 -745
  47. package/dist/fs/index.cjs +0 -1818
  48. package/dist/fs/index.d.cts +0 -464
  49. package/dist/image/index.cjs +0 -1071
  50. package/dist/image/index.d.cts +0 -88
  51. package/dist/index.cjs +0 -1838
  52. package/dist/index.d.cts +0 -10
  53. package/dist/mime/index.cjs +0 -509
  54. package/dist/mime/index.d.cts +0 -502
  55. package/dist/types/index.cjs +0 -38
  56. package/dist/types/index.d.cts +0 -333
  57. package/dist/url/index.cjs +0 -181
  58. package/dist/url/index.d.cts +0 -33
  59. package/dist/utils/index.cjs +0 -157
  60. package/dist/utils/index.d.cts +0 -25
package/dist/fs/index.cjs DELETED
@@ -1,1818 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
20
- };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
-
31
- // src/fs/index.ts
32
- var fs_exports = {};
33
- __export(fs_exports, {
34
- default: () => Fs
35
- });
36
- module.exports = __toCommonJS(fs_exports);
37
- var import_child_process = require("child_process");
38
- var import_fs = __toESM(require("fs"), 1);
39
- var import_promises = __toESM(require("fs/promises"), 1);
40
- var import_node_os = require("os");
41
- var import_path = require("path");
42
- var dotenv = __toESM(require("dotenv"), 1);
43
- var import_dotenv_expand = __toESM(require("dotenv-expand"), 1);
44
- var import_sharp = __toESM(require("sharp"), 1);
45
-
46
- // src/utils/index.ts
47
- var UtilsService = class {
48
- static {
49
- __name(this, "UtilsService");
50
- }
51
- chunkArray(arr, maxChunkLength) {
52
- const chunks = Array.of();
53
- let currentChunkLength = 0;
54
- let currentChunk = Array.of();
55
- for (const [index, val] of arr.entries()) {
56
- if (val.length + currentChunkLength >= maxChunkLength) {
57
- if (currentChunk.length) {
58
- chunks.push(currentChunk);
59
- }
60
- currentChunkLength = val.length;
61
- currentChunk = [val];
62
- } else {
63
- currentChunk.push(val);
64
- currentChunkLength += val.length + 1;
65
- }
66
- if (arr.length === index + 1) {
67
- chunks.push(currentChunk);
68
- }
69
- }
70
- return chunks.length ? chunks : [arr];
71
- }
72
- b64ToBlob(b64Data) {
73
- {
74
- const sliceSize = 512;
75
- const typeMatch = /^data:((?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*);base64,(.+)$/i.exec(
76
- b64Data
77
- );
78
- if (!typeMatch) {
79
- throw new Error(`${b64Data} is not a valid data Url`);
80
- }
81
- const type = typeMatch[1];
82
- const base64Data = typeMatch?.[2] ?? "";
83
- const byteCharacters = Buffer.from(base64Data, "base64").toString(
84
- "binary"
85
- );
86
- const byteArrays = Array.of();
87
- for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
88
- const slice = byteCharacters.slice(offset, offset + sliceSize);
89
- const byteNumbers = new Array(slice.length);
90
- for (let i = 0; i < slice.length; i++) {
91
- byteNumbers[i] = slice.charCodeAt(i);
92
- }
93
- const byteArray = new Uint8Array(byteNumbers);
94
- byteArrays.push(byteArray);
95
- }
96
- const blob = new Blob(byteArrays, { type });
97
- return blob;
98
- }
99
- }
100
- arrToArrOfArrs = /* @__PURE__ */ __name(({
101
- arrToFragment = Array.of(),
102
- arrOfArrsAggregator = Array.of(),
103
- interval
104
- }) => new Promise(
105
- (resolve2, _reject) => resolve2(
106
- ((interval2) => {
107
- for (let i = 0; i <= arrToFragment.length; i++) {
108
- if ((i % interval2 === 0 || i === 0) && i <= arrToFragment.length) {
109
- let segment = arrToFragment.slice(i, i + interval2);
110
- arrOfArrsAggregator.push(segment);
111
- }
112
- }
113
- })(interval)
114
- )
115
- ).then((_) => arrOfArrsAggregator), "arrToArrOfArrs");
116
- extractTuple(obj, props) {
117
- return [props, obj[props]];
118
- }
119
- sort(obj, order) {
120
- return Object.fromEntries(
121
- Object.entries(obj).sort(
122
- ([a, _aa], [b, _bb]) => order === "DESC" ? b.localeCompare(a) - a.localeCompare(b) : a.localeCompare(b) - b.localeCompare(a)
123
- )
124
- );
125
- }
126
- excludeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
127
- const resolve2 = Object.fromEntries(
128
- Object.entries(obj).map(([key, val]) => {
129
- if (props.includes(key)) {
130
- return ["omit", "omit"];
131
- } else return [key, val];
132
- }).filter(([t, _v]) => /omit/.test(t) === false)
133
- );
134
- return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
135
- }, "excludeTargeted");
136
- includeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
137
- const resolve2 = Object.fromEntries(
138
- props.map((val) => this.extractTuple(obj, val))
139
- );
140
- return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
141
- }, "includeTargeted");
142
- countsSorter = /* @__PURE__ */ __name((counter, keySort = "ASC", valSort = "DESC") => Object.fromEntries(
143
- Array.from(Object.entries(counter)).sort(
144
- ([aStr, _aNum], [bStr, _bNum]) => keySort === "DESC" ? bStr.localeCompare(aStr) - aStr.localeCompare(bStr) : aStr.localeCompare(bStr) - bStr.localeCompare(aStr)
145
- ).sort(([aStr, aNum], [bStr, bNum]) => {
146
- if (typeof (aNum && bNum) === "number") {
147
- return valSort === "ASC" ? aNum - bNum : bNum - aNum;
148
- } else if (typeof (aNum && bNum) === "string") {
149
- return valSort === "ASC" ? aStr.localeCompare(bStr) - bStr.localeCompare(aStr) : bStr.localeCompare(aStr) - aStr.localeCompare(bStr);
150
- } else
151
- throw new Error(
152
- "only Record<string, string> and Record<string,number> types supported"
153
- );
154
- })
155
- ), "countsSorter");
156
- range(from, to) {
157
- const values = Array.of();
158
- for (let i = from; i < to; i++) {
159
- values.push(i);
160
- }
161
- return values;
162
- }
163
- isPrimeNumber = /* @__PURE__ */ __name((n) => {
164
- for (let i = 2; n > i; i++) {
165
- if (n % i === 0) {
166
- return false;
167
- }
168
- }
169
- return n > 1;
170
- }, "isPrimeNumber");
171
- acceptor = /* @__PURE__ */ __name((num) => [...Array(num !== 0 ? num : this.range(num = -101, num = 101)).keys()].reverse().filter(this.isPrimeNumber), "acceptor");
172
- };
173
-
174
- // src/url/index.ts
175
- var UrlService = class extends UtilsService {
176
- static {
177
- __name(this, "UrlService");
178
- }
179
- URL_REGEX = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
180
- parseUrl(url) {
181
- const parsed = this.URL_REGEX.exec(url);
182
- if (parsed) {
183
- return {
184
- href: parsed[0],
185
- protocol: parsed[1] ?? "",
186
- baseUrl: `${parsed[1]}${parsed[3]}`,
187
- host: parsed[4] ?? "",
188
- pathname: parsed[5] ?? "",
189
- search: parsed[6] ?? "",
190
- hash: parsed[8] ?? ""
191
- };
192
- } else return null;
193
- }
194
- };
195
-
196
- // src/mime/index.ts
197
- var extMimeMap = {
198
- aac: ["audio/aac"],
199
- abw: ["application/x-abiword"],
200
- aces: ["image/aces"],
201
- apng: ["image/apng"],
202
- arc: ["application/x-freearc"],
203
- avci: ["image/avci"],
204
- avif: ["image/avif"],
205
- avi: ["video/x-msvideo"],
206
- azw: ["application/vnd.amazon.ebook"],
207
- bin: ["application/octet-stream", "multipart/voice-message"],
208
- bmp: ["image/bmp"],
209
- bz: ["application/x-bzip"],
210
- bz2: ["application/x-bzip2"],
211
- cda: ["application/x-cdf"],
212
- cjs: ["application/node", "text/javascript"],
213
- csh: ["application/x-csh"],
214
- css: ["text/css"],
215
- csv: ["text/csv"],
216
- cur: ["image/x-icon"],
217
- doc: ["application/msword"],
218
- docx: [
219
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
220
- ],
221
- dpx: ["image/dpx"],
222
- emf: ["image/emf"],
223
- eot: ["application/vnd.ms-fontobject"],
224
- epub: ["application/epub+zip"],
225
- gif: ["image/gif"],
226
- glb: ["model/gltf-binary"],
227
- gltf: ["model/gltf+json"],
228
- gz: ["application/gzip", "application/x-gzip"],
229
- hjif: ["haptics/hjif"],
230
- hmpg: ["haptics/hmpg"],
231
- htm: ["text/html"],
232
- html: ["text/html"],
233
- ico: ["image/vnd.microsoft.icon", "image/x-icon"],
234
- ics: ["text/calendar"],
235
- ivs: ["haptics/ivs"],
236
- ivt: ["haptics/ivs"],
237
- jar: ["application/java-archive"],
238
- jfif: ["image/jpeg"],
239
- jif: ["image/jpeg"],
240
- jpe: ["image/jpeg"],
241
- jpeg: ["image/jpeg"],
242
- jpg: ["image/jpeg"],
243
- js: ["application/node", "text/javascript"],
244
- json: ["application/json"],
245
- jsonld: ["application/ld+json"],
246
- ktx: ["image/ktx"],
247
- ktx2: ["image/ktx2"],
248
- m3u8: ["application/vnd.apple.mpegurl"],
249
- m4a: ["audio/mp4"],
250
- m4v: ["video/mp4"],
251
- md: ["text/markdown"],
252
- mdx: ["application/x-mdx"],
253
- mid: ["audio/midi"],
254
- midi: ["audio/x-midi"],
255
- mjs: ["text/javascript"],
256
- mp3: ["audio/mpeg"],
257
- mp4: ["video/mp4"],
258
- mpd: ["application/dash+xml"],
259
- mpeg: ["video/mpeg"],
260
- mpkg: ["application/vnd.apple.installer+xml"],
261
- mtlx: ["application/xml"],
262
- ndjson: ["application/x-ndjson"],
263
- node: ["application/node", "text/javascript"],
264
- obj: ["model/obj", "application/octet-stream", "text/plain"],
265
- odp: ["application/vnd.oasis.opendocument.presentation"],
266
- ods: ["application/vnd.oasis.opendocument.spreadsheet"],
267
- odt: ["application/vnd.oasis.opendocument.text"],
268
- oga: ["audio/ogg"],
269
- ogg: ["audio/ogg"],
270
- ogv: ["video/ogg"],
271
- ogx: ["application/ogg"],
272
- opus: ["audio/ogg"],
273
- otf: ["font/otf"],
274
- png: ["image/png"],
275
- pdf: ["application/pdf"],
276
- php: ["application/x-httpd-php"],
277
- pjp: ["image/jpeg"],
278
- pjpeg: ["image/jpeg"],
279
- pkpass: ["application/vnd.apple.pkpass"],
280
- ppt: ["application/vnd.ms-powerpoint"],
281
- pptx: [
282
- "application/vnd.openxmlformats-officedocument.presentationml.presentation"
283
- ],
284
- py: ["text/x-python"],
285
- pyc: ["application/x-python-code"],
286
- rar: ["application/vnd.rar"],
287
- rs: ["text/rust"],
288
- rtf: ["application/rtf"],
289
- sh: ["application/x-sh"],
290
- sql: ["application/sql"],
291
- sse: ["text/event-stream"],
292
- svg: ["image/svg+xml"],
293
- tar: ["application/x-tar"],
294
- tif: ["image/tiff"],
295
- tiff: ["image/tiff"],
296
- toml: ["application/toml"],
297
- ts: ["text/typescript", "video/mp2t", "video/vnd.dlna.mpeg-tts"],
298
- ttf: ["application/font-sfnt", "font/ttf"],
299
- txt: ["text/plain"],
300
- usdz: ["model/vnd.usdz+zip"],
301
- vsd: ["application/vnd.visio"],
302
- vtt: ["text/vtt"],
303
- wasm: ["application/wasm"],
304
- wav: ["audio/wav"],
305
- weba: ["audio/webm"],
306
- webm: ["video/webm"],
307
- webmanifest: ["application/manifest+json"],
308
- webp: ["image/webp"],
309
- woff: ["font/woff"],
310
- woff2: ["font/woff2"],
311
- xhtml: ["application/xhtml+xml"],
312
- xls: ["application/vnd.ms-excel"],
313
- xlsx: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
314
- xml: ["application/xml", "text/xml"],
315
- xul: ["application/vnd.mozilla.xul+xml"],
316
- yaml: ["application/yaml"],
317
- yml: ["application/yaml"],
318
- zip: ["application/zip", "application/x-zip-compressed"],
319
- "3gp": ["video/3gpp"],
320
- "3g2": ["video/3gpp2"],
321
- "7z": ["application/x-7z-compressed"]
322
- };
323
- var mimeToExt = {
324
- "application/dash+xml": ["mpd"],
325
- "application/epub+zip": ["epub"],
326
- "application/font-sfnt": ["ttf"],
327
- "application/gzip": ["gz"],
328
- "application/java-archive": ["jar"],
329
- "application/json": ["json"],
330
- "application/ld+json": ["jsonld"],
331
- "application/manifest+json": ["webmanifest"],
332
- "application/msword": ["doc"],
333
- "application/node": ["node", "js"],
334
- "application/octet-stream": ["bin", "obj"],
335
- "application/ogg": ["ogx"],
336
- "application/pdf": ["pdf"],
337
- "application/rtf": ["rtf"],
338
- "application/sql": ["sql"],
339
- "application/toml": ["toml"],
340
- "application/vnd.amazon.ebook": ["azw"],
341
- "application/vnd.apple.installer+xml": ["mpkg"],
342
- "application/vnd.apple.mpegurl": ["m3u8"],
343
- "application/vnd.apple.pkpass": ["pkpass"],
344
- "application/vnd.mozilla.xul+xml": ["xul"],
345
- "application/vnd.ms-excel": ["xls"],
346
- "application/vnd.ms-fontobject": ["eot"],
347
- "application/vnd.ms-powerpoint": ["ppt"],
348
- "application/vnd.oasis.opendocument.presentation": ["odp"],
349
- "application/vnd.oasis.opendocument.spreadsheet": ["ods"],
350
- "application/vnd.oasis.opendocument.text": ["odt"],
351
- "application/vnd.openxmlformats-officedocument.presentationml.presentation": [
352
- "pptx"
353
- ],
354
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"],
355
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
356
- "docx"
357
- ],
358
- "application/vnd.rar": ["rar"],
359
- "application/vnd.visio": ["vsd"],
360
- "application/wasm": ["wasm"],
361
- "application/x-7z-compressed": ["7z"],
362
- "application/x-abiword": ["abw"],
363
- "application/x-bzip": ["bz"],
364
- "application/x-bzip2": ["bz2"],
365
- "application/x-cdf": ["cda"],
366
- "application/x-csh": ["csh"],
367
- "application/x-freearc": ["arc"],
368
- "application/x-gzip": ["gz"],
369
- "application/x-httpd-php": ["php"],
370
- "application/x-mdx": ["mdx"],
371
- "application/x-ndjson": ["ndjson"],
372
- "application/x-python-code": ["pyc"],
373
- "application/x-sh": ["sh"],
374
- "application/x-tar": ["tar"],
375
- "application/x-zip-compressed": ["zip"],
376
- "application/xhtml+xml": ["xhtml"],
377
- "application/xml": ["xml", "mtlx"],
378
- "application/yaml": ["yml", "yaml"],
379
- "application/zip": ["zip"],
380
- "audio/aac": ["aac"],
381
- "audio/midi": ["mid"],
382
- "audio/mp4": ["m4a"],
383
- "audio/mpeg": ["mp3"],
384
- "audio/ogg": ["opus", "ogg", "oga"],
385
- "audio/wav": ["wav"],
386
- "audio/webm": ["weba"],
387
- "audio/x-midi": ["midi"],
388
- "font/otf": ["otf"],
389
- "font/ttf": ["ttf"],
390
- "font/woff": ["woff"],
391
- "font/woff2": ["woff2"],
392
- "haptics/hjif": ["hjif"],
393
- "haptics/hmpg": ["hmpg"],
394
- "haptics/ivs": ["ivs", "ivt"],
395
- "image/aces": ["aces"],
396
- "image/apng": ["apng"],
397
- "image/avci": ["avci"],
398
- "image/avif": ["avif"],
399
- "image/bmp": ["bmp"],
400
- "image/dpx": ["dpx"],
401
- "image/emf": ["emf"],
402
- "image/gif": ["gif"],
403
- "image/jpeg": ["jpg", "jpeg", "jpe", "jif", "jfif", "pjp", "pjpeg"],
404
- "image/ktx": ["ktx"],
405
- "image/ktx2": ["ktx2"],
406
- "image/png": ["png"],
407
- "image/svg+xml": ["svg"],
408
- "image/tiff": ["tiff", "tif"],
409
- "image/vnd.microsoft.icon": ["ico"],
410
- "image/webp": ["webp"],
411
- "image/x-icon": ["cur", "ico"],
412
- "model/gltf-binary": ["glb"],
413
- "model/gltf+json": ["gltf"],
414
- "model/obj": ["obj"],
415
- "model/vnd.usdz+zip": ["usdz"],
416
- "multipart/voice-message": ["bin"],
417
- "text/calendar": ["ics"],
418
- "text/css": ["css"],
419
- "text/csv": ["csv"],
420
- "text/event-stream": ["sse"],
421
- "text/html": ["html", "htm"],
422
- "text/javascript": ["js", "mjs", "cjs"],
423
- "text/markdown": ["md"],
424
- "text/plain": ["txt"],
425
- "text/rust": ["rs"],
426
- "text/typescript": ["ts"],
427
- "text/vtt": ["vtt"],
428
- "text/xml": ["xml"],
429
- "text/x-python": ["py"],
430
- "video/3gpp": ["3gp"],
431
- "video/3gpp2": ["3g2"],
432
- "video/mp2t": ["ts"],
433
- "video/mp4": ["mp4", "m4v"],
434
- "video/mpeg": ["mpeg"],
435
- "video/ogg": ["ogv"],
436
- "video/vnd.dlna.mpeg-tts": ["ts"],
437
- "video/webm": ["webm"],
438
- "video/x-msvideo": ["avi"]
439
- };
440
- var MimeService = class extends UrlService {
441
- static {
442
- __name(this, "MimeService");
443
- }
444
- constructor() {
445
- super();
446
- }
447
- mimeTypeObj = extMimeMap;
448
- toExtObj = mimeToExt;
449
- compareMimeToExt(p = "mime") {
450
- let a = {};
451
- if (p === "mime") {
452
- for (const [_key, vals] of Object.entries(extMimeMap)) {
453
- for (const val of vals) {
454
- a[val] = (a[val] ?? 0) + 1;
455
- }
456
- }
457
- for (const [key, _val] of Object.entries(mimeToExt)) {
458
- a[key] = (a[key] ?? 0) + 1;
459
- }
460
- return Object.fromEntries(
461
- Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
462
- );
463
- } else {
464
- for (const [_key, vals] of Object.entries(mimeToExt)) {
465
- for (const val of vals) {
466
- a[val] = (a[val] ?? 0) + 1;
467
- }
468
- }
469
- for (const [key, _val] of Object.entries(extMimeMap)) {
470
- a[key] = (a[key] ?? 0) + 1;
471
- }
472
- return Object.fromEntries(
473
- Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
474
- );
475
- }
476
- }
477
- mimeToExt(mime) {
478
- const extensions = this.toExtObj[mime];
479
- if (extensions.length === 1) return extensions[0];
480
- if (extensions.length === 2) {
481
- return extensions[0];
482
- }
483
- if (extensions.length === 3) {
484
- if (mime === "audio/ogg") return "ogg";
485
- return extensions[0];
486
- }
487
- if (extensions.length === 7) {
488
- return extensions[0];
489
- }
490
- return extensions[0];
491
- }
492
- assetType(url) {
493
- const parsed = this.parseUrl(url);
494
- if (!parsed) return void 0;
495
- const ext = parsed.pathname.split(/([.])/g)?.reverse()?.[0]?.toLowerCase();
496
- return ext && ext in this.mimeTypeObj ? ext : void 0;
497
- }
498
- getMimes(ext) {
499
- return this.mimeTypeObj[ext];
500
- }
501
- getMimeFor(ext, opts) {
502
- const mimes = this.getMimes(ext);
503
- if (mimes.length === 1) return mimes[0];
504
- if (opts?.type) {
505
- const found = mimes.find((mime) => mime.startsWith(opts.type + "/"));
506
- return found ?? mimes[0];
507
- }
508
- return mimes[0];
509
- }
510
- isMimeFor(ext, mime) {
511
- return this.getMimes(ext).find((s) => s === mime);
512
- }
513
- getMimeTypeForPath(path, opts) {
514
- const ext = this.assetType(path);
515
- if (!ext) return "application/octet-stream";
516
- return this.getMimeFor(ext, opts);
517
- }
518
- };
519
-
520
- // src/image/index.ts
521
- var ImageService = class extends MimeService {
522
- static {
523
- __name(this, "ImageService");
524
- }
525
- parseExif(buffer, app1Pos, app1Size) {
526
- const exifHeader = buffer.toString("ascii", app1Pos + 2, app1Pos + 8);
527
- if (exifHeader !== "Exif\0\0")
528
- return { orientation: null, dateTimeOriginal: null };
529
- let tiffPos = app1Pos + 8;
530
- const app1End = app1Pos + app1Size;
531
- if (tiffPos + 10 > app1End)
532
- return { orientation: null, dateTimeOriginal: null };
533
- const byteOrder = buffer.toString("ascii", tiffPos, tiffPos + 2);
534
- const littleEndian = byteOrder === "II";
535
- const readUInt16 = littleEndian ? buffer.readUInt16LE.bind(buffer) : buffer.readUInt16BE.bind(buffer);
536
- const readUInt32 = littleEndian ? buffer.readUInt32LE.bind(buffer) : buffer.readUInt32BE.bind(buffer);
537
- if (readUInt16(tiffPos + 2) !== 42)
538
- return { orientation: null, dateTimeOriginal: null };
539
- let ifdOffset = readUInt32(tiffPos + 4);
540
- tiffPos += ifdOffset;
541
- const numEntries = readUInt16(tiffPos);
542
- tiffPos += 2;
543
- let orientation = null;
544
- let dateTimeOriginal = null;
545
- for (let i = 0; i < numEntries; i++) {
546
- const tag = readUInt16(tiffPos), type = readUInt16(tiffPos + 2), count = readUInt32(tiffPos + 4), valueOffset = tiffPos + 8;
547
- if (tag === 274 && type === 3 && count === 1) {
548
- orientation = readUInt16(valueOffset);
549
- } else if (tag === 36867 && type === 2 && count === 20) {
550
- const offset = readUInt32(valueOffset);
551
- if (app1Pos + 2 + offset + 19 > app1End) {
552
- dateTimeOriginal = null;
553
- } else {
554
- dateTimeOriginal = buffer.toString("ascii", app1Pos + 2 + offset, app1Pos + 2 + offset + 19).trim();
555
- }
556
- }
557
- tiffPos += 12;
558
- }
559
- return { orientation, dateTimeOriginal };
560
- }
561
- parseXmpFromAvif(buffer, meta, _ipco) {
562
- const iinf = this.findBox(
563
- buffer,
564
- "iinf",
565
- meta.pos + 4,
566
- meta.pos + meta.size
567
- );
568
- if (!iinf) return null;
569
- let pos = iinf.pos;
570
- const version = buffer[pos++];
571
- const itemCount = version === 0 ? buffer.readUInt16BE(pos) : buffer.readUInt32BE(pos);
572
- pos += version === 0 ? 2 : 4;
573
- let xmpItemId;
574
- for (let i = 0; i < itemCount; i++) {
575
- const infeStart = pos;
576
- const infeSize = buffer.readUInt32BE(pos);
577
- if (buffer.toString("ascii", pos + 4, pos + 8) !== "infe") break;
578
- pos += 8;
579
- const infeVersion = buffer?.[pos++];
580
- if (!infeVersion) return null;
581
- const itemId = infeVersion < 2 ? buffer.readUInt16BE(pos) : buffer.readUInt32BE(pos);
582
- pos += infeVersion < 2 ? 2 : 4;
583
- pos += 2;
584
- const itemType = buffer.toString("ascii", pos, pos + 4);
585
- pos += 4;
586
- let nameEnd = pos;
587
- while (buffer[nameEnd] !== 0 && nameEnd < infeStart + infeSize) nameEnd++;
588
- const _itemName = buffer.toString("ascii", pos, nameEnd);
589
- pos = nameEnd + 1;
590
- if (itemType === "mime") {
591
- let ctEnd = pos;
592
- while (buffer[ctEnd] !== 0 && ctEnd < infeStart + infeSize) ctEnd++;
593
- const contentType = buffer.toString("ascii", pos, ctEnd);
594
- if (contentType === "application/rdf+xml") {
595
- xmpItemId = itemId;
596
- break;
597
- }
598
- pos = ctEnd + 1;
599
- }
600
- pos = infeStart + infeSize;
601
- }
602
- if (!xmpItemId) return null;
603
- const iloc = this.findBox(
604
- buffer,
605
- "iloc",
606
- meta.pos + 4,
607
- meta.pos + meta.size
608
- );
609
- if (!iloc) return null;
610
- pos = iloc.pos;
611
- const ilocVersion = buffer[pos++];
612
- const sizes = buffer?.[pos++];
613
- if (!sizes) return null;
614
- const offsetSize = sizes >> 4 & 15;
615
- const lengthSize = sizes & 15;
616
- let indexSize = 0;
617
- if (ilocVersion === 1 || ilocVersion === 2) {
618
- const indexSizes = buffer?.[pos++];
619
- if (!indexSizes) return null;
620
- indexSize = indexSizes >> 4 & 15;
621
- }
622
- if (!ilocVersion) return null;
623
- let buffpos = buffer?.[pos++];
624
- if (!buffpos) return null;
625
- const baseOffsetSize = ilocVersion < 2 ? 0 : buffpos >> 4 & 15;
626
- const itemCountIloc = ilocVersion < 2 ? buffer.readUInt16BE(pos) : buffer.readUInt32BE(pos);
627
- pos += ilocVersion < 2 ? 2 : 4;
628
- let xmpOffset = 0;
629
- let xmpLength = 0;
630
- for (let i = 0; i < itemCountIloc; i++) {
631
- const curItemId = ilocVersion < 2 ? buffer.readUInt16BE(pos) : buffer.readUInt32BE(pos);
632
- pos += ilocVersion < 2 ? 2 : 4;
633
- if (curItemId !== xmpItemId) {
634
- if (ilocVersion === 1 || ilocVersion === 2) pos += 2;
635
- pos += 2;
636
- pos += baseOffsetSize;
637
- const extentCount2 = buffer.readUInt16BE(pos);
638
- pos += 2;
639
- for (let e = 0; e < extentCount2; e++) {
640
- if (indexSize > 0) pos += indexSize;
641
- pos += offsetSize + lengthSize;
642
- }
643
- continue;
644
- }
645
- if (ilocVersion === 1 || ilocVersion === 2) {
646
- const constructionMethod = buffer.readUInt16BE(pos);
647
- pos += 2;
648
- if (constructionMethod !== 0) return null;
649
- }
650
- pos += 2;
651
- const baseOffset = this.readVarSize(buffer, pos, baseOffsetSize);
652
- pos += baseOffsetSize;
653
- const extentCount = buffer.readUInt16BE(pos);
654
- pos += 2;
655
- if (extentCount !== 1) return null;
656
- if (indexSize > 0) pos += indexSize;
657
- const extentOffset = this.readVarSize(buffer, pos, offsetSize);
658
- pos += offsetSize;
659
- const extentLength = this.readVarSize(buffer, pos, lengthSize);
660
- xmpOffset = baseOffset + extentOffset;
661
- xmpLength = extentLength;
662
- break;
663
- }
664
- if (xmpOffset === 0 || xmpLength === 0 || xmpOffset + xmpLength > buffer.length)
665
- return null;
666
- return buffer.toString("utf8", xmpOffset, xmpOffset + xmpLength);
667
- }
668
- readVarSize(buffer, pos, size) {
669
- if (size === 0) return 0;
670
- if (size === 1 && buffer?.[pos]) return buffer?.[pos];
671
- if (size === 2) return buffer.readUInt16BE(pos);
672
- if (size === 3) {
673
- let pos1 = buffer?.[pos + 1], pos2 = buffer?.[pos + 2];
674
- if (buffer?.[pos] && pos1 && pos2) {
675
- return buffer[pos] << 16 | pos1 << 8 | pos2;
676
- }
677
- throw new Error("Invalid var size");
678
- }
679
- if (size === 4) return buffer.readUInt32BE(pos);
680
- if (size === 8) return Number(buffer.readBigUInt64BE(pos));
681
- throw new Error("Invalid var size");
682
- }
683
- findBox(buffer, type, start = 0, end = buffer.length) {
684
- let pos = start;
685
- while (pos < end) {
686
- let boxSize = buffer.readUInt32BE(pos);
687
- let boxType = buffer.toString("ascii", pos + 4, pos + 8);
688
- let hdrSize = 8;
689
- if (boxSize === 1) {
690
- boxSize = Number(buffer.readBigUInt64BE(pos + 8));
691
- hdrSize = 16;
692
- } else if (boxSize === 0) {
693
- boxSize = end - pos;
694
- }
695
- if (boxType === type) {
696
- return { pos: pos + hdrSize, size: boxSize - hdrSize };
697
- }
698
- pos += boxSize;
699
- }
700
- return null;
701
- }
702
- getImageSpecsWorkup(buffer) {
703
- if (buffer?.length >= 24 && buffer?.[0] === 137 && buffer?.[1] === 80 && buffer?.[2] === 78 && buffer?.[3] === 71 && buffer?.[4] === 13 && buffer?.[5] === 10 && buffer?.[6] === 26 && buffer?.[7] === 10) {
704
- if (buffer.readUint32BE(8) !== 13 || buffer?.[12] !== 73 || buffer?.[13] !== 72 || buffer?.[14] !== 68 || buffer?.[15] !== 82) {
705
- throw new Error("IHDR Chunk of png not found or incorrect.");
706
- }
707
- const colorType = buffer[25];
708
- let colorSpace;
709
- let hasAlpha = false;
710
- switch (colorType) {
711
- case 0:
712
- colorSpace = "grayscale";
713
- break;
714
- case 2:
715
- colorSpace = "rgb";
716
- break;
717
- case 3:
718
- colorSpace = "indexed";
719
- break;
720
- case 4:
721
- colorSpace = "grayscale-alpha";
722
- hasAlpha = true;
723
- break;
724
- case 6:
725
- colorSpace = "rgba";
726
- hasAlpha = true;
727
- break;
728
- default:
729
- colorSpace = "unknown";
730
- }
731
- const width = buffer.readUInt32BE(16);
732
- const height = buffer.readUInt32BE(20);
733
- let frames = 1;
734
- let animated = false;
735
- let iccProfile = null;
736
- let exifDateTimeOriginal = null;
737
- let orientation = null;
738
- let pos = 33;
739
- while (pos < buffer.length - 12) {
740
- const chunkLen = buffer.readUInt32BE(pos);
741
- const chunkType = buffer.toString("ascii", pos + 4, pos + 8);
742
- const chunkData = pos + 8;
743
- if (chunkType === "acTL") {
744
- animated = true;
745
- frames = buffer.readUInt32BE(chunkData);
746
- } else if (chunkType === "iCCP") {
747
- const nameEnd = buffer.indexOf(0, chunkData);
748
- const profileName = buffer.toString("ascii", chunkData, nameEnd);
749
- iccProfile = profileName || "embedded";
750
- } else if (chunkType === "tIME") {
751
- const month = buffer?.[chunkData + 2], day = buffer?.[chunkData + 3], hour = buffer?.[chunkData + 4], minute = buffer?.[chunkData + 5], second = buffer?.[chunkData + 6];
752
- if (typeof month !== "undefined" && typeof day !== "undefined" && typeof hour !== "undefined" && typeof minute !== "undefined" && typeof second !== "undefined") {
753
- const year = buffer.readUInt16BE(chunkData);
754
- exifDateTimeOriginal = `${year}:${month.toString().padStart(2, "0")}:${day.toString().padStart(2, "0")} ${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}:${second.toString().padStart(2, "0")}`;
755
- }
756
- } else if (chunkType === "IDAT") {
757
- break;
758
- }
759
- pos += 12 + chunkLen;
760
- }
761
- return {
762
- width,
763
- height,
764
- format: "png",
765
- frames,
766
- animated,
767
- hasAlpha,
768
- orientation,
769
- aspectRatio: width / height,
770
- colorSpace,
771
- iccProfile,
772
- exifDateTimeOriginal
773
- };
774
- }
775
- if (buffer.length >= 10 && buffer[0] === 255 && buffer[1] === 216) {
776
- let pos = 2, colorSpace = "unknown", hasAlpha = false, width = 0, height = 0, iccProfile = null, orientation = null, exifDateTimeOriginal = null;
777
- while (pos < buffer.length - 10) {
778
- if (buffer[pos] !== 255) {
779
- throw new Error("Invalid JPEG file");
780
- }
781
- const marker = buffer[pos + 1];
782
- if (marker === 218) break;
783
- const segmentSize = buffer.readUInt16BE(pos + 2);
784
- if (!marker) {
785
- throw new Error("no marker for jpeg");
786
- }
787
- if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
788
- const numComponents = buffer[pos + 4];
789
- switch (numComponents) {
790
- case 1:
791
- colorSpace = "grayscale";
792
- break;
793
- case 3:
794
- colorSpace = "ycbcr";
795
- break;
796
- // Most common for RGB JPEGs (stored as YCbCr)
797
- case 4:
798
- colorSpace = "ycck";
799
- break;
800
- // YCCK for CMYK with alpha-like, but no true alpha
801
- default:
802
- colorSpace = "unknown";
803
- }
804
- width = buffer.readUInt16BE(pos + 7);
805
- height = buffer.readUInt16BE(pos + 5);
806
- } else if (marker === 225) {
807
- const { orientation: ori, dateTimeOriginal } = this.parseExif(
808
- buffer,
809
- pos,
810
- segmentSize
811
- );
812
- orientation = ori;
813
- exifDateTimeOriginal = dateTimeOriginal;
814
- } else if (marker === 226) {
815
- const iccHeader = buffer.toString("ascii", pos + 4, pos + 18);
816
- if (iccHeader.startsWith("ICC_PROFILE")) {
817
- iccProfile = "embedded";
818
- }
819
- }
820
- pos += segmentSize + 2;
821
- }
822
- if (width === 0) throw new Error("No dimensions found in JPEG file");
823
- return {
824
- width,
825
- height,
826
- format: "jpeg",
827
- frames: 1,
828
- animated: false,
829
- // JPEG not animated
830
- hasAlpha,
831
- orientation,
832
- aspectRatio: width / height,
833
- colorSpace,
834
- iccProfile,
835
- exifDateTimeOriginal
836
- };
837
- }
838
- const gifHeader = buffer.toString("ascii", 0, 6);
839
- if (buffer.length >= 10 && (gifHeader === "GIF87a" || gifHeader === "GIF89a")) {
840
- const width = buffer.readUInt16LE(6), height = buffer.readUInt16LE(8);
841
- let frames = 0;
842
- let pos = 13;
843
- let bufTen = buffer?.[10];
844
- if (typeof bufTen === "undefined") {
845
- pos = 13;
846
- frames = 0;
847
- } else if (bufTen & 128) pos += 3 << (bufTen & 7) + 1;
848
- while (pos < buffer.length) {
849
- if (buffer[pos] === 33) {
850
- pos += 2;
851
- let subSize = buffer?.[pos];
852
- while (subSize && subSize > 0) {
853
- pos += subSize + 1;
854
- subSize = buffer?.[pos];
855
- }
856
- pos++;
857
- } else if (buffer?.[pos] && buffer?.[pos] === 44) {
858
- frames++;
859
- pos += 10;
860
- let b = buffer?.[pos - 1];
861
- if (typeof b !== "undefined" && b & 128)
862
- pos += 3 << (b & 7) + 1;
863
- pos++;
864
- let dataSize = buffer?.[pos];
865
- while (dataSize && dataSize > 0) {
866
- pos += dataSize + 1;
867
- dataSize = buffer[pos];
868
- }
869
- pos++;
870
- } else if (buffer[pos] === 59) {
871
- break;
872
- } else {
873
- pos++;
874
- }
875
- }
876
- return {
877
- width,
878
- height,
879
- format: "gif",
880
- frames,
881
- animated: frames > 1,
882
- hasAlpha: null,
883
- // GIF transparency is per-pixel binary, not full alpha; set null or true if transparent color exists, but complex
884
- orientation: null,
885
- // No orientation in GIF
886
- aspectRatio: width / height,
887
- colorSpace: "indexed",
888
- iccProfile: null,
889
- // No ICC in GIF
890
- exifDateTimeOriginal: null
891
- // No EXIF in GIF
892
- };
893
- }
894
- if (buffer.length >= 26 && buffer?.[0] === 66 && buffer?.[1] === 77) {
895
- const width = buffer.readInt32LE(18);
896
- const height = Math.abs(buffer.readInt32LE(22));
897
- const bitDepth = buffer.readUInt16LE(28);
898
- let colorSpace = bitDepth <= 8 ? "indexed" : "rgb";
899
- return {
900
- width,
901
- height,
902
- format: "bmp",
903
- frames: 1,
904
- animated: false,
905
- hasAlpha: null,
906
- // Some BMP have alpha in 32bpp, check if bitDepth===32 && compression===3 (bitfields with alpha)
907
- orientation: buffer.readInt32LE(22) < 0 ? 1 : 6,
908
- // Negative height means top-down (orientation 1), positive bottom-up (like 6, but simplified)
909
- aspectRatio: width / height,
910
- colorSpace,
911
- iccProfile: null,
912
- // Rare in BMP
913
- exifDateTimeOriginal: null
914
- };
915
- }
916
- if (buffer.length >= 30 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP") {
917
- const chunkType = buffer.toString("ascii", 12, 16);
918
- let colorSpace = "unknown";
919
- let hasAlpha = false;
920
- let width = 0;
921
- let height = 0;
922
- let frames = 1;
923
- let animated = false;
924
- let iccProfile = null;
925
- if (chunkType === "VP8X") {
926
- const flags = buffer?.[20];
927
- colorSpace = flags ? flags & 2 ? "rgba" : "rgb" : "unknown";
928
- hasAlpha = flags ? !!(flags & 2) : false;
929
- animated = flags ? !!(flags & 1) : false;
930
- let widthSubtractOne = 0;
931
- let heightSubtractOne = 0;
932
- if (buffer?.[24] && buffer?.[25] && buffer?.[26]) {
933
- widthSubtractOne = buffer[24] | buffer[25] << 8 | buffer[26] << 16;
934
- }
935
- if (buffer?.[27] && buffer?.[28] && buffer?.[29]) {
936
- heightSubtractOne = buffer[27] | buffer[28] << 8 | buffer[29] << 16;
937
- }
938
- width = widthSubtractOne + 1;
939
- height = heightSubtractOne + 1;
940
- if (animated) {
941
- let pos = 30;
942
- frames = 0;
943
- while (pos < buffer.length - 8) {
944
- const subChunkType = buffer.toString("ascii", pos, pos + 4);
945
- const subChunkSize = buffer.readUInt32LE(pos + 4);
946
- if (subChunkType === "ICCP") {
947
- iccProfile = "embedded";
948
- } else if (subChunkType === "ANMF") {
949
- frames++;
950
- }
951
- pos += 8 + subChunkSize + subChunkSize % 2;
952
- }
953
- }
954
- } else if (chunkType === "VP8 ") {
955
- colorSpace = "rgb";
956
- hasAlpha = false;
957
- const dataStart = 20;
958
- if (buffer?.[dataStart + 3] !== 157 || buffer?.[dataStart + 4] !== 1 || buffer?.[dataStart + 5] !== 42) {
959
- throw new Error("Invalid VP8 keyframe");
960
- }
961
- width = buffer.readUInt16LE(dataStart + 6) & 16383;
962
- height = buffer.readUInt16LE(dataStart + 8) & 16383;
963
- } else if (chunkType === "VP8L") {
964
- const dataStart = 20;
965
- if (buffer?.[dataStart] !== 47) {
966
- throw new Error("Invalid VP8L signature");
967
- }
968
- const bits = buffer.readUInt32LE(dataStart + 1);
969
- if (bits >>> 29 !== 0) {
970
- throw new Error("Invalid VP8L version");
971
- }
972
- colorSpace = bits & 1 << 8 ? "rgba" : "rgb";
973
- hasAlpha = !!(bits & 1 << 8);
974
- width = 1 + (bits & 16383);
975
- height = 1 + (bits >> 14 & 16383);
976
- } else {
977
- throw new Error("Unsupported WebP chunk");
978
- }
979
- return {
980
- width,
981
- height,
982
- format: "webp",
983
- frames,
984
- animated,
985
- hasAlpha,
986
- orientation: null,
987
- // No standard orientation in WebP
988
- aspectRatio: width / height,
989
- colorSpace,
990
- iccProfile,
991
- exifDateTimeOriginal: null
992
- // Can have EXIF chunk, but rare; add if needed
993
- };
994
- }
995
- if (buffer.length >= 32 && buffer.toString("ascii", 4, 8) === "ftyp") {
996
- const ftyp = this.findBox(buffer, "ftyp");
997
- if (!ftyp) throw new Error("Invalid AVIF: No ftyp");
998
- const brands = buffer.toString("ascii", ftyp.pos, ftyp.pos + ftyp.size);
999
- const isAvif = brands.includes("avif");
1000
- const isAvis = brands.includes("avis");
1001
- if (!isAvif && !isAvis) throw new Error("Not an AVIF file");
1002
- const meta = this.findBox(buffer, "meta");
1003
- if (!meta) throw new Error("Invalid AVIF: No meta");
1004
- const metaSubStart = meta.pos + 4;
1005
- const metaSubEnd = meta.pos + meta.size;
1006
- const iprp = this.findBox(buffer, "iprp", metaSubStart, metaSubEnd);
1007
- if (!iprp) throw new Error("Invalid AVIF: No iprp");
1008
- const ipco = this.findBox(buffer, "ipco", iprp.pos, iprp.pos + iprp.size);
1009
- if (!ipco) throw new Error("Invalid AVIF: No ipco");
1010
- const ispe = this.findBox(buffer, "ispe", ipco.pos, ipco.pos + ipco.size);
1011
- if (!ispe) throw new Error("Invalid AVIF: No ispe");
1012
- if (buffer[ispe.pos] !== 0) throw new Error("Invalid ispe version");
1013
- const width = buffer.readUInt32BE(ispe.pos + 4);
1014
- const height = buffer.readUInt32BE(ispe.pos + 8);
1015
- let colorSpace = "rgb";
1016
- let hasAlpha = false;
1017
- let iccProfile = null;
1018
- const colr = this.findBox(buffer, "colr", ipco.pos, ipco.pos + ipco.size);
1019
- if (colr) {
1020
- const colrType = buffer.toString("ascii", colr.pos, colr.pos + 4);
1021
- if (colrType === "nclx") {
1022
- const matrix = buffer.readUInt16BE(colr.pos + 6);
1023
- colorSpace = matrix === 2 ? "rgb" : "ycbcr";
1024
- } else if (colrType === "rICC" || colrType === "prof") {
1025
- colorSpace = "unknown";
1026
- iccProfile = "embedded";
1027
- }
1028
- }
1029
- const auxC = this.findBox(buffer, "auxC", ipco.pos, ipco.pos + ipco.size);
1030
- if (auxC && buffer.toString("ascii", auxC.pos, auxC.pos + auxC.size).includes("alpha")) {
1031
- hasAlpha = true;
1032
- if (colorSpace === "rgb") {
1033
- colorSpace = "rgba";
1034
- } else if (colorSpace === "ycbcr") {
1035
- colorSpace = "ycck";
1036
- } else if (colorSpace === "grayscale" || colorSpace === "unknown") {
1037
- colorSpace = "grayscale-alpha";
1038
- }
1039
- }
1040
- const xmpXml = this.parseXmpFromAvif(buffer, meta, ipco);
1041
- let exifDateTimeOriginal = null;
1042
- if (xmpXml) {
1043
- let dateStart = xmpXml.indexOf('xmp:CreateDate="');
1044
- if (dateStart === -1)
1045
- dateStart = xmpXml.indexOf('photoshop:DateCreated="');
1046
- if (dateStart !== -1) {
1047
- dateStart += 16;
1048
- const dateEnd = xmpXml.indexOf('"', dateStart);
1049
- if (dateEnd !== -1) {
1050
- exifDateTimeOriginal = xmpXml.substring(dateStart, dateEnd);
1051
- }
1052
- }
1053
- }
1054
- let frames = 1;
1055
- let animated = isAvis;
1056
- if (animated) {
1057
- const iloc = this.findBox(buffer, "iloc", metaSubStart, metaSubEnd);
1058
- if (iloc) {
1059
- const version = buffer?.[iloc.pos] ?? 0;
1060
- const itemCountPos = iloc.pos + (version < 2 ? 4 : 6);
1061
- let itemCount = buffer?.readUInt16BE(itemCountPos) ?? 0;
1062
- if (version >= 2) itemCount = buffer?.readUInt32BE(itemCountPos) ?? 0;
1063
- frames = Math.max(1, Math.floor(itemCount / (hasAlpha ? 2 : 1)));
1064
- }
1065
- }
1066
- return {
1067
- width,
1068
- height,
1069
- format: "avif",
1070
- frames,
1071
- animated,
1072
- hasAlpha: hasAlpha ? true : null,
1073
- orientation: null,
1074
- // Can have 'irot' or 'imir' transforms, but rare
1075
- aspectRatio: width / height,
1076
- colorSpace,
1077
- iccProfile,
1078
- exifDateTimeOriginal
1079
- // Can have 'XMP' box, but parse XMP for date if needed
1080
- };
1081
- }
1082
- throw new Error("Unsupported image format or invalid file");
1083
- }
1084
- };
1085
-
1086
- // src/types/index.ts
1087
- var unitsObj = {
1088
- PB: 5,
1089
- TB: 4,
1090
- GB: 3,
1091
- MB: 2,
1092
- KB: 1,
1093
- B: 0
1094
- };
1095
-
1096
- // src/fs/index.ts
1097
- dotenv.config({ quiet: true });
1098
- var Fs = class extends ImageService {
1099
- constructor(cwd) {
1100
- super();
1101
- this.cwd = cwd;
1102
- cwd ??= process.cwd();
1103
- }
1104
- static {
1105
- __name(this, "Fs");
1106
- }
1107
- async getImageSpecs(filePath) {
1108
- const buffer = await this.fileToBufferAsync(filePath);
1109
- return this.getImageSpecsWorkup(buffer);
1110
- }
1111
- async getImageSpecsTmp(target) {
1112
- const buffer = await this.readTmpAsync(target);
1113
- return this.getImageSpecsWorkup(buffer);
1114
- }
1115
- get myEnv() {
1116
- return dotenv.config({ processEnv: {} });
1117
- }
1118
- get tmpDir() {
1119
- return (0, import_node_os.tmpdir)();
1120
- }
1121
- get tmpDirRelative() {
1122
- return (0, import_path.relative)(this.cwd, (0, import_node_os.tmpdir)());
1123
- }
1124
- parseDotEnv() {
1125
- return import_dotenv_expand.default.expand(this.myEnv);
1126
- }
1127
- /**
1128
- *
1129
- * @param target path to the file or directory to check for existence
1130
- * @returns true if the file or directory exists, false otherwise
1131
- * @example
1132
- * ```ts
1133
- * const fs = new Fs(process.cwd());
1134
- * const exists = fs.exists("my-file.txt");
1135
- * console.log(exists); // true if the file exists, false otherwise
1136
- * ```
1137
- * @description
1138
- * This method checks if a file or directory exists at the specified path input
1139
- *
1140
- * Additional Note:
1141
- *
1142
- * say you have a directory that begins with a dot, such as `.turbo`;
1143
- *
1144
- * in this scenario, both `./.turbo` and `.turbo` will return true if the directory exists
1145
- *
1146
- */
1147
- exists(target) {
1148
- if (!/\//gm.test(target)) {
1149
- if (/\./g.test(target)) {
1150
- return import_fs.default.existsSync((0, import_path.resolve)((0, import_path.join)(this.cwd, target)));
1151
- } else {
1152
- const statsSync = import_fs.default.statSync((0, import_path.resolve)((0, import_path.join)(this.cwd, target)), {
1153
- throwIfNoEntry: false
1154
- });
1155
- const isDir = statsSync?.isDirectory();
1156
- if (isDir) {
1157
- return isDir;
1158
- } else return false;
1159
- }
1160
- } else {
1161
- if (/\./g.test(target)) {
1162
- return import_fs.default.existsSync((0, import_path.relative)(this.cwd ?? process.cwd(), target));
1163
- } else {
1164
- const statsSync = import_fs.default.statSync((0, import_path.relative)(this.cwd, target), {
1165
- throwIfNoEntry: false
1166
- });
1167
- const isDir = statsSync?.isDirectory();
1168
- if (isDir) {
1169
- return isDir;
1170
- } else return false;
1171
- }
1172
- }
1173
- }
1174
- /**
1175
- *
1176
- * @param ms milliseconds to wait
1177
- * @returns a promise that resolves after the specified number of milliseconds
1178
- * @example
1179
- * ```ts
1180
- * const fs = new Fs(process.cwd());
1181
- * await fs.wait(1000); // waits for 1 second
1182
- * console.log("Done waiting!");
1183
- * ```
1184
- *
1185
- * Alternatively, you can use it like this:
1186
- * ```ts
1187
- * const fs = new Fs(process.cwd());
1188
- * fs.wait(1000).then(() => { // waits for 1 second
1189
- * console.log("Done waiting!");
1190
- * // do something after waiting
1191
- * });
1192
- * ```
1193
- *
1194
- * @description
1195
- * This method is useful for delaying execution in asynchronous code, such as when you need to wait for a file operation to complete or when you want to introduce a delay in a loop.
1196
- */
1197
- wait(ms) {
1198
- return new Promise((resolve2) => setTimeout(resolve2, ms));
1199
- }
1200
- /**
1201
- * Handles an array or readonly array of strings and/or Buffers, converting Buffers to strings
1202
- * @param arr An array or readonly array of strings and/or Buffers
1203
- * @returns An array of strings with Buffers converted to UTF-8 strings.
1204
- */
1205
- handleBuffStrArrUnion(arr) {
1206
- return arr.map(
1207
- (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
1208
- );
1209
- }
1210
- isRootPathTargeted(path) {
1211
- if (/^(?:\.\/|\.|\/|root|\.\.\/|~\/\.?|cwd|\.\/\.)$/g.test(path)) {
1212
- return true;
1213
- } else return false;
1214
- }
1215
- /**
1216
- *
1217
- * @param path path to the directory relative to the cwd
1218
- * @param options options for reading the directory, defaults to recursive
1219
- *
1220
- * The following two examples are equivalent:
1221
- *
1222
- * @example
1223
- * ```ts
1224
- * const fs = new Fs(process.cwd());
1225
- * const files = fs.readDir("./my-directory", { recursive: true });
1226
- * console.log(files);
1227
- * ```
1228
- * @example
1229
- * ```ts
1230
- * const fs = new Fs(process.cwd());
1231
- * const files = fs.readDir("my-directory", { recursive: true });
1232
- * console.log(files);
1233
- * ```
1234
- *
1235
- * @returns an array of strings representing the contents of the directory
1236
- */
1237
- readDir(path, options = {
1238
- recursive: true,
1239
- withFileTypes: false,
1240
- encoding: "utf-8"
1241
- }) {
1242
- if (this.isRootPathTargeted(path)) {
1243
- return this.handleBuffStrArrUnion(
1244
- import_fs.default.readdirSync((0, import_path.resolve)((0, import_path.join)(this.cwd, "./")), { ...options })
1245
- );
1246
- } else {
1247
- return this.handleBuffStrArrUnion(
1248
- import_fs.default.readdirSync(
1249
- (0, import_path.relative)(this.cwd ??= process.cwd(), path),
1250
- options
1251
- )
1252
- );
1253
- }
1254
- }
1255
- executeCommand = /* @__PURE__ */ __name(({
1256
- command,
1257
- ...options
1258
- }) => Buffer.from((0, import_child_process.execSync)(command, { ...options }).toJSON().data).toString(
1259
- "utf-8"
1260
- ), "executeCommand");
1261
- existsSync(path) {
1262
- return this.exists(path);
1263
- }
1264
- pathHandler(path) {
1265
- return /\//g.test(path) === true ? path.split(/([/])/gim).reverse().slice(2).reverse().join("") : path;
1266
- }
1267
- mkdirSync(path, options) {
1268
- return import_fs.default.mkdirSync((0, import_path.relative)(this.cwd, path), options);
1269
- }
1270
- units = unitsObj;
1271
- u = ["B", "KB", "MB", "GB", "TB", "PB"];
1272
- autoFileSizeRaw(size) {
1273
- let s = typeof size === "bigint" ? Number(size) : size;
1274
- let i = 0;
1275
- while (s >= 1024 && i < this.u.length - 1) {
1276
- s /= 1024;
1277
- i++;
1278
- }
1279
- return { value: s, unit: this.u[i] };
1280
- }
1281
- getSize(size, target, opts = { decimals: 4, includeUnits: true }) {
1282
- const { decimals, includeUnits } = opts;
1283
- if (target === "auto") {
1284
- const { value, unit } = this.autoFileSizeRaw(size);
1285
- const rounded2 = value.toFixed(decimals);
1286
- return includeUnits ? `${rounded2} ${unit}` : Number.parseFloat(rounded2);
1287
- }
1288
- const key = target.toUpperCase();
1289
- const exp = this.units[key];
1290
- const divisor = typeof size === "bigint" ? 1024n ** BigInt(exp) : 1024 ** exp;
1291
- let v = 0;
1292
- if (typeof size === "bigint" || typeof divisor === "bigint") {
1293
- if (typeof size === "bigint" && typeof divisor === "bigint")
1294
- v = Number(size / divisor);
1295
- else if (typeof size !== "bigint" && typeof divisor === "bigint")
1296
- v = size / Number(divisor);
1297
- else if (typeof size === "bigint" && typeof divisor !== "bigint")
1298
- v = Number(size) / divisor;
1299
- } else if (typeof size === "number" && typeof divisor === "number") {
1300
- v = size / divisor;
1301
- }
1302
- const rounded = v.toFixed(decimals);
1303
- return includeUnits ? `${rounded} ${key}` : Number.parseFloat(rounded);
1304
- }
1305
- fileSizeMb(path) {
1306
- return import_fs.default.statSync((0, import_path.relative)(this.cwd, path)).size / (1024 * 1024);
1307
- }
1308
- fileSize(path, target, opts) {
1309
- if (!this.exists(path)) throw new Error(`path ${path} does not exist`);
1310
- else {
1311
- return this.getSize(
1312
- import_fs.default.statSync((0, import_path.relative)(this.cwd, path)).size,
1313
- target,
1314
- opts
1315
- );
1316
- }
1317
- }
1318
- generateDirIfDNE(path, options) {
1319
- if (this.existsSync(path)) return;
1320
- else {
1321
- return this.mkdirSync(path, options);
1322
- }
1323
- }
1324
- withWs(path, data, options) {
1325
- try {
1326
- if (/\//g.test(path) === true) {
1327
- return this.generateDirIfDNE(this.pathHandler(path), {
1328
- recursive: true
1329
- });
1330
- } else return path;
1331
- } catch (error) {
1332
- console.error(
1333
- `[withWs error]: `.concat(
1334
- typeof error === "string" ? error : JSON.stringify(error, null, 2)
1335
- )
1336
- );
1337
- } finally {
1338
- return import_fs.default.createWriteStream(
1339
- (0, import_path.relative)(this.cwd ?? process.cwd(), path),
1340
- typeof options !== "undefined" ? typeof options === "object" ? options : options : { autoClose: true }
1341
- ).write(Buffer.from(Buffer.from(data).toJSON().data));
1342
- }
1343
- }
1344
- writeFileAsync = /* @__PURE__ */ __name(async (path, data, options) => {
1345
- try {
1346
- if (/\//g.test(path) === true)
1347
- return this.generateDirIfDNE(this.pathHandler(path), {
1348
- recursive: true
1349
- });
1350
- else return path;
1351
- } catch (error) {
1352
- console.error(
1353
- `[writeFileAsync error]: `.concat(
1354
- error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error, null, 2)
1355
- )
1356
- );
1357
- } finally {
1358
- return await import_promises.default.writeFile(
1359
- (0, import_path.relative)(this.cwd ?? process.cwd(), path),
1360
- Buffer.from(Buffer.from(data).toJSON().data),
1361
- options
1362
- );
1363
- }
1364
- }, "writeFileAsync");
1365
- async unlink(path) {
1366
- if (this.existsSync(path)) {
1367
- return await import_promises.default.unlink((0, import_path.relative)(this.cwd, path));
1368
- } else {
1369
- throw new Error(`input path ${path} does not exist`);
1370
- }
1371
- }
1372
- rmFile(filePath) {
1373
- if (this.exists(filePath)) {
1374
- if (this.isRootPathTargeted(filePath)) {
1375
- import_fs.default.rmSync((0, import_path.resolve)((0, import_path.join)(this.cwd, filePath)));
1376
- } else import_fs.default.rmSync((0, import_path.resolve)(this.cwd, filePath));
1377
- } else return;
1378
- }
1379
- async rmdir(dir, options) {
1380
- const resolved = (0, import_path.relative)(this.cwd, dir);
1381
- if (this.exists(dir)) {
1382
- return import_promises.default.rmdir((0, import_path.relative)(this.cwd, dir), options);
1383
- } else {
1384
- throw new Error(`directory ${resolved} does not exist`);
1385
- }
1386
- }
1387
- rmDirSync(dir) {
1388
- const resolved = (0, import_path.resolve)(this.cwd, dir);
1389
- if (this.exists(dir)) {
1390
- return import_fs.default.rm(resolved, { force: true, recursive: true }, (err) => {
1391
- if (err?.message) {
1392
- console.error(err?.message);
1393
- }
1394
- });
1395
- } else {
1396
- throw new Error(`directory ${resolved} does not exist`);
1397
- }
1398
- }
1399
- fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
1400
- import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
1401
- ), "fileToBuffer");
1402
- fileToBufferAsync = /* @__PURE__ */ __name(async (path) => {
1403
- return await import_promises.default.readFile((0, import_path.relative)(this.cwd, path));
1404
- }, "fileToBufferAsync");
1405
- dirContainsDir(readDir, targetDir, options) {
1406
- return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
1407
- }
1408
- async assetToBuffer(path) {
1409
- const [fetcher] = await Promise.all([
1410
- fetch(path).then((t) => t.arrayBuffer())
1411
- ]);
1412
- const mime = this.getMimeTypeForPath(path);
1413
- const b64encodedData = `data:${mime};base64, ${Buffer.from(fetcher).toString("base64")}`;
1414
- const extension = this.assetType(path) ?? "txt";
1415
- return {
1416
- b64encodedData,
1417
- extension
1418
- };
1419
- }
1420
- async assetToBufferView(path) {
1421
- const response = await fetch(path, { method: "GET" });
1422
- if (!response.ok) {
1423
- throw new Error(`Failed to fetch asset: ${response.statusText}`);
1424
- }
1425
- const reader = response.body?.getReader();
1426
- if (reader) {
1427
- const chunks = Array.of();
1428
- while (true) {
1429
- const { done, value } = await reader.read();
1430
- if (done) break;
1431
- if (value) chunks.push(value);
1432
- }
1433
- const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
1434
- const completeBuffer = new Uint8Array(totalLength);
1435
- let offset = 0;
1436
- for (const chunk of chunks) {
1437
- completeBuffer.set(chunk, offset);
1438
- offset += chunk.length;
1439
- }
1440
- const mime = this.getMimeTypeForPath(path);
1441
- const b64encodedData = `data:${mime};base64, ${Buffer.from(completeBuffer).toString("base64")}`;
1442
- const extension = this.assetType(path);
1443
- return { b64encodedData, extension };
1444
- } else {
1445
- const arrayBuffer = await response.arrayBuffer();
1446
- const mime = this.getMimeTypeForPath(path);
1447
- const b64encodedData = `data:${mime};base64, ${Buffer.from(arrayBuffer).toString("base64")}`;
1448
- const extension = this.assetType(path);
1449
- return { b64encodedData, extension };
1450
- }
1451
- }
1452
- formatHelper(f) {
1453
- if (/([A-Za-z]+-[A-Za-z]+)/g.test(f) === true) {
1454
- const formatting = f.split(/-/g).map((v) => v.substring(0, 1).toUpperCase().concat(v.substring(1))).join(" ");
1455
- return formatting;
1456
- } else return f.substring(0, 1).toUpperCase().concat(f.substring(1));
1457
- }
1458
- cleanDataUrl(props) {
1459
- return props.replace(
1460
- /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
1461
- ""
1462
- );
1463
- }
1464
- /**
1465
- *
1466
- * @param inputUrl remote url to fetch data from
1467
- * @param outputPath desired output path relative to the cwd
1468
- * @param useDetectedExtension optional, defaults to true
1469
- *
1470
- * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
1471
- *
1472
- * 🚫 'public/assets/image-1'
1473
- *
1474
- * ✅ 'public/assets/image-1.png'
1475
- */
1476
- async fetchRemoteWriteLocal(inputUrl, outputPath, useDetectedExtension = true) {
1477
- try {
1478
- const result = await this.assetToBufferView(inputUrl);
1479
- const cleanData = this.cleanDataUrl(result.b64encodedData);
1480
- const formattedPath = useDetectedExtension ? `${outputPath}.${result.extension}` : outputPath;
1481
- if (/\./g.test(formattedPath) === false) {
1482
- throw new Error(
1483
- "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension) or provide an output path without a file extension"
1484
- );
1485
- }
1486
- this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
1487
- } catch (err) {
1488
- return console.error(err);
1489
- }
1490
- }
1491
- knownToBlockHead(inputUrl) {
1492
- if (inputUrl.startsWith("https://github.com")) {
1493
- return "GET";
1494
- } else if (inputUrl.startsWith("https://raw.githubusercontent.com")) {
1495
- return "GET";
1496
- } else {
1497
- return "HEAD";
1498
- }
1499
- }
1500
- /**
1501
- *
1502
- * @param inputUrl remote url to fetch data from
1503
- * @param outputPath desired output path relative to the cwd
1504
- * @param useDetectedExtension optional, defaults to true
1505
- *
1506
- * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
1507
- *
1508
- * 🚫 'public/assets/image-1'
1509
- *
1510
- * ✅ 'public/assets/image-1.png'
1511
- *
1512
- * @description
1513
- * This method is designed for all files regardless of size, but especially for
1514
- * larger files that may not fit into memory (it intelligently determines the best approach on the fly)
1515
- * For files > 100 MB, it streams the data directly to disk instead of loading it all into memory
1516
- */
1517
- async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPathI, useDetectedExtension = true) {
1518
- if (!URL.canParse(inputUrl))
1519
- throw new Error(`invalid URL ${inputUrl} is unable to be parsed`);
1520
- const MAX_SAFE_IN_MEMORY_MB = 100;
1521
- try {
1522
- const head = await fetch(inputUrl, {
1523
- method: this.knownToBlockHead(inputUrl)
1524
- });
1525
- const contentLength = head.headers.get("content-length");
1526
- const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
1527
- let outputPath = outputPathI;
1528
- const assetTypeViaUrl = this.assetType(inputUrl);
1529
- const contentType = head.headers.get("content-type") ?? "application/octet-stream";
1530
- const formattedPath = useDetectedExtension ? `${outputPath}.${typeof assetTypeViaUrl === "undefined" ? this.toExtObj[contentType][0] : assetTypeViaUrl}` : outputPath;
1531
- this.generateDirIfDNE(this.pathHandler(formattedPath), {
1532
- recursive: true
1533
- });
1534
- if (fileSizeMb !== null && fileSizeMb > MAX_SAFE_IN_MEMORY_MB) {
1535
- const res = await fetch(inputUrl);
1536
- if (!res.ok || !res.body) {
1537
- throw new Error(`Failed to fetch asset: ${res.statusText}`);
1538
- }
1539
- const writeStream = import_fs.default.createWriteStream(
1540
- (0, import_path.relative)(this.cwd ?? process.cwd(), formattedPath)
1541
- );
1542
- const reader = res.body.getReader();
1543
- const pump = /* @__PURE__ */ __name(async () => {
1544
- while (true) {
1545
- const { done, value } = await reader.read();
1546
- if (done) break;
1547
- writeStream.write(value);
1548
- }
1549
- writeStream.end();
1550
- }, "pump");
1551
- await pump();
1552
- return;
1553
- }
1554
- const result = await this.assetToBufferView(inputUrl);
1555
- const cleanedData = this.cleanDataUrl(result.b64encodedData);
1556
- this.withWs(formattedPath, Buffer.from(cleanedData, "base64"));
1557
- } catch (err) {
1558
- console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
1559
- }
1560
- }
1561
- /**
1562
- *
1563
- * @access package-private
1564
- *
1565
- * work in progress, for internal package maintainer use only
1566
- */
1567
- // USE fluent-ffmpeg for video/animated image transforms (apng, etc)
1568
- // https://www.npmjs.com/package/fluent-ffmpeg
1569
- // https://www.npmjs.com/package/@types/fluent-ffmpeg
1570
- async imageTransform({
1571
- format,
1572
- target,
1573
- quality = 80,
1574
- tint,
1575
- resize
1576
- }) {
1577
- if (tint && !resize) {
1578
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).toBuffer();
1579
- } else if (!tint && resize) {
1580
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
1581
- } else if (tint && resize) {
1582
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
1583
- } else {
1584
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).toBuffer();
1585
- }
1586
- }
1587
- /**
1588
- * Write data to a file in the system's tmp directory
1589
- * @param filename The filename (can include subdirectories like "img-probe/file.txt")
1590
- * @param data The data to write
1591
- * @param options Optional write stream options
1592
- * @returns The full path to the written file
1593
- * @example
1594
- * ```ts
1595
- * const fs = new Fs(process.cwd());
1596
- * const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
1597
- * // Or with a subdirectory:
1598
- * fs.writeTmp("img-probe/output.png", imageBuffer);
1599
- * ```
1600
- */
1601
- writeTmp(filename, data, options) {
1602
- const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1603
- Promise.resolve(this.withWs(fullPath, data, options));
1604
- }
1605
- async readTmpAsync(filename) {
1606
- const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1607
- if (!this.exists(fullPath)) {
1608
- throw new Error(`Tmp file not found: ${filename}`);
1609
- }
1610
- return await this.fileToBufferAsync(fullPath);
1611
- }
1612
- /**
1613
- * Read a file from the tmp directory
1614
- * @param filename The filename to read (can include subdirectories)
1615
- * @returns Buffer containing the file data
1616
- * @example
1617
- * ```ts
1618
- * const fs = new Fs(process.cwd());
1619
- * const data = fs.readTmp("session-data.json");
1620
- * const parsed = JSON.parse(data.toString("utf-8"));
1621
- * ```
1622
- */
1623
- readTmp(filename) {
1624
- const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1625
- if (!this.exists(fullPath)) {
1626
- throw new Error(`Tmp file not found: ${filename}`);
1627
- }
1628
- return this.fileToBuffer(fullPath);
1629
- }
1630
- /**
1631
- * Scan the tmp directory for files matching a pattern
1632
- * @param pattern Optional pattern to filter files (e.g., "img-probe")
1633
- * @param options Options for directory reading (defaults to non-recursive to avoid permission issues)
1634
- * @returns Array of matching file paths relative to tmp directory
1635
- * @example
1636
- * ```ts
1637
- * const fs = new Fs(process.cwd());
1638
- * // Get all img-probe files
1639
- * const imgFiles = fs.scanTmp("img-probe");
1640
- * // Get all files in tmp (non-recursive)
1641
- * const allFiles = fs.scanTmp();
1642
- * ```
1643
- */
1644
- scanTmp(pattern, options = {
1645
- recursive: false,
1646
- withFileTypes: false,
1647
- encoding: "utf-8"
1648
- }) {
1649
- const dirs = (0, import_path.resolve)(this.tmpDir);
1650
- const tmpContents = this.readDir(dirs, options);
1651
- if (!pattern) {
1652
- return tmpContents;
1653
- }
1654
- if (typeof pattern === "string") {
1655
- return tmpContents.filter((t) => t.includes(pattern));
1656
- }
1657
- return tmpContents.filter((path) => {
1658
- return pattern.test(path);
1659
- });
1660
- }
1661
- /**
1662
- * Extract specific files from tmp directory to a target location
1663
- * @param pattern Pattern to match files (e.g., "img-probe")
1664
- * @param targetDir Target directory to extract files to
1665
- * @param options Options for extraction behavior
1666
- * @returns Array of extracted file paths
1667
- * @example
1668
- * ```ts
1669
- * const fs = new Fs(process.cwd());
1670
- * // Extract all img-probe files to ./output
1671
- * const extracted = fs.extractFromTmp("img-probe", "./output");
1672
- * // Extract with custom behavior
1673
- * fs.extractFromTmp("session-", "./sessions", {
1674
- * preserveStructure: true,
1675
- * cleanupAfter: true
1676
- * });
1677
- * ```
1678
- */
1679
- extractFromTmp(pattern, targetDir, options) {
1680
- const {
1681
- preserveStructure = false,
1682
- cleanupAfter = false,
1683
- overwrite = true
1684
- } = options ?? {};
1685
- const matchingFiles = this.scanTmp(pattern);
1686
- const extracted = [];
1687
- for (const file of matchingFiles) {
1688
- const sourcePath = (0, import_path.resolve)(this.tmpDir, file);
1689
- const lastSegment = file.includes("/") ? file.split("/").pop() : file;
1690
- if (!lastSegment) continue;
1691
- const targetPath = preserveStructure ? (0, import_path.resolve)(targetDir, file) : (0, import_path.resolve)(targetDir, lastSegment);
1692
- if (this.exists(targetPath) && !overwrite) {
1693
- console.warn(`Skipping existing file: ${targetPath}`);
1694
- continue;
1695
- }
1696
- const data = this.fileToBuffer(sourcePath);
1697
- this.withWs(targetPath, data);
1698
- extracted.push(targetPath);
1699
- if (cleanupAfter) {
1700
- this.rmFile(sourcePath);
1701
- }
1702
- }
1703
- return extracted;
1704
- }
1705
- /**
1706
- * Clean up tmp files matching a pattern
1707
- * @param pattern Pattern to match files for deletion
1708
- * @param maxAge Optional max age in milliseconds (only delete files older than this)
1709
- * @returns Number of files removed
1710
- * @example
1711
- * ```ts
1712
- * const fs = new Fs(process.cwd());
1713
- * // Remove all img-probe files
1714
- * fs.cleanupTmp("img-probe");
1715
- * // Remove session files older than 1 hour
1716
- * fs.cleanupTmp("session-", 60 * 60 * 1000);
1717
- * ```
1718
- */
1719
- cleanupTmp(pattern, maxAge) {
1720
- const matchingFiles = this.scanTmp(pattern);
1721
- let removed = 0;
1722
- for (const file of matchingFiles) {
1723
- const fullPath = (0, import_path.resolve)(this.tmpDir, file);
1724
- try {
1725
- const stats = import_fs.default.statSync(fullPath);
1726
- if (maxAge) {
1727
- const age = Date.now() - stats.mtimeMs;
1728
- if (age < maxAge) {
1729
- continue;
1730
- }
1731
- }
1732
- if (stats.isDirectory()) {
1733
- this.rmDirSync(fullPath);
1734
- } else {
1735
- this.rmFile(fullPath);
1736
- }
1737
- removed++;
1738
- } catch (err) {
1739
- console.warn(`Failed to remove tmp file ${file}:`, err);
1740
- }
1741
- }
1742
- return removed;
1743
- }
1744
- rmTmpFile(filename) {
1745
- const tmpPath = (0, import_path.resolve)(this.tmpDir, filename);
1746
- this.rmFile(tmpPath);
1747
- }
1748
- /**
1749
- * Generate a unique tmp filename with optional prefix
1750
- * @param prefix Optional prefix for the filename
1751
- * @param extension Optional file extension (without dot)
1752
- * @returns Unique filename
1753
- * @example
1754
- * ```ts
1755
- * const fs = new Fs(process.cwd());
1756
- * const filename = fs.uniqueTmpName("img-probe", "png");
1757
- * // Returns: "img-probe-1701234567890-a3b2c1.png"
1758
- * ```
1759
- */
1760
- uniqueTmpName(prefix, extension) {
1761
- const timestamp = Date.now();
1762
- const random = Math.random().toString(36).substring(2, 8);
1763
- const parts = [prefix ?? "tmp", timestamp, random].join("-");
1764
- return extension ? `${parts}.${extension}` : parts;
1765
- }
1766
- /**
1767
- * Async generator for cleaning tmp files with batched removal
1768
- * @param pattern Pattern to match files for deletion
1769
- * @param batchSize Number of files to remove per batch (default 10)
1770
- * @yields Progress information during cleanup
1771
- * @returns Final cleanup summary
1772
- * @example
1773
- * ```ts
1774
- * const fs = new Fs(process.cwd());
1775
- * // Clean up with progress tracking
1776
- * for await (const progress of fs.cleanTmpGenerator("session-", 25)) {
1777
- * console.log(progress);
1778
- * }
1779
- * ```
1780
- */
1781
- async *cleanTmpGenerator(pattern, batchSize = 10) {
1782
- const files = this.scanTmp(pattern);
1783
- const batches = await this.arrToArrOfArrs({
1784
- arrToFragment: files,
1785
- arrOfArrsAggregator: [],
1786
- interval: batchSize
1787
- });
1788
- let totalRemoved = 0;
1789
- for (const [index, batch] of batches.entries()) {
1790
- yield {
1791
- action: "removing",
1792
- batch: [...batch],
1793
- batchNumber: index + 1,
1794
- totalBatches: batches.length,
1795
- totalFound: files.length,
1796
- removed: totalRemoved
1797
- };
1798
- for (const file of batch) {
1799
- this.rmTmpFile(file);
1800
- totalRemoved++;
1801
- }
1802
- yield {
1803
- action: "batch-complete",
1804
- batchNumber: index + 1,
1805
- batchSize: batch.length,
1806
- totalRemoved,
1807
- remaining: files.length - totalRemoved
1808
- };
1809
- }
1810
- return {
1811
- action: "complete",
1812
- totalRemoved,
1813
- totalBatches: batches.length,
1814
- pattern: pattern.toString()
1815
- };
1816
- }
1817
- };
1818
- //# sourceMappingURL=index.cjs.map