@cyberskill/shared 3.10.0 → 3.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/config/env/env.util.js.map +1 -1
  2. package/dist/config/vitest/vitest.e2e.js +1 -1
  3. package/dist/config/vitest/vitest.unit.js +1 -1
  4. package/dist/constant/response-status.d.ts +4 -0
  5. package/dist/constant/response-status.js.map +1 -1
  6. package/dist/node/express/express.util.d.ts +6 -0
  7. package/dist/node/express/express.util.js.map +1 -1
  8. package/dist/node/mongo/mongo.controller.helpers.d.ts +43 -0
  9. package/dist/node/mongo/mongo.controller.helpers.js +20 -0
  10. package/dist/node/mongo/mongo.controller.helpers.js.map +1 -0
  11. package/dist/node/mongo/mongo.controller.native.js +65 -93
  12. package/dist/node/mongo/mongo.controller.native.js.map +1 -1
  13. package/dist/node/mongo/mongo.util.js.map +1 -1
  14. package/dist/node/storage/index.js +3 -3
  15. package/dist/node/storage/storage.constant.d.ts +0 -3
  16. package/dist/node/storage/storage.constant.js +2 -2
  17. package/dist/node/storage/storage.constant.js.map +1 -1
  18. package/dist/node/storage/storage.type.d.ts +0 -11
  19. package/dist/node/storage/storage.util.d.ts +1 -1
  20. package/dist/node/storage/storage.util.js +60 -68
  21. package/dist/node/storage/storage.util.js.map +1 -1
  22. package/dist/node/upload/upload.type.d.ts +2 -0
  23. package/dist/node/upload/upload.type.js.map +1 -1
  24. package/dist/node/upload/upload.util.js +10 -2
  25. package/dist/node/upload/upload.util.js.map +1 -1
  26. package/dist/node_modules/.pnpm/vitest@4.1.0_@types_node@25.5.0_jsdom@29.0.1_@noble_hashes@1.8.0__vite@8.0.1_@types_nod_5f6c16f4d4385f16c87b17afc93c851f/node_modules/vitest/dist/config.js +8 -0
  27. package/dist/node_modules/.pnpm/{vitest@4.1.0_@types_node@25.5.0_jsdom@29.0.0_@noble_hashes@1.8.0__vite@8.0.1_@types_nod_36acd00c2670b611b011192023dc5bd9 → vitest@4.1.0_@types_node@25.5.0_jsdom@29.0.1_@noble_hashes@1.8.0__vite@8.0.1_@types_nod_5f6c16f4d4385f16c87b17afc93c851f}/node_modules/vitest/dist/config.js.map +1 -1
  28. package/dist/react/storage/storage.hook.d.ts +1 -1
  29. package/dist/react/storage/storage.hook.js.map +1 -1
  30. package/dist/react/storage/storage.util.d.ts +6 -7
  31. package/dist/react/storage/storage.util.js +15 -10
  32. package/dist/react/storage/storage.util.js.map +1 -1
  33. package/dist/util/common/common.util.d.ts +15 -2
  34. package/dist/util/common/common.util.js +22 -9
  35. package/dist/util/common/common.util.js.map +1 -1
  36. package/dist/util/common/index.js +2 -2
  37. package/dist/util/index.js +7 -7
  38. package/dist/util/object/object.util.d.ts +7 -3
  39. package/dist/util/object/object.util.js.map +1 -1
  40. package/package.json +5 -6
  41. package/dist/node_modules/.pnpm/vitest@4.1.0_@types_node@25.5.0_jsdom@29.0.0_@noble_hashes@1.8.0__vite@8.0.1_@types_nod_36acd00c2670b611b011192023dc5bd9/node_modules/vitest/dist/config.js +0 -8
