@node-minify/utils 9.0.1 → 10.0.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 (81) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +70 -5
  3. package/dist/buildArgs.d.ts +24 -0
  4. package/dist/buildArgs.d.ts.map +1 -0
  5. package/dist/buildArgs.js +43 -0
  6. package/dist/buildArgs.js.map +1 -0
  7. package/dist/compressSingleFile.d.ts +12 -0
  8. package/dist/compressSingleFile.d.ts.map +1 -0
  9. package/dist/compressSingleFile.js +28 -0
  10. package/dist/compressSingleFile.js.map +1 -0
  11. package/dist/deleteFile.d.ts +17 -0
  12. package/dist/deleteFile.d.ts.map +1 -0
  13. package/dist/deleteFile.js +28 -0
  14. package/dist/deleteFile.js.map +1 -0
  15. package/dist/deprecation.d.ts +31 -0
  16. package/dist/deprecation.d.ts.map +1 -0
  17. package/dist/deprecation.js +39 -0
  18. package/dist/deprecation.js.map +1 -0
  19. package/dist/error-B_uK-F18.js +30 -0
  20. package/dist/error-B_uK-F18.js.map +1 -0
  21. package/dist/error.d.ts +23 -0
  22. package/dist/error.d.ts.map +1 -0
  23. package/dist/error.js +3 -0
  24. package/dist/getContentFromFiles.d.ts +19 -0
  25. package/dist/getContentFromFiles.d.ts.map +1 -0
  26. package/dist/getContentFromFiles.js +49 -0
  27. package/dist/getContentFromFiles.js.map +1 -0
  28. package/dist/getFilesizeGzippedInBytes.d.ts +19 -0
  29. package/dist/getFilesizeGzippedInBytes.d.ts.map +1 -0
  30. package/dist/getFilesizeGzippedInBytes.js +37 -0
  31. package/dist/getFilesizeGzippedInBytes.js.map +1 -0
  32. package/dist/getFilesizeInBytes.d.ts +17 -0
  33. package/dist/getFilesizeInBytes.d.ts.map +1 -0
  34. package/dist/getFilesizeInBytes.js +24 -0
  35. package/dist/getFilesizeInBytes.js.map +1 -0
  36. package/dist/index.d.ts +17 -31
  37. package/dist/index.js +16 -158
  38. package/dist/isValidFile-UAwceQud.js +30 -0
  39. package/dist/isValidFile-UAwceQud.js.map +1 -0
  40. package/dist/isValidFile.d.ts +20 -0
  41. package/dist/isValidFile.d.ts.map +1 -0
  42. package/dist/isValidFile.js +3 -0
  43. package/dist/prettyBytes.d.ts +20 -0
  44. package/dist/prettyBytes.d.ts.map +1 -0
  45. package/dist/prettyBytes.js +43 -0
  46. package/dist/prettyBytes.js.map +1 -0
  47. package/dist/readFile.d.ts +15 -0
  48. package/dist/readFile.d.ts.map +1 -0
  49. package/dist/readFile.js +20 -0
  50. package/dist/readFile.js.map +1 -0
  51. package/dist/run.d.ts +23 -0
  52. package/dist/run.d.ts.map +1 -0
  53. package/dist/run.js +52 -0
  54. package/dist/run.js.map +1 -0
  55. package/dist/setFileNameMin.d.ts +22 -0
  56. package/dist/setFileNameMin.d.ts.map +1 -0
  57. package/dist/setFileNameMin.js +45 -0
  58. package/dist/setFileNameMin.js.map +1 -0
  59. package/dist/setPublicFolder.d.ts +19 -0
  60. package/dist/setPublicFolder.d.ts.map +1 -0
  61. package/dist/setPublicFolder.js +26 -0
  62. package/dist/setPublicFolder.js.map +1 -0
  63. package/dist/types-DtDQlx-T.d.ts +149 -0
  64. package/dist/types-DtDQlx-T.d.ts.map +1 -0
  65. package/dist/types.d.ts +12 -0
  66. package/dist/types.d.ts.map +1 -0
  67. package/dist/types.js +1 -0
  68. package/dist/wildcards.d.ts +19 -0
  69. package/dist/wildcards.d.ts.map +1 -0
  70. package/dist/wildcards.js +58 -0
  71. package/dist/wildcards.js.map +1 -0
  72. package/dist/writeFile-CwK9ZWXr.js +37 -0
  73. package/dist/writeFile-CwK9ZWXr.js.map +1 -0
  74. package/dist/writeFile.d.ts +29 -0
  75. package/dist/writeFile.d.ts.map +1 -0
  76. package/dist/writeFile.js +3 -0
  77. package/package.json +23 -20
  78. package/dist/index.d.mts +0 -31
  79. package/dist/index.js.map +0 -1
  80. package/dist/index.mjs +0 -132
  81. package/dist/index.mjs.map +0 -1
