@intlayer/backend 5.7.8 → 5.8.0-canary.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/cjs/schemas/dictionary.schema.cjs.map +1 -1
- package/dist/cjs/schemas/discussion.schema.cjs.map +1 -1
- package/dist/cjs/schemas/oAuth2.schema.cjs.map +1 -1
- package/dist/cjs/schemas/organization.schema.cjs.map +1 -1
- package/dist/cjs/schemas/plans.schema.cjs.map +1 -1
- package/dist/cjs/schemas/project.schema.cjs.map +1 -1
- package/dist/cjs/schemas/session.schema.cjs.map +1 -1
- package/dist/cjs/schemas/tag.schema.cjs.map +1 -1
- package/dist/cjs/schemas/user.schema.cjs.map +1 -1
- package/dist/cjs/services/organization.service.cjs +1 -2
- package/dist/cjs/services/organization.service.cjs.map +1 -1
- package/dist/cjs/utils/AI/aiSdk.cjs +2 -3
- package/dist/cjs/utils/AI/aiSdk.cjs.map +1 -1
- package/dist/cjs/utils/AI/askDocQuestion/askDocQuestion.cjs +1 -1
- package/dist/cjs/utils/AI/askDocQuestion/askDocQuestion.cjs.map +1 -1
- package/dist/cjs/utils/AI/askDocQuestion/embeddings.json +20502 -9216
- package/dist/cjs/utils/AI/autocomplete/index.cjs +2 -5
- package/dist/cjs/utils/AI/autocomplete/index.cjs.map +1 -1
- package/dist/cjs/utils/permissions.cjs +1 -1
- package/dist/cjs/utils/permissions.cjs.map +1 -1
- package/dist/cjs/utils/rateLimiter.cjs.map +1 -1
- package/dist/esm/schemas/dictionary.schema.mjs.map +1 -1
- package/dist/esm/schemas/discussion.schema.mjs.map +1 -1
- package/dist/esm/schemas/oAuth2.schema.mjs.map +1 -1
- package/dist/esm/schemas/organization.schema.mjs.map +1 -1
- package/dist/esm/schemas/plans.schema.mjs.map +1 -1
- package/dist/esm/schemas/project.schema.mjs.map +1 -1
- package/dist/esm/schemas/session.schema.mjs.map +1 -1
- package/dist/esm/schemas/tag.schema.mjs.map +1 -1
- package/dist/esm/schemas/user.schema.mjs.map +1 -1
- package/dist/esm/services/organization.service.mjs +1 -2
- package/dist/esm/services/organization.service.mjs.map +1 -1
- package/dist/esm/utils/AI/aiSdk.mjs +2 -3
- package/dist/esm/utils/AI/aiSdk.mjs.map +1 -1
- package/dist/esm/utils/AI/askDocQuestion/askDocQuestion.mjs +1 -1
- package/dist/esm/utils/AI/askDocQuestion/askDocQuestion.mjs.map +1 -1
- package/dist/esm/utils/AI/askDocQuestion/embeddings.json +20502 -9216
- package/dist/esm/utils/AI/autocomplete/index.mjs +2 -5
- package/dist/esm/utils/AI/autocomplete/index.mjs.map +1 -1
- package/dist/esm/utils/permissions.mjs +1 -1
- package/dist/esm/utils/permissions.mjs.map +1 -1
- package/dist/esm/utils/rateLimiter.mjs.map +1 -1
- package/dist/types/models/dictionary.model.d.ts +1 -1
- package/dist/types/models/discussion.model.d.ts +1 -1
- package/dist/types/models/oAuth2.model.d.ts +1 -1
- package/dist/types/schemas/dictionary.schema.d.ts +2 -2
- package/dist/types/schemas/discussion.schema.d.ts +2 -2
- package/dist/types/schemas/oAuth2.schema.d.ts +2 -2
- package/dist/types/schemas/organization.schema.d.ts +2 -2
- package/dist/types/schemas/plans.schema.d.ts +2 -2
- package/dist/types/schemas/project.schema.d.ts +2 -2
- package/dist/types/schemas/session.schema.d.ts +2 -2
- package/dist/types/schemas/tag.schema.d.ts +2 -2
- package/dist/types/schemas/user.schema.d.ts +2 -2
- package/dist/types/services/organization.service.d.ts.map +1 -1
- package/dist/types/utils/AI/aiSdk.d.ts +2 -3
- package/dist/types/utils/AI/aiSdk.d.ts.map +1 -1
- package/dist/types/utils/AI/autocomplete/index.d.ts.map +1 -1
- package/dist/types/utils/rateLimiter.d.ts +1 -1
- package/dist/types/utils/rateLimiter.d.ts.map +1 -1
- package/package.json +20 -20
|
@@ -35,8 +35,7 @@ const CHAT_GPT_PROMPT = getFileContent("./PROMPT.md");
|
|
|
35
35
|
const aiDefaultOptions = {
|
|
36
36
|
provider: import_aiSdk.AIProvider.OPENAI,
|
|
37
37
|
model: "gpt-4o-mini",
|
|
38
|
-
temperature: 0.7
|
|
39
|
-
maxTokens: 128
|
|
38
|
+
temperature: 0.7
|
|
40
39
|
};
|
|
41
40
|
const autocomplete = async ({
|
|
42
41
|
text,
|
|
@@ -55,9 +54,7 @@ const autocomplete = async ({
|
|
|
55
54
|
messages: [
|
|
56
55
|
{ role: "system", content: prompt },
|
|
57
56
|
{ role: "assistant", content: text }
|
|
58
|
-
]
|
|
59
|
-
maxTokens: aiConfig.maxTokens ?? 128
|
|
60
|
-
// Generate next tokens
|
|
57
|
+
]
|
|
61
58
|
});
|
|
62
59
|
import_logger.logger.info(`${usage?.totalTokens ?? 0} tokens used in the request`);
|
|
63
60
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/utils/AI/autocomplete/index.ts"],"sourcesContent":["import { logger } from '@logger';\nimport { generateText } from 'ai';\nimport { readFileSync } from 'fs';\nimport { dirname, join } from 'path';\nimport { fileURLToPath } from 'url';\nimport { AIConfig, AIOptions, AIProvider } from '../aiSdk';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// Get the content of a file at the specified path\nconst getFileContent = (filePath: string) =>\n readFileSync(join(__dirname, filePath), { encoding: 'utf-8' });\n\nexport type AutocompleteOptions = {\n text: string;\n aiConfig: AIConfig;\n applicationContext?: string;\n contextBefore?: string;\n currentLine?: string;\n contextAfter?: string;\n};\n\nexport type AutocompleteFileResultData = {\n autocompletion: string;\n tokenUsed: number;\n};\n\n// The prompt template to send to the AI model\nconst CHAT_GPT_PROMPT = getFileContent('./PROMPT.md');\n\nexport const aiDefaultOptions: AIOptions = {\n provider: AIProvider.OPENAI,\n model: 'gpt-4o-mini',\n temperature: 0.7,\n
|
|
1
|
+
{"version":3,"sources":["../../../../../src/utils/AI/autocomplete/index.ts"],"sourcesContent":["import { logger } from '@logger';\nimport { generateText } from 'ai';\nimport { readFileSync } from 'fs';\nimport { dirname, join } from 'path';\nimport { fileURLToPath } from 'url';\nimport { AIConfig, AIOptions, AIProvider } from '../aiSdk';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// Get the content of a file at the specified path\nconst getFileContent = (filePath: string) =>\n readFileSync(join(__dirname, filePath), { encoding: 'utf-8' });\n\nexport type AutocompleteOptions = {\n text: string;\n aiConfig: AIConfig;\n applicationContext?: string;\n contextBefore?: string;\n currentLine?: string;\n contextAfter?: string;\n};\n\nexport type AutocompleteFileResultData = {\n autocompletion: string;\n tokenUsed: number;\n};\n\n// The prompt template to send to the AI model\nconst CHAT_GPT_PROMPT = getFileContent('./PROMPT.md');\n\nexport const aiDefaultOptions: AIOptions = {\n provider: AIProvider.OPENAI,\n model: 'gpt-4o-mini',\n temperature: 0.7,\n};\n\n/**\n * Autocompletes a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const autocomplete = async ({\n text,\n aiConfig,\n applicationContext,\n contextBefore,\n currentLine,\n contextAfter,\n}: AutocompleteOptions): Promise<AutocompleteFileResultData | undefined> => {\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = CHAT_GPT_PROMPT.replace(\n '{{applicationContext}}',\n applicationContext ?? ''\n )\n .replace('{{contextBefore}}', contextBefore ?? '')\n .replace('{{currentLine}}', currentLine ?? '')\n .replace('{{contextAfter}}', contextAfter ?? '');\n\n // Use the AI SDK to generate the completion\n const { text: newContent, usage } = await generateText({\n ...aiConfig,\n messages: [\n { role: 'system', content: prompt },\n { role: 'assistant', content: text },\n ],\n });\n\n logger.info(`${usage?.totalTokens ?? 0} tokens used in the request`);\n\n return {\n autocompletion: newContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAuB;AACvB,gBAA6B;AAC7B,gBAA6B;AAC7B,kBAA8B;AAC9B,iBAA8B;AAC9B,mBAAgD;AALhD;AAOA,MAAM,gBAAY,yBAAQ,0BAAc,YAAY,GAAG,CAAC;AAGxD,MAAM,iBAAiB,CAAC,iBACtB,4BAAa,kBAAK,WAAW,QAAQ,GAAG,EAAE,UAAU,QAAQ,CAAC;AAiB/D,MAAM,kBAAkB,eAAe,aAAa;AAE7C,MAAM,mBAA8B;AAAA,EACzC,UAAU,wBAAW;AAAA,EACrB,OAAO;AAAA,EACP,aAAa;AACf;AAOO,MAAM,eAAe,OAAO;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAA4E;AAE1E,QAAM,SAAS,gBAAgB;AAAA,IAC7B;AAAA,IACA,sBAAsB;AAAA,EACxB,EACG,QAAQ,qBAAqB,iBAAiB,EAAE,EAChD,QAAQ,mBAAmB,eAAe,EAAE,EAC5C,QAAQ,oBAAoB,gBAAgB,EAAE;AAGjD,QAAM,EAAE,MAAM,YAAY,MAAM,IAAI,UAAM,wBAAa;AAAA,IACrD,GAAG;AAAA,IACH,UAAU;AAAA,MACR,EAAE,MAAM,UAAU,SAAS,OAAO;AAAA,MAClC,EAAE,MAAM,aAAa,SAAS,KAAK;AAAA,IACrC;AAAA,EACF,CAAC;AAED,uBAAO,KAAK,GAAG,OAAO,eAAe,CAAC,6BAA6B;AAEnE,SAAO;AAAA,IACL,gBAAgB;AAAA,IAChB,WAAW,OAAO,eAAe;AAAA,EACnC;AACF;","names":[]}
|
|
@@ -248,7 +248,7 @@ const hasPermission = (roles, permission) => {
|
|
|
248
248
|
const rolesCheck = roles.map(
|
|
249
249
|
(role) => ROLE_POLICY[role]?.[permission] ?? (() => false)
|
|
250
250
|
);
|
|
251
|
-
return (args) => rolesCheck.some((check) => check(args));
|
|
251
|
+
return ((args) => rolesCheck.some((check) => check(args)));
|
|
252
252
|
};
|
|
253
253
|
// Annotate the CommonJS export names for ESM import in node:
|
|
254
254
|
0 && (module.exports = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/permissions.ts"],"sourcesContent":["import { Dictionary, DictionaryAPI } from '@/types/dictionary.types';\nimport { Organization, OrganizationAPI } from '@/types/organization.types';\nimport { Project, ProjectAPI } from '@/types/project.types';\nimport { SessionContext } from '@/types/session.types';\nimport { Tag, TagAPI } from '@/types/tag.types';\nimport { User, UserAPI } from '@/types/user.types';\n\n/**\n * A named grouping of privileges (e.g. `\"org_admin\"`).\n * Users are *granted* one or more Roles.\n */\nexport type Roles =\n | 'user'\n | 'admin'\n | 'org_admin'\n | 'org_user'\n | 'project_admin'\n | 'project_user'\n | 'project_reviewer';\n\n/**\n * An atomic operation that can be performed on a resource.\n * - **read**: view or list\n * - **write**: create or update\n * - **admin**: delete or change permissions\n */\nexport type Action = 'read' | 'write' | 'admin';\n\n/**\n * A first‑class entity in your domain model that you want to protect.\n */\nexport type Resource = {\n organization: Organization;\n project: Project;\n dictionary: Dictionary;\n tag: Tag;\n user: User;\n};\n\n/**\n * A literal string combining a Resource and an Action, e.g. `\"project:write\"`.\n * This is the *unit* checked at runtime in your middleware.\n */\nexport type Permission = `${keyof Resource}:${Action}`;\n\ntype CheckPrivilege = (\n args: any\n) => boolean | undefined | Promise<boolean> | Promise<undefined>;\n\ntype RolePolicy = Record<Roles, Partial<Record<Permission, CheckPrivilege>>>;\n\nexport const ROLE_POLICY = {\n admin: {\n 'organization:read': () => true,\n 'organization:write': () => true,\n 'organization:admin': () => true,\n 'project:read': () => true,\n 'project:write': () => true,\n 'project:admin': () => true,\n 'dictionary:read': () => true,\n 'dictionary:write': () => true,\n 'dictionary:admin': () => true,\n 'tag:read': () => true,\n 'tag:write': () => true,\n 'tag:admin': () => true,\n 'user:read': () => true,\n 'user:write': () => true,\n 'user:admin': () => true,\n },\n user: {\n 'user:read': ({\n user,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every(\n (targetUser) =>\n String(targetUser.id) === String(user?.id) &&\n targetUser.email === user?.email\n ),\n 'user:write': ({\n user,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every(\n (targetUser) =>\n String(targetUser.id) === String(user?.id) &&\n targetUser.email === user?.email\n ),\n 'user:admin': ({\n user,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every(\n (targetUser) =>\n String(targetUser.id) === String(user?.id) &&\n targetUser.email === user?.email\n ),\n 'organization:read': ({\n user,\n targetOrganizations,\n }: SessionContext & {\n targetOrganizations: (Organization | OrganizationAPI)[];\n }) =>\n targetOrganizations.every((organization) =>\n organization?.membersIds?.map(String).includes(String(user?.id))\n ),\n },\n org_admin: {\n 'organization:read': ({\n organization,\n targetOrganizations,\n }: SessionContext & {\n targetOrganizations: (Organization | OrganizationAPI)[];\n }) =>\n targetOrganizations.every(\n (targetOrg) => String(targetOrg.id) === String(organization?.id)\n ),\n 'organization:write': ({\n organization,\n targetOrganizations,\n }: SessionContext & {\n targetOrganizations: (Organization | OrganizationAPI)[];\n }) =>\n targetOrganizations.every(\n (targetOrg) => String(targetOrg.id) === String(organization?.id)\n ),\n 'organization:admin': ({\n organization,\n targetOrganizations,\n }: SessionContext & {\n targetOrganizations: (Organization | OrganizationAPI)[];\n }) =>\n targetOrganizations.every(\n (targetOrg) => String(targetOrg.id) === String(organization?.id)\n ),\n\n 'project:read': ({ organization, project }: SessionContext) =>\n String(project?.organizationId) === String(organization?.id),\n 'project:write': ({ organization, project }: SessionContext) =>\n String(project?.organizationId) === String(organization?.id),\n 'project:admin': ({ organization, project }: SessionContext) =>\n String(project?.organizationId) === String(organization?.id),\n\n 'tag:read': ({ organization, project }: SessionContext) =>\n String(project?.organizationId) === String(organization?.id),\n 'tag:write': ({ organization, project }: SessionContext) =>\n String(project?.organizationId) === String(organization?.id),\n 'tag:admin': ({ organization, project }: SessionContext) =>\n String(project?.organizationId) === String(organization?.id),\n\n 'user:write': ({\n organization,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every((targetUser) =>\n organization?.membersIds?.map(String).includes(String(targetUser?.id))\n ),\n },\n org_user: {\n 'organization:read': ({\n organization,\n targetOrganizations,\n }: SessionContext & {\n targetOrganizations: (Organization | OrganizationAPI)[];\n }) =>\n targetOrganizations.every(\n (targetOrg) => String(targetOrg.id) === String(organization?.id)\n ),\n\n 'project:read': ({\n user,\n targetProjects,\n }: SessionContext & {\n targetProjects: (Project | ProjectAPI)[];\n }) =>\n targetProjects?.every((project) =>\n project?.membersIds?.map(String).includes(String(user?.id))\n ),\n\n 'user:read': ({\n organization,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every((targetUser) =>\n organization?.membersIds?.map(String).includes(String(targetUser?.id))\n ),\n },\n project_admin: {\n 'project:read': ({\n project,\n targetProjectIds,\n }: SessionContext & {\n targetProjectIds?: (Project | ProjectAPI)['id'][];\n }) =>\n targetProjectIds?.every(\n (projectId) => String(project?.id) === String(projectId)\n ),\n 'project:write': ({\n project,\n targetProjectIds,\n }: SessionContext & {\n targetProjectIds?: (Project | ProjectAPI)['id'][];\n }) =>\n targetProjectIds?.every(\n (projectId) => String(project?.id) === String(projectId)\n ),\n 'project:admin': ({\n project,\n targetProjectIds,\n }: SessionContext & {\n targetProjectIds?: (Project | ProjectAPI)['id'][];\n }) =>\n targetProjectIds?.every(\n (projectId) => String(project?.id) === String(projectId)\n ),\n\n 'tag:read': ({\n project,\n targetTags,\n }: SessionContext & { targetTags: (Tag | TagAPI)[] }) =>\n targetTags.every((tag) => String(project?.id) === String(tag?.projectId)),\n 'tag:write': ({\n project,\n targetTags,\n }: SessionContext & { targetTags: (Tag | TagAPI)[] }) =>\n targetTags.every((tag) => String(project?.id) === String(tag?.projectId)),\n 'tag:admin': ({\n project,\n targetTags,\n }: SessionContext & { targetTags: (Tag | TagAPI)[] }) =>\n targetTags.every((tag) => String(project?.id) === String(tag?.projectId)),\n\n 'user:write': ({\n project,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every((targetUser) =>\n project?.membersIds?.map(String).includes(String(targetUser?.id))\n ),\n\n 'dictionary:read': ({ project, user }: SessionContext) =>\n project?.adminsIds?.map(String).includes(String(user?.id)),\n 'dictionary:write': ({ project, user }: SessionContext) =>\n project?.adminsIds?.map(String).includes(String(user?.id)),\n 'dictionary:admin': ({ project, user }: SessionContext) =>\n project?.adminsIds?.map(String).includes(String(user?.id)),\n },\n project_user: {\n 'project:read': ({ user, organization, project }: SessionContext) =>\n String(organization?.id) === String(project?.organizationId) &&\n organization?.membersIds?.map(String).includes(String(user?.id)) &&\n project?.membersIds?.map(String).includes(String(user?.id)),\n\n 'dictionary:read': ({\n user,\n project,\n targetDictionaries,\n }: SessionContext & {\n targetDictionaries: (Dictionary | DictionaryAPI)[];\n }) =>\n project?.membersIds?.map(String).includes(String(user?.id)) &&\n targetDictionaries.every((dictionary) =>\n dictionary?.projectIds?.map(String).includes(String(project?.id))\n ),\n 'dictionary:write': ({ user, project }: SessionContext) =>\n project?.adminsIds?.map(String).includes(String(user?.id)),\n\n 'tag:read': ({\n project,\n targetTags,\n user,\n }: SessionContext & {\n targetTags: (Tag | TagAPI)[];\n }) =>\n project?.membersIds?.map(String).includes(String(user?.id)) &&\n targetTags.every((tag) => String(project?.id) === String(tag?.projectId)),\n 'tag:write': ({\n project,\n targetTags,\n user,\n }: SessionContext & {\n targetTags: (Tag | TagAPI)[];\n }) =>\n project?.membersIds?.map(String).includes(String(user?.id)) &&\n targetTags.every((tag) => String(project?.id) === String(tag?.projectId)),\n 'tag:admin': ({\n user,\n project,\n targetTags,\n }: SessionContext & {\n targetTags: (Tag | TagAPI)[];\n }) =>\n project?.adminsIds?.map(String).includes(String(user?.id)) &&\n targetTags.every((tag) => String(project?.id) === String(tag?.projectId)),\n\n 'user:read': ({\n project,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every((targetUser) =>\n project?.membersIds?.map(String).includes(String(targetUser?.id))\n ),\n },\n project_reviewer: {\n 'dictionary:read': ({ user, project }: SessionContext) =>\n project?.membersIds?.map(String).includes(String(user?.id)),\n 'dictionary:write': ({ user, project }: SessionContext) =>\n project?.membersIds?.map(String).includes(String(user?.id)),\n\n 'tag:read': () => true,\n },\n} as const satisfies RolePolicy;\n\nexport const getSessionRoles = ({\n user,\n organization,\n project,\n}: SessionContext): Roles[] => {\n const roles: Roles[] = [];\n\n if (!user) {\n return roles;\n }\n\n roles.push('user');\n\n const isUserAdmin = user.role === 'admin';\n\n if (isUserAdmin) {\n roles.push('admin');\n }\n\n if (!organization) {\n return roles;\n }\n\n const isOrganizationAdmin = organization.adminsIds\n ?.map(String)\n .includes(String(user!.id));\n\n if (isOrganizationAdmin) {\n roles.push('org_admin');\n }\n\n const isOrganizationMember = organization.membersIds\n ?.map(String)\n .includes(String(user!.id));\n\n if (isOrganizationMember) {\n roles.push('org_user');\n }\n\n if (!project) {\n return roles;\n }\n\n const isProjectAdmin = project.adminsIds\n ?.map(String)\n .includes(String(user!.id));\n\n if (isProjectAdmin) {\n roles.push('project_admin');\n }\n\n const isProjectMember = project?.membersIds\n ?.map(String)\n .includes(String(user!.id));\n\n if (isProjectMember) {\n roles.push('project_user');\n }\n\n // const isProjectReviewer =\n // session.project?.reviewersIds?.includes(session.user!.id);\n\n // if (isProjectReviewer) {\n // roles.push('project_reviewer');\n // }\n\n return roles;\n};\n\nexport const computeEffectivePermission = (roles: Roles[]): Permission[] =>\n Array.from(\n new Set(\n roles.flatMap((role) => Object.keys(ROLE_POLICY[role]) as Permission[])\n )\n );\n\n/**\n * Intersect two permission lists\n * @param permissionList1 - The first permission list\n * @param permissionList2 - The second permission list\n * @returns The intersection of the two permission lists (only permissions present in both)\n */\nexport const intersectPermissions = (\n permissions1: Permission[],\n permissions2: Permission[]\n): Permission[] =>\n permissions1.filter((permission) => permissions2.includes(permission));\n\ntype PermissionResult<\n R extends Roles,\n P extends Permission,\n> = (typeof ROLE_POLICY)[R] extends infer RolePerms\n ? RolePerms extends Record<string, (args: any) => any>\n ? P extends keyof RolePerms\n ? RolePerms[P] extends undefined\n ? never\n : RolePerms[P]\n : never\n : never\n : never;\n\nexport const hasPermission = <P extends Permission>(\n roles: Roles[],\n permission: P\n): PermissionResult<Roles, P> => {\n const rolesCheck: any = roles.map(\n (role) =>\n ROLE_POLICY[role]?.[\n permission as keyof (typeof ROLE_POLICY)[typeof role]\n ] ?? (() => false)\n ) as unknown as PermissionResult<Roles, P>[];\n\n return ((args: any) => rolesCheck.some((check: any) => check(args))) as any;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmDO,MAAM,cAAc;AAAA,EACzB,OAAO;AAAA,IACL,qBAAqB,MAAM;AAAA,IAC3B,sBAAsB,MAAM;AAAA,IAC5B,sBAAsB,MAAM;AAAA,IAC5B,gBAAgB,MAAM;AAAA,IACtB,iBAAiB,MAAM;AAAA,IACvB,iBAAiB,MAAM;AAAA,IACvB,mBAAmB,MAAM;AAAA,IACzB,oBAAoB,MAAM;AAAA,IAC1B,oBAAoB,MAAM;AAAA,IAC1B,YAAY,MAAM;AAAA,IAClB,aAAa,MAAM;AAAA,IACnB,aAAa,MAAM;AAAA,IACnB,aAAa,MAAM;AAAA,IACnB,cAAc,MAAM;AAAA,IACpB,cAAc,MAAM;AAAA,EACtB;AAAA,EACA,MAAM;AAAA,IACJ,aAAa,CAAC;AAAA,MACZ;AAAA,MACA;AAAA,IACF,MACE,YAAY;AAAA,MACV,CAAC,eACC,OAAO,WAAW,EAAE,MAAM,OAAO,MAAM,EAAE,KACzC,WAAW,UAAU,MAAM;AAAA,IAC/B;AAAA,IACF,cAAc,CAAC;AAAA,MACb;AAAA,MACA;AAAA,IACF,MACE,YAAY;AAAA,MACV,CAAC,eACC,OAAO,WAAW,EAAE,MAAM,OAAO,MAAM,EAAE,KACzC,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AM;AAAA,EACJ,IAAI;AAAA,IACF,MAAM,QAAQ,CAAC,SAAS,OAAO,KAAK,YAAY,IAAI,CAAC,CAAiB;AAAA,EACxE;AACF;AAQK,MAAM,uBAAuB,CAClC,cACA,iBAEA,aAAa,OAAO,CAAC,eAAe,aAAa,SAAS,UAAU,CAAC;AAehE,MAAM,gBAAgB,CAC3B,OACA,eAC+B;AAC/B,QAAM,aAAkB,MAAM;AAAA,IAC5B,CAAC,SACC,YAAY,IAAI,IACd,UACF,MAAM,MAAM;AAAA,EAChB;AAEA,SAAQ,CAAC,SAAc,WAAW,KAAK,CAAC,UAAe,MAAM,IAAI,CAAC;AACpE;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/permissions.ts"],"sourcesContent":["import { Dictionary, DictionaryAPI } from '@/types/dictionary.types';\nimport { Organization, OrganizationAPI } from '@/types/organization.types';\nimport { Project, ProjectAPI } from '@/types/project.types';\nimport { SessionContext } from '@/types/session.types';\nimport { Tag, TagAPI } from '@/types/tag.types';\nimport { User, UserAPI } from '@/types/user.types';\n\n/**\n * A named grouping of privileges (e.g. `\"org_admin\"`).\n * Users are *granted* one or more Roles.\n */\nexport type Roles =\n | 'user'\n | 'admin'\n | 'org_admin'\n | 'org_user'\n | 'project_admin'\n | 'project_user'\n | 'project_reviewer';\n\n/**\n * An atomic operation that can be performed on a resource.\n * - **read**: view or list\n * - **write**: create or update\n * - **admin**: delete or change permissions\n */\nexport type Action = 'read' | 'write' | 'admin';\n\n/**\n * A first‑class entity in your domain model that you want to protect.\n */\nexport type Resource = {\n organization: Organization;\n project: Project;\n dictionary: Dictionary;\n tag: Tag;\n user: User;\n};\n\n/**\n * A literal string combining a Resource and an Action, e.g. `\"project:write\"`.\n * This is the *unit* checked at runtime in your middleware.\n */\nexport type Permission = `${keyof Resource}:${Action}`;\n\ntype CheckPrivilege = (\n args: any\n) => boolean | undefined | Promise<boolean> | Promise<undefined>;\n\ntype RolePolicy = Record<Roles, Partial<Record<Permission, CheckPrivilege>>>;\n\nexport const ROLE_POLICY = {\n admin: {\n 'organization:read': () => true,\n 'organization:write': () => true,\n 'organization:admin': () => true,\n 'project:read': () => true,\n 'project:write': () => true,\n 'project:admin': () => true,\n 'dictionary:read': () => true,\n 'dictionary:write': () => true,\n 'dictionary:admin': () => true,\n 'tag:read': () => true,\n 'tag:write': () => true,\n 'tag:admin': () => true,\n 'user:read': () => true,\n 'user:write': () => true,\n 'user:admin': () => true,\n },\n user: {\n 'user:read': ({\n user,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every(\n (targetUser) =>\n String(targetUser.id) === String(user?.id) &&\n targetUser.email === user?.email\n ),\n 'user:write': ({\n user,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every(\n (targetUser) =>\n String(targetUser.id) === String(user?.id) &&\n targetUser.email === user?.email\n ),\n 'user:admin': ({\n user,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every(\n (targetUser) =>\n String(targetUser.id) === String(user?.id) &&\n targetUser.email === user?.email\n ),\n 'organization:read': ({\n user,\n targetOrganizations,\n }: SessionContext & {\n targetOrganizations: (Organization | OrganizationAPI)[];\n }) =>\n targetOrganizations.every((organization) =>\n organization?.membersIds?.map(String).includes(String(user?.id))\n ),\n },\n org_admin: {\n 'organization:read': ({\n organization,\n targetOrganizations,\n }: SessionContext & {\n targetOrganizations: (Organization | OrganizationAPI)[];\n }) =>\n targetOrganizations.every(\n (targetOrg) => String(targetOrg.id) === String(organization?.id)\n ),\n 'organization:write': ({\n organization,\n targetOrganizations,\n }: SessionContext & {\n targetOrganizations: (Organization | OrganizationAPI)[];\n }) =>\n targetOrganizations.every(\n (targetOrg) => String(targetOrg.id) === String(organization?.id)\n ),\n 'organization:admin': ({\n organization,\n targetOrganizations,\n }: SessionContext & {\n targetOrganizations: (Organization | OrganizationAPI)[];\n }) =>\n targetOrganizations.every(\n (targetOrg) => String(targetOrg.id) === String(organization?.id)\n ),\n\n 'project:read': ({ organization, project }: SessionContext) =>\n String(project?.organizationId) === String(organization?.id),\n 'project:write': ({ organization, project }: SessionContext) =>\n String(project?.organizationId) === String(organization?.id),\n 'project:admin': ({ organization, project }: SessionContext) =>\n String(project?.organizationId) === String(organization?.id),\n\n 'tag:read': ({ organization, project }: SessionContext) =>\n String(project?.organizationId) === String(organization?.id),\n 'tag:write': ({ organization, project }: SessionContext) =>\n String(project?.organizationId) === String(organization?.id),\n 'tag:admin': ({ organization, project }: SessionContext) =>\n String(project?.organizationId) === String(organization?.id),\n\n 'user:write': ({\n organization,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every((targetUser) =>\n organization?.membersIds?.map(String).includes(String(targetUser?.id))\n ),\n },\n org_user: {\n 'organization:read': ({\n organization,\n targetOrganizations,\n }: SessionContext & {\n targetOrganizations: (Organization | OrganizationAPI)[];\n }) =>\n targetOrganizations.every(\n (targetOrg) => String(targetOrg.id) === String(organization?.id)\n ),\n\n 'project:read': ({\n user,\n targetProjects,\n }: SessionContext & {\n targetProjects: (Project | ProjectAPI)[];\n }) =>\n targetProjects?.every((project) =>\n project?.membersIds?.map(String).includes(String(user?.id))\n ),\n\n 'user:read': ({\n organization,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every((targetUser) =>\n organization?.membersIds?.map(String).includes(String(targetUser?.id))\n ),\n },\n project_admin: {\n 'project:read': ({\n project,\n targetProjectIds,\n }: SessionContext & {\n targetProjectIds?: (Project | ProjectAPI)['id'][];\n }) =>\n targetProjectIds?.every(\n (projectId) => String(project?.id) === String(projectId)\n ),\n 'project:write': ({\n project,\n targetProjectIds,\n }: SessionContext & {\n targetProjectIds?: (Project | ProjectAPI)['id'][];\n }) =>\n targetProjectIds?.every(\n (projectId) => String(project?.id) === String(projectId)\n ),\n 'project:admin': ({\n project,\n targetProjectIds,\n }: SessionContext & {\n targetProjectIds?: (Project | ProjectAPI)['id'][];\n }) =>\n targetProjectIds?.every(\n (projectId) => String(project?.id) === String(projectId)\n ),\n\n 'tag:read': ({\n project,\n targetTags,\n }: SessionContext & { targetTags: (Tag | TagAPI)[] }) =>\n targetTags.every((tag) => String(project?.id) === String(tag?.projectId)),\n 'tag:write': ({\n project,\n targetTags,\n }: SessionContext & { targetTags: (Tag | TagAPI)[] }) =>\n targetTags.every((tag) => String(project?.id) === String(tag?.projectId)),\n 'tag:admin': ({\n project,\n targetTags,\n }: SessionContext & { targetTags: (Tag | TagAPI)[] }) =>\n targetTags.every((tag) => String(project?.id) === String(tag?.projectId)),\n\n 'user:write': ({\n project,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every((targetUser) =>\n project?.membersIds?.map(String).includes(String(targetUser?.id))\n ),\n\n 'dictionary:read': ({ project, user }: SessionContext) =>\n project?.adminsIds?.map(String).includes(String(user?.id)),\n 'dictionary:write': ({ project, user }: SessionContext) =>\n project?.adminsIds?.map(String).includes(String(user?.id)),\n 'dictionary:admin': ({ project, user }: SessionContext) =>\n project?.adminsIds?.map(String).includes(String(user?.id)),\n },\n project_user: {\n 'project:read': ({ user, organization, project }: SessionContext) =>\n String(organization?.id) === String(project?.organizationId) &&\n organization?.membersIds?.map(String).includes(String(user?.id)) &&\n project?.membersIds?.map(String).includes(String(user?.id)),\n\n 'dictionary:read': ({\n user,\n project,\n targetDictionaries,\n }: SessionContext & {\n targetDictionaries: (Dictionary | DictionaryAPI)[];\n }) =>\n project?.membersIds?.map(String).includes(String(user?.id)) &&\n targetDictionaries.every((dictionary) =>\n dictionary?.projectIds?.map(String).includes(String(project?.id))\n ),\n 'dictionary:write': ({ user, project }: SessionContext) =>\n project?.adminsIds?.map(String).includes(String(user?.id)),\n\n 'tag:read': ({\n project,\n targetTags,\n user,\n }: SessionContext & {\n targetTags: (Tag | TagAPI)[];\n }) =>\n project?.membersIds?.map(String).includes(String(user?.id)) &&\n targetTags.every((tag) => String(project?.id) === String(tag?.projectId)),\n 'tag:write': ({\n project,\n targetTags,\n user,\n }: SessionContext & {\n targetTags: (Tag | TagAPI)[];\n }) =>\n project?.membersIds?.map(String).includes(String(user?.id)) &&\n targetTags.every((tag) => String(project?.id) === String(tag?.projectId)),\n 'tag:admin': ({\n user,\n project,\n targetTags,\n }: SessionContext & {\n targetTags: (Tag | TagAPI)[];\n }) =>\n project?.adminsIds?.map(String).includes(String(user?.id)) &&\n targetTags.every((tag) => String(project?.id) === String(tag?.projectId)),\n\n 'user:read': ({\n project,\n targetUsers,\n }: SessionContext & { targetUsers: (User | UserAPI)[] }) =>\n targetUsers.every((targetUser) =>\n project?.membersIds?.map(String).includes(String(targetUser?.id))\n ),\n },\n project_reviewer: {\n 'dictionary:read': ({ user, project }: SessionContext) =>\n project?.membersIds?.map(String).includes(String(user?.id)),\n 'dictionary:write': ({ user, project }: SessionContext) =>\n project?.membersIds?.map(String).includes(String(user?.id)),\n\n 'tag:read': () => true,\n },\n} as const satisfies RolePolicy;\n\nexport const getSessionRoles = ({\n user,\n organization,\n project,\n}: SessionContext): Roles[] => {\n const roles: Roles[] = [];\n\n if (!user) {\n return roles;\n }\n\n roles.push('user');\n\n const isUserAdmin = user.role === 'admin';\n\n if (isUserAdmin) {\n roles.push('admin');\n }\n\n if (!organization) {\n return roles;\n }\n\n const isOrganizationAdmin = organization.adminsIds\n ?.map(String)\n .includes(String(user!.id));\n\n if (isOrganizationAdmin) {\n roles.push('org_admin');\n }\n\n const isOrganizationMember = organization.membersIds\n ?.map(String)\n .includes(String(user!.id));\n\n if (isOrganizationMember) {\n roles.push('org_user');\n }\n\n if (!project) {\n return roles;\n }\n\n const isProjectAdmin = project.adminsIds\n ?.map(String)\n .includes(String(user!.id));\n\n if (isProjectAdmin) {\n roles.push('project_admin');\n }\n\n const isProjectMember = project?.membersIds\n ?.map(String)\n .includes(String(user!.id));\n\n if (isProjectMember) {\n roles.push('project_user');\n }\n\n // const isProjectReviewer =\n // session.project?.reviewersIds?.includes(session.user!.id);\n\n // if (isProjectReviewer) {\n // roles.push('project_reviewer');\n // }\n\n return roles;\n};\n\nexport const computeEffectivePermission = (roles: Roles[]): Permission[] =>\n Array.from(\n new Set(\n roles.flatMap((role) => Object.keys(ROLE_POLICY[role]) as Permission[])\n )\n );\n\n/**\n * Intersect two permission lists\n * @param permissionList1 - The first permission list\n * @param permissionList2 - The second permission list\n * @returns The intersection of the two permission lists (only permissions present in both)\n */\nexport const intersectPermissions = (\n permissions1: Permission[],\n permissions2: Permission[]\n): Permission[] =>\n permissions1.filter((permission) => permissions2.includes(permission));\n\ntype PermissionResult<\n R extends Roles,\n P extends Permission,\n> = (typeof ROLE_POLICY)[R] extends infer RolePerms\n ? RolePerms extends Record<string, (args: any) => any>\n ? P extends keyof RolePerms\n ? RolePerms[P] extends undefined\n ? never\n : RolePerms[P]\n : never\n : never\n : never;\n\nexport const hasPermission = <P extends Permission>(\n roles: Roles[],\n permission: P\n): PermissionResult<Roles, P> => {\n const rolesCheck: any = roles.map(\n (role) =>\n ROLE_POLICY[role]?.[\n permission as keyof (typeof ROLE_POLICY)[typeof role]\n ] ?? (() => false)\n ) as unknown as PermissionResult<Roles, P>[];\n\n return ((args: any) => rolesCheck.some((check: any) => check(args))) as any;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmDO,MAAM,cAAc;AAAA,EACzB,OAAO;AAAA,IACL,qBAAqB,MAAM;AAAA,IAC3B,sBAAsB,MAAM;AAAA,IAC5B,sBAAsB,MAAM;AAAA,IAC5B,gBAAgB,MAAM;AAAA,IACtB,iBAAiB,MAAM;AAAA,IACvB,iBAAiB,MAAM;AAAA,IACvB,mBAAmB,MAAM;AAAA,IACzB,oBAAoB,MAAM;AAAA,IAC1B,oBAAoB,MAAM;AAAA,IAC1B,YAAY,MAAM;AAAA,IAClB,aAAa,MAAM;AAAA,IACnB,aAAa,MAA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,UAAM,KAAK,UAAU;AAAA,EACvB;AAEA,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,QAAM,iBAAiB,QAAQ,WAC3B,IAAI,MAAM,EACX,SAAS,OAAO,KAAM,EAAE,CAAC;AAE5B,MAAI,gBAAgB;AAClB,UAAM,KAAK,eAAe;AAAA,EAC5B;AAEA,QAAM,kBAAkB,SAAS,YAC7B,IAAI,MAAM,EACX,SAAS,OAAO,KAAM,EAAE,CAAC;AAE5B,MAAI,iBAAiB;AACnB,UAAM,KAAK,cAAc;AAAA,EAC3B;AASA,SAAO;AACT;AAEO,MAAM,6BAA6B,CAAC,UACzC,MAAM;AAAA,EACJ,IAAI;AAAA,IACF,MAAM,QAAQ,CAAC,SAAS,OAAO,KAAK,YAAY,IAAI,CAAC,CAAiB;AAAA,EACxE;AACF;AAQK,MAAM,uBAAuB,CAClC,cACA,iBAEA,aAAa,OAAO,CAAC,eAAe,aAAa,SAAS,UAAU,CAAC;AAehE,MAAM,gBAAgB,CAC3B,OACA,eAC+B;AAC/B,QAAM,aAAkB,MAAM;AAAA,IAC5B,CAAC,SACC,YAAY,IAAI,IACd,UACF,MAAM,MAAM;AAAA,EAChB;AAEA,UAAQ,CAAC,SAAc,WAAW,KAAK,CAAC,UAAe,MAAM,IAAI,CAAC;AACpE;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/rateLimiter.ts"],"sourcesContent":["import type { NextFunction, Request, Response } from 'express';\nimport rateLimit from 'express-rate-limit';\nimport { ErrorHandler } from './errors';\n\n// -------------------------------------------------------------\n// Create the rate-limiter instances once at module load-time so\n// that the hit counters are shared across every incoming request.\n// -------------------------------------------------------------\n\nexport const ipLimiter: (\n req: Request,\n res: Response,\n next: NextFunction\n) =>
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/rateLimiter.ts"],"sourcesContent":["import type { NextFunction, Request, Response } from 'express';\nimport rateLimit from 'express-rate-limit';\nimport { ErrorHandler } from './errors';\n\n// -------------------------------------------------------------\n// Create the rate-limiter instances once at module load-time so\n// that the hit counters are shared across every incoming request.\n// -------------------------------------------------------------\n\nexport const ipLimiter: (\n req: Request,\n res: Response,\n next: NextFunction\n) => unknown = rateLimit({\n windowMs: 60 * 1000, // 1-minute window\n limit: 500, // 500 requests / IP / window\n standardHeaders: 'draft-8',\n legacyHeaders: false,\n // Use a custom key generator that handles proxy headers securely\n keyGenerator: (req) => {\n // Use the real IP address, falling back to socket remote address\n return req.ip ?? req.socket?.remoteAddress ?? 'unknown';\n },\n handler: (req, res, _next) => {\n const { limit, remaining, resetTime } = (req as any).rateLimit;\n\n ErrorHandler.handleGenericErrorResponse(res, 'RATE_LIMIT_EXCEEDED', {\n limit: `${limit} per minute`,\n retryAfter: Math.ceil((resetTime!.getTime() - Date.now()) / 1000),\n remaining,\n });\n },\n});\n\nexport const unauthenticatedChatBotLimiter: (\n req: Request,\n res: Response,\n next: NextFunction\n) => any = rateLimit({\n windowMs: 60 * 60 * 1000, // 1-hour window\n limit: 3, // 3 requests / IP / window\n standardHeaders: 'draft-8',\n skip: (_req, res) => Boolean(res.locals.user), // authenticated? then skip\n legacyHeaders: false,\n // Use a custom key generator that handles proxy headers securely\n keyGenerator: (req) => {\n // Use the real IP address, falling back to socket remote address\n return req.ip ?? req.socket?.remoteAddress ?? 'unknown';\n },\n handler: (req, res) => {\n const { limit, remaining, resetTime } = (req as any).rateLimit;\n\n ErrorHandler.handleGenericErrorResponse(\n res,\n 'RATE_LIMIT_EXCEEDED_UNAUTHENTICATED',\n {\n limit: `${limit} per hour`,\n retryAfter: Math.ceil((resetTime!.getTime() - Date.now()) / 1000),\n remaining,\n }\n );\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,gCAAsB;AACtB,oBAA6B;AAOtB,MAAM,gBAIE,0BAAAA,SAAU;AAAA,EACvB,UAAU,KAAK;AAAA;AAAA,EACf,OAAO;AAAA;AAAA,EACP,iBAAiB;AAAA,EACjB,eAAe;AAAA;AAAA,EAEf,cAAc,CAAC,QAAQ;AAErB,WAAO,IAAI,MAAM,IAAI,QAAQ,iBAAiB;AAAA,EAChD;AAAA,EACA,SAAS,CAAC,KAAK,KAAK,UAAU;AAC5B,UAAM,EAAE,OAAO,WAAW,UAAU,IAAK,IAAY;AAErD,+BAAa,2BAA2B,KAAK,uBAAuB;AAAA,MAClE,OAAO,GAAG,KAAK;AAAA,MACf,YAAY,KAAK,MAAM,UAAW,QAAQ,IAAI,KAAK,IAAI,KAAK,GAAI;AAAA,MAChE;AAAA,IACF,CAAC;AAAA,EACH;AACF,CAAC;AAEM,MAAM,oCAIF,0BAAAA,SAAU;AAAA,EACnB,UAAU,KAAK,KAAK;AAAA;AAAA,EACpB,OAAO;AAAA;AAAA,EACP,iBAAiB;AAAA,EACjB,MAAM,CAAC,MAAM,QAAQ,QAAQ,IAAI,OAAO,IAAI;AAAA;AAAA,EAC5C,eAAe;AAAA;AAAA,EAEf,cAAc,CAAC,QAAQ;AAErB,WAAO,IAAI,MAAM,IAAI,QAAQ,iBAAiB;AAAA,EAChD;AAAA,EACA,SAAS,CAAC,KAAK,QAAQ;AACrB,UAAM,EAAE,OAAO,WAAW,UAAU,IAAK,IAAY;AAErD,+BAAa;AAAA,MACX;AAAA,MACA;AAAA,MACA;AAAA,QACE,OAAO,GAAG,KAAK;AAAA,QACf,YAAY,KAAK,MAAM,UAAW,QAAQ,IAAI,KAAK,IAAI,KAAK,GAAI;AAAA,QAChE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF,CAAC;","names":["rateLimit"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/schemas/dictionary.schema.ts"],"sourcesContent":["import type {\n DictionarySchema,\n VersionedContentEl,\n} from '@/types/dictionary.types';\nimport { Schema } from 'mongoose';\n\nconst versionedContentElSchema = new Schema<VersionedContentEl>(\n {\n name: {\n type: String,\n },\n description: {\n type: String,\n },\n content: {\n type: Schema.Types.Mixed,\n required: true,\n },\n },\n {\n timestamps: true,\n }\n);\n\nexport const dictionarySchema = new Schema<DictionarySchema>(\n {\n projectIds: {\n type: [Schema.Types.ObjectId],\n ref: 'Project',\n required: true,\n },\n key: {\n type: String,\n required: true,\n },\n title: {\n type: String,\n default: '',\n },\n description: {\n type: String,\n default: '',\n },\n tags: {\n type: [String],\n default: [],\n },\n content: {\n type: Map,\n of: versionedContentElSchema,\n required: true,\n default: null,\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n filePath: {\n type: Map,\n of: String,\n default: null,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AAIA,SAAS,cAAc;AAEvB,MAAM,2BAA2B,IAAI;AAAA,EACnC;AAAA,IACE,MAAM;AAAA,MACJ,MAAM;AAAA,IACR;AAAA,IACA,aAAa;AAAA,MACX,MAAM;AAAA,IACR;AAAA,IACA,SAAS;AAAA,MACP,MAAM,OAAO,MAAM;AAAA,MACnB,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,EACd;AACF;AAEO,MAAM,mBAAmB,IAAI;AAAA,EAClC;AAAA,IACE,YAAY;AAAA,MACV,MAAM,CAAC,OAAO,MAAM,QAAQ;AAAA,MAC5B,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,KAAK;AAAA,MACH,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS;AAAA,IACX;AAAA,IACA,aAAa;AAAA,MACX,MAAM;AAAA,MACN,SAAS;AAAA,IACX;AAAA,IACA,MAAM;AAAA,MACJ,MAAM,CAAC,MAAM;AAAA,MACb,SAAS,CAAC;AAAA,IACZ;AAAA,IACA,SAAS;AAAA,MACP,MAAM;AAAA,MACN,IAAI;AAAA,MACJ,UAAU;AAAA,MACV,SAAS;AAAA,IACX;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,UAAU;AAAA,MACR,MAAM;AAAA,MACN,IAAI;AAAA,MACJ,SAAS;AAAA,IACX;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,
|
|
1
|
+
{"version":3,"sources":["../../../src/schemas/dictionary.schema.ts"],"sourcesContent":["import type {\n DictionarySchema,\n VersionedContentEl,\n} from '@/types/dictionary.types';\nimport { Schema } from 'mongoose';\n\nconst versionedContentElSchema = new Schema<VersionedContentEl>(\n {\n name: {\n type: String,\n },\n description: {\n type: String,\n },\n content: {\n type: Schema.Types.Mixed,\n required: true,\n },\n },\n {\n timestamps: true,\n }\n);\n\nexport const dictionarySchema = new Schema<DictionarySchema>(\n {\n projectIds: {\n type: [Schema.Types.ObjectId],\n ref: 'Project',\n required: true,\n },\n key: {\n type: String,\n required: true,\n },\n title: {\n type: String,\n default: '',\n },\n description: {\n type: String,\n default: '',\n },\n tags: {\n type: [String],\n default: [],\n },\n content: {\n type: Map,\n of: versionedContentElSchema,\n required: true,\n default: null,\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n filePath: {\n type: Map,\n of: String,\n default: null,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret: any) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret: any) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AAIA,SAAS,cAAc;AAEvB,MAAM,2BAA2B,IAAI;AAAA,EACnC;AAAA,IACE,MAAM;AAAA,MACJ,MAAM;AAAA,IACR;AAAA,IACA,aAAa;AAAA,MACX,MAAM;AAAA,IACR;AAAA,IACA,SAAS;AAAA,MACP,MAAM,OAAO,MAAM;AAAA,MACnB,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,EACd;AACF;AAEO,MAAM,mBAAmB,IAAI;AAAA,EAClC;AAAA,IACE,YAAY;AAAA,MACV,MAAM,CAAC,OAAO,MAAM,QAAQ;AAAA,MAC5B,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,KAAK;AAAA,MACH,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS;AAAA,IACX;AAAA,IACA,aAAa;AAAA,MACX,MAAM;AAAA,MACN,SAAS;AAAA,IACX;AAAA,IACA,MAAM;AAAA,MACJ,MAAM,CAAC,MAAM;AAAA,MACb,SAAS,CAAC;AAAA,IACZ;AAAA,IACA,SAAS;AAAA,MACP,MAAM;AAAA,MACN,IAAI;AAAA,MACJ,UAAU;AAAA,MACV,SAAS;AAAA,IACX;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,UAAU;AAAA,MACR,MAAM;AAAA,MACN,IAAI;AAAA,MACJ,SAAS;AAAA,IACX;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI,IAAI,SAAS;AAC1B,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,UAAU;AAAA,MACV,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI;AACb,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/schemas/discussion.schema.ts"],"sourcesContent":["import type { DiscussionSchema } from '@/types/discussion.types';\nimport { Schema } from 'mongoose';\n\nexport const discussionSchema = new Schema<DiscussionSchema>(\n {\n discutionId: {\n type: String,\n required: true,\n unique: true,\n },\n messages: [\n {\n role: {\n type: String,\n required: true,\n enum: ['user', 'assistant', 'system'],\n },\n content: {\n type: String,\n required: true,\n },\n timestamp: {\n type: Date,\n default: Date.now,\n },\n },\n ],\n userId: {\n type: Schema.Types.ObjectId,\n ref: 'user',\n required: true,\n },\n projectId: {\n type: Schema.Types.ObjectId,\n ref: 'project',\n required: true,\n },\n organizationId: {\n type: Schema.Types.ObjectId,\n ref: 'organization',\n required: true,\n },\n title: {\n type: String,\n required: false,\n },\n isArchived: {\n type: Boolean,\n default: false,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AACA,SAAS,cAAc;AAEhB,MAAM,mBAAmB,IAAI;AAAA,EAClC;AAAA,IACE,aAAa;AAAA,MACX,MAAM;AAAA,MACN,UAAU;AAAA,MACV,QAAQ;AAAA,IACV;AAAA,IACA,UAAU;AAAA,MACR;AAAA,QACE,MAAM;AAAA,UACJ,MAAM;AAAA,UACN,UAAU;AAAA,UACV,MAAM,CAAC,QAAQ,aAAa,QAAQ;AAAA,QACtC;AAAA,QACA,SAAS;AAAA,UACP,MAAM;AAAA,UACN,UAAU;AAAA,QACZ;AAAA,QACA,WAAW;AAAA,UACT,MAAM;AAAA,UACN,SAAS,KAAK;AAAA,QAChB;AAAA,MACF;AAAA,IACF;AAAA,IACA,QAAQ;AAAA,MACN,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,gBAAgB;AAAA,MACd,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,YAAY;AAAA,MACV,MAAM;AAAA,MACN,SAAS;AAAA,IACX;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,
|
|
1
|
+
{"version":3,"sources":["../../../src/schemas/discussion.schema.ts"],"sourcesContent":["import type { DiscussionSchema } from '@/types/discussion.types';\nimport { Schema } from 'mongoose';\n\nexport const discussionSchema = new Schema<DiscussionSchema>(\n {\n discutionId: {\n type: String,\n required: true,\n unique: true,\n },\n messages: [\n {\n role: {\n type: String,\n required: true,\n enum: ['user', 'assistant', 'system'],\n },\n content: {\n type: String,\n required: true,\n },\n timestamp: {\n type: Date,\n default: Date.now,\n },\n },\n ],\n userId: {\n type: Schema.Types.ObjectId,\n ref: 'user',\n required: true,\n },\n projectId: {\n type: Schema.Types.ObjectId,\n ref: 'project',\n required: true,\n },\n organizationId: {\n type: Schema.Types.ObjectId,\n ref: 'organization',\n required: true,\n },\n title: {\n type: String,\n required: false,\n },\n isArchived: {\n type: Boolean,\n default: false,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret: any) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret: any) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AACA,SAAS,cAAc;AAEhB,MAAM,mBAAmB,IAAI;AAAA,EAClC;AAAA,IACE,aAAa;AAAA,MACX,MAAM;AAAA,MACN,UAAU;AAAA,MACV,QAAQ;AAAA,IACV;AAAA,IACA,UAAU;AAAA,MACR;AAAA,QACE,MAAM;AAAA,UACJ,MAAM;AAAA,UACN,UAAU;AAAA,UACV,MAAM,CAAC,QAAQ,aAAa,QAAQ;AAAA,QACtC;AAAA,QACA,SAAS;AAAA,UACP,MAAM;AAAA,UACN,UAAU;AAAA,QACZ;AAAA,QACA,WAAW;AAAA,UACT,MAAM;AAAA,UACN,SAAS,KAAK;AAAA,QAChB;AAAA,MACF;AAAA,IACF;AAAA,IACA,QAAQ;AAAA,MACN,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,gBAAgB;AAAA,MACd,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,YAAY;AAAA,MACV,MAAM;AAAA,MACN,SAAS;AAAA,IACX;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI,IAAI,SAAS;AAC1B,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,UAAU;AAAA,MACV,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI;AACb,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/schemas/oAuth2.schema.ts"],"sourcesContent":["import type { User } from '@/types/user.types';\nimport { Schema } from 'mongoose';\nimport type { Client, Token as TokenType } from 'oauth2-server';\n\nexport type Token = Omit<TokenType, 'client' | 'user'> & {\n clientId: Client['id'];\n userId: User['id'];\n};\n\nexport const accessTokenSchema = new Schema<Token>(\n {\n accessToken: {\n type: String,\n required: true,\n },\n accessTokenExpiresAt: {\n type: Date,\n },\n clientId: {\n type: String,\n ref: 'Project',\n required: true,\n },\n userId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n\naccessTokenSchema.index(\n { createdAt: 1 },\n {\n expireAfterSeconds: 60 * 60 * 24 * 10, // 10 Days\n }\n);\n"],"mappings":"AACA,SAAS,cAAc;AAQhB,MAAM,oBAAoB,IAAI;AAAA,EACnC;AAAA,IACE,aAAa;AAAA,MACX,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,sBAAsB;AAAA,MACpB,MAAM;AAAA,IACR;AAAA,IACA,UAAU;AAAA,MACR,MAAM;AAAA,MACN,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,QAAQ;AAAA,MACN,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,
|
|
1
|
+
{"version":3,"sources":["../../../src/schemas/oAuth2.schema.ts"],"sourcesContent":["import type { User } from '@/types/user.types';\nimport { Schema } from 'mongoose';\nimport type { Client, Token as TokenType } from 'oauth2-server';\n\nexport type Token = Omit<TokenType, 'client' | 'user'> & {\n clientId: Client['id'];\n userId: User['id'];\n};\n\nexport const accessTokenSchema = new Schema<Token>(\n {\n accessToken: {\n type: String,\n required: true,\n },\n accessTokenExpiresAt: {\n type: Date,\n },\n clientId: {\n type: String,\n ref: 'Project',\n required: true,\n },\n userId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret: any) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret: any) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n\naccessTokenSchema.index(\n { createdAt: 1 },\n {\n expireAfterSeconds: 60 * 60 * 24 * 10, // 10 Days\n }\n);\n"],"mappings":"AACA,SAAS,cAAc;AAQhB,MAAM,oBAAoB,IAAI;AAAA,EACnC;AAAA,IACE,aAAa;AAAA,MACX,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,sBAAsB;AAAA,MACpB,MAAM;AAAA,IACR;AAAA,IACA,UAAU;AAAA,MACR,MAAM;AAAA,MACN,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,QAAQ;AAAA,MACN,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI,IAAI,SAAS;AAC1B,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,UAAU;AAAA,MACV,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI;AACb,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,EACF;AACF;AAEA,kBAAkB;AAAA,EAChB,EAAE,WAAW,EAAE;AAAA,EACf;AAAA,IACE,oBAAoB,KAAK,KAAK,KAAK;AAAA;AAAA,EACrC;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/schemas/organization.schema.ts"],"sourcesContent":["import { OrganizationSchema } from '@/export';\nimport {\n MEMBERS_MIN_LENGTH,\n NAME_MAX_LENGTH,\n NAME_MIN_LENGTH,\n} from '@utils/validation/validateOrganization';\nimport { Schema } from 'mongoose';\nimport { planSchema } from './plans.schema';\n\nexport const organizationSchema = new Schema<OrganizationSchema>(\n {\n name: {\n type: String,\n required: true,\n minlength: NAME_MIN_LENGTH,\n maxlength: NAME_MAX_LENGTH,\n },\n membersIds: {\n type: [Schema.Types.ObjectId],\n ref: 'User',\n required: true,\n minlength: MEMBERS_MIN_LENGTH,\n },\n adminsIds: {\n type: [Schema.Types.ObjectId],\n ref: 'User',\n required: true,\n minlength: MEMBERS_MIN_LENGTH,\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n plan: {\n type: planSchema,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n\n// Add virtual field for id\norganizationSchema.virtual('id').get(function () {\n return this._id.toString();\n});\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAEpB,MAAM,qBAAqB,IAAI;AAAA,EACpC;AAAA,IACE,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,UAAU;AAAA,MACV,WAAW;AAAA,MACX,WAAW;AAAA,IACb;AAAA,IACA,YAAY;AAAA,MACV,MAAM,CAAC,OAAO,MAAM,QAAQ;AAAA,MAC5B,KAAK;AAAA,MACL,UAAU;AAAA,MACV,WAAW;AAAA,IACb;AAAA,IACA,WAAW;AAAA,MACT,MAAM,CAAC,OAAO,MAAM,QAAQ;AAAA,MAC5B,KAAK;AAAA,MACL,UAAU;AAAA,MACV,WAAW;AAAA,IACb;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,MAAM;AAAA,MACJ,MAAM;AAAA,IACR;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,
|
|
1
|
+
{"version":3,"sources":["../../../src/schemas/organization.schema.ts"],"sourcesContent":["import { OrganizationSchema } from '@/export';\nimport {\n MEMBERS_MIN_LENGTH,\n NAME_MAX_LENGTH,\n NAME_MIN_LENGTH,\n} from '@utils/validation/validateOrganization';\nimport { Schema } from 'mongoose';\nimport { planSchema } from './plans.schema';\n\nexport const organizationSchema = new Schema<OrganizationSchema>(\n {\n name: {\n type: String,\n required: true,\n minlength: NAME_MIN_LENGTH,\n maxlength: NAME_MAX_LENGTH,\n },\n membersIds: {\n type: [Schema.Types.ObjectId],\n ref: 'User',\n required: true,\n minlength: MEMBERS_MIN_LENGTH,\n },\n adminsIds: {\n type: [Schema.Types.ObjectId],\n ref: 'User',\n required: true,\n minlength: MEMBERS_MIN_LENGTH,\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n plan: {\n type: planSchema,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret: any) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret: any) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n\n// Add virtual field for id\norganizationSchema.virtual('id').get(function () {\n return this._id.toString();\n});\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAEpB,MAAM,qBAAqB,IAAI;AAAA,EACpC;AAAA,IACE,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,UAAU;AAAA,MACV,WAAW;AAAA,MACX,WAAW;AAAA,IACb;AAAA,IACA,YAAY;AAAA,MACV,MAAM,CAAC,OAAO,MAAM,QAAQ;AAAA,MAC5B,KAAK;AAAA,MACL,UAAU;AAAA,MACV,WAAW;AAAA,IACb;AAAA,IACA,WAAW;AAAA,MACT,MAAM,CAAC,OAAO,MAAM,QAAQ;AAAA,MAC5B,KAAK;AAAA,MACL,UAAU;AAAA,MACV,WAAW;AAAA,IACb;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,MAAM;AAAA,MACJ,MAAM;AAAA,IACR;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI,IAAI,SAAS;AAC1B,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,UAAU;AAAA,MACV,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI;AACb,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,EACF;AACF;AAGA,mBAAmB,QAAQ,IAAI,EAAE,IAAI,WAAY;AAC/C,SAAO,KAAK,IAAI,SAAS;AAC3B,CAAC;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/schemas/plans.schema.ts"],"sourcesContent":["import type { PlanSchema } from '@/types/plan.types';\nimport { Schema } from 'mongoose';\n\nexport const planSchema = new Schema<PlanSchema>(\n {\n type: {\n type: String,\n required: true,\n enum: ['PREMIUM', 'ENTERPRISE'],\n },\n period: {\n type: String,\n required: true,\n enum: ['MONTHLY', 'YEARLY'],\n default: 'MONTHLY',\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n subscriptionId: {\n type: String,\n required: true,\n },\n customerId: {\n type: String,\n required: true,\n },\n priceId: {\n type: String,\n required: true,\n },\n status: {\n type: String,\n required: true,\n enum: [\n 'active',\n 'canceled',\n 'past_due',\n 'unpaid',\n 'incomplete',\n 'incomplete_expired',\n 'paused',\n 'trialing',\n ],\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AACA,SAAS,cAAc;AAEhB,MAAM,aAAa,IAAI;AAAA,EAC5B;AAAA,IACE,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,UAAU;AAAA,MACV,MAAM,CAAC,WAAW,YAAY;AAAA,IAChC;AAAA,IACA,QAAQ;AAAA,MACN,MAAM;AAAA,MACN,UAAU;AAAA,MACV,MAAM,CAAC,WAAW,QAAQ;AAAA,MAC1B,SAAS;AAAA,IACX;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,gBAAgB;AAAA,MACd,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,YAAY;AAAA,MACV,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,SAAS;AAAA,MACP,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,QAAQ;AAAA,MACN,MAAM;AAAA,MACN,UAAU;AAAA,MACV,MAAM;AAAA,QACJ;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,
|
|
1
|
+
{"version":3,"sources":["../../../src/schemas/plans.schema.ts"],"sourcesContent":["import type { PlanSchema } from '@/types/plan.types';\nimport { Schema } from 'mongoose';\n\nexport const planSchema = new Schema<PlanSchema>(\n {\n type: {\n type: String,\n required: true,\n enum: ['PREMIUM', 'ENTERPRISE'],\n },\n period: {\n type: String,\n required: true,\n enum: ['MONTHLY', 'YEARLY'],\n default: 'MONTHLY',\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n subscriptionId: {\n type: String,\n required: true,\n },\n customerId: {\n type: String,\n required: true,\n },\n priceId: {\n type: String,\n required: true,\n },\n status: {\n type: String,\n required: true,\n enum: [\n 'active',\n 'canceled',\n 'past_due',\n 'unpaid',\n 'incomplete',\n 'incomplete_expired',\n 'paused',\n 'trialing',\n ],\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret: any) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret: any) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AACA,SAAS,cAAc;AAEhB,MAAM,aAAa,IAAI;AAAA,EAC5B;AAAA,IACE,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,UAAU;AAAA,MACV,MAAM,CAAC,WAAW,YAAY;AAAA,IAChC;AAAA,IACA,QAAQ;AAAA,MACN,MAAM;AAAA,MACN,UAAU;AAAA,MACV,MAAM,CAAC,WAAW,QAAQ;AAAA,MAC1B,SAAS;AAAA,IACX;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,gBAAgB;AAAA,MACd,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,YAAY;AAAA,MACV,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,SAAS;AAAA,MACP,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,QAAQ;AAAA,MACN,MAAM;AAAA,MACN,UAAU;AAAA,MACV,MAAM;AAAA,QACJ;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI,IAAI,SAAS;AAC1B,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,UAAU;AAAA,MACV,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI;AACb,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/schemas/project.schema.ts"],"sourcesContent":["import type {\n OAuth2Access,\n Project,\n ProjectSchema,\n} from '@/types/project.types';\nimport { Locales } from '@intlayer/config';\nimport type { RenameId } from '@utils/mongoDB/types';\nimport {\n MEMBERS_MIN_LENGTH,\n NAME_MAX_LENGTH,\n NAME_MIN_LENGTH,\n} from '@utils/validation/validateProject';\nimport { Schema } from 'mongoose';\n\n// Define the oAuth2Access subdocument schema with timestamps\nconst oAuth2AccessSchema = new Schema<RenameId<OAuth2Access>>(\n {\n clientId: { type: String, required: true },\n clientSecret: { type: String, required: true },\n userId: { type: Schema.Types.ObjectId, ref: 'User', required: true },\n name: { type: String, required: true },\n expiresAt: { type: Date },\n accessToken: { type: [String], required: true, default: [] },\n grants: { type: [String], required: true, default: [] },\n },\n {\n timestamps: true,\n }\n);\n\nconst projectConfigSchema = new Schema<Project['configuration']>(\n {\n internationalization: {\n locales: {\n type: [String],\n enum: Object.values(Locales),\n required: true,\n },\n defaultLocale: {\n type: String,\n enum: Object.values(Locales),\n },\n },\n editor: {\n applicationURL: {\n type: String,\n },\n cmsURL: {\n type: String,\n },\n },\n },\n {\n _id: false, // Prevents the generation of an _id field for this subdocument\n }\n);\n\nexport const projectSchema = new Schema<ProjectSchema>(\n {\n organizationId: {\n type: Schema.Types.ObjectId,\n ref: 'Organization',\n required: true,\n },\n name: {\n type: String,\n required: true,\n minlength: NAME_MIN_LENGTH,\n maxlength: NAME_MAX_LENGTH,\n },\n configuration: projectConfigSchema,\n oAuth2Access: [oAuth2AccessSchema],\n membersIds: {\n type: [Schema.Types.ObjectId],\n ref: 'User',\n required: true,\n minlength: MEMBERS_MIN_LENGTH,\n },\n adminsIds: {\n type: [Schema.Types.ObjectId],\n ref: 'User',\n required: true,\n minlength: MEMBERS_MIN_LENGTH,\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AAKA,SAAS,eAAe;AAExB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AAGvB,MAAM,qBAAqB,IAAI;AAAA,EAC7B;AAAA,IACE,UAAU,EAAE,MAAM,QAAQ,UAAU,KAAK;AAAA,IACzC,cAAc,EAAE,MAAM,QAAQ,UAAU,KAAK;AAAA,IAC7C,QAAQ,EAAE,MAAM,OAAO,MAAM,UAAU,KAAK,QAAQ,UAAU,KAAK;AAAA,IACnE,MAAM,EAAE,MAAM,QAAQ,UAAU,KAAK;AAAA,IACrC,WAAW,EAAE,MAAM,KAAK;AAAA,IACxB,aAAa,EAAE,MAAM,CAAC,MAAM,GAAG,UAAU,MAAM,SAAS,CAAC,EAAE;AAAA,IAC3D,QAAQ,EAAE,MAAM,CAAC,MAAM,GAAG,UAAU,MAAM,SAAS,CAAC,EAAE;AAAA,EACxD;AAAA,EACA;AAAA,IACE,YAAY;AAAA,EACd;AACF;AAEA,MAAM,sBAAsB,IAAI;AAAA,EAC9B;AAAA,IACE,sBAAsB;AAAA,MACpB,SAAS;AAAA,QACP,MAAM,CAAC,MAAM;AAAA,QACb,MAAM,OAAO,OAAO,OAAO;AAAA,QAC3B,UAAU;AAAA,MACZ;AAAA,MACA,eAAe;AAAA,QACb,MAAM;AAAA,QACN,MAAM,OAAO,OAAO,OAAO;AAAA,MAC7B;AAAA,IACF;AAAA,IACA,QAAQ;AAAA,MACN,gBAAgB;AAAA,QACd,MAAM;AAAA,MACR;AAAA,MACA,QAAQ;AAAA,QACN,MAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAAA,EACA;AAAA,IACE,KAAK;AAAA;AAAA,EACP;AACF;AAEO,MAAM,gBAAgB,IAAI;AAAA,EAC/B;AAAA,IACE,gBAAgB;AAAA,MACd,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,UAAU;AAAA,MACV,WAAW;AAAA,MACX,WAAW;AAAA,IACb;AAAA,IACA,eAAe;AAAA,IACf,cAAc,CAAC,kBAAkB;AAAA,IACjC,YAAY;AAAA,MACV,MAAM,CAAC,OAAO,MAAM,QAAQ;AAAA,MAC5B,KAAK;AAAA,MACL,UAAU;AAAA,MACV,WAAW;AAAA,IACb;AAAA,IACA,WAAW;AAAA,MACT,MAAM,CAAC,OAAO,MAAM,QAAQ;AAAA,MAC5B,KAAK;AAAA,MACL,UAAU;AAAA,MACV,WAAW;AAAA,IACb;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,
|
|
1
|
+
{"version":3,"sources":["../../../src/schemas/project.schema.ts"],"sourcesContent":["import type {\n OAuth2Access,\n Project,\n ProjectSchema,\n} from '@/types/project.types';\nimport { Locales } from '@intlayer/config';\nimport type { RenameId } from '@utils/mongoDB/types';\nimport {\n MEMBERS_MIN_LENGTH,\n NAME_MAX_LENGTH,\n NAME_MIN_LENGTH,\n} from '@utils/validation/validateProject';\nimport { Schema } from 'mongoose';\n\n// Define the oAuth2Access subdocument schema with timestamps\nconst oAuth2AccessSchema = new Schema<RenameId<OAuth2Access>>(\n {\n clientId: { type: String, required: true },\n clientSecret: { type: String, required: true },\n userId: { type: Schema.Types.ObjectId, ref: 'User', required: true },\n name: { type: String, required: true },\n expiresAt: { type: Date },\n accessToken: { type: [String], required: true, default: [] },\n grants: { type: [String], required: true, default: [] },\n },\n {\n timestamps: true,\n }\n);\n\nconst projectConfigSchema = new Schema<Project['configuration']>(\n {\n internationalization: {\n locales: {\n type: [String],\n enum: Object.values(Locales),\n required: true,\n },\n defaultLocale: {\n type: String,\n enum: Object.values(Locales),\n },\n },\n editor: {\n applicationURL: {\n type: String,\n },\n cmsURL: {\n type: String,\n },\n },\n },\n {\n _id: false, // Prevents the generation of an _id field for this subdocument\n }\n);\n\nexport const projectSchema = new Schema<ProjectSchema>(\n {\n organizationId: {\n type: Schema.Types.ObjectId,\n ref: 'Organization',\n required: true,\n },\n name: {\n type: String,\n required: true,\n minlength: NAME_MIN_LENGTH,\n maxlength: NAME_MAX_LENGTH,\n },\n configuration: projectConfigSchema,\n oAuth2Access: [oAuth2AccessSchema],\n membersIds: {\n type: [Schema.Types.ObjectId],\n ref: 'User',\n required: true,\n minlength: MEMBERS_MIN_LENGTH,\n },\n adminsIds: {\n type: [Schema.Types.ObjectId],\n ref: 'User',\n required: true,\n minlength: MEMBERS_MIN_LENGTH,\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret: any) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret: any) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AAKA,SAAS,eAAe;AAExB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AAGvB,MAAM,qBAAqB,IAAI;AAAA,EAC7B;AAAA,IACE,UAAU,EAAE,MAAM,QAAQ,UAAU,KAAK;AAAA,IACzC,cAAc,EAAE,MAA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AW;AAAA,IACb;AAAA,IACA,WAAW;AAAA,MACT,MAAM,CAAC,OAAO,MAAM,QAAQ;AAAA,MAC5B,KAAK;AAAA,MACL,UAAU;AAAA,MACV,WAAW;AAAA,IACb;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI,IAAI,SAAS;AAC1B,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,UAAU;AAAA,MACV,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI;AACb,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/schemas/session.schema.ts"],"sourcesContent":["import { SessionSchema } from '@/export';\nimport { Schema } from 'mongoose';\n\nexport const sessionSchema = new Schema<SessionSchema>(\n {\n activeOrganizationId: {\n type: Schema.Types.ObjectId,\n ref: 'Organization',\n required: false,\n },\n activeProjectId: {\n type: Schema.Types.ObjectId,\n ref: 'Project',\n required: false,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AACA,SAAS,cAAc;AAEhB,MAAM,gBAAgB,IAAI;AAAA,EAC/B;AAAA,IACE,sBAAsB;AAAA,MACpB,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,iBAAiB;AAAA,MACf,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,
|
|
1
|
+
{"version":3,"sources":["../../../src/schemas/session.schema.ts"],"sourcesContent":["import { SessionSchema } from '@/export';\nimport { Schema } from 'mongoose';\n\nexport const sessionSchema = new Schema<SessionSchema>(\n {\n activeOrganizationId: {\n type: Schema.Types.ObjectId,\n ref: 'Organization',\n required: false,\n },\n activeProjectId: {\n type: Schema.Types.ObjectId,\n ref: 'Project',\n required: false,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret: any) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret: any) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AACA,SAAS,cAAc;AAEhB,MAAM,gBAAgB,IAAI;AAAA,EAC/B;AAAA,IACE,sBAAsB;AAAA,MACpB,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,iBAAiB;AAAA,MACf,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI,IAAI,SAAS;AAC1B,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,UAAU;AAAA,MACV,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI;AACb,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/schemas/tag.schema.ts"],"sourcesContent":["import type { TagSchema } from '@/types/tag.types';\nimport {\n KEY_MAX_LENGTH,\n KEY_MIN_LENGTH,\n NAME_MAX_LENGTH,\n NAME_MIN_LENGTH,\n} from '@utils/validation/validateTag';\nimport { Schema } from 'mongoose';\n\nexport const tagSchema = new Schema<TagSchema>(\n {\n organizationId: {\n type: Schema.Types.ObjectId,\n ref: 'Organization',\n required: true,\n },\n projectId: {\n type: Schema.Types.ObjectId,\n ref: 'Project',\n required: true,\n },\n key: {\n type: String,\n required: true,\n minlength: KEY_MIN_LENGTH,\n maxlength: KEY_MAX_LENGTH,\n },\n name: {\n type: String,\n minlength: NAME_MIN_LENGTH,\n maxlength: NAME_MAX_LENGTH,\n },\n description: {\n type: String,\n },\n instructions: {\n type: String,\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AAEhB,MAAM,YAAY,IAAI;AAAA,EAC3B;AAAA,IACE,gBAAgB;AAAA,MACd,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,KAAK;AAAA,MACH,MAAM;AAAA,MACN,UAAU;AAAA,MACV,WAAW;AAAA,MACX,WAAW;AAAA,IACb;AAAA,IACA,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,WAAW;AAAA,MACX,WAAW;AAAA,IACb;AAAA,IACA,aAAa;AAAA,MACX,MAAM;AAAA,IACR;AAAA,IACA,cAAc;AAAA,MACZ,MAAM;AAAA,IACR;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,
|
|
1
|
+
{"version":3,"sources":["../../../src/schemas/tag.schema.ts"],"sourcesContent":["import type { TagSchema } from '@/types/tag.types';\nimport {\n KEY_MAX_LENGTH,\n KEY_MIN_LENGTH,\n NAME_MAX_LENGTH,\n NAME_MIN_LENGTH,\n} from '@utils/validation/validateTag';\nimport { Schema } from 'mongoose';\n\nexport const tagSchema = new Schema<TagSchema>(\n {\n organizationId: {\n type: Schema.Types.ObjectId,\n ref: 'Organization',\n required: true,\n },\n projectId: {\n type: Schema.Types.ObjectId,\n ref: 'Project',\n required: true,\n },\n key: {\n type: String,\n required: true,\n minlength: KEY_MIN_LENGTH,\n maxlength: KEY_MAX_LENGTH,\n },\n name: {\n type: String,\n minlength: NAME_MIN_LENGTH,\n maxlength: NAME_MAX_LENGTH,\n },\n description: {\n type: String,\n },\n instructions: {\n type: String,\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret: any) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret: any) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AAEhB,MAAM,YAAY,IAAI;AAAA,EAC3B;AAAA,IACE,gBAAgB;AAAA,MACd,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,KAAK;AAAA,MACH,MAAM;AAAA,MACN,UAAU;AAAA,MACV,WAAW;AAAA,MACX,WAAW;AAAA,IACb;AAAA,IACA,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,WAAW;AAAA,MACX,WAAW;AAAA,IACb;AAAA,IACA,aAAa;AAAA,MACX,MAAM;AAAA,IACR;AAAA,IACA,cAAc;AAAA,MACZ,MAAM;AAAA,IACR;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI,IAAI,SAAS;AAC1B,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,UAAU;AAAA,MACV,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI;AACb,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/schemas/user.schema.ts"],"sourcesContent":["import type { UserSchema } from '@/types/user.types';\nimport {\n NAMES_MAX_LENGTH,\n NAMES_MIN_LENGTH,\n} from '@utils/validation/validateUser';\nimport { Schema } from 'mongoose';\nimport validator from 'validator';\n\nexport const userSchema = new Schema<UserSchema>(\n {\n email: {\n type: String,\n required: true,\n unique: true,\n validate: [validator.isEmail, 'Please fill a valid email address'],\n lowercase: true,\n trim: true,\n },\n name: {\n type: String,\n maxlength: NAMES_MAX_LENGTH,\n minlength: NAMES_MIN_LENGTH,\n },\n phone: {\n type: String,\n maxlength: 20,\n },\n\n customerId: {\n type: String,\n required: false,\n },\n\n emailsList: {\n type: {\n newsLetter: {\n type: Boolean,\n default: false,\n },\n },\n required: false,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AACvB,OAAO,eAAe;AAEf,MAAM,aAAa,IAAI;AAAA,EAC5B;AAAA,IACE,OAAO;AAAA,MACL,MAAM;AAAA,MACN,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,UAAU,CAAC,UAAU,SAAS,mCAAmC;AAAA,MACjE,WAAW;AAAA,MACX,MAAM;AAAA,IACR;AAAA,IACA,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,WAAW;AAAA,MACX,WAAW;AAAA,IACb;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,MACN,WAAW;AAAA,IACb;AAAA,IAEA,YAAY;AAAA,MACV,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IAEA,YAAY;AAAA,MACV,MAAM;AAAA,QACJ,YAAY;AAAA,UACV,MAAM;AAAA,UACN,SAAS;AAAA,QACX;AAAA,MACF;AAAA,MACA,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,
|
|
1
|
+
{"version":3,"sources":["../../../src/schemas/user.schema.ts"],"sourcesContent":["import type { UserSchema } from '@/types/user.types';\nimport {\n NAMES_MAX_LENGTH,\n NAMES_MIN_LENGTH,\n} from '@utils/validation/validateUser';\nimport { Schema } from 'mongoose';\nimport validator from 'validator';\n\nexport const userSchema = new Schema<UserSchema>(\n {\n email: {\n type: String,\n required: true,\n unique: true,\n validate: [validator.isEmail, 'Please fill a valid email address'],\n lowercase: true,\n trim: true,\n },\n name: {\n type: String,\n maxlength: NAMES_MAX_LENGTH,\n minlength: NAMES_MIN_LENGTH,\n },\n phone: {\n type: String,\n maxlength: 20,\n },\n\n customerId: {\n type: String,\n required: false,\n },\n\n emailsList: {\n type: {\n newsLetter: {\n type: Boolean,\n default: false,\n },\n },\n required: false,\n },\n },\n {\n timestamps: true,\n\n toJSON: {\n virtuals: true, // keep the automatic `id` getter\n versionKey: false, // drop __v\n transform(doc, ret: any) {\n ret.id = ret._id.toString(); // convert _id to id\n delete ret._id; // remove _id\n },\n },\n toObject: {\n virtuals: true,\n transform(doc, ret: any) {\n ret.id = ret._id; // convert _id to id\n delete ret._id; // remove _id\n },\n },\n }\n);\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AACvB,OAAO,eAAe;AAEf,MAAM,aAAa,IAAI;AAAA,EAC5B;AAAA,IACE,OAAO;AAAA,MACL,MAAM;AAAA,MACN,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,UAAU,CAAC,UAAU,SAAS,mCAAmC;AAAA,MACjE,WAAW;AAAA,MACX,MAAM;AAAA,IACR;AAAA,IACA,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,WAAW;AAAA,MACX,WAAW;AAAA,IACb;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,MACN,WAAW;AAAA,IACb;AAAA,IAEA,YAAY;AAAA,MACV,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IAEA,YAAY;AAAA,MACV,MAAM;AAAA,QACJ,YAAY;AAAA,UACV,MAAM;AAAA,UACN,SAAS;AAAA,QACX;AAAA,MACF;AAAA,MACA,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IAEZ,QAAQ;AAAA,MACN,UAAU;AAAA;AAAA,MACV,YAAY;AAAA;AAAA,MACZ,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI,IAAI,SAAS;AAC1B,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,UAAU;AAAA,MACV,UAAU,KAAK,KAAU;AACvB,YAAI,KAAK,IAAI;AACb,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -69,8 +69,7 @@ const updatePlan = async (organization, plan) => {
|
|
|
69
69
|
}
|
|
70
70
|
const updateOrganizationResult = await OrganizationModel.updateOne(
|
|
71
71
|
{ _id: organization.id },
|
|
72
|
-
{ $set: { plan: { ...prevPlan, ...plan } } }
|
|
73
|
-
{ new: true }
|
|
72
|
+
{ $set: { plan: { ...prevPlan, ...plan } } }
|
|
74
73
|
);
|
|
75
74
|
if (updateOrganizationResult.matchedCount === 0) {
|
|
76
75
|
throw new GenericError("ORGANIZATION_UPDATE_FAILED", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/organization.service.ts"],"sourcesContent":["import type {\n Organization,\n OrganizationCreationData,\n OrganizationDocument,\n} from '@/types/organization.types';\nimport type { Plan, PlanDocument } from '@/types/plan.types';\nimport { OrganizationModel } from '@models/organization.model';\nimport { GenericError } from '@utils/errors';\nimport type { OrganizationFilters } from '@utils/filtersAndPagination/getOrganizationFiltersAndPagination';\nimport {\n type OrganizationFields,\n validateOrganization,\n} from '@utils/validation/validateOrganization';\nimport type { Types } from 'mongoose';\n\n/**\n * Finds organizations based on filters and pagination options.\n * @param filters - MongoDB filter query.\n * @param skip - Number of documents to skip.\n * @param limit - Number of documents to limit.\n * @returns List of organizations matching the filters.\n */\nexport const findOrganizations = async (\n filters: OrganizationFilters,\n skip: number,\n limit: number\n): Promise<OrganizationDocument[]> =>\n await OrganizationModel.find(filters).skip(skip).limit(limit);\n\n/**\n * Finds an organization by its ID.\n * @param organizationId - The ID of the organization to find.\n * @returns The organization matching the ID.\n */\nexport const getOrganizationById = async (\n organizationId: string | Types.ObjectId\n): Promise<OrganizationDocument> => {\n const organization = await OrganizationModel.findById(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', { organizationId });\n }\n\n return organization;\n};\n\n/**\n * Counts the total number of organizations that match the filters.\n * @param filters - MongoDB filter query.\n * @returns Total number of organizations.\n */\nexport const countOrganizations = async (\n filters: OrganizationFilters\n): Promise<number> => {\n const result = await OrganizationModel.countDocuments(filters);\n\n if (typeof result === 'undefined') {\n throw new GenericError('ORGANIZATION_COUNT_FAILED', { filters });\n }\n\n return result;\n};\n\n/**\n * Creates a new organization in the database.\n * @param organization - The organization data to create.\n * @returns The created organization.\n */\nexport const createOrganization = async (\n organization: OrganizationCreationData,\n userId: string | Types.ObjectId\n): Promise<OrganizationDocument> => {\n const errors = validateOrganization(organization, ['name']);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('ORGANIZATION_INVALID_FIELDS', { errors });\n }\n\n try {\n const result = await OrganizationModel.create({\n creatorId: userId,\n membersIds: [userId],\n adminsIds: [userId],\n ...organization,\n });\n\n return result;\n } catch (error) {\n throw new GenericError('ORGANIZATION_CREATION_FAILED', {\n error: (error as Error).message,\n });\n }\n};\n\n/**\n * Updates an existing organization in the database by its ID.\n * @param organizationId - The ID of the organization to update.\n * @param organization - The updated organization data.\n * @returns The updated organization.\n */\nexport const updateOrganizationById = async (\n organizationId: string | Types.ObjectId,\n organization: Partial<Organization>\n): Promise<OrganizationDocument> => {\n const updatedKeys = Object.keys(organization) as OrganizationFields;\n const errors = validateOrganization(organization, updatedKeys);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('ORGANIZATION_INVALID_FIELDS', {\n organizationId,\n errors,\n });\n }\n\n const result = await OrganizationModel.updateOne(\n { _id: organizationId },\n organization\n );\n\n if (result.matchedCount === 0) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', { organizationId });\n }\n\n return await getOrganizationById(organizationId);\n};\n\n/**\n * Deletes an organization from the database by its ID.\n * @param organizationId - The ID of the organization to delete.\n * @returns The result of the deletion operation.\n */\nexport const deleteOrganizationById = async (\n organizationId: string | Types.ObjectId\n): Promise<OrganizationDocument> => {\n const organization =\n await OrganizationModel.findByIdAndDelete(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', { organizationId });\n }\n\n return organization;\n};\n\n/**\n * Updates an existing plan in the database by its ID.\n * @param planId - The ID of the plan to update.\n * @param plan - The updated plan data.\n * @returns The updated plan.\n */\nexport const updatePlan = async (\n organization: Organization | OrganizationDocument,\n plan: Partial<Plan>\n): Promise<OrganizationDocument | null> => {\n let prevPlan = organization.plan ?? {};\n\n if (typeof (prevPlan as PlanDocument)?.toObject === 'function') {\n prevPlan = (prevPlan as PlanDocument).toObject();\n }\n\n const updateOrganizationResult = await OrganizationModel.updateOne(\n { _id: organization.id },\n { $set: { plan: { ...prevPlan, ...plan } } }
|
|
1
|
+
{"version":3,"sources":["../../../src/services/organization.service.ts"],"sourcesContent":["import type {\n Organization,\n OrganizationCreationData,\n OrganizationDocument,\n} from '@/types/organization.types';\nimport type { Plan, PlanDocument } from '@/types/plan.types';\nimport { OrganizationModel } from '@models/organization.model';\nimport { GenericError } from '@utils/errors';\nimport type { OrganizationFilters } from '@utils/filtersAndPagination/getOrganizationFiltersAndPagination';\nimport {\n type OrganizationFields,\n validateOrganization,\n} from '@utils/validation/validateOrganization';\nimport type { Types } from 'mongoose';\n\n/**\n * Finds organizations based on filters and pagination options.\n * @param filters - MongoDB filter query.\n * @param skip - Number of documents to skip.\n * @param limit - Number of documents to limit.\n * @returns List of organizations matching the filters.\n */\nexport const findOrganizations = async (\n filters: OrganizationFilters,\n skip: number,\n limit: number\n): Promise<OrganizationDocument[]> =>\n await OrganizationModel.find(filters).skip(skip).limit(limit);\n\n/**\n * Finds an organization by its ID.\n * @param organizationId - The ID of the organization to find.\n * @returns The organization matching the ID.\n */\nexport const getOrganizationById = async (\n organizationId: string | Types.ObjectId\n): Promise<OrganizationDocument> => {\n const organization = await OrganizationModel.findById(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', { organizationId });\n }\n\n return organization;\n};\n\n/**\n * Counts the total number of organizations that match the filters.\n * @param filters - MongoDB filter query.\n * @returns Total number of organizations.\n */\nexport const countOrganizations = async (\n filters: OrganizationFilters\n): Promise<number> => {\n const result = await OrganizationModel.countDocuments(filters);\n\n if (typeof result === 'undefined') {\n throw new GenericError('ORGANIZATION_COUNT_FAILED', { filters });\n }\n\n return result;\n};\n\n/**\n * Creates a new organization in the database.\n * @param organization - The organization data to create.\n * @returns The created organization.\n */\nexport const createOrganization = async (\n organization: OrganizationCreationData,\n userId: string | Types.ObjectId\n): Promise<OrganizationDocument> => {\n const errors = validateOrganization(organization, ['name']);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('ORGANIZATION_INVALID_FIELDS', { errors });\n }\n\n try {\n const result = await OrganizationModel.create({\n creatorId: userId,\n membersIds: [userId],\n adminsIds: [userId],\n ...organization,\n });\n\n return result;\n } catch (error) {\n throw new GenericError('ORGANIZATION_CREATION_FAILED', {\n error: (error as Error).message,\n });\n }\n};\n\n/**\n * Updates an existing organization in the database by its ID.\n * @param organizationId - The ID of the organization to update.\n * @param organization - The updated organization data.\n * @returns The updated organization.\n */\nexport const updateOrganizationById = async (\n organizationId: string | Types.ObjectId,\n organization: Partial<Organization>\n): Promise<OrganizationDocument> => {\n const updatedKeys = Object.keys(organization) as OrganizationFields;\n const errors = validateOrganization(organization, updatedKeys);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('ORGANIZATION_INVALID_FIELDS', {\n organizationId,\n errors,\n });\n }\n\n const result = await OrganizationModel.updateOne(\n { _id: organizationId },\n organization\n );\n\n if (result.matchedCount === 0) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', { organizationId });\n }\n\n return await getOrganizationById(organizationId);\n};\n\n/**\n * Deletes an organization from the database by its ID.\n * @param organizationId - The ID of the organization to delete.\n * @returns The result of the deletion operation.\n */\nexport const deleteOrganizationById = async (\n organizationId: string | Types.ObjectId\n): Promise<OrganizationDocument> => {\n const organization =\n await OrganizationModel.findByIdAndDelete(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', { organizationId });\n }\n\n return organization;\n};\n\n/**\n * Updates an existing plan in the database by its ID.\n * @param planId - The ID of the plan to update.\n * @param plan - The updated plan data.\n * @returns The updated plan.\n */\nexport const updatePlan = async (\n organization: Organization | OrganizationDocument,\n plan: Partial<Plan>\n): Promise<OrganizationDocument | null> => {\n let prevPlan = organization.plan ?? {};\n\n if (typeof (prevPlan as PlanDocument)?.toObject === 'function') {\n prevPlan = (prevPlan as PlanDocument).toObject();\n }\n\n const updateOrganizationResult = await OrganizationModel.updateOne(\n { _id: organization.id },\n { $set: { plan: { ...prevPlan, ...plan } } }\n );\n\n if (updateOrganizationResult.matchedCount === 0) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization.id,\n });\n }\n\n const updatedOrganization = await getOrganizationById(organization.id);\n\n return updatedOrganization;\n};\n"],"mappings":"AAMA,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAE7B;AAAA,EAEE;AAAA,OACK;AAUA,MAAM,oBAAoB,OAC/B,SACA,MACA,UAEA,MAAM,kBAAkB,KAAK,OAAO,EAAE,KAAK,IAAI,EAAE,MAAM,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;AAC7B,UAAM,IAAI,aAAa,8BAA8B,EAAE,eAAe,CAAC;AAAA,EACzE;AAEA,SAAO,MAAM,oBAAoB,cAAc;AACjD;AAOO,MAAM,yBAAyB,OACpC,mBACkC;AAClC,QAAM,eACJ,MAAM,kBAAkB,kBAAkB,cAAc;AAE1D,MAAI,CAAC,cAAc;AACjB,UAAM,IAAI,aAAa,0BAA0B,EAAE,eAAe,CAAC;AAAA,EACrE;AAEA,SAAO;AACT;AAQO,MAAM,aAAa,OACxB,cACA,SACyC;AACzC,MAAI,WAAW,aAAa,QAAQ,CAAC;AAErC,MAAI,OAAQ,UAA2B,aAAa,YAAY;AAC9D,eAAY,SAA0B,SAAS;AAAA,EACjD;AAEA,QAAM,2BAA2B,MAAM,kBAAkB;AAAA,IACvD,EAAE,KAAK,aAAa,GAAG;AAAA,IACvB,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,UAAU,GAAG,KAAK,EAAE,EAAE;AAAA,EAC7C;AAEA,MAAI,yBAAyB,iBAAiB,GAAG;AAC/C,UAAM,IAAI,aAAa,8BAA8B;AAAA,MACnD,gBAAgB,aAAa;AAAA,IAC/B,CAAC;AAAA,EACH;AAEA,QAAM,sBAAsB,MAAM,oBAAoB,aAAa,EAAE;AAErE,SAAO;AACT;","names":[]}
|
|
@@ -28,10 +28,10 @@ const getAPIKey = (res, accessType, aiOptions) => {
|
|
|
28
28
|
return void 0;
|
|
29
29
|
};
|
|
30
30
|
const getModel = (provider, userApiKey, userModel, defaultModel) => {
|
|
31
|
-
let fallBackModel = defaultModel ?? "
|
|
31
|
+
let fallBackModel = defaultModel ?? "chatgpt-4o-latest";
|
|
32
32
|
switch (provider) {
|
|
33
33
|
case "openai" /* OPENAI */:
|
|
34
|
-
defaultModel = "
|
|
34
|
+
defaultModel = "chatgpt-4o-latest";
|
|
35
35
|
break;
|
|
36
36
|
case "anthropic" /* ANTHROPIC */:
|
|
37
37
|
defaultModel = "claude-3-haiku-20240307";
|
|
@@ -123,7 +123,6 @@ const getAIConfig = async (res, options) => {
|
|
|
123
123
|
}
|
|
124
124
|
return {
|
|
125
125
|
model: languageModel,
|
|
126
|
-
maxTokens: protectedOptions.maxTokens,
|
|
127
126
|
temperature: protectedOptions.temperature
|
|
128
127
|
};
|
|
129
128
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/utils/AI/aiSdk.ts"],"sourcesContent":["import { anthropic, createAnthropic } from '@ai-sdk/anthropic';\nimport { createDeepSeek, deepseek } from '@ai-sdk/deepseek';\nimport { createGoogleGenerativeAI, google } from '@ai-sdk/google';\nimport { createMistral, mistral } from '@ai-sdk/mistral';\nimport { createOpenAI, openai } from '@ai-sdk/openai';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../src/utils/AI/aiSdk.ts"],"sourcesContent":["import { anthropic, createAnthropic } from '@ai-sdk/anthropic';\nimport { createDeepSeek, deepseek } from '@ai-sdk/deepseek';\nimport { createGoogleGenerativeAI, google } from '@ai-sdk/google';\nimport { createMistral, mistral } from '@ai-sdk/mistral';\nimport { createOpenAI, openai } from '@ai-sdk/openai';\nimport {\n AssistantModelMessage,\n generateText,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from 'ai';\nimport { Response } from 'express';\n\ntype AnthropicModel = Parameters<typeof anthropic>[0];\ntype DeepSeekModel = Parameters<typeof deepseek>[0];\ntype MistralModel = Parameters<typeof mistral>[0];\ntype OpenAIModel = Parameters<typeof openai>[0];\ntype GoogleModel = Parameters<typeof google>[0];\n\nexport type Messages = (\n | SystemModelMessage\n | UserModelMessage\n | AssistantModelMessage\n | ToolModelMessage\n)[];\n\n/**\n * Supported AI models\n */\nexport type Model =\n | AnthropicModel\n | DeepSeekModel\n | MistralModel\n | OpenAIModel\n | GoogleModel\n | (string & {});\n\n/**\n * Supported AI SDK providers\n */\nexport enum AIProvider {\n OPENAI = 'openai',\n ANTHROPIC = 'anthropic',\n MISTRAL = 'mistral',\n DEEPSEEK = 'deepseek',\n GEMINI = 'gemini',\n}\n\n/**\n * Common options for all AI providers\n */\nexport type AIOptions = {\n provider?: AIProvider;\n model?: Model;\n temperature?: number;\n apiKey?: string;\n applicationContext?: string;\n};\n\n// Define the structure of messages used in chat completions\nexport type ChatCompletionRequestMessage = {\n role: 'system' | 'user' | 'assistant'; // The role of the message sender\n content: string; // The text content of the message\n timestamp?: Date; // The timestamp of the message\n};\n\ntype AccessType = 'apiKey' | 'registered_user' | 'premium_user' | 'public';\n\nconst getAPIKey = (\n res: Response,\n accessType: AccessType[],\n aiOptions?: AIOptions\n) => {\n const defaultApiKey = process.env.OPENAI_API_KEY;\n\n if (accessType.includes('public')) {\n return aiOptions?.apiKey ?? defaultApiKey;\n }\n\n if (accessType.includes('apiKey') && aiOptions?.apiKey) {\n return aiOptions?.apiKey;\n }\n\n if (accessType.includes('registered_user') && res.locals.user) {\n return aiOptions?.apiKey ?? defaultApiKey;\n }\n\n // TODO: Implement premium user access\n if (accessType.includes('premium_user') && res.locals.user) {\n return aiOptions?.apiKey ?? defaultApiKey;\n }\n\n return undefined;\n};\n\nconst getModel = (\n provider: AIProvider,\n userApiKey: string,\n userModel?: Model,\n defaultModel?: Model\n): Model => {\n // Set default models based on provider\n let fallBackModel: Model = defaultModel ?? 'chatgpt-4o-latest';\n\n switch (provider) {\n case AIProvider.OPENAI:\n defaultModel = 'chatgpt-4o-latest';\n break;\n case AIProvider.ANTHROPIC:\n defaultModel = 'claude-3-haiku-20240307';\n break;\n case AIProvider.MISTRAL:\n defaultModel = 'mistral-large-latest';\n break;\n case AIProvider.DEEPSEEK:\n defaultModel = 'deepseek-coder';\n break;\n case AIProvider.GEMINI:\n defaultModel = 'gemini-1.5-pro';\n break;\n }\n\n // If the user use his own API, let him use the model he wants\n if (Boolean(userApiKey) && Boolean(userModel)) {\n return userModel!;\n }\n\n if (Boolean(userModel)) {\n throw new Error(\n 'The user should use his own API key to use a custom model'\n );\n }\n\n return fallBackModel;\n};\n\nexport type AIConfig = Parameters<typeof generateText>[0];\n\nconst DEFAULT_PROVIDER: AIProvider = AIProvider.OPENAI as AIProvider;\nconst DEFAULT_TEMPERATURE: number = 1; // ChatGPT 5 accept only temperature 1\n\nexport type AIConfigOptions = {\n userOptions?: AIOptions;\n defaultOptions?: AIOptions;\n accessType?: AccessType[];\n};\n\n/**\n * Get AI model configuration based on the selected provider and options\n * This function handles the configuration for different AI providers\n *\n * @param options Configuration options including provider, API keys, models and temperature\n * @returns Configured AI model ready to use with generateText\n */\nexport const getAIConfig = async (\n res: Response,\n options: AIConfigOptions\n): Promise<AIConfig> => {\n const {\n userOptions,\n defaultOptions,\n accessType = ['registered_user'],\n } = options;\n\n const aiOptions = {\n provider: DEFAULT_PROVIDER,\n temperature: DEFAULT_TEMPERATURE,\n ...defaultOptions,\n ...userOptions,\n } satisfies AIOptions;\n\n const apiKey = getAPIKey(res, accessType, aiOptions);\n\n // Check if API key is provided\n if (!apiKey) {\n throw new Error(`API key for ${aiOptions.provider} is missing`);\n }\n\n const selectedModel = getModel(\n aiOptions.provider,\n apiKey,\n aiOptions.model,\n defaultOptions?.model\n );\n\n const protectedOptions = {\n ...aiOptions,\n apiKey,\n model: selectedModel,\n } satisfies AIOptions;\n\n let languageModel: AIConfig['model'];\n\n switch (protectedOptions.provider) {\n case AIProvider.OPENAI: {\n languageModel = createOpenAI({\n apiKey,\n })(selectedModel);\n break;\n }\n\n case AIProvider.ANTHROPIC: {\n languageModel = createAnthropic({\n apiKey,\n })(selectedModel);\n break;\n }\n\n case AIProvider.MISTRAL: {\n languageModel = createMistral({\n apiKey,\n })(selectedModel);\n break;\n }\n\n case AIProvider.DEEPSEEK: {\n languageModel = createDeepSeek({\n apiKey,\n })(selectedModel);\n break;\n }\n\n case AIProvider.GEMINI: {\n languageModel = createGoogleGenerativeAI({\n apiKey,\n })(selectedModel);\n break;\n }\n\n default: {\n throw new Error(`Provider ${protectedOptions.provider} not supported`);\n }\n }\n\n return {\n model: languageModel,\n temperature: protectedOptions.temperature,\n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AiB;AAAA,EAChC;AACF;","names":["AIProvider"]}
|
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
} from "../aiSdk.mjs";
|
|
12
12
|
import embeddingsList from "./embeddings.json" with { type: "json" };
|
|
13
13
|
const vectorStore = [];
|
|
14
|
-
const MODEL = "
|
|
14
|
+
const MODEL = "chatgpt-4o-latest";
|
|
15
15
|
const MODEL_TEMPERATURE = 0.1;
|
|
16
16
|
const MAX_RELEVANT_CHUNKS_NB = 20;
|
|
17
17
|
const MIN_RELEVANT_CHUNKS_SIMILARITY = 0.42;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/utils/AI/askDocQuestion/askDocQuestion.ts"],"sourcesContent":["import { getBlogs, getDocs, getFrequentQuestions } from '@intlayer/docs';\nimport { streamText } from 'ai';\nimport dotenv from 'dotenv';\nimport { readFileSync, writeFileSync } from 'fs';\nimport { getMarkdownMetadata } from 'intlayer';\nimport { OpenAI } from 'openai';\nimport { dirname, join } from 'path';\nimport { fileURLToPath } from 'url';\nimport {\n AIConfig,\n AIOptions,\n AIProvider,\n ChatCompletionRequestMessage,\n} from '../aiSdk';\nimport embeddingsList from './embeddings.json' with { type: 'json' };\n\ntype VectorStoreEl = {\n fileKey: string;\n chunkNumber: number;\n content: string;\n embedding: number[];\n docUrl: string;\n docName: string;\n};\n\n/**\n * Simple in-memory vector store to hold document embeddings and their content.\n * Each entry contains:\n * - fileKey: A unique key identifying the file\n * - chunkNumber: The number of the chunk within the document\n * - content: The chunk content\n * - embedding: The numerical embedding vector for the chunk\n */\nconst vectorStore: VectorStoreEl[] = [];\n\n/*\n * Ask question AI configuration\n */\nconst MODEL: AIOptions['model'] = 'gpt-5'; // Model to use for chat completions\nconst MODEL_TEMPERATURE: AIOptions['temperature'] = 0.1; // Temperature to use for chat completions\nconst MAX_RELEVANT_CHUNKS_NB: number = 20; // Maximum number of relevant chunks to attach to chatGPT context\nconst MIN_RELEVANT_CHUNKS_SIMILARITY: number = 0.42; // Minimum similarity required for a chunk to be considered relevant\n\nexport const aiDefaultOptions: AIOptions = {\n provider: AIProvider.OPENAI,\n model: MODEL,\n temperature: MODEL_TEMPERATURE,\n};\n\n/*\n * Embedding model configuration\n */\nconst EMBEDDING_MODEL: OpenAI.EmbeddingModel = 'text-embedding-3-large'; // Model to use for embedding generation\nconst OVERLAP_TOKENS: number = 200; // Number of tokens to overlap between chunks\nconst MAX_CHUNK_TOKENS: number = 800; // Maximum number of tokens per chunk\nconst CHAR_BY_TOKEN: number = 4.15; // Approximate pessimistically the number of characters per token // Can use `tiktoken` or other tokenizers to calculate it more precisely\nconst MAX_CHARS: number = MAX_CHUNK_TOKENS * CHAR_BY_TOKEN;\nconst OVERLAP_CHARS: number = OVERLAP_TOKENS * CHAR_BY_TOKEN;\n\n/**\n * Splits a given text into chunks ensuring each chunk does not exceed MAX_CHARS.\n * @param text - The input text to split.\n * @returns - Array of text chunks.\n */\nconst chunkText = (text: string): string[] => {\n const chunks: string[] = [];\n let start = 0;\n\n while (start < text.length) {\n let end = Math.min(start + MAX_CHARS, text.length);\n\n // Ensure we don't cut words in the middle (find nearest space)\n if (end < text.length) {\n const lastSpace = text.lastIndexOf(' ', end);\n if (lastSpace > start) {\n end = lastSpace;\n }\n }\n\n chunks.push(text.substring(start, end));\n\n // Move start forward correctly\n const nextStart = end - OVERLAP_CHARS;\n if (nextStart <= start) {\n // Prevent infinite loop if overlap is too large\n start = end;\n } else {\n start = nextStart;\n }\n }\n\n return chunks;\n};\n\n/**\n * Generates an embedding for a given text using OpenAI's embedding API.\n * Trims the text if it exceeds the maximum allowed characters.\n *\n * @param text - The input text to generate an embedding for\n * @returns The embedding vector as a number array\n */\nconst generateEmbedding = async (text: string): Promise<number[]> => {\n try {\n const openaiClient = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n\n const response = await openaiClient.embeddings.create({\n model: EMBEDDING_MODEL,\n input: text,\n });\n\n return response.data[0].embedding;\n } catch (error) {\n console.error('Error generating embedding:', error);\n return [];\n }\n};\n\n/**\n * Calculates the cosine similarity between two vectors.\n * Cosine similarity measures the cosine of the angle between two vectors in an inner product space.\n * Used to determine the similarity between chunks of text.\n *\n * @param vecA - The first vector\n * @param vecB - The second vector\n * @returns The cosine similarity score\n */\nconst cosineSimilarity = (vecA: number[], vecB: number[]): number => {\n // Calculate the dot product of the two vectors\n const dotProduct = vecA.reduce((sum, a, idx) => sum + a * vecB[idx], 0);\n\n // Calculate the magnitude (Euclidean norm) of each vector\n const magnitudeA = Math.sqrt(vecA.reduce((sum, a) => sum + a * a, 0));\n const magnitudeB = Math.sqrt(vecB.reduce((sum, b) => sum + b * b, 0));\n\n // Compute and return the cosine similarity\n return dotProduct / (magnitudeA * magnitudeB);\n};\n\n/**\n * Indexes all Markdown documents by generating embeddings for each chunk and storing them in memory.\n * Also updates the embeddings.json file if new embeddings are generated.\n * Handles cases where files have been updated and chunk counts have changed.\n */\nexport const indexMarkdownFiles = async (): Promise<void> => {\n const env = process.env.NODE_ENV;\n dotenv.config({\n path: [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'],\n });\n\n // if (process.env.SKIP_DOC_EMBEDDINGS_INDEX === 'true') return;\n\n // Retrieve documentation and blog posts in English locale\n const frequentQuestions = await getFrequentQuestions();\n const docs = await getDocs();\n const blogs = await getBlogs();\n\n let result: Record<string, number[]> = {}; // Object to hold updated embeddings\n const currentChunkKeys = new Set<string>(); // Track which chunks should exist\n\n const files = { ...docs, ...blogs, ...frequentQuestions }; // Combine docs and blogs into a single object\n\n // Iterate over each file key (identifier) in the combined files\n for await (const fileKey of Object.keys(files)) {\n // Get the metadata of the file\n const fileMetadata = getMarkdownMetadata(\n files[fileKey as keyof typeof files] as string\n );\n\n // Split the document into chunks based on headings\n const fileChunks = chunkText(\n files[fileKey as keyof typeof files] as string\n );\n\n // Check if the number of chunks has changed for this file\n const existingChunksForFile = Object.keys(embeddingsList).filter((key) =>\n key.startsWith(`${fileKey}/chunk_`)\n );\n const currentChunkCount = fileChunks.length;\n const previousChunkCount = existingChunksForFile.length;\n\n let shouldRegenerateFileEmbeddings = false;\n\n // If chunk count differs, we need to regenerate embeddings for this file\n if (currentChunkCount !== previousChunkCount) {\n console.info(\n `File \"${fileKey}\" chunk count changed: ${previousChunkCount} -> ${currentChunkCount}. Regenerating embeddings.`\n );\n shouldRegenerateFileEmbeddings = true;\n }\n\n // Iterate over each chunk within the current file\n for await (const chunkIndex of Object.keys(fileChunks)) {\n const chunkNumber = Number(chunkIndex) + 1; // Chunk number starts at 1\n const chunksNumber = fileChunks.length;\n\n const fileChunk = fileChunks[\n chunkIndex as keyof typeof fileChunks\n ] as string;\n\n const embeddingKeyName = `${fileKey}/chunk_${chunkNumber}`; // Unique key for the chunk\n currentChunkKeys.add(embeddingKeyName); // Track this chunk as current\n\n // Retrieve precomputed embedding if available and file hasn't changed\n const docEmbedding = !shouldRegenerateFileEmbeddings\n ? (embeddingsList[embeddingKeyName as keyof typeof embeddingsList] as\n | number[]\n | undefined)\n : undefined;\n\n let embedding = docEmbedding; // Use existing embedding if available and valid\n\n if (!embedding) {\n embedding = await generateEmbedding(fileChunk); // Generate embedding if not present or file changed\n console.info(`- Generated new embedding: ${embeddingKeyName}`);\n }\n\n // Update the result object with the embedding\n result = { ...result, [embeddingKeyName]: embedding };\n\n // Store the embedding and content in the in-memory vector store\n vectorStore.push({\n fileKey,\n chunkNumber,\n embedding,\n content: fileChunk,\n docUrl: fileMetadata.url,\n docName: fileMetadata.title,\n });\n\n console.info(`- Indexed: ${embeddingKeyName}/${chunksNumber}`);\n }\n }\n\n // Remove outdated embeddings that no longer exist in current files\n const filteredEmbeddings: Record<string, number[]> = {};\n for (const [key, embedding] of Object.entries(embeddingsList)) {\n if (currentChunkKeys.has(key)) {\n // Only keep embeddings for chunks that still exist\n if (!result[key]) {\n filteredEmbeddings[key] = embedding as number[];\n }\n }\n }\n\n // Merge filtered existing embeddings with new ones\n result = { ...filteredEmbeddings, ...result };\n\n try {\n // Compare the newly generated embeddings with existing ones\n if (JSON.stringify(result) !== JSON.stringify(embeddingsList)) {\n // If there are new embeddings or changes, save them to embeddings.json\n writeFileSync(\n 'src/utils/AI/askDocQuestion/embeddings.json',\n JSON.stringify(result, null, 2)\n );\n }\n } catch (error) {\n console.error(error); // Log any errors during the file write process\n }\n};\n\n// Automatically index Markdown files\nindexMarkdownFiles();\n\n/**\n * Searches the indexed documents for the most relevant chunks based on a query.\n * Utilizes cosine similarity to find the closest matching embeddings.\n *\n * @param query - The search query provided by the user\n * @returns An array of the top matching document chunks' content\n */\nexport const searchChunkReference = async (\n query: string,\n maxResults: number = MAX_RELEVANT_CHUNKS_NB,\n minSimilarity: number = MIN_RELEVANT_CHUNKS_SIMILARITY\n): Promise<VectorStoreEl[]> => {\n // Generate an embedding for the user's query\n const queryEmbedding = await generateEmbedding(query);\n\n // Calculate similarity scores between the query embedding and each document's embedding\n const selection = vectorStore\n .map((chunk) => ({\n ...chunk,\n similarity: cosineSimilarity(queryEmbedding, chunk.embedding), // Add similarity score to each doc\n }))\n .filter((chunk) => chunk.similarity > minSimilarity) // Filter out documents with low similarity scores\n .sort((a, b) => b.similarity - a.similarity) // Sort documents by highest similarity first\n .slice(0, maxResults); // Select the top 6 most similar documents\n\n const orderedDocKeys = new Set(selection.map((chunk) => chunk.fileKey));\n\n const orderedVectorStore = vectorStore.sort((a, b) =>\n orderedDocKeys.has(a.fileKey) ? -1 : 1\n );\n\n const results = orderedVectorStore.filter((chunk) =>\n selection.some(\n (v) => v.fileKey === chunk.fileKey && v.chunkNumber === chunk.chunkNumber\n )\n );\n\n // Return the content of the top matching documents\n return results;\n};\n\n/**\n * Reads the content of a file synchronously.\n *\n * @function\n * @param relativeFilePath - The relative or absolute path to the target file.\n * @returns The entire contents of the specified file as a UTF-8 encoded string.\n */\nconst getFileContent = (relativeFilePath: string): string => {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n const absolutePath = join(__dirname, relativeFilePath);\n const fileContent = readFileSync(absolutePath, 'utf-8');\n return fileContent;\n};\n\nconst CHAT_GPT_PROMPT = getFileContent('./PROMPT.md');\n\n// Initial prompt configuration for the chatbot\nexport const initPrompt: ChatCompletionRequestMessage = {\n role: 'system',\n content: CHAT_GPT_PROMPT,\n};\n\nexport type AskDocQuestionResult = {\n response: string;\n relatedFiles: string[];\n};\n\nexport type AskDocQuestionOptions = {\n onMessage?: (chunk: string) => void;\n};\n\n/**\n * Handles the \"Ask a question\" endpoint in an Express.js route.\n * Processes user messages, retrieves relevant documents, and interacts with AI models to generate responses.\n *\n * @param messages - An array of chat messages from the user and assistant\n * @returns The assistant's response as a string\n */\nexport const askDocQuestion = async (\n messages: ChatCompletionRequestMessage[],\n aiConfig: AIConfig,\n options?: AskDocQuestionOptions\n): Promise<AskDocQuestionResult> => {\n // Format the user's question to keep only the relevant keywords\n const query = messages\n .filter((message) => message.role === 'user')\n .map((message) => `- ${message.content}`)\n .join('\\n');\n\n // 1) Find relevant documents based on the user's question\n const relevantFilesReferences = await searchChunkReference(query);\n\n // 2) Integrate the relevant documents into the initial system prompt\n const systemPrompt = initPrompt.content.replace(\n '{{relevantFilesReferences}}',\n relevantFilesReferences.length === 0\n ? 'Not relevant file found related to the question.'\n : relevantFilesReferences\n .map((doc, idx) =>\n [\n '-----',\n '---',\n `chunkId: ${idx}`,\n `docChunk: \"${doc.chunkNumber}/${doc.fileKey.length}\"`,\n `docName: \"${doc.docName}\"`,\n `docUrl: \"${doc.docUrl}\"`,\n `---`,\n doc.content,\n `-----`,\n ].join('\\n')\n )\n .join('\\n\\n') // Insert relevant docs into the prompt\n );\n\n // Format messages for AI SDK\n const aiMessages = [\n {\n role: 'system' as const,\n content: systemPrompt,\n },\n ...messages.slice(-8),\n ];\n\n if (!aiConfig) {\n throw new Error('Failed to initialize AI configuration');\n }\n\n // 3) Use the AI SDK to stream the response\n let fullResponse = '';\n const stream = streamText({\n ...aiConfig,\n messages: aiMessages,\n });\n\n // Process the stream\n for await (const chunk of stream.textStream) {\n fullResponse += chunk;\n options?.onMessage?.(chunk);\n }\n\n // 4) Extract unique related files\n const relatedFiles = [\n ...new Set(relevantFilesReferences.map((doc) => doc.fileKey)),\n ];\n\n // 5) Return the assistant's response to the user\n return {\n response: fullResponse ?? 'Error: No result found',\n relatedFiles,\n };\n};\n"],"mappings":"AAAA,SAAS,UAAU,SAAS,4BAA4B;AACxD,SAAS,kBAAkB;AAC3B,OAAO,YAAY;AACnB,SAAS,cAAc,qBAAqB;AAC5C,SAAS,2BAA2B;AACpC,SAAS,cAAc;AACvB,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAC9B;AAAA,EAGE;AAAA,OAEK;AACP,OAAO,oBAAoB,oBAAoB,KAAK,EAAE,MAAM,OAAO;AAmBnE,MAAM,cAA+B,CAAC;AAKtC,MAAM,QAA4B;AAClC,MAAM,oBAA8C;AACpD,MAAM,yBAAiC;AACvC,MAAM,iCAAyC;AAExC,MAAM,mBAA8B;AAAA,EACzC,UAAU,WAAW;AAAA,EACrB,OAAO;AAAA,EACP,aAAa;AACf;AAKA,MAAM,kBAAyC;AAC/C,MAAM,iBAAyB;AAC/B,MAAM,mBAA2B;AACjC,MAAM,gBAAwB;AAC9B,MAAM,YAAoB,mBAAmB;AAC7C,MAAM,gBAAwB,iBAAiB;AAO/C,MAAM,YAAY,CAAC,SAA2B;AAC5C,QAAM,SAAmB,CAAC;AAC1B,MAAI,QAAQ;AAEZ,SAAO,QAAQ,KAAK,QAAQ;AAC1B,QAAI,MAAM,KAAK,IAAI,QAAQ,WAAW,KAAK,MAAM;AAGjD,QAAI,MAAM,KAAK,QAAQ;AACrB,YAAM,YAAY,KAAK,YAAY,KAAK,GAAG;AAC3C,UAAI,YAAY,OAAO;AACrB,cAAM;AAAA,MACR;AAAA,IACF;AAEA,WAAO,KAAK,KAAK,UAAU,OAAO,GAAG,CAAC;AAGtC,UAAM,YAAY,MAAM;AACxB,QAAI,aAAa,OAAO;AAEtB,cAAQ;AAAA,IACV,OAAO;AACL,cAAQ;A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I/askDocQuestion/askDocQuestion.ts"],"sourcesContent":["import { getBlogs, getDocs, getFrequentQuestions } from '@intlayer/docs';\nimport { streamText } from 'ai';\nimport dotenv from 'dotenv';\nimport { readFileSync, writeFileSync } from 'fs';\nimport { getMarkdownMetadata } from 'intlayer';\nimport { OpenAI } from 'openai';\nimport { dirname, join } from 'path';\nimport { fileURLToPath } from 'url';\nimport {\n AIConfig,\n AIOptions,\n AIProvider,\n ChatCompletionRequestMessage,\n} from '../aiSdk';\nimport embeddingsList from './embeddings.json' with { type: 'json' };\n\ntype VectorStoreEl = {\n fileKey: string;\n chunkNumber: number;\n content: string;\n embedding: number[];\n docUrl: string;\n docName: string;\n};\n\n/**\n * Simple in-memory vector store to hold document embeddings and their content.\n * Each entry contains:\n * - fileKey: A unique key identifying the file\n * - chunkNumber: The number of the chunk within the document\n * - content: The chunk content\n * - embedding: The numerical embedding vector for the chunk\n */\nconst vectorStore: VectorStoreEl[] = [];\n\n/*\n * Ask question AI configuration\n */\nconst MODEL: AIOptions['model'] = 'chatgpt-4o-latest'; // Model to use for chat completions\nconst MODEL_TEMPERATURE: AIOptions['temperature'] = 0.1; // Temperature to use for chat completions\nconst MAX_RELEVANT_CHUNKS_NB: number = 20; // Maximum number of relevant chunks to attach to chatGPT context\nconst MIN_RELEVANT_CHUNKS_SIMILARITY: number = 0.42; // Minimum similarity required for a chunk to be considered relevant\n\nexport const aiDefaultOptions: AIOptions = {\n provider: AIProvider.OPENAI,\n model: MODEL,\n temperature: MODEL_TEMPERATURE,\n};\n\n/*\n * Embedding model configuration\n */\nconst EMBEDDING_MODEL: OpenAI.EmbeddingModel = 'text-embedding-3-large'; // Model to use for embedding generation\nconst OVERLAP_TOKENS: number = 200; // Number of tokens to overlap between chunks\nconst MAX_CHUNK_TOKENS: number = 800; // Maximum number of tokens per chunk\nconst CHAR_BY_TOKEN: number = 4.15; // Approximate pessimistically the number of characters per token // Can use `tiktoken` or other tokenizers to calculate it more precisely\nconst MAX_CHARS: number = MAX_CHUNK_TOKENS * CHAR_BY_TOKEN;\nconst OVERLAP_CHARS: number = OVERLAP_TOKENS * CHAR_BY_TOKEN;\n\n/**\n * Splits a given text into chunks ensuring each chunk does not exceed MAX_CHARS.\n * @param text - The input text to split.\n * @returns - Array of text chunks.\n */\nconst chunkText = (text: string): string[] => {\n const chunks: string[] = [];\n let start = 0;\n\n while (start < text.length) {\n let end = Math.min(start + MAX_CHARS, text.length);\n\n // Ensure we don't cut words in the middle (find nearest space)\n if (end < text.length) {\n const lastSpace = text.lastIndexOf(' ', end);\n if (lastSpace > start) {\n end = lastSpace;\n }\n }\n\n chunks.push(text.substring(start, end));\n\n // Move start forward correctly\n const nextStart = end - OVERLAP_CHARS;\n if (nextStart <= start) {\n // Prevent infinite loop if overlap is too large\n start = end;\n } else {\n start = nextStart;\n }\n }\n\n return chunks;\n};\n\n/**\n * Generates an embedding for a given text using OpenAI's embedding API.\n * Trims the text if it exceeds the maximum allowed characters.\n *\n * @param text - The input text to generate an embedding for\n * @returns The embedding vector as a number array\n */\nconst generateEmbedding = async (text: string): Promise<number[]> => {\n try {\n const openaiClient = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n\n const response = await openaiClient.embeddings.create({\n model: EMBEDDING_MODEL,\n input: text,\n });\n\n return response.data[0].embedding;\n } catch (error) {\n console.error('Error generating embedding:', error);\n return [];\n }\n};\n\n/**\n * Calculates the cosine similarity between two vectors.\n * Cosine similarity measures the cosine of the angle between two vectors in an inner product space.\n * Used to determine the similarity between chunks of text.\n *\n * @param vecA - The first vector\n * @param vecB - The second vector\n * @returns The cosine similarity score\n */\nconst cosineSimilarity = (vecA: number[], vecB: number[]): number => {\n // Calculate the dot product of the two vectors\n const dotProduct = vecA.reduce((sum, a, idx) => sum + a * vecB[idx], 0);\n\n // Calculate the magnitude (Euclidean norm) of each vector\n const magnitudeA = Math.sqrt(vecA.reduce((sum, a) => sum + a * a, 0));\n const magnitudeB = Math.sqrt(vecB.reduce((sum, b) => sum + b * b, 0));\n\n // Compute and return the cosine similarity\n return dotProduct / (magnitudeA * magnitudeB);\n};\n\n/**\n * Indexes all Markdown documents by generating embeddings for each chunk and storing them in memory.\n * Also updates the embeddings.json file if new embeddings are generated.\n * Handles cases where files have been updated and chunk counts have changed.\n */\nexport const indexMarkdownFiles = async (): Promise<void> => {\n const env = process.env.NODE_ENV;\n dotenv.config({\n path: [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'],\n });\n\n // if (process.env.SKIP_DOC_EMBEDDINGS_INDEX === 'true') return;\n\n // Retrieve documentation and blog posts in English locale\n const frequentQuestions = await getFrequentQuestions();\n const docs = await getDocs();\n const blogs = await getBlogs();\n\n let result: Record<string, number[]> = {}; // Object to hold updated embeddings\n const currentChunkKeys = new Set<string>(); // Track which chunks should exist\n\n const files = { ...docs, ...blogs, ...frequentQuestions }; // Combine docs and blogs into a single object\n\n // Iterate over each file key (identifier) in the combined files\n for await (const fileKey of Object.keys(files)) {\n // Get the metadata of the file\n const fileMetadata = getMarkdownMetadata(\n files[fileKey as keyof typeof files] as string\n );\n\n // Split the document into chunks based on headings\n const fileChunks = chunkText(\n files[fileKey as keyof typeof files] as string\n );\n\n // Check if the number of chunks has changed for this file\n const existingChunksForFile = Object.keys(embeddingsList).filter((key) =>\n key.startsWith(`${fileKey}/chunk_`)\n );\n const currentChunkCount = fileChunks.length;\n const previousChunkCount = existingChunksForFile.length;\n\n let shouldRegenerateFileEmbeddings = false;\n\n // If chunk count differs, we need to regenerate embeddings for this file\n if (currentChunkCount !== previousChunkCount) {\n console.info(\n `File \"${fileKey}\" chunk count changed: ${previousChunkCount} -> ${currentChunkCount}. Regenerating embeddings.`\n );\n shouldRegenerateFileEmbeddings = true;\n }\n\n // Iterate over each chunk within the current file\n for await (const chunkIndex of Object.keys(fileChunks)) {\n const chunkNumber = Number(chunkIndex) + 1; // Chunk number starts at 1\n const chunksNumber = fileChunks.length;\n\n const fileChunk = fileChunks[\n chunkIndex as keyof typeof fileChunks\n ] as string;\n\n const embeddingKeyName = `${fileKey}/chunk_${chunkNumber}`; // Unique key for the chunk\n currentChunkKeys.add(embeddingKeyName); // Track this chunk as current\n\n // Retrieve precomputed embedding if available and file hasn't changed\n const docEmbedding = !shouldRegenerateFileEmbeddings\n ? (embeddingsList[embeddingKeyName as keyof typeof embeddingsList] as\n | number[]\n | undefined)\n : undefined;\n\n let embedding = docEmbedding; // Use existing embedding if available and valid\n\n if (!embedding) {\n embedding = await generateEmbedding(fileChunk); // Generate embedding if not present or file changed\n console.info(`- Generated new embedding: ${embeddingKeyName}`);\n }\n\n // Update the result object with the embedding\n result = { ...result, [embeddingKeyName]: embedding };\n\n // Store the embedding and content in the in-memory vector store\n vectorStore.push({\n fileKey,\n chunkNumber,\n embedding,\n content: fileChunk,\n docUrl: fileMetadata.url,\n docName: fileMetadata.title,\n });\n\n console.info(`- Indexed: ${embeddingKeyName}/${chunksNumber}`);\n }\n }\n\n // Remove outdated embeddings that no longer exist in current files\n const filteredEmbeddings: Record<string, number[]> = {};\n for (const [key, embedding] of Object.entries(embeddingsList)) {\n if (currentChunkKeys.has(key)) {\n // Only keep embeddings for chunks that still exist\n if (!result[key]) {\n filteredEmbeddings[key] = embedding as number[];\n }\n }\n }\n\n // Merge filtered existing embeddings with new ones\n result = { ...filteredEmbeddings, ...result };\n\n try {\n // Compare the newly generated embeddings with existing ones\n if (JSON.stringify(result) !== JSON.stringify(embeddingsList)) {\n // If there are new embeddings or changes, save them to embeddings.json\n writeFileSync(\n 'src/utils/AI/askDocQuestion/embeddings.json',\n JSON.stringify(result, null, 2)\n );\n }\n } catch (error) {\n console.error(error); // Log any errors during the file write process\n }\n};\n\n// Automatically index Markdown files\nindexMarkdownFiles();\n\n/**\n * Searches the indexed documents for the most relevant chunks based on a query.\n * Utilizes cosine similarity to find the closest matching embeddings.\n *\n * @param query - The search query provided by the user\n * @returns An array of the top matching document chunks' content\n */\nexport const searchChunkReference = async (\n query: string,\n maxResults: number = MAX_RELEVANT_CHUNKS_NB,\n minSimilarity: number = MIN_RELEVANT_CHUNKS_SIMILARITY\n): Promise<VectorStoreEl[]> => {\n // Generate an embedding for the user's query\n const queryEmbedding = await generateEmbedding(query);\n\n // Calculate similarity scores between the query embedding and each document's embedding\n const selection = vectorStore\n .map((chunk) => ({\n ...chunk,\n similarity: cosineSimilarity(queryEmbedding, chunk.embedding), // Add similarity score to each doc\n }))\n .filter((chunk) => chunk.similarity > minSimilarity) // Filter out documents with low similarity scores\n .sort((a, b) => b.similarity - a.similarity) // Sort documents by highest similarity first\n .slice(0, maxResults); // Select the top 6 most similar documents\n\n const orderedDocKeys = new Set(selection.map((chunk) => chunk.fileKey));\n\n const orderedVectorStore = vectorStore.sort((a, b) =>\n orderedDocKeys.has(a.fileKey) ? -1 : 1\n );\n\n const results = orderedVectorStore.filter((chunk) =>\n selection.some(\n (v) => v.fileKey === chunk.fileKey && v.chunkNumber === chunk.chunkNumber\n )\n );\n\n // Return the content of the top matching documents\n return results;\n};\n\n/**\n * Reads the content of a file synchronously.\n *\n * @function\n * @param relativeFilePath - The relative or absolute path to the target file.\n * @returns The entire contents of the specified file as a UTF-8 encoded string.\n */\nconst getFileContent = (relativeFilePath: string): string => {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n const absolutePath = join(__dirname, relativeFilePath);\n const fileContent = readFileSync(absolutePath, 'utf-8');\n return fileContent;\n};\n\nconst CHAT_GPT_PROMPT = getFileContent('./PROMPT.md');\n\n// Initial prompt configuration for the chatbot\nexport const initPrompt: ChatCompletionRequestMessage = {\n role: 'system',\n content: CHAT_GPT_PROMPT,\n};\n\nexport type AskDocQuestionResult = {\n response: string;\n relatedFiles: string[];\n};\n\nexport type AskDocQuestionOptions = {\n onMessage?: (chunk: string) => void;\n};\n\n/**\n * Handles the \"Ask a question\" endpoint in an Express.js route.\n * Processes user messages, retrieves relevant documents, and interacts with AI models to generate responses.\n *\n * @param messages - An array of chat messages from the user and assistant\n * @returns The assistant's response as a string\n */\nexport const askDocQuestion = async (\n messages: ChatCompletionRequestMessage[],\n aiConfig: AIConfig,\n options?: AskDocQuestionOptions\n): Promise<AskDocQuestionResult> => {\n // Format the user's question to keep only the relevant keywords\n const query = messages\n .filter((message) => message.role === 'user')\n .map((message) => `- ${message.content}`)\n .join('\\n');\n\n // 1) Find relevant documents based on the user's question\n const relevantFilesReferences = await searchChunkReference(query);\n\n // 2) Integrate the relevant documents into the initial system prompt\n const systemPrompt = initPrompt.content.replace(\n '{{relevantFilesReferences}}',\n relevantFilesReferences.length === 0\n ? 'Not relevant file found related to the question.'\n : relevantFilesReferences\n .map((doc, idx) =>\n [\n '-----',\n '---',\n `chunkId: ${idx}`,\n `docChunk: \"${doc.chunkNumber}/${doc.fileKey.length}\"`,\n `docName: \"${doc.docName}\"`,\n `docUrl: \"${doc.docUrl}\"`,\n `---`,\n doc.content,\n `-----`,\n ].join('\\n')\n )\n .join('\\n\\n') // Insert relevant docs into the prompt\n );\n\n // Format messages for AI SDK\n const aiMessages = [\n {\n role: 'system' as const,\n content: systemPrompt,\n },\n ...messages.slice(-8),\n ];\n\n if (!aiConfig) {\n throw new Error('Failed to initialize AI configuration');\n }\n\n // 3) Use the AI SDK to stream the response\n let fullResponse = '';\n const stream = streamText({\n ...aiConfig,\n messages: aiMessages,\n });\n\n // Process the stream\n for await (const chunk of stream.textStream) {\n fullResponse += chunk;\n options?.onMessage?.(chunk);\n }\n\n // 4) Extract unique related files\n const relatedFiles = [\n ...new Set(relevantFilesReferences.map((doc) => doc.fileKey)),\n ];\n\n // 5) Return the assistant's response to the user\n return {\n response: fullResponse ?? 'Error: No result found',\n relatedFiles,\n };\n};\n"],"mappings":"AAAA,SAAS,UAAU,SAAS,4BAA4B;AACxD,SAAS,kBAAkB;AAC3B,OAAO,YAAY;AACnB,SAAS,cAAc,qBAAqB;AAC5C,SAAS,2BAA2B;AACpC,SAAS,cAAc;AACvB,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAC9B;AAAA,EAGE;AAAA,OAEK;AACP,OAAO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