@@ -1 +1 @@
1
- {"version":3,"file":"mongo.util.js","names":[],"sources":["../../../src/node/mongo/mongo.util.ts"],"sourcesContent":["import type migrate from 'migrate-mongo';\nimport type mongooseRaw from 'mongoose';\n\nimport aggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\nimport { randomUUID } from 'node:crypto';\n\nimport { getNestedValue, regexSearchMapper, setNestedValue } from '#util/index.js';\nimport { validate } from '#util/validate/index.js';\n\nimport type { MongoController } from './mongo.controller.js';\nimport type { C_Document, I_CreateModelOptions, I_CreateSchemaOptions, I_DynamicVirtualConfig, I_DynamicVirtualOptions, I_ExtendedModel, I_GenericDocument, I_MongooseModelMiddleware, T_Filter, T_MongoosePlugin, T_MongooseSchema, T_QueryFilter, T_VirtualOptions, T_WithId } from './mongo.type.js';\n\nimport { addGitIgnoreEntry, writeFileSync } from '../fs/index.js';\nimport { MIGRATE_MONGO_CONFIG, PATH } from '../path/index.js';\n\n/**\n * Converts enum values to proper model names.\n * Handles common naming conventions like converting 'USER' to 'User'.\n *\n * @param enumValue - The enum value to convert\n * @returns The converted model name\n */\nexport function convertEnumToModelName(enumValue: string): string {\n if (enumValue === enumValue.toUpperCase()) {\n return enumValue.charAt(0).toUpperCase() + enumValue.slice(1).toLowerCase();\n }\n\n return enumValue;\n}\n\n/**\n * Interface for the MongoDB utility object to enable explicit type annotation.\n * Required to avoid TS7056 (inferred type exceeds maximum serialization length).\n */\ninterface I_MongoUtils {\n createGenericFields: () => I_GenericDocument;\n applyPlugins: <T>(schema: T_MongooseSchema<T>, plugins: Array<T_MongoosePlugin | false>) => void;\n applyMiddlewares: <T extends Partial<C_Document>>(schema: T_MongooseSchema<T>, middlewares: I_MongooseModelMiddleware<T>[]) => void;\n createGenericSchema: (mongoose: typeof mongooseRaw) => T_MongooseSchema<I_GenericDocument>;\n createSchema: <T, R extends string = string>(options: I_CreateSchemaOptions<T, R>) => T_MongooseSchema<T>;\n createModel: <T extends Partial<C_Document>, R extends string = string>(options: I_CreateModelOptions<T, R>) => I_ExtendedModel<T>;\n validator: {\n isRequired: <T>() => (this: T, value: unknown) => Promise<boolean>;\n isUnique: <T extends { constructor: { exists: (query: { [key: string]: unknown }) => Promise<unknown> } }>(fields: string[]) => (this: T, value: unknown) => Promise<boolean>;\n matchesRegex: (regexArray: RegExp[]) => (value: string) => Promise<boolean>;\n };\n migrate: {\n getModule: () => Promise<typeof migrate>;\n setConfig: (options: Partial<migrate.config.Config> & { moduleSystem?: 'commonjs' | 'esm' }) => void;\n };\n regexify: <T>(filter?: T_QueryFilter<T>, fields?: (keyof T | string)[]) => T_QueryFilter<T>;\n isDynamicVirtual: <T, R extends string>(options?: T_VirtualOptions<T, R>) => options is I_DynamicVirtualOptions<T, R>;\n getNewRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean, filter?: T_Filter<T>) => Promise<T[]>;\n getExistingRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean, filter?: T_Filter<T>) => Promise<T_WithId<T>[]>;\n}\n\n/**\n * MongoDB utility object providing comprehensive database operations and utilities.\n * This object contains methods for creating generic fields, applying plugins and middlewares,\n * creating schemas and models, validation functions, migration utilities, and regex filtering.\n */\nexport const mongo: I_MongoUtils = {\n /**\n * Creates generic fields that are commonly used across MongoDB documents.\n * This function generates standard fields including a UUID, deletion flag, and timestamps\n * that can be applied to any document schema.\n *\n * @returns An object containing generic document fields (id, isDel, createdAt, updatedAt).\n */\n createGenericFields(): I_GenericDocument {\n return {\n id: randomUUID(),\n isDel: false,\n createdAt: new Date(),\n updatedAt: new Date(),\n };\n },\n /**\n * Applies plugins to a Mongoose schema.\n * This function filters out falsy plugins and applies the remaining valid plugins\n * to the provided schema.\n *\n * @param schema - The Mongoose schema to apply plugins to.\n * @param plugins - An array of plugin functions or false values to filter and apply.\n */\n applyPlugins<T>(schema: T_MongooseSchema<T>, plugins: Array<T_MongoosePlugin | false>) {\n plugins\n .filter((plugin): plugin is T_MongoosePlugin => typeof plugin === 'function')\n .forEach(plugin => schema.plugin(plugin));\n },\n /**\n * Applies middleware functions to a Mongoose schema.\n * This function configures pre and post middleware for specified methods on the schema.\n *\n * @param schema - The Mongoose schema to apply middleware to.\n * @param middlewares - An array of middleware configurations with method, pre, and post functions.\n */\n applyMiddlewares<T extends Partial<C_Document>>(\n schema: T_MongooseSchema<T>,\n middlewares: I_MongooseModelMiddleware<T>[],\n ) {\n middlewares.forEach(({ method, pre, post }) => {\n if (method && pre) {\n schema.pre(method as RegExp, pre);\n }\n\n if (method && post) {\n schema.post(method as RegExp, post);\n }\n });\n },\n /**\n * Creates a generic Mongoose schema with common fields.\n * This function creates a base schema with UUID field and deletion flag,\n * configured with automatic timestamps.\n *\n * @param mongoose - The Mongoose instance to create the schema with.\n * @returns A Mongoose schema with generic document fields.\n */\n createGenericSchema(mongoose: typeof mongooseRaw) {\n return new mongoose.Schema<I_GenericDocument>(\n {\n id: { type: String, default: () => randomUUID(), unique: true },\n isDel: { type: Boolean, default: false },\n },\n { timestamps: true },\n );\n },\n /**\n * Creates a Mongoose schema with optional virtual fields and generic fields.\n * This function creates a new Mongoose schema from the provided schema definition,\n * optionally adds virtual fields, and includes generic fields (unless standalone is true).\n *\n * @param options - Configuration options including mongoose instance, schema definition, virtuals, and standalone flag.\n * @param options.mongoose - The Mongoose instance to use for schema creation.\n * @param options.schema - The schema definition object.\n * @param options.virtuals - Optional array of virtual field configurations.\n * @param options.standalone - Whether to exclude generic fields (default: false).\n * @returns A configured Mongoose schema.\n */\n createSchema<T, R extends string = string>({\n mongoose,\n schema,\n virtuals = [],\n standalone = false,\n }: I_CreateSchemaOptions<T, R>): T_MongooseSchema<T> {\n const createdSchema = new mongoose.Schema<T>(schema, {\n toJSON: { virtuals: true }, // So `res.json()` and other `JSON.stringify()` functions include virtuals\n toObject: { virtuals: true }, // So `console.log()` and other functions that use `toObject()` include virtuals\n });\n\n virtuals.forEach(({ name, options, get }) => {\n if (mongo.isDynamicVirtual<T, R>(options)) {\n const schemaStatics = createdSchema.statics as Record<string, unknown>;\n\n if (!schemaStatics['_dynamicVirtuals']) {\n schemaStatics['_dynamicVirtuals'] = [];\n }\n\n (schemaStatics['_dynamicVirtuals'] as I_DynamicVirtualConfig<T>[]).push({\n name: name as string,\n options,\n });\n\n const virtualInstance = createdSchema.virtual(name as string);\n\n if (get) {\n virtualInstance.get(get);\n }\n else {\n virtualInstance.get(function (this: T & { _populated?: { [key: string]: unknown } }) {\n return this._populated?.[name as string] || (options?.count ? 0 : (options?.justOne ? null : []));\n });\n }\n }\n else {\n const virtualInstance = createdSchema.virtual(name as string, options);\n\n if (get) {\n virtualInstance.get(get);\n }\n }\n });\n\n if (!standalone) {\n createdSchema.add(mongo.createGenericSchema(mongoose));\n }\n\n return createdSchema;\n },\n /**\n * Creates a Mongoose model with plugins, middleware, and pagination support.\n * This function creates a model from a schema with optional pagination and aggregation plugins,\n * and applies any specified middleware. If a model with the same name already exists, it returns the existing model.\n *\n * @param options - Configuration options including mongoose instance, model name, schema, and feature flags.\n * @param options.mongoose - The Mongoose instance to use for model creation.\n * @param options.name - The name of the model to create.\n * @param options.schema - The schema definition for the model.\n * @param options.pagination - Whether to enable pagination plugin (default: false).\n * @param options.aggregate - Whether to enable aggregation pagination plugin (default: false).\n * @param options.virtuals - Optional array of virtual field configurations.\n * @param options.middlewares - Optional array of middleware configurations.\n * @returns A configured Mongoose model with extended functionality.\n * @throws {Error} When the model name is not provided.\n */\n createModel<T extends Partial<C_Document>, R extends string = string>({\n mongoose: currentMongooseInstance,\n name,\n schema,\n virtuals = [],\n pagination = true,\n aggregate = true,\n middlewares = [],\n }: I_CreateModelOptions<T, R>): I_ExtendedModel<T> {\n if (!name) {\n throw new Error('Model name is required.');\n }\n\n if (currentMongooseInstance.models[name]) {\n return currentMongooseInstance.models[name] as I_ExtendedModel<T>;\n }\n\n const createdSchema = mongo.createSchema({ mongoose: currentMongooseInstance, schema, virtuals });\n\n if (pagination || aggregate) {\n mongo.applyPlugins<T>(createdSchema, [\n pagination && mongoosePaginate,\n aggregate && aggregatePaginate,\n ]);\n }\n\n mongo.applyMiddlewares<T>(createdSchema, middlewares);\n\n const model = currentMongooseInstance.model<T>(name, createdSchema) as I_ExtendedModel<T>;\n\n if (virtuals.length > 0) {\n // Mongoose Model has no typed _virtualConfigs; used by MongooseController.getDynamicVirtuals()\n (model as any)._virtualConfigs = virtuals;\n }\n\n return model;\n },\n /**\n * Validation utilities for Mongoose schemas.\n * This object provides common validation functions that can be used in Mongoose schema definitions.\n */\n validator: {\n /**\n * Creates a required field validator.\n * This function returns a validator that checks if a field value is not empty\n * using the validate.isEmpty utility.\n *\n * @returns A validation function that returns true if the field is not empty.\n */\n isRequired<T>(): (this: T, value: unknown) => Promise<boolean> {\n return async function (this: T, value: unknown): Promise<boolean> {\n return !validate.isEmpty(value);\n };\n },\n /**\n * Creates a unique field validator.\n * This function returns a validator that checks if a field value is unique\n * across the specified fields in the collection.\n *\n * @param fields - An array of field names to check for uniqueness.\n * @returns A validation function that returns true if the value is unique across the specified fields.\n * @throws {Error} When fields is not a non-empty array of strings.\n */\n isUnique<T extends { constructor: { exists: (query: { [key: string]: unknown }) => Promise<unknown> } }>(fields: string[]) {\n return async function (this: T, value: unknown): Promise<boolean> {\n if (!Array.isArray(fields) || fields.length === 0) {\n throw new Error('Fields must be a non-empty array of strings.');\n }\n\n const query = { $or: fields.map(field => ({ [field]: value })) };\n const existingDocument = await this.constructor.exists(query);\n\n return !existingDocument;\n };\n },\n /**\n * Creates a regex pattern validator.\n * This function returns a validator that checks if a string value matches\n * all provided regular expressions.\n *\n * @param regexArray - An array of regular expressions to test against the value.\n * @returns A validation function that returns true if the value matches all regex patterns.\n * @throws {Error} When regexArray is not an array of valid RegExp objects.\n */\n matchesRegex(regexArray: RegExp[]): (value: string) => Promise<boolean> {\n return async (value: string): Promise<boolean> => {\n if (!Array.isArray(regexArray) || regexArray.some(r => !(r instanceof RegExp))) {\n throw new Error('regexArray must be an array of valid RegExp objects.');\n }\n\n return regexArray.every(regex => regex.test(value));\n };\n },\n },\n /**\n * Migration utilities for MongoDB.\n * This object extends the migrate-mongo library with additional configuration utilities.\n */\n migrate: {\n /**\n * Lazily loads the migrate-mongo module to avoid eager import overhead.\n * Use this to access migrate-mongo methods (up, down, status, create) programmatically.\n *\n * @returns A promise resolving to the migrate-mongo module.\n */\n async getModule(): Promise<typeof migrate> {\n return (await import('migrate-mongo')).default;\n },\n /**\n * Sets the migration configuration and updates .gitignore.\n * This function creates a migration configuration file and ensures it's properly\n * excluded from version control.\n *\n * @param options - Migration configuration options to write to the config file.\n */\n setConfig: (options: Partial<migrate.config.Config> & { moduleSystem?: 'commonjs' | 'esm' }) => {\n const optionsJS = `// This file is automatically generated by the Cyberskill CLI.\\nmodule.exports = ${JSON.stringify(options, null, 4)}`;\n\n writeFileSync(PATH.MIGRATE_MONGO_CONFIG, optionsJS);\n\n addGitIgnoreEntry(PATH.GIT_IGNORE, MIGRATE_MONGO_CONFIG);\n },\n },\n /**\n * Converts string values in a filter to regex patterns for case-insensitive search.\n * This function recursively processes a filter object and converts string values in specified fields\n * to MongoDB regex patterns that support accented character matching.\n *\n * @remarks\n * **Performance guard:** Input strings are capped at 200 characters to mitigate ReDoS risk.\n * The generated regex patterns include accented character alternation groups (e.g., `(a|à|á|...)`)\n * which can be polynomially complex for very long inputs. For production search on large collections,\n * consider using MongoDB `$text` search indexes instead of `$regex` for better performance.\n *\n * @param filter - The filter object to process.\n * @param fields - An array of field names to convert to regex patterns.\n * @returns A new filter object with string values converted to regex patterns.\n */\n regexify<T>(filter?: T_QueryFilter<T>, fields?: (keyof T | string)[]): T_QueryFilter<T> {\n if (!filter) {\n return {} as T_QueryFilter<T>;\n }\n\n let newFilter = { ...filter };\n\n if (!fields || fields.length === 0) {\n return newFilter;\n }\n\n const MAX_REGEX_INPUT_LENGTH = 200;\n\n for (const field of fields) {\n const path = field.toString().split('.');\n const value = getNestedValue(newFilter, path);\n\n if (typeof value === 'string' && value.length > 0 && value.length <= MAX_REGEX_INPUT_LENGTH) {\n const regexValue = {\n $regex: `.*${regexSearchMapper(value)}.*`,\n $options: 'i',\n };\n\n newFilter = setNestedValue(newFilter, path, regexValue);\n }\n }\n\n return newFilter;\n },\n /**\n * Checks if a virtual options object has a dynamic ref function.\n *\n * @param options - The virtual options to check.\n * @returns True if the options contain a dynamic ref function.\n */\n isDynamicVirtual<T, R extends string = string>(options?: T_VirtualOptions<T, R>): options is I_DynamicVirtualOptions<T, R> {\n return Boolean(options && typeof options.ref === 'function');\n },\n\n /**\n * Generic utility function to get new records from the database\n * @param controller - MongoController instance\n * @param recordsToCheck - Array of records to check\n * @param filterFn - Function to determine if a record already exists\n * @returns Array of records that don't exist in the database\n */\n async getNewRecords<T extends I_GenericDocument>(\n controller: MongoController<T>,\n recordsToCheck: T[],\n filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean,\n filter: T_Filter<T> = {} as T_Filter<T>,\n ): Promise<T[]> {\n const existingRecords = await controller.findAll(filter);\n\n if (!existingRecords.success) {\n throw new Error(`Failed to query existing records: ${existingRecords.message}`);\n }\n\n if ('truncated' in existingRecords && existingRecords.truncated) {\n throw new Error('getNewRecords: Results were truncated by the default limit. Use pagination or set an explicit limit to ensure complete data.');\n }\n\n const filteredRecords = recordsToCheck.filter(newRecord =>\n !existingRecords.result.some((existingRecord: T_WithId<T>) =>\n filterFn(existingRecord, newRecord),\n ),\n );\n\n return filteredRecords;\n },\n\n /**\n * Generic utility function to get existing records that match the filter criteria\n * @param controller - MongoController instance\n * @param recordsToCheck - Array of records to check\n * @param filterFn - Function to determine if a record exists\n * @returns Array of existing records that match the filter criteria\n * @throws {Error} When the database query fails — prevents silent data inconsistency.\n */\n async getExistingRecords<T extends I_GenericDocument>(\n controller: MongoController<T>,\n recordsToCheck: T[],\n filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean,\n filter: T_Filter<T> = {} as T_Filter<T>,\n ): Promise<T_WithId<T>[]> {\n const existingRecords = await controller.findAll(filter);\n\n if (!existingRecords.success) {\n throw new Error(`Failed to query existing records: ${existingRecords.message}`);\n }\n\n if ('truncated' in existingRecords && existingRecords.truncated) {\n throw new Error('getExistingRecords: Results were truncated by the default limit. Use pagination or set an explicit limit to ensure complete data.');\n }\n\n const foundRecords = existingRecords.result.filter((existingRecord: T_WithId<T>) =>\n recordsToCheck.some((newRecord: T) =>\n filterFn(existingRecord, newRecord),\n ),\n );\n\n return foundRecords;\n },\n};\n\nexport { applyNestedPopulate } from './mongo.populate.js';\n"],"mappings":";;;;;;;;;;AAuBA,SAAgB,EAAuB,GAA2B;AAK9D,QAJI,MAAc,EAAU,aAAa,GAC9B,EAAU,OAAO,EAAE,CAAC,aAAa,GAAG,EAAU,MAAM,EAAE,CAAC,aAAa,GAGxE;;A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B,EAAU,CACtC,CACJ;;CAIR"}
1
+ {"version":3,"file":"mongo.util.js","names":[],"sources":["../../../src/node/mongo/mongo.util.ts"],"sourcesContent":["import type migrate from 'migrate-mongo';\nimport type mongooseRaw from 'mongoose';\n\nimport aggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\nimport { randomUUID } from 'node:crypto';\n\nimport { getNestedValue, regexSearchMapper, setNestedValue } from '#util/index.js';\nimport { validate } from '#util/validate/index.js';\n\nimport type { MongoController } from './mongo.controller.js';\nimport type { C_Document, I_CreateModelOptions, I_CreateSchemaOptions, I_DynamicVirtualConfig, I_DynamicVirtualOptions, I_ExtendedModel, I_GenericDocument, I_MongooseModelMiddleware, T_Filter, T_MongoosePlugin, T_MongooseSchema, T_QueryFilter, T_VirtualOptions, T_WithId } from './mongo.type.js';\n\nimport { addGitIgnoreEntry, writeFileSync } from '../fs/index.js';\nimport { MIGRATE_MONGO_CONFIG, PATH } from '../path/index.js';\n\n/**\n * Converts enum values to proper model names.\n * Handles common naming conventions like converting 'USER' to 'User'.\n *\n * @param enumValue - The enum value to convert\n * @returns The converted model name\n */\nexport function convertEnumToModelName(enumValue: string): string {\n if (enumValue === enumValue.toUpperCase()) {\n return enumValue.charAt(0).toUpperCase() + enumValue.slice(1).toLowerCase();\n }\n\n return enumValue;\n}\n\n/**\n * Interface for the MongoDB utility object to enable explicit type annotation.\n * Required to avoid TS7056 (inferred type exceeds maximum serialization length).\n */\ninterface I_MongoUtils {\n createGenericFields: () => I_GenericDocument;\n applyPlugins: <T>(schema: T_MongooseSchema<T>, plugins: Array<T_MongoosePlugin | false>) => void;\n applyMiddlewares: <T extends Partial<C_Document>>(schema: T_MongooseSchema<T>, middlewares: I_MongooseModelMiddleware<T>[]) => void;\n createGenericSchema: (mongoose: typeof mongooseRaw) => T_MongooseSchema<I_GenericDocument>;\n createSchema: <T, R extends string = string>(options: I_CreateSchemaOptions<T, R>) => T_MongooseSchema<T>;\n createModel: <T extends Partial<C_Document>, R extends string = string>(options: I_CreateModelOptions<T, R>) => I_ExtendedModel<T>;\n validator: {\n isRequired: <T>() => (this: T, value: unknown) => Promise<boolean>;\n isUnique: <T extends { constructor: { exists: (query: { [key: string]: unknown }) => Promise<unknown> } }>(fields: string[]) => (this: T, value: unknown) => Promise<boolean>;\n matchesRegex: (regexArray: RegExp[]) => (value: string) => Promise<boolean>;\n };\n migrate: {\n getModule: () => Promise<typeof migrate>;\n setConfig: (options: Partial<migrate.config.Config> & { moduleSystem?: 'commonjs' | 'esm' }) => void;\n };\n regexify: <T>(filter?: T_QueryFilter<T>, fields?: (keyof T | string)[]) => T_QueryFilter<T>;\n isDynamicVirtual: <T, R extends string>(options?: T_VirtualOptions<T, R>) => options is I_DynamicVirtualOptions<T, R>;\n getNewRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean, filter?: T_Filter<T>) => Promise<T[]>;\n getExistingRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean, filter?: T_Filter<T>) => Promise<T_WithId<T>[]>;\n}\n\n/**\n * MongoDB utility object providing comprehensive database operations and utilities.\n * This object contains methods for creating generic fields, applying plugins and middlewares,\n * creating schemas and models, validation functions, migration utilities, and regex filtering.\n */\nexport const mongo: I_MongoUtils = {\n /**\n * Creates generic fields that are commonly used across MongoDB documents.\n * This function generates standard fields including a UUID, deletion flag, and timestamps\n * that can be applied to any document schema.\n *\n * @returns An object containing generic document fields (id, isDel, createdAt, updatedAt).\n */\n createGenericFields(): I_GenericDocument {\n return {\n id: randomUUID(),\n isDel: false,\n createdAt: new Date(),\n updatedAt: new Date(),\n };\n },\n /**\n * Applies plugins to a Mongoose schema.\n * This function filters out falsy plugins and applies the remaining valid plugins\n * to the provided schema.\n *\n * @param schema - The Mongoose schema to apply plugins to.\n * @param plugins - An array of plugin functions or false values to filter and apply.\n */\n applyPlugins<T>(schema: T_MongooseSchema<T>, plugins: Array<T_MongoosePlugin | false>) {\n plugins\n .filter((plugin): plugin is T_MongoosePlugin => typeof plugin === 'function')\n .forEach(plugin => schema.plugin(plugin));\n },\n /**\n * Applies middleware functions to a Mongoose schema.\n * This function configures pre and post middleware for specified methods on the schema.\n *\n * @param schema - The Mongoose schema to apply middleware to.\n * @param middlewares - An array of middleware configurations with method, pre, and post functions.\n */\n applyMiddlewares<T extends Partial<C_Document>>(\n schema: T_MongooseSchema<T>,\n middlewares: I_MongooseModelMiddleware<T>[],\n ) {\n middlewares.forEach(({ method, pre, post }) => {\n if (method && pre) {\n schema.pre(method as RegExp, pre);\n }\n\n if (method && post) {\n schema.post(method as RegExp, post);\n }\n });\n },\n /**\n * Creates a generic Mongoose schema with common fields.\n * This function creates a base schema with UUID field and deletion flag,\n * configured with automatic timestamps.\n *\n * @param mongoose - The Mongoose instance to create the schema with.\n * @returns A Mongoose schema with generic document fields.\n */\n createGenericSchema(mongoose: typeof mongooseRaw) {\n return new mongoose.Schema<I_GenericDocument>(\n {\n id: { type: String, default: () => randomUUID(), unique: true },\n isDel: { type: Boolean, default: false },\n },\n { timestamps: true },\n );\n },\n /**\n * Creates a Mongoose schema with optional virtual fields and generic fields.\n * This function creates a new Mongoose schema from the provided schema definition,\n * optionally adds virtual fields, and includes generic fields (unless standalone is true).\n *\n * @param options - Configuration options including mongoose instance, schema definition, virtuals, and standalone flag.\n * @param options.mongoose - The Mongoose instance to use for schema creation.\n * @param options.schema - The schema definition object.\n * @param options.virtuals - Optional array of virtual field configurations.\n * @param options.standalone - Whether to exclude generic fields (default: false).\n * @returns A configured Mongoose schema.\n */\n createSchema<T, R extends string = string>({\n mongoose,\n schema,\n virtuals = [],\n standalone = false,\n }: I_CreateSchemaOptions<T, R>): T_MongooseSchema<T> {\n const createdSchema = new mongoose.Schema<T>(schema, {\n toJSON: { virtuals: true }, // So `res.json()` and other `JSON.stringify()` functions include virtuals\n toObject: { virtuals: true }, // So `console.log()` and other functions that use `toObject()` include virtuals\n });\n\n virtuals.forEach(({ name, options, get }) => {\n if (mongo.isDynamicVirtual<T, R>(options)) {\n const schemaStatics = createdSchema.statics as Record<string, unknown>;\n\n if (!schemaStatics['_dynamicVirtuals']) {\n schemaStatics['_dynamicVirtuals'] = [];\n }\n\n (schemaStatics['_dynamicVirtuals'] as I_DynamicVirtualConfig<T>[]).push({\n name: name as string,\n options,\n });\n\n const virtualInstance = createdSchema.virtual(name as string);\n\n if (get) {\n virtualInstance.get(get);\n }\n else {\n virtualInstance.get(function (this: T & { _populated?: { [key: string]: unknown } }) {\n return this._populated?.[name as string] || (options?.count ? 0 : (options?.justOne ? null : []));\n });\n }\n }\n else {\n const virtualInstance = createdSchema.virtual(name as string, options);\n\n if (get) {\n virtualInstance.get(get);\n }\n }\n });\n\n if (!standalone) {\n createdSchema.add(mongo.createGenericSchema(mongoose));\n }\n\n return createdSchema;\n },\n /**\n * Creates a Mongoose model with plugins, middleware, and pagination support.\n * This function creates a model from a schema with optional pagination and aggregation plugins,\n * and applies any specified middleware. If a model with the same name already exists, it returns the existing model.\n *\n * @param options - Configuration options including mongoose instance, model name, schema, and feature flags.\n * @param options.mongoose - The Mongoose instance to use for model creation.\n * @param options.name - The name of the model to create.\n * @param options.schema - The schema definition for the model.\n * @param options.pagination - Whether to enable pagination plugin (default: false).\n * @param options.aggregate - Whether to enable aggregation pagination plugin (default: false).\n * @param options.virtuals - Optional array of virtual field configurations.\n * @param options.middlewares - Optional array of middleware configurations.\n * @returns A configured Mongoose model with extended functionality.\n * @throws {Error} When the model name is not provided.\n */\n createModel<T extends Partial<C_Document>, R extends string = string>({\n mongoose: currentMongooseInstance,\n name,\n schema,\n virtuals = [],\n pagination = true,\n aggregate = true,\n middlewares = [],\n }: I_CreateModelOptions<T, R>): I_ExtendedModel<T> {\n if (!name) {\n throw new Error('Model name is required.');\n }\n\n if (currentMongooseInstance.models[name]) {\n return currentMongooseInstance.models[name] as I_ExtendedModel<T>;\n }\n\n const createdSchema = mongo.createSchema({ mongoose: currentMongooseInstance, schema, virtuals });\n\n if (pagination || aggregate) {\n mongo.applyPlugins<T>(createdSchema, [\n pagination && mongoosePaginate,\n aggregate && aggregatePaginate,\n ]);\n }\n\n mongo.applyMiddlewares<T>(createdSchema, middlewares);\n\n const model = currentMongooseInstance.model<T>(name, createdSchema) as I_ExtendedModel<T>;\n\n if (virtuals.length > 0) {\n // Mongoose Model has no typed _virtualConfigs; used by MongooseController.getDynamicVirtuals()\n (model as any)._virtualConfigs = virtuals;\n }\n\n return model;\n },\n /**\n * Validation utilities for Mongoose schemas.\n * This object provides common validation functions that can be used in Mongoose schema definitions.\n */\n validator: {\n /**\n * Creates a required field validator.\n * This function returns a validator that checks if a field value is not empty\n * using the validate.isEmpty utility.\n *\n * @returns A validation function that returns true if the field is not empty.\n */\n isRequired<T>(): (this: T, value: unknown) => Promise<boolean> {\n return async function (this: T, value: unknown): Promise<boolean> {\n return !validate.isEmpty(value);\n };\n },\n /**\n * Creates a unique field validator.\n * This function returns a validator that checks if a field value is unique\n * across the specified fields in the collection.\n *\n * @param fields - An array of field names to check for uniqueness.\n * @returns A validation function that returns true if the value is unique across the specified fields.\n * @throws {Error} When fields is not a non-empty array of strings.\n */\n isUnique<T extends { constructor: { exists: (query: { [key: string]: unknown }) => Promise<unknown> } }>(fields: string[]) {\n return async function (this: T, value: unknown): Promise<boolean> {\n if (!Array.isArray(fields) || fields.length === 0) {\n throw new Error('Fields must be a non-empty array of strings.');\n }\n\n const query = { $or: fields.map(field => ({ [field]: value })) };\n const existingDocument = await this.constructor.exists(query);\n\n return !existingDocument;\n };\n },\n /**\n * Creates a regex pattern validator.\n * This function returns a validator that checks if a string value matches\n * all provided regular expressions.\n *\n * @param regexArray - An array of regular expressions to test against the value.\n * @returns A validation function that returns true if the value matches all regex patterns.\n * @throws {Error} When regexArray is not an array of valid RegExp objects.\n */\n matchesRegex(regexArray: RegExp[]): (value: string) => Promise<boolean> {\n return async (value: string): Promise<boolean> => {\n if (!Array.isArray(regexArray) || regexArray.some(r => !(r instanceof RegExp))) {\n throw new Error('regexArray must be an array of valid RegExp objects.');\n }\n\n return regexArray.every(regex => regex.test(value));\n };\n },\n },\n /**\n * Migration utilities for MongoDB.\n * This object extends the migrate-mongo library with additional configuration utilities.\n */\n migrate: {\n /**\n * Lazily loads the migrate-mongo module to avoid eager import overhead.\n * Use this to access migrate-mongo methods (up, down, status, create) programmatically.\n *\n * @returns A promise resolving to the migrate-mongo module.\n */\n async getModule(): Promise<typeof migrate> {\n return (await import('migrate-mongo')).default;\n },\n /**\n * Sets the migration configuration and updates .gitignore.\n * This function creates a migration configuration file and ensures it's properly\n * excluded from version control.\n *\n * @param options - Migration configuration options to write to the config file.\n */\n setConfig: (options: Partial<migrate.config.Config> & { moduleSystem?: 'commonjs' | 'esm' }) => {\n const optionsJS = `// This file is automatically generated by the Cyberskill CLI.\\nmodule.exports = ${JSON.stringify(options, null, 4)}`;\n\n writeFileSync(PATH.MIGRATE_MONGO_CONFIG, optionsJS);\n\n addGitIgnoreEntry(PATH.GIT_IGNORE, MIGRATE_MONGO_CONFIG);\n },\n },\n /**\n * Converts string values in a filter to regex patterns for case-insensitive search.\n * This function recursively processes a filter object and converts string values in specified fields\n * to MongoDB regex patterns that support accented character matching.\n *\n * @remarks\n * **Performance guard:** Input strings are capped at 200 characters to mitigate ReDoS risk.\n * The generated regex patterns include accented character alternation groups (e.g., `(a|à|á|...)`)\n * which can be polynomially complex for very long inputs. For production search on large collections,\n * consider using MongoDB `$text` search indexes instead of `$regex` for better performance.\n *\n * @param filter - The filter object to process.\n * @param fields - An array of field names to convert to regex patterns.\n * @returns A new filter object with string values converted to regex patterns.\n */\n regexify<T>(filter?: T_QueryFilter<T>, fields?: (keyof T | string)[]): T_QueryFilter<T> {\n if (!filter) {\n return {} as T_QueryFilter<T>;\n }\n\n let newFilter = { ...filter };\n\n if (!fields || fields.length === 0) {\n return newFilter;\n }\n\n const MAX_REGEX_INPUT_LENGTH = 200;\n\n for (const field of fields) {\n const path = field.toString().split('.');\n const value = getNestedValue(newFilter, path);\n\n if (typeof value === 'string' && value.length > 0 && value.length <= MAX_REGEX_INPUT_LENGTH) {\n const regexValue = {\n $regex: `.*${regexSearchMapper(value)}.*`,\n $options: 'i',\n };\n\n newFilter = setNestedValue(newFilter, path, regexValue);\n }\n }\n\n return newFilter;\n },\n /**\n * Checks if a virtual options object has a dynamic ref function.\n *\n * @param options - The virtual options to check.\n * @returns True if the options contain a dynamic ref function.\n */\n isDynamicVirtual<T, R extends string = string>(options?: T_VirtualOptions<T, R>): options is I_DynamicVirtualOptions<T, R> {\n return Boolean(options && typeof options.ref === 'function');\n },\n\n /**\n * Generic utility function to get new records from the database\n * @param controller - MongoController instance\n * @param recordsToCheck - Array of records to check\n * @param filterFn - Function to determine if a record already exists\n * @param filter - Optional filter to narrow the query\n * @returns Array of records that don't exist in the database\n */\n async getNewRecords<T extends I_GenericDocument>(\n controller: MongoController<T>,\n recordsToCheck: T[],\n filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean,\n filter: T_Filter<T> = {} as T_Filter<T>,\n ): Promise<T[]> {\n const existingRecords = await controller.findAll(filter);\n\n if (!existingRecords.success) {\n throw new Error(`Failed to query existing records: ${existingRecords.message}`);\n }\n\n if ('truncated' in existingRecords && existingRecords.truncated) {\n throw new Error('getNewRecords: Results were truncated by the default limit. Use pagination or set an explicit limit to ensure complete data.');\n }\n\n const filteredRecords = recordsToCheck.filter(newRecord =>\n !existingRecords.result.some((existingRecord: T_WithId<T>) =>\n filterFn(existingRecord, newRecord),\n ),\n );\n\n return filteredRecords;\n },\n\n /**\n * Generic utility function to get existing records that match the filter criteria\n * @param controller - MongoController instance\n * @param recordsToCheck - Array of records to check\n * @param filterFn - Function to determine if a record exists\n * @param filter - Optional filter to narrow the query\n * @returns Array of existing records that match the filter criteria\n * @throws {Error} When the database query fails — prevents silent data inconsistency.\n */\n async getExistingRecords<T extends I_GenericDocument>(\n controller: MongoController<T>,\n recordsToCheck: T[],\n filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean,\n filter: T_Filter<T> = {} as T_Filter<T>,\n ): Promise<T_WithId<T>[]> {\n const existingRecords = await controller.findAll(filter);\n\n if (!existingRecords.success) {\n throw new Error(`Failed to query existing records: ${existingRecords.message}`);\n }\n\n if ('truncated' in existingRecords && existingRecords.truncated) {\n throw new Error('getExistingRecords: Results were truncated by the default limit. Use pagination or set an explicit limit to ensure complete data.');\n }\n\n const foundRecords = existingRecords.result.filter((existingRecord: T_WithId<T>) =>\n recordsToCheck.some((newRecord: T) =>\n filterFn(existingRecord, newRecord),\n ),\n );\n\n return foundRecords;\n },\n};\n\nexport { applyNestedPopulate } from './mongo.populate.js';\n"],"mappings":";;;;;;;;;;AAuBA,SAAgB,EAAuB,GAA2B;AAK9D,QAJI,MAAc,EAAU,aAAa,GAC9B,EAAU,OAAO,EAAE,CAAC,aAAa,GAAG,EAAU,MAAM,EAAE,CAAC,aAAa,GAGxE;;AAkCX,IAAa,IAAsB;CAQ/B,sBAAyC;AACrC,SAAO;GACH,IAAI,GAAY;GAChB,OAAO;GACP,2BAAW,IAAI,MAAM;GACrB,2BAAW,IAAI,MAAM;GACxB;;CAUL,aAAgB,GAA6B,GAA0C;AACnF,IACK,QAAQ,MAAuC,OAAO,KAAW,WAAW,CAC5E,SAAQ,MAAU,EAAO,OAAO,EAAO,CAAC;;CASjD,iBACI,GACA,GACF;AACE,IAAY,SAAS,EAAE,WAAQ,QAAK,cAAW;AAK3C,GAJI,KAAU,KACV,EAAO,IAAI,GAAkB,EAAI,EAGjC,KAAU,KACV,EAAO,KAAK,GAAkB,EAAK;IAEzC;;CAUN,oBAAoB,GAA8B;AAC9C,SAAO,IAAI,EAAS,OAChB;GACI,IAAI;IAAE,MAAM;IAAQ,eAAe,GAAY;IAAE,QAAQ;IAAM;GAC/D,OAAO;IAAE,MAAM;IAAS,SAAS;IAAO;GAC3C,EACD,EAAE,YA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Q,KAAW,OAAO,EAAQ,OAAQ;;CAWrD,MAAM,cACF,GACA,GACA,GACA,IAAsB,EAAE,EACZ;EACZ,IAAM,IAAkB,MAAM,EAAW,QAAQ,EAAO;AAExD,MAAI,CAAC,EAAgB,QACjB,OAAU,MAAM,qCAAqC,EAAgB,UAAU;AAGnF,MAAI,eAAe,KAAmB,EAAgB,UAClD,OAAU,MAAM,+HAA+H;AASnJ,SANwB,EAAe,QAAO,MAC1C,CAAC,EAAgB,OAAO,MAAM,MAC1B,EAAS,GAAgB,EAAU,CACtC,CACJ;;CAcL,MAAM,mBACF,GACA,GACA,GACA,IAAsB,EAAE,EACF;EACtB,IAAM,IAAkB,MAAM,EAAW,QAAQ,EAAO;AAExD,MAAI,CAAC,EAAgB,QACjB,OAAU,MAAM,qCAAqC,EAAgB,UAAU;AAGnF,MAAI,eAAe,KAAmB,EAAgB,UAClD,OAAU,MAAM,oIAAoI;AASxJ,SANqB,EAAgB,OAAO,QAAQ,MAChD,EAAe,MAAM,MACjB,EAAS,GAAgB,EAAU,CACtC,CACJ;;CAIR"}
@@ -1,3 +1,3 @@
1
- import { NODE_FS_DRIVER_NAME as e, STORAGE_INSTANCE_NAME as t, STORAGE_KEY_EXTENSION as n, STORAGE_STORE_NAME as r } from "./storage.constant.js";
2
- import { resetStorageForTesting as i, storage as a } from "./storage.util.js";
3
- export { e as NODE_FS_DRIVER_NAME, t as STORAGE_INSTANCE_NAME, n as STORAGE_KEY_EXTENSION, r as STORAGE_STORE_NAME, i as resetStorageForTesting, a as storage };
1
+ import { STORAGE_KEY_EXTENSION as e } from "./storage.constant.js";
2
+ import { resetStorageForTesting as t, storage as n } from "./storage.util.js";
3
+ export { e as STORAGE_KEY_EXTENSION, t as resetStorageForTesting, n as storage };
@@ -1,4 +1 @@
1
- export declare const NODE_FS_DRIVER_NAME = "localforage-node-fs";
2
1
  export declare const STORAGE_KEY_EXTENSION = ".json";
