@js-utils-kit/fs 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`fs`);c=s(c);let l=require(`path`);l=s(l);let u=require(`archiver`);u=s(u);let d=require(`node:fs/promises`),f=require(`url`);function p({format:e,source:t,destination:n,options:r={},log:i=!0,onSuccess:a}){let o=l.default.resolve(t);if(!c.default.existsSync(o)||!c.default.statSync(o).isDirectory())throw Error(`Source directory "${t}" does not exist or is not a directory.`);let s=c.default.createWriteStream(n);e===`zip`&&(r={...r,zlib:{level:9}});let d=(0,u.default)(e,r);return new Promise((e,r)=>{s.on(`close`,()=>{let t=d.pointer();i&&console.log(`${n} created: ${t} total bytes`),a&&a(t),e()}),d.on(`error`,e=>{r(e)}),d.pipe(s),d.directory(t,!1),d.finalize().catch(e=>r(e instanceof Error?e:Error(String(e))))})}const m=typeof __filename<`u`;async function h(e){try{return await(0,d.access)(e),!0}catch{return!1}}function g(e){if(!e)throw Error(`locateModuleFile requires import.meta.url (ESM) or __filename (CJS).`);return e.startsWith(`file:`)?(0,f.fileURLToPath)(e):e}function _(e){return l.default.dirname(g(e))}function v(e,t){let n=_(t),r=l.default.resolve(n,e);if(l.default.relative(n,r).startsWith(`..`))throw Error(`Resolved path escapes module directory.`);return r}function y(e){return e.replace(/\\/g,`/`)}function b(e){return e.replace(/\//g,`\\`)}function x(e){return e.replace(/[/\\]/g,l.default.sep)}exports.createArchive=p,exports.exists=h,exports.hasCommonJSFilename=m,exports.locateModuleDirectory=_,exports.locateModuleFile=g,exports.resolveModuleRelative=v,exports.toPlatformPath=x,exports.toPosixPath=y,exports.toWinPath=b;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`fs`);c=s(c);let l=require(`path`);l=s(l);let u=require(`archiver`);u=s(u);let d=require(`node:fs/promises`),f=require(`url`);function p({format:e,source:t,destination:n,options:r={},log:i=!0,onSuccess:a}){let o=l.default.resolve(t);if(!c.default.existsSync(o)||!c.default.statSync(o).isDirectory())throw Error(`Source directory "${t}" does not exist or is not a directory.`);let s=c.default.createWriteStream(n);e===`zip`&&(r={...r,zlib:{level:9}});let d=(0,u.default)(e,r);return new Promise((e,r)=>{s.on(`close`,()=>{let t=d.pointer();i&&console.log(`${n} created: ${t} total bytes`),a&&a(t),e()}),d.on(`error`,e=>{r(e)}),d.pipe(s),d.directory(t,!1),d.finalize().catch(e=>r(e instanceof Error?e:Error(String(e))))})}const m=typeof __filename<`u`;async function h(e){try{return await(0,d.access)(e),!0}catch{return!1}}async function g(e){try{return(await(0,d.stat)(e)).isFile()}catch{return!1}}async function _(e){try{return(await(0,d.stat)(e)).isDirectory()}catch{return!1}}async function v(e){try{let t=(await(0,d.stat)(e)).size;return typeof t==`number`?t:0}catch{return 0}}function y(e){return JSON.parse(e)}function b(e,{space:t=2,replacer:n=null}={}){return typeof n==`function`||Array.isArray(n)?JSON.stringify(e,n,t):JSON.stringify(e,null,t)}async function x(e){return y(await(0,d.readFile)(e,`utf-8`))}async function S(e,t,{space:n=2,replacer:r=null}={}){await(0,d.writeFile)(e,b(t,{space:n,replacer:r}),`utf-8`)}function C(e){if(!e)throw Error(`locateModuleFile requires import.meta.url (ESM) or __filename (CJS).`);return e.startsWith(`file:`)?(0,f.fileURLToPath)(e):e}function w(e){return l.default.dirname(C(e))}function T(e,t){let n=w(t),r=l.default.resolve(n,e);if(l.default.relative(n,r).startsWith(`..`))throw Error(`Resolved path escapes module directory.`);return r}function E(e){return e.replace(/\\/g,`/`)}function D(e){return e.replace(/\//g,`\\`)}function O(e){return e.replace(/[/\\]/g,l.default.sep)}exports.createArchive=p,exports.exists=h,exports.getContentSize=v,exports.hasCommonJSFilename=m,exports.isDirectory=_,exports.isFile=g,exports.locateModuleDirectory=w,exports.locateModuleFile=C,exports.parseJson=y,exports.readJsonFile=x,exports.resolveModuleRelative=T,exports.stringifyJson=b,exports.toPlatformPath=O,exports.toPosixPath=E,exports.toWinPath=D,exports.writeJsonFile=S;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,5 @@
1
- import { CreateArchiveOptions } from "@js-utils-kit/types";
1
+ import { CreateArchiveOptions, JsonReplacer } from "@js-utils-kit/types";
2
+ import { PathLike } from "node:fs";
2
3
 
3
4
  //#region src/createArchive.d.ts
4
5
  /**
@@ -59,6 +60,115 @@ declare const hasCommonJSFilename: boolean;
59
60
  declare function exists(/** Absolute or relative path to check */
60
61
 
61
62
  path: string): Promise<boolean>;
63
+ /**
64
+ * Check whether the given path points to a file.
65
+ *
66
+ * @returns `true` if the path is a file, otherwise `false`.
67
+ */
68
+ declare function isFile(/** Absolute or relative path to check */
69
+
70
+ path: string): Promise<boolean>;
71
+ /**
72
+ * Check whether the given path points to a directory.
73
+ *
74
+ * @returns `true` if the path is a directory, otherwise `false`.
75
+ */
76
+ declare function isDirectory(/** Absolute or relative path to check */
77
+
78
+ path: string): Promise<boolean>;
79
+ /**
80
+ * Get the size (in bytes) of a file system resource.
81
+ *
82
+ * @returns The size in bytes, or `0` if the path does not exist or cannot be accessed (failure).
83
+ */
84
+ declare function getContentSize(/** Path to check */
85
+
86
+ path: PathLike): Promise<number>;
87
+ //#endregion
88
+ //#region src/json.d.ts
89
+ /**
90
+ * Parse a JSON string into a typed value.
91
+ *
92
+ * @typeParam T - Expected return type of the parsed JSON.
93
+ *
94
+ * @remarks
95
+ * This function does not handle errors. It will throw if the input is invalid JSON.
96
+ *
97
+ * @returns Parsed value cast to type `T`.
98
+ */
99
+ declare function parseJson<T = unknown>(/** JSON string to parse */
100
+
101
+ v: string): T;
102
+ /**
103
+ * Convert a value to a JSON string with optional formatting and transformation.
104
+ *
105
+ * @remarks
106
+ * Defaults to 2-space indentation if `space` is not provided.
107
+ *
108
+ * @returns JSON string representation of the input value.
109
+ *
110
+ */
111
+ declare function stringifyJson(/** The value to stringify */
112
+
113
+ v: unknown, {
114
+ /**
115
+ * Number of spaces or string used for indentation.
116
+ *
117
+ * @default 2
118
+ */
119
+ space,
120
+ /**
121
+ * A function or array to transform or filter values during serialization.
122
+ *
123
+ * @default null
124
+ */
125
+ replacer
126
+ }?: {
127
+ replacer?: JsonReplacer;
128
+ space?: Parameters<typeof JSON.stringify>[2];
129
+ }): string;
130
+ /**
131
+ * Read and parse a JSON file.
132
+ *
133
+ * @typeParam T - Expected type of the parsed JSON content.
134
+ *
135
+ * @throws Will throw if the file cannot be read or contains invalid JSON.
136
+ *
137
+ * @returns Parsed JSON content as type `T`.
138
+ *
139
+ */
140
+ declare function readJsonFile<T = unknown>(/** Path to the JSON file */
141
+
142
+ path: string): Promise<T>;
143
+ /**
144
+ * Serialize data to JSON and write it to a file.
145
+ *
146
+ * @returns A promise that resolves when the file is written.
147
+ *
148
+ * @remarks
149
+ * Overwrites the file if it already exists.
150
+ */
151
+ declare function writeJsonFile(/** Path to the output file */
152
+
153
+ path: string, /** Data to serialize and write */
154
+
155
+ data: unknown, {
156
+ /**
157
+ * Number of spaces or string used for indentation.
158
+ *
159
+ * @default 2
160
+ */
161
+ space,
162
+ /**
163
+ * A function or array to transform or filter values during serialization.
164
+ *
165
+ * @default null
166
+ */
167
+ replacer
168
+ }?: {
169
+ replacer?: JsonReplacer;
170
+ space?: Parameters<typeof JSON.stringify>[2];
171
+ }): Promise<void>;
62
172
  //#endregion
63
173
  //#region src/locator.d.ts
64
174
  /**
@@ -145,7 +255,11 @@ metaUrlOrPath: string): string;
145
255
  * );
146
256
  * ```
147
257
  */
148
- declare function resolveModuleRelative(/** Path relative to the module directory */relativePath: string, /** `import.meta.url` (ESM) or `__filename` (CJS) */metaUrlOrPath: string): string;
258
+ declare function resolveModuleRelative(/** Path relative to the module directory */
259
+
260
+ relativePath: string, /** `import.meta.url` (ESM) or `__filename` (CJS) */
261
+
262
+ metaUrlOrPath: string): string;
149
263
  //#endregion
150
264
  //#region src/path.d.ts
151
265
  /**
@@ -215,4 +329,5 @@ declare function toPlatformPath(/** The path to convert */
215
329
 
216
330
  p: string): string;
