@node-minify/utils 10.0.0-next.0 → 10.0.1

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 (79) 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 +17 -131
  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 +13 -11
  78. package/dist/index.cjs +0 -165
  79. package/dist/index.d.cts +0 -31
@@ -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": "10.0.0-next.0",
3
+ "version": "10.0.1",
4
4
  "description": "utils for @node-minify",
5
5
  "keywords": [
6
6
  "compressor",
@@ -13,20 +13,19 @@
13
13
  "license": "MIT",
14
14
  "type": "module",
15
15
  "engines": {
16
- "node": ">=22.0.0"
16
+ "node": ">=20.0.0"
17
17
  },
18
18
  "directories": {
19
19
  "lib": "dist",
20
20
  "test": "__tests__"
21
21
  },
22
- "main": "./dist/index.cjs",
22
+ "types": "./dist/index.d.ts",
23
+ "main": "./dist/index.js",
23
24
  "exports": {
24
- "./package.json": "./package.json",
25
- ".": {
26
- "import": "./dist/index.js",
27
- "default": "./dist/index.cjs"
28
- }
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
29
27
  },
28
+ "sideEffects": false,
30
29
  "files": [
31
30
  "dist/**/*"
32
31
  ],
@@ -41,16 +40,19 @@
41
40
  "url": "https://github.com/srod/node-minify/issues"
42
41
  },
43
42
  "scripts": {
44
- "build": "tsup src/index.ts --format cjs,esm --dts --clean && bunx fix-tsup-cjs",
45
- "check-exports": "attw --pack .",
43
+ "build": "tsdown src/*.ts",
44
+ "check-exports": "attw --pack . --profile esm-only",
46
45
  "format:check": "biome check .",
47
46
  "lint": "biome lint .",
48
47
  "prepublishOnly": "bun run build",
49
48
  "test": "vitest run",
50
49
  "test:ci": "vitest run --coverage",
51
- "test:watch": "vitest"
50
+ "test:watch": "vitest",
51
+ "typecheck": "tsc --noEmit",
52
+ "dev": "tsdown src/index.ts --watch"
52
53
  },
53
54
  "dependencies": {
55
+ "fast-glob": "^3.3.3",
54
56
  "gzip-size": "7.0.0"
55
57
  },