3
- export declare const STORAGE_INSTANCE_NAME = "cyberskill";
4
- export declare const STORAGE_STORE_NAME = "node-storage";
@@ -1,6 +1,6 @@
1
1
  //#region src/node/storage/storage.constant.ts
2
- var e = "localforage-node-fs", t = ".json", n = "cyberskill", r = "node-storage";
2
+ var e = ".json";
3
3
  //#endregion
4
- export { e as NODE_FS_DRIVER_NAME, n as STORAGE_INSTANCE_NAME, t as STORAGE_KEY_EXTENSION, r as STORAGE_STORE_NAME };
4
+ export { e as STORAGE_KEY_EXTENSION };
5
5
 
6
6
  //# sourceMappingURL=storage.constant.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"storage.constant.js","names":[],"sources":["../../../src/node/storage/storage.constant.ts"],"sourcesContent":["export const NODE_FS_DRIVER_NAME = 'localforage-node-fs';\nexport const STORAGE_KEY_EXTENSION = '.json';\nexport const STORAGE_INSTANCE_NAME = 'cyberskill';\nexport const STORAGE_STORE_NAME = 'node-storage';\n"],"mappings":";AAAA,IAAa,IAAsB,uBACtB,IAAwB,SACxB,IAAwB,cACxB,IAAqB"}