@@ -0,0 +1,149 @@
1
+ //#region ../types/src/types.d.ts
2
+
3
+ /**
4
+ * Result returned by a compressor function.
5
+ */
6
+ type CompressorResult = {
7
+ code: string;
8
+ map?: string;
9
+ };
10
+ /**
11
+ * Base options that all compressors can accept.
12
+ * Specific compressors may extend this with their own options.
13
+ */
14
+ type CompressorOptions = Record<string, unknown>;
15
+ /**
16
+ * A compressor function that minifies content.
17
+ * @param args - The minifier options including settings and content
18
+ * @returns A promise resolving to the compression result
19
+ */
20
+ type Compressor<TOptions extends CompressorOptions = CompressorOptions> = (args: MinifierOptions<TOptions>) => Promise<CompressorResult>;
21
+ /**
22
+ * File type for compressors that support multiple types (e.g., YUI).
23
+ */
24
+ type FileType = "js" | "css";
25
+ /**
26
+ * User-facing settings for the minify function.
27
+ * This is what users pass when calling minify().
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * import { minify } from '@node-minify/core';
32
+ * import { terser } from '@node-minify/terser';
33
+ *
34
+ * await minify({
35
+ * compressor: terser,
36
+ * input: 'src/*.js',
37
+ * output: 'dist/bundle.min.js',
38
+ * options: { mangle: true }
39
+ * });
40
+ * ```
41
+ */
42
+ type Settings<TOptions extends CompressorOptions = CompressorOptions> = {
43
+ /**
44
+ * The compressor function to use for minification.
45
+ */
46
+ compressor: Compressor<TOptions>;
47
+
48
+ /**
49
+ * Optional label for the compressor (used in logging).
50
+ */
51
+ compressorLabel?: string;
52
+
53
+ /**
54
+ * Content to minify (for in-memory minification).
55
+ * If provided, input/output are not required.
56
+ */
57
+ content?: string;
58
+
59
+ /**
60
+ * Input file path(s) or glob pattern.
61
+ * Can be a single file, array of files, or wildcard pattern.
62
+ *
63
+ * @example
64
+ * - 'src/app.js'
65
+ * - ['src/a.js', 'src/b.js']
66
+ * - 'src/**\/*.js'
67
+ */
68
+ input?: string | string[];
69
+
70
+ /**
71
+ * Output file path.
72
+ * Use $1 as placeholder for input filename in multi-file scenarios.
73
+ * Can be a single file, array of files, or pattern with $1.
74
+ *
75
+ * @example
76
+ * - 'dist/bundle.min.js'
77
+ * - ['file1.min.js', 'file2.min.js']
78
+ * - '$1.min.js' (creates app.min.js from app.js)
79
+ */
80
+ output?: string | string[];
81
+
82
+ /**
83
+ * Compressor-specific options.
84
+ * See individual compressor documentation for available options.
85
+ */
86
+ options?: TOptions;
87
+
88
+ /**
89
+ * CLI option string (used by CLI only).
90
+ * @internal
91
+ */
92
+ option?: string;
93
+
94
+ /**
95
+ * Buffer size for file operations (in bytes).
96
+ * @default 1024000 (1MB)
97
+ */
98
+ buffer?: number;
99
+
100
+ /**
101
+ * File type for compressors that support multiple types.
102
+ * Required for YUI compressor.
103
+ */
104
+ type?: FileType;
105
+
106
+ /**
107
+ * Suppress console output.
108
+ * @default false
109
+ */
110
+ silence?: boolean;
111
+
112
+ /**
113
+ * Public folder to prepend to input paths.
114
+ *
115
+ * @example
116
+ * With publicFolder: 'public/js/' and input: 'app.js',
117
+ * the actual path becomes 'public/js/app.js'
118
+ */
119
+ publicFolder?: string;
120
+
121
+ /**
122
+ * Replace files in place instead of creating new output files.
123
+ * @default false
124
+ */
125
+ replaceInPlace?: boolean;
126
+ };
127
+ /**
128
+ * Options passed to compressor functions internally.
129
+ * This is what compressors receive, not what users pass.
130
+ */
131
+ type MinifierOptions<TOptions extends CompressorOptions = CompressorOptions> = {
132
+ /**
133
+ * The full settings object.
134
+ */
135
+ settings: Settings<TOptions>;
136
+
137
+ /**
138
+ * The content to minify.
139
+ */
140
+ content?: string;
141
+
142
+ /**
143
+ * Index of current file when processing multiple files.
144
+ */
145
+ index?: number;
146
+ };
147
+ //#endregion
148
+ export { Settings as t };
149
+ //# sourceMappingURL=types-DtDQlx-T.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-DtDQlx-T.d.ts","names":["CompressorReturnType","CompressorResult","CompressorOptions","Record","Compressor","TOptions","MinifierOptions","Promise","FileType","Settings","Result","MinifyOptions"],"sources":["../../types/src/types.d.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-2025 Rodolphe Stoclin\n * MIT Licensed\n */\n\n/**\n * The return type of a compressor function.\n * @deprecated Use `CompressorResult` instead. Will be removed in v11.\n */\nexport type CompressorReturnType = string;\n\n/**\n * Result returned by a compressor function.\n */\nexport type CompressorResult = {\n code: string;\n map?: string;\n};\n\n/**\n * Base options that all compressors can accept.\n * Specific compressors may extend this with their own options.\n */\nexport type CompressorOptions = Record<string, unknown>;\n\n/**\n * A compressor function that minifies content.\n * @param args - The minifier options including settings and content\n * @returns A promise resolving to the compression result\n */\nexport type Compressor<TOptions extends CompressorOptions = CompressorOptions> =\n (args: MinifierOptions<TOptions>) => Promise<CompressorResult>;\n\n/**\n * File type for compressors that support multiple types (e.g., YUI).\n */\nexport type FileType = \"js\" | \"css\";\n\n/**\n * User-facing settings for the minify function.\n * This is what users pass when calling minify().\n *\n * @example\n * ```ts\n * import { minify } from '@node-minify/core';\n * import { terser } from '@node-minify/terser';\n *\n * await minify({\n * compressor: terser,\n * input: 'src/*.js',\n * output: 'dist/bundle.min.js',\n * options: { mangle: true }\n * });\n * ```\n */\nexport type Settings<TOptions extends CompressorOptions = CompressorOptions> = {\n /**\n * The compressor function to use for minification.\n */\n compressor: Compressor<TOptions>;\n\n /**\n * Optional label for the compressor (used in logging).\n */\n compressorLabel?: string;\n\n /**\n * Content to minify (for in-memory minification).\n * If provided, input/output are not required.\n */\n content?: string;\n\n /**\n * Input file path(s) or glob pattern.\n * Can be a single file, array of files, or wildcard pattern.\n *\n * @example\n * - 'src/app.js'\n * - ['src/a.js', 'src/b.js']\n * - 'src/**\\/*.js'\n */\n input?: string | string[];\n\n /**\n * Output file path.\n * Use $1 as placeholder for input filename in multi-file scenarios.\n * Can be a single file, array of files, or pattern with $1.\n *\n * @example\n * - 'dist/bundle.min.js'\n * - ['file1.min.js', 'file2.min.js']\n * - '$1.min.js' (creates app.min.js from app.js)\n */\n output?: string | string[];\n\n /**\n * Compressor-specific options.\n * See individual compressor documentation for available options.\n */\n options?: TOptions;\n\n /**\n * CLI option string (used by CLI only).\n * @internal\n */\n option?: string;\n\n /**\n * Buffer size for file operations (in bytes).\n * @default 1024000 (1MB)\n */\n buffer?: number;\n\n /**\n * File type for compressors that support multiple types.\n * Required for YUI compressor.\n */\n type?: FileType;\n\n /**\n * Suppress console output.\n * @default false\n */\n silence?: boolean;\n\n /**\n * Public folder to prepend to input paths.\n *\n * @example\n * With publicFolder: 'public/js/' and input: 'app.js',\n * the actual path becomes 'public/js/app.js'\n */\n publicFolder?: string;\n\n /**\n * Replace files in place instead of creating new output files.\n * @default false\n */\n replaceInPlace?: boolean;\n};\n\n/**\n * Options passed to compressor functions internally.\n * This is what compressors receive, not what users pass.\n */\nexport type MinifierOptions<\n TOptions extends CompressorOptions = CompressorOptions,\n> = {\n /**\n * The full settings object.\n */\n settings: Settings<TOptions>;\n\n /**\n * The content to minify.\n */\n content?: string;\n\n /**\n * Index of current file when processing multiple files.\n */\n index?: number;\n};\n\n/**\n * Result returned after compression (used by CLI).\n */\nexport type Result = {\n /**\n * Label of the compressor used.\n */\n compressorLabel: string;\n\n /**\n * Size of minified content (formatted string, e.g., \"1.5 KB\").\n */\n size: string;\n\n /**\n * Gzipped size of minified content (formatted string).\n */\n sizeGzip: string;\n};\n\n/**\n * Type alias for user convenience.\n * @deprecated Use `Settings` instead. Will be removed in v11.\n */\nexport type MinifyOptions<\n TOptions extends CompressorOptions = CompressorOptions,\n> = Settings<TOptions>;\n"],"mappings":";;AAwDA;;;AAI2BK,KA7CfJ,gBAAAA,GA6CeI;EAAXD,IAAAA,EAAAA,MAAAA;EAwCFC,GAAAA,CAAAA,EAAAA,MAAAA;CAkBHG;AA4BX;;;;AAMcC,KAhIFP,iBAAAA,GAAoBC,MAgIlBM,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;;;;;;KAzHFL,4BAA4BF,oBAAoBA,4BACjDI,gBAAgBD,cAAcE,QAAQN;;;;KAKrCO,QAAAA;;;;;;;;;;;;;;;;;;KAmBAC,0BAA0BP,oBAAoBA;;;;cAI1CE,WAAWC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAwCbA;;;;;;;;;;;;;;;;;;SAkBHG;;;;;;;;;;;;;;;;;;;;;;;;;;;KA4BCF,iCACSJ,oBAAoBA;;;;YAK3BO,SAASJ"}
@@ -0,0 +1,12 @@
1
+ //#region src/types.d.ts
2
+ /*!
3
+ * node-minify
4
+ * Copyright(c) 2011-2025 Rodolphe Stoclin
5
+ * MIT Licensed
6
+ */
7
+ interface BuildArgsOptions {
8
+ [key: string]: string | boolean | number | undefined;
9
+ }
10
+ //#endregion
11
+ export { BuildArgsOptions };
12
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;AAMA;;;;UAAiB,gBAAA"}
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,19 @@
1
+ //#region src/wildcards.d.ts
2
+ /*!
3
+ * node-minify
4
+ * Copyright(c) 2011-2025 Rodolphe Stoclin
5
+ * MIT Licensed
6
+ */
7
+ /**
8
+ * Handle wildcards in a path, get the real path of each file.
9
+ * @param input - Path with wildcards
10
+ * @param publicFolder - Path to the public folder
11
+ */
12
+ declare function wildcards(input: string | string[], publicFolder?: string): {
13
+ input: string[];
14
+ } | {
15
+ input?: undefined;
16
+ };
17
+ //#endregion
18
+ export { wildcards };
19
+ //# sourceMappingURL=wildcards.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wildcards.d.ts","names":[],"sources":["../src/wildcards.ts"],"sourcesContent":[],"mappings":";;AAqBA;;;;;;;;;iBAAgB,SAAA"}
@@ -0,0 +1,58 @@
1
+ import os from "node:os";
2
+ import fg from "fast-glob";
3
+
4
+ //#region src/wildcards.ts
5
+ /*!
6
+ * node-minify
7
+ * Copyright(c) 2011-2025 Rodolphe Stoclin
8
+ * MIT Licensed
9
+ */
10
+ /**
11
+ * Check if the platform is Windows
12
+ */
13
+ function isWindows() {
14
+ return os.platform() === "win32";
15
+ }
16
+ /**
17
+ * Handle wildcards in a path, get the real path of each file.
18
+ * @param input - Path with wildcards
19
+ * @param publicFolder - Path to the public folder
20
+ */
21
+ function wildcards(input, publicFolder) {
22
+ if (Array.isArray(input)) return wildcardsArray(input, publicFolder);
23
+ return wildcardsString(input, publicFolder);
24
+ }
25
+ /**
26
+ * Handle wildcards in a path (string only), get the real path of each file.
27
+ * @param input - Path with wildcards
28
+ * @param publicFolder - Path to the public folder
29
+ */
30
+ function wildcardsString(input, publicFolder) {
31
+ if (!input.includes("*")) return {};
32
+ return { input: getFilesFromWildcards(input, publicFolder).filter((path) => !path.includes("*")) };
33
+ }
34
+ /**
35
+ * Handle wildcards in a path (array only), get the real path of each file.
36
+ * @param input - Array of paths with wildcards
37
+ * @param publicFolder - Path to the public folder
38
+ */
39
+ function wildcardsArray(input, publicFolder) {
40
+ const inputWithPublicFolder = input.map((item) => {
41
+ const input2 = publicFolder ? publicFolder + item : item;
42
+ return isWindows() ? fg.convertPathToPattern(input2) : input2;
43
+ });
44
+ return { input: (inputWithPublicFolder.some((item) => item.includes("*")) ? fg.globSync(inputWithPublicFolder) : input).filter((path) => !path.includes("*")) };
45
+ }
46
+ /**
47
+ * Get the real path of each file.
48
+ * @param input - Path with wildcards
49
+ * @param publicFolder - Path to the public folder
50
+ */
51
+ function getFilesFromWildcards(input, publicFolder) {
52
+ const fullPath = publicFolder ? `${publicFolder}${input}` : input;
53
+ return fg.globSync(isWindows() ? fg.convertPathToPattern(fullPath) : fullPath);
54
+ }
55
+
56
+ //#endregion
57
+ export { wildcards };
58
+ //# sourceMappingURL=wildcards.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wildcards.js","names":[],"sources":["../src/wildcards.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-2025 Rodolphe Stoclin\n * MIT Licensed\n */\n\nimport os from \"node:os\";\nimport fg from \"fast-glob\";\n\n/**\n * Check if the platform is Windows\n */\nfunction isWindows() {\n return os.platform() === \"win32\";\n}\n\n/**\n * Handle wildcards in a path, get the real path of each file.\n * @param input - Path with wildcards\n * @param publicFolder - Path to the public folder\n */\nexport function wildcards(input: string | string[], publicFolder?: string) {\n if (Array.isArray(input)) {\n return wildcardsArray(input, publicFolder);\n }\n\n return wildcardsString(input, publicFolder);\n}\n\n/**\n * Handle wildcards in a path (string only), get the real path of each file.\n * @param input - Path with wildcards\n * @param publicFolder - Path to the public folder\n */\nfunction wildcardsString(input: string, publicFolder?: string) {\n if (!input.includes(\"*\")) {\n return {};\n }\n\n const files = getFilesFromWildcards(input, publicFolder);\n const finalPaths = files.filter((path: string) => !path.includes(\"*\"));\n\n return {\n input: finalPaths,\n };\n}\n\n/**\n * Handle wildcards in a path (array only), get the real path of each file.\n * @param input - Array of paths with wildcards\n * @param publicFolder - Path to the public folder\n */\nfunction wildcardsArray(input: string[], publicFolder?: string) {\n // Convert input paths to patterns with public folder prefix\n const inputWithPublicFolder = input.map((item) => {\n const input2 = publicFolder ? publicFolder + item : item;\n return isWindows() ? fg.convertPathToPattern(input2) : input2;\n });\n\n // Check if any wildcards exist\n const hasWildcards = inputWithPublicFolder.some((item) =>\n item.includes(\"*\")\n );\n\n // Process paths based on whether wildcards exist\n const processedPaths = hasWildcards\n ? fg.globSync(inputWithPublicFolder)\n : input;\n\n // Filter out any remaining paths with wildcards\n const finalPaths = processedPaths.filter(\n (path: string) => !path.includes(\"*\")\n );\n\n return { input: finalPaths };\n}\n\n/**\n * Get the real path of each file.\n * @param input - Path with wildcards\n * @param publicFolder - Path to the public folder\n */\nfunction getFilesFromWildcards(input: string, publicFolder?: string) {\n const fullPath = publicFolder ? `${publicFolder}${input}` : input;\n return fg.globSync(\n isWindows() ? fg.convertPathToPattern(fullPath) : fullPath\n );\n}\n"],"mappings":";;;;;;;;;;;;AAYA,SAAS,YAAY;AACjB,QAAO,GAAG,UAAU,KAAK;;;;;;;AAQ7B,SAAgB,UAAU,OAA0B,cAAuB;AACvE,KAAI,MAAM,QAAQ,MAAM,CACpB,QAAO,eAAe,OAAO,aAAa;AAG9C,QAAO,gBAAgB,OAAO,aAAa;;;;;;;AAQ/C,SAAS,gBAAgB,OAAe,cAAuB;AAC3D,KAAI,CAAC,MAAM,SAAS,IAAI,CACpB,QAAO,EAAE;AAMb,QAAO,EACH,OAJU,sBAAsB,OAAO,aAAa,CAC/B,QAAQ,SAAiB,CAAC,KAAK,SAAS,IAAI,CAAC,EAIrE;;;;;;;AAQL,SAAS,eAAe,OAAiB,cAAuB;CAE5D,MAAM,wBAAwB,MAAM,KAAK,SAAS;EAC9C,MAAM,SAAS,eAAe,eAAe,OAAO;AACpD,SAAO,WAAW,GAAG,GAAG,qBAAqB,OAAO,GAAG;GACzD;AAiBF,QAAO,EAAE,QAdY,sBAAsB,MAAM,SAC7C,KAAK,SAAS,IAAI,CACrB,GAIK,GAAG,SAAS,sBAAsB,GAClC,OAG4B,QAC7B,SAAiB,CAAC,KAAK,SAAS,IAAI,CACxC,EAE2B;;;;;;;AAQhC,SAAS,sBAAsB,OAAe,cAAuB;CACjE,MAAM,WAAW,eAAe,GAAG,eAAe,UAAU;AAC5D,QAAO,GAAG,SACN,WAAW,GAAG,GAAG,qBAAqB,SAAS,GAAG,SACrD"}
@@ -0,0 +1,37 @@
1
+ import { n as ValidationError, t as FileOperationError } from "./error-B_uK-F18.js";
2
+ import { existsSync, lstatSync, writeFileSync } from "node:fs";
3
+
4
+ //#region src/writeFile.ts
5
+ /*!
6
+ * node-minify
7
+ * Copyright(c) 2011-2025 Rodolphe Stoclin
8
+ * MIT Licensed
9
+ */
10
+ /**
11
+ * Write content into file.
12
+ * @param params Object containing file path, content and optional index
13
+ * @returns Written content
14
+ * @throws {ValidationError} If no target file is provided
15
+ * @throws {FileOperationError} If file operations fail
16
+ * @example
17
+ * writeFile({ file: 'output.js', content: 'console.log("Hello")' })
18
+ * writeFile({ file: ['file1.js', 'file2.js'], content: 'shared content', index: 0 })
19
+ */
20
+ function writeFile({ file, content, index }) {
21
+ try {
22
+ if (!file) throw new ValidationError("No target file provided");
23
+ if (!content) throw new ValidationError("No content provided");
24
+ const targetFile = index !== void 0 ? Array.isArray(file) ? file[index] : file : file;
25
+ if (typeof targetFile !== "string") throw new ValidationError("Invalid target file path");
26
+ if (!(!existsSync(targetFile) || !lstatSync(targetFile).isDirectory())) throw new Error("Target path exists and is a directory");
27
+ writeFileSync(targetFile, content, "utf8");
28
+ return content;
29
+ } catch (error) {
30
+ if (error instanceof ValidationError) throw error;
31
+ throw new FileOperationError("write to", typeof file === "string" ? file : "multiple files", error);
32
+ }
33
+ }
34
+
35
+ //#endregion
36
+ export { writeFile as t };
37
+ //# sourceMappingURL=writeFile-CwK9ZWXr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"writeFile-CwK9ZWXr.js","names":[],"sources":["../src/writeFile.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-2025 Rodolphe Stoclin\n * MIT Licensed\n */\n\nimport { existsSync, lstatSync, writeFileSync } from \"node:fs\";\nimport { FileOperationError, ValidationError } from \"./error.ts\";\n\ninterface WriteFileParams {\n file: string | string[];\n content: string | Buffer;\n index?: number;\n}\n\n/**\n * Write content into file.\n * @param params Object containing file path, content and optional index\n * @returns Written content\n * @throws {ValidationError} If no target file is provided\n * @throws {FileOperationError} If file operations fail\n * @example\n * writeFile({ file: 'output.js', content: 'console.log(\"Hello\")' })\n * writeFile({ file: ['file1.js', 'file2.js'], content: 'shared content', index: 0 })\n */\nexport function writeFile({\n file,\n content,\n index,\n}: WriteFileParams): string | Buffer {\n try {\n if (!file) {\n throw new ValidationError(\"No target file provided\");\n }\n\n if (!content) {\n throw new ValidationError(\"No content provided\");\n }\n\n const targetFile =\n index !== undefined\n ? Array.isArray(file)\n ? file[index]\n : file\n : file;\n\n if (typeof targetFile !== \"string\") {\n throw new ValidationError(\"Invalid target file path\");\n }\n\n const shouldWrite =\n !existsSync(targetFile) || !lstatSync(targetFile).isDirectory();\n\n if (!shouldWrite) {\n throw new Error(\"Target path exists and is a directory\");\n }\n\n writeFileSync(targetFile, content, \"utf8\");\n return content;\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new FileOperationError(\n \"write to\",\n typeof file === \"string\" ? file : \"multiple files\",\n error as Error\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,UAAU,EACtB,MACA,SACA,SACiC;AACjC,KAAI;AACA,MAAI,CAAC,KACD,OAAM,IAAI,gBAAgB,0BAA0B;AAGxD,MAAI,CAAC,QACD,OAAM,IAAI,gBAAgB,sBAAsB;EAGpD,MAAM,aACF,UAAU,SACJ,MAAM,QAAQ,KAAK,GACf,KAAK,SACL,OACJ;AAEV,MAAI,OAAO,eAAe,SACtB,OAAM,IAAI,gBAAgB,2BAA2B;AAMzD,MAAI,EAFA,CAAC,WAAW,WAAW,IAAI,CAAC,UAAU,WAAW,CAAC,aAAa,EAG/D,OAAM,IAAI,MAAM,wCAAwC;AAG5D,gBAAc,YAAY,SAAS,OAAO;AAC1C,SAAO;UACF,OAAO;AACZ,MAAI,iBAAiB,gBACjB,OAAM;AAEV,QAAM,IAAI,mBACN,YACA,OAAO,SAAS,WAAW,OAAO,kBAClC,MACH"}
@@ -0,0 +1,29 @@
1
+ //#region src/writeFile.d.ts
2
+ /*!
3
+ * node-minify
4
+ * Copyright(c) 2011-2025 Rodolphe Stoclin
5
+ * MIT Licensed
6
+ */
7
+ interface WriteFileParams {
8
+ file: string | string[];
9
+ content: string | Buffer;
10
+ index?: number;
11
+ }
12
+ /**
13
+ * Write content into file.
14
+ * @param params Object containing file path, content and optional index
15
+ * @returns Written content
16
+ * @throws {ValidationError} If no target file is provided
17
+ * @throws {FileOperationError} If file operations fail
18
+ * @example
19
+ * writeFile({ file: 'output.js', content: 'console.log("Hello")' })
20
+ * writeFile({ file: ['file1.js', 'file2.js'], content: 'shared content', index: 0 })
21
+ */
22
+ declare function writeFile({
23
+ file,
24
+ content,
25
+ index
26
+ }: WriteFileParams): string | Buffer;
27
+ //#endregion
28
+ export { writeFile };
29
+ //# sourceMappingURL=writeFile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"writeFile.d.ts","names":[],"sources":["../src/writeFile.ts"],"sourcesContent":[],"mappings":";;;AAyBA;;;UAhBU,eAAA,CAmBN;EACD,IAAA,EAAA,MAAA,GAAA,MAAA,EAAA;EAA2B,OAAA,EAAA,MAAA,GAlBR,MAkBQ;EAAM,KAAA,CAAA,EAAA,MAAA;;;;;;;;;;;;iBAJpB,SAAA;;;;GAIb,2BAA2B"}
@@ -0,0 +1,3 @@
1
+ import { t as writeFile } from "./writeFile-CwK9ZWXr.js";
2
+
3
+ export { writeFile };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@node-minify/utils",
3
- "version": "9.0.1",
3
+ "version": "10.0.0",
4
4
  "description": "utils for @node-minify",
