@stonyx/utils 0.2.3-beta.14 → 0.2.3-beta.15

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/date.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function getTimestamp(dateObject?: Date | null): number;
package/dist/date.js ADDED
@@ -0,0 +1,4 @@
1
+ export function getTimestamp(dateObject = null) {
2
+ const ts = dateObject ? dateObject.getTime() : Date.now();
3
+ return Math.floor(ts / 1000);
4
+ }
package/dist/file.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ interface FileOptions {
2
+ json?: boolean;
3
+ }
4
+ interface ReadFileOptions extends FileOptions {
5
+ missingFileCallback?: (filePath: string) => unknown;
6
+ }
7
+ interface DeleteFileOptions {
8
+ ignoreAccessFailure?: boolean;
9
+ }
10
+ interface ForEachFileImportOptions {
11
+ ignoreAccessFailure?: boolean;
12
+ recursive?: boolean;
13
+ recursiveNaming?: boolean;
14
+ rawName?: boolean;
15
+ namePrefix?: string;
16
+ fullExport?: boolean;
17
+ }
18
+ interface FileImportMeta {
19
+ name: string;
20
+ stats: import('fs').Stats;
21
+ path: string;
22
+ }
23
+ export declare function createFile(filePath: string, data: unknown, options?: FileOptions): Promise<void>;
24
+ export declare function updateFile(filePath: string, data: unknown, options?: FileOptions): Promise<void>;
25
+ interface CopyFileOptions {
26
+ overwrite?: boolean;
27
+ }
28
+ export declare function copyFile(sourcePath: string, targetPath: string, options?: CopyFileOptions): Promise<boolean>;
29
+ export declare function readFile(filePath: string, options?: ReadFileOptions): Promise<unknown>;
30
+ export declare function deleteFile(filePath: string, options?: DeleteFileOptions): Promise<void>;
31
+ export declare function deleteDirectory(dir: string): Promise<void>;
32
+ export declare function createDirectory(dir: string): Promise<void>;
33
+ export declare function forEachFileImport(dir: string, callback: (output: unknown, meta: FileImportMeta) => void, options?: ForEachFileImportOptions): Promise<void>;
34
+ export declare function fileExists(filePath: string): Promise<boolean>;
35
+ export {};
package/dist/file.js ADDED
@@ -0,0 +1,128 @@
1
+ import { getTimestamp } from './date.js';
2
+ import { kebabCaseToCamelCase } from './string.js';
3
+ import { objToJson } from './object.js';
4
+ import { promises as fsp } from 'fs';
5
+ import path from 'path';
6
+ export async function createFile(filePath, data, options = {}) {
7
+ try {
8
+ filePath = path.resolve(filePath);
9
+ await createDirectory(path.dirname(filePath));
10
+ await fsp.writeFile(filePath, options.json ? objToJson(data) : data, 'utf8');
11
+ }
12
+ catch (error) {
13
+ throw new Error(String(error));
14
+ }
15
+ }
16
+ export async function updateFile(filePath, data, options = {}) {
17
+ try {
18
+ await fsp.access(filePath);
19
+ const swapFile = `${filePath}.temp-${getTimestamp()}`;
20
+ await fsp.writeFile(swapFile, options.json ? objToJson(data) : data);
21
+ await fsp.rename(swapFile, filePath);
22
+ }
23
+ catch (error) {
24
+ throw new Error(String(error));
25
+ }
26
+ }
27
+ export async function copyFile(sourcePath, targetPath, options = {}) {
28
+ try {
29
+ sourcePath = path.resolve(sourcePath);
30
+ targetPath = path.resolve(targetPath);
31
+ await fsp.access(sourcePath);
32
+ }
33
+ catch (error) {
34
+ throw new Error(String(error));
35
+ }
36
+ try {
37
+ await fsp.access(targetPath);
38
+ if (!options.overwrite)
39
+ return false;
40
+ }
41
+ catch { }
42
+ try {
43
+ await fsp.copyFile(sourcePath, targetPath);
44
+ }
45
+ catch (error) {
46
+ throw new Error(String(error));
47
+ }
48
+ return true;
49
+ }
50
+ export async function readFile(filePath, options = {}) {
51
+ try {
52
+ filePath = path.resolve(filePath);
53
+ await fsp.access(filePath);
54
+ const fileData = await fsp.readFile(filePath, 'utf8');
55
+ return options.json ? JSON.parse(fileData) : fileData;
56
+ }
57
+ catch (error) {
58
+ const { missingFileCallback } = options;
59
+ if (error.code === 'ENOENT' && missingFileCallback) {
60
+ return missingFileCallback(filePath);
61
+ }
62
+ throw new Error(String(error));
63
+ }
64
+ }
65
+ export async function deleteFile(filePath, options) {
66
+ try {
67
+ filePath = path.resolve(filePath);
68
+ await fsp.access(filePath);
69
+ }
70
+ catch (error) {
71
+ if (options?.ignoreAccessFailure)
72
+ return;
73
+ throw error;
74
+ }
75
+ await fsp.unlink(filePath);
76
+ }
77
+ export async function deleteDirectory(dir) {
78
+ await fsp.rm(dir, { recursive: true, force: true });
79
+ }
80
+ export async function createDirectory(dir) {
81
+ await fsp.mkdir(dir, { recursive: true });
82
+ }
83
+ export async function forEachFileImport(dir, callback, options = {}) {
84
+ if (typeof callback !== 'function')
85
+ throw new Error('Callback must be valid function');
86
+ try {
87
+ await fsp.access(dir);
88
+ }
89
+ catch (error) {
90
+ if (!options.ignoreAccessFailure)
91
+ throw new Error(`Unable to access directory: ${dir}`);
92
+ return;
93
+ }
94
+ const files = await fsp.readdir(dir);
95
+ for (const file of files) {
96
+ const filePath = path.join(dir, file);
97
+ const stats = await fsp.stat(filePath);
98
+ if (options.recursive && stats.isDirectory()) {
99
+ const newOptions = { ...options };
100
+ if (options.recursiveNaming) {
101
+ const pathPrefix = options.rawName ? file : `${kebabCaseToCamelCase(file)}`;
102
+ newOptions.namePrefix = options.namePrefix ? `${options.namePrefix}${pathPrefix}/` : `${pathPrefix}/`;
103
+ }
104
+ await forEachFileImport(filePath, callback, newOptions);
105
+ continue;
106
+ }
107
+ if (!stats.isFile() || !file.endsWith('.js'))
108
+ continue;
109
+ const prefix = process.platform === 'win32' ? 'file://' : '';
110
+ const rawName = file.replace('.js', '');
111
+ let name = options.rawName ? rawName : kebabCaseToCamelCase(rawName);
112
+ if (options.namePrefix)
113
+ name = `${options.namePrefix}${name}`;
114
+ const exported = await import(prefix + path.resolve(filePath));
115
+ const output = !options.fullExport ? exported.default : exported;
116
+ callback(output, { name, stats, path: filePath });
117
+ }
118
+ }
119
+ export async function fileExists(filePath) {
120
+ try {
121
+ filePath = path.resolve(filePath);
122
+ await fsp.access(filePath);
123
+ return true;
124
+ }
125
+ catch (error) {
126
+ return false;
127
+ }
128
+ }
@@ -0,0 +1,11 @@
1
+ export declare function deepCopy<T>(obj: T): T;
2
+ export declare function objToJson(obj: unknown, format?: string | number): string;
3
+ export declare function makeArray<T>(obj: T | T[]): T[];
4
+ interface MergeOptions {
5
+ ignoreNewKeys?: boolean;
6
+ }
7
+ export declare function mergeObject(obj1: Record<string, unknown>, obj2: Record<string, unknown>, options?: MergeOptions): Record<string, unknown>;
8
+ export declare function get(obj: Record<string, unknown>, path: string): unknown;
9
+ export declare function get(obj: unknown, path?: unknown): void;
10
+ export declare function getOrSet<K, V>(map: Map<K, V>, key: K, defaultValue: V | (() => V)): V;
11
+ export {};
package/dist/object.js ADDED
@@ -0,0 +1,58 @@
1
+ export function deepCopy(obj) {
2
+ return JSON.parse(JSON.stringify(obj));
3
+ }
4
+ export function objToJson(obj, format = '\t') {
5
+ return JSON.stringify(obj, null, format);
6
+ }
7
+ export function makeArray(obj) {
8
+ return Array.isArray(obj) ? obj : [obj];
9
+ }
10
+ function cloneShallow(value) {
11
+ if (Array.isArray(value))
12
+ return value.slice();
13
+ if (value && typeof value === 'object')
14
+ return { ...value };
15
+ return value;
16
+ }
17
+ export function mergeObject(obj1, obj2, options = {}) {
18
+ if (Array.isArray(obj1) || Array.isArray(obj2))
19
+ throw new Error('Cannot merge arrays.');
20
+ if (obj1 === null || typeof obj1 !== 'object')
21
+ return cloneShallow(obj2);
22
+ if (obj2 === null || typeof obj2 !== 'object')
23
+ return cloneShallow(obj1);
24
+ const result = {};
25
+ for (const key of Object.keys(obj1))
26
+ result[key] = cloneShallow(obj1[key]);
27
+ for (const key of Object.keys(obj2)) {
28
+ if (options.ignoreNewKeys && !(key in obj1))
29
+ continue;
30
+ const val1 = obj1[key];
31
+ const val2 = obj2[key];
32
+ const shouldMerge = val1 && val2 && typeof val1 === 'object' && typeof val2 === 'object' && !Array.isArray(val1) && !Array.isArray(val2);
33
+ result[key] = shouldMerge ? mergeObject(val1, val2, options) : cloneShallow(val2);
34
+ }
35
+ return result;
36
+ }
37
+ export function get(obj, path) {
38
+ if (arguments.length !== 2)
39
+ return console.error('Get must be called with two arguments; an object and a property key.');
40
+ if (!obj)
41
+ return console.error(`Cannot call get with '${path}' on an undefined object.`);
42
+ if (typeof path !== 'string')
43
+ return console.error('The path provided to get must be a string.');
44
+ let current = obj;
45
+ for (const key of path.split('.')) {
46
+ if (current[key] === undefined)
47
+ return;
48
+ current = current[key];
49
+ }
50
+ return current;
51
+ }
52
+ export function getOrSet(map, key, defaultValue) {
53
+ if (!(map instanceof Map))
54
+ throw new Error('First argument to getOrSet must be a Map.');
55
+ if (!map.has(key))
56
+ map.set(key, typeof defaultValue === "function" ? defaultValue() : defaultValue);
57
+ return map.get(key);
58
+ }
@@ -0,0 +1 @@
1
+ export default function pluralize(word: string): string;
@@ -0,0 +1,87 @@
1
+ // --- Irregular nouns ---
2
+ const irregular = {
3
+ person: 'people',
4
+ man: 'men',
5
+ woman: 'women',
6
+ child: 'children',
7
+ tooth: 'teeth',
8
+ foot: 'feet',
9
+ mouse: 'mice',
10
+ goose: 'geese',
11
+ ox: 'oxen',
12
+ cactus: 'cacti',
13
+ nucleus: 'nuclei',
14
+ syllabus: 'syllabi',
15
+ focus: 'foci',
16
+ fungus: 'fungi',
17
+ appendix: 'appendices',
18
+ index: 'indices',
19
+ criterion: 'criteria',
20
+ phenomenon: 'phenomena',
21
+ die: 'dice',
22
+ thesis: 'theses',
23
+ analysis: 'analyses',
24
+ crisis: 'crises',
25
+ radius: 'radii',
26
+ corpus: 'corpora',
27
+ };
28
+ // --- Uncountables ---
29
+ const uncountable = new Set([
30
+ 'sheep', 'fish', 'deer', 'series', 'species', 'news', 'information',
31
+ 'rice', 'moose', 'bison', 'salmon', 'aircraft', 'offspring'
32
+ ]);
33
+ // --- Exceptions ---
34
+ const fExceptions = new Set(['chief', 'roof', 'belief', 'chef', 'cliff', 'reef', 'proof', 'brief']);
35
+ // Keep only true irregular -o exceptions (consonant + o but take just "s")
36
+ const oExceptions = new Set(['piano', 'photo', 'halo', 'canto', 'solo']);
37
+ // --- Utility to preserve casing ---
38
+ function applyCasing(original, plural) {
39
+ if (original === original.toUpperCase())
40
+ return plural.toUpperCase();
41
+ if (original === original.toLowerCase())
42
+ return plural.toLowerCase();
43
+ if (original[0] === original[0].toUpperCase()) {
44
+ return plural.charAt(0).toUpperCase() + plural.slice(1);
45
+ }
46
+ return plural;
47
+ }
48
+ // --- Rule-based pluralization ---
49
+ const rules = [
50
+ // quiz -> quizzes, waltz -> waltzes, topaz -> topazes
51
+ [/z$/i, w => (/iz$/i.test(w) ? w + 'zes' : w + 'es')],
52
+ // bus -> buses, box -> boxes, church -> churches, but stomach -> stomachs (exclude -ach)
53
+ [/(s|x|ch|sh)$/i, w => (/ach$/i.test(w) ? w + 's' : w + 'es')],
54
+ // vowel + y -> +s (key -> keys)
55
+ [/[aeiou]y$/i, w => w + 's'],
56
+ // consonant + y -> -ies (city -> cities)
57
+ [/y$/i, w => w.slice(0, -1) + 'ies'],
58
+ // -fe -> -ves (knife -> knives), but not chief/roof/etc
59
+ [/fe$/i, w => (fExceptions.has(w) ? w + 's' : w.slice(0, -2) + 'ves')],
60
+ // -f -> -ves (wolf -> wolves), but not cliff/etc
61
+ [/f$/i, w => (fExceptions.has(w) ? w + 's' : w.slice(0, -1) + 'ves')],
62
+ // -sis -> -ses (analysis -> analyses, thesis -> theses)
63
+ [/sis$/i, w => w.slice(0, -2) + 'ses'],
64
+ // vowel + o -> +s (zoo -> zoos, video -> videos, patio -> patios)
65
+ [/[aeiou]o$/i, w => w + 's'],
66
+ // consonant + o -> usually +es, unless in oExceptions
67
+ [/o$/i, w => (oExceptions.has(w) ? w + 's' : w + 'es')],
68
+ // default: just +s
69
+ [/$/i, w => w + 's']
70
+ ];
71
+ // --- Exported pluralizer ---
72
+ export default function pluralize(word) {
73
+ if (typeof word !== 'string' || !/^[a-zA-Z]+$/.test(word))
74
+ return word;
75
+ const lower = word.toLowerCase();
76
+ if (uncountable.has(lower))
77
+ return word;
78
+ if (irregular[lower]) {
79
+ return applyCasing(word, irregular[lower]);
80
+ }
81
+ for (const [pattern, transform] of rules) {
82
+ if (pattern.test(lower)) {
83
+ return applyCasing(word, transform(lower));
84
+ }
85
+ }
86
+ return word; // fallback (shouldn't hit)
87
+ }
@@ -0,0 +1 @@
1
+ export declare function sleep(seconds: number): Promise<void>;
@@ -0,0 +1,5 @@
1
+ export async function sleep(seconds) {
2
+ return new Promise(resolve => {
3
+ setTimeout(resolve, 1000 * seconds);
4
+ });
5
+ }
@@ -0,0 +1,8 @@
1
+ import type { Readable, Writable } from 'stream';
2
+ interface PromptOptions {
3
+ input?: Readable;
4
+ output?: Writable;
5
+ }
6
+ export declare function confirm(question: string, { input, output }?: PromptOptions): Promise<boolean>;
7
+ export declare function prompt(question: string, { input, output }?: PromptOptions): Promise<string>;
8
+ export {};
package/dist/prompt.js ADDED
@@ -0,0 +1,25 @@
1
+ import { createInterface } from 'readline';
2
+ export function confirm(question, { input, output } = {}) {
3
+ const rl = createInterface({
4
+ input: input ?? process.stdin,
5
+ output: output ?? process.stdout,
6
+ });
7
+ return new Promise(resolve => {
8
+ rl.question(`${question} (y/N) `, (answer) => {
9
+ rl.close();
10
+ resolve(answer.trim().toLowerCase() === 'y');
11
+ });
12
+ });
13
+ }
14
+ export function prompt(question, { input, output } = {}) {
15
+ const rl = createInterface({
16
+ input: input ?? process.stdin,
17
+ output: output ?? process.stdout,
18
+ });
19
+ return new Promise(resolve => {
20
+ rl.question(`${question} `, (answer) => {
21
+ rl.close();
22
+ resolve(answer.trim());
23
+ });
24
+ });
25
+ }
@@ -0,0 +1,5 @@
1
+ export declare function kebabCaseToCamelCase(str: string): string;
2
+ export declare function kebabCaseToPascalCase(str: string): string;
3
+ export declare function camelCaseToKebabCase(str: string): string;
4
+ export declare function generateRandomString(length?: number): string;
5
+ export { default as pluralize } from './plurarize.js';
package/dist/string.js ADDED
@@ -0,0 +1,32 @@
1
+ function kebabToCase(str, pascal = false) {
2
+ let out = '';
3
+ let upperNext = pascal; // PascalCase starts uppercase
4
+ for (let i = 0; i < str.length; i++) {
5
+ const ch = str.charAt(i);
6
+ if (ch === '-') {
7
+ upperNext = true;
8
+ }
9
+ else if (upperNext) {
10
+ out += ch.toUpperCase();
11
+ upperNext = false;
12
+ }
13
+ else {
14
+ out += ch;
15
+ }
16
+ }
17
+ return out;
18
+ }
19
+ export function kebabCaseToCamelCase(str) {
20
+ return kebabToCase(str, false);
21
+ }
22
+ export function kebabCaseToPascalCase(str) {
23
+ return kebabToCase(str, true);
24
+ }
25
+ export function camelCaseToKebabCase(str) {
26
+ return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
27
+ }
28
+ export function generateRandomString(length = 8) {
29
+ const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
30
+ return Array(length).fill('').map(() => characters.charAt(Math.floor(Math.random() * characters.length))).join('');
31
+ }
32
+ export { default as pluralize } from './plurarize.js';
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "keywords": [
4
4
  "stonyx-module"
5
5
  ],