1
+ {"version":3,"file":"storage.constant.js","names":[],"sources":["../../../src/node/storage/storage.constant.ts"],"sourcesContent":["export const STORAGE_KEY_EXTENSION = '.json';\n"],"mappings":";AAAA,IAAa,IAAwB"}
@@ -1,14 +1,3 @@
1
- import { default as localForage } from 'localforage';
2
- export type LocalForageDriver = Parameters<typeof localForage.defineDriver>[0];
3
- export interface NodeLocalForageOptions {
4
- driver?: string | string[];
5
- size?: number;
6
- version?: number;
7
- description?: string;
8
- name?: string;
9
- storeName?: string;
10
- baseDir?: string;
11
- }
12
1
  export interface NodeFsDriverState {
13
2
  baseDir: string;
14
3
  }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Persistent storage utility object for data persistence across application sessions.
3
- * This object provides methods for storing, retrieving, and managing data using localForage,
3
+ * Uses a filesystem-backed driver that stores JSON-encoded values on disk,
4
4
  * with automatic initialization and error handling.
5
5
  */
6
6
  export declare const storage: {
@@ -1,120 +1,112 @@
1
1
  import { getEnv as e } from "../../config/env/env.util.js";
2
2
  import { catchError as t, log as n } from "../log/log.util.js";
3
- import { NODE_FS_DRIVER_NAME as r, STORAGE_INSTANCE_NAME as i, STORAGE_KEY_EXTENSION as a, STORAGE_STORE_NAME as o } from "./storage.constant.js";
4
- import s from "localforage";
5
- import c from "node:path";
6
- import l from "node:fs/promises";
3
+ import { STORAGE_KEY_EXTENSION as r } from "./storage.constant.js";
4
+ import i from "node:path";
5
+ import a from "node:fs/promises";
7
6
  //#region src/node/storage/storage.util.ts
8
- var u = 200, d = { baseDir: "" };
9
- function f(e) {
10
- return `${encodeURIComponent(e)}${a}`;
7
+ var o = 200, s = { baseDir: "" };
8
+ function c(e) {
9
+ if (e.length > o) throw RangeError(`Storage key exceeds maximum length of ${o} characters`);
10
+ return `${encodeURIComponent(e)}${r}`;
11
11
  }
12
- function p(e) {
13
- return decodeURIComponent(e.slice(0, -a.length));
12
+ function l(e) {
13
+ return decodeURIComponent(e.slice(0, -r.length));
14
14
  }
15
- function m(e, t) {
16
- return c.join(t, f(e));
15
+ function u(e, t) {
16
+ return i.join(t, c(e));
17
17
  }
18
- var h = {
19
- _driver: r,
20
- _support: !0,
21
- async _initStorage(t) {
18
+ var d = {
19
+ async init(t) {
22
20
  try {
23
- let n = typeof t == "object" && t && "baseDir" in t ? t.baseDir : void 0;
24
- typeof n == "string" && n.length > 0 ? d.baseDir = n : d.baseDir = e().CYBERSKILL_STORAGE_DIRECTORY, await l.mkdir(d.baseDir, { recursive: !0 });
21
+ typeof t == "string" && t.length > 0 ? s.baseDir = t : s.baseDir = e().CYBERSKILL_STORAGE_DIRECTORY, await a.mkdir(s.baseDir, { recursive: !0 });
25
22
  } catch (e) {
26
23
  throw n.error("[Storage:init]", e), e;
27
24
  }
28
25
  },
29
26
  async clear() {
30
- let { baseDir: e } = d;
31
- e && (await l.rm(e, {
32
- recursive: !0,
33
- force: !0
34
- }), await l.mkdir(e, { recursive: !0 }));
27
+ let { baseDir: e } = s;
28
+ if (!e) return;
29
+ let t = `${e}.trash.${Date.now()}`, n = `${e}.fresh.${Date.now()}`;
30
+ try {
31
+ await a.mkdir(n, { recursive: !0 });
32
+ try {
33
+ await a.rename(e, t);
34
+ } catch {}
35
+ await a.rename(n, e), a.rm(t, {
36
+ recursive: !0,
37
+ force: !0
38
+ }).catch(() => {});
39
+ } catch {
40
+ await a.rm(e, {
41
+ recursive: !0,
42
+ force: !0
43
+ }), await a.mkdir(e, { recursive: !0 }), a.rm(n, {
44
+ recursive: !0,
45
+ force: !0
46
+ }).catch(() => {}), a.rm(t, {
47
+ recursive: !0,
48
+ force: !0
49
+ }).catch(() => {});
50
+ }
35
51
  },
36
52
  async getItem(e) {
37
- let { baseDir: t } = d, n = m(e, t);
53
+ let { baseDir: t } = s, n = u(e, t);
38
54
  try {
39
- let e = await l.readFile(n, "utf8");
55
+ let e = await a.readFile(n, "utf8");
40
56
  return JSON.parse(e);
41
57
  } catch (e) {
42
58
  if (e.code === "ENOENT") return null;
43
59
  throw e;
44
60
  }
45
61
  },
46
- async iterate(e) {
47
- let t = await h.keys(), n = 1;
48
- for (let r of t) {
49
- let t = e(await h.getItem(r), r, n);
50
- if (t !== void 0) return t;
51
- n += 1;
52
- }
53
- },
54
- async key(e) {
55
- return (await h.keys())[e] ?? null;
56
- },
57
62
  async keys() {
58
- let { baseDir: e } = d;
63
+ let { baseDir: e } = s;
59
64
  try {
60
- return (await l.readdir(e)).filter((e) => e.endsWith(a)).map(p);
65
+ return (await a.readdir(e)).filter((e) => e.endsWith(r)).map(l);
61
66
  } catch (e) {
62
67
  if (e.code === "ENOENT") return [];
63
68
  throw e;
64
69
  }
65
70
  },
66
- async length() {
67
- return (await h.keys()).length;
68
- },
69
71
  async removeItem(e) {
70
- let { baseDir: t } = d, n = m(e, t);
71
- await l.rm(n, { force: !0 });
72
+ let { baseDir: t } = s, n = u(e, t);
73
+ await a.rm(n, { force: !0 });
72
74
  },
73
75
  async setItem(e, t) {
74
- let { baseDir: n } = d, r = m(e, n);
75
- return await l.mkdir(n, { recursive: !0 }), await l.writeFile(r, JSON.stringify(t), "utf8"), t;
76
+ let { baseDir: n } = s, r = u(e, n);
77
+ return await a.mkdir(n, { recursive: !0 }), await a.writeFile(r, JSON.stringify(t), "utf8"), t;
76
78
  }
77
- }, g = null, _ = null;
78
- async function v() {
79
- return g ? (await g, _) : (g = (async () => {
80
- await s.defineDriver(h), d.baseDir = e().CYBERSKILL_STORAGE_DIRECTORY;
81
- let t = await s.getDriver(r);
82
- await t._initStorage({
83
- baseDir: d.baseDir,
84
- name: i,
85
- storeName: o
86
- }), _ = t;
87
- })().catch((e) => {
88
- throw g = null, e;
89
- }), await g, _);
79
+ }, f = null;
80
+ async function p() {
81
+ return f ? (await f, d) : (f = d.init().catch((e) => {
82
+ throw f = null, e;
83
+ }), await f, d);
90
84
  }
91
- var y = {
85
+ var m = {
92
86
  async get(e) {
93
- if (e.length > u) return n.warn(`[Storage:get] Key exceeds maximum length of ${u} characters`), null;
94
87
  try {
95
- return await (await v()).getItem(e) ?? null;
88
+ return await (await p()).getItem(e) ?? null;
96
89
  } catch (e) {
97
90
  return t(e, { returnValue: null });
98
91
  }
99
92
  },
100
93
  async set(e, n) {
101
- if (e.length > u) throw RangeError(`Storage key exceeds maximum length of ${u} characters`);
102
94
  try {
103
- await (await v()).setItem(e, n);
95
+ await (await p()).setItem(e, n);
104
96
  } catch (e) {
105
97
  throw t(e), e;
106
98
  }
107
99
  },
108
100
  async remove(e) {
109
101
  try {
110
- await (await v()).removeItem(e);
102
+ await (await p()).removeItem(e);
111
103
  } catch (e) {
112
104
  t(e);
113
105
  }
114
106
  },
115
107
  async keys() {
116
108
  try {
117
- let e = await (await v()).keys();
109
+ let e = await (await p()).keys();
118
110
  return Array.isArray(e) ? e : (n.warn("[Storage:keys] Invalid keys response:", e), []);
119
111
  } catch (e) {
120
112
  return t(e, { returnValue: [] });
@@ -122,16 +114,16 @@ var y = {
122
114
  },
123
115
  async getLogLink(n) {
124
116
  try {
125
- return `${c.join(e().CYBERSKILL_STORAGE_DIRECTORY, f(n))} (key: ${n})`;
117
+ return `${i.join(e().CYBERSKILL_STORAGE_DIRECTORY, c(n))} (key: ${n})`;
126
118
  } catch (e) {
127
119
  return t(e, { returnValue: null });
128
120
  }
129
121
  }
130
122
  };
131
- function b() {
132
- g = null, _ = null, d.baseDir = "";
123
+ function h() {
124
+ f = null, s.baseDir = "";
133
125
  }
134
126
  //#endregion
135
- export { b as resetStorageForTesting, y as storage };
127
+ export { h as resetStorageForTesting, m as storage };
136
128
 
137
129
  //# sourceMappingURL=storage.util.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"storage.util.js","names":[],"sources":["../../../src/node/storage/storage.util.ts"],"sourcesContent":["import localForage from 'localforage';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { getEnv } from '#config/env/index.js';\n\nimport type { LocalForageDriver, NodeFsDriverState, NodeLocalForageOptions } from './storage.type.js';\n\nimport { catchError, log } from '../log/index.js';\nimport { NODE_FS_DRIVER_NAME, STORAGE_INSTANCE_NAME, STORAGE_KEY_EXTENSION, STORAGE_STORE_NAME } from './storage.constant.js';\n\nconst MAX_KEY_LENGTH = 200;\n\nconst nodeFsDriverState: NodeFsDriverState = {\n baseDir: '',\n};\n\n/**\n * Encodes a storage key into a filename-safe string.\n */\nfunction encodeKey(key: string): string {\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 * Custom localForage driver that stores JSON-encoded values on the filesystem.\n */\nconst nodeFsDriver: LocalForageDriver = {\n _driver: NODE_FS_DRIVER_NAME,\n _support: true,\n /** Ensures the storage directory exists and respects custom baseDir overrides. */\n async _initStorage(options: unknown) {\n try {\n const baseDirFromOptions = typeof options === 'object' && options !== null && 'baseDir' in options\n ? (options as { baseDir?: unknown }).baseDir\n : undefined;\n\n if (typeof baseDirFromOptions === 'string' && baseDirFromOptions.length > 0) {\n nodeFsDriverState.baseDir = baseDirFromOptions;\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 by recreating the directory. Callers must ensure no concurrent operations. */\n async clear() {\n const { baseDir } = nodeFsDriverState;\n\n if (!baseDir) {\n return;\n }\n\n await fs.rm(baseDir, { recursive: true, force: true });\n await fs.mkdir(baseDir, { recursive: true });\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 /** Iterates through all keys, invoking the iterator until it returns a value. */\n async iterate<T, U>(iterator: (value: T, key: string, iterationNumber: number) => U): Promise<U> {\n const keys = await nodeFsDriver.keys();\n let iterationNumber = 1;\n\n for (const key of keys) {\n const value = await nodeFsDriver.getItem<T>(key);\n\n const result = iterator(value as T, key, iterationNumber);\n\n if (result !== undefined) {\n return result;\n }\n iterationNumber += 1;\n }\n\n return undefined as unknown as U;\n },\n /** Returns the key name at the given index or null when out of bounds. */\n async key(keyIndex: number): Promise<string> {\n const keys = await nodeFsDriver.keys();\n\n return keys[keyIndex] ?? null as unknown as string;\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 /** Returns the count of stored keys. */\n async length(): Promise<number> {\n const keys = await nodeFsDriver.keys();\n\n return keys.length;\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 driverInstance: LocalForageDriver | null = null;\n\n/**\n * Prepares and returns the filesystem-backed localForage driver.\n * We bypass localForage's default driver selection and explicitly initialize\n * our custom driver to ensure Node compatibility.\n */\nasync function ensureLocalForageReady(): Promise<LocalForageDriver> {\n if (initPromise) {\n await initPromise;\n return driverInstance as LocalForageDriver;\n }\n\n initPromise = (async () => {\n await localForage.defineDriver(nodeFsDriver);\n nodeFsDriverState.baseDir = getEnv().CYBERSKILL_STORAGE_DIRECTORY;\n const driver = await localForage.getDriver(NODE_FS_DRIVER_NAME);\n\n const initOptions = {\n baseDir: nodeFsDriverState.baseDir,\n name: STORAGE_INSTANCE_NAME,\n storeName: STORAGE_STORE_NAME,\n } satisfies NodeLocalForageOptions;\n\n await driver._initStorage(initOptions as unknown as Parameters<typeof driver._initStorage>[0]);\n driverInstance = driver;\n })().catch((error) => {\n initPromise = null;\n throw error;\n });\n\n await initPromise;\n\n return driverInstance as LocalForageDriver;\n}\n\n/**\n * Persistent storage utility object for data persistence across application sessions.\n * This object provides methods for storing, retrieving, and managing data using localForage,\n * with automatic initialization and error handling.\n */\nexport const storage = {\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 if (key.length > MAX_KEY_LENGTH) {\n log.warn(`[Storage:get] Key exceeds maximum length of ${MAX_KEY_LENGTH} characters`);\n return null;\n }\n\n try {\n const driver = await ensureLocalForageReady();\n const result = await driver.getItem<T>(key);\n\n return result ?? null;\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 * @returns A promise that resolves when the storage operation is complete.\n */\n async set<T = unknown>(key: string, value: T): Promise<void> {\n if (key.length > MAX_KEY_LENGTH) {\n throw new RangeError(`Storage key exceeds maximum length of ${MAX_KEY_LENGTH} characters`);\n }\n\n try {\n const driver = await ensureLocalForageReady();\n\n await driver.setItem(key, value);\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 ensureLocalForageReady();\n\n await driver.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.\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 ensureLocalForageReady();\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};\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 */\nexport function resetStorageForTesting(): void {\n initPromise = null;\n driverInstance = null;\n nodeFsDriverState.baseDir = '';\n}\n"],"mappings":";;;;;;;AAWA,IAAM,IAAiB,KAEjB,IAAuC,EACzC,SAAS,IACZ;AAKD,SAAS,EAAU,GAAqB;AACpC,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;;AAM7C,IAAM,IAAkC;CACpC,SAAS;CACT,UAAU;CAEV,MAAM,aAAa,GAAkB;AACjC,MAAI;GACA,IAAM,IAAqB,OAAO,KAAY,YAAY,KAAoB,aAAa,IACpF,EAAkC,UACnC,KAAA;AASN,GAPI,OAAO,KAAuB,YAAY,EAAmB,SAAS,IACtE,EAAkB,UAAU,IAG5B,EAAkB,UAAU,GAAQ,CAAC,8BAGzC,MAAM,EAAG,MAAM,EAAkB,SAAS,EAAE,WAAW,IAAM,CAAC;WAE3D,GAAO;AAEV,SADA,EAAI,MAAM,kBAAkB,EAAM,EAC5B;;;CAId,MAAM,QAAQ;EACV,IAAM,EAAE,eAAY;AAEf,QAIL,MAAM,EAAG,GAAG,GAAS;GAAE,WAAW;GAAM,OAAO;GAAM,CAAC,EACtD,MAAM,EAAG,MAAM,GAAS,E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,CAAC,8BAA8B,EAAU,EAAI,CAAC,CAE9D,SAAS,EAAI;WAEhC,GAAO;AACV,UAAO,EAAW,GAAO,EAAE,aAAa,MAAM,CAAC;;;CAI1D;AAOD,SAAgB,IAA+B;AAG3C,CAFA,IAAc,MACd,IAAiB,MACjB,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 { 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\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 * storage operations without the unnecessary browser-oriented dependency.\n */\nconst fsDriver = {\n /** Ensures the storage directory exists. */\n async init(baseDir?: string) {\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;\n\n/**\n * Initializes the filesystem storage driver (singleton, idempotent).\n * Ensures the storage directory exists before any read/write operations.\n */\nasync function ensureDriverReady(): Promise<typeof fsDriver> {\n if (initPromise) {\n await initPromise;\n return fsDriver;\n }\n\n initPromise = fsDriver.init().catch((error) => {\n initPromise = null;\n throw error;\n });\n\n await initPromise;\n\n return fsDriver;\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 * 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<T>(key);\n\n return result ?? null;\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 * @returns A promise that resolves when the storage operation is complete.\n */\n async set<T = unknown>(key: string, value: T): Promise<void> {\n try {\n const driver = await ensureDriverReady();\n\n await driver.setItem(key, value);\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 * 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};\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 */\nexport function resetStorageForTesting(): void {\n initPromise = null;\n nodeFsDriverState.baseDir = '';\n}\n"],"mappings":";;;;;;AAQA,IAAM,IAAiB,KAMjB,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;;AAQ7C,IAAM,IAAW;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,EAAK,GAKjB,KAJH,EAAI,KAAK,yCAAyC,EAAK,EAChD,EAAE;WAKV,GAAO;AACV,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,GAAO;AACV,UAAO,EAAW,GAAO,EAAE,aAAa,MAAM,CAAC;;;CAI1D;AAOD,SAAgB,IAA+B;AAE3C,CADA,IAAc,MACd,EAAkB,UAAU"}
@@ -32,4 +32,6 @@ export interface I_UploadOptions {
32
32
  path: string;
33
33
  type: E_UploadType;
34
34
  config?: I_UploadConfig;
35
+ /** Base directory for path containment validation. When set, the resolved `path` must reside within this directory. */
36
+ baseDir?: string;
35
37
  }
@@ -1 +1 @@
1
- {"version":3,"file":"upload.type.js","names":[],"sources":["../../../src/node/upload/upload.type.ts"],"sourcesContent":["export enum E_UploadType {\n IMAGE = 'IMAGE',\n VIDEO = 'VIDEO',\n AUDIO = 'AUDIO',\n DOCUMENT = 'DOCUMENT',\n OTHER = 'OTHER',\n}\n\nexport interface I_UploadValidationConfig {\n filename: string;\n fileSize?: number;\n}\n\nexport interface I_UploadTypeConfig {\n allowedExtensions: string[];\n sizeLimit: number;\n}\n\nexport interface I_UploadConfig {\n [E_UploadType.IMAGE]: I_UploadTypeConfig;\n [E_UploadType.VIDEO]: I_UploadTypeConfig;\n [E_UploadType.AUDIO]: I_UploadTypeConfig;\n [E_UploadType.DOCUMENT]: I_UploadTypeConfig;\n [E_UploadType.OTHER]: I_UploadTypeConfig;\n}\n\nexport interface I_UploadFileData {\n createReadStream: () => NodeJS.ReadableStream;\n filename: string;\n}\n\nexport interface I_UploadFile {\n file: I_UploadFileData;\n}\n\nexport interface I_UploadOptions {\n file: Promise<I_UploadFile>;\n path: string;\n type: E_UploadType;\n config?: I_UploadConfig;\n}\n"],"mappings":";AAAA,IAAY,IAAL,yBAAA,GAAA;QACH,EAAA,QAAA,SACA,EAAA,QAAA,SACA,EAAA,QAAA,SACA,EAAA,WAAA,YACA,EAAA,QAAA;KACH"}
1
+ {"version":3,"file":"upload.type.js","names":[],"sources":["../../../src/node/upload/upload.type.ts"],"sourcesContent":["export enum E_UploadType {\n IMAGE = 'IMAGE',\n VIDEO = 'VIDEO',\n AUDIO = 'AUDIO',\n DOCUMENT = 'DOCUMENT',\n OTHER = 'OTHER',\n}\n\nexport interface I_UploadValidationConfig {\n filename: string;\n fileSize?: number;\n}\n\nexport interface I_UploadTypeConfig {\n allowedExtensions: string[];\n sizeLimit: number;\n}\n\nexport interface I_UploadConfig {\n [E_UploadType.IMAGE]: I_UploadTypeConfig;\n [E_UploadType.VIDEO]: I_UploadTypeConfig;\n [E_UploadType.AUDIO]: I_UploadTypeConfig;\n [E_UploadType.DOCUMENT]: I_UploadTypeConfig;\n [E_UploadType.OTHER]: I_UploadTypeConfig;\n}\n\nexport interface I_UploadFileData {\n createReadStream: () => NodeJS.ReadableStream;\n filename: string;\n}\n\nexport interface I_UploadFile {\n file: I_UploadFileData;\n}\n\nexport interface I_UploadOptions {\n file: Promise<I_UploadFile>;\n path: string;\n type: E_UploadType;\n config?: I_UploadConfig;\n /** Base directory for path containment validation. When set, the resolved `path` must reside within this directory. */\n baseDir?: string;\n}\n"],"mappings":";AAAA,IAAY,IAAL,yBAAA,GAAA;QACH,EAAA,QAAA,SACA,EAAA,QAAA,SACA,EAAA,QAAA,SACA,EAAA,WAAA,YACA,EAAA,QAAA;KACH"}
@@ -74,13 +74,21 @@ function _(e) {
74
74
  };
75
75
  }
76
76
  async function v(n) {
77
- let { path: r, file: c, config: u, type: d } = n;
77
+ let { path: r, file: c, config: u, type: d, baseDir: f } = n;
78
78
  if (!r || typeof r != "string") return {
79
79
  success: !1,
80
80
  message: "Invalid path provided",
81
81
  code: e.BAD_REQUEST.CODE
82
82
  };
83
- if (l.resolve(r) !== l.normalize(r) && r.includes("..")) return {
83
+ let m = l.resolve(r);
84
+ if (f) {
85
+ let t = l.resolve(f) + l.sep;
86
+ if (!m.startsWith(t) && m !== l.resolve(f)) return {
87
+ success: !1,
88
+ message: "Path traversal detected: path resolves outside the allowed base directory",
89
+ code: e.BAD_REQUEST.CODE
90
+ };
91
+ } else if (r.includes("..")) return {
84
92
  success: !1,
85
93
  message: "Path traversal detected: \"..\" segments are not allowed",
86
94
  code: e.BAD_REQUEST.CODE
@@ -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 { 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 },\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 } = 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 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 */\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 } = 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: Prevent directory traversal attacks by checking the resolved path\n const resolvedPath = nodePath.resolve(path);\n\n if (resolvedPath !== nodePath.normalize(path) && 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 writeStream = createReadStream();\n const out = createWriteStream(path);\n writeStream.pipe(out);\n\n await new Promise<void>((resolve, reject) => {\n out.on('finish', () => resolve());\n out.on('error', reject);\n writeStream.on('error', reject);\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":";;;;;;;;;;AAwBA,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,EA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,0BAA0B,EAAa,aAAa,CAAC;IAC9D,MAAM,EAAgB,YAAY;IACrC;;;AAKb,KAAI;EACA,IAAM,IAAW,MAAM,EAAmB,GAAM,MAAM,GAAM,EAAO;AAEnE,MAAI,CAAC,EAAS,QACV,QAAO;EAGX,IAAM,EAAE,wBAAqB,EAAS,QAEhC,IAAM,EAAQ,EAAK;AAEzB,EAAK,EAAe,EAAI,IACpB,EAAU,GAAK,EAAE,WAAW,IAAM,CAAC;EAGvC,IAAM,IAAc,GAAkB,EAChC,IAAM,EAAkB,EAAK;AASnC,SARA,EAAY,KAAK,EAAI,EAErB,MAAM,IAAI,SAAe,GAAS,MAAW;AAGzC,GAFA,EAAI,GAAG,gBAAgB,GAAS,CAAC,EACjC,EAAI,GAAG,SAAS,EAAO,EACvB,EAAY,GAAG,SAAS,EAAO;IACjC,EAEK;GACH,SAAS;GACT,QAAQ;GACR,SAAS;GACT,MAAM,EAAgB,GAAG;GAC5B;UAEE,GAAO;AACV,SAAO;GACH,SAAS;GACT,SAAS,aAAiB,QAAQ,EAAM,UAAU;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 { 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 },\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 } = 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 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 */\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 writeStream = createReadStream();\n const out = createWriteStream(path);\n writeStream.pipe(out);\n\n await new Promise<void>((resolve, reject) => {\n out.on('finish', () => resolve());\n out.on('error', reject);\n writeStream.on('error', reject);\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":";;;;;;;;;;AAwBA,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,EACzC,GACA,EACH;AAUD,QARK,EAAiB,UAQf;EACH,SAAS;EACT,QAAQ;EACR,SAAS;EACZ,GAXU;EACH,SAAS;EACT,SAAS,EAAiB,SAAS;EACnC,MAAM,EAAgB,YAAY;EACrC;;AAwBT,eAAsB,EAAiB,GAAoB,GAAoB,GAAwE;CAEnJ,IAAM,KADe,KAAU,GAAoB,EACnB,IAE1B,IAAW,MAAM,EAAmB,GAAM,GAAM,EAAO;AAE7D,KAAI,CAAC,EAAS,QACV,QAAO;CAGX,IAAM,EAAE,wBAAqB,EAAS,QAElC,IAAiB,EAAW,WAE1B,IAAuB,IAAI,EAAU,EACvC,UAAU,GAAe,GAAsB,GAAI;AAG/C,EAFA,KAAkB,EAAM,QAEpB,IAAiB,IACjB,EAAG,gBAAI,MAAM,8BAA8B,EAAW,YAAY,EAAa,IAAI,CAAC,GAGpF,EAAG,MAAM,EAAM;IAG1B,CAAC,EAEI,IAD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AAGzC,GAFA,EAAI,GAAG,gBAAgB,GAAS,CAAC,EACjC,EAAI,GAAG,SAAS,EAAO,EACvB,EAAY,GAAG,SAAS,EAAO;IACjC,EAEK;GACH,SAAS;GACT,QAAQ;GACR,SAAS;GACT,MAAM,EAAgB,GAAG;GAC5B;UAEE,GAAO;AACV,SAAO;GACH,SAAS;GACT,SAAS,aAAiB,QAAQ,EAAM,UAAU;GAClD,MAAM,EAAgB,sBAAsB;GAC/C"}
@@ -0,0 +1,8 @@
1
+ //#region node_modules/.pnpm/vitest@4.1.0_@types+node@25.5.0_jsdom@29.0.1_@noble+hashes@1.8.0__vite@8.0.1_@types+nod_5f6c16f4d4385f16c87b17afc93c851f/node_modules/vitest/dist/config.js
2
+ function e(e) {
3
+ return e;
4
+ }
5
+ //#endregion
6
+ export { e as defineConfig };
7
+
8
+ //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":[],"sources":["../../../../../../../node_modules/.pnpm/vitest@4.1.0_@types+node@25.5.0_jsdom@29.0.0_@noble+hashes@1.8.0__vite@8.0.1_@types+nod_36acd00c2670b611b011192023dc5bd9/node_modules/vitest/dist/config.js"],"sourcesContent":["export { c as configDefaults, a as coverageConfigDefaults, d as defaultExclude, b as defaultInclude } from './chunks/defaults.CdU2lD-q.js';\nexport { mergeConfig } from 'vite';\nexport { d as defaultBrowserPort } from './chunks/constants.CPYnjOGj.js';\nimport 'node:os';\nimport './chunks/env.D4Lgay0q.js';\nimport 'std-env';\n\nfunction defineConfig(config) {\n\treturn config;\n}\nfunction defineProject(config) {\n\treturn config;\n}\n\nexport { defineConfig, defineProject };\n"],"x_google_ignoreList":[0],"mappings":";AAOA,SAAS,EAAa,GAAQ;AAC7B,QAAO"}
1
+ {"version":3,"file":"config.js","names":[],"sources":["../../../../../../../node_modules/.pnpm/vitest@4.1.0_@types+node@25.5.0_jsdom@29.0.1_@noble+hashes@1.8.0__vite@8.0.1_@types+nod_5f6c16f4d4385f16c87b17afc93c851f/node_modules/vitest/dist/config.js"],"sourcesContent":["export { c as configDefaults, a as coverageConfigDefaults, d as defaultExclude, b as defaultInclude } from './chunks/defaults.CdU2lD-q.js';\nexport { mergeConfig } from 'vite';\nexport { d as defaultBrowserPort } from './chunks/constants.CPYnjOGj.js';\nimport 'node:os';\nimport './chunks/env.D4Lgay0q.js';\nimport 'std-env';\n\nfunction defineConfig(config) {\n\treturn config;\n}\nfunction defineProject(config) {\n\treturn config;\n}\n\nexport { defineConfig, defineProject };\n"],"x_google_ignoreList":[0],"mappings":";AAOA,SAAS,EAAa,GAAQ;AAC7B,QAAO"}
@@ -1,7 +1,7 @@
1
1
  import { I_Serializer } from '../../util/serializer/index.js';
2
2
  /**
3
3
  * React hook that provides persistent storage functionality with automatic serialization.
4
- * This hook manages state that persists across browser sessions using localForage,
4
+ * This hook manages state that persists across browser sessions using localStorage,
5
5
  * with automatic serialization/deserialization of complex data types. It provides
6
6
  * a React-friendly interface for storage operations with proper error handling.
7
7
  *