@cyberskill/shared 3.16.0 → 3.18.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.
@@ -1 +1 @@
1
- {"version":3,"file":"storage.util.js","names":[],"sources":["../../../src/node/storage/storage.util.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { getEnv } from '#config/env/index.js';\n\nimport { createTtlEnvelope, isExpiredEnvelope, isTtlEnvelope } from '../../util/storage/storage-envelope.js';\nimport { catchError, log } from '../log/index.js';\nimport { STORAGE_KEY_EXTENSION } from './storage.constant.js';\n\nconst MAX_KEY_LENGTH = 200;\n\ninterface NodeFsDriverState {\n baseDir: string;\n}\n\nexport interface I_StorageDriver {\n init: (options?: unknown) => Promise<void>;\n clear: () => Promise<void>;\n getItem: <T>(key: string) => Promise<T | null>;\n keys: () => Promise<string[]>;\n removeItem: (key: string) => Promise<void>;\n setItem: <T>(key: string, value: T) => Promise<T>;\n}\n\nconst nodeFsDriverState: NodeFsDriverState = {\n baseDir: '',\n};\n\n/**\n * Encodes a storage key into a filename-safe string.\n * Validates key length before encoding to prevent OS filename limits.\n *\n * @throws {RangeError} When key exceeds maximum length.\n */\nfunction encodeKey(key: string): string {\n if (key.length > MAX_KEY_LENGTH) {\n throw new RangeError(`Storage key exceeds maximum length of ${MAX_KEY_LENGTH} characters`);\n }\n return `${encodeURIComponent(key)}${STORAGE_KEY_EXTENSION}`;\n}\n\n/**\n * Decodes a filename-safe key back to the original storage key.\n */\nfunction decodeKey(fileName: string): string {\n return decodeURIComponent(fileName.slice(0, -STORAGE_KEY_EXTENSION.length));\n}\n\n/**\n * Maps a storage key to an absolute file path inside the storage directory.\n */\nfunction getFilePath(key: string, baseDir: string): string {\n return path.join(baseDir, encodeKey(key));\n}\n\n/**\n * Filesystem-backed storage driver that stores JSON-encoded values on disk.\n * Directly implements all storage operations without any external dependencies.\n */\nconst fsDriver: I_StorageDriver = {\n /** Ensures the storage directory exists. */\n async init(baseDir?: unknown) {\n try {\n if (typeof baseDir === 'string' && baseDir.length > 0) {\n nodeFsDriverState.baseDir = baseDir;\n }\n else {\n nodeFsDriverState.baseDir = getEnv().CYBERSKILL_STORAGE_DIRECTORY;\n }\n\n await fs.mkdir(nodeFsDriverState.baseDir, { recursive: true });\n }\n catch (error) {\n log.error('[Storage:init]', error);\n throw error;\n }\n },\n /** Deletes all stored entries atomically by swapping to a fresh directory. */\n async clear() {\n const { baseDir } = nodeFsDriverState;\n\n if (!baseDir) {\n return;\n }\n\n // Atomic swap: create a fresh temp dir, rename old→trash, rename fresh→baseDir, remove trash\n const trashDir = `${baseDir}.trash.${Date.now()}`;\n const freshDir = `${baseDir}.fresh.${Date.now()}`;\n\n try {\n await fs.mkdir(freshDir, { recursive: true });\n // Try atomic rename swap\n try {\n await fs.rename(baseDir, trashDir);\n }\n catch {\n // baseDir might not exist yet; no-op\n }\n await fs.rename(freshDir, baseDir);\n // Clean up trash in the background (non-blocking)\n fs.rm(trashDir, { recursive: true, force: true }).catch(() => { });\n }\n catch {\n // Fallback: non-atomic clear (e.g., cross-device rename)\n await fs.rm(baseDir, { recursive: true, force: true });\n await fs.mkdir(baseDir, { recursive: true });\n // Clean up any leftover temp dirs\n fs.rm(freshDir, { recursive: true, force: true }).catch(() => { });\n fs.rm(trashDir, { recursive: true, force: true }).catch(() => { });\n }\n },\n /** Reads and parses a stored value; returns null when the file is missing. */\n async getItem<T>(key: string): Promise<T | null> {\n const { baseDir } = nodeFsDriverState;\n const filePath = getFilePath(key, baseDir);\n\n try {\n const content = await fs.readFile(filePath, 'utf8');\n\n return JSON.parse(content) as T;\n }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n },\n /** Lists all stored keys. */\n async keys(): Promise<string[]> {\n const { baseDir } = nodeFsDriverState;\n\n try {\n const files = await fs.readdir(baseDir);\n\n return files\n .filter(file => file.endsWith(STORAGE_KEY_EXTENSION))\n .map(decodeKey);\n }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n },\n /** Removes a stored value for the given key. */\n async removeItem(key: string): Promise<void> {\n const { baseDir } = nodeFsDriverState;\n const filePath = getFilePath(key, baseDir);\n\n await fs.rm(filePath, { force: true });\n },\n /** Stores a value as JSON on disk. */\n async setItem<T>(key: string, value: T): Promise<T> {\n const { baseDir } = nodeFsDriverState;\n const filePath = getFilePath(key, baseDir);\n\n await fs.mkdir(baseDir, { recursive: true });\n await fs.writeFile(filePath, JSON.stringify(value), 'utf8');\n\n return value;\n },\n};\n\nlet initPromise: Promise<void> | null = null;\nlet activeDriver: I_StorageDriver = fsDriver;\n\n/**\n * Initializes the storage driver (singleton, idempotent).\n */\nasync function ensureDriverReady(): Promise<I_StorageDriver> {\n if (initPromise) {\n await initPromise;\n return activeDriver;\n }\n\n initPromise = activeDriver.init().catch((error) => {\n initPromise = null;\n throw error;\n });\n\n await initPromise;\n\n return activeDriver;\n}\n\n/**\n * Persistent storage utility object for data persistence across application sessions.\n * Uses a filesystem-backed driver that stores JSON-encoded values on disk,\n * with automatic initialization and error handling.\n */\nexport const storage = {\n /**\n * Initializes the utility with a custom storage driver instead of the default filesystem driver.\n * This allows swapping to Redis, Memory, or cloud-based drivers.\n * Must optionally be called before the first read/write operation.\n *\n * @param driver - The custom storage driver object that adheres to I_StorageDriver.\n */\n async initDriver(driver: I_StorageDriver): Promise<void> {\n activeDriver = driver;\n initPromise = null;\n await ensureDriverReady();\n },\n /**\n * Retrieves a value from persistent storage by key.\n * This method fetches data that was previously stored using the set method.\n * Returns null if the key doesn't exist or if an error occurs.\n *\n * @param key - The unique identifier for the stored value.\n * @returns A promise that resolves to the stored value or null if not found.\n */\n async get<T = unknown>(key: string): Promise<T | null> {\n try {\n const driver = await ensureDriverReady();\n const result = await driver.getItem<unknown>(key);\n\n if (result === null) {\n return null;\n }\n\n if (isTtlEnvelope<T>(result)) {\n if (isExpiredEnvelope(result)) {\n driver.removeItem(key).catch(() => { });\n\n return null;\n }\n\n return result.value;\n }\n\n return result as T;\n }\n catch (error) {\n return catchError(error, { returnValue: null });\n }\n },\n /**\n * Stores a value in persistent storage with a unique key.\n * This method saves data that can be retrieved later using the get method.\n * The data is automatically serialized and stored in the configured storage directory.\n *\n * @param key - The unique identifier for the value to store.\n * @param value - The data to store (will be automatically serialized).\n * @param options - Optional settings, such as `ttlMs` for setting an expiration on the key.\n * @param options.ttlMs - The time-to-live in milliseconds.\n * @returns A promise that resolves when the storage operation is complete.\n */\n async set<T = unknown>(key: string, value: T, options?: { ttlMs?: number }): Promise<void> {\n try {\n const driver = await ensureDriverReady();\n\n let payloadToStore: unknown = value;\n\n if (options?.ttlMs) {\n payloadToStore = createTtlEnvelope(value, options.ttlMs);\n }\n\n await driver.setItem(key, payloadToStore);\n }\n catch (error) {\n catchError(error);\n throw error;\n }\n },\n /**\n * Removes a value from persistent storage by key.\n * This method permanently deletes the stored data associated with the specified key.\n *\n * @param key - The unique identifier of the value to remove.\n * @returns A promise that resolves when the removal operation is complete.\n */\n async remove(key: string): Promise<void> {\n try {\n const driver = await ensureDriverReady();\n\n await driver.removeItem(key);\n }\n catch (error) {\n catchError(error);\n }\n },\n /**\n * Checks if a key exists in persistent storage.\n * This method efficiently checks for key existence and respects TTL parsing.\n * Returns false if the key exists but has expired.\n *\n * @param key - The unique identifier to check.\n * @returns A promise that resolves to true if the key exists and has not expired.\n * @since 3.13.0\n */\n async has(key: string): Promise<boolean> {\n try {\n const driver = await ensureDriverReady();\n const result = await driver.getItem<unknown>(key);\n\n if (result === null) {\n return false;\n }\n\n if (isTtlEnvelope<unknown>(result)) {\n if (isExpiredEnvelope(result)) {\n driver.removeItem(key).catch(() => { });\n\n return false;\n }\n }\n\n return true;\n }\n catch (error) {\n return catchError(error, { returnValue: false });\n }\n },\n /**\n * Clears all entries from storage atomically.\n * @returns A promise that resolves when the clearing operation is complete.\n */\n async clear(): Promise<void> {\n try {\n const driver = await ensureDriverReady();\n await driver.clear();\n }\n catch (error) {\n catchError(error);\n }\n },\n /**\n * Retrieves all storage keys.\n * This method returns an array of all keys that currently have stored values.\n * Returns an empty array if no keys exist or if an error occurs.\n *\n * @returns A promise that resolves to an array of storage keys.\n */\n async keys(): Promise<string[]> {\n try {\n const driver = await ensureDriverReady();\n const keys = await driver.keys();\n\n if (!Array.isArray(keys)) {\n log.warn(`[Storage:keys] Invalid keys response:`, keys);\n return [];\n }\n\n return keys;\n }\n catch (error) {\n return catchError(error, { returnValue: [] });\n }\n },\n /**\n * Gets a human-readable log link for a storage key.\n * This method provides a formatted string that shows the storage directory path\n * and the key name for debugging and manual inspection purposes.\n *\n * @param key - The storage key to generate a log link for.\n * @returns A promise that resolves to a formatted log link string or null if an error occurs.\n */\n async getLogLink(key: string): Promise<string | null> {\n try {\n const storagePath = path.join(getEnv().CYBERSKILL_STORAGE_DIRECTORY, encodeKey(key));\n\n return `${storagePath} (key: ${key})`;\n }\n catch (error) {\n return catchError(error, { returnValue: null });\n }\n },\n /**\n * Retrieves a value from persistent storage, or creates and stores it if it doesn't exist.\n * This method combines check, creation, and storage into a single convenient operation.\n *\n * @param key - The unique identifier for the value.\n * @param factory - A function (sync or async) that generates the value if it's missing or expired.\n * @param options - Optional storage options.\n * @param options.ttlMs - The time-to-live in milliseconds.\n * @returns A promise that resolves to the retrieved or newly created value.\n */\n async getOrSet<T = unknown>(key: string, factory: () => T | Promise<T>, options?: { ttlMs?: number }): Promise<T> {\n let value = await this.get<T>(key);\n\n if (value === null) {\n value = await factory();\n await this.set(key, value, options);\n }\n\n return value;\n },\n};\n\n/**\n * Resets all module-level singleton state used by the storage module.\n * Intended for use in tests to ensure isolation between test cases.\n * Do NOT call this in production code.\n * @since 3.13.0\n */\nexport function resetStorageForTesting(): void {\n initPromise = null;\n activeDriver = fsDriver;\n nodeFsDriverState.baseDir = '';\n}\n"],"mappings":";;;;;;;AASA,IAAM,IAAiB,KAejB,IAAuC,EACzC,SAAS,IAC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,EAAK,KAAK,GAAQ,CAAC,8BAA8B,EAAU,EAAI,CAAC,CAE9D,SAAS,EAAI;WAEhC,GAAO;AACV,UAAO,EAAW,GAAO,EAAE,aAAa,MAAM,CAAC;;;CAavD,MAAM,SAAsB,GAAa,GAA+B,GAA0C;EAC9G,IAAI,IAAQ,MAAM,KAAK,IAAO,EAAI;AAOlC,SALI,MAAU,SACV,IAAQ,MAAM,GAAS,EACvB,MAAM,KAAK,IAAI,GAAK,GAAO,EAAQ,GAGhC;;CAEd;AAQD,SAAgB,IAA+B;AAG3C,CAFA,IAAc,MACd,IAAe,GACf,EAAkB,UAAU"}
1
+ {"version":3,"file":"storage.util.js","names":[],"sources":["../../../src/node/storage/storage.util.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { getEnv } from '#config/env/index.js';\n\nimport { createTtlEnvelope, isExpiredEnvelope, isTtlEnvelope } from '../../util/storage/storage-envelope.js';\nimport { catchError, log } from '../log/index.js';\nimport { STORAGE_KEY_EXTENSION } from './storage.constant.js';\n\nconst MAX_KEY_LENGTH = 200;\n\ninterface NodeFsDriverState {\n baseDir: string;\n}\n\nexport interface I_StorageDriver {\n init: (options?: unknown) => Promise<void>;\n clear: () => Promise<void>;\n getItem: <T>(key: string) => Promise<T | null>;\n keys: () => Promise<string[]>;\n removeItem: (key: string) => Promise<void>;\n setItem: <T>(key: string, value: T) => Promise<T>;\n}\n\nconst nodeFsDriverState: NodeFsDriverState = {\n baseDir: '',\n};\n\n/**\n * Encodes a storage key into a filename-safe string.\n * Validates key length before encoding to prevent OS filename limits.\n *\n * @throws {RangeError} When key exceeds maximum length.\n */\nfunction encodeKey(key: string): string {\n if (key.length > MAX_KEY_LENGTH) {\n throw new RangeError(`Storage key exceeds maximum length of ${MAX_KEY_LENGTH} characters`);\n }\n return `${encodeURIComponent(key)}${STORAGE_KEY_EXTENSION}`;\n}\n\n/**\n * Decodes a filename-safe key back to the original storage key.\n */\nfunction decodeKey(fileName: string): string {\n return decodeURIComponent(fileName.slice(0, -STORAGE_KEY_EXTENSION.length));\n}\n\n/**\n * Maps a storage key to an absolute file path inside the storage directory.\n */\nfunction getFilePath(key: string, baseDir: string): string {\n return path.join(baseDir, encodeKey(key));\n}\n\n/**\n * Filesystem-backed storage driver that stores JSON-encoded values on disk.\n * Directly implements all storage operations without any external dependencies.\n */\nconst fsDriver: I_StorageDriver = {\n /** Ensures the storage directory exists. */\n async init(baseDir?: unknown) {\n try {\n if (typeof baseDir === 'string' && baseDir.length > 0) {\n nodeFsDriverState.baseDir = baseDir;\n }\n else {\n nodeFsDriverState.baseDir = getEnv().CYBERSKILL_STORAGE_DIRECTORY;\n }\n\n await fs.mkdir(nodeFsDriverState.baseDir, { recursive: true });\n }\n catch (error: unknown) {\n log.error('[Storage:init]', error);\n throw error;\n }\n },\n /** Deletes all stored entries atomically by swapping to a fresh directory. */\n async clear() {\n const { baseDir } = nodeFsDriverState;\n\n if (!baseDir) {\n return;\n }\n\n // Atomic swap: create a fresh temp dir, rename old→trash, rename fresh→baseDir, remove trash\n const trashDir = `${baseDir}.trash.${Date.now()}`;\n const freshDir = `${baseDir}.fresh.${Date.now()}`;\n\n try {\n await fs.mkdir(freshDir, { recursive: true });\n // Try atomic rename swap\n try {\n await fs.rename(baseDir, trashDir);\n }\n catch {\n // baseDir might not exist yet; no-op\n }\n await fs.rename(freshDir, baseDir);\n // Clean up trash in the background (non-blocking)\n fs.rm(trashDir, { recursive: true, force: true }).catch(() => { });\n }\n catch {\n // Fallback: non-atomic clear (e.g., cross-device rename)\n await fs.rm(baseDir, { recursive: true, force: true });\n await fs.mkdir(baseDir, { recursive: true });\n // Clean up any leftover temp dirs\n fs.rm(freshDir, { recursive: true, force: true }).catch(() => { });\n fs.rm(trashDir, { recursive: true, force: true }).catch(() => { });\n }\n },\n /** Reads and parses a stored value; returns null when the file is missing. */\n async getItem<T>(key: string): Promise<T | null> {\n const { baseDir } = nodeFsDriverState;\n const filePath = getFilePath(key, baseDir);\n\n try {\n const content = await fs.readFile(filePath, 'utf8');\n\n return JSON.parse(content) as T;\n }\n catch (error: unknown) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n },\n /** Lists all stored keys. */\n async keys(): Promise<string[]> {\n const { baseDir } = nodeFsDriverState;\n\n try {\n const files = await fs.readdir(baseDir);\n\n return files\n .filter(file => file.endsWith(STORAGE_KEY_EXTENSION))\n .map(decodeKey);\n }\n catch (error: unknown) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n },\n /** Removes a stored value for the given key. */\n async removeItem(key: string): Promise<void> {\n const { baseDir } = nodeFsDriverState;\n const filePath = getFilePath(key, baseDir);\n\n await fs.rm(filePath, { force: true });\n },\n /** Stores a value as JSON on disk. */\n async setItem<T>(key: string, value: T): Promise<T> {\n const { baseDir } = nodeFsDriverState;\n const filePath = getFilePath(key, baseDir);\n\n await fs.mkdir(baseDir, { recursive: true });\n await fs.writeFile(filePath, JSON.stringify(value), 'utf8');\n\n return value;\n },\n};\n\nlet initPromise: Promise<void> | null = null;\nlet activeDriver: I_StorageDriver = fsDriver;\n\n/**\n * Initializes the storage driver (singleton, idempotent).\n */\nasync function ensureDriverReady(): Promise<I_StorageDriver> {\n if (initPromise) {\n await initPromise;\n return activeDriver;\n }\n\n initPromise = activeDriver.init().catch((error) => {\n initPromise = null;\n throw error;\n });\n\n await initPromise;\n\n return activeDriver;\n}\n\n/**\n * Persistent storage utility object for data persistence across application sessions.\n * Uses a filesystem-backed driver that stores JSON-encoded values on disk,\n * with automatic initialization and error handling.\n */\nexport const storage = {\n /**\n * Initializes the utility with a custom storage driver instead of the default filesystem driver.\n * This allows swapping to Redis, Memory, or cloud-based drivers.\n * Must optionally be called before the first read/write operation.\n *\n * @param driver - The custom storage driver object that adheres to I_StorageDriver.\n */\n async initDriver(driver: I_StorageDriver): Promise<void> {\n activeDriver = driver;\n initPromise = null;\n await ensureDriverReady();\n },\n /**\n * Retrieves a value from persistent storage by key.\n * This method fetches data that was previously stored using the set method.\n * Returns null if the key doesn't exist or if an error occurs.\n *\n * @param key - The unique identifier for the stored value.\n * @returns A promise that resolves to the stored value or null if not found.\n */\n async get<T = unknown>(key: string): Promise<T | null> {\n try {\n const driver = await ensureDriverReady();\n const result = await driver.getItem<unknown>(key);\n\n if (result === null) {\n return null;\n }\n\n if (isTtlEnvelope<T>(result)) {\n if (isExpiredEnvelope(result)) {\n driver.removeItem(key).catch(() => { });\n\n return null;\n }\n\n return result.value;\n }\n\n return result as T;\n }\n catch (error: unknown) {\n return catchError(error, { returnValue: null });\n }\n },\n /**\n * Stores a value in persistent storage with a unique key.\n * This method saves data that can be retrieved later using the get method.\n * The data is automatically serialized and stored in the configured storage directory.\n *\n * @param key - The unique identifier for the value to store.\n * @param value - The data to store (will be automatically serialized).\n * @param options - Optional settings, such as `ttlMs` for setting an expiration on the key.\n * @param options.ttlMs - The time-to-live in milliseconds.\n * @returns A promise that resolves when the storage operation is complete.\n */\n async set<T = unknown>(key: string, value: T, options?: { ttlMs?: number }): Promise<void> {\n try {\n const driver = await ensureDriverReady();\n\n let payloadToStore: unknown = value;\n\n if (options?.ttlMs) {\n payloadToStore = createTtlEnvelope(value, options.ttlMs);\n }\n\n await driver.setItem(key, payloadToStore);\n }\n catch (error: unknown) {\n catchError(error);\n throw error;\n }\n },\n /**\n * Removes a value from persistent storage by key.\n * This method permanently deletes the stored data associated with the specified key.\n *\n * @param key - The unique identifier of the value to remove.\n * @returns A promise that resolves when the removal operation is complete.\n */\n async remove(key: string): Promise<void> {\n try {\n const driver = await ensureDriverReady();\n\n await driver.removeItem(key);\n }\n catch (error: unknown) {\n catchError(error);\n }\n },\n /**\n * Checks if a key exists in persistent storage.\n * This method efficiently checks for key existence and respects TTL parsing.\n * Returns false if the key exists but has expired.\n *\n * @param key - The unique identifier to check.\n * @returns A promise that resolves to true if the key exists and has not expired.\n * @since 3.13.0\n */\n async has(key: string): Promise<boolean> {\n try {\n const driver = await ensureDriverReady();\n const result = await driver.getItem<unknown>(key);\n\n if (result === null) {\n return false;\n }\n\n if (isTtlEnvelope<unknown>(result)) {\n if (isExpiredEnvelope(result)) {\n driver.removeItem(key).catch(() => { });\n\n return false;\n }\n }\n\n return true;\n }\n catch (error: unknown) {\n return catchError(error, { returnValue: false });\n }\n },\n /**\n * Clears all entries from storage atomically.\n * @returns A promise that resolves when the clearing operation is complete.\n */\n async clear(): Promise<void> {\n try {\n const driver = await ensureDriverReady();\n await driver.clear();\n }\n catch (error: unknown) {\n catchError(error);\n }\n },\n /**\n * Retrieves all storage keys.\n * This method returns an array of all keys that currently have stored values.\n * Returns an empty array if no keys exist or if an error occurs.\n *\n * @returns A promise that resolves to an array of storage keys.\n */\n async keys(): Promise<string[]> {\n try {\n const driver = await ensureDriverReady();\n const keys = await driver.keys();\n\n if (!Array.isArray(keys)) {\n log.warn(`[Storage:keys] Invalid keys response:`, keys);\n return [];\n }\n\n return keys;\n }\n catch (error: unknown) {\n return catchError(error, { returnValue: [] });\n }\n },\n /**\n * Gets a human-readable log link for a storage key.\n * This method provides a formatted string that shows the storage directory path\n * and the key name for debugging and manual inspection purposes.\n *\n * @param key - The storage key to generate a log link for.\n * @returns A promise that resolves to a formatted log link string or null if an error occurs.\n */\n async getLogLink(key: string): Promise<string | null> {\n try {\n const storagePath = path.join(getEnv().CYBERSKILL_STORAGE_DIRECTORY, encodeKey(key));\n\n return `${storagePath} (key: ${key})`;\n }\n catch (error: unknown) {\n return catchError(error, { returnValue: null });\n }\n },\n /**\n * Retrieves a value from persistent storage, or creates and stores it if it doesn't exist.\n * This method combines check, creation, and storage into a single convenient operation.\n *\n * @param key - The unique identifier for the value.\n * @param factory - A function (sync or async) that generates the value if it's missing or expired.\n * @param options - Optional storage options.\n * @param options.ttlMs - The time-to-live in milliseconds.\n * @returns A promise that resolves to the retrieved or newly created value.\n */\n async getOrSet<T = unknown>(key: string, factory: () => T | Promise<T>, options?: { ttlMs?: number }): Promise<T> {\n let value = await this.get<T>(key);\n\n if (value === null) {\n value = await factory();\n await this.set(key, value, options);\n }\n\n return value;\n },\n};\n\n/**\n * Resets all module-level singleton state used by the storage module.\n * Intended for use in tests to ensure isolation between test cases.\n * Do NOT call this in production code.\n * @since 3.13.0\n */\nexport function resetStorageForTesting(): void {\n initPromise = null;\n activeDriver = fsDriver;\n nodeFsDriverState.baseDir = '';\n}\n"],"mappings":";;;;;;;AASA,IAAM,IAAiB,KAejB,IAAuC,EACzC,SAAS,IACZ;AAQD,SAAS,EAAU,GAAqB;AACpC,KAAI,EAAI,SAAS,EACb,OAAU,WAAW,yCAAyC,EAAe,aAAa;AAE9F,QAAO,GAAG,mBAAmB,EAAI,GAAG;;AAMxC,SAAS,EAAU,GAA0B;AACzC,QAAO,mBAAmB,EAAS,MAAM,GAAG,CAAC,EAAsB,OAAO,CAAC;;AAM/E,SAAS,EAAY,GAAa,GAAyB;AACvD,QAAO,EAAK,KAAK,GAAS,EAAU,EAAI,CAAC;;AAO7C,IAAM,IAA4B;CAE9B,MAAM,KAAK,GAAmB;AAC1B,MAAI;AAQA,GAPI,OAAO,KAAY,YAAY,EAAQ,SAAS,IAChD,EAAkB,UAAU,IAG5B,EAAkB,UAAU,GAAQ,CAAC,8BAGzC,MAAM,EAAG,MAAM,EAAkB,SAAS,EAAE,WAAW,IAAM,CAAC;WAE3D,GAAgB;AAEnB,SADA,EAAI,MAAM,kBAAkB,EAAM,EAC5B;;;CAId,MAAM,QAAQ;EACV,IAAM,EAAE,eAAY;AAEpB,MAAI,CAAC,EACD;EAIJ,IAAM,IAAW,GAAG,EAAQ,SAAS,KAAK,KAAK,IACzC,IAAW,GAAG,EAAQ,SAAS,KAAK,KAAK;AAE/C,MAAI;AACA,SAAM,EAAG,MAAM,GAAU,EAAE,WAAW,IAAM,CAAC;AAE7C,OAAI;AACA,UAAM,EAAG,OAAO,GAAS,EAAS;WAEhC;AAKN,GAFA,MAAM,EAAG,OAAO,GAAU,EAAQ,EAElC,EA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C3B,OAAO;WAEjB,GAAgB;AACnB,KAAW,EAAM;;;CAUzB,MAAM,OAA0B;AAC5B,MAAI;GAEA,IAAM,IAAO,OADE,MAAM,GAAmB,EACd,MAAM;AAOhC,UALK,MAAM,QAAQ,EAAK,GAKjB,KAJH,EAAI,KAAK,yCAAyC,EAAK,EAChD,EAAE;WAKV,GAAgB;AACnB,UAAO,EAAW,GAAO,EAAE,aAAa,EAAE,EAAE,CAAC;;;CAWrD,MAAM,WAAW,GAAqC;AAClD,MAAI;AAGA,UAAO,GAFa,EAAK,KAAK,GAAQ,CAAC,8BAA8B,EAAU,EAAI,CAAC,CAE9D,SAAS,EAAI;WAEhC,GAAgB;AACnB,UAAO,EAAW,GAAO,EAAE,aAAa,MAAM,CAAC;;;CAavD,MAAM,SAAsB,GAAa,GAA+B,GAA0C;EAC9G,IAAI,IAAQ,MAAM,KAAK,IAAO,EAAI;AAOlC,SALI,MAAU,SACV,IAAQ,MAAM,GAAS,EACvB,MAAM,KAAK,IAAI,GAAK,GAAO,EAAQ,GAGhC;;CAEd;AAQD,SAAgB,IAA+B;AAG3C,CAFA,IAAc,MACd,IAAe,GACf,EAAkB,UAAU"}
@@ -1 +1 @@
1
- {"version":3,"file":"upload.util.js","names":[],"sources":["../../../src/node/upload/upload.util.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport nodePath from 'node:path';\nimport { Transform } from 'node:stream';\nimport { ReadableStream } from 'node:stream/web';\n\nimport type { I_Return } from '#typescript/index.js';\n\nimport { RESPONSE_STATUS } from '#constant/index.js';\n\nimport type { I_UploadConfig, I_UploadFile, I_UploadFileData, I_UploadOptions, I_UploadTypeConfig, I_UploadValidationConfig } from './upload.type.js';\n\nimport { createWriteStream, mkdirSync, pathExistsSync } from '../fs/index.js';\nimport { log } from '../log/index.js';\nimport { dirname } from '../path/index.js';\nimport { BYTES_PER_MB, DEFAULT_UPLOAD_CONFIG } from './upload.constant.js';\nimport { E_UploadType } from './upload.type.js';\n\n/**\n * Calculates the size of a file from a readable stream.\n * This function reads through the entire stream to determine the total byte size\n * by accumulating the length of each data chunk.\n *\n * @param stream - The readable stream to calculate the size for.\n * @returns A promise that resolves to the total size of the stream in bytes.\n */\nexport async function getFileSizeFromStream(stream: NodeJS.ReadableStream): Promise<number> {\n return new Promise((resolve, reject) => {\n let size = 0;\n stream.on('data', (chunk) => {\n size += chunk.length;\n });\n stream.on('end', () => resolve(size));\n stream.on('error', reject);\n });\n}\n\n/**\n * Extracts and validates file data from an upload file.\n * This function processes upload files by:\n * - Extracting file metadata and creating a readable stream\n * - Calculating the file size from the stream\n * - Validating file size and extension against upload configuration\n * - Returning a standardized response with success status and error codes\n * - Providing validated file data for further processing\n *\n * @param type - The type of upload being processed (IMAGE, VIDEO, DOCUMENT, OTHER).\n * @param file - The upload file object containing file metadata and stream creation method.\n * @param config - Optional upload configuration. If not provided, uses default configuration.\n * @returns A promise that resolves to a standardized response containing validated file data or error information.\n */\nexport async function getAndValidateFile(type: E_UploadType, file: I_UploadFile, config?: I_UploadConfig): Promise<I_Return<I_UploadFileData>> {\n const fileData = await (await file).file;\n const stream = fileData.createReadStream();\n // Stream is consumed here for validation; callers use createReadStream() again for the actual write.\n // This is intentional — createReadStream() is a factory that yields a new stream per call.\n const fileSize = await getFileSizeFromStream(stream);\n const uploadConfig = config ?? createUploadConfig();\n\n const validationResult = validateUpload(\n { filename: fileData.filename, fileSize, mimetype: fileData.mimetype },\n uploadConfig,\n type,\n );\n\n if (!validationResult.isValid) {\n return {\n success: false,\n message: validationResult.error || 'File validation failed',\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n\n return {\n success: true,\n result: fileData,\n message: 'File validated successfully',\n };\n}\n\n/**\n * Creates a validated web-readable stream from an upload file with size validation.\n * This function processes file uploads for web environments by:\n * - Validating file data using getAndValidateFile function\n * - Creating a size validation transform stream to monitor upload progress\n * - Returning a web-compatible ReadableStream with real-time validation\n * - Providing standardized error responses for validation failures\n * - Wrapping the stream in a standardized response format\n *\n * @param type - The type of upload being processed (IMAGE, VIDEO, DOCUMENT, OTHER).\n * @param file - The upload file object containing file metadata and stream creation method.\n * @param config - Optional upload configuration. If not provided, uses default configuration.\n * @returns A promise that resolves to a standardized response containing either a web ReadableStream or error information.\n */\nexport async function getFileWebStream(type: E_UploadType, file: I_UploadFile, config?: I_UploadConfig): Promise<I_Return<ReadableStream<Uint8Array>>> {\n const uploadConfig = config ?? createUploadConfig();\n const typeConfig = uploadConfig[type];\n\n const fileData = await getAndValidateFile(type, file, config);\n\n if (!fileData.success) {\n return fileData;\n }\n\n const { createReadStream } = fileData.result;\n\n let remainingBytes = typeConfig.sizeLimit;\n\n const sizeValidationStream = new Transform({\n transform(chunk: Buffer, _enc: BufferEncoding, cb) {\n remainingBytes -= chunk.length;\n\n if (remainingBytes < 0) {\n cb(new Error(`File size exceeds limit of ${typeConfig.sizeLimit / BYTES_PER_MB}MB`));\n }\n else {\n cb(null, chunk);\n }\n },\n });\n const originalStream = createReadStream();\n const validatedStream = originalStream.pipe(sizeValidationStream);\n\n return {\n success: true,\n result: new ReadableStream<Uint8Array>({\n start(controller) {\n validatedStream.on('data', (chunk: Buffer | string) => {\n controller.enqueue(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);\n });\n validatedStream.on('end', () => controller.close());\n validatedStream.on('error', (err: unknown) => controller.error(err));\n },\n }),\n };\n}\n\n/**\n * Validates if a file has an allowed extension.\n * This function extracts the file extension from the filename and checks if it's\n * included in the list of allowed extensions (case-insensitive comparison).\n *\n * @param filename - The filename to check for valid extension.\n * @param allowedExtensions - An array of allowed file extensions (without dots).\n * @returns True if the file extension is allowed, false otherwise.\n */\nexport function validateFileExtension(filename: string, allowedExtensions: string[]): boolean {\n const lastDotIndex = filename.lastIndexOf('.');\n\n if (lastDotIndex === -1) {\n return false;\n }\n\n const extension = filename.substring(lastDotIndex + 1).toLowerCase();\n\n return allowedExtensions.includes(extension);\n}\n\n/**\n * Validates an upload against the specified configuration.\n * This function performs comprehensive validation including:\n * - File extension validation against allowed extensions\n * - File size validation against size limits\n * - Returns detailed error messages for validation failures\n *\n * @param config - The validation configuration including filename and optional file size.\n * @param uploadConfig - The upload configuration containing allowed extensions and size limits.\n * @param uploadType - The type of upload being validated.\n * @returns An object indicating validation success and optional error message.\n */\nexport function validateUpload(\n config: I_UploadValidationConfig,\n uploadConfig: I_UploadConfig,\n uploadType: E_UploadType,\n): { isValid: boolean; error?: string } {\n const { filename, fileSize, mimetype } = config;\n const typeConfig: I_UploadTypeConfig = uploadConfig[uploadType];\n\n const { allowedExtensions, sizeLimit } = typeConfig;\n\n if (!validateFileExtension(filename, allowedExtensions)) {\n return {\n isValid: false,\n error: `File extension not allowed for ${uploadType.toLowerCase()} files. Allowed extensions: ${allowedExtensions.join(', ')}`,\n };\n }\n\n if (fileSize !== undefined && fileSize > sizeLimit) {\n const maxSizeMB = Math.round(sizeLimit / (1024 * 1024));\n\n return {\n isValid: false,\n error: `File size exceeds limit for ${uploadType.toLowerCase()} files. Maximum size: ${maxSizeMB}MB`,\n };\n }\n\n if (mimetype) {\n let expectedPrefix = '';\n\n if (uploadType === E_UploadType.IMAGE) {\n expectedPrefix = 'image/';\n }\n else if (uploadType === E_UploadType.VIDEO) {\n expectedPrefix = 'video/';\n }\n else if (uploadType === E_UploadType.AUDIO) {\n expectedPrefix = 'audio/';\n }\n\n if (expectedPrefix && !mimetype.startsWith(expectedPrefix)) {\n // Advisory MIME validation - log warning but DO NOT reject\n log.warn(`Advisory Mimetype Warning: File '${filename}' (type: ${uploadType}) has unexpected mimetype '${mimetype}'. Expected prefix: '${expectedPrefix}'`);\n }\n }\n\n return { isValid: true };\n}\n\n/**\n * Creates a default upload configuration with predefined settings for different file types.\n * This function provides sensible defaults for image, video, document, and other file types,\n * including allowed extensions and size limits. The configuration can be customized with overrides.\n *\n * @param overrides - Optional configuration overrides to merge with the default configuration.\n * @returns A complete upload configuration object with defaults and any provided overrides.\n * @since 3.13.0\n */\nexport function createUploadConfig(overrides?: Partial<I_UploadConfig>): I_UploadConfig {\n return { ...DEFAULT_UPLOAD_CONFIG, ...overrides };\n}\n\n/**\n * Uploads a file with comprehensive validation and error handling.\n * This function processes file uploads with the following features:\n * - Input validation for path and file parameters\n * - Configuration validation for all upload types\n * - File validation using getAndValidateFile function\n * - Automatic directory creation\n * - Stream-based file writing\n * - Comprehensive error handling with standardized response codes\n *\n * @param options - Upload configuration including file, path, type, and optional validation config.\n * @returns A promise that resolves to a standardized response with success status, message, file path, and response codes.\n */\nexport async function upload(options: I_UploadOptions): Promise<I_Return<string>> {\n const { path, file, config, type, baseDir } = options;\n\n if (!path || typeof path !== 'string') {\n return {\n success: false,\n message: 'Invalid path provided',\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n\n // Security: Validate path is within allowed base directory to prevent path traversal.\n // When baseDir is provided, the resolved path must start with it.\n // When baseDir is not provided, reject any path containing \"..\" segments.\n const resolvedPath = nodePath.resolve(path);\n\n if (baseDir) {\n const resolvedBase = nodePath.resolve(baseDir) + nodePath.sep;\n if (!resolvedPath.startsWith(resolvedBase) && resolvedPath !== nodePath.resolve(baseDir)) {\n return {\n success: false,\n message: 'Path traversal detected: path resolves outside the allowed base directory',\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n }\n else if (path.includes('..')) {\n return {\n success: false,\n message: 'Path traversal detected: \"..\" segments are not allowed',\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n\n if (!file || typeof file !== 'object') {\n return {\n success: false,\n message: 'Invalid file provided',\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n\n if (config) {\n const requiredTypes = [E_UploadType.IMAGE, E_UploadType.VIDEO, E_UploadType.DOCUMENT, E_UploadType.OTHER];\n\n for (const requiredType of requiredTypes) {\n if (!config[requiredType] || !Array.isArray(config[requiredType].allowedExtensions) || config[requiredType].allowedExtensions.length === 0) {\n return {\n success: false,\n message: `Invalid config for ${requiredType.toLowerCase()} files`,\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n if (typeof config[requiredType].sizeLimit !== 'number' || config[requiredType].sizeLimit <= 0) {\n return {\n success: false,\n message: `Invalid size limit for ${requiredType.toLowerCase()} files`,\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n }\n }\n\n try {\n const fileData = await getAndValidateFile(type, await file, config);\n\n if (!fileData.success) {\n return fileData;\n }\n\n const { createReadStream } = fileData.result;\n\n const dir = dirname(path);\n\n if (!pathExistsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n const readStream = createReadStream();\n const out = createWriteStream(path);\n readStream.pipe(out);\n\n await new Promise<void>((resolve, reject) => {\n out.on('finish', () => resolve());\n out.on('error', (err) => {\n // Destroy the read stream to release resources if write fails\n if ('destroy' in readStream && typeof readStream.destroy === 'function') {\n readStream.destroy();\n }\n reject(err);\n });\n readStream.on('error', (err) => {\n out.destroy();\n reject(err);\n });\n });\n\n return {\n success: true,\n result: path,\n message: 'File uploaded successfully',\n code: RESPONSE_STATUS.OK.CODE,\n };\n }\n catch (error) {\n return {\n success: false,\n message: error instanceof Error ? error.message : 'File upload failed',\n code: RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AAyBA,eAAsB,EAAsB,GAAgD;AACxF,QAAO,IAAI,SAAS,GAAS,MAAW;EACpC,IAAI,IAAO;AAKX,EAJA,EAAO,GAAG,SAAS,MAAU;AACzB,QAAQ,EAAM;IAChB,EACF,EAAO,GAAG,aAAa,EAAQ,EAAK,CAAC,EACrC,EAAO,GAAG,SAAS,EAAO;GAC5B;;AAiBN,eAAsB,EAAmB,GAAoB,GAAoB,GAA8D;CAC3I,IAAM,IAAW,OAAO,MAAM,GAAM,MAI9B,IAAW,MAAM,EAHR,EAAS,kBAAkB,CAGU,EAC9C,IAAe,KAAU,GAAoB,EAE7C,IAAmB,EACrB;EAAE,UAAU,EAAS;EAAU;EAAU,UAAU,EAAS;EA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AAU;GAClD,MAAM,EAAgB,sBAAsB;GAC/C"}
1
+ {"version":3,"file":"upload.util.js","names":[],"sources":["../../../src/node/upload/upload.util.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport nodePath from 'node:path';\nimport { Transform } from 'node:stream';\nimport { ReadableStream } from 'node:stream/web';\n\nimport type { I_Return } from '#typescript/index.js';\n\nimport { RESPONSE_STATUS } from '#constant/index.js';\n\nimport type { I_UploadConfig, I_UploadFile, I_UploadFileData, I_UploadOptions, I_UploadTypeConfig, I_UploadValidationConfig } from './upload.type.js';\n\nimport { createWriteStream, mkdirSync, pathExistsSync } from '../fs/index.js';\nimport { log } from '../log/index.js';\nimport { dirname } from '../path/index.js';\nimport { BYTES_PER_MB, DEFAULT_UPLOAD_CONFIG } from './upload.constant.js';\nimport { E_UploadType } from './upload.type.js';\n\n/**\n * Calculates the size of a file from a readable stream.\n * This function reads through the entire stream to determine the total byte size\n * by accumulating the length of each data chunk.\n *\n * @param stream - The readable stream to calculate the size for.\n * @returns A promise that resolves to the total size of the stream in bytes.\n */\nexport async function getFileSizeFromStream(stream: NodeJS.ReadableStream): Promise<number> {\n return new Promise((resolve, reject) => {\n let size = 0;\n stream.on('data', (chunk) => {\n size += chunk.length;\n });\n stream.on('end', () => resolve(size));\n stream.on('error', reject);\n });\n}\n\n/**\n * Extracts and validates file data from an upload file.\n * This function processes upload files by:\n * - Extracting file metadata and creating a readable stream\n * - Calculating the file size from the stream\n * - Validating file size and extension against upload configuration\n * - Returning a standardized response with success status and error codes\n * - Providing validated file data for further processing\n *\n * @param type - The type of upload being processed (IMAGE, VIDEO, DOCUMENT, OTHER).\n * @param file - The upload file object containing file metadata and stream creation method.\n * @param config - Optional upload configuration. If not provided, uses default configuration.\n * @returns A promise that resolves to a standardized response containing validated file data or error information.\n */\nexport async function getAndValidateFile(type: E_UploadType, file: I_UploadFile, config?: I_UploadConfig): Promise<I_Return<I_UploadFileData>> {\n const fileData = await (await file).file;\n const stream = fileData.createReadStream();\n // Stream is consumed here for validation; callers use createReadStream() again for the actual write.\n // This is intentional — createReadStream() is a factory that yields a new stream per call.\n const fileSize = await getFileSizeFromStream(stream);\n const uploadConfig = config ?? createUploadConfig();\n\n const validationResult = validateUpload(\n { filename: fileData.filename, fileSize, mimetype: fileData.mimetype },\n uploadConfig,\n type,\n );\n\n if (!validationResult.isValid) {\n return {\n success: false,\n message: validationResult.error || 'File validation failed',\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n\n return {\n success: true,\n result: fileData,\n message: 'File validated successfully',\n };\n}\n\n/**\n * Creates a validated web-readable stream from an upload file with size validation.\n * This function processes file uploads for web environments by:\n * - Validating file data using getAndValidateFile function\n * - Creating a size validation transform stream to monitor upload progress\n * - Returning a web-compatible ReadableStream with real-time validation\n * - Providing standardized error responses for validation failures\n * - Wrapping the stream in a standardized response format\n *\n * @param type - The type of upload being processed (IMAGE, VIDEO, DOCUMENT, OTHER).\n * @param file - The upload file object containing file metadata and stream creation method.\n * @param config - Optional upload configuration. If not provided, uses default configuration.\n * @returns A promise that resolves to a standardized response containing either a web ReadableStream or error information.\n */\nexport async function getFileWebStream(type: E_UploadType, file: I_UploadFile, config?: I_UploadConfig): Promise<I_Return<ReadableStream<Uint8Array>>> {\n const uploadConfig = config ?? createUploadConfig();\n const typeConfig = uploadConfig[type];\n\n const fileData = await getAndValidateFile(type, file, config);\n\n if (!fileData.success) {\n return fileData;\n }\n\n const { createReadStream } = fileData.result;\n\n let remainingBytes = typeConfig.sizeLimit;\n\n const sizeValidationStream = new Transform({\n transform(chunk: Buffer, _enc: BufferEncoding, cb) {\n remainingBytes -= chunk.length;\n\n if (remainingBytes < 0) {\n cb(new Error(`File size exceeds limit of ${typeConfig.sizeLimit / BYTES_PER_MB}MB`));\n }\n else {\n cb(null, chunk);\n }\n },\n });\n const originalStream = createReadStream();\n const validatedStream = originalStream.pipe(sizeValidationStream);\n\n return {\n success: true,\n result: new ReadableStream<Uint8Array>({\n start(controller) {\n validatedStream.on('data', (chunk: Buffer | string) => {\n controller.enqueue(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);\n });\n validatedStream.on('end', () => controller.close());\n validatedStream.on('error', (err: unknown) => controller.error(err));\n },\n }),\n };\n}\n\n/**\n * Validates if a file has an allowed extension.\n * This function extracts the file extension from the filename and checks if it's\n * included in the list of allowed extensions (case-insensitive comparison).\n *\n * @param filename - The filename to check for valid extension.\n * @param allowedExtensions - An array of allowed file extensions (without dots).\n * @returns True if the file extension is allowed, false otherwise.\n */\nexport function validateFileExtension(filename: string, allowedExtensions: string[]): boolean {\n const lastDotIndex = filename.lastIndexOf('.');\n\n if (lastDotIndex === -1) {\n return false;\n }\n\n const extension = filename.substring(lastDotIndex + 1).toLowerCase();\n\n return allowedExtensions.includes(extension);\n}\n\n/**\n * Validates an upload against the specified configuration.\n * This function performs comprehensive validation including:\n * - File extension validation against allowed extensions\n * - File size validation against size limits\n * - Returns detailed error messages for validation failures\n *\n * @param config - The validation configuration including filename and optional file size.\n * @param uploadConfig - The upload configuration containing allowed extensions and size limits.\n * @param uploadType - The type of upload being validated.\n * @returns An object indicating validation success and optional error message.\n */\nexport function validateUpload(\n config: I_UploadValidationConfig,\n uploadConfig: I_UploadConfig,\n uploadType: E_UploadType,\n): { isValid: boolean; error?: string } {\n const { filename, fileSize, mimetype } = config;\n const typeConfig: I_UploadTypeConfig = uploadConfig[uploadType];\n\n const { allowedExtensions, sizeLimit } = typeConfig;\n\n if (!validateFileExtension(filename, allowedExtensions)) {\n return {\n isValid: false,\n error: `File extension not allowed for ${uploadType.toLowerCase()} files. Allowed extensions: ${allowedExtensions.join(', ')}`,\n };\n }\n\n if (fileSize !== undefined && fileSize > sizeLimit) {\n const maxSizeMB = Math.round(sizeLimit / (1024 * 1024));\n\n return {\n isValid: false,\n error: `File size exceeds limit for ${uploadType.toLowerCase()} files. Maximum size: ${maxSizeMB}MB`,\n };\n }\n\n if (mimetype) {\n let expectedPrefix = '';\n\n if (uploadType === E_UploadType.IMAGE) {\n expectedPrefix = 'image/';\n }\n else if (uploadType === E_UploadType.VIDEO) {\n expectedPrefix = 'video/';\n }\n else if (uploadType === E_UploadType.AUDIO) {\n expectedPrefix = 'audio/';\n }\n\n if (expectedPrefix && !mimetype.startsWith(expectedPrefix)) {\n // Advisory MIME validation - log warning but DO NOT reject\n log.warn(`Advisory Mimetype Warning: File '${filename}' (type: ${uploadType}) has unexpected mimetype '${mimetype}'. Expected prefix: '${expectedPrefix}'`);\n }\n }\n\n return { isValid: true };\n}\n\n/**\n * Creates a default upload configuration with predefined settings for different file types.\n * This function provides sensible defaults for image, video, document, and other file types,\n * including allowed extensions and size limits. The configuration can be customized with overrides.\n *\n * @param overrides - Optional configuration overrides to merge with the default configuration.\n * @returns A complete upload configuration object with defaults and any provided overrides.\n * @since 3.13.0\n */\nexport function createUploadConfig(overrides?: Partial<I_UploadConfig>): I_UploadConfig {\n return { ...DEFAULT_UPLOAD_CONFIG, ...overrides };\n}\n\n/**\n * Uploads a file with comprehensive validation and error handling.\n * This function processes file uploads with the following features:\n * - Input validation for path and file parameters\n * - Configuration validation for all upload types\n * - File validation using getAndValidateFile function\n * - Automatic directory creation\n * - Stream-based file writing\n * - Comprehensive error handling with standardized response codes\n *\n * @param options - Upload configuration including file, path, type, and optional validation config.\n * @returns A promise that resolves to a standardized response with success status, message, file path, and response codes.\n */\nexport async function upload(options: I_UploadOptions): Promise<I_Return<string>> {\n const { path, file, config, type, baseDir } = options;\n\n if (!path || typeof path !== 'string') {\n return {\n success: false,\n message: 'Invalid path provided',\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n\n // Security: Validate path is within allowed base directory to prevent path traversal.\n // When baseDir is provided, the resolved path must start with it.\n // When baseDir is not provided, reject any path containing \"..\" segments.\n const resolvedPath = nodePath.resolve(path);\n\n if (baseDir) {\n const resolvedBase = nodePath.resolve(baseDir) + nodePath.sep;\n if (!resolvedPath.startsWith(resolvedBase) && resolvedPath !== nodePath.resolve(baseDir)) {\n return {\n success: false,\n message: 'Path traversal detected: path resolves outside the allowed base directory',\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n }\n else if (path.includes('..')) {\n return {\n success: false,\n message: 'Path traversal detected: \"..\" segments are not allowed',\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n\n if (!file || typeof file !== 'object') {\n return {\n success: false,\n message: 'Invalid file provided',\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n\n if (config) {\n const requiredTypes = [E_UploadType.IMAGE, E_UploadType.VIDEO, E_UploadType.DOCUMENT, E_UploadType.OTHER];\n\n for (const requiredType of requiredTypes) {\n if (!config[requiredType] || !Array.isArray(config[requiredType].allowedExtensions) || config[requiredType].allowedExtensions.length === 0) {\n return {\n success: false,\n message: `Invalid config for ${requiredType.toLowerCase()} files`,\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n if (typeof config[requiredType].sizeLimit !== 'number' || config[requiredType].sizeLimit <= 0) {\n return {\n success: false,\n message: `Invalid size limit for ${requiredType.toLowerCase()} files`,\n code: RESPONSE_STATUS.BAD_REQUEST.CODE,\n };\n }\n }\n }\n\n try {\n const fileData = await getAndValidateFile(type, await file, config);\n\n if (!fileData.success) {\n return fileData;\n }\n\n const { createReadStream } = fileData.result;\n\n const dir = dirname(path);\n\n if (!pathExistsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n const readStream = createReadStream();\n const out = createWriteStream(path);\n readStream.pipe(out);\n\n await new Promise<void>((resolve, reject) => {\n out.on('finish', () => resolve());\n out.on('error', (err) => {\n // Destroy the read stream to release resources if write fails\n if ('destroy' in readStream && typeof readStream.destroy === 'function') {\n readStream.destroy();\n }\n reject(err);\n });\n readStream.on('error', (err) => {\n out.destroy();\n reject(err);\n });\n });\n\n return {\n success: true,\n result: path,\n message: 'File uploaded successfully',\n code: RESPONSE_STATUS.OK.CODE,\n };\n }\n catch (error: unknown) {\n return {\n success: false,\n message: error instanceof Error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,IACpB,EAAU,GAAK,EAAE,WAAW,IAAM,CAAC;EAGvC,IAAM,IAAa,GAAkB,EAC/B,IAAM,EAAkB,EAAK;AAkBnC,SAjBA,EAAW,KAAK,EAAI,EAEpB,MAAM,IAAI,SAAe,GAAS,MAAW;AASzC,GARA,EAAI,GAAG,gBAAgB,GAAS,CAAC,EACjC,EAAI,GAAG,UAAU,MAAQ;AAKrB,IAHI,aAAa,KAAc,OAAO,EAAW,WAAY,cACzD,EAAW,SAAS,EAExB,EAAO,EAAI;KACb,EACF,EAAW,GAAG,UAAU,MAAQ;AAE5B,IADA,EAAI,SAAS,EACb,EAAO,EAAI;KACb;IACJ,EAEK;GACH,SAAS;GACT,QAAQ;GACR,SAAS;GACT,MAAM,EAAgB,GAAG;GAC5B;UAEE,GAAgB;AACnB,SAAO;GACH,SAAS;GACT,SAAS,aAAiB,QAAQ,EAAM,UAAU;GAClD,MAAM,EAAgB,sBAAsB;GAC/C"}
@@ -1 +1 @@
1
- {"version":3,"file":"storage.hook.js","names":[],"sources":["../../../src/react/storage/storage.hook.tsx"],"sourcesContent":["import { useCallback, useEffect, useState } from 'react';\n\nimport type { I_Serializer } from '#util/serializer/index.js';\n\nimport { serializer as defaultSerializer } from '#util/serializer/index.js';\n\nimport { catchError } from '../log/index.js';\nimport { storage } from './storage.util.js';\n\n/**\n * React hook that provides persistent storage functionality with automatic serialization.\n * This hook manages state that persists across browser sessions using localStorage,\n * with automatic serialization/deserialization of complex data types. It provides\n * a React-friendly interface for storage operations with proper error handling.\n *\n * Features:\n * - Automatic data serialization and deserialization\n * - Persistent storage across browser sessions\n * - Initial value handling and fallback\n * - Error handling with graceful degradation\n * - Automatic storage synchronization\n * - Support for complex data types via custom serializers\n *\n * @param key - The unique storage key for the data.\n * @param initialValue - Optional initial value to use if no stored value exists.\n * @param serializer - Optional custom serializer for complex data types (defaults to JSON serializer).\n * @returns An object containing the current value, set function, and remove function.\n */\nexport function useStorage<T>(\n key: string,\n initialValue?: T,\n serializer: I_Serializer<T> = defaultSerializer as I_Serializer<T>,\n) {\n const [value, setValue] = useState<T | undefined>(initialValue);\n const [isLoaded, setIsLoaded] = useState(false);\n\n useEffect(() => {\n let isMounted = true;\n\n const loadValue = async () => {\n try {\n const valueFound = await storage.get<string>(key);\n\n if (isMounted) {\n if (valueFound !== null) {\n const parsedValue = serializer.deserialize(valueFound);\n setValue(parsedValue);\n }\n else if (initialValue !== undefined) {\n const serialized = serializer.serialize(initialValue);\n await storage.set(key, serialized);\n setValue(initialValue);\n }\n else {\n setValue(undefined);\n }\n }\n }\n catch (error) {\n catchError(error);\n\n if (isMounted) {\n setValue(initialValue);\n }\n }\n finally {\n if (isMounted)\n setIsLoaded(true);\n }\n };\n\n loadValue();\n\n return () => {\n isMounted = false;\n setIsLoaded(false);\n };\n }, [key, initialValue, serializer]);\n\n useEffect(() => {\n if (!isLoaded)\n return;\n\n const saveValue = async () => {\n try {\n if (value !== undefined) {\n const serialized = serializer.serialize(value);\n await storage.set(key, serialized);\n }\n }\n catch (error) {\n catchError(error);\n }\n };\n\n saveValue();\n }, [value, key, serializer, isLoaded]);\n\n const set = useCallback(\n (newValue: T | ((val: T | undefined) => T)) => {\n setValue((prev) => {\n if (typeof newValue === 'function') {\n return (newValue as (val: T | undefined) => T)(prev);\n }\n return newValue;\n });\n },\n [],\n );\n\n const remove = useCallback(async () => {\n try {\n await storage.remove(key);\n setValue(undefined);\n }\n catch (error) {\n catchError(error);\n }\n }, [key]);\n\n return { value, set, remove };\n}\n"],"mappings":";;;;;AA4BA,SAAgB,EACZ,GACA,GACA,IAA8B,GAChC;CACE,IAAM,CAAC,GAAO,KAAY,EAAwB,EAAa,EACzD,CAAC,GAAU,KAAe,EAAS,GAAM;AAsF/C,QApFA,QAAgB;EACZ,IAAI,IAAY;AAoChB,UAlCkB,YAAY;AAC1B,OAAI;IACA,IAAM,IAAa,MAAM,EAAQ,IAAY,EAAI;AAEjD,QAAI,EACA,KAAI,MAAe,KAEf,GADoB,EAAW,YAAY,EAAW,CACjC;aAEhB,MAAiB,KAAA,GAAW;KACjC,IAAM,IAAa,EAAW,UAAU,EAAa;AAErD,KADA,MAAM,EAAQ,IAAI,GAAK,EAAW,EAClC,EAAS,EAAa;UAGtB,GAAS,KAAA,EAAU;YAIxB,GAAO;AAGV,IAFA,EAAW,EAAM,EAEb,KACA,EAAS,EAAa;aAGtB;AACJ,IAAI,KACA,EAAY,GAAK;;MAIlB,QAEE;AAET,GADA,IAAY,IACZ,EAAY,GAAM;;IAEvB;EAAC;EAAK;EAAc;EAAW,CAAC,EAEnC,QAAgB;AACP,QAGa,YAAY;AAC1B,OAAI;AACA,QAAI,MAAU,KAAA,GAAW;KACrB,IAAM,IAAa,EAAW,UAAU,EAAM;AAC9C,WAAM,EAAQ,IAAI,GAAK,EAAW;;YAGnC,GAAO;AACV,MAAW,EAAM;;MAId;IACZ;EAAC;EAAO;EAAK;EAAY;EAAS,CAAC,EAwB/B;EAAE;EAAO,KAtBJ,GACP,MAA8C;AAC3C,MAAU,MACF,OAAO,KAAa,aACZ,EAAuC,EAAK,GAEjD,EACT;KAEN,EAAE,CACL;EAYoB,QAVN,EAAY,YAAY;AACnC,OAAI;AAEA,IADA,MAAM,EAAQ,OAAO,EAAI,EACzB,EAAS,KAAA,EAAU;YAEhB,GAAO;AACV,MAAW,EAAM;;KAEtB,CAAC,EAAI,CAAC;EAEoB"}
1
+ {"version":3,"file":"storage.hook.js","names":[],"sources":["../../../src/react/storage/storage.hook.tsx"],"sourcesContent":["import { useCallback, useEffect, useState } from 'react';\n\nimport type { I_Serializer } from '#util/serializer/index.js';\n\nimport { serializer as defaultSerializer } from '#util/serializer/index.js';\n\nimport { catchError } from '../log/index.js';\nimport { storage } from './storage.util.js';\n\n/**\n * React hook that provides persistent storage functionality with automatic serialization.\n * This hook manages state that persists across browser sessions using localStorage,\n * with automatic serialization/deserialization of complex data types. It provides\n * a React-friendly interface for storage operations with proper error handling.\n *\n * Features:\n * - Automatic data serialization and deserialization\n * - Persistent storage across browser sessions\n * - Initial value handling and fallback\n * - Error handling with graceful degradation\n * - Automatic storage synchronization\n * - Support for complex data types via custom serializers\n *\n * @param key - The unique storage key for the data.\n * @param initialValue - Optional initial value to use if no stored value exists.\n * @param serializer - Optional custom serializer for complex data types (defaults to JSON serializer).\n * @returns An object containing the current value, set function, and remove function.\n */\nexport function useStorage<T>(\n key: string,\n initialValue?: T,\n serializer: I_Serializer<T> = defaultSerializer as I_Serializer<T>,\n) {\n const [value, setValue] = useState<T | undefined>(initialValue);\n const [isLoaded, setIsLoaded] = useState(false);\n\n useEffect(() => {\n let isMounted = true;\n\n const loadValue = async () => {\n try {\n const valueFound = await storage.get<string>(key);\n\n if (isMounted) {\n if (valueFound !== null) {\n const parsedValue = serializer.deserialize(valueFound);\n setValue(parsedValue);\n }\n else if (initialValue !== undefined) {\n const serialized = serializer.serialize(initialValue);\n await storage.set(key, serialized);\n setValue(initialValue);\n }\n else {\n setValue(undefined);\n }\n }\n }\n catch (error: unknown) {\n catchError(error);\n\n if (isMounted) {\n setValue(initialValue);\n }\n }\n finally {\n if (isMounted)\n setIsLoaded(true);\n }\n };\n\n loadValue();\n\n return () => {\n isMounted = false;\n setIsLoaded(false);\n };\n }, [key, initialValue, serializer]);\n\n useEffect(() => {\n if (!isLoaded)\n return;\n\n const saveValue = async () => {\n try {\n if (value !== undefined) {\n const serialized = serializer.serialize(value);\n await storage.set(key, serialized);\n }\n }\n catch (error: unknown) {\n catchError(error);\n }\n };\n\n saveValue();\n }, [value, key, serializer, isLoaded]);\n\n const set = useCallback(\n (newValue: T | ((val: T | undefined) => T)) => {\n setValue((prev) => {\n if (typeof newValue === 'function') {\n return (newValue as (val: T | undefined) => T)(prev);\n }\n return newValue;\n });\n },\n [],\n );\n\n const remove = useCallback(async () => {\n try {\n await storage.remove(key);\n setValue(undefined);\n }\n catch (error: unknown) {\n catchError(error);\n }\n }, [key]);\n\n return { value, set, remove };\n}\n"],"mappings":";;;;;AA4BA,SAAgB,EACZ,GACA,GACA,IAA8B,GAChC;CACE,IAAM,CAAC,GAAO,KAAY,EAAwB,EAAa,EACzD,CAAC,GAAU,KAAe,EAAS,GAAM;AAsF/C,QApFA,QAAgB;EACZ,IAAI,IAAY;AAoChB,UAlCkB,YAAY;AAC1B,OAAI;IACA,IAAM,IAAa,MAAM,EAAQ,IAAY,EAAI;AAEjD,QAAI,EACA,KAAI,MAAe,KAEf,GADoB,EAAW,YAAY,EAAW,CACjC;aAEhB,MAAiB,KAAA,GAAW;KACjC,IAAM,IAAa,EAAW,UAAU,EAAa;AAErD,KADA,MAAM,EAAQ,IAAI,GAAK,EAAW,EAClC,EAAS,EAAa;UAGtB,GAAS,KAAA,EAAU;YAIxB,GAAgB;AAGnB,IAFA,EAAW,EAAM,EAEb,KACA,EAAS,EAAa;aAGtB;AACJ,IAAI,KACA,EAAY,GAAK;;MAIlB,QAEE;AAET,GADA,IAAY,IACZ,EAAY,GAAM;;IAEvB;EAAC;EAAK;EAAc;EAAW,CAAC,EAEnC,QAAgB;AACP,QAGa,YAAY;AAC1B,OAAI;AACA,QAAI,MAAU,KAAA,GAAW;KACrB,IAAM,IAAa,EAAW,UAAU,EAAM;AAC9C,WAAM,EAAQ,IAAI,GAAK,EAAW;;YAGnC,GAAgB;AACnB,MAAW,EAAM;;MAId;IACZ;EAAC;EAAO;EAAK;EAAY;EAAS,CAAC,EAwB/B;EAAE;EAAO,KAtBJ,GACP,MAA8C;AAC3C,MAAU,MACF,OAAO,KAAa,aACZ,EAAuC,EAAK,GAEjD,EACT;KAEN,EAAE,CACL;EAYoB,QAVN,EAAY,YAAY;AACnC,OAAI;AAEA,IADA,MAAM,EAAQ,OAAO,EAAI,EACzB,EAAS,KAAA,EAAU;YAEhB,GAAgB;AACnB,MAAW,EAAM;;KAEtB,CAAC,EAAI,CAAC;EAEoB"}
@@ -1 +1 @@
1
- {"version":3,"file":"storage.util.js","names":[],"sources":["../../../src/react/storage/storage.util.ts"],"sourcesContent":["import { createTtlEnvelope, isExpiredEnvelope, isTtlEnvelope } from '../../util/storage/storage-envelope.js';\nimport { catchError } from '../log/index.js';\n\n/**\n * Browser storage utility object using native localStorage.\n * This object provides a unified interface for browser storage operations\n * with comprehensive error handling and type safety.\n * Values are stored as JSON strings for consistent serialization.\n */\nexport const storage = {\n /**\n * Retrieves a value from browser storage by key.\n * This method fetches data that was previously stored using the set method.\n * Returns null if the key doesn't exist or if an error occurs during retrieval.\n *\n * @param key - The unique identifier for the stored value.\n * @returns A promise that resolves to the stored value or null if not found.\n */\n async get<T = unknown>(key: string): Promise<T | null> {\n try {\n const raw = localStorage.getItem(key);\n\n if (raw === null) {\n return null;\n }\n\n const obj = JSON.parse(raw);\n\n if (isTtlEnvelope<T>(obj)) {\n if (isExpiredEnvelope(obj)) {\n localStorage.removeItem(key);\n\n return null;\n }\n\n return obj.value;\n }\n\n return obj as T;\n }\n catch (error) {\n return catchError(error, { returnValue: null });\n }\n },\n /**\n * Stores a value in browser storage with a unique key.\n * This method saves data that can be retrieved later using the get method.\n * The data is automatically serialized to JSON.\n *\n * @param key - The unique identifier for the value to store.\n * @param value - The data to store (will be automatically serialized to JSON).\n * @param options - Optional settings.\n * @param options.ttlMs - The time-to-live in milliseconds.\n * @returns A promise that resolves when the storage operation is complete.\n */\n async set<T = unknown>(key: string, value: T, options?: { ttlMs?: number }): Promise<void> {\n try {\n let payloadToStore: unknown = value;\n\n if (options?.ttlMs) {\n payloadToStore = createTtlEnvelope(value, options.ttlMs);\n }\n\n localStorage.setItem(key, JSON.stringify(payloadToStore));\n }\n catch (error) {\n catchError(error);\n }\n },\n /**\n * Removes a value from browser storage by key.\n * This method permanently deletes the stored data associated with the specified key.\n * If the key doesn't exist, the operation completes successfully without error.\n *\n * @param key - The unique identifier of the value to remove.\n * @returns A promise that resolves when the removal operation is complete.\n */\n async remove(key: string): Promise<void> {\n try {\n localStorage.removeItem(key);\n }\n catch (error) {\n catchError(error);\n }\n },\n /**\n * Retrieves all storage keys.\n * This method returns an array of all keys that currently have stored values.\n * Returns an empty array if no keys exist or if an error occurs during retrieval.\n *\n * @returns A promise that resolves to an array of storage keys.\n */\n async keys(): Promise<string[]> {\n try {\n const keys: string[] = [];\n\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n\n if (key !== null) {\n keys.push(key);\n }\n }\n\n return keys;\n }\n catch (error) {\n return catchError(error, { returnValue: [] });\n }\n },\n /**\n * Checks if a key exists in browser storage.\n * This method efficiently checks for key existence without deserializing the value.\n * It also respects TTL — returns false if the key exists but has expired.\n *\n * @param key - The unique identifier to check.\n * @returns A promise that resolves to true if the key exists and has not expired.\n */\n async has(key: string): Promise<boolean> {\n try {\n const raw = localStorage.getItem(key);\n\n if (raw === null) {\n return false;\n }\n\n const obj = JSON.parse(raw);\n\n if (isTtlEnvelope<unknown>(obj)) {\n if (isExpiredEnvelope(obj)) {\n localStorage.removeItem(key);\n\n return false;\n }\n }\n\n return true;\n }\n catch (error) {\n return catchError(error, { returnValue: false });\n }\n },\n /**\n * Clears all values from browser storage.\n * This method permanently removes all stored data.\n *\n * @returns A promise that resolves when the clear operation is complete.\n */\n async clear(): Promise<void> {\n try {\n localStorage.clear();\n }\n catch (error) {\n catchError(error);\n }\n },\n /**\n * Retrieves a value from browser storage, or creates and stores it if it doesn't exist.\n * This method combines check, creation, and storage into a single convenient operation.\n *\n * @param key - The unique identifier for the value.\n * @param factory - A function (sync or async) that generates the value if it's missing or expired.\n * @param options - Optional storage options.\n * @param options.ttlMs - The time-to-live in milliseconds.\n * @returns A promise that resolves to the retrieved or newly created value.\n */\n async getOrSet<T = unknown>(key: string, factory: () => T | Promise<T>, options?: { ttlMs?: number }): Promise<T> {\n let value = await this.get<T>(key);\n\n if (value === null) {\n value = await factory();\n await this.set(key, value, options);\n }\n\n return value;\n },\n};\n"],"mappings":";;;AASA,IAAa,IAAU;CASnB,MAAM,IAAiB,GAAgC;AACnD,MAAI;GACA,IAAM,IAAM,aAAa,QAAQ,EAAI;AAErC,OAAI,MAAQ,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AAI;AAOlC,SALI,MAAU,SACV,IAAQ,MAAM,GAAS,EACvB,MAAM,KAAK,IAAI,GAAK,GAAO,EAAQ,GAGhC;;CAEd"}
1
+ {"version":3,"file":"storage.util.js","names":[],"sources":["../../../src/react/storage/storage.util.ts"],"sourcesContent":["import { createTtlEnvelope, isExpiredEnvelope, isTtlEnvelope } from '../../util/storage/storage-envelope.js';\nimport { catchError } from '../log/index.js';\n\n/**\n * Browser storage utility object using native localStorage.\n * This object provides a unified interface for browser storage operations\n * with comprehensive error handling and type safety.\n * Values are stored as JSON strings for consistent serialization.\n */\nexport const storage = {\n /**\n * Retrieves a value from browser storage by key.\n * This method fetches data that was previously stored using the set method.\n * Returns null if the key doesn't exist or if an error occurs during retrieval.\n *\n * @param key - The unique identifier for the stored value.\n * @returns A promise that resolves to the stored value or null if not found.\n */\n async get<T = unknown>(key: string): Promise<T | null> {\n try {\n const raw = localStorage.getItem(key);\n\n if (raw === null) {\n return null;\n }\n\n const obj = JSON.parse(raw);\n\n if (isTtlEnvelope<T>(obj)) {\n if (isExpiredEnvelope(obj)) {\n localStorage.removeItem(key);\n\n return null;\n }\n\n return obj.value;\n }\n\n return obj as T;\n }\n catch (error: unknown) {\n return catchError(error, { returnValue: null });\n }\n },\n /**\n * Stores a value in browser storage with a unique key.\n * This method saves data that can be retrieved later using the get method.\n * The data is automatically serialized to JSON.\n *\n * @param key - The unique identifier for the value to store.\n * @param value - The data to store (will be automatically serialized to JSON).\n * @param options - Optional settings.\n * @param options.ttlMs - The time-to-live in milliseconds.\n * @returns A promise that resolves when the storage operation is complete.\n */\n async set<T = unknown>(key: string, value: T, options?: { ttlMs?: number }): Promise<void> {\n try {\n let payloadToStore: unknown = value;\n\n if (options?.ttlMs) {\n payloadToStore = createTtlEnvelope(value, options.ttlMs);\n }\n\n localStorage.setItem(key, JSON.stringify(payloadToStore));\n }\n catch (error: unknown) {\n catchError(error);\n }\n },\n /**\n * Removes a value from browser storage by key.\n * This method permanently deletes the stored data associated with the specified key.\n * If the key doesn't exist, the operation completes successfully without error.\n *\n * @param key - The unique identifier of the value to remove.\n * @returns A promise that resolves when the removal operation is complete.\n */\n async remove(key: string): Promise<void> {\n try {\n localStorage.removeItem(key);\n }\n catch (error: unknown) {\n catchError(error);\n }\n },\n /**\n * Retrieves all storage keys.\n * This method returns an array of all keys that currently have stored values.\n * Returns an empty array if no keys exist or if an error occurs during retrieval.\n *\n * @returns A promise that resolves to an array of storage keys.\n */\n async keys(): Promise<string[]> {\n try {\n const keys: string[] = [];\n\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n\n if (key !== null) {\n keys.push(key);\n }\n }\n\n return keys;\n }\n catch (error: unknown) {\n return catchError(error, { returnValue: [] });\n }\n },\n /**\n * Checks if a key exists in browser storage.\n * This method efficiently checks for key existence without deserializing the value.\n * It also respects TTL — returns false if the key exists but has expired.\n *\n * @param key - The unique identifier to check.\n * @returns A promise that resolves to true if the key exists and has not expired.\n */\n async has(key: string): Promise<boolean> {\n try {\n const raw = localStorage.getItem(key);\n\n if (raw === null) {\n return false;\n }\n\n const obj = JSON.parse(raw);\n\n if (isTtlEnvelope<unknown>(obj)) {\n if (isExpiredEnvelope(obj)) {\n localStorage.removeItem(key);\n\n return false;\n }\n }\n\n return true;\n }\n catch (error: unknown) {\n return catchError(error, { returnValue: false });\n }\n },\n /**\n * Clears all values from browser storage.\n * This method permanently removes all stored data.\n *\n * @returns A promise that resolves when the clear operation is complete.\n */\n async clear(): Promise<void> {\n try {\n localStorage.clear();\n }\n catch (error: unknown) {\n catchError(error);\n }\n },\n /**\n * Retrieves a value from browser storage, or creates and stores it if it doesn't exist.\n * This method combines check, creation, and storage into a single convenient operation.\n *\n * @param key - The unique identifier for the value.\n * @param factory - A function (sync or async) that generates the value if it's missing or expired.\n * @param options - Optional storage options.\n * @param options.ttlMs - The time-to-live in milliseconds.\n * @returns A promise that resolves to the retrieved or newly created value.\n */\n async getOrSet<T = unknown>(key: string, factory: () => T | Promise<T>, options?: { ttlMs?: number }): Promise<T> {\n let value = await this.get<T>(key);\n\n if (value === null) {\n value = await factory();\n await this.set(key, value, options);\n }\n\n return value;\n },\n};\n"],"mappings":";;;AASA,IAAa,IAAU;CASnB,MAAM,IAAiB,GAAgC;AACnD,MAAI;GACA,IAAM,IAAM,aAAa,QAAQ,EAAI;AAErC,OAAI,MAAQ,KACR,QAAO;GAGX,IAAM,IAAM,KAAK,MAAM,EAAI;AAY3B,UAVI,EAAiB,EAAI,GACjB,EAAkB,EAAI,IACtB,aAAa,WAAW,EAAI,EAErB,QAGJ,EAAI,QAGR;WAEJ,GAAgB;AACnB,UAAO,EAAW,GAAO,EAAE,aAAa,MAAM,CAAC;;;CAcvD,MAAM,IAAiB,GAAa,GAAU,GAA6C;AACvF,MAAI;GACA,IAAI,IAA0B;AAM9B,GAJI,GAAS,UACT,IAAiB,EAAkB,GAAO,EAAQ,MAAM,GAG5D,aAAa,QAAQ,GAAK,KAAK,UAAU,EAAe,CAAC;WAEtD,GAAgB;AACnB,KAAW,EAAM;;;CAWzB,MAAM,OAAO,GAA4B;AACrC,MAAI;AACA,gBAAa,WAAW,EAAI;WAEzB,GAAgB;AACnB,KAAW,EAAM;;;CAUzB,MAAM,OAA0B;AAC5B,MAAI;GACA,IAAM,IAAiB,EAAE;AAEzB,QAAK,IAAI,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;IAC1C,IAAM,IAAM,aAAa,IAAI,EAAE;AAE/B,IAAI,MAAQ,QACR,EAAK,KAAK,EAAI;;AAItB,UAAO;WAEJ,GAAgB;AACnB,UAAO,EAAW,GAAO,EAAE,aAAa,EAAE,EAAE,CAAC;;;CAWrD,MAAM,IAAI,GAA+B;AACrC,MAAI;GACA,IAAM,IAAM,aAAa,QAAQ,EAAI;AAErC,OAAI,MAAQ,KACR,QAAO;GAGX,IAAM,IAAM,KAAK,MAAM,EAAI;AAU3B,UARI,EAAuB,EAAI,IACvB,EAAkB,EAAI,IACtB,aAAa,WAAW,EAAI,EAErB,MAIR;WAEJ,GAAgB;AACnB,UAAO,EAAW,GAAO,EAAE,aAAa,IAAO,CAAC;;;CASxD,MAAM,QAAuB;AACzB,MAAI;AACA,gBAAa,OAAO;WAEjB,GAAgB;AACnB,KAAW,EAAM;;;CAazB,MAAM,SAAsB,GAAa,GAA+B,GAA0C;EAC9G,IAAI,IAAQ,MAAM,KAAK,IAAO,EAAI;AAOlC,SALI,MAAU,SACV,IAAQ,MAAM,GAAS,EACvB,MAAM,KAAK,IAAI,GAAK,GAAO,EAAQ,GAGhC;;CAEd"}
@@ -34,39 +34,31 @@ function p(e, t) {
34
34
  }
35
35
  function m(e = 8) {
36
36
  if (!Number.isSafeInteger(e) || e < 0) throw RangeError("length must be a non-negative safe integer");
37
- let t = "abcdefghijklmnopqrstuvwxyz", n = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", r = "0123456789", i = "!@#$%^&*()_+[]{}|;:,.<>?", a = p(e, t + n + r + i);
37
+ let t = "abcdefghijklmnopqrstuvwxyz", n = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", r = "0123456789", i = "!@#$%^&*()_+[]{}|;:,.<>?", a = t + n + r + i, u = p(e, a);
38
38
  if (e >= 4) {
39
- let u = o.test(a), d = s.test(a), f = c.test(a), m = l.test(a);
40
- if (u && d && f && m) return a;
41
- let h = [...a], g = [
42
- {
43
- test: u,
44
- pool: t
45
- },
46
- {
47
- test: d,
48
- pool: n
49
- },
50
- {
51
- test: f,
52
- pool: r
53
- },
54
- {
55
- test: m,
56
- pool: i
57
- }
58
- ], _ = Array.from({ length: e }, (e, t) => t);
59
- for (let e = _.length - 1; e > 0; e--) {
60
- let t = new Uint32Array(1);
61
- crypto.getRandomValues(t);
62
- let n = t[0] % (e + 1);
63
- [_[e], _[n]] = [_[n], _[e]];
39
+ let d = o.test(u), f = s.test(u), m = c.test(u), h = l.test(u);
40
+ if (d && f && m && h) return u;
41
+ let g = [
42
+ p(1, t),
43
+ p(1, n),
44
+ p(1, r),
45
+ p(1, i)
46
+ ];
47
+ if (e > 4) {
48
+ let t = p(e - 4, a);
49
+ for (let e of t) g.push(e);
64
50
  }
65
- let v = 0;
66
- for (let { test: e, pool: t } of g) e || (h[_[v]] = p(1, t), v++);
67
- return h.join("");
51
+ for (let e = g.length - 1; e > 0; e--) {
52
+ let t = e + 1, n = Math.floor(4294967296 / t) * t, r = new Uint32Array(1), i;
53
+ do
54
+ crypto.getRandomValues(r), i = r[0];
55
+ while (i >= n);
56
+ let a = i % t;
57
+ [g[e], g[a]] = [g[a], g[e]];
58
+ }
59
+ return g.join("");
68
60
  }
69
- return a;
61
+ return u;
70
62
  }
71
63
  function h(e = 8, t = "abcdefghijklmnopqrstuvwxyz0123456789") {
72
64
  if (!Number.isSafeInteger(e) || e < 0) throw RangeError("length must be a non-negative safe integer");
@@ -1 +1 @@
1
- {"version":3,"file":"string.util.js","names":[],"sources":["../../../src/util/string/string.util.ts"],"sourcesContent":["import type { T_Object } from '#typescript/index.js';\n\nimport type { I_SlugifyOptions } from './string.type.js';\n\nimport { removeAccent } from '../common/common.util.js';\n\nconst RE_NON_ALNUM = /[^a-z0-9\\s-]/gi;\nconst RE_MULTI_SPACE_DASH = /[\\s-]+/g;\nconst RE_LEADING_TRAILING_DASH = /^-+|-+$/g;\nconst RE_HYPHEN = /-/g;\nconst RE_QUERY_FRAGMENT = /[?#]/;\nconst RE_HAS_LOWER = /[a-z]/;\nconst RE_HAS_UPPER = /[A-Z]/;\nconst RE_HAS_DIGIT = /\\d/;\nconst RE_HAS_SPECIAL = /[!@#$%^&*()_+[\\]{}|;:,.<>?]/;\n\n/**\n * Generates a slug from a string.\n * The slug is a URL-friendly version of the string, removing special characters\n * and converting spaces to hyphens.\n *\n * @param input - The string to be slugified.\n * @param options - Options for slugification.\n * @returns The slugified string.\n */\nfunction slugify(input: string, options?: I_SlugifyOptions): string {\n let slug = input.trim();\n\n // 1. Remove accents\n slug = removeAccent(slug);\n\n // 2. To lower case if requested (default true)\n if (options?.lower !== false) {\n slug = slug.toLowerCase();\n }\n\n // 3. Replace invalid characters with space (keeping alphanumeric, hyphens, and spaces)\n slug = slug.replace(RE_NON_ALNUM, ' ');\n\n // 4. Replace multiple spaces or hyphens with a single hyphen\n slug = slug.replace(RE_MULTI_SPACE_DASH, '-');\n\n // 5. Remove leading/trailing hyphens\n slug = slug.replace(RE_LEADING_TRAILING_DASH, '');\n\n return slug;\n}\n\n/**\n * Generates a slug from a string or an object containing strings.\n * The slug is a URL-friendly version of the string, removing special characters\n * and converting spaces to hyphens. This function can handle both single strings\n * and objects with string values.\n *\n * @param input - The string or object to be slugified.\n * @param options - Options for slugification including replacement character, case sensitivity, locale, etc.\n * @returns The slugified string or object with the same structure as the input.\n */\nexport function generateSlug<T = string>(\n input: T,\n options?: I_SlugifyOptions,\n): T {\n const slugifyWithOptions = (value: string) =>\n slugify(value ?? '', options);\n\n if (typeof input === 'object' && input !== null) {\n const result: T_Object = {};\n\n for (const [key, value] of Object.entries(input)) {\n result[key] = slugifyWithOptions(value as string);\n }\n\n return result as T;\n }\n\n return slugifyWithOptions(input as string) as T;\n}\n\n/**\n * Generates a short ID from a UUID.\n * The ID is a substring of the UUID, providing a shorter identifier.\n * Note: This is NOT cryptographically secure and collisions are possible,\n * but suitable for display purposes where uniqueness is handled elsewhere.\n *\n * @param uuid - The UUID to be converted to a short ID.\n * @param length - The desired length of the short ID (default: 4 characters).\n * @returns A short ID string of the specified length derived from the UUID.\n */\nexport function generateShortId(uuid: string, length = 4): string {\n // Simple hash function (FNV-1a variant) to generate a hex string from the UUID\n let hash = 0x811C9DC5;\n for (let i = 0; i < uuid.length; i++) {\n hash ^= uuid.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n // Convert to unsigned 32-bit integer hex string\n const hex = (hash >>> 0).toString(16).padStart(8, '0');\n\n // If we need more than 8 chars, we can just append part of the original UUID (stripped of dashes)\n // or use a different strategy. For short IDs (usually < 8), the hash is fine.\n // If length > 8, we fallback to just slicing the clean UUID.\n if (length > 8) {\n return uuid.replace(RE_HYPHEN, '').slice(0, length);\n }\n\n return hex.slice(0, length);\n}\n\n/**\n * Internal helper that fills `length` characters from `charset` using\n * rejection-sampling over `crypto.getRandomValues` to avoid modulo bias.\n * Random values are requested in bounded chunks to keep allocations small.\n *\n * @param length - Number of characters to generate.\n * @param charset - The pool of characters to draw from.\n * @returns A randomly generated string of the requested length.\n */\nfunction generateRandomFromCharset(length: number, charset: string): string {\n const limit = Math.floor(2 ** 32 / charset.length) * charset.length;\n const result: string[] = [];\n const MAX_UINT32_VALUES_PER_CALL = 16384;\n\n while (result.length < length) {\n const remaining = length - result.length;\n const chunkSize = remaining > MAX_UINT32_VALUES_PER_CALL ? MAX_UINT32_VALUES_PER_CALL : remaining;\n const values = new Uint32Array(chunkSize);\n crypto.getRandomValues(values);\n\n for (const value of values) {\n if (result.length >= length) {\n break;\n }\n if (value < limit) {\n result.push(charset[value % charset.length] as string);\n }\n }\n }\n\n return result.join('');\n}\n\n/**\n * Generates a random password of a given length.\n * The password contains a mix of letters (both cases), numbers, and special characters\n * to ensure complexity and security.\n *\n * @param length - The desired length of the password (default: 8 characters).\n * @returns A randomly generated password string with the specified length.\n * @throws {RangeError} If `length` is not a non-negative safe integer.\n */\nexport function generateRandomPassword(length = 8): string {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw new RangeError('length must be a non-negative safe integer');\n }\n\n const lower = 'abcdefghijklmnopqrstuvwxyz';\n const upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n const digits = '0123456789';\n const special = '!@#$%^&*()_+[]{}|;:,.<>?';\n const charset = lower + upper + digits + special;\n\n const password = generateRandomFromCharset(length, charset);\n\n // Ensure at least one char from each class when length >= 4\n if (length >= 4) {\n const hasLower = RE_HAS_LOWER.test(password);\n const hasUpper = RE_HAS_UPPER.test(password);\n const hasDigit = RE_HAS_DIGIT.test(password);\n const hasSpecial = RE_HAS_SPECIAL.test(password);\n\n if (hasLower && hasUpper && hasDigit && hasSpecial) {\n return password;\n }\n\n // Replace random positions with missing classes to avoid predictable placement\n const chars = [...password];\n const missing: { test: boolean; pool: string }[] = [\n { test: hasLower, pool: lower },\n { test: hasUpper, pool: upper },\n { test: hasDigit, pool: digits },\n { test: hasSpecial, pool: special },\n ];\n\n // Collect random, unique indices via Fisher-Yates partial shuffle\n const indices = Array.from({ length }, (_, i) => i);\n for (let i = indices.length - 1; i > 0; i--) {\n const buf = new Uint32Array(1);\n crypto.getRandomValues(buf);\n const j = buf[0]! % (i + 1);\n [indices[i], indices[j]] = [indices[j]!, indices[i]!];\n }\n\n let pos = 0;\n for (const { test, pool } of missing) {\n if (!test) {\n chars[indices[pos]!] = generateRandomFromCharset(1, pool);\n pos++;\n }\n }\n\n return chars.join('');\n }\n\n return password;\n}\n\n/**\n * Generates a random string of a given length using a secure random number generator.\n * This function is a cryptographically secure alternative to Math.random().toString(36).\n *\n * @param length - The desired length of the string (default: 8 characters).\n * @param charset - The characters to use (default: lowercase alphanumeric).\n * @returns A randomly generated string.\n * @throws {RangeError} If `length` is not a non-negative safe integer.\n * @throws {RangeError} If `charset` is empty or exceeds 2^32 characters.\n */\nexport function generateRandomString(\n length = 8,\n charset = 'abcdefghijklmnopqrstuvwxyz0123456789',\n): string {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw new RangeError('length must be a non-negative safe integer');\n }\n\n if (charset.length === 0 || charset.length > 2 ** 32) {\n throw new RangeError('charset.length must be between 1 and 2^32');\n }\n\n return generateRandomFromCharset(length, charset);\n}\n\n/**\n * Get the file name from a URL.\n * This function extracts the file name from a URL, optionally including or excluding\n * the file extension. It handles URLs with query parameters and fragments.\n *\n * @param url - The URL to extract the file name from (default: empty string).\n * @param getExtension - Whether to include the file extension in the result (default: false).\n * @returns The file name extracted from the URL, with or without the extension.\n */\nexport function getFileName(url = '', getExtension = false): string {\n const withoutQuery = url.split(RE_QUERY_FRAGMENT)[0] || '';\n const fileName = withoutQuery.substring(withoutQuery.lastIndexOf('/') + 1);\n\n if (getExtension) {\n return fileName;\n }\n\n const dotIndex = fileName.lastIndexOf('.');\n\n return dotIndex > 0 ? fileName.slice(0, dotIndex) : fileName;\n}\n\n/**\n * Extracts a substring between two strings.\n * This function finds the first occurrence of the starting string, then finds the first\n * occurrence of the ending string after the starting string, and returns the content between them.\n *\n * @param s - The original string to search within.\n * @param a - The starting string that marks the beginning of the desired substring.\n * @param b - The ending string that marks the end of the desired substring.\n * @returns The substring between the two specified strings, or an empty string if either string is not found.\n */\nexport function substringBetween(s: string, a: string, b: string): string {\n const start = s.indexOf(a);\n\n if (start === -1) {\n return '';\n }\n\n const from = start + a.length;\n const end = s.indexOf(b, from);\n\n if (end === -1) {\n return '';\n }\n\n return s.slice(from, end);\n}\n"],"mappings":";;AAMA,IAAM,IAAe,kBACf,IAAsB,WACtB,IAA2B,YAC3B,IAAY,MACZ,IAAoB,QACpB,IAAe,SACf,IAAe,SACf,IAAe,MACf,IAAiB;AAWvB,SAAS,EAAQ,GAAe,GAAoC;CAChE,IAAI,IAAO,EAAM,MAAM;AAmBvB,QAhBA,IAAO,EAAa,EAAK,EAGrB,GAAS,UAAU,OACnB,IAAO,EAAK,aAAa,GAI7B,IAAO,EAAK,QAAQ,GAAc,IAAI,EAGtC,IAAO,EAAK,QAAQ,GAAqB,IAAI,EAG7C,IAAO,EAAK,QAAQ,GAA0B,GAAG,EAE1C;;AAaX,SAAgB,EACZ,GACA,GACC;CACD,IAAM,KAAsB,MACxB,EAAQ,KAAS,IAAI,EAAQ;AAEjC,KAAI,OAAO,KAAU,YAAY,GAAgB;EAC7C,IAAM,IAAmB,EAAE;AAE3B,OAAK,IAAM,CAAC,GAAK,MAAU,OAAO,QAAQ,EAAM,CAC5C,GAAO,KAAO,EAAmB,EAAgB;AAGrD,SAAO;;AAGX,QAAO,EAAmB,EAAgB;;AAa9C,SAAgB,EAAgB,GAAc,IAAS,GAAW;CAE9D,IAAI,IAAO;AACX,MAAK,IAAI,IAAI,GAAG,IAAI,EAAK,QAAQ,IAE7B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AGJ,EAAE,MAAM,GAAM,EAAI"}
1
+ {"version":3,"file":"string.util.js","names":[],"sources":["../../../src/util/string/string.util.ts"],"sourcesContent":["import type { T_Object } from '#typescript/index.js';\n\nimport type { I_SlugifyOptions } from './string.type.js';\n\nimport { removeAccent } from '../common/common.util.js';\n\nconst RE_NON_ALNUM = /[^a-z0-9\\s-]/gi;\nconst RE_MULTI_SPACE_DASH = /[\\s-]+/g;\nconst RE_LEADING_TRAILING_DASH = /^-+|-+$/g;\nconst RE_HYPHEN = /-/g;\nconst RE_QUERY_FRAGMENT = /[?#]/;\nconst RE_HAS_LOWER = /[a-z]/;\nconst RE_HAS_UPPER = /[A-Z]/;\nconst RE_HAS_DIGIT = /\\d/;\nconst RE_HAS_SPECIAL = /[!@#$%^&*()_+[\\]{}|;:,.<>?]/;\n\n/**\n * Generates a slug from a string.\n * The slug is a URL-friendly version of the string, removing special characters\n * and converting spaces to hyphens.\n *\n * @param input - The string to be slugified.\n * @param options - Options for slugification.\n * @returns The slugified string.\n */\nfunction slugify(input: string, options?: I_SlugifyOptions): string {\n let slug = input.trim();\n\n // 1. Remove accents\n slug = removeAccent(slug);\n\n // 2. To lower case if requested (default true)\n if (options?.lower !== false) {\n slug = slug.toLowerCase();\n }\n\n // 3. Replace invalid characters with space (keeping alphanumeric, hyphens, and spaces)\n slug = slug.replace(RE_NON_ALNUM, ' ');\n\n // 4. Replace multiple spaces or hyphens with a single hyphen\n slug = slug.replace(RE_MULTI_SPACE_DASH, '-');\n\n // 5. Remove leading/trailing hyphens\n slug = slug.replace(RE_LEADING_TRAILING_DASH, '');\n\n return slug;\n}\n\n/**\n * Generates a slug from a string or an object containing strings.\n * The slug is a URL-friendly version of the string, removing special characters\n * and converting spaces to hyphens. This function can handle both single strings\n * and objects with string values.\n *\n * @param input - The string or object to be slugified.\n * @param options - Options for slugification including replacement character, case sensitivity, locale, etc.\n * @returns The slugified string or object with the same structure as the input.\n */\nexport function generateSlug<T = string>(\n input: T,\n options?: I_SlugifyOptions,\n): T {\n const slugifyWithOptions = (value: string) =>\n slugify(value ?? '', options);\n\n if (typeof input === 'object' && input !== null) {\n const result: T_Object = {};\n\n for (const [key, value] of Object.entries(input)) {\n result[key] = slugifyWithOptions(value as string);\n }\n\n return result as T;\n }\n\n return slugifyWithOptions(input as string) as T;\n}\n\n/**\n * Generates a short ID from a UUID.\n * The ID is a substring of the UUID, providing a shorter identifier.\n * Note: This is NOT cryptographically secure and collisions are possible,\n * but suitable for display purposes where uniqueness is handled elsewhere.\n *\n * @param uuid - The UUID to be converted to a short ID.\n * @param length - The desired length of the short ID (default: 4 characters).\n * @returns A short ID string of the specified length derived from the UUID.\n */\nexport function generateShortId(uuid: string, length = 4): string {\n // Simple hash function (FNV-1a variant) to generate a hex string from the UUID\n let hash = 0x811C9DC5;\n for (let i = 0; i < uuid.length; i++) {\n hash ^= uuid.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n // Convert to unsigned 32-bit integer hex string\n const hex = (hash >>> 0).toString(16).padStart(8, '0');\n\n // If we need more than 8 chars, we can just append part of the original UUID (stripped of dashes)\n // or use a different strategy. For short IDs (usually < 8), the hash is fine.\n // If length > 8, we fallback to just slicing the clean UUID.\n if (length > 8) {\n return uuid.replace(RE_HYPHEN, '').slice(0, length);\n }\n\n return hex.slice(0, length);\n}\n\n/**\n * Internal helper that fills `length` characters from `charset` using\n * rejection-sampling over `crypto.getRandomValues` to avoid modulo bias.\n * Random values are requested in bounded chunks to keep allocations small.\n *\n * @param length - Number of characters to generate.\n * @param charset - The pool of characters to draw from.\n * @returns A randomly generated string of the requested length.\n */\nfunction generateRandomFromCharset(length: number, charset: string): string {\n const limit = Math.floor(2 ** 32 / charset.length) * charset.length;\n const result: string[] = [];\n const MAX_UINT32_VALUES_PER_CALL = 16384;\n\n while (result.length < length) {\n const remaining = length - result.length;\n const chunkSize = remaining > MAX_UINT32_VALUES_PER_CALL ? MAX_UINT32_VALUES_PER_CALL : remaining;\n const values = new Uint32Array(chunkSize);\n crypto.getRandomValues(values);\n\n for (const value of values) {\n if (result.length >= length) {\n break;\n }\n if (value < limit) {\n result.push(charset[value % charset.length] as string);\n }\n }\n }\n\n return result.join('');\n}\n\n/**\n * Generates a random password of a given length.\n * The password contains a mix of letters (both cases), numbers, and special characters\n * to ensure complexity and security.\n *\n * @param length - The desired length of the password (default: 8 characters).\n * @returns A randomly generated password string with the specified length.\n * @throws {RangeError} If `length` is not a non-negative safe integer.\n */\nexport function generateRandomPassword(length = 8): string {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw new RangeError('length must be a non-negative safe integer');\n }\n\n const lower = 'abcdefghijklmnopqrstuvwxyz';\n const upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n const digits = '0123456789';\n const special = '!@#$%^&*()_+[]{}|;:,.<>?';\n const charset = lower + upper + digits + special;\n\n const password = generateRandomFromCharset(length, charset);\n\n // Ensure at least one char from each class when length >= 4\n if (length >= 4) {\n const hasLower = RE_HAS_LOWER.test(password);\n const hasUpper = RE_HAS_UPPER.test(password);\n const hasDigit = RE_HAS_DIGIT.test(password);\n const hasSpecial = RE_HAS_SPECIAL.test(password);\n\n if (hasLower && hasUpper && hasDigit && hasSpecial) {\n return password;\n }\n\n // If the pure random string lacks required classes, construct a guaranteed-valid one\n const chars = [\n generateRandomFromCharset(1, lower),\n generateRandomFromCharset(1, upper),\n generateRandomFromCharset(1, digits),\n generateRandomFromCharset(1, special),\n ];\n\n // Fill the rest with random characters\n if (length > 4) {\n const rest = generateRandomFromCharset(length - 4, charset);\n for (const c of rest) {\n chars.push(c);\n }\n }\n\n // Fisher-Yates shuffle using rejection sampling to avoid modulo bias\n for (let i = chars.length - 1; i > 0; i--) {\n const range = i + 1;\n // 0x1_0000_0000 = 2^32, the exclusive upper bound of Uint32Array values\n const maxUnbiased = Math.floor(0x1_0000_0000 / range) * range;\n const buf = new Uint32Array(1);\n let randomValue: number;\n\n do {\n crypto.getRandomValues(buf);\n randomValue = buf[0]!;\n } while (randomValue >= maxUnbiased);\n\n const j = randomValue % range;\n [chars[i], chars[j]] = [chars[j]!, chars[i]!];\n }\n\n return chars.join('');\n }\n\n return password;\n}\n\n/**\n * Generates a random string of a given length using a secure random number generator.\n * This function is a cryptographically secure alternative to Math.random().toString(36).\n *\n * @param length - The desired length of the string (default: 8 characters).\n * @param charset - The characters to use (default: lowercase alphanumeric).\n * @returns A randomly generated string.\n * @throws {RangeError} If `length` is not a non-negative safe integer.\n * @throws {RangeError} If `charset` is empty or exceeds 2^32 characters.\n */\nexport function generateRandomString(\n length = 8,\n charset = 'abcdefghijklmnopqrstuvwxyz0123456789',\n): string {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw new RangeError('length must be a non-negative safe integer');\n }\n\n if (charset.length === 0 || charset.length > 2 ** 32) {\n throw new RangeError('charset.length must be between 1 and 2^32');\n }\n\n return generateRandomFromCharset(length, charset);\n}\n\n/**\n * Get the file name from a URL.\n * This function extracts the file name from a URL, optionally including or excluding\n * the file extension. It handles URLs with query parameters and fragments.\n *\n * @param url - The URL to extract the file name from (default: empty string).\n * @param getExtension - Whether to include the file extension in the result (default: false).\n * @returns The file name extracted from the URL, with or without the extension.\n */\nexport function getFileName(url = '', getExtension = false): string {\n const withoutQuery = url.split(RE_QUERY_FRAGMENT)[0] || '';\n const fileName = withoutQuery.substring(withoutQuery.lastIndexOf('/') + 1);\n\n if (getExtension) {\n return fileName;\n }\n\n const dotIndex = fileName.lastIndexOf('.');\n\n return dotIndex > 0 ? fileName.slice(0, dotIndex) : fileName;\n}\n\n/**\n * Extracts a substring between two strings.\n * This function finds the first occurrence of the starting string, then finds the first\n * occurrence of the ending string after the starting string, and returns the content between them.\n *\n * @param s - The original string to search within.\n * @param a - The starting string that marks the beginning of the desired substring.\n * @param b - The ending string that marks the end of the desired substring.\n * @returns The substring between the two specified strings, or an empty string if either string is not found.\n */\nexport function substringBetween(s: string, a: string, b: string): string {\n const start = s.indexOf(a);\n\n if (start === -1) {\n return '';\n }\n\n const from =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AAI,IAAc;AACxB,IAAC,EAAM,IAAI,EAAM,MAAM,CAAC,EAAM,IAAK,EAAM,GAAI;;AAGjD,SAAO,EAAM,KAAK,GAAG;;AAGzB,QAAO;;AAaX,SAAgB,EACZ,IAAS,GACT,IAAU,wCACJ;AACN,KAAI,CAAC,OAAO,cAAc,EAAO,IAAI,IAAS,EAC1C,OAAU,WAAW,6CAA6C;AAGtE,KAAI,EAAQ,WAAW,KAAK,EAAQ,SAAS,KAAK,GAC9C,OAAU,WAAW,4CAA4C;AAGrE,QAAO,EAA0B,GAAQ,EAAQ;;AAYrD,SAAgB,EAAY,IAAM,IAAI,IAAe,IAAe;CAChE,IAAM,IAAe,EAAI,MAAM,EAAkB,CAAC,MAAM,IAClD,IAAW,EAAa,UAAU,EAAa,YAAY,IAAI,GAAG,EAAE;AAE1E,KAAI,EACA,QAAO;CAGX,IAAM,IAAW,EAAS,YAAY,IAAI;AAE1C,QAAO,IAAW,IAAI,EAAS,MAAM,GAAG,EAAS,GAAG;;AAaxD,SAAgB,EAAiB,GAAW,GAAW,GAAmB;CACtE,IAAM,IAAQ,EAAE,QAAQ,EAAE;AAE1B,KAAI,MAAU,GACV,QAAO;CAGX,IAAM,IAAO,IAAQ,EAAE,QACjB,IAAM,EAAE,QAAQ,GAAG,EAAK;AAM9B,QAJI,MAAQ,KACD,KAGJ,EAAE,MAAM,GAAM,EAAI"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cyberskill/shared",
3
3
  "type": "module",
4
- "version": "3.16.0",
4
+ "version": "3.18.0",
5
5
  "description": "CyberSkill Shared",
6
6
  "author": "Stephen Cheng",
7
7
  "license": "MIT",
@@ -230,7 +230,7 @@
230
230
  },
231
231
  "scripts": {
232
232
  "ai:setup": "tsx src/node/cli/index.ts ai:setup",
233
- "build": "vite build",
233
+ "build": "tsx src/node/cli/index.ts build",
234
234
  "commitlint": "tsx src/node/cli/index.ts commitlint",
235
235
  "dev": "vite build --watch",
236
236
  "inspect": "tsx src/node/cli/index.ts inspect",
@@ -255,8 +255,8 @@
255
255
  "@eslint-react/eslint-plugin": "3.0.0",
256
256
  "@graphql-codegen/cli": "6.2.1",
257
257
  "@graphql-codegen/client-preset": "5.2.4",
258
- "@nestjs/common": "11.1.17",
259
- "@nestjs/core": "11.1.17",
258
+ "@nestjs/common": "11.1.18",
259
+ "@nestjs/core": "11.1.18",
260
260
  "@userback/widget": "0.3.12",
261
261
  "@vitejs/plugin-react": "6.0.1",
262
262
  "body-parser": "2.2.2",
@@ -289,8 +289,8 @@
289
289
  "mongoose": "9.3.3",
290
290
  "mongoose-aggregate-paginate-v2": "1.1.4",
291
291
  "mongoose-paginate-v2": "1.9.4",
292
- "next-intl": "4.8.4",
293
- "path-to-regexp": "8.4.1",
292
+ "next-intl": "4.9.0",
293
+ "path-to-regexp": "8.4.2",
294
294
  "qs": "6.15.0",
295
295
  "react": "19.2.4",
296
296
  "react-dom": "19.2.4",
@@ -308,8 +308,8 @@
308
308
  "@semantic-release/changelog": "6.0.3",
309
309
  "@semantic-release/git": "10.0.1",
310
310
  "@semantic-release/github": "12.0.6",
311
- "@storybook/react": "10.3.3",
312
- "@storybook/react-vite": "10.3.3",
311
+ "@storybook/react": "10.3.4",
312
+ "@storybook/react-vite": "10.3.4",
313
313
  "@testing-library/dom": "10.4.1",
314
314
  "@testing-library/jest-dom": "6.9.1",
315
315
  "@testing-library/react": "16.3.2",
@@ -324,7 +324,7 @@
324
324
  "@types/fs-extra": "11.0.4",
325
325
  "@types/graphql-upload": "17.0.0",
326
326
  "@types/migrate-mongo": "10.0.6",
327
- "@types/node": "25.5.0",
327
+ "@types/node": "25.5.2",
328
328
  "@types/react": "19.2.14",
329
329
  "@types/react-dom": "19.2.3",
330
330
  "@types/ws": "8.18.1",
@@ -339,7 +339,7 @@
339
339
  "lint-staged": "16.4.0",
340
340
  "node-modules-inspector": "1.4.2",
341
341
  "npm-run-all2": "8.0.4",
342
- "sass": "1.98.0",
342
+ "sass": "1.99.0",
343
343
  "semantic-release": "25.0.3",
344
344
  "simple-git-hooks": "2.13.1",
345
345
  "tsx": "4.21.0",
@@ -355,9 +355,10 @@
355
355
  },
356
356
  "pnpm": {
357
357
  "overrides": {
358
- "lodash": ">=4.17.23",
358
+ "lodash": ">=4.18.0",
359
+ "lodash-es": ">=4.18.0",
359
360
  "minimatch": ">=10.2.4",
360
- "path-to-regexp": "8.4.1"
361
+ "path-to-regexp": "8.4.2"
361
362
  }
362
363
  }
363
364
  }