@cyberskill/shared 3.12.0 → 3.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/commitlint/index.d.ts +5 -1
- package/dist/{src/config → config}/config.type.d.ts +1 -1
- package/dist/{src/config → config}/config.util.d.ts +1 -1
- package/dist/{src/config → config}/env/env.util.d.ts +5 -0
- package/dist/config/env/env.util.js +20 -16
- package/dist/config/env/env.util.js.map +1 -1
- package/dist/config/env/index.d.ts +3 -1
- package/dist/config/env/index.js +2 -2
- package/dist/config/eslint/index.d.ts +1198 -1
- package/dist/config/graphql-codegen/index.d.ts +2 -1
- package/dist/config/index.d.ts +2 -1
- package/dist/config/lint-staged/index.d.ts +5 -1
- package/dist/config/storybook/index.d.ts +2 -1
- package/dist/config/vitest/index.d.ts +3 -1
- package/dist/config/vitest/vitest.e2e.d.ts +20 -1
- package/dist/config/vitest/vitest.e2e.js +4 -4
- package/dist/config/vitest/vitest.e2e.js.map +1 -1
- package/dist/config/vitest/vitest.unit.d.ts +22 -1
- package/dist/config/vitest/vitest.unit.js +5 -5
- package/dist/config/vitest/vitest.unit.js.map +1 -1
- package/dist/config/vitest/vitest.unit.setup.js +10 -0
- package/dist/config/vitest/vitest.unit.setup.js.map +1 -0
- package/dist/constant/index.d.ts +5 -1
- package/dist/node/apollo-server/apollo-server.type.d.ts +20 -0
- package/dist/{src/node → node}/apollo-server/apollo-server.util.d.ts +1 -0
- package/dist/node/apollo-server/apollo-server.util.js +40 -16
- package/dist/node/apollo-server/apollo-server.util.js.map +1 -1
- package/dist/node/apollo-server/index.d.ts +2 -1
- package/dist/node/cli/index.d.ts +2 -1
- package/dist/node/cli/index.js +26 -28
- package/dist/node/cli/index.js.map +1 -1
- package/dist/{src/node → node}/command/command.util.d.ts +5 -0
- package/dist/node/command/command.util.js +49 -48
- package/dist/node/command/command.util.js.map +1 -1
- package/dist/node/command/index.d.ts +2 -1
- package/dist/node/command/index.js +2 -2
- package/dist/{src/node → node}/express/express.type.d.ts +11 -0
- package/dist/{src/node → node}/express/express.util.d.ts +34 -6
- package/dist/node/express/express.util.js +81 -56
- package/dist/node/express/express.util.js.map +1 -1
- package/dist/node/express/index.d.ts +2 -1
- package/dist/node/express/index.js +2 -2
- package/dist/node/fs/index.d.ts +2 -1
- package/dist/node/log/index.d.ts +2 -1
- package/dist/node/log/log.type.d.ts +46 -0
- package/dist/node/log/log.type.js.map +1 -1
- package/dist/{src/node → node}/log/log.util.d.ts +1 -1
- package/dist/node/log/log.util.js +25 -11
- package/dist/node/log/log.util.js.map +1 -1
- package/dist/node/mongo/index.d.ts +7 -1
- package/dist/node/mongo/index.js +7 -8
- package/dist/{src/node → node}/mongo/mongo.constant.d.ts +5 -0
- package/dist/node/mongo/mongo.constant.js +2 -2
- package/dist/node/mongo/mongo.constant.js.map +1 -1
- package/dist/{src/node → node}/mongo/mongo.controller.helpers.d.ts +1 -1
- package/dist/{src/node → node}/mongo/mongo.controller.mongoose.d.ts +4 -1
- package/dist/node/mongo/mongo.controller.mongoose.js +41 -55
- package/dist/node/mongo/mongo.controller.mongoose.js.map +1 -1
- package/dist/{src/node → node}/mongo/mongo.controller.native.d.ts +30 -3
- package/dist/node/mongo/mongo.controller.native.js +31 -14
- package/dist/node/mongo/mongo.controller.native.js.map +1 -1
- package/dist/{src/node → node}/mongo/mongo.controller.type.d.ts +1 -1
- package/dist/{src/node → node}/mongo/mongo.type.d.ts +3 -1
- package/dist/{src/node → node}/mongo/mongo.util.d.ts +1 -0
- package/dist/node/mongo/mongo.util.js +38 -17
- package/dist/node/mongo/mongo.util.js.map +1 -1
- package/dist/node/package/index.d.ts +2 -1
- package/dist/{src/node → node}/package/package.util.d.ts +1 -1
- package/dist/node/package/package.util.js +47 -47
- package/dist/node/path/index.d.ts +2 -1
- package/dist/node/path/index.js +2 -2
- package/dist/{src/node → node}/path/path.constant.d.ts +4 -0
- package/dist/node/path/path.constant.js +75 -72
- package/dist/node/path/path.constant.js.map +1 -1
- package/dist/node/storage/index.d.ts +3 -1
- package/dist/{src/node → node}/storage/storage.util.d.ts +50 -1
- package/dist/node/storage/storage.util.js +79 -54
- package/dist/node/storage/storage.util.js.map +1 -1
- package/dist/node/upload/index.d.ts +3 -1
- package/dist/{src/node → node}/upload/upload.type.d.ts +2 -0
- package/dist/node/upload/upload.type.js.map +1 -1
- package/dist/{src/node → node}/upload/upload.util.d.ts +2 -1
- package/dist/node/upload/upload.util.js +62 -52
- package/dist/node/upload/upload.util.js.map +1 -1
- package/dist/node/ws/index.d.ts +2 -1
- package/dist/{src/node → node}/ws/ws.util.d.ts +7 -0
- package/dist/node/ws/ws.util.js +20 -19
- package/dist/node/ws/ws.util.js.map +1 -1
- package/dist/react/apollo-client/apollo-client.component.js.map +1 -1
- package/dist/{src/react → react}/apollo-client/apollo-client.type.d.ts +3 -1
- package/dist/react/apollo-client/apollo-client.util.js +6 -6
- package/dist/react/apollo-client/apollo-client.util.js.map +1 -1
- package/dist/react/apollo-client/index.d.ts +9 -1
- package/dist/react/apollo-client/links/index.d.ts +1 -1
- package/dist/react/apollo-client-nextjs/apollo-client-nextjs.rsc.d.ts +16 -1
- package/dist/react/apollo-client-nextjs/index.d.ts +2 -1
- package/dist/react/apollo-error/apollo-error.component.js +1 -1
- package/dist/react/apollo-error/apollo-error.component.js.map +1 -1
- package/dist/react/apollo-error/apollo-error.util.js.map +1 -1
- package/dist/react/apollo-error/index.d.ts +6 -1
- package/dist/react/i18next/i18next.server.d.ts +17 -0
- package/dist/react/i18next/i18next.server.js +9 -0
- package/dist/react/i18next/i18next.server.js.map +1 -0
- package/dist/react/i18next/index.d.ts +2 -1
- package/dist/react/loading/index.d.ts +5 -1
- package/dist/{src/react → react}/loading/loading.provider.d.ts +1 -1
- package/dist/react/log/index.d.ts +2 -1
- package/dist/react/log/log.type.d.ts +1 -0
- package/dist/{src/react → react}/log/log.util.d.ts +1 -1
- package/dist/react/next-intl/index.d.ts +6 -1
- package/dist/{src/react → react}/next-intl/next-intl.hoc.d.ts +5 -9
- package/dist/react/next-intl/next-intl.hoc.js +14 -10
- package/dist/react/next-intl/next-intl.hoc.js.map +1 -1
- package/dist/react/next-intl/next-intl.server.d.ts +10 -0
- package/dist/react/next-intl/next-intl.server.js +7 -0
- package/dist/react/next-intl/next-intl.server.js.map +1 -0
- package/dist/{src/react → react}/next-intl/next-intl.type.d.ts +1 -1
- package/dist/react/storage/index.d.ts +2 -1
- package/dist/{src/react → react}/storage/storage.hook.d.ts +1 -1
- package/dist/{src/react → react}/storage/storage.util.d.ts +34 -1
- package/dist/react/storage/storage.util.js +30 -5
- package/dist/react/storage/storage.util.js.map +1 -1
- package/dist/react/toast/index.d.ts +1 -1
- package/dist/react/userback/index.d.ts +2 -1
- package/dist/react/userback/userback.component.js.map +1 -1
- package/dist/{src/typescript → typescript}/common.type.d.ts +4 -0
- package/dist/typescript/common.type.js +2 -2
- package/dist/typescript/common.type.js.map +1 -1
- package/dist/typescript/index.d.ts +5 -1
- package/dist/typescript/index.js +2 -2
- package/dist/util/common/index.d.ts +5 -1
- package/dist/util/index.d.ts +9 -1
- package/dist/util/log/index.d.ts +2 -1
- package/dist/{src/util → util}/log/log.util.d.ts +1 -1
- package/dist/util/object/index.d.ts +4 -1
- package/dist/util/object/object.util.js +29 -18
- package/dist/util/object/object.util.js.map +1 -1
- package/dist/util/serializer/index.d.ts +2 -1
- package/dist/{src/util → util}/serializer/serializer.util.d.ts +8 -0
- package/dist/util/serializer/serializer.util.js +51 -64
- package/dist/util/serializer/serializer.util.js.map +1 -1
- package/dist/util/storage/storage-envelope.d.ts +25 -0
- package/dist/util/storage/storage-envelope.js +18 -0
- package/dist/util/storage/storage-envelope.js.map +1 -0
- package/dist/util/string/index.d.ts +5 -1
- package/dist/util/validate/index.d.ts +4 -1
- package/package.json +33 -12
- package/dist/node/mongo/mongo.type.js +0 -8
- package/dist/node/mongo/mongo.type.js.map +0 -1
- package/dist/node_modules/.pnpm/vitest@4.1.2_@types_node@25.5.0_jsdom@29.0.1_@noble_hashes@1.8.0__vite@8.0.3_@types_nod_0827261ede788764a5d99ac6bdf44bde/node_modules/vitest/dist/config.js +0 -8
- package/dist/node_modules/.pnpm/vitest@4.1.2_@types_node@25.5.0_jsdom@29.0.1_@noble_hashes@1.8.0__vite@8.0.3_@types_nod_0827261ede788764a5d99ac6bdf44bde/node_modules/vitest/dist/config.js.map +0 -1
- package/dist/src/config/commitlint/index.d.ts +0 -5
- package/dist/src/config/env/index.d.ts +0 -3
- package/dist/src/config/eslint/index.d.ts +0 -1198
- package/dist/src/config/graphql-codegen/index.d.ts +0 -2
- package/dist/src/config/index.d.ts +0 -2
- package/dist/src/config/lint-staged/index.d.ts +0 -5
- package/dist/src/config/storybook/index.d.ts +0 -2
- package/dist/src/config/vitest/index.d.ts +0 -3
- package/dist/src/config/vitest/vitest.e2e.d.ts +0 -20
- package/dist/src/config/vitest/vitest.unit.d.ts +0 -22
- package/dist/src/constant/index.d.ts +0 -5
- package/dist/src/node/apollo-server/apollo-server.type.d.ts +0 -8
- package/dist/src/node/apollo-server/index.d.ts +0 -2
- package/dist/src/node/cli/index.d.ts +0 -2
- package/dist/src/node/command/index.d.ts +0 -2
- package/dist/src/node/express/index.d.ts +0 -2
- package/dist/src/node/fs/index.d.ts +0 -2
- package/dist/src/node/log/index.d.ts +0 -2
- package/dist/src/node/log/log.type.d.ts +0 -29
- package/dist/src/node/mongo/index.d.ts +0 -6
- package/dist/src/node/package/index.d.ts +0 -2
- package/dist/src/node/path/index.d.ts +0 -2
- package/dist/src/node/storage/index.d.ts +0 -3
- package/dist/src/node/upload/index.d.ts +0 -3
- package/dist/src/node/ws/index.d.ts +0 -2
- package/dist/src/react/apollo-client/index.d.ts +0 -9
- package/dist/src/react/apollo-client/links/index.d.ts +0 -1
- package/dist/src/react/apollo-client-nextjs/apollo-client-nextjs.rsc.d.ts +0 -16
- package/dist/src/react/apollo-client-nextjs/index.d.ts +0 -2
- package/dist/src/react/apollo-error/index.d.ts +0 -6
- package/dist/src/react/i18next/index.d.ts +0 -2
- package/dist/src/react/loading/index.d.ts +0 -5
- package/dist/src/react/log/index.d.ts +0 -2
- package/dist/src/react/log/log.type.d.ts +0 -1
- package/dist/src/react/next-intl/index.d.ts +0 -6
- package/dist/src/react/storage/index.d.ts +0 -2
- package/dist/src/react/toast/index.d.ts +0 -1
- package/dist/src/react/userback/index.d.ts +0 -2
- package/dist/src/typescript/index.d.ts +0 -5
- package/dist/src/util/common/index.d.ts +0 -5
- package/dist/src/util/index.d.ts +0 -9
- package/dist/src/util/log/index.d.ts +0 -2
- package/dist/src/util/object/index.d.ts +0 -4
- package/dist/src/util/serializer/index.d.ts +0 -2
- package/dist/src/util/string/index.d.ts +0 -5
- package/dist/src/util/validate/index.d.ts +0 -4
- /package/dist/{src/config → config}/env/env.constant.d.ts +0 -0
- /package/dist/{src/config → config}/env/env.type.d.ts +0 -0
- /package/dist/{src/config → config}/graphql-codegen/graphql-codegen.type.d.ts +0 -0
- /package/dist/{src/config → config}/graphql-codegen/graphql-codegen.util.d.ts +0 -0
- /package/dist/{src/config → config}/storybook/storybook.main.d.ts +0 -0
- /package/dist/{src/config → config}/storybook/storybook.preview.d.ts +0 -0
- /package/dist/{src/config → config}/vitest/vitest.unit.setup.d.ts +0 -0
- /package/dist/{src/constant → constant}/common.d.ts +0 -0
- /package/dist/{src/constant → constant}/response-status.d.ts +0 -0
- /package/dist/{src/node → node}/command/command.type.d.ts +0 -0
- /package/dist/{src/node → node}/fs/fs.type.d.ts +0 -0
- /package/dist/{src/node → node}/fs/fs.util.d.ts +0 -0
- /package/dist/{src/node → node}/mongo/mongo.controller.d.ts +0 -0
- /package/dist/{src/node → node}/mongo/mongo.dynamic-populate.d.ts +0 -0
- /package/dist/{src/node → node}/mongo/mongo.internal-types.d.ts +0 -0
- /package/dist/{src/node → node}/mongo/mongo.populate.d.ts +0 -0
- /package/dist/{src/node → node}/package/package.type.d.ts +0 -0
- /package/dist/{src/node → node}/path/path.util.d.ts +0 -0
- /package/dist/{src/node → node}/storage/storage.constant.d.ts +0 -0
- /package/dist/{src/node → node}/storage/storage.type.d.ts +0 -0
- /package/dist/{src/node → node}/upload/upload.constant.d.ts +0 -0
- /package/dist/{src/node → node}/ws/ws.type.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-client/apollo-client.component.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-client/apollo-client.constant.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-client/apollo-client.context.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-client/apollo-client.hook.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-client/apollo-client.util.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-client/links/upload.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-client-nextjs/apollo-client-nextjs.component.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-client-nextjs/apollo-client-nextjs.util.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-error/apollo-error.component.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-error/apollo-error.context.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-error/apollo-error.hook.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-error/apollo-error.provider.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-error/apollo-error.type.d.ts +0 -0
- /package/dist/{src/react → react}/apollo-error/apollo-error.util.d.ts +0 -0
- /package/dist/{src/react → react}/i18next/i18next.hook.d.ts +0 -0
- /package/dist/{src/react → react}/i18next/i18next.util.d.ts +0 -0
- /package/dist/{src/react → react}/loading/loading.component.d.ts +0 -0
- /package/dist/{src/react → react}/loading/loading.context.d.ts +0 -0
- /package/dist/{src/react → react}/loading/loading.hook.d.ts +0 -0
- /package/dist/{src/react → react}/loading/loading.type.d.ts +0 -0
- /package/dist/{src/react → react}/next-intl/next-intl.constant.d.ts +0 -0
- /package/dist/{src/react → react}/next-intl/next-intl.context.d.ts +0 -0
- /package/dist/{src/react → react}/next-intl/next-intl.hook.d.ts +0 -0
- /package/dist/{src/react → react}/next-intl/next-intl.provider.d.ts +0 -0
- /package/dist/{src/react → react}/userback/userback.component.d.ts +0 -0
- /package/dist/{src/react → react}/userback/userback.type.d.ts +0 -0
- /package/dist/{src/typescript → typescript}/react.type.d.ts +0 -0
- /package/dist/{src/util → util}/common/common.type.d.ts +0 -0
- /package/dist/{src/util → util}/common/common.util.d.ts +0 -0
- /package/dist/{src/util → util}/log/log.type.d.ts +0 -0
- /package/dist/{src/util → util}/object/object.util.d.ts +0 -0
- /package/dist/{src/util → util}/serializer/serializer.type.d.ts +0 -0
- /package/dist/{src/util → util}/string/string.type.d.ts +0 -0
- /package/dist/{src/util → util}/string/string.util.d.ts +0 -0
- /package/dist/{src/util → util}/validate/validate.util.d.ts +0 -0
|
@@ -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 * @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;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pF,MAAI,CAAC,EACD,QAAO,EAAE;EAGb,IAAI,IAAY,EAAE,GAAG,GAAQ;AAE7B,MAAI,CAAC,KAAU,EAAO,WAAW,EAC7B,QAAO;AAKX,OAAK,IAAM,KAAS,GAAQ;GACxB,IAAM,IAAO,EAAM,UAAU,CAAC,MAAM,IAAI,EAClC,IAAQ,EAAe,GAAW,EAAK;AAE7C,OAAI,OAAO,KAAU,YAAY,EAAM,SAAS,KAAK,EAAM,UAAU,KAAwB;IACzF,IAAM,IAAa;KACf,QAAQ,KAAK,EAAkB,EAAM,CAAC;KACtC,UAAU;KACb;AAED,QAAY,EAAe,GAAW,GAAM,EAAW;;;AAI/D,SAAO;;CAQX,iBAA+C,GAA4E;AACvH,SAAO,GAAQ,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
|
+
{"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 * 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 health: (mongooseInstance: typeof mongooseRaw) => Record<string, unknown>;\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 (model as I_ExtendedModel<T> & { _virtualConfigs: typeof virtuals })._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]: { $eq: 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 * @since 3.13.0\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 batchSize = 1000;\n let skip = 0;\n let isComplete = false;\n\n const allExistingRecords: T_WithId<T>[] = [];\n\n while (!isComplete) {\n const pageResult = await controller.findAll(filter, { skip, limit: batchSize });\n\n if (!pageResult.success) {\n throw new Error(`Failed to query existing records on skip ${skip}: ${pageResult.message}`);\n }\n\n allExistingRecords.push(...pageResult.result);\n\n if (pageResult.truncated && pageResult.result.length === batchSize) {\n skip += batchSize;\n }\n else {\n isComplete = true;\n }\n }\n\n const filteredRecords = recordsToCheck.filter(newRecord =>\n !allExistingRecords.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 * @since 3.13.0\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 batchSize = 1000;\n let skip = 0;\n let isComplete = false;\n\n const allExistingRecords: T_WithId<T>[] = [];\n\n while (!isComplete) {\n const pageResult = await controller.findAll(filter, { skip, limit: batchSize });\n\n if (!pageResult.success) {\n throw new Error(`Failed to query existing records on skip ${skip}: ${pageResult.message}`);\n }\n\n allExistingRecords.push(...pageResult.result);\n\n if (pageResult.truncated && pageResult.result.length === batchSize) {\n skip += batchSize;\n }\n else {\n isComplete = true;\n }\n }\n\n const foundRecords = allExistingRecords.filter((existingRecord: T_WithId<T>) =>\n recordsToCheck.some((newRecord: T) =>\n filterFn(existingRecord, newRecord),\n ),\n );\n\n return foundRecords;\n },\n\n /**\n * Retrieves health and connection pool statistics for the Mongoose connection.\n * This utility helps monitor database connection health and observability.\n *\n * @param mongooseInstance - The Mongoose instance to check.\n * @returns An object containing connection health statistics.\n */\n health(mongooseInstance: typeof mongooseRaw): Record<string, unknown> {\n const conn = mongooseInstance.connection;\n\n return {\n readyState: conn.readyState,\n host: conn.host,\n name: conn.name,\n models: Object.keys(mongooseInstance.models).length,\n };\n },\n};\n\nexport { applyNestedPopulate } from './mongo.populate.js';\n"],"mappings":";;;;;;;;;;AAsBA,SAAgB,EAAuB,GAA2B;AAK9D,QAJI,MAAc,EAAU,aAAa,GAC9B,EAAU,OAAO,EAAE,CAAC,aAAa,GAAG,EAAU,MAAM,EAAE,CAAC,aAAa,GAGxE;;AAmCX,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,O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,GAFA,EAAmB,KAAK,GAAG,EAAW,OAAO,EAEzC,EAAW,aAAa,EAAW,OAAO,WAAW,IACrD,KAAQ,IAGR,IAAa;;AAUrB,SANqB,EAAmB,QAAQ,MAC5C,EAAe,MAAM,MACjB,EAAS,GAAgB,EAAU,CACtC,CACJ;;CAYL,OAAO,GAA+D;EAClE,IAAM,IAAO,EAAiB;AAE9B,SAAO;GACH,YAAY,EAAK;GACjB,MAAM,EAAK;GACX,MAAM,EAAK;GACX,QAAQ,OAAO,KAAK,EAAiB,OAAO,CAAC;GAChD;;CAER"}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export
|
|
1
|
+
export * from './package.type.js';
|
|
2
|
+
export * from './package.util.js';
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { getEnv as e } from "../../config/env/env.util.js";
|
|
2
|
+
import { catchError as t, log as n } from "../log/log.util.js";
|
|
3
|
+
import { pathExistsSync as r, readJsonSync as i, writeFileSync as a } from "../fs/fs.util.js";
|
|
4
4
|
import { E_PackageType as o } from "./package.type.js";
|
|
5
5
|
import { runCommand as s } from "../command/command.util.js";
|
|
6
6
|
import { join as c } from "../path/path.util.js";
|
|
7
7
|
import { NODE_MODULES as l, PACKAGE_JSON as u, PATH as d, command as f } from "../path/path.constant.js";
|
|
8
8
|
//#region src/node/package/package.util.ts
|
|
9
|
-
var p =
|
|
9
|
+
var p = e();
|
|
10
10
|
async function m(e) {
|
|
11
11
|
try {
|
|
12
12
|
let t = await fetch(`https://registry.npmjs.org/${e}/latest`);
|
|
@@ -17,20 +17,20 @@ async function m(e) {
|
|
|
17
17
|
result: n
|
|
18
18
|
};
|
|
19
19
|
} catch (e) {
|
|
20
|
-
return
|
|
20
|
+
return t(e);
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
|
-
async function h(
|
|
23
|
+
async function h(e) {
|
|
24
24
|
try {
|
|
25
|
-
if (!
|
|
26
|
-
if (
|
|
27
|
-
let e =
|
|
25
|
+
if (!e) {
|
|
26
|
+
if (r(d.PACKAGE_JSON)) {
|
|
27
|
+
let e = i(d.PACKAGE_JSON), { name: t = "", version: n = "" } = e;
|
|
28
28
|
return {
|
|
29
29
|
success: !0,
|
|
30
30
|
result: {
|
|
31
|
-
name:
|
|
32
|
-
currentVersion:
|
|
33
|
-
latestVersion:
|
|
31
|
+
name: t,
|
|
32
|
+
currentVersion: n,
|
|
33
|
+
latestVersion: n,
|
|
34
34
|
isCurrentProject: !0,
|
|
35
35
|
isInstalled: !0,
|
|
36
36
|
isUpToDate: !0,
|
|
@@ -57,42 +57,42 @@ async function h(n) {
|
|
|
57
57
|
}
|
|
58
58
|
};
|
|
59
59
|
}
|
|
60
|
-
if (!
|
|
60
|
+
if (!r(d.PACKAGE_JSON)) return {
|
|
61
61
|
success: !0,
|
|
62
62
|
result: {
|
|
63
|
-
name:
|
|
63
|
+
name: e.name,
|
|
64
64
|
currentVersion: "",
|
|
65
65
|
latestVersion: "",
|
|
66
66
|
isCurrentProject: !1,
|
|
67
67
|
isInstalled: !1,
|
|
68
68
|
isUpToDate: !1,
|
|
69
|
-
isDependency:
|
|
70
|
-
isDevDependency:
|
|
69
|
+
isDependency: e.type === o.DEPENDENCY,
|
|
70
|
+
isDevDependency: e.type === o.DEV_DEPENDENCY,
|
|
71
71
|
installedPath: "",
|
|
72
72
|
file: {}
|
|
73
73
|
}
|
|
74
74
|
};
|
|
75
|
-
let
|
|
76
|
-
if (
|
|
75
|
+
let t = i(d.PACKAGE_JSON), { name: n, version: a = "", dependencies: s = {}, devDependencies: f = {} } = t;
|
|
76
|
+
if (e.name === n) return {
|
|
77
77
|
success: !0,
|
|
78
78
|
result: {
|
|
79
|
-
name:
|
|
79
|
+
name: n,
|
|
80
80
|
currentVersion: a,
|
|
81
81
|
latestVersion: a,
|
|
82
82
|
isCurrentProject: !0,
|
|
83
83
|
isInstalled: !0,
|
|
84
84
|
isUpToDate: !0,
|
|
85
|
-
isDependency:
|
|
86
|
-
isDevDependency:
|
|
85
|
+
isDependency: e.type === o.DEPENDENCY,
|
|
86
|
+
isDevDependency: e.type === o.DEV_DEPENDENCY,
|
|
87
87
|
installedPath: d.PACKAGE_JSON,
|
|
88
|
-
file:
|
|
88
|
+
file: t
|
|
89
89
|
}
|
|
90
90
|
};
|
|
91
|
-
let h =
|
|
91
|
+
let h = e.name in s, g = e.name in f, _ = await m(e.name);
|
|
92
92
|
if (!_.success) return {
|
|
93
93
|
success: !0,
|
|
94
94
|
result: {
|
|
95
|
-
name:
|
|
95
|
+
name: e.name,
|
|
96
96
|
currentVersion: "",
|
|
97
97
|
latestVersion: "",
|
|
98
98
|
isCurrentProject: !1,
|
|
@@ -107,23 +107,23 @@ async function h(n) {
|
|
|
107
107
|
if (!h && !g) return {
|
|
108
108
|
success: !0,
|
|
109
109
|
result: {
|
|
110
|
-
name:
|
|
110
|
+
name: e.name,
|
|
111
111
|
currentVersion: "",
|
|
112
112
|
latestVersion: _.result,
|
|
113
113
|
isCurrentProject: !1,
|
|
114
114
|
isInstalled: !1,
|
|
115
115
|
isUpToDate: !1,
|
|
116
|
-
isDependency:
|
|
117
|
-
isDevDependency:
|
|
116
|
+
isDependency: e.type === o.DEPENDENCY,
|
|
117
|
+
isDevDependency: e.type === o.DEV_DEPENDENCY,
|
|
118
118
|
installedPath: "",
|
|
119
119
|
file: {}
|
|
120
120
|
}
|
|
121
121
|
};
|
|
122
|
-
let v = s[
|
|
123
|
-
if (!
|
|
122
|
+
let v = s[e.name] ?? f[e.name] ?? "", y = c(p.CWD, l, e.name, u);
|
|
123
|
+
if (!r(y)) return {
|
|
124
124
|
success: !0,
|
|
125
125
|
result: {
|
|
126
|
-
name:
|
|
126
|
+
name: e.name,
|
|
127
127
|
currentVersion: "",
|
|
128
128
|
latestVersion: _.result,
|
|
129
129
|
isCurrentProject: !1,
|
|
@@ -135,11 +135,11 @@ async function h(n) {
|
|
|
135
135
|
file: {}
|
|
136
136
|
}
|
|
137
137
|
};
|
|
138
|
-
let b =
|
|
138
|
+
let b = i(y), { version: x = "" } = b;
|
|
139
139
|
return v === x ? {
|
|
140
140
|
success: !0,
|
|
141
141
|
result: {
|
|
142
|
-
name:
|
|
142
|
+
name: e.name,
|
|
143
143
|
currentVersion: v,
|
|
144
144
|
latestVersion: _.result,
|
|
145
145
|
isCurrentProject: !1,
|
|
@@ -153,7 +153,7 @@ async function h(n) {
|
|
|
153
153
|
} : {
|
|
154
154
|
success: !0,
|
|
155
155
|
result: {
|
|
156
|
-
name:
|
|
156
|
+
name: e.name,
|
|
157
157
|
currentVersion: x || v,
|
|
158
158
|
latestVersion: _.result,
|
|
159
159
|
isCurrentProject: !1,
|
|
@@ -166,15 +166,15 @@ async function h(n) {
|
|
|
166
166
|
}
|
|
167
167
|
};
|
|
168
168
|
} catch (e) {
|
|
169
|
-
return
|
|
169
|
+
return t(e);
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
172
|
async function g(e) {
|
|
173
173
|
try {
|
|
174
|
-
let
|
|
175
|
-
e.isDependency ?
|
|
174
|
+
let t = i(d.PACKAGE_JSON), r = t.dependencies ?? {}, o = t.devDependencies ?? {};
|
|
175
|
+
e.isDependency ? r[e.name] = e.latestVersion : e.isDevDependency && (o[e.name] = e.latestVersion), a(d.PACKAGE_JSON, JSON.stringify(t, null, 4)), n.info(`Updated "${e.name}" to version ${e.latestVersion}`);
|
|
176
176
|
} catch (e) {
|
|
177
|
-
|
|
177
|
+
t(e);
|
|
178
178
|
}
|
|
179
179
|
}
|
|
180
180
|
async function _() {
|
|
@@ -184,35 +184,35 @@ async function _() {
|
|
|
184
184
|
await s(`Installing dependencies (standard) using: ${e}`, e);
|
|
185
185
|
return;
|
|
186
186
|
} catch (e) {
|
|
187
|
-
|
|
187
|
+
t(e);
|
|
188
188
|
}
|
|
189
189
|
try {
|
|
190
190
|
let e = await f.pnpmInstallLegacy();
|
|
191
191
|
await s(`Retrying with legacy peer dependencies using: ${e}`, e);
|
|
192
192
|
return;
|
|
193
193
|
} catch (e) {
|
|
194
|
-
|
|
194
|
+
t(e);
|
|
195
195
|
}
|
|
196
196
|
try {
|
|
197
197
|
let e = await f.pnpmInstallForce();
|
|
198
198
|
await s(`Retrying with force install using: ${e}`, e);
|
|
199
199
|
} catch (e) {
|
|
200
|
-
|
|
200
|
+
t(e);
|
|
201
201
|
}
|
|
202
202
|
} catch (e) {
|
|
203
|
-
|
|
203
|
+
t(e);
|
|
204
204
|
}
|
|
205
205
|
}
|
|
206
|
-
async function v(
|
|
206
|
+
async function v(e, i) {
|
|
207
207
|
try {
|
|
208
|
-
if (!
|
|
209
|
-
|
|
208
|
+
if (!r(d.PACKAGE_JSON)) {
|
|
209
|
+
n.error("package.json not found. Aborting setup.");
|
|
210
210
|
return;
|
|
211
211
|
}
|
|
212
|
-
let
|
|
213
|
-
|
|
212
|
+
let t = (await Promise.all(e.map(h))).filter((e) => e.success && !!e.result && !e.result.isCurrentProject).map((e) => e.result), a = t.filter((e) => !e.isInstalled), o = t.filter((e) => !e.isUpToDate), c = [];
|
|
213
|
+
i?.install && a.length > 0 && c.push(...a.map(g)), i?.update && o.length > 0 && c.push(...o.map(g)), c.length > 0 && (await Promise.all(c), await _(), await s("Running ESLint with auto-fix", await f.eslintFix())), await i?.callback?.();
|
|
214
214
|
} catch (e) {
|
|
215
|
-
|
|
215
|
+
t(e);
|
|
216
216
|
}
|
|
217
217
|
}
|
|
218
218
|
//#endregion
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export
|
|
1
|
+
export * from './path.constant.js';
|
|
2
|
+
export * from './path.util.js';
|
package/dist/node/path/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { dirname as e, join as t, path as n, resolve as r, resolveWorkingPath as i } from "./path.util.js";
|
|
2
|
-
import { AG_KIT_PACKAGE_NAME as a, BUILD_DIRECTORY as o, COMMIT_LINT_CLI as s, COMMIT_LINT_CONVENTIONAL_CONFIG_PACKAGE_NAME as c, COMMIT_LINT_PACKAGE_NAME as l, CYBERSKILL_CLI as u, CYBERSKILL_CLI_PATH as d, CYBERSKILL_DIRECTORY as f, CYBERSKILL_PACKAGE_NAME as p, DOT_AGENT as m, ESLINT_CLI as h, ESLINT_INSPECT_CLI as g, ESLINT_INSPECT_PACKAGE_NAME as _, ESLINT_PACKAGE_NAME as v, GIT_CLI as y, GIT_COMMIT_EDITMSG as b, GIT_EXCLUDE as x, GIT_HOOK as S, GIT_IGNORE as C, LINT_STAGED_CLI as w, LINT_STAGED_PACKAGE_NAME as T, MIGRATE_MONGO_CLI as E, MIGRATE_MONGO_CONFIG as D, MIGRATE_MONGO_PACKAGE_NAME as O, NODE_MODULES as k, NODE_MODULES_INSPECT_CLI as A, NODE_MODULES_INSPECT_PACKAGE_NAME as j, PACKAGE_JSON as M, PACKAGE_LOCK_JSON as N, PATH as P, PNPM_CLI as F, PNPM_EXEC_CLI as I, PNPM_LOCK_YAML as L, PUBLIC_DIRECTORY as R, SIMPLE_GIT_HOOKS_PACKAGE_NAME as z, SIMPLE_GIT_HOOK_CLI as B, SIMPLE_GIT_HOOK_JSON as V, STORYBOOK_CLI as H, STORYBOOK_PACKAGE_NAME as U, TSCONFIG_JSON as W, TSC_CLI as G, TSC_PACKAGE_NAME as K, TSX_CLI as q, VITEST_CLI as J, VITEST_PACKAGE_NAME as Y, WORKING_DIRECTORY as X, command as Z, createGitHooksConfig as Q, getCyberskillDirectory as
|
|
3
|
-
export { a as AG_KIT_PACKAGE_NAME, o as BUILD_DIRECTORY, s as COMMIT_LINT_CLI, c as COMMIT_LINT_CONVENTIONAL_CONFIG_PACKAGE_NAME, l as COMMIT_LINT_PACKAGE_NAME, u as CYBERSKILL_CLI, d as CYBERSKILL_CLI_PATH, f as CYBERSKILL_DIRECTORY, p as CYBERSKILL_PACKAGE_NAME, m as DOT_AGENT, h as ESLINT_CLI, g as ESLINT_INSPECT_CLI, _ as ESLINT_INSPECT_PACKAGE_NAME, v as ESLINT_PACKAGE_NAME, y as GIT_CLI, b as GIT_COMMIT_EDITMSG, x as GIT_EXCLUDE, S as GIT_HOOK, C as GIT_IGNORE, w as LINT_STAGED_CLI, T as LINT_STAGED_PACKAGE_NAME, E as MIGRATE_MONGO_CLI, D as MIGRATE_MONGO_CONFIG, O as MIGRATE_MONGO_PACKAGE_NAME, k as NODE_MODULES, A as NODE_MODULES_INSPECT_CLI, j as NODE_MODULES_INSPECT_PACKAGE_NAME, M as PACKAGE_JSON, N as PACKAGE_LOCK_JSON, P as PATH, F as PNPM_CLI, I as PNPM_EXEC_CLI, L as PNPM_LOCK_YAML, R as PUBLIC_DIRECTORY, z as SIMPLE_GIT_HOOKS_PACKAGE_NAME, B as SIMPLE_GIT_HOOK_CLI, V as SIMPLE_GIT_HOOK_JSON, H as STORYBOOK_CLI, U as STORYBOOK_PACKAGE_NAME, W as TSCONFIG_JSON, G as TSC_CLI, K as TSC_PACKAGE_NAME, q as TSX_CLI, J as VITEST_CLI, Y as VITEST_PACKAGE_NAME, X as WORKING_DIRECTORY, Z as command, Q as createGitHooksConfig, e as dirname, $ as getCyberskillDirectory, t as join, n as path, r as resolve, i as resolveWorkingPath };
|
|
2
|
+
import { AG_KIT_PACKAGE_NAME as a, BUILD_DIRECTORY as o, COMMIT_LINT_CLI as s, COMMIT_LINT_CONVENTIONAL_CONFIG_PACKAGE_NAME as c, COMMIT_LINT_PACKAGE_NAME as l, CYBERSKILL_CLI as u, CYBERSKILL_CLI_PATH as d, CYBERSKILL_DIRECTORY as f, CYBERSKILL_PACKAGE_NAME as p, DOT_AGENT as m, ESLINT_CLI as h, ESLINT_INSPECT_CLI as g, ESLINT_INSPECT_PACKAGE_NAME as _, ESLINT_PACKAGE_NAME as v, GIT_CLI as y, GIT_COMMIT_EDITMSG as b, GIT_EXCLUDE as x, GIT_HOOK as S, GIT_IGNORE as C, LINT_STAGED_CLI as w, LINT_STAGED_PACKAGE_NAME as T, MIGRATE_MONGO_CLI as E, MIGRATE_MONGO_CONFIG as D, MIGRATE_MONGO_PACKAGE_NAME as O, NODE_MODULES as k, NODE_MODULES_INSPECT_CLI as A, NODE_MODULES_INSPECT_PACKAGE_NAME as j, PACKAGE_JSON as M, PACKAGE_LOCK_JSON as N, PATH as P, PNPM_CLI as F, PNPM_EXEC_CLI as I, PNPM_LOCK_YAML as L, PUBLIC_DIRECTORY as R, SIMPLE_GIT_HOOKS_PACKAGE_NAME as z, SIMPLE_GIT_HOOK_CLI as B, SIMPLE_GIT_HOOK_JSON as V, STORYBOOK_CLI as H, STORYBOOK_PACKAGE_NAME as U, TSCONFIG_JSON as W, TSC_CLI as G, TSC_PACKAGE_NAME as K, TSX_CLI as q, VITEST_CLI as J, VITEST_PACKAGE_NAME as Y, WORKING_DIRECTORY as X, command as Z, createGitHooksConfig as Q, getCyberskillDirectory as $, resetCyberskillDirCacheForTesting as ee } from "./path.constant.js";
|
|
3
|
+
export { a as AG_KIT_PACKAGE_NAME, o as BUILD_DIRECTORY, s as COMMIT_LINT_CLI, c as COMMIT_LINT_CONVENTIONAL_CONFIG_PACKAGE_NAME, l as COMMIT_LINT_PACKAGE_NAME, u as CYBERSKILL_CLI, d as CYBERSKILL_CLI_PATH, f as CYBERSKILL_DIRECTORY, p as CYBERSKILL_PACKAGE_NAME, m as DOT_AGENT, h as ESLINT_CLI, g as ESLINT_INSPECT_CLI, _ as ESLINT_INSPECT_PACKAGE_NAME, v as ESLINT_PACKAGE_NAME, y as GIT_CLI, b as GIT_COMMIT_EDITMSG, x as GIT_EXCLUDE, S as GIT_HOOK, C as GIT_IGNORE, w as LINT_STAGED_CLI, T as LINT_STAGED_PACKAGE_NAME, E as MIGRATE_MONGO_CLI, D as MIGRATE_MONGO_CONFIG, O as MIGRATE_MONGO_PACKAGE_NAME, k as NODE_MODULES, A as NODE_MODULES_INSPECT_CLI, j as NODE_MODULES_INSPECT_PACKAGE_NAME, M as PACKAGE_JSON, N as PACKAGE_LOCK_JSON, P as PATH, F as PNPM_CLI, I as PNPM_EXEC_CLI, L as PNPM_LOCK_YAML, R as PUBLIC_DIRECTORY, z as SIMPLE_GIT_HOOKS_PACKAGE_NAME, B as SIMPLE_GIT_HOOK_CLI, V as SIMPLE_GIT_HOOK_JSON, H as STORYBOOK_CLI, U as STORYBOOK_PACKAGE_NAME, W as TSCONFIG_JSON, G as TSC_CLI, K as TSC_PACKAGE_NAME, q as TSX_CLI, J as VITEST_CLI, Y as VITEST_PACKAGE_NAME, X as WORKING_DIRECTORY, Z as command, Q as createGitHooksConfig, e as dirname, $ as getCyberskillDirectory, t as join, n as path, ee as resetCyberskillDirCacheForTesting, r as resolve, i as resolveWorkingPath };
|
|
@@ -13,6 +13,10 @@ export declare const GIT_HOOK = ".git/hooks/";
|
|
|
13
13
|
export declare const GIT_COMMIT_EDITMSG = ".git/COMMIT_EDITMSG";
|
|
14
14
|
export declare const GIT_EXCLUDE = ".git/info/exclude";
|
|
15
15
|
export declare const MIGRATE_MONGO_CONFIG = ".migrate-mongo.config.js";
|
|
16
|
+
/**
|
|
17
|
+
* Resets the cached directory path. For testing only.
|
|
18
|
+
*/
|
|
19
|
+
export declare function resetCyberskillDirCacheForTesting(): void;
|
|
16
20
|
/**
|
|
17
21
|
* Lazily computes the CyberSkill directory path.
|
|
18
22
|
* Reads package.json on first access to determine whether this is the shared package itself
|