56
58
  "devDependencies": {
package/dist/index.cjs DELETED
@@ -1,165 +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 __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
33
- utils: () => utils
34
- });
35
- module.exports = __toCommonJS(src_exports);
36
- var import_node_fs = require("fs");
37
- var utils = {};
38
- utils.readFile = (file) => (0, import_node_fs.readFileSync)(file, "utf8");
39
- utils.writeFile = ({ file, content, index }) => {
40
- const _file = index !== void 0 ? file[index] : file;
41
- if (!(0, import_node_fs.existsSync)(_file) || (0, import_node_fs.existsSync)(_file) && !(0, import_node_fs.lstatSync)(_file).isDirectory()) {
42
- (0, import_node_fs.writeFileSync)(_file, content, "utf8");
43
- }
44
- return content;
45
- };
46
- utils.deleteFile = (file) => (0, import_node_fs.unlinkSync)(file);
47
- utils.buildArgs = (options) => {
48
- const args = [];
49
- Object.keys(options).forEach((key) => {
50
- if (options[key] && options[key] !== false) {
51
- args.push(`--${key}`);
52
- }
53
- if (options[key] && options[key] !== true) {
54
- args.push(options[key]);
55
- }
56
- });
57
- return args;
58
- };
59
- utils.clone = (obj) => JSON.parse(JSON.stringify(obj));
60
- utils.getFilesizeInBytes = (file) => {
61
- const stats = (0, import_node_fs.statSync)(file);
62
- const fileSizeInBytes = stats.size;
63
- return utils.prettyBytes(fileSizeInBytes);
64
- };
65
- utils.getFilesizeGzippedInBytes = async (file) => {
66
- const { gzipSizeStream } = await import("gzip-size");
67
- return new Promise((resolve) => {
68
- const source = (0, import_node_fs.createReadStream)(file);
69
- source.pipe(gzipSizeStream()).on("gzip-size", (size) => {
70
- resolve(utils.prettyBytes(size));
71
- });
72
- });
73
- };
74
- utils.prettyBytes = (num) => {
75
- const UNITS = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
76
- if (!Number.isFinite(num)) {
77
- throw new TypeError(
78
- `Expected a finite number, got ${typeof num}: ${num}`
79
- );
80
- }
81
- const neg = num < 0;
82
- if (neg) {
83
- num = -num;
84
- }
85
- if (num < 1) {
86
- return `${(neg ? "-" : "") + num} B`;
87
- }
88
- const exponent = Math.min(
89
- Math.floor(Math.log(num) / Math.log(1e3)),
90
- UNITS.length - 1
91
- );
92
- const numStr = Number((num / 1e3 ** exponent).toPrecision(3));
93
- const unit = UNITS[exponent];
94
- return `${(neg ? "-" : "") + numStr} ${unit}`;
95
- };
96
- utils.setFileNameMin = (file, output, publicFolder, replaceInPlace) => {
97
- const filePath = file.substr(0, file.lastIndexOf("/") + 1);
98
- const fileWithoutPath = file.substr(file.lastIndexOf("/") + 1);
99
- let fileWithoutExtension = fileWithoutPath.substr(
100
- 0,
101
- fileWithoutPath.lastIndexOf(".")
102
- );
103
- if (publicFolder) {
104
- fileWithoutExtension = publicFolder + fileWithoutExtension;
105
- }
106
- if (replaceInPlace) {
107
- fileWithoutExtension = filePath + fileWithoutExtension;
108
- }
109
- return output.replace("$1", fileWithoutExtension);
110
- };
111
- utils.compressSingleFile = (settings) => {
112
- const content = settings.content ? settings.content : settings.input ? utils.getContentFromFiles(settings.input) : "";
113
- return settings.sync ? utils.runSync({ settings, content }) : utils.runAsync({ settings, content });
114
- };
115
- utils.getContentFromFiles = (input) => {
116
- if (!Array.isArray(input)) {
117
- return (0, import_node_fs.readFileSync)(input, "utf8");
118
- }
119
- return input.map(
120
- (path) => !(0, import_node_fs.existsSync)(path) || (0, import_node_fs.existsSync)(path) && !(0, import_node_fs.lstatSync)(path).isDirectory() ? (0, import_node_fs.readFileSync)(path, "utf8") : ""
121
- ).join("\n");
122
- };
123
- utils.runSync = ({ settings, content, index }) => settings && typeof settings.compressor !== "string" ? typeof settings.compressor === "function" ? String(
124
- settings.compressor({
125
- settings,
126
- content,
127
- callback: null,
128
- index
129
- }) || ""
130
- ) : "" : "";
131
- utils.runAsync = ({
132
- settings,
133
- content,
134
- index
135
- }) => {
136
- return new Promise((resolve, reject) => {
137
- settings?.compressor && typeof settings.compressor !== "string" ? settings.compressor({
138
- settings,
139
- content,
140
- callback: (err, result) => {
141
- if (err) {
142
- return reject(err);
143
- }
144
- resolve(result || "");
145
- },
146
- index
147
- }) : null;
148
- });
149
- };
150
- // Annotate the CommonJS export names for ESM import in node:
151
- 0 && (module.exports = {
152
- utils
153
- });
154
- /*!
155
- * node-minify
156
- * Copyright(c) 2011-2024 Rodolphe Stoclin
157
- * MIT Licensed
158
- */
159
-
160
- // fix-cjs-exports
161
- if (module.exports.default) {
162
- Object.assign(module.exports.default, module.exports);
163
- module.exports = module.exports.default;
164
- delete module.exports.default;
165
- }
package/dist/index.d.cts 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 };