217
331
  //#endregion
218
- export { createArchive, exists, hasCommonJSFilename, locateModuleDirectory, locateModuleFile, resolveModuleRelative, toPlatformPath, toPosixPath, toWinPath };
332
+ export { createArchive, exists, getContentSize, hasCommonJSFilename, isDirectory, isFile, locateModuleDirectory, locateModuleFile, parseJson, readJsonFile, resolveModuleRelative, stringifyJson, toPlatformPath, toPosixPath, toWinPath, writeJsonFile };
333
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/createArchive.ts","../src/env.ts","../src/file.ts","../src/json.ts","../src/locator.ts","../src/path.ts"],"mappings":";;;;;;;AA6BA;;;;;;;;;;;;;;;;;;;;iBAAgB,aAAA,CAAA;EACd,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;AAgBA;;;;;AAgBA;;;;iBGoBgB,cAAA;;AAEd,CAAA"}
package/dist/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
- import { CreateArchiveOptions } from "@js-utils-kit/types";
1
+ import { CreateArchiveOptions, JsonReplacer } from "@js-utils-kit/types";
2
+ import { PathLike } from "node:fs";
2
3
 
3
4
  //#region src/createArchive.d.ts
4
5
  /**
@@ -59,6 +60,115 @@ declare const hasCommonJSFilename: boolean;
59
60
  declare function exists(/** Absolute or relative path to check */