6
- "version": "0.2.3-beta.14",
6
+ "version": "0.2.3-beta.15",
7
7
  "description": "Utils module for Stonyx Framework",
8
8
  "repository": {
9
9
  "type": "git",
@@ -11,16 +11,34 @@
11
11
  },
12
12
  "type": "module",
13
13
  "files": [
14
- "src",
14
+ "dist",
15
15
  "README.md"
16
16
  ],
17
17
  "exports": {
18
- "./date": "./src/date.js",
19
- "./object": "./src/object.js",
20
- "./file": "./src/file.js",
21
- "./promise": "./src/promise.js",
22
- "./prompt": "./src/prompt.js",
23
- "./string": "./src/string.js"
18
+ "./date": {
19
+ "types": "./dist/date.d.ts",
20
+ "default": "./dist/date.js"
21
+ },
22
+ "./object": {
23
+ "types": "./dist/object.d.ts",
24
+ "default": "./dist/object.js"
25
+ },
26
+ "./file": {
27
+ "types": "./dist/file.d.ts",
28
+ "default": "./dist/file.js"
29
+ },
30
+ "./promise": {
31
+ "types": "./dist/promise.d.ts",
32
+ "default": "./dist/promise.js"
33
+ },
34
+ "./prompt": {
35
+ "types": "./dist/prompt.d.ts",
36
+ "default": "./dist/prompt.js"
37
+ },
38
+ "./string": {
39
+ "types": "./dist/string.d.ts",
40
+ "default": "./dist/string.js"
41
+ }
24
42
  },