5
5
  "keywords": [
6
6
  "compressor",
@@ -9,25 +9,23 @@
9
9
  "utils"
10
10
  ],
11
11
  "author": "Rodolphe Stoclin <srodolphe@gmail.com>",
12
- "homepage": "https://github.com/srod/node-minify/tree/master/packages/utils#readme",
12
+ "homepage": "https://github.com/srod/node-minify/tree/main/packages/utils#readme",
13
13
  "license": "MIT",
14
+ "type": "module",
14
15
  "engines": {
15
- "node": ">=18.0.0"
16
+ "node": ">=20.0.0"
16
17
  },
17
18
  "directories": {
18
19
  "lib": "dist",
19
20
  "test": "__tests__"
20
21
  },
21
- "main": "./dist/index.js",
22
- "module": "./dist/index.mjs",
23
22
  "types": "./dist/index.d.ts",
23
+ "main": "./dist/index.js",
24
24
  "exports": {
25
- ".": {
26
- "types": "./dist/index.d.ts",
27
- "import": "./dist/index.mjs",
28
- "require": "./dist/index.js"
29
- }
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
30
27
  },
28
+ "sideEffects": false,
31
29
  "files": [
32
30
  "dist/**/*"
33
31
  ],
@@ -41,18 +39,23 @@
41
39
  "bugs": {
42
40
  "url": "https://github.com/srod/node-minify/issues"
43
41
  },