60
61
 
61
62
  path: string): Promise<boolean>;
63
+ /**
64
+ * Check whether the given path points to a file.
65
+ *
66
+ * @returns `true` if the path is a file, otherwise `false`.
67
+ */
68
+ declare function isFile(/** Absolute or relative path to check */
69
+
70
+ path: string): Promise<boolean>;
71
+ /**
72
+ * Check whether the given path points to a directory.
73
+ *
74
+ * @returns `true` if the path is a directory, otherwise `false`.
75
+ */
76
+ declare function isDirectory(/** Absolute or relative path to check */
77
+
78
+ path: string): Promise<boolean>;
79
+ /**
80
+ * Get the size (in bytes) of a file system resource.
81
+ *
82
+ * @returns The size in bytes, or `0` if the path does not exist or cannot be accessed (failure).
83
+ */
84
+ declare function getContentSize(/** Path to check */
85
+
86
+ path: PathLike): Promise<number>;
87
+ //#endregion
88
+ //#region src/json.d.ts
89
+ /**
90
+ * Parse a JSON string into a typed value.
91
+ *
92
+ * @typeParam T - Expected return type of the parsed JSON.
93
+ *
94
+ * @remarks
95
+ * This function does not handle errors. It will throw if the input is invalid JSON.
96
+ *
97
+ * @returns Parsed value cast to type `T`.
98
+ */
99
+ declare function parseJson<T = unknown>(/** JSON string to parse */
100
+
101
+ v: string): T;
102
+ /**
103
+ * Convert a value to a JSON string with optional formatting and transformation.
104
+ *
105
+ * @remarks
106
+ * Defaults to 2-space indentation if `space` is not provided.
107
+ *
108
+ * @returns JSON string representation of the input value.
109
+ *
110
+ */
111
+ declare function stringifyJson(/** The value to stringify */
112
+
113
+ v: unknown, {
114
+ /**
115
+ * Number of spaces or string used for indentation.
116
+ *
117
+ * @default 2
118
+ */
119
+ space,
120
+ /**
121
+ * A function or array to transform or filter values during serialization.
122
+ *
123
+ * @default null
124
+ */
125
+ replacer
126
+ }?: {
127
+ replacer?: JsonReplacer;
128
+ space?: Parameters<typeof JSON.stringify>[2];
129
+ }): string;
130
+ /**
131
+ * Read and parse a JSON file.
132
+ *
133
+ * @typeParam T - Expected type of the parsed JSON content.
134
+ *
135
+ * @throws Will throw if the file cannot be read or contains invalid JSON.
136
+ *
137
+ * @returns Parsed JSON content as type `T`.
138
+ *
139
+ */
140
+ declare function readJsonFile<T = unknown>(/** Path to the JSON file */
141
+
142
+ path: string): Promise<T>;
143
+ /**
144
+ * Serialize data to JSON and write it to a file.
145
+ *
146
+ * @returns A promise that resolves when the file is written.
147
+ *
148
+ * @remarks
149
+ * Overwrites the file if it already exists.
150
+ */
151
+ declare function writeJsonFile(/** Path to the output file */
152
+
153
+ path: string, /** Data to serialize and write */
154
+
155
+ data: unknown, {
156
+ /**
157
+ * Number of spaces or string used for indentation.
158
+ *
159
+ * @default 2
160
+ */
161
+ space,
162
+ /**
163
+ * A function or array to transform or filter values during serialization.
164
+ *
165
+ * @default null
166
+ */
167
+ replacer
168
+ }?: {
169
+ replacer?: JsonReplacer;
170
+ space?: Parameters<typeof JSON.stringify>[2];
171
+ }): Promise<void>;
62
172
  //#endregion