25
43
  "publishConfig": {
26
44
  "access": "public",
@@ -32,12 +50,14 @@
32
50
  "Stone Costa <stone.costa@synamicd.com>"
33
51
  ],
34
52
  "devDependencies": {
53
+ "@types/node": "^25.5.2",
35
54
  "fs": "^0.0.1-security",
36
55
  "qunit": "^2.24.1",
37
- "sinon": "^21.0.0"
56
+ "sinon": "^21.0.0",
57
+ "typescript": "^5.8.3"
38
58
  },
39
- "dependencies": {},
40
59
  "scripts": {
41
- "test": "qunit"
60
+ "build": "tsc",
61
+ "test": "pnpm build && qunit"
42
62
  }
43
63
  }
package/src/date.js DELETED
@@ -1,5 +0,0 @@
1
- export function getTimestamp(dateObject=null) {
2
- const ts = dateObject ? dateObject.getTime() : Date.now();
3
-
4
- return Math.floor(ts / 1000);
5
- }
package/src/file.js DELETED
@@ -1,145 +0,0 @@
1
- import { getTimestamp } from '@stonyx/utils/date';
2
- import { kebabCaseToCamelCase } from '@stonyx/utils/string';
3
- import { objToJson } from '@stonyx/utils/object';
4
- import { promises as fsp } from 'fs';
5
- import path from 'path';
6
-
7
- export async function createFile(filePath, data, options={}) {
8
- try {
9
- filePath = path.resolve(filePath);
10
-
11
- await createDirectory(path.dirname(filePath));
12
- await fsp.writeFile(filePath, options.json ? objToJson(data) : data, 'utf8');
13
- } catch (error) {
14
- throw new Error(error);
15
- }
16
- }
17
-
18
- export async function updateFile(filePath, data, options={}) {
19
- try {
20
- await fsp.access(filePath);
21
-
22
- const swapFile = `${filePath}.temp-${getTimestamp()}`;
23
- await fsp.writeFile(swapFile, options.json ? objToJson(data) : data);
24
- await fsp.rename(swapFile, filePath);
25
- } catch (error) {
26
-
27
- throw new Error(error);
28
- }
29
- }
30
-
31
- export async function copyFile(sourcePath, targetPath, options={}) {
32
- try {
33
- sourcePath = path.resolve(sourcePath);
34
- targetPath = path.resolve(targetPath);
35
- await fsp.access(sourcePath);
36
- } catch (error) {
37
- throw new Error(error);
38
- }
39
-
40
- try {
41
- await fsp.access(targetPath);
42
- if (!options.overwrite) return false;
43
- } catch {}
44
-
45
- try {
46
- await fsp.copyFile(sourcePath, targetPath);
47
- } catch (error) {
48
- throw new Error(error);
49
- }
50
-
51
- return true;
52
- }
53
-
54
- export async function readFile(filePath, options={}) {
55
- try {
56
- filePath = path.resolve(filePath);
57
-
58
- await fsp.access(filePath);
59
- const fileData = await fsp.readFile(filePath, 'utf8');
60
-
61
- return options.json ? JSON.parse(fileData) : fileData;
62
- } catch (error) {
63
- const { missingFileCallback } = options;
64
-
65
- if (error.code === 'ENOENT' && missingFileCallback) {
66
- return missingFileCallback(filePath);
67
- }
68
-
69
- throw new Error(error);
70
- }
71
- }
72
-
73
- export async function deleteFile(filePath, options) {
74
- try {
75
- filePath = path.resolve(filePath);
76
-
77
- await fsp.access(filePath);
78
- } catch (error) {
79
- if (options?.ignoreAccessFailure) return;
80
- throw error;
81
- }
82
-
83
- await fsp.unlink(filePath);
84
- }
85
-
86
- export async function deleteDirectory(dir) {
87
- await fsp.rm(dir, { recursive: true, force: true });
88
- }
89
-
90
- export async function createDirectory(dir) {
91
- await fsp.mkdir(dir, { recursive: true });
92
- }
93
-
94
- export async function forEachFileImport(dir, callback, options={}) {
95
- if (typeof callback !== 'function') throw new Error('Callback must be valid function');
96
-
97
- try {
98
- await fsp.access(dir);
99
- } catch (error) {
100
- if (!options.ignoreAccessFailure) throw new Error(`Unable to access directory: ${dir}`);
101
- return;
102
- }
103
-
104
- const files = await fsp.readdir(dir);
105
-
106
- for (const file of files) {
107
- const filePath = path.join(dir, file);
108
- const stats = await fsp.stat(filePath);
109
-
110
- if (options.recursive && stats.isDirectory()) {
111
- const newOptions = { ...options };
112
-
113
- if (options.recursiveNaming) {
114
- const pathPrefix = options.rawName ? file : `${kebabCaseToCamelCase(file)}`;
115
- newOptions.namePrefix = options.namePrefix ? `${options.namePrefix}${pathPrefix}/` : `${pathPrefix}/`;
116
- }
117
-
118
- await forEachFileImport(filePath, callback, newOptions);
119
- continue;
120
- }
121
-
122
- if (!stats.isFile() || !file.endsWith('.js')) continue;
123
-
124
- const prefix = process.platform === 'win32' ? 'file://' : '';
125
- const rawName = file.replace('.js', '');
126
- let name = options.rawName ? rawName : kebabCaseToCamelCase(rawName);
127
-
128
- if (options.namePrefix) name = `${options.namePrefix}${name}`;
129
-
130
- const exported = await import(prefix + path.resolve(filePath));
131
- const output = !options.fullExport ? exported.default : exported;
132
-
133
- callback(output, { name, stats, path: filePath });
134
- }
135
- }
136
-
137
- export async function fileExists(filePath) {
138
- try {
139
- filePath = path.resolve(filePath);
140
- await fsp.access(filePath);
141
- return true;
142
- } catch (error) {
143
- return false;
144
- }
145
- }
package/src/object.js DELETED
@@ -1,61 +0,0 @@
1
- export function deepCopy(obj) {
2
- return JSON.parse(JSON.stringify(obj));
3
- }
4
-
5
- export function objToJson(obj, format='\t') {
6
- return JSON.stringify(obj, null, format);
7
- }
8
-
9
- export function makeArray(obj) {
10
- return Array.isArray(obj) ? obj : [obj];
11
- }
12
-
13
- function cloneShallow(value) {
14
- if (Array.isArray(value)) return value.slice();
15
- if (value && typeof value === 'object') return { ...value };
16
- return value;
17
- }
18
-
19
- export function mergeObject(obj1, obj2, options={}) {
20
- if (Array.isArray(obj1) || Array.isArray(obj2)) throw new Error('Cannot merge arrays.');
21
-
22
- if (obj1 === null || typeof obj1 !== 'object') return cloneShallow(obj2);
23
- if (obj2 === null || typeof obj2 !== 'object') return cloneShallow(obj1);
24
-
25
- const result = {};
26
-
27
- for (const key of Object.keys(obj1)) result[key] = cloneShallow(obj1[key]);
28
- for (const key of Object.keys(obj2)) {
29
- if (options.ignoreNewKeys && !(key in obj1)) continue;
30
-
31
- const val1 = obj1[key];
32
- const val2 = obj2[key];
33
- const shouldMerge = val1 && val2 && typeof val1 === 'object' && typeof val2 === 'object' && !Array.isArray(val1) && !Array.isArray(val2);
34
- result[key] = shouldMerge ? mergeObject(val1, val2, options) : cloneShallow(val2);
35
-
36
- }
37
-
38
- return result;
39
- }
40
-
41
- export function get(obj, path) {
42
- if (arguments.length !== 2) return console.error('Get must be called with two arguments; an object and a property key.');
43
- if (!obj) return console.error(`Cannot call get with '${path}' on an undefined object.`);
44
- if (typeof path !== 'string') return console.error('The path provided to get must be a string.');
45
-
46
- for (const key of path.split('.')) {
47
- if (obj[key] === undefined) return;
48
-
49
- obj = obj[key];
50
- }
51
-
52
- return obj;
53
- }
54
-
55
- export function getOrSet(map, key, defaultValue) {
56
- if (!(map instanceof Map)) throw new Error('First argument to getOrSet must be a Map.');
57
-
58
- if (!map.has(key)) map.set(key, typeof defaultValue === "function" ? defaultValue() : defaultValue);
59
-
60
- return map.get(key);
61
- }
package/src/plurarize.js DELETED
@@ -1,103 +0,0 @@
1
- // --- Irregular nouns ---
2
- const irregular = {
3
- person: 'people',
4
- man: 'men',
5
- woman: 'women',
6
- child: 'children',
7
- tooth: 'teeth',
8
- foot: 'feet',
9
- mouse: 'mice',
10
- goose: 'geese',
11
- ox: 'oxen',
12
- cactus: 'cacti',
13
- nucleus: 'nuclei',
14
- syllabus: 'syllabi',
15
- focus: 'foci',
16
- fungus: 'fungi',
17
- appendix: 'appendices',
18
- index: 'indices',
19
- criterion: 'criteria',
20
- phenomenon: 'phenomena',
21
- die: 'dice',
22
- thesis: 'theses',
23
- analysis: 'analyses',
24
- crisis: 'crises',
25
- radius: 'radii',
26
- corpus: 'corpora',
27
- };
28
-
29
- // --- Uncountables ---
30
- const uncountable = new Set([
31
- 'sheep', 'fish', 'deer', 'series', 'species', 'news', 'information',
32
- 'rice', 'moose', 'bison', 'salmon', 'aircraft', 'offspring'
33
- ]);
34
-
35
- // --- Exceptions ---
36
- const fExceptions = new Set(['chief', 'roof', 'belief', 'chef', 'cliff', 'reef', 'proof', 'brief']);
37
-
38
- // Keep only true irregular -o exceptions (consonant + o but take just "s")
39
- const oExceptions = new Set(['piano', 'photo', 'halo', 'canto', 'solo']);
40
-
41
- // --- Utility to preserve casing ---
42
- function applyCasing(original, plural) {
43
- if (original === original.toUpperCase()) return plural.toUpperCase();
44
- if (original === original.toLowerCase()) return plural.toLowerCase();
45
- if (original[0] === original[0].toUpperCase()) {
46
- return plural.charAt(0).toUpperCase() + plural.slice(1);
47
- }
48
- return plural;
49
- }
50
-
51
- // --- Rule-based pluralization ---
52
- const rules = [
53
- // quiz → quizzes, waltz → waltzes, topaz → topazes
54
- [/z$/i, w => (/iz$/i.test(w) ? w + 'zes' : w + 'es')],
55
-
56
- // bus → buses, box → boxes, church → churches, but stomach → stomachs (exclude -ach)
57
- [/(s|x|ch|sh)$/i, w => (/ach$/i.test(w) ? w + 's' : w + 'es')],
58
-
59
- // vowel + y → +s (key → keys)
60
- [/[aeiou]y$/i, w => w + 's'],
61
-
62
- // consonant + y → -ies (city → cities)
63
- [/y$/i, w => w.slice(0, -1) + 'ies'],
64
-
65
- // -fe → -ves (knife → knives), but not chief/roof/etc
66
- [/fe$/i, w => (fExceptions.has(w) ? w + 's' : w.slice(0, -2) + 'ves')],
67
-
68
- // -f → -ves (wolf → wolves), but not cliff/etc
69
- [/f$/i, w => (fExceptions.has(w) ? w + 's' : w.slice(0, -1) + 'ves')],
70
-
71
- // -sis → -ses (analysis → analyses, thesis → theses)
72
- [/sis$/i, w => w.slice(0, -2) + 'ses'],
73
-
74
- // vowel + o → +s (zoo → zoos, video → videos, patio → patios)
75
- [/[aeiou]o$/i, w => w + 's'],
76
-
77
- // consonant + o → usually +es, unless in oExceptions
78
- [/o$/i, w => (oExceptions.has(w) ? w + 's' : w + 'es')],
79
-
80
- // default: just +s
81
- [/$/i, w => w + 's']
82
- ];
83
-
84
- // --- Exported pluralizer ---
85
- export default function pluralize(word) {
86
- if (typeof word !== 'string' || !/^[a-zA-Z]+$/.test(word)) return word;
87
-
88
- const lower = word.toLowerCase();
89
-
90
- if (uncountable.has(lower)) return word;
91
-
92
- if (irregular[lower]) {
93
- return applyCasing(word, irregular[lower]);
94
- }
95
-
96
- for (const [pattern, transform] of rules) {
97
- if (pattern.test(lower)) {
98
- return applyCasing(word, transform(lower));
99
- }
100
- }
101
-
102
- return word; // fallback (shouldn't hit)
103
- }
package/src/promise.js DELETED
@@ -1,5 +0,0 @@
1
- export async function sleep(seconds) {
2
- return new Promise(resolve => {
3
- setTimeout(resolve, 1000 * seconds);
4
- })
5
- }
package/src/prompt.js DELETED
@@ -1,29 +0,0 @@
1
- import { createInterface } from 'readline';
2
-
3
- export function confirm(question, { input, output } = {}) {
4
- const rl = createInterface({
5
- input: input ?? process.stdin,
6
- output: output ?? process.stdout,
7
- });
8
-
9
- return new Promise(resolve => {
10
- rl.question(`${question} (y/N) `, answer => {
11
- rl.close();
12
- resolve(answer.trim().toLowerCase() === 'y');
13
- });
14
- });
15
- }
16
-
17
- export function prompt(question, { input, output } = {}) {
18
- const rl = createInterface({
19
- input: input ?? process.stdin,
20
- output: output ?? process.stdout,
21
- });
22
-
23
- return new Promise(resolve => {
24
- rl.question(`${question} `, answer => {
25
- rl.close();
26
- resolve(answer.trim());
27
- });
28
- });
29
- }
package/src/string.js DELETED
@@ -1,35 +0,0 @@
1
- function kebabToCase(str, pascal=false) {
2
- let out = '';
3
- let upperNext = pascal; // PascalCase starts uppercase
4
- for (let i = 0; i < str.length; i++) {
5
- const ch = str.charAt(i);
6
- if (ch === '-') {
7
- upperNext = true;
8
- } else if (upperNext) {
9
- out += ch.toUpperCase();
10
- upperNext = false;
11
- } else {
12
- out += ch;
13
- }
14
- }
15
- return out;
16
- }
17
-
18
- export function kebabCaseToCamelCase(str) {
19
- return kebabToCase(str, false);
20
- }
21
-
22
- export function kebabCaseToPascalCase(str) {
23
- return kebabToCase(str, true);
24
- }
25
-
26
- export function camelCaseToKebabCase(str) {
27
- return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
28
- }
29
-
30
- export function generateRandomString(length=8) {
31
- const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
32
- return Array(length).fill('').map(() => characters.charAt(Math.floor(Math.random() * characters.length))).join('');
33
- }
34
-
35
- export { default as pluralize } from './plurarize.js';