44
- "dependencies": {
45
- "gzip-size": "6.0.0"
46
- },
47
- "devDependencies": {
48
- "@node-minify/types": "9.0.0"
49
- },
50
42
  "scripts": {
51
- "clean": "pnpm dlx rimraf dist",
52
- "build": "pnpm clean && tsup src/index.ts --format cjs,esm --dts --clean --sourcemap",
43
+ "build": "tsdown src/*.ts",
44
+ "check-exports": "attw --pack . --profile esm-only",
45
+ "format:check": "biome check .",
53
46
  "lint": "biome lint .",
47
+ "prepublishOnly": "bun run build",
54
48
  "test": "vitest run",
55
49
  "test:ci": "vitest run --coverage",
56
- "test:watch": "vitest"
50
+ "test:watch": "vitest",
51
+ "typecheck": "tsc --noEmit",
52
+ "dev": "tsdown src/index.ts --watch"
53
+ },
54
+ "dependencies": {
55
+ "fast-glob": "^3.3.3",
56
+ "gzip-size": "7.0.0"
57
+ },
58
+ "devDependencies": {
59
+ "@node-minify/types": "workspace:*"
57
60
  }
58
- }
61
+ }
package/dist/index.d.mts DELETED
@@ -1,31 +0,0 @@
1
- import { OptionsPossible, Settings, MinifierOptions } from '@node-minify/types';
2
-
3
- /*!
4
- * node-minify
5
- * Copyright(c) 2011-2024 Rodolphe Stoclin
6
- * MIT Licensed
7
- */
8
-
9
- type Utils = {
10
- readFile: (file: string) => string;
11
- writeFile: ({ file, content, index }: WriteFile) => string;
12
- deleteFile: (file: string) => void;
13
- buildArgs: (options: Record<string, OptionsPossible>) => any;
14
- clone: (obj: object) => object;
15
- getFilesizeInBytes: (file: string) => string;
16
- getFilesizeGzippedInBytes: (file: string) => Promise<string>;
17
- prettyBytes: (num: number) => string;
18
- setFileNameMin: (file: string, output: string, publicFolder?: string, replaceInPlace?: boolean) => string;
19
- compressSingleFile: (settings: Settings) => string | Promise<string>;
20
- getContentFromFiles: (input: string | string[]) => string;
21
- runSync: ({ settings, content, index }: MinifierOptions) => string;
22
- runAsync: ({ settings, content, index, }: MinifierOptions) => Promise<string>;
23
- };
24
- type WriteFile = {
25
- file: string;
26
- content: any;
27
- index?: number;
28
- };
29
- declare const utils: Utils;
30
-
31
- export { utils };
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-2024 Rodolphe Stoclin\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\nimport {\n createReadStream,\n existsSync,\n lstatSync,\n readFileSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport type {\n MinifierOptions,\n OptionsPossible,\n Settings,\n} from \"@node-minify/types\";\nimport gzipSize from \"gzip-size\";\n\ntype Utils = {\n readFile: (file: string) => string;\n writeFile: ({ file, content, index }: WriteFile) => string;\n deleteFile: (file: string) => void;\n buildArgs: (options: Record<string, OptionsPossible>) => any;\n clone: (obj: object) => object;\n getFilesizeInBytes: (file: string) => string;\n getFilesizeGzippedInBytes: (file: string) => Promise<string>;\n prettyBytes: (num: number) => string;\n setFileNameMin: (\n file: string,\n output: string,\n publicFolder?: string,\n replaceInPlace?: boolean\n ) => string;\n compressSingleFile: (settings: Settings) => string | Promise<string>;\n getContentFromFiles: (input: string | string[]) => string;\n runSync: ({ settings, content, index }: MinifierOptions) => string;\n runAsync: ({\n settings,\n content,\n index,\n }: MinifierOptions) => Promise<string>;\n};\n\ntype WriteFile = {\n file: string;\n content: any;\n index?: number;\n};\n\nconst utils = {} as Utils;\n\n/**\n * Read content from file.\n * @param file File name\n */\nutils.readFile = (file: string): string => readFileSync(file, \"utf8\");\n\n/**\n * Write content into file.\n * @param file File name\n * @param content Content to write\n * @param index Index of the file being processed\n */\nutils.writeFile = ({ file, content, index }: WriteFile): string => {\n const _file = index !== undefined ? file[index] : file;\n if (\n !existsSync(_file) ||\n (existsSync(_file) && !lstatSync(_file).isDirectory())\n ) {\n writeFileSync(_file, content, \"utf8\");\n }\n\n return content;\n};\n\n/**\n * Delete file.\n * @param file File name\n */\nutils.deleteFile = (file: string) => unlinkSync(file);\n\n/**\n * Builds arguments array based on an object.\n * @param options\n */\nutils.buildArgs = (\n options: Record<string, OptionsPossible>\n): OptionsPossible[] => {\n const args: OptionsPossible[] = [];\n Object.keys(options).forEach((key: string) => {\n if (options[key] && (options[key] as unknown) !== false) {\n args.push(`--${key}`);\n }\n\n if (options[key] && options[key] !== true) {\n args.push(options[key]);\n }\n });\n\n return args;\n};\n\n/**\n * Clone an object.\n * @param obj Object\n */\nutils.clone = (obj: object): object => JSON.parse(JSON.stringify(obj));\n\n/**\n * Get the file size in bytes.\n * @param file File name\n */\nutils.getFilesizeInBytes = (file: string): string => {\n const stats = statSync(file);\n const fileSizeInBytes = stats.size;\n return utils.prettyBytes(fileSizeInBytes);\n};\n\n/**\n * Get the gzipped file size in bytes.\n * @param file File name\n */\nutils.getFilesizeGzippedInBytes = (file: string): Promise<string> => {\n return new Promise((resolve) => {\n const source = createReadStream(file);\n source.pipe(gzipSize.stream()).on(\"gzip-size\", (size) => {\n resolve(utils.prettyBytes(size));\n });\n });\n};\n\n/**\n * Get the size in human readable.\n * From https://github.com/sindresorhus/pretty-bytes\n * @param num Number\n */\nutils.prettyBytes = (num: number): string => {\n const UNITS = [\"B\", \"kB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"];\n\n if (!Number.isFinite(num)) {\n throw new TypeError(\n `Expected a finite number, got ${typeof num}: ${num}`\n );\n }\n\n const neg = num < 0;\n\n if (neg) {\n num = -num;\n }\n\n if (num < 1) {\n return `${(neg ? \"-\" : \"\") + num} B`;\n }\n\n const exponent = Math.min(\n Math.floor(Math.log(num) / Math.log(1000)),\n UNITS.length - 1\n );\n const numStr = Number((num / 1000 ** exponent).toPrecision(3));\n const unit = UNITS[exponent];\n\n return `${(neg ? \"-\" : \"\") + numStr} ${unit}`;\n};\n\n/**\n * Set the file name as minified.\n * eg. file.js returns file.min.js\n * @param file File name\n * @param output Output file name\n * @param publicFolder Public folder\n * @param replaceInPlace Replace in place\n */\nutils.setFileNameMin = (\n file: string,\n output: string,\n publicFolder?: string,\n replaceInPlace?: boolean\n): string => {\n const filePath = file.substr(0, file.lastIndexOf(\"/\") + 1);\n const fileWithoutPath = file.substr(file.lastIndexOf(\"/\") + 1);\n let fileWithoutExtension = fileWithoutPath.substr(\n 0,\n fileWithoutPath.lastIndexOf(\".\")\n );\n if (publicFolder) {\n fileWithoutExtension = publicFolder + fileWithoutExtension;\n }\n if (replaceInPlace) {\n fileWithoutExtension = filePath + fileWithoutExtension;\n }\n return output.replace(\"$1\", fileWithoutExtension);\n};\n\n/**\n * Compress a single file.\n * @param settings Settings\n */\nutils.compressSingleFile = (settings: Settings): Promise<string> | string => {\n const content = settings.content\n ? settings.content\n : settings.input\n ? utils.getContentFromFiles(settings.input)\n : \"\";\n return settings.sync\n ? utils.runSync({ settings, content })\n : utils.runAsync({ settings, content });\n};\n\n/**\n * Concatenate all input files and get the data.\n * @param input Input files\n */\nutils.getContentFromFiles = (input: string | string[]): string => {\n if (!Array.isArray(input)) {\n return readFileSync(input, \"utf8\");\n }\n\n return input\n .map((path) =>\n !existsSync(path) ||\n (existsSync(path) && !lstatSync(path).isDirectory())\n ? readFileSync(path, \"utf8\")\n : \"\"\n )\n .join(\"\\n\");\n};\n\n/**\n * Run compressor in sync.\n * @param settings Settings\n * @param content Content to minify\n * @param index Index of the file being processed\n */\nutils.runSync = ({ settings, content, index }: MinifierOptions): string =>\n settings && typeof settings.compressor !== \"string\"\n ? typeof settings.compressor === \"function\"\n ? String(\n settings.compressor({\n settings,\n content,\n callback: null,\n index,\n }) || \"\"\n )\n : \"\"\n : \"\";\n\n/**\n * Run compressor in async.\n * @param settings Settings\n * @param content Content to minify\n * @param index Index of the file being processed\n */\nutils.runAsync = ({\n settings,\n content,\n index,\n}: MinifierOptions): Promise<string> => {\n return new Promise((resolve, reject) => {\n settings?.compressor && typeof settings.compressor !== \"string\"\n ? settings.compressor({\n settings,\n content,\n callback: (err: unknown, result?: string) => {\n if (err) {\n return reject(err);\n }\n resolve(result || \"\");\n },\n index,\n })\n : null;\n });\n};\n\n/**\n * Expose `utils`.\n */\nexport { utils };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,qBAQO;AAMP,uBAAqB;AAiCrB,IAAM,QAAQ,CAAC;AAMf,MAAM,WAAW,CAAC,aAAyB,6BAAa,MAAM,MAAM;AAQpE,MAAM,YAAY,CAAC,EAAE,MAAM,SAAS,MAAM,MAAyB;AAC/D,QAAM,QAAQ,UAAU,SAAY,KAAK,KAAK,IAAI;AAClD,MACI,KAAC,2BAAW,KAAK,SAChB,2BAAW,KAAK,KAAK,KAAC,0BAAU,KAAK,EAAE,YAAY,GACtD;AACE,sCAAc,OAAO,SAAS,MAAM;AAAA,EACxC;AAEA,SAAO;AACX;AAMA,MAAM,aAAa,CAAC,aAAiB,2BAAW,IAAI;AAMpD,MAAM,YAAY,CACd,YACoB;AACpB,QAAM,OAA0B,CAAC;AACjC,SAAO,KAAK,OAAO,EAAE,QAAQ,CAAC,QAAgB;AAC1C,QAAI,QAAQ,GAAG,KAAM,QAAQ,GAAG,MAAkB,OAAO;AACrD,WAAK,KAAK,KAAK,GAAG,EAAE;AAAA,IACxB;AAEA,QAAI,QAAQ,GAAG,KAAK,QAAQ,GAAG,MAAM,MAAM;AACvC,WAAK,KAAK,QAAQ,GAAG,CAAC;AAAA,IAC1B;AAAA,EACJ,CAAC;AAED,SAAO;AACX;AAMA,MAAM,QAAQ,CAAC,QAAwB,KAAK,MAAM,KAAK,UAAU,GAAG,CAAC;AAMrE,MAAM,qBAAqB,CAAC,SAAyB;AACjD,QAAM,YAAQ,yBAAS,IAAI;AAC3B,QAAM,kBAAkB,MAAM;AAC9B,SAAO,MAAM,YAAY,eAAe;AAC5C;AAMA,MAAM,4BAA4B,CAAC,SAAkC;AACjE,SAAO,IAAI,QAAQ,CAAC,YAAY;A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
- createReadStream,
4
- existsSync,
5
- lstatSync,
6
- readFileSync,
7
- statSync,
8
- unlinkSync,
9
- writeFileSync
10
- } from "node:fs";
11
- import gzipSize from "gzip-size";
12
- var utils = {};
13
- utils.readFile = (file) => readFileSync(file, "utf8");
14
- utils.writeFile = ({ file, content, index }) => {
15
- const _file = index !== void 0 ? file[index] : file;
16
- if (!existsSync(_file) || existsSync(_file) && !lstatSync(_file).isDirectory()) {
17
- writeFileSync(_file, content, "utf8");
18
- }
19
- return content;
20
- };
21
- utils.deleteFile = (file) => unlinkSync(file);
22
- utils.buildArgs = (options) => {
23
- const args = [];
24
- Object.keys(options).forEach((key) => {
25
- if (options[key] && options[key] !== false) {
26
- args.push(`--${key}`);
27
- }
28
- if (options[key] && options[key] !== true) {
29
- args.push(options[key]);
30
- }
31
- });
32
- return args;
33
- };
34
- utils.clone = (obj) => JSON.parse(JSON.stringify(obj));
35
- utils.getFilesizeInBytes = (file) => {
36
- const stats = statSync(file);
37
- const fileSizeInBytes = stats.size;
38
- return utils.prettyBytes(fileSizeInBytes);
39
- };
40
- utils.getFilesizeGzippedInBytes = (file) => {
41
- return new Promise((resolve) => {
42
- const source = createReadStream(file);
43
- source.pipe(gzipSize.stream()).on("gzip-size", (size) => {
44
- resolve(utils.prettyBytes(size));
45
- });
46
- });
47
- };
48
- utils.prettyBytes = (num) => {
49
- const UNITS = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
50
- if (!Number.isFinite(num)) {
51
- throw new TypeError(
52
- `Expected a finite number, got ${typeof num}: ${num}`
53
- );
54
- }
55
- const neg = num < 0;
56
- if (neg) {
57
- num = -num;
58
- }
59
- if (num < 1) {
60
- return `${(neg ? "-" : "") + num} B`;
61
- }
62
- const exponent = Math.min(
63
- Math.floor(Math.log(num) / Math.log(1e3)),
64
- UNITS.length - 1
65
- );
66
- const numStr = Number((num / 1e3 ** exponent).toPrecision(3));
67
- const unit = UNITS[exponent];
68
- return `${(neg ? "-" : "") + numStr} ${unit}`;
69
- };
70
- utils.setFileNameMin = (file, output, publicFolder, replaceInPlace) => {
71
- const filePath = file.substr(0, file.lastIndexOf("/") + 1);
72
- const fileWithoutPath = file.substr(file.lastIndexOf("/") + 1);
73
- let fileWithoutExtension = fileWithoutPath.substr(
74
- 0,
75
- fileWithoutPath.lastIndexOf(".")
76
- );
77
- if (publicFolder) {
78
- fileWithoutExtension = publicFolder + fileWithoutExtension;
79
- }
80
- if (replaceInPlace) {
81
- fileWithoutExtension = filePath + fileWithoutExtension;
82
- }
83
- return output.replace("$1", fileWithoutExtension);
84
- };
85
- utils.compressSingleFile = (settings) => {
86
- const content = settings.content ? settings.content : settings.input ? utils.getContentFromFiles(settings.input) : "";
87
- return settings.sync ? utils.runSync({ settings, content }) : utils.runAsync({ settings, content });
88
- };
89
- utils.getContentFromFiles = (input) => {
90
- if (!Array.isArray(input)) {
91
- return readFileSync(input, "utf8");
92
- }
93
- return input.map(
94
- (path) => !existsSync(path) || existsSync(path) && !lstatSync(path).isDirectory() ? readFileSync(path, "utf8") : ""
95
- ).join("\n");
96
- };
97
- utils.runSync = ({ settings, content, index }) => settings && typeof settings.compressor !== "string" ? typeof settings.compressor === "function" ? String(
98
- settings.compressor({
99
- settings,
100
- content,
101
- callback: null,
102
- index
103
- }) || ""
104
- ) : "" : "";
105
- utils.runAsync = ({
106
- settings,
107
- content,
108
- index
109
- }) => {
110
- return new Promise((resolve, reject) => {
111
- settings?.compressor && typeof settings.compressor !== "string" ? settings.compressor({
112
- settings,
113
- content,
114
- callback: (err, result) => {
115
- if (err) {
116
- return reject(err);
117
- }
118
- resolve(result || "");
119
- },
120
- index
121
- }) : null;
122
- });
123
- };
124
- export {
125
- utils
126
- };
127
- /*!
128
- * node-minify
129
- * Copyright(c) 2011-2024 Rodolphe Stoclin
130
- * MIT Licensed
131
- */
132
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-2024 Rodolphe Stoclin\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\nimport {\n createReadStream,\n existsSync,\n lstatSync,\n readFileSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport type {\n MinifierOptions,\n OptionsPossible,\n Settings,\n} from \"@node-minify/types\";\nimport gzipSize from \"gzip-size\";\n\ntype Utils = {\n readFile: (file: string) => string;\n writeFile: ({ file, content, index }: WriteFile) => string;\n deleteFile: (file: string) => void;\n buildArgs: (options: Record<string, OptionsPossible>) => any;\n clone: (obj: object) => object;\n getFilesizeInBytes: (file: string) => string;\n getFilesizeGzippedInBytes: (file: string) => Promise<string>;\n prettyBytes: (num: number) => string;\n setFileNameMin: (\n file: string,\n output: string,\n publicFolder?: string,\n replaceInPlace?: boolean\n ) => string;\n compressSingleFile: (settings: Settings) => string | Promise<string>;\n getContentFromFiles: (input: string | string[]) => string;\n runSync: ({ settings, content, index }: MinifierOptions) => string;\n runAsync: ({\n settings,\n content,\n index,\n }: MinifierOptions) => Promise<string>;\n};\n\ntype WriteFile = {\n file: string;\n content: any;\n index?: number;\n};\n\nconst utils = {} as Utils;\n\n/**\n * Read content from file.\n * @param file File name\n */\nutils.readFile = (file: string): string => readFileSync(file, \"utf8\");\n\n/**\n * Write content into file.\n * @param file File name\n * @param content Content to write\n * @param index Index of the file being processed\n */\nutils.writeFile = ({ file, content, index }: WriteFile): string => {\n const _file = index !== undefined ? file[index] : file;\n if (\n !existsSync(_file) ||\n (existsSync(_file) && !lstatSync(_file).isDirectory())\n ) {\n writeFileSync(_file, content, \"utf8\");\n }\n\n return content;\n};\n\n/**\n * Delete file.\n * @param file File name\n */\nutils.deleteFile = (file: string) => unlinkSync(file);\n\n/**\n * Builds arguments array based on an object.\n * @param options\n */\nutils.buildArgs = (\n options: Record<string, OptionsPossible>\n): OptionsPossible[] => {\n const args: OptionsPossible[] = [];\n Object.keys(options).forEach((key: string) => {\n if (options[key] && (options[key] as unknown) !== false) {\n args.push(`--${key}`);\n }\n\n if (options[key] && options[key] !== true) {\n args.push(options[key]);\n }\n });\n\n return args;\n};\n\n/**\n * Clone an object.\n * @param obj Object\n */\nutils.clone = (obj: object): object => JSON.parse(JSON.stringify(obj));\n\n/**\n * Get the file size in bytes.\n * @param file File name\n */\nutils.getFilesizeInBytes = (file: string): string => {\n const stats = statSync(file);\n const fileSizeInBytes = stats.size;\n return utils.prettyBytes(fileSizeInBytes);\n};\n\n/**\n * Get the gzipped file size in bytes.\n * @param file File name\n */\nutils.getFilesizeGzippedInBytes = (file: string): Promise<string> => {\n return new Promise((resolve) => {\n const source = createReadStream(file);\n source.pipe(gzipSize.stream()).on(\"gzip-size\", (size) => {\n resolve(utils.prettyBytes(size));\n });\n });\n};\n\n/**\n * Get the size in human readable.\n * From https://github.com/sindresorhus/pretty-bytes\n * @param num Number\n */\nutils.prettyBytes = (num: number): string => {\n const UNITS = [\"B\", \"kB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"];\n\n if (!Number.isFinite(num)) {\n throw new TypeError(\n `Expected a finite number, got ${typeof num}: ${num}`\n );\n }\n\n const neg = num < 0;\n\n if (neg) {\n num = -num;\n }\n\n if (num < 1) {\n return `${(neg ? \"-\" : \"\") + num} B`;\n }\n\n const exponent = Math.min(\n Math.floor(Math.log(num) / Math.log(1000)),\n UNITS.length - 1\n );\n const numStr = Number((num / 1000 ** exponent).toPrecision(3));\n const unit = UNITS[exponent];\n\n return `${(neg ? \"-\" : \"\") + numStr} ${unit}`;\n};\n\n/**\n * Set the file name as minified.\n * eg. file.js returns file.min.js\n * @param file File name\n * @param output Output file name\n * @param publicFolder Public folder\n * @param replaceInPlace Replace in place\n */\nutils.setFileNameMin = (\n file: string,\n output: string,\n publicFolder?: string,\n replaceInPlace?: boolean\n): string => {\n const filePath = file.substr(0, file.lastIndexOf(\"/\") + 1);\n const fileWithoutPath = file.substr(file.lastIndexOf(\"/\") + 1);\n let fileWithoutExtension = fileWithoutPath.substr(\n 0,\n fileWithoutPath.lastIndexOf(\".\")\n );\n if (publicFolder) {\n fileWithoutExtension = publicFolder + fileWithoutExtension;\n }\n if (replaceInPlace) {\n fileWithoutExtension = filePath + fileWithoutExtension;\n }\n return output.replace(\"$1\", fileWithoutExtension);\n};\n\n/**\n * Compress a single file.\n * @param settings Settings\n */\nutils.compressSingleFile = (settings: Settings): Promise<string> | string => {\n const content = settings.content\n ? settings.content\n : settings.input\n ? utils.getContentFromFiles(settings.input)\n : \"\";\n return settings.sync\n ? utils.runSync({ settings, content })\n : utils.runAsync({ settings, content });\n};\n\n/**\n * Concatenate all input files and get the data.\n * @param input Input files\n */\nutils.getContentFromFiles = (input: string | string[]): string => {\n if (!Array.isArray(input)) {\n return readFileSync(input, \"utf8\");\n }\n\n return input\n .map((path) =>\n !existsSync(path) ||\n (existsSync(path) && !lstatSync(path).isDirectory())\n ? readFileSync(path, \"utf8\")\n : \"\"\n )\n .join(\"\\n\");\n};\n\n/**\n * Run compressor in sync.\n * @param settings Settings\n * @param content Content to minify\n * @param index Index of the file being processed\n */\nutils.runSync = ({ settings, content, index }: MinifierOptions): string =>\n settings && typeof settings.compressor !== \"string\"\n ? typeof settings.compressor === \"function\"\n ? String(\n settings.compressor({\n settings,\n content,\n callback: null,\n index,\n }) || \"\"\n )\n : \"\"\n : \"\";\n\n/**\n * Run compressor in async.\n * @param settings Settings\n * @param content Content to minify\n * @param index Index of the file being processed\n */\nutils.runAsync = ({\n settings,\n content,\n index,\n}: MinifierOptions): Promise<string> => {\n return new Promise((resolve, reject) => {\n settings?.compressor && typeof settings.compressor !== \"string\"\n ? settings.compressor({\n settings,\n content,\n callback: (err: unknown, result?: string) => {\n if (err) {\n return reject(err);\n }\n resolve(result || \"\");\n },\n index,\n })\n : null;\n });\n};\n\n/**\n * Expose `utils`.\n */\nexport { utils };\n"],"mappings":";AASA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA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