63
173
  //#region src/locator.d.ts
64
174
  /**
@@ -145,7 +255,11 @@ metaUrlOrPath: string): string;
145
255
  * );
146
256
  * ```
147
257
  */
148
- declare function resolveModuleRelative(/** Path relative to the module directory */relativePath: string, /** `import.meta.url` (ESM) or `__filename` (CJS) */metaUrlOrPath: string): string;
258
+ declare function resolveModuleRelative(/** Path relative to the module directory */
259
+
260
+ relativePath: string, /** `import.meta.url` (ESM) or `__filename` (CJS) */
261
+
262
+ metaUrlOrPath: string): string;
149
263
  //#endregion
150
264
  //#region src/path.d.ts
151
265
  /**
@@ -215,4 +329,5 @@ declare function toPlatformPath(/** The path to convert */
215
329
 
216
330
  p: string): string;
217
331
  //#endregion
218
- export { createArchive, exists, hasCommonJSFilename, locateModuleDirectory, locateModuleFile, resolveModuleRelative, toPlatformPath, toPosixPath, toWinPath };
332
+ export { createArchive, exists, getContentSize, hasCommonJSFilename, isDirectory, isFile, locateModuleDirectory, locateModuleFile, parseJson, readJsonFile, resolveModuleRelative, stringifyJson, toPlatformPath, toPosixPath, toWinPath, writeJsonFile };
333
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/createArchive.ts","../src/env.ts","../src/file.ts","../src/json.ts","../src/locator.ts","../src/path.ts"],"mappings":";;;;;;;AA6BA;;;;;;;;;;;;;;;;;;;;iBAAgB,aAAA,CAAA;EACd,MAAA;EACA,MAAA;EACA,WAAA;EACA,OAAA;EACA,GAAA;EACA;AAAA,GACC,oBAAA,GAAuB,OAAA;;;;;;;AAP1B;;;;;;;;;;;;;;cCXa,mBAAA;;;;iBCdS,MAAA;;AAEpB,IAAA,WAAY,OAAA;;;;;;iBAeQ,MAAA;;AAEpB,IAAA,WAAY,OAAA;;;;;;iBAcQ,WAAA;;AAEpB,IAAA,WAAY,OAAA;;;;;;iBAcQ,cAAA;;AAEpB,IAAA,EAAM,QAAA,GAAQ,OAAA;;;;;;AF1BhB;;;;;;;iBGhBgB,SAAA,aAAA;;AAEd,CAAA,WAEwB,CAAA;;;;;;;;;;iBAYV,aAAA;;AAEd,CAAA;;;;;;EAOE,KAAA;;;;;AFpBJ;EE0BI;AAAA;EAEA,QAAA,GAAW,YAAA;EACX,KAAA,GAAQ,UAAA,QAAkB,IAAA,CAAK,SAAA;AAAA;;;;AD3CnC;;;;;AAiBA;;iBC4CsB,YAAA,aAAA;;AAEpB,IAAA,WAAY,OAAA,CAAA,CAAA;AD9Bd;;;;;AAgBA;;;AAhBA,iBC4CsB,aAAA;;AAEpB,IAAA;;AAEA,IAAA;;;;;AAxEF;EA+EI,KAAA;;;;;;EAMA;AAAA;EAEA,QAAA,GAAW,YAAA;EACX,KAAA,GAAQ,UAAA,QAAkB,IAAA,CAAK,SAAA;AAAA,IAC3B,OAAA;;;;;;;AHzER;;;;;;;;;;;;;;;;;;;;;;iBIAgB,gBAAA;;AAEd,aAAA;;;;;;;;AHbF;;;;;;;;ACdA;;;iBEuDgB,qBAAA;;AAEd,aAAA;;;;;AFxBF;;;;;AAgBA;;;;;;;;;;;;ACxCA;;;;;;;;;AAgBA;;;;iBCuEgB,qBAAA;;AAEd,YAAA;;AAEA,aAAA;;;;;;;AJ3EF;;;;;;;;;;;;;;;;;iBKNgB,WAAA;;AAEd,CAAA;;;;;;;;;;;;;AJPF;;;;;;;iBI+BgB,SAAA,CH7ChB;;AG+CE,CAAA;;;;AH9BF;;;;;AAgBA;;;;;AAgBA;;;;iBGoBgB,cAAA;;AAEd,CAAA"}
package/dist/index.mjs CHANGED
@@ -1 +1,2 @@
1
- import e from"fs";import t from"path";import n from"archiver";import{access as r}from"node:fs/promises";import{fileURLToPath as i}from"url";function a({format:r,source:i,destination:a,options:o={},log:s=!0,onSuccess:c}){let l=t.resolve(i);if(!e.existsSync(l)||!e.statSync(l).isDirectory())throw Error(`Source directory "${i}" does not exist or is not a directory.`);let u=e.createWriteStream(a);r===`zip`&&(o={...o,zlib:{level:9}});let d=n(r,o);return new Promise((e,t)=>{u.on(`close`,()=>{let t=d.pointer();s&&console.log(`${a} created: ${t} total bytes`),c&&c(t),e()}),d.on(`error`,e=>{t(e)}),d.pipe(u),d.directory(i,!1),d.finalize().catch(e=>t(e instanceof Error?e:Error(String(e))))})}const o=typeof __filename<`u`;async function s(e){try{return await r(e),!0}catch{return!1}}function c(e){if(!e)throw Error(`locateModuleFile requires import.meta.url (ESM) or __filename (CJS).`);return e.startsWith(`file:`)?i(e):e}function l(e){return t.dirname(c(e))}function u(e,n){let r=l(n),i=t.resolve(r,e);if(t.relative(r,i).startsWith(`..`))throw Error(`Resolved path escapes module directory.`);return i}function d(e){return e.replace(/\\/g,`/`)}function f(e){return e.replace(/\//g,`\\`)}function p(e){return e.replace(/[/\\]/g,t.sep)}export{a as createArchive,s as exists,o as hasCommonJSFilename,l as locateModuleDirectory,c as locateModuleFile,u as resolveModuleRelative,p as toPlatformPath,d as toPosixPath,f as toWinPath};
1
+ import e from"fs";import t from"path";import n from"archiver";import{access as r,readFile as i,stat as a,writeFile as o}from"node:fs/promises";import{fileURLToPath as s}from"url";function c({format:r,source:i,destination:a,options:o={},log:s=!0,onSuccess:c}){let l=t.resolve(i);if(!e.existsSync(l)||!e.statSync(l).isDirectory())throw Error(`Source directory "${i}" does not exist or is not a directory.`);let u=e.createWriteStream(a);r===`zip`&&(o={...o,zlib:{level:9}});let d=n(r,o);return new Promise((e,t)=>{u.on(`close`,()=>{let t=d.pointer();s&&console.log(`${a} created: ${t} total bytes`),c&&c(t),e()}),d.on(`error`,e=>{t(e)}),d.pipe(u),d.directory(i,!1),d.finalize().catch(e=>t(e instanceof Error?e:Error(String(e))))})}const l=typeof __filename<`u`;async function u(e){try{return await r(e),!0}catch{return!1}}async function d(e){try{return(await a(e)).isFile()}catch{return!1}}async function f(e){try{return(await a(e)).isDirectory()}catch{return!1}}async function p(e){try{let t=(await a(e)).size;return typeof t==`number`?t:0}catch{return 0}}function m(e){return JSON.parse(e)}function h(e,{space:t=2,replacer:n=null}={}){return typeof n==`function`||Array.isArray(n)?JSON.stringify(e,n,t):JSON.stringify(e,null,t)}async function g(e){return m(await i(e,`utf-8`))}async function _(e,t,{space:n=2,replacer:r=null}={}){await o(e,h(t,{space:n,replacer:r}),`utf-8`)}function v(e){if(!e)throw Error(`locateModuleFile requires import.meta.url (ESM) or __filename (CJS).`);return e.startsWith(`file:`)?s(e):e}function y(e){return t.dirname(v(e))}function b(e,n){let r=y(n),i=t.resolve(r,e);if(t.relative(r,i).startsWith(`..`))throw Error(`Resolved path escapes module directory.`);return i}function x(e){return e.replace(/\\/g,`/`)}function S(e){return e.replace(/\//g,`\\`)}function C(e){return e.replace(/[/\\]/g,t.sep)}export{c as createArchive,u as exists,p as getContentSize,l as hasCommonJSFilename,f as isDirectory,d as isFile,y as locateModuleDirectory,v as locateModuleFile,m as parseJson,g as readJsonFile,b as resolveModuleRelative,h as stringifyJson,C as toPlatformPath,x as toPosixPath,S as toWinPath,_ as writeJsonFile};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/createArchive.ts","../src/env.ts","../src/file.ts","../src/json.ts","../src/locator.ts","../src/path.ts"],"sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport archiver from 'archiver';\nimport type { Archiver } from 'archiver';\nimport type { CreateArchiveOptions } from '@js-utils-kit/types';\n\n/**\n * Creates a {@link ArchiveFormat } archive from a specified directory.\n *\n * This function uses the `archiver` library to package a directory into an archive file.\n * It supports optional compression for `zip` and returns a Promise that resolves\n * when the archive is successfully created.\n *\n * @example\n *\n * Function usage:\n *\n * ```ts\n * await createArchive({\n * format: \"zip\",\n * source: \"dist/\",\n * destination: \"dist.zip\",\n * });\n * ```\n *\n * @returns A Promise that resolves when the archive is created\n *\n * @throws If an error occurs during the archiving process\n */\nexport function createArchive({\n format,\n source,\n destination,\n options = {},\n log = true,\n onSuccess,\n}: CreateArchiveOptions): Promise<void> {\n const resolvedSource = path.resolve(source);\n\n if (!fs.existsSync(resolvedSource) || !fs.statSync(resolvedSource).isDirectory()) {\n throw new Error(`Source directory \"${source}\" does not exist or is not a directory.`);\n }\n\n const output = fs.createWriteStream(destination);\n\n if (format === 'zip') {\n options = {\n ...options,\n /**\n * Maximum compression level for zip is 9.\n */\n zlib: { level: 9 },\n };\n }\n\n const archive: Archiver = archiver(format, options);\n\n return new Promise((resolve, reject) => {\n output.on('close', () => {\n const size = archive.pointer();\n\n if (log) {\n console.log(`${destination} created: ${size} total bytes`);\n }\n if (onSuccess) {\n onSuccess(size);\n }\n\n resolve();\n });\n\n archive.on('error', (err: Error) => {\n reject(err);\n });\n\n archive.pipe(output);\n archive.directory(source, false);\n archive.finalize().catch((err) => reject(err instanceof Error ? err : new Error(String(err))));\n });\n}\n","/**\n * Determines whether the current runtime provides the CommonJS `__filename` variable.\n *\n * @remarks\n * - In CommonJS environments, Node.js injects a module-scoped `__filename` variable representing the absolute path of the current module file.\n * - In pure ESM environments, `__filename` does not exist.\n * - This helper allows environment-aware branching while remaining testable (e.g., via mocking in unit tests).\n *\n * @returns `true` if `__filename` is available in the current runtime; otherwise `false`.\n *\n * @example\n * ```ts\n * if (hasCommonJSFilename) {\n * console.log(\"Running in CommonJS environment\");\n * } else {\n * console.log(\"Running in ESM environment\");\n * }\n */\nexport const hasCommonJSFilename = typeof __filename !== 'undefined';\n","import type { PathLike } from 'node:fs';\nimport { access, stat } from 'node:fs/promises';\n\n/** Check whether a file or directory exists */\nexport async function exists(\n /** Absolute or relative path to check */\n path: string,\n) {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check whether the given path points to a file.\n *\n * @returns `true` if the path is a file, otherwise `false`.\n */\nexport async function isFile(\n /** Absolute or relative path to check */\n path: string,\n) {\n try {\n return (await stat(path)).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * Check whether the given path points to a directory.\n *\n * @returns `true` if the path is a directory, otherwise `false`.\n */\nexport async function isDirectory(\n /** Absolute or relative path to check */\n path: string,\n) {\n try {\n return (await stat(path)).isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Get the size (in bytes) of a file system resource.\n *\n * @returns The size in bytes, or `0` if the path does not exist or cannot be accessed (failure).\n */\nexport async function getContentSize(\n /** Path to check */\n path: PathLike,\n) {\n try {\n const size = (await stat(path)).size;\n return typeof size === 'number' ? size : 0;\n } catch {\n return 0;\n }\n}\n","import { readFile, writeFile } from 'node:fs/promises';\nimport type { JsonReplacer } from '@js-utils-kit/types';\n\n/**\n * Parse a JSON string into a typed value.\n *\n * @typeParam T - Expected return type of the parsed JSON.\n *\n * @remarks\n * This function does not handle errors. It will throw if the input is invalid JSON.\n *\n * @returns Parsed value cast to type `T`.\n */\nexport function parseJson<T = unknown>(\n /** JSON string to parse */\n v: string,\n) {\n return JSON.parse(v) as T;\n}\n\n/**\n * Convert a value to a JSON string with optional formatting and transformation.\n *\n * @remarks\n * Defaults to 2-space indentation if `space` is not provided.\n *\n * @returns JSON string representation of the input value.\n *\n */\nexport function stringifyJson(\n /** The value to stringify */\n v: unknown,\n {\n /**\n * Number of spaces or string used for indentation.\n *\n * @default 2\n */\n space = 2,\n /**\n * A function or array to transform or filter values during serialization.\n *\n * @default null\n */\n replacer = null,\n }: {\n replacer?: JsonReplacer;\n space?: Parameters<typeof JSON.stringify>[2];\n } = {},\n) {\n if (typeof replacer === 'function') return JSON.stringify(v, replacer, space);\n else if (Array.isArray(replacer)) return JSON.stringify(v, replacer, space);\n return JSON.stringify(v, null, space);\n}\n\n/**\n * Read and parse a JSON file.\n *\n * @typeParam T - Expected type of the parsed JSON content.\n *\n * @throws Will throw if the file cannot be read or contains invalid JSON.\n *\n * @returns Parsed JSON content as type `T`.\n *\n */\nexport async function readJsonFile<T = unknown>(\n /** Path to the JSON file */\n path: string,\n) {\n const content = await readFile(path, 'utf-8');\n return parseJson<T>(content);\n}\n\n/**\n * Serialize data to JSON and write it to a file.\n *\n * @returns A promise that resolves when the file is written.\n *\n * @remarks\n * Overwrites the file if it already exists.\n */\nexport async function writeJsonFile(\n /** Path to the output file */\n path: string,\n /** Data to serialize and write */\n data: unknown,\n {\n /**\n * Number of spaces or string used for indentation.\n *\n * @default 2\n */\n space = 2,\n /**\n * A function or array to transform or filter values during serialization.\n *\n * @default null\n */\n replacer = null,\n }: {\n replacer?: JsonReplacer;\n space?: Parameters<typeof JSON.stringify>[2];\n } = {},\n) {\n const content = stringifyJson(data, { space, replacer });\n await writeFile(path, content, 'utf-8');\n}\n","import path from 'path';\nimport { fileURLToPath } from 'url';\n\n/**\n * Returns the absolute file path of a module.\n *\n * @remarks\n * This utility supports both:\n * - **ESM** → pass `import.meta.url`\n * - **CommonJS** → pass `__filename`\n *\n * The path MUST be explicitly provided. Automatic runtime detection is intentionally not performed to avoid incorrect module resolution.\n *\n * @returns Absolute path to the provided module file.\n *\n * @throws {Error} If `metaUrlOrPath` is not provided.\n *\n * @example ESM usage\n * ```ts\n * const file = locateModuleFile(import.meta.url);\n * console.log(file);\n * ```\n *\n * @example CommonJS usage\n * ```ts\n * const file = locateModuleFile(__filename);\n * console.log(file);\n * ```\n */\nexport function locateModuleFile(\n /** `import.meta.url` (ESM) or `__filename` (CJS) */\n metaUrlOrPath: string,\n): string {\n if (!metaUrlOrPath) {\n throw new Error('locateModuleFile requires import.meta.url (ESM) or __filename (CJS).');\n }\n\n return metaUrlOrPath.startsWith('file:') ? fileURLToPath(metaUrlOrPath) : metaUrlOrPath;\n}\n\n/**\n * Returns the absolute directory path of a module.\n *\n * @remarks\n * Internally derives the directory from {@link locateModuleFile}.\n *\n * @returns Absolute directory path.\n *\n * @example ESM\n * ```ts\n * const dir = locateModuleDirectory(import.meta.url);\n * ```\n *\n * @example CommonJS\n * ```ts\n * const dir = locateModuleDirectory(__filename);\n * ```\n */\n\nexport function locateModuleDirectory(\n /** `import.meta.url` (ESM) or `__filename` (CJS) */\n metaUrlOrPath: string,\n) {\n return path.dirname(locateModuleFile(metaUrlOrPath));\n}\n\n/**\n * Resolves a path relative to the provided module's directory.\n *\n * @remarks\n * Useful for loading internal assets such as:\n * - `.hbs` templates\n * - JSON files\n * - SQL schemas\n * - bundled static resources\n *\n * Unlike `process.cwd()`, this resolves relative to the module\n * file location, making it safe for usage inside `node_modules`.\n *\n * @returns Absolute resolved path.\n *\n * @throws {Error}\n * If module path is not provided.\n *\n * @example ESM\n * ```ts\n * const templatePath = resolveModuleRelative(\n * \"../templates/welcome.hbs\",\n * import.meta.url\n * );\n * ```\n *\n * @example CommonJS\n * ```ts\n * const templatePath = resolveModuleRelative(\n * \"../templates/welcome.hbs\",\n * __filename\n * );\n * ```\n */\nexport function resolveModuleRelative(\n /** Path relative to the module directory */\n relativePath: string,\n /** `import.meta.url` (ESM) or `__filename` (CJS) */\n metaUrlOrPath: string,\n) {\n const baseDir = locateModuleDirectory(metaUrlOrPath);\n const resolvedPath = path.resolve(baseDir, relativePath);\n const relative = path.relative(baseDir, resolvedPath);\n\n if (relative.startsWith('..')) {\n throw new Error('Resolved path escapes module directory.');\n }\n\n return resolvedPath;\n}\n","import path from 'path';\n\n/**\n * Converts a file system path to POSIX format.\n *\n * @remarks\n * - Replaces all backslashes (`\\`) with forward slashes (`/`).\n * - Does NOT perform full path normalization (e.g., resolving `.` or `..` segments).\n *\n * @returns The path using POSIX separators (`/`).\n *\n * @example\n * ```ts\n * toPosixPath('C:\\\\Users\\\\TenE\\\\project')\n * // => 'C:/Users/TenE/project'\n * ```\n *\n * @example\n * ```ts\n * toPosixPath('src\\\\utils\\\\file.ts')\n * // => 'src/utils/file.ts'\n * ```\n */\nexport function toPosixPath(\n /** The path to convert */\n p: string,\n): string {\n return p.replace(/\\\\/g, '/');\n}\n\n/**\n * Converts a file system path to Windows (Win32) format.\n *\n * On POSIX systems (Linux/macOS), all forward slashes (`/`) are replaced with backslashes (`\\`).\n *\n * @returns The path using Windows separators (`\\`).\n *\n * @example\n * ```ts\n * toWinPath('src/utils/file.ts')\n * // => 'src\\\\utils\\\\file.ts'\n * ```\n *\n * @example\n * ```ts\n * toWinPath('/usr/local/bin')\n * // => '\\\\usr\\\\local\\\\bin'\n * ```\n */\nexport function toWinPath(\n /** The path to convert */\n p: string,\n): string {\n return p.replace(/\\//g, '\\\\');\n}\n\n/**\n * Converts a file system path to the current platform-specific format.\n *\n * This replaces both forward slashes (`/`) and backslashes (`\\`) with the platform's separator (`path.sep`).\n *\n * - Windows → `\\`\n * - macOS/Linux → `/`\n *\n * @returns The path using the current OS separator.\n *\n * @example Mixed Separators\n * ```ts\n * toPlatformPath('src/utils/file.ts')\n * // On Windows: 'src\\\\utils\\\\file.ts'\n * // On POSIX: 'src/utils/file.ts'\n * ```\n */\nexport function toPlatformPath(\n /** The path to convert */\n p: string,\n): string {\n return p.replace(/[/\\\\]/g, path.sep);\n}\n"],"mappings":"mLA6BA,SAAgB,EAAc,CAC5B,SACA,SACA,cACA,UAAU,EAAE,CACZ,MAAM,GACN,aACsC,CACtC,IAAM,EAAiB,EAAK,QAAQ,EAAO,CAE3C,GAAI,CAAC,EAAG,WAAW,EAAe,EAAI,CAAC,EAAG,SAAS,EAAe,CAAC,aAAa,CAC9E,MAAU,MAAM,qBAAqB,EAAO,yCAAyC,CAGvF,IAAM,EAAS,EAAG,kBAAkB,EAAY,CAE5C,IAAW,QACb,EAAU,CACR,GAAG,EAIH,KAAM,CAAE,MAAO,EAAG,CACnB,EAGH,IAAM,EAAoB,EAAS,EAAQ,EAAQ,CAEnD,OAAO,IAAI,SAAS,EAAS,IAAW,CACtC,EAAO,GAAG,YAAe,CACvB,IAAM,EAAO,EAAQ,SAAS,CAE1B,GACF,QAAQ,IAAI,GAAG,EAAY,YAAY,EAAK,cAAc,CAExD,GACF,EAAU,EAAK,CAGjB,GAAS,EACT,CAEF,EAAQ,GAAG,QAAU,GAAe,CAClC,EAAO,EAAI,EACX,CAEF,EAAQ,KAAK,EAAO,CACpB,EAAQ,UAAU,EAAQ,GAAM,CAChC,EAAQ,UAAU,CAAC,MAAO,GAAQ,EAAO,aAAe,MAAQ,EAAU,MAAM,OAAO,EAAI,CAAC,CAAC,CAAC,EAC9F,CC5DJ,MAAa,EAAsB,OAAO,WAAe,ICdzD,eAAsB,EAEpB,EACA,CACA,GAAI,CAEF,OADA,MAAM,EAAO,EAAK,CACX,QACD,CACN,MAAO,IASX,eAAsB,EAEpB,EACA,CACA,GAAI,CACF,OAAQ,MAAM,EAAK,EAAK,EAAE,QAAQ,MAC5B,CACN,MAAO,IASX,eAAsB,EAEpB,EACA,CACA,GAAI,CACF,OAAQ,MAAM,EAAK,EAAK,EAAE,aAAa,MACjC,CACN,MAAO,IASX,eAAsB,EAEpB,EACA,CACA,GAA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
3
+ "version": "1.7.0",
4
4
  "description": "File system utilities",
5
5
  "homepage": "https://js-utils.js.org",
6
6
  "repository": {
@@ -36,7 +36,7 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "archiver": "^7.0.1",
39
- "@js-utils-kit/types": "1.5.0"
39
+ "@js-utils-kit/types": "1.6.0"
40
40
  },
41
41
  "scripts": {
42
42
  "build": "tsdown",