@open-mercato/core 0.9.1-develop.7477.1.64ba865101 → 0.9.1-develop.7497.1.543ea44c40
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/.turbo/turbo-build.log +1 -1
- package/dist/modules/business_rules/data/validators.js +8 -3
- package/dist/modules/business_rules/data/validators.js.map +2 -2
- package/dist/modules/catalog/api/dictionaries/[key]/route.js +35 -7
- package/dist/modules/catalog/api/dictionaries/[key]/route.js.map +2 -2
- package/dist/modules/communication_channels/lib/email-mime.js +1 -2
- package/dist/modules/communication_channels/lib/email-mime.js.map +2 -2
- package/dist/modules/configs/cli.js +8 -2
- package/dist/modules/configs/cli.js.map +2 -2
- package/dist/modules/customers/api/companies/[id]/people/route.js +3 -0
- package/dist/modules/customers/api/companies/[id]/people/route.js.map +2 -2
- package/dist/modules/customers/api/companies/route.js +3 -3
- package/dist/modules/customers/api/companies/route.js.map +2 -2
- package/dist/modules/customers/api/deals/[id]/companies/route.js +3 -0
- package/dist/modules/customers/api/deals/[id]/companies/route.js.map +2 -2
- package/dist/modules/customers/api/deals/[id]/people/route.js +3 -0
- package/dist/modules/customers/api/deals/[id]/people/route.js.map +2 -2
- package/dist/modules/customers/api/dictionaries/kind-settings/route.js +6 -0
- package/dist/modules/customers/api/dictionaries/kind-settings/route.js.map +2 -2
- package/dist/modules/customers/api/labels/route.js +10 -1
- package/dist/modules/customers/api/labels/route.js.map +2 -2
- package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js +6 -0
- package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js.map +2 -2
- package/dist/modules/customers/api/people/[id]/companies/enriched/route.js +3 -0
- package/dist/modules/customers/api/people/[id]/companies/enriched/route.js.map +2 -2
- package/dist/modules/customers/api/people/[id]/companies/route.js +6 -0
- package/dist/modules/customers/api/people/[id]/companies/route.js.map +2 -2
- package/dist/modules/customers/api/people/route.js +3 -3
- package/dist/modules/customers/api/people/route.js.map +2 -2
- package/dist/modules/customers/commands/deals.js +2 -0
- package/dist/modules/customers/commands/deals.js.map +2 -2
- package/dist/modules/customers/components/ActivityTypeEditor.js +11 -5
- package/dist/modules/customers/components/ActivityTypeEditor.js.map +2 -2
- package/dist/modules/customers/components/detail/InlineEditors.js +7 -3
- package/dist/modules/customers/components/detail/InlineEditors.js.map +2 -2
- package/dist/modules/customers/components/detail/PersonHighlights.js +1 -1
- package/dist/modules/customers/components/detail/PersonHighlights.js.map +2 -2
- package/dist/modules/customers/components/detail/PlannedActivitiesSection.js +4 -5
- package/dist/modules/customers/components/detail/PlannedActivitiesSection.js.map +2 -2
- package/dist/modules/data_sync/di.js.map +2 -2
- package/dist/modules/data_sync/lib/sync-schedule-service.js +60 -27
- package/dist/modules/data_sync/lib/sync-schedule-service.js.map +2 -2
- package/dist/modules/messages/commands/messages.js +10 -7
- package/dist/modules/messages/commands/messages.js.map +2 -2
- package/dist/modules/messages/lib/constants.js +3 -1
- package/dist/modules/messages/lib/constants.js.map +2 -2
- package/dist/modules/messages/subscribers/message-notification.js +2 -1
- package/dist/modules/messages/subscribers/message-notification.js.map +2 -2
- package/dist/modules/sales/api/documents/factory.js +3 -4
- package/dist/modules/sales/api/documents/factory.js.map +2 -2
- package/dist/modules/sales/commands/payments.js +9 -1
- package/dist/modules/sales/commands/payments.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/business_rules/data/validators.ts +12 -3
- package/src/modules/catalog/api/dictionaries/[key]/route.ts +49 -7
- package/src/modules/communication_channels/lib/email-mime.ts +1 -2
- package/src/modules/configs/cli.ts +10 -1
- package/src/modules/customers/api/companies/[id]/people/route.ts +3 -0
- package/src/modules/customers/api/companies/route.ts +6 -6
- package/src/modules/customers/api/deals/[id]/companies/route.ts +3 -0
- package/src/modules/customers/api/deals/[id]/people/route.ts +3 -0
- package/src/modules/customers/api/dictionaries/kind-settings/route.ts +6 -0
- package/src/modules/customers/api/labels/route.ts +10 -1
- package/src/modules/customers/api/people/[id]/companies/[linkId]/route.ts +6 -0
- package/src/modules/customers/api/people/[id]/companies/enriched/route.ts +3 -0
- package/src/modules/customers/api/people/[id]/companies/route.ts +6 -0
- package/src/modules/customers/api/people/route.ts +6 -6
- package/src/modules/customers/commands/deals.ts +2 -0
- package/src/modules/customers/components/ActivityTypeEditor.tsx +11 -5
- package/src/modules/customers/components/detail/InlineEditors.tsx +8 -4
- package/src/modules/customers/components/detail/PersonHighlights.tsx +4 -1
- package/src/modules/customers/components/detail/PlannedActivitiesSection.tsx +4 -5
- package/src/modules/customers/i18n/de.json +2 -0
- package/src/modules/customers/i18n/en.json +2 -0
- package/src/modules/customers/i18n/es.json +2 -0
- package/src/modules/customers/i18n/ko.json +2 -0
- package/src/modules/customers/i18n/pl.json +2 -0
- package/src/modules/data_sync/di.ts +1 -0
- package/src/modules/data_sync/lib/sync-schedule-service.ts +80 -28
- package/src/modules/messages/commands/messages.ts +10 -7
- package/src/modules/messages/lib/constants.ts +6 -0
- package/src/modules/messages/subscribers/message-notification.ts +2 -0
- package/src/modules/sales/api/documents/factory.ts +6 -7
- package/src/modules/sales/commands/payments.ts +10 -2
package/.turbo/turbo-build.log
CHANGED
|
@@ -107,6 +107,11 @@ const businessRuleBaseFields = {
|
|
|
107
107
|
organizationId: uuid,
|
|
108
108
|
createdBy: z.string().max(50).optional().nullable()
|
|
109
109
|
};
|
|
110
|
+
const businessRuleUpdateFieldOverrides = {
|
|
111
|
+
enabled: z.boolean().optional(),
|
|
112
|
+
priority: z.number().int().min(0).max(9999).optional(),
|
|
113
|
+
version: z.number().int().min(1).optional()
|
|
114
|
+
};
|
|
110
115
|
const createBusinessRuleSchema = z.object({
|
|
111
116
|
...businessRuleBaseFields,
|
|
112
117
|
conditionExpression: conditionExpressionSchema.optional().nullable(),
|
|
@@ -118,7 +123,7 @@ const updateBusinessRuleSchema = z.object({
|
|
|
118
123
|
conditionExpression: conditionExpressionSchema.optional().nullable(),
|
|
119
124
|
successActions: actionsArraySchema,
|
|
120
125
|
failureActions: actionsArraySchema
|
|
121
|
-
}).omit({ tenantId: true, organizationId: true, createdBy: true }).partial().extend({ id: uuid }).superRefine((data, ctx) => refineEffectiveDateRange(data, ctx));
|
|
126
|
+
}).omit({ tenantId: true, organizationId: true, createdBy: true }).partial().extend({ ...businessRuleUpdateFieldOverrides, id: uuid }).superRefine((data, ctx) => refineEffectiveDateRange(data, ctx));
|
|
122
127
|
function createLocalizedBusinessRuleSchema(t) {
|
|
123
128
|
const conditionSchema = createConditionExpressionSchema(t);
|
|
124
129
|
const actionsSchema = createActionsArraySchema(t);
|
|
@@ -139,7 +144,7 @@ function createLocalizedUpdateBusinessRuleSchema(t) {
|
|
|
139
144
|
conditionExpression: conditionSchema.optional().nullable(),
|
|
140
145
|
successActions: actionsSchema,
|
|
141
146
|
failureActions: actionsSchema
|
|
142
|
-
}).omit({ tenantId: true, organizationId: true, createdBy: true }).partial().extend({ id: uuid }).superRefine((data, ctx) => refineEffectiveDateRange(data, ctx, message));
|
|
147
|
+
}).omit({ tenantId: true, organizationId: true, createdBy: true }).partial().extend({ ...businessRuleUpdateFieldOverrides, id: uuid }).superRefine((data, ctx) => refineEffectiveDateRange(data, ctx, message));
|
|
143
148
|
}
|
|
144
149
|
const businessRuleFilterSchema = z.object({
|
|
145
150
|
ruleId: z.string().optional(),
|
|
@@ -186,7 +191,7 @@ const createRuleSetSchema = z.object({
|
|
|
186
191
|
organizationId: uuid,
|
|
187
192
|
createdBy: z.string().max(50).optional().nullable()
|
|
188
193
|
});
|
|
189
|
-
const updateRuleSetSchema = createRuleSetSchema.omit({ tenantId: true, organizationId: true, createdBy: true }).partial().extend({ id: uuid });
|
|
194
|
+
const updateRuleSetSchema = createRuleSetSchema.omit({ tenantId: true, organizationId: true, createdBy: true }).partial().extend({ enabled: z.boolean().optional(), id: uuid });
|
|
190
195
|
const ruleSetFilterSchema = z.object({
|
|
191
196
|
setId: z.string().optional(),
|
|
192
197
|
setName: z.string().optional(),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/business_rules/data/validators.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod'\nimport {\n validateConditionExpressionForApi,\n validateActionsForApi,\n isSafeExpression,\n} from '../lib/payload-validation'\nimport type { TranslatorFn } from '../components/utils/conditionValidation'\n\n/**\n * Business Rules Module - Zod Validators\n */\n\nconst uuid = z.uuid()\n\n// Rule Types\nexport const ruleTypeSchema = z.enum(['GUARD', 'VALIDATION', 'CALCULATION', 'ACTION', 'ASSIGNMENT'])\nexport type RuleType = z.infer<typeof ruleTypeSchema>\n\n// Condition Types\nexport const conditionTypeSchema = z.enum(['EXPRESSION', 'GROUP'])\nexport type ConditionType = z.infer<typeof conditionTypeSchema>\n\n// Logical Operators\nexport const logicalOperatorSchema = z.enum(['AND', 'OR', 'NOT'])\nexport type LogicalOperator = z.infer<typeof logicalOperatorSchema>\n\n// Comparison Operators\nexport const comparisonOperatorSchema = z.enum([\n '=',\n '==',\n '!=',\n '>',\n '>=',\n '<',\n '<=',\n 'IN',\n 'NOT_IN',\n 'CONTAINS',\n 'NOT_CONTAINS',\n 'STARTS_WITH',\n 'ENDS_WITH',\n 'MATCHES',\n 'IS_EMPTY',\n 'IS_NOT_EMPTY',\n])\nexport type ComparisonOperator = z.infer<typeof comparisonOperatorSchema>\n\n// Data Types\nexport const dataTypeSchema = z.enum(['STRING', 'NUMBER', 'BOOLEAN', 'DATE', 'ARRAY', 'OBJECT'])\nexport type DataType = z.infer<typeof dataTypeSchema>\n\n// Action Trigger\nexport const actionTriggerSchema = z.enum(['ON_SUCCESS', 'ON_FAILURE', 'ALWAYS'])\nexport type ActionTrigger = z.infer<typeof actionTriggerSchema>\n\n// Execution Result\nexport const executionResultSchema = z.enum(['SUCCESS', 'FAILURE', 'ERROR'])\nexport type ExecutionResult = z.infer<typeof executionResultSchema>\n\n// Condition Expression Schema with Validation\n// Uses runtime validation to check structure, nesting, and field paths\nfunction createConditionExpressionSchema(t?: TranslatorFn) {\n return z.any()\n .optional()\n .nullable()\n .superRefine((val, ctx) => {\n // Null/undefined is allowed (optional field)\n if (val === null || val === undefined) return\n\n // Check for dangerous patterns first (DoS prevention)\n if (!isSafeExpression(val)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Condition expression exceeds safety limits (max depth: 10, max rules per group: 50, max field path length: 200)'\n })\n return\n }\n\n // Validate structure and content\n const result = validateConditionExpressionForApi(val, t)\n if (!result.valid) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: result.error || 'Invalid condition expression'\n })\n }\n })\n}\n\nexport const conditionExpressionSchema = createConditionExpressionSchema()\n\n// Action Schema with Validation\n// Validates action type and required config fields\nexport const actionSchema = z.object({\n type: z.string().min(1),\n config: z.record(z.string(), z.any()).optional(),\n})\n\nfunction createActionsArraySchema(t?: TranslatorFn) {\n return z.array(actionSchema).optional().nullable()\n .superRefine((val, ctx) => {\n // Null/undefined/empty is allowed (optional field)\n if (!val || (Array.isArray(val) && val.length === 0)) return\n\n const result = validateActionsForApi(val, 'actions', t)\n if (!result.valid) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: result.error || 'Invalid actions'\n })\n }\n })\n}\n\nexport const actionsArraySchema = createActionsArraySchema()\n\n// Date preprocessing helper\nconst dateOrNull = z.preprocess((value) => {\n if (value === undefined || value === null || value === '') return null\n const date = value instanceof Date ? value : new Date(String(value))\n return Number.isNaN(date.getTime()) ? null : date\n}, z.date().nullable())\n\n// Cross-field refine: effectiveTo must be later than effectiveFrom when both are provided.\n// Accepts Date objects, ISO strings, or null/undefined so it works on both the\n// preprocessed server schemas and the string-based client form schema.\nexport const EFFECTIVE_DATE_RANGE_DEFAULT_MESSAGE =\n 'Effective To must be later than Effective From'\n\nfunction toDateOrNull(value: unknown): Date | null {\n if (value === undefined || value === null || value === '') return null\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value\n const parsed = new Date(String(value))\n return Number.isNaN(parsed.getTime()) ? null : parsed\n}\n\nexport function refineEffectiveDateRange(\n data: { effectiveFrom?: unknown; effectiveTo?: unknown },\n ctx: z.RefinementCtx,\n message: string = EFFECTIVE_DATE_RANGE_DEFAULT_MESSAGE,\n): void {\n const from = toDateOrNull(data.effectiveFrom)\n const to = toDateOrNull(data.effectiveTo)\n if (from === null || to === null) return\n if (to.getTime() <= from.getTime()) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message,\n path: ['effectiveTo'],\n })\n }\n}\n\n// BusinessRule base fields (without condition/action schemas)\nconst businessRuleBaseFields = {\n ruleId: z.string().min(1).max(50),\n ruleName: z.string().min(1).max(200),\n description: z.string().max(5000).optional().nullable(),\n ruleType: ruleTypeSchema,\n ruleCategory: z.string().max(50).optional().nullable(),\n entityType: z.string().min(1).max(50),\n eventType: z.string().max(50).optional().nullable(),\n enabled: z.boolean().optional().default(true),\n priority: z.number().int().min(0).max(9999).optional().default(100),\n version: z.number().int().min(1).optional().default(1),\n effectiveFrom: dateOrNull.optional(),\n effectiveTo: dateOrNull.optional(),\n tenantId: uuid,\n organizationId: uuid,\n createdBy: z.string().max(50).optional().nullable(),\n} as const\n\n// Static schemas (without i18n \u2014 used for OpenAPI docs and non-route contexts)\nexport const createBusinessRuleSchema = z\n .object({\n ...businessRuleBaseFields,\n conditionExpression: conditionExpressionSchema.optional().nullable(),\n successActions: actionsArraySchema,\n failureActions: actionsArraySchema,\n })\n .superRefine((data, ctx) => refineEffectiveDateRange(data, ctx))\n\nexport type CreateBusinessRuleInput = z.input<typeof createBusinessRuleSchema>\n\nexport const updateBusinessRuleSchema = z\n .object({\n ...businessRuleBaseFields,\n conditionExpression: conditionExpressionSchema.optional().nullable(),\n successActions: actionsArraySchema,\n failureActions: actionsArraySchema,\n })\n .omit({ tenantId: true, organizationId: true, createdBy: true })\n .partial()\n .extend({ id: uuid })\n .superRefine((data, ctx) => refineEffectiveDateRange(data, ctx))\n\nexport type UpdateBusinessRuleInput = z.input<typeof updateBusinessRuleSchema>\n\n// Factory functions for i18n-aware schemas (used in API routes with resolveTranslations)\nexport function createLocalizedBusinessRuleSchema(t: TranslatorFn) {\n const conditionSchema = createConditionExpressionSchema(t)\n const actionsSchema = createActionsArraySchema(t)\n const message = t('business_rules.rules.form.errors.effectiveToBeforeFrom')\n return z\n .object({\n ...businessRuleBaseFields,\n conditionExpression: conditionSchema.optional().nullable(),\n successActions: actionsSchema,\n failureActions: actionsSchema,\n })\n .superRefine((data, ctx) => refineEffectiveDateRange(data, ctx, message))\n}\n\nexport function createLocalizedUpdateBusinessRuleSchema(t: TranslatorFn) {\n const conditionSchema = createConditionExpressionSchema(t)\n const actionsSchema = createActionsArraySchema(t)\n const message = t('business_rules.rules.form.errors.effectiveToBeforeFrom')\n return z\n .object({\n ...businessRuleBaseFields,\n conditionExpression: conditionSchema.optional().nullable(),\n successActions: actionsSchema,\n failureActions: actionsSchema,\n })\n .omit({ tenantId: true, organizationId: true, createdBy: true })\n .partial()\n .extend({ id: uuid })\n .superRefine((data, ctx) => refineEffectiveDateRange(data, ctx, message))\n}\n\n// Query/Filter Schema\nexport const businessRuleFilterSchema = z.object({\n ruleId: z.string().optional(),\n ruleName: z.string().optional(),\n ruleType: ruleTypeSchema.optional(),\n ruleCategory: z.string().optional(),\n entityType: z.string().optional(),\n eventType: z.string().optional(),\n enabled: z.boolean().optional(),\n tenantId: uuid.optional(),\n organizationId: uuid.optional(),\n})\n\nexport type BusinessRuleFilter = z.infer<typeof businessRuleFilterSchema>\n\n// RuleExecutionLog Create Schema\nexport const createRuleExecutionLogSchema = z.object({\n ruleId: uuid,\n entityId: uuid,\n entityType: z.string().min(1).max(50),\n executionResult: executionResultSchema,\n inputContext: z.any().optional().nullable(),\n outputContext: z.any().optional().nullable(),\n errorMessage: z.string().optional().nullable(),\n executionTimeMs: z.number().int().min(0),\n executedAt: z.date().optional(),\n tenantId: uuid,\n organizationId: uuid.optional().nullable(),\n executedBy: z.string().max(50).optional().nullable(),\n})\n\nexport type CreateRuleExecutionLogInput = z.infer<typeof createRuleExecutionLogSchema>\n\n// RuleExecutionLog Query/Filter Schema\nexport const ruleExecutionLogFilterSchema = z.object({\n ruleId: uuid.optional(),\n entityId: uuid.optional(),\n entityType: z.string().optional(),\n executionResult: executionResultSchema.optional(),\n tenantId: uuid.optional(),\n organizationId: uuid.optional(),\n executedBy: z.string().optional(),\n executedAtFrom: z.date().optional(),\n executedAtTo: z.date().optional(),\n})\n\nexport type RuleExecutionLogFilter = z.infer<typeof ruleExecutionLogFilterSchema>\n\n// RuleSet Create Schema\nexport const createRuleSetSchema = z.object({\n setId: z.string().min(1).max(50),\n setName: z.string().min(1).max(200),\n description: z.string().max(5000).optional().nullable(),\n enabled: z.boolean().optional().default(true),\n tenantId: uuid,\n organizationId: uuid,\n createdBy: z.string().max(50).optional().nullable(),\n})\n\nexport type CreateRuleSetInput = z.infer<typeof createRuleSetSchema>\n\n// RuleSet Update Schema\nexport const updateRuleSetSchema = createRuleSetSchema\n .omit({ tenantId: true, organizationId: true, createdBy: true })\n .partial()\n .extend({ id: uuid })\n\nexport type UpdateRuleSetInput = z.infer<typeof updateRuleSetSchema>\n\n// RuleSet Query/Filter Schema\nexport const ruleSetFilterSchema = z.object({\n setId: z.string().optional(),\n setName: z.string().optional(),\n enabled: z.boolean().optional(),\n tenantId: uuid.optional(),\n organizationId: uuid.optional(),\n})\n\nexport type RuleSetFilter = z.infer<typeof ruleSetFilterSchema>\n\n// RuleSetMember Create Schema\nexport const createRuleSetMemberSchema = z.object({\n ruleSetId: uuid,\n ruleId: uuid,\n sequence: z.number().int().min(0).optional().default(0),\n enabled: z.boolean().optional().default(true),\n tenantId: uuid,\n organizationId: uuid,\n})\n\nexport type CreateRuleSetMemberInput = z.infer<typeof createRuleSetMemberSchema>\n\n// RuleSetMember Update Schema\nexport const updateRuleSetMemberSchema = z.object({\n id: uuid,\n sequence: z.number().int().min(0).optional(),\n enabled: z.boolean().optional(),\n})\n\nexport type UpdateRuleSetMemberInput = z.infer<typeof updateRuleSetMemberSchema>\n\n// RuleSetMember Query/Filter Schema\nexport const ruleSetMemberFilterSchema = z.object({\n ruleSetId: uuid.optional(),\n ruleId: uuid.optional(),\n enabled: z.boolean().optional(),\n tenantId: uuid.optional(),\n organizationId: uuid.optional(),\n})\n\nexport type RuleSetMemberFilter = z.infer<typeof ruleSetMemberFilterSchema>\n\n// Rule Engine Context Schema\nexport const ruleEngineContextSchema = z.looseObject({\n entityType: z.string().min(1, 'entityType is required'),\n entityId: z.string().optional(),\n eventType: z.string().optional(),\n data: z.any(),\n user: z.looseObject({\n id: z.string().optional(),\n email: z.string().optional(),\n role: z.string().optional(),\n }).optional(),\n tenant: z.looseObject({\n id: z.string().optional(),\n }).optional(),\n organization: z.looseObject({\n id: z.string().optional(),\n }).optional(),\n tenantId: z.uuid('tenantId must be a valid UUID'),\n organizationId: z.uuid('organizationId must be a valid UUID'),\n executedBy: z.string().optional(),\n dryRun: z.boolean().optional(),\n})\n\nexport type RuleEngineContextInput = z.infer<typeof ruleEngineContextSchema>\n\n// Rule Discovery Options Schema\nexport const ruleDiscoveryOptionsSchema = z.object({\n entityType: z.string().min(1, 'entityType is required'),\n eventType: z.string().optional(),\n tenantId: z.uuid('tenantId must be a valid UUID'),\n organizationId: z.uuid('organizationId must be a valid UUID'),\n ruleType: ruleTypeSchema.optional(),\n})\n\nexport type RuleDiscoveryOptionsInput = z.infer<typeof ruleDiscoveryOptionsSchema>\n\n// Direct Rule Execution Context Schema (for executing a specific rule by ID)\nexport const directRuleExecutionContextSchema = z.object({\n ruleId: z.uuid('ruleId must be a valid UUID'),\n data: z.any(),\n user: z.looseObject({\n id: z.string().optional(),\n email: z.string().optional(),\n role: z.string().optional(),\n }).optional(),\n tenantId: z.uuid('tenantId must be a valid UUID'),\n organizationId: z.uuid('organizationId must be a valid UUID'),\n executedBy: z.string().optional(),\n dryRun: z.boolean().optional(),\n // See `ruleIdExecutionContextSchema.skipActions`.\n skipActions: z.boolean().optional(),\n entityType: z.string().optional(),\n entityId: z.string().optional(),\n eventType: z.string().optional(),\n})\n\nexport type DirectRuleExecutionContextInput = z.infer<typeof directRuleExecutionContextSchema>\n\n// Rule ID Execution Context Schema (for executing a specific rule by its string rule_id identifier)\nexport const ruleIdExecutionContextSchema = z.object({\n ruleId: z.string().min(1, 'ruleId must be a non-empty string').max(50),\n data: z.any(),\n user: z.looseObject({\n id: z.string().optional(),\n email: z.string().optional(),\n role: z.string().optional(),\n }).optional(),\n tenantId: z.uuid('tenantId must be a valid UUID'),\n organizationId: z.uuid('organizationId must be a valid UUID'),\n executedBy: z.string().optional(),\n dryRun: z.boolean().optional(),\n // Evaluate the conditions but do not run the rule's success/failure ACTIONS.\n // `dryRun` only suppresses the execution LOG, so it is not the flag a caller\n // that must produce no side effects can rely on.\n skipActions: z.boolean().optional(),\n entityType: z.string().optional(),\n entityId: z.string().optional(),\n eventType: z.string().optional(),\n})\n\nexport type RuleIdExecutionContextInput = z.infer<typeof ruleIdExecutionContextSchema>\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,MAAM,OAAO,EAAE,KAAK;AAGb,MAAM,iBAAiB,EAAE,KAAK,CAAC,SAAS,cAAc,eAAe,UAAU,YAAY,CAAC;AAI5F,MAAM,sBAAsB,EAAE,KAAK,CAAC,cAAc,OAAO,CAAC;AAI1D,MAAM,wBAAwB,EAAE,KAAK,CAAC,OAAO,MAAM,KAAK,CAAC;AAIzD,MAAM,2BAA2B,EAAE,KAAK;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAIM,MAAM,iBAAiB,EAAE,KAAK,CAAC,UAAU,UAAU,WAAW,QAAQ,SAAS,QAAQ,CAAC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C,EAAE,IAAI,EAAE;AAAA,EACpC,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,SAAS,EAAE,SAAS;AAAA,EAClD,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EAC5C,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,IAAI,EAAE,SAAS,EAAE,QAAQ,GAAG;AAAA,EAClE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,SAAS,EAAE,QAAQ,CAAC;AAAA,EACrD,eAAe,WAAW,SAAS;AAAA,EACnC,aAAa,WAAW,SAAS;AAAA,EACjC,UAAU;AAAA,EACV,gBAAgB;AAAA,EAChB,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,SAAS,EAAE,SAAS;AACpD;AAGO,MAAM,2BAA2B,EACrC,OAAO;AAAA,EACN,GAAG;AAAA,EACH,qBAAqB,0BAA0B,SAAS,EAAE,SAAS;AAAA,EACnE,gBAAgB;AAAA,EAChB,gBAAgB;AAClB,CAAC,EACA,YAAY,CAAC,MAAM,QAAQ,yBAAyB,MAAM,GAAG,CAAC;AAI1D,MAAM,2BAA2B,EACrC,OAAO;AAAA,EACN,GAAG;AAAA,EACH,qBAAqB,0BAA0B,SAAS,EAAE,SAAS;AAAA,EACnE,gBAAgB;AAAA,EAChB,gBAAgB;AAClB,CAAC,EACA,KAAK,EAAE,UAAU,MAAM,gBAAgB,MAAM,WAAW,KAAK,CAAC,EAC9D,QAAQ,EACR,OAAO,EAAE,IAAI,KAAK,CAAC,
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod'\nimport {\n validateConditionExpressionForApi,\n validateActionsForApi,\n isSafeExpression,\n} from '../lib/payload-validation'\nimport type { TranslatorFn } from '../components/utils/conditionValidation'\n\n/**\n * Business Rules Module - Zod Validators\n */\n\nconst uuid = z.uuid()\n\n// Rule Types\nexport const ruleTypeSchema = z.enum(['GUARD', 'VALIDATION', 'CALCULATION', 'ACTION', 'ASSIGNMENT'])\nexport type RuleType = z.infer<typeof ruleTypeSchema>\n\n// Condition Types\nexport const conditionTypeSchema = z.enum(['EXPRESSION', 'GROUP'])\nexport type ConditionType = z.infer<typeof conditionTypeSchema>\n\n// Logical Operators\nexport const logicalOperatorSchema = z.enum(['AND', 'OR', 'NOT'])\nexport type LogicalOperator = z.infer<typeof logicalOperatorSchema>\n\n// Comparison Operators\nexport const comparisonOperatorSchema = z.enum([\n '=',\n '==',\n '!=',\n '>',\n '>=',\n '<',\n '<=',\n 'IN',\n 'NOT_IN',\n 'CONTAINS',\n 'NOT_CONTAINS',\n 'STARTS_WITH',\n 'ENDS_WITH',\n 'MATCHES',\n 'IS_EMPTY',\n 'IS_NOT_EMPTY',\n])\nexport type ComparisonOperator = z.infer<typeof comparisonOperatorSchema>\n\n// Data Types\nexport const dataTypeSchema = z.enum(['STRING', 'NUMBER', 'BOOLEAN', 'DATE', 'ARRAY', 'OBJECT'])\nexport type DataType = z.infer<typeof dataTypeSchema>\n\n// Action Trigger\nexport const actionTriggerSchema = z.enum(['ON_SUCCESS', 'ON_FAILURE', 'ALWAYS'])\nexport type ActionTrigger = z.infer<typeof actionTriggerSchema>\n\n// Execution Result\nexport const executionResultSchema = z.enum(['SUCCESS', 'FAILURE', 'ERROR'])\nexport type ExecutionResult = z.infer<typeof executionResultSchema>\n\n// Condition Expression Schema with Validation\n// Uses runtime validation to check structure, nesting, and field paths\nfunction createConditionExpressionSchema(t?: TranslatorFn) {\n return z.any()\n .optional()\n .nullable()\n .superRefine((val, ctx) => {\n // Null/undefined is allowed (optional field)\n if (val === null || val === undefined) return\n\n // Check for dangerous patterns first (DoS prevention)\n if (!isSafeExpression(val)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Condition expression exceeds safety limits (max depth: 10, max rules per group: 50, max field path length: 200)'\n })\n return\n }\n\n // Validate structure and content\n const result = validateConditionExpressionForApi(val, t)\n if (!result.valid) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: result.error || 'Invalid condition expression'\n })\n }\n })\n}\n\nexport const conditionExpressionSchema = createConditionExpressionSchema()\n\n// Action Schema with Validation\n// Validates action type and required config fields\nexport const actionSchema = z.object({\n type: z.string().min(1),\n config: z.record(z.string(), z.any()).optional(),\n})\n\nfunction createActionsArraySchema(t?: TranslatorFn) {\n return z.array(actionSchema).optional().nullable()\n .superRefine((val, ctx) => {\n // Null/undefined/empty is allowed (optional field)\n if (!val || (Array.isArray(val) && val.length === 0)) return\n\n const result = validateActionsForApi(val, 'actions', t)\n if (!result.valid) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: result.error || 'Invalid actions'\n })\n }\n })\n}\n\nexport const actionsArraySchema = createActionsArraySchema()\n\n// Date preprocessing helper\nconst dateOrNull = z.preprocess((value) => {\n if (value === undefined || value === null || value === '') return null\n const date = value instanceof Date ? value : new Date(String(value))\n return Number.isNaN(date.getTime()) ? null : date\n}, z.date().nullable())\n\n// Cross-field refine: effectiveTo must be later than effectiveFrom when both are provided.\n// Accepts Date objects, ISO strings, or null/undefined so it works on both the\n// preprocessed server schemas and the string-based client form schema.\nexport const EFFECTIVE_DATE_RANGE_DEFAULT_MESSAGE =\n 'Effective To must be later than Effective From'\n\nfunction toDateOrNull(value: unknown): Date | null {\n if (value === undefined || value === null || value === '') return null\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value\n const parsed = new Date(String(value))\n return Number.isNaN(parsed.getTime()) ? null : parsed\n}\n\nexport function refineEffectiveDateRange(\n data: { effectiveFrom?: unknown; effectiveTo?: unknown },\n ctx: z.RefinementCtx,\n message: string = EFFECTIVE_DATE_RANGE_DEFAULT_MESSAGE,\n): void {\n const from = toDateOrNull(data.effectiveFrom)\n const to = toDateOrNull(data.effectiveTo)\n if (from === null || to === null) return\n if (to.getTime() <= from.getTime()) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message,\n path: ['effectiveTo'],\n })\n }\n}\n\n// BusinessRule base fields (without condition/action schemas)\nconst businessRuleBaseFields = {\n ruleId: z.string().min(1).max(50),\n ruleName: z.string().min(1).max(200),\n description: z.string().max(5000).optional().nullable(),\n ruleType: ruleTypeSchema,\n ruleCategory: z.string().max(50).optional().nullable(),\n entityType: z.string().min(1).max(50),\n eventType: z.string().max(50).optional().nullable(),\n enabled: z.boolean().optional().default(true),\n priority: z.number().int().min(0).max(9999).optional().default(100),\n version: z.number().int().min(1).optional().default(1),\n effectiveFrom: dateOrNull.optional(),\n effectiveTo: dateOrNull.optional(),\n tenantId: uuid,\n organizationId: uuid,\n createdBy: z.string().max(50).optional().nullable(),\n} as const\n\n// Zod 4 still applies `.default()` to keys omitted from a `.partial()` schema,\n// so update schemas re-declare defaulted fields without defaults to keep\n// partial PUTs from overwriting stored values.\nconst businessRuleUpdateFieldOverrides = {\n enabled: z.boolean().optional(),\n priority: z.number().int().min(0).max(9999).optional(),\n version: z.number().int().min(1).optional(),\n} as const\n\n// Static schemas (without i18n \u2014 used for OpenAPI docs and non-route contexts)\nexport const createBusinessRuleSchema = z\n .object({\n ...businessRuleBaseFields,\n conditionExpression: conditionExpressionSchema.optional().nullable(),\n successActions: actionsArraySchema,\n failureActions: actionsArraySchema,\n })\n .superRefine((data, ctx) => refineEffectiveDateRange(data, ctx))\n\nexport type CreateBusinessRuleInput = z.input<typeof createBusinessRuleSchema>\n\nexport const updateBusinessRuleSchema = z\n .object({\n ...businessRuleBaseFields,\n conditionExpression: conditionExpressionSchema.optional().nullable(),\n successActions: actionsArraySchema,\n failureActions: actionsArraySchema,\n })\n .omit({ tenantId: true, organizationId: true, createdBy: true })\n .partial()\n .extend({ ...businessRuleUpdateFieldOverrides, id: uuid })\n .superRefine((data, ctx) => refineEffectiveDateRange(data, ctx))\n\nexport type UpdateBusinessRuleInput = z.input<typeof updateBusinessRuleSchema>\n\n// Factory functions for i18n-aware schemas (used in API routes with resolveTranslations)\nexport function createLocalizedBusinessRuleSchema(t: TranslatorFn) {\n const conditionSchema = createConditionExpressionSchema(t)\n const actionsSchema = createActionsArraySchema(t)\n const message = t('business_rules.rules.form.errors.effectiveToBeforeFrom')\n return z\n .object({\n ...businessRuleBaseFields,\n conditionExpression: conditionSchema.optional().nullable(),\n successActions: actionsSchema,\n failureActions: actionsSchema,\n })\n .superRefine((data, ctx) => refineEffectiveDateRange(data, ctx, message))\n}\n\nexport function createLocalizedUpdateBusinessRuleSchema(t: TranslatorFn) {\n const conditionSchema = createConditionExpressionSchema(t)\n const actionsSchema = createActionsArraySchema(t)\n const message = t('business_rules.rules.form.errors.effectiveToBeforeFrom')\n return z\n .object({\n ...businessRuleBaseFields,\n conditionExpression: conditionSchema.optional().nullable(),\n successActions: actionsSchema,\n failureActions: actionsSchema,\n })\n .omit({ tenantId: true, organizationId: true, createdBy: true })\n .partial()\n .extend({ ...businessRuleUpdateFieldOverrides, id: uuid })\n .superRefine((data, ctx) => refineEffectiveDateRange(data, ctx, message))\n}\n\n// Query/Filter Schema\nexport const businessRuleFilterSchema = z.object({\n ruleId: z.string().optional(),\n ruleName: z.string().optional(),\n ruleType: ruleTypeSchema.optional(),\n ruleCategory: z.string().optional(),\n entityType: z.string().optional(),\n eventType: z.string().optional(),\n enabled: z.boolean().optional(),\n tenantId: uuid.optional(),\n organizationId: uuid.optional(),\n})\n\nexport type BusinessRuleFilter = z.infer<typeof businessRuleFilterSchema>\n\n// RuleExecutionLog Create Schema\nexport const createRuleExecutionLogSchema = z.object({\n ruleId: uuid,\n entityId: uuid,\n entityType: z.string().min(1).max(50),\n executionResult: executionResultSchema,\n inputContext: z.any().optional().nullable(),\n outputContext: z.any().optional().nullable(),\n errorMessage: z.string().optional().nullable(),\n executionTimeMs: z.number().int().min(0),\n executedAt: z.date().optional(),\n tenantId: uuid,\n organizationId: uuid.optional().nullable(),\n executedBy: z.string().max(50).optional().nullable(),\n})\n\nexport type CreateRuleExecutionLogInput = z.infer<typeof createRuleExecutionLogSchema>\n\n// RuleExecutionLog Query/Filter Schema\nexport const ruleExecutionLogFilterSchema = z.object({\n ruleId: uuid.optional(),\n entityId: uuid.optional(),\n entityType: z.string().optional(),\n executionResult: executionResultSchema.optional(),\n tenantId: uuid.optional(),\n organizationId: uuid.optional(),\n executedBy: z.string().optional(),\n executedAtFrom: z.date().optional(),\n executedAtTo: z.date().optional(),\n})\n\nexport type RuleExecutionLogFilter = z.infer<typeof ruleExecutionLogFilterSchema>\n\n// RuleSet Create Schema\nexport const createRuleSetSchema = z.object({\n setId: z.string().min(1).max(50),\n setName: z.string().min(1).max(200),\n description: z.string().max(5000).optional().nullable(),\n enabled: z.boolean().optional().default(true),\n tenantId: uuid,\n organizationId: uuid,\n createdBy: z.string().max(50).optional().nullable(),\n})\n\nexport type CreateRuleSetInput = z.infer<typeof createRuleSetSchema>\n\n// RuleSet Update Schema\nexport const updateRuleSetSchema = createRuleSetSchema\n .omit({ tenantId: true, organizationId: true, createdBy: true })\n .partial()\n .extend({ enabled: z.boolean().optional(), id: uuid })\n\nexport type UpdateRuleSetInput = z.infer<typeof updateRuleSetSchema>\n\n// RuleSet Query/Filter Schema\nexport const ruleSetFilterSchema = z.object({\n setId: z.string().optional(),\n setName: z.string().optional(),\n enabled: z.boolean().optional(),\n tenantId: uuid.optional(),\n organizationId: uuid.optional(),\n})\n\nexport type RuleSetFilter = z.infer<typeof ruleSetFilterSchema>\n\n// RuleSetMember Create Schema\nexport const createRuleSetMemberSchema = z.object({\n ruleSetId: uuid,\n ruleId: uuid,\n sequence: z.number().int().min(0).optional().default(0),\n enabled: z.boolean().optional().default(true),\n tenantId: uuid,\n organizationId: uuid,\n})\n\nexport type CreateRuleSetMemberInput = z.infer<typeof createRuleSetMemberSchema>\n\n// RuleSetMember Update Schema\nexport const updateRuleSetMemberSchema = z.object({\n id: uuid,\n sequence: z.number().int().min(0).optional(),\n enabled: z.boolean().optional(),\n})\n\nexport type UpdateRuleSetMemberInput = z.infer<typeof updateRuleSetMemberSchema>\n\n// RuleSetMember Query/Filter Schema\nexport const ruleSetMemberFilterSchema = z.object({\n ruleSetId: uuid.optional(),\n ruleId: uuid.optional(),\n enabled: z.boolean().optional(),\n tenantId: uuid.optional(),\n organizationId: uuid.optional(),\n})\n\nexport type RuleSetMemberFilter = z.infer<typeof ruleSetMemberFilterSchema>\n\n// Rule Engine Context Schema\nexport const ruleEngineContextSchema = z.looseObject({\n entityType: z.string().min(1, 'entityType is required'),\n entityId: z.string().optional(),\n eventType: z.string().optional(),\n data: z.any(),\n user: z.looseObject({\n id: z.string().optional(),\n email: z.string().optional(),\n role: z.string().optional(),\n }).optional(),\n tenant: z.looseObject({\n id: z.string().optional(),\n }).optional(),\n organization: z.looseObject({\n id: z.string().optional(),\n }).optional(),\n tenantId: z.uuid('tenantId must be a valid UUID'),\n organizationId: z.uuid('organizationId must be a valid UUID'),\n executedBy: z.string().optional(),\n dryRun: z.boolean().optional(),\n})\n\nexport type RuleEngineContextInput = z.infer<typeof ruleEngineContextSchema>\n\n// Rule Discovery Options Schema\nexport const ruleDiscoveryOptionsSchema = z.object({\n entityType: z.string().min(1, 'entityType is required'),\n eventType: z.string().optional(),\n tenantId: z.uuid('tenantId must be a valid UUID'),\n organizationId: z.uuid('organizationId must be a valid UUID'),\n ruleType: ruleTypeSchema.optional(),\n})\n\nexport type RuleDiscoveryOptionsInput = z.infer<typeof ruleDiscoveryOptionsSchema>\n\n// Direct Rule Execution Context Schema (for executing a specific rule by ID)\nexport const directRuleExecutionContextSchema = z.object({\n ruleId: z.uuid('ruleId must be a valid UUID'),\n data: z.any(),\n user: z.looseObject({\n id: z.string().optional(),\n email: z.string().optional(),\n role: z.string().optional(),\n }).optional(),\n tenantId: z.uuid('tenantId must be a valid UUID'),\n organizationId: z.uuid('organizationId must be a valid UUID'),\n executedBy: z.string().optional(),\n dryRun: z.boolean().optional(),\n // See `ruleIdExecutionContextSchema.skipActions`.\n skipActions: z.boolean().optional(),\n entityType: z.string().optional(),\n entityId: z.string().optional(),\n eventType: z.string().optional(),\n})\n\nexport type DirectRuleExecutionContextInput = z.infer<typeof directRuleExecutionContextSchema>\n\n// Rule ID Execution Context Schema (for executing a specific rule by its string rule_id identifier)\nexport const ruleIdExecutionContextSchema = z.object({\n ruleId: z.string().min(1, 'ruleId must be a non-empty string').max(50),\n data: z.any(),\n user: z.looseObject({\n id: z.string().optional(),\n email: z.string().optional(),\n role: z.string().optional(),\n }).optional(),\n tenantId: z.uuid('tenantId must be a valid UUID'),\n organizationId: z.uuid('organizationId must be a valid UUID'),\n executedBy: z.string().optional(),\n dryRun: z.boolean().optional(),\n // Evaluate the conditions but do not run the rule's success/failure ACTIONS.\n // `dryRun` only suppresses the execution LOG, so it is not the flag a caller\n // that must produce no side effects can rely on.\n skipActions: z.boolean().optional(),\n entityType: z.string().optional(),\n entityId: z.string().optional(),\n eventType: z.string().optional(),\n})\n\nexport type RuleIdExecutionContextInput = z.infer<typeof ruleIdExecutionContextSchema>\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,MAAM,OAAO,EAAE,KAAK;AAGb,MAAM,iBAAiB,EAAE,KAAK,CAAC,SAAS,cAAc,eAAe,UAAU,YAAY,CAAC;AAI5F,MAAM,sBAAsB,EAAE,KAAK,CAAC,cAAc,OAAO,CAAC;AAI1D,MAAM,wBAAwB,EAAE,KAAK,CAAC,OAAO,MAAM,KAAK,CAAC;AAIzD,MAAM,2BAA2B,EAAE,KAAK;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAIM,MAAM,iBAAiB,EAAE,KAAK,CAAC,UAAU,UAAU,WAAW,QAAQ,SAAS,QAAQ,CAAC;AAIxF,MAAM,sBAAsB,EAAE,KAAK,CAAC,cAAc,c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-mercato/core/modules/dictiona
|
|
|
4
4
|
import { resolveDictionariesRouteContext } from "@open-mercato/core/modules/dictionaries/api/context";
|
|
5
5
|
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
6
6
|
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
7
|
+
import { getTranslationOverlayPlugin } from "@open-mercato/shared/lib/localization/overlay-plugin";
|
|
7
8
|
const logger = createLogger("catalog");
|
|
9
|
+
const DICTIONARY_ENTRY_ENTITY_TYPE = "dictionaries:dictionary_entry";
|
|
10
|
+
async function applyEntryTranslations(req, entries, context) {
|
|
11
|
+
const { overlay, resolveLocale } = getTranslationOverlayPlugin();
|
|
12
|
+
if (!overlay || !resolveLocale || entries.length === 0) return entries;
|
|
13
|
+
const locale = resolveLocale(req);
|
|
14
|
+
if (!locale) return entries;
|
|
15
|
+
try {
|
|
16
|
+
const translated = await overlay(entries, {
|
|
17
|
+
entityType: DICTIONARY_ENTRY_ENTITY_TYPE,
|
|
18
|
+
locale,
|
|
19
|
+
tenantId: context.tenantId,
|
|
20
|
+
organizationId: context.organizationId,
|
|
21
|
+
container: context.container
|
|
22
|
+
});
|
|
23
|
+
const labelsById = /* @__PURE__ */ new Map();
|
|
24
|
+
for (const item of translated) {
|
|
25
|
+
if (typeof item.id === "string" && typeof item.label === "string" && item.label.trim().length > 0) {
|
|
26
|
+
labelsById.set(item.id, item.label);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return entries.map((entry) => ({ ...entry, label: labelsById.get(entry.id) ?? entry.label }));
|
|
30
|
+
} catch (err) {
|
|
31
|
+
logger.warn("catalog.dictionaries.GET Translation overlay failed", { err });
|
|
32
|
+
return entries;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
8
35
|
const KEY_ALIASES = {
|
|
9
36
|
currency: ["currency", "currencies"],
|
|
10
37
|
unit: ["unit", "units", "measurement_units"]
|
|
@@ -43,15 +70,16 @@ async function GET(req, ctx) {
|
|
|
43
70
|
},
|
|
44
71
|
{ orderBy: { label: "asc" } }
|
|
45
72
|
);
|
|
73
|
+
const payload = entries.map((entry) => ({
|
|
74
|
+
id: entry.id,
|
|
75
|
+
value: entry.value,
|
|
76
|
+
label: entry.label,
|
|
77
|
+
color: entry.color ?? null,
|
|
78
|
+
icon: entry.icon ?? null
|
|
79
|
+
}));
|
|
46
80
|
return NextResponse.json({
|
|
47
81
|
id: dictionary.id,
|
|
48
|
-
entries:
|
|
49
|
-
id: entry.id,
|
|
50
|
-
value: entry.value,
|
|
51
|
-
label: entry.label,
|
|
52
|
-
color: entry.color ?? null,
|
|
53
|
-
icon: entry.icon ?? null
|
|
54
|
-
}))
|
|
82
|
+
entries: await applyEntryTranslations(req, payload, context)
|
|
55
83
|
});
|
|
56
84
|
} catch (err) {
|
|
57
85
|
if (isCrudHttpError(err)) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/catalog/api/dictionaries/%5Bkey%5D/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport { resolveDictionariesRouteContext } from '@open-mercato/core/modules/dictionaries/api/context'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('catalog')\n\nconst KEY_ALIASES: Record<string, string[]> = {\n currency: ['currency', 'currencies'],\n unit: ['unit', 'units', 'measurement_units'],\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['catalog.products.manage'] },\n}\n\nexport async function GET(\n req: Request,\n ctx: { params?: { key?: string } },\n): Promise<Response> {\n try {\n const context = await resolveDictionariesRouteContext(req)\n const keyParam = (ctx.params?.key ?? '').toLowerCase().trim()\n if (!keyParam) {\n throw new CrudHttpError(400, { error: 'Dictionary key is required.' })\n }\n const keys = KEY_ALIASES[keyParam] ?? [keyParam]\n const dictionaries = await context.em.find(\n Dictionary,\n {\n tenantId: context.tenantId,\n key: { $in: keys },\n deletedAt: null,\n isActive: true,\n },\n { orderBy: { organizationId: 'asc', createdAt: 'asc' } },\n )\n const dictionary =\n dictionaries.find((entry) => entry.organizationId === context.organizationId) ??\n dictionaries[0] ??\n null\n if (!dictionary) {\n return NextResponse.json({ error: 'Dictionary not found.' }, { status: 404 })\n }\n const entries = await context.em.find(\n DictionaryEntry,\n {\n dictionary,\n organizationId: dictionary.organizationId,\n tenantId: dictionary.tenantId,\n },\n { orderBy: { label: 'asc' } },\n )\n
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,YAAY,uBAAuB;AAC5C,SAAS,uCAAuC;AAChD,SAAS,eAAe,uBAAuB;AAE/C,SAAS,oBAAoB;
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport { resolveDictionariesRouteContext } from '@open-mercato/core/modules/dictionaries/api/context'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTranslationOverlayPlugin } from '@open-mercato/shared/lib/localization/overlay-plugin'\n\nconst logger = createLogger('catalog')\n\nconst DICTIONARY_ENTRY_ENTITY_TYPE = 'dictionaries:dictionary_entry'\n\ntype DictionaryEntryPayload = {\n id: string\n value: string\n label: string\n color: string | null\n icon: string | null\n}\n\nasync function applyEntryTranslations(\n req: Request,\n entries: DictionaryEntryPayload[],\n context: Awaited<ReturnType<typeof resolveDictionariesRouteContext>>,\n): Promise<DictionaryEntryPayload[]> {\n const { overlay, resolveLocale } = getTranslationOverlayPlugin()\n if (!overlay || !resolveLocale || entries.length === 0) return entries\n const locale = resolveLocale(req)\n if (!locale) return entries\n try {\n const translated = await overlay(entries, {\n entityType: DICTIONARY_ENTRY_ENTITY_TYPE,\n locale,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n container: context.container,\n })\n const labelsById = new Map<string, string>()\n for (const item of translated) {\n if (typeof item.id === 'string' && typeof item.label === 'string' && item.label.trim().length > 0) {\n labelsById.set(item.id, item.label)\n }\n }\n return entries.map((entry) => ({ ...entry, label: labelsById.get(entry.id) ?? entry.label }))\n } catch (err) {\n logger.warn('catalog.dictionaries.GET Translation overlay failed', { err })\n return entries\n }\n}\n\nconst KEY_ALIASES: Record<string, string[]> = {\n currency: ['currency', 'currencies'],\n unit: ['unit', 'units', 'measurement_units'],\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['catalog.products.manage'] },\n}\n\nexport async function GET(\n req: Request,\n ctx: { params?: { key?: string } },\n): Promise<Response> {\n try {\n const context = await resolveDictionariesRouteContext(req)\n const keyParam = (ctx.params?.key ?? '').toLowerCase().trim()\n if (!keyParam) {\n throw new CrudHttpError(400, { error: 'Dictionary key is required.' })\n }\n const keys = KEY_ALIASES[keyParam] ?? [keyParam]\n const dictionaries = await context.em.find(\n Dictionary,\n {\n tenantId: context.tenantId,\n key: { $in: keys },\n deletedAt: null,\n isActive: true,\n },\n { orderBy: { organizationId: 'asc', createdAt: 'asc' } },\n )\n const dictionary =\n dictionaries.find((entry) => entry.organizationId === context.organizationId) ??\n dictionaries[0] ??\n null\n if (!dictionary) {\n return NextResponse.json({ error: 'Dictionary not found.' }, { status: 404 })\n }\n const entries = await context.em.find(\n DictionaryEntry,\n {\n dictionary,\n organizationId: dictionary.organizationId,\n tenantId: dictionary.tenantId,\n },\n { orderBy: { label: 'asc' } },\n )\n const payload = entries.map((entry) => ({\n id: entry.id,\n value: entry.value,\n label: entry.label,\n color: entry.color ?? null,\n icon: entry.icon ?? null,\n }))\n return NextResponse.json({\n id: dictionary.id,\n entries: await applyEntryTranslations(req, payload, context),\n })\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n logger.error('catalog.dictionaries.GET Unexpected error', { err })\n return NextResponse.json({ error: 'Failed to load dictionary.' }, { status: 500 })\n }\n}\n\nconst dictionaryEntrySchema = z.object({\n id: z.string().uuid(),\n value: z.string(),\n label: z.string(),\n color: z.string().nullable(),\n icon: z.string().nullable(),\n})\n\nconst dictionaryResponseSchema = z.object({\n id: z.string().uuid(),\n entries: z.array(dictionaryEntrySchema),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Catalog',\n summary: 'Catalog Dictionary lookup',\n methods: {\n GET: {\n summary: 'Get dictionary entries by key',\n description: 'Returns dictionary entries for a specific key (e.g., currency, unit).',\n responses: [\n {\n status: 200,\n description: 'Dictionary entries',\n schema: dictionaryResponseSchema,\n },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,YAAY,uBAAuB;AAC5C,SAAS,uCAAuC;AAChD,SAAS,eAAe,uBAAuB;AAE/C,SAAS,oBAAoB;AAC7B,SAAS,mCAAmC;AAE5C,MAAM,SAAS,aAAa,SAAS;AAErC,MAAM,+BAA+B;AAUrC,eAAe,uBACb,KACA,SACA,SACmC;AACnC,QAAM,EAAE,SAAS,cAAc,IAAI,4BAA4B;AAC/D,MAAI,CAAC,WAAW,CAAC,iBAAiB,QAAQ,WAAW,EAAG,QAAO;AAC/D,QAAM,SAAS,cAAc,GAAG;AAChC,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI;AACF,UAAM,aAAa,MAAM,QAAQ,SAAS;AAAA,MACxC,YAAY;AAAA,MACZ;AAAA,MACA,UAAU,QAAQ;AAAA,MAClB,gBAAgB,QAAQ;AAAA,MACxB,WAAW,QAAQ;AAAA,IACrB,CAAC;AACD,UAAM,aAAa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AC;AAEM,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -121,7 +121,6 @@ function assembleRfc2822(input) {
|
|
|
121
121
|
const textPart2 = encodeBodyPart(input.text);
|
|
122
122
|
const htmlPart = encodeBodyPart(input.html);
|
|
123
123
|
const body = [
|
|
124
|
-
"",
|
|
125
124
|
`--${boundary}`,
|
|
126
125
|
"Content-Type: text/plain; charset=utf-8",
|
|
127
126
|
`Content-Transfer-Encoding: ${textPart2.cte}`,
|
|
@@ -135,7 +134,7 @@ function assembleRfc2822(input) {
|
|
|
135
134
|
`--${boundary}--`,
|
|
136
135
|
""
|
|
137
136
|
].join("\r\n");
|
|
138
|
-
return Buffer.from(headers.join("\r\n") + body, "utf-8");
|
|
137
|
+
return Buffer.from(headers.join("\r\n") + "\r\n\r\n" + body, "utf-8");
|
|
139
138
|
}
|
|
140
139
|
if (input.html) {
|
|
141
140
|
const htmlPart = encodeBodyPart(input.html);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/communication_channels/lib/email-mime.ts"],
|
|
4
|
-
"sourcesContent": ["import crypto from 'node:crypto'\nimport type { NormalizedInboundMessage, NormalizedAttachment } from './adapter'\nimport { EMAIL_MAX_ATTACHMENT_BYTES } from './email-capabilities'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('communication_channels').child({ component: 'email-mime' })\n\n/**\n * Aggregate ceiling for all attachments on a single inbound message. Inbound\n * mail is untrusted, so without a cap a malicious/large message would be fully\n * base64-buffered in memory (~1.33x raw bytes) and persisted. Allow a small\n * multiple of the per-attachment limit for legitimate multi-file emails.\n */\nconst TOTAL_INBOUND_ATTACHMENTS_MAX_BYTES = EMAIL_MAX_ATTACHMENT_BYTES * 2\n\n/**\n * Shared email MIME helpers for the email channel providers (Gmail, IMAP).\n * Outbound assembly, inbound parsing, header/address normalization,\n * and threading-id extraction all live here so every provider shares one\n * correct implementation instead of copy-pasting (which previously let Gmail's\n * `extractHeaders` drift into a Map-handling bug that IMAP had already fixed).\n *\n * Provider-specific transport (Gmail History API, IMAP UID sync)\n * stays in each package \u2014 this module only owns the format-level plumbing.\n */\n\n// \u2500\u2500 Outbound MIME helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function stringOrUndefined(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nexport function toAddressList(value: unknown): string[] {\n if (Array.isArray(value)) return value.map((v) => String(v).trim()).filter((v) => v.length > 0)\n if (typeof value === 'string') {\n return value\n .split(/[,;]\\s*/)\n .map((v) => v.trim())\n .filter((v) => v.length > 0)\n }\n return []\n}\n\nexport function referencesFromMeta(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined\n return value.filter((entry): entry is string => typeof entry === 'string')\n}\n\n/**\n * Strip every `<tag>\u2026</tag>` block (and its contents) for a single tag name.\n * Inbound HTML is untrusted, so the matcher must resist evasion: the close tag\n * allows trailing attributes/whitespace (`</script >`, `</style foo>`), the `i`\n * flag covers mixed case, and the replacement loops until the string is stable\n * so a payload split across nested or reconstructed tags cannot survive a\n * single pass (`<scr<script>ipt>` collapsing back into `<script>`).\n *\n * The opening tag is also matched when it is truncated or never closed \u2014 a bare\n * `<script` or an unterminated `<script>\u2026` running to end-of-input is removed\n * outright \u2014 so no prefix of the element name can leak into the output.\n */\nfunction stripTagBlocks(html: string, tag: string): string {\n const blockPattern = new RegExp(\n `<${tag}\\\\b[^>]*(?:>[\\\\s\\\\S]*?(?:<\\\\/${tag}[^>]*>|$)|$)`,\n 'gi',\n )\n let previous: string\n let current = html\n do {\n previous = current\n current = current.replace(blockPattern, ' ')\n } while (current !== previous)\n return current\n}\n\n/**\n * Drop HTML comments (`<!-- \u2026 -->`), including an unterminated comment running\n * to end-of-input. Comments are stripped first because they can wrap content\n * that would otherwise survive tag removal (`<!--<script-->`), and a naive\n * filter that ignores them leaves a tag fragment behind.\n */\nfunction stripHtmlComments(html: string): string {\n return html.replace(/<!--[\\s\\S]*?(?:-->|$)/g, ' ')\n}\n\nconst BASIC_HTML_ENTITIES: Record<string, string> = {\n ' ': ' ',\n '<': '<',\n '>': '>',\n '"': '\"',\n '&': '&',\n}\n\n/**\n * Decode the handful of HTML entities we surface in plaintext in ONE\n * left-to-right pass. A single pass cannot double-unescape: characters produced\n * by a replacement (e.g. the `&` from `&`) are never re-scanned, so\n * `&lt;` decodes to the literal `<` rather than collapsing into `<`.\n */\nfunction decodeBasicEntities(input: string): string {\n return input.replace(\n /&(?:nbsp|lt|gt|quot|amp);/gi,\n (match) => BASIC_HTML_ENTITIES[match.toLowerCase()] ?? match,\n )\n}\n\n/**\n * Remove every remaining `<\u2026>` tag, looping until the string is stable so a tag\n * reconstructed by a single pass (`<<div>div>`) cannot survive \u2014 the same\n * loop-until-stable shape `stripTagBlocks` uses. A raw `<` that is not part of a\n * tag (`a < b`) has no closing `>`, never matches, and is intentionally kept.\n */\nfunction stripRemainingTags(html: string): string {\n let previous: string\n let current = html\n do {\n previous = current\n current = current.replace(/<[^>]*>/g, '')\n } while (current !== previous)\n return current\n}\n\n/**\n * Convert untrusted inbound HTML to plaintext. Entities are decoded FIRST so any\n * entity-encoded markup (e.g. `<script>`) is normalized into real tag\n * syntax before the strippers run \u2014 otherwise decoding last would reintroduce a\n * `<script` fragment into the final output after sanitization had finished\n * (CodeQL `js/incomplete-multi-character-sanitization`). After decoding, all\n * tag removal (script/style blocks, then remaining tags) happens via\n * loop-until-stable passes, so no `<tag` prefix can leak into the plaintext.\n */\nexport function htmlToText(html: string): string {\n const decoded = decodeBasicEntities(html)\n const stripped = stripTagBlocks(stripTagBlocks(stripHtmlComments(decoded), 'style'), 'script')\n .replace(/<br\\s*\\/?>(?=\\s*)/gi, '\\n')\n .replace(/<\\/p\\s*>/gi, '\\n\\n')\n return stripRemainingTags(stripped)\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim()\n}\n\nexport function escapeQuotes(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')\n}\n\n/**\n * Collapse CR/LF/TAB in an email header value to a single space to prevent\n * RFC 5322 header injection \u2014 e.g. a Subject smuggling an extra\n * `Bcc:`/`Content-Type:` header or splitting the message into a body.\n * Collapsing (rather than folding) is safe for the short structured headers\n * we emit (Subject, addresses, Message-ID, References).\n */\nexport function sanitizeHeaderValue(value: string): string {\n return value.replace(/[\\r\\n\\t]+/g, ' ').trim()\n}\n\nexport function ensureBrackets(value: string): string {\n const trimmed = sanitizeHeaderValue(value)\n if (trimmed.startsWith('<') && trimmed.endsWith('>')) return trimmed\n return `<${trimmed}>`\n}\n\nfunction isPureAscii(value: string): boolean {\n // eslint-disable-next-line no-control-regex\n return /^[\\x00-\\x7F]*$/.test(value)\n}\n\n/**\n * Encode a single header value as an RFC 2047 \"B\" (base64) encoded-word when it\n * contains non-ASCII characters, so 8-bit text like \"Caf\u00E9\" survives strict MTAs\n * that treat header bytes as 7-bit ASCII. Pure-ASCII values are returned\n * unchanged. Apply only AFTER `sanitizeHeaderValue` so the CR/LF injection guard\n * still runs against the raw value.\n */\nexport function encodeHeaderWord(value: string): string {\n if (isPureAscii(value)) return value\n return `=?utf-8?B?${Buffer.from(value, 'utf-8').toString('base64')}?=`\n}\n\n/**\n * Encode the display-name part of a single address header value, leaving the\n * `<addr@domain>` untouched (per RFC 2047, encoded-words are not permitted\n * inside the addr-spec). Inputs without a bracketed address are treated as a\n * bare display name / address and encoded only when non-ASCII.\n */\nexport function encodeAddressHeaderWord(value: string): string {\n if (isPureAscii(value)) return value\n const match = value.match(/^(.*?)(\\s*<[^>]*>)\\s*$/)\n if (match) {\n const [, displayPart, addrPart] = match\n const displayName = displayPart.replace(/^\"|\"$/g, '').trim()\n if (!displayName) return value\n return `${encodeHeaderWord(displayName)}${addrPart}`\n }\n return encodeHeaderWord(value)\n}\n\n/**\n * Generate an RFC 5322 Message-ID rooted in the sender's domain. Used as a\n * downstream idempotency key, so entropy comes from `crypto.randomUUID()`\n * rather than `Math.random()`.\n */\nexport function generateMessageId(fromAddress: string, fallbackDomain = 'localhost'): string {\n const domain = fromAddress.split('@')[1] ?? fallbackDomain\n return `<${crypto.randomUUID()}@${domain}>`\n}\n\nexport interface AssembleRfc2822Input {\n from: string\n to: string[]\n cc: string[]\n bcc: string[]\n subject: string | undefined\n text: string | undefined\n html: string | undefined\n inReplyTo: string | undefined\n references: string[] | undefined\n messageId: string\n}\n\n/**\n * Render one MIME body part's CTE header + body content. Non-ASCII bodies are\n * base64-encoded (CRLF-wrapped at 76 cols) and labelled\n * `Content-Transfer-Encoding: base64` so 8-bit text survives strict MTAs;\n * pure-ASCII bodies stay `7bit` and verbatim.\n */\nfunction encodeBodyPart(content: string): { cte: string; body: string } {\n if (isPureAscii(content)) return { cte: '7bit', body: content }\n const base64 = Buffer.from(content, 'utf-8').toString('base64')\n const wrapped = base64.match(/.{1,76}/g)?.join('\\r\\n') ?? base64\n return { cte: 'base64', body: wrapped }\n}\n\n/**\n * Assemble a raw RFC2822 message (used by transports that send the encoded\n * message directly, e.g. Gmail `users.messages.send`). Emits a\n * `multipart/alternative` body when both html and text are present, otherwise a\n * single-part text or html body.\n */\nexport function assembleRfc2822(input: AssembleRfc2822Input): Buffer {\n const boundary = `omc_${crypto.randomUUID()}`\n const headers: string[] = []\n headers.push(`From: ${encodeAddressHeaderWord(sanitizeHeaderValue(input.from))}`)\n headers.push(`To: ${input.to.map((value) => encodeAddressHeaderWord(sanitizeHeaderValue(value))).join(', ')}`)\n if (input.cc.length) headers.push(`Cc: ${input.cc.map((value) => encodeAddressHeaderWord(sanitizeHeaderValue(value))).join(', ')}`)\n if (input.bcc.length) headers.push(`Bcc: ${input.bcc.map((value) => encodeAddressHeaderWord(sanitizeHeaderValue(value))).join(', ')}`)\n if (input.subject) headers.push(`Subject: ${encodeHeaderWord(sanitizeHeaderValue(input.subject))}`)\n headers.push(`Message-ID: ${ensureBrackets(input.messageId)}`)\n if (input.inReplyTo) headers.push(`In-Reply-To: ${ensureBrackets(input.inReplyTo)}`)\n if (input.references && input.references.length) {\n headers.push(`References: ${input.references.map(ensureBrackets).join(' ')}`)\n }\n headers.push('MIME-Version: 1.0')\n headers.push(`Date: ${new Date().toUTCString()}`)\n\n if (input.html && input.text) {\n headers.push(`Content-Type: multipart/alternative; boundary=\"${boundary}\"`)\n const textPart = encodeBodyPart(input.text)\n const htmlPart = encodeBodyPart(input.html)\n const body = [\n '',\n `--${boundary}`,\n 'Content-Type: text/plain; charset=utf-8',\n `Content-Transfer-Encoding: ${textPart.cte}`,\n '',\n textPart.body,\n `--${boundary}`,\n 'Content-Type: text/html; charset=utf-8',\n `Content-Transfer-Encoding: ${htmlPart.cte}`,\n '',\n htmlPart.body,\n `--${boundary}--`,\n '',\n ].join('\\r\\n')\n return Buffer.from(headers.join('\\r\\n') + body, 'utf-8')\n }\n\n if (input.html) {\n const htmlPart = encodeBodyPart(input.html)\n headers.push('Content-Type: text/html; charset=utf-8')\n headers.push(`Content-Transfer-Encoding: ${htmlPart.cte}`)\n return Buffer.from(headers.join('\\r\\n') + '\\r\\n\\r\\n' + htmlPart.body, 'utf-8')\n }\n\n const textPart = encodeBodyPart(input.text ?? '')\n headers.push('Content-Type: text/plain; charset=utf-8')\n headers.push(`Content-Transfer-Encoding: ${textPart.cte}`)\n return Buffer.from(headers.join('\\r\\n') + '\\r\\n\\r\\n' + textPart.body, 'utf-8')\n}\n\n// \u2500\u2500 Inbound MIME parsing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface ParsedMail {\n messageId?: string | null\n inReplyTo?: string | null\n references?: string | string[] | null\n from?: { value?: Array<{ address?: string; name?: string }> }\n to?: { value?: Array<{ address?: string; name?: string }> }\n cc?: { value?: Array<{ address?: string; name?: string }> }\n bcc?: { value?: Array<{ address?: string; name?: string }> }\n subject?: string | null\n html?: string | false\n text?: string\n date?: string | Date | null\n attachments?: ParsedAttachment[]\n headers?: Map<string, unknown> | Record<string, unknown>\n}\n\nexport interface ParsedAttachment {\n content?: Buffer | Uint8Array\n contentType?: string\n filename?: string\n size?: number\n contentDisposition?: string\n cid?: string\n}\n\nexport function stripBrackets(value: string | undefined | null): string | undefined {\n if (!value) return undefined\n const trimmed = value.trim()\n if (!trimmed) return undefined\n if (trimmed.startsWith('<') && trimmed.endsWith('>')) return trimmed.slice(1, -1)\n return trimmed\n}\n\nexport function parseReferences(value: string | string[] | undefined | null): string[] {\n if (!value) return []\n if (Array.isArray(value)) return value.map((v) => stripBrackets(v)).filter((v): v is string => Boolean(v))\n return value\n .split(/\\s+/)\n .map((segment) => stripBrackets(segment))\n .filter((segment): segment is string => Boolean(segment))\n}\n\nexport function normalizeAttachments(attachments: ParsedAttachment[]): NormalizedAttachment[] {\n const out: NormalizedAttachment[] = []\n let totalBytes = 0\n for (const att of attachments) {\n if (!att.content) continue\n const byteLength = att.content.byteLength\n if (byteLength > EMAIL_MAX_ATTACHMENT_BYTES) {\n logger.warn('dropping oversized inbound attachment', { fileName: att.filename ?? 'attachment', bytes: byteLength, maxBytes: EMAIL_MAX_ATTACHMENT_BYTES })\n continue\n }\n if (totalBytes + byteLength > TOTAL_INBOUND_ATTACHMENTS_MAX_BYTES) {\n logger.warn('aggregate inbound attachment size exceeded; dropping remaining attachments', { maxBytes: TOTAL_INBOUND_ATTACHMENTS_MAX_BYTES })\n break\n }\n totalBytes += byteLength\n const base64 = Buffer.isBuffer(att.content)\n ? att.content.toString('base64')\n : Buffer.from(att.content).toString('base64')\n out.push({\n url: `data:${att.contentType ?? 'application/octet-stream'};base64,${base64}`,\n mimeType: att.contentType ?? 'application/octet-stream',\n fileName: att.filename ?? 'attachment',\n fileSize: att.size,\n inline: Boolean(att.contentDisposition && /inline/i.test(att.contentDisposition)) || Boolean(att.cid),\n })\n }\n return out\n}\n\nfunction stringifyHeaderValue(value: unknown): string | undefined {\n if (typeof value === 'string') return value\n if (Array.isArray(value)) return value.map((v) => String(v)).join(', ')\n if (value instanceof Date) return value.toISOString()\n if (value && typeof value === 'object') {\n try {\n return JSON.stringify(value)\n } catch {\n return undefined\n }\n }\n if (value === undefined || value === null) return undefined\n return String(value)\n}\n\n/**\n * Flatten parsed MIME headers to a `Record<string, string>`.\n *\n * mailparser returns `headers` as a `Map<string, unknown>`. `Object.entries` on\n * a Map yields an empty array (Maps have no enumerable own properties), so we\n * iterate Map entries directly, with a Record fallback for test fakes.\n */\nexport function extractHeaders(headers: ParsedMail['headers']): Record<string, string> {\n if (!headers) return {}\n const out: Record<string, string> = {}\n if (headers instanceof Map) {\n for (const [key, value] of headers.entries()) {\n const stringified = stringifyHeaderValue(value)\n if (stringified !== undefined) out[String(key)] = stringified\n }\n return out\n }\n for (const [key, value] of Object.entries(headers as Record<string, unknown>)) {\n const stringified = stringifyHeaderValue(value)\n if (stringified !== undefined) out[key] = stringified\n }\n return out\n}\n\nexport interface NormalizeMimeInboundOptions {\n /**\n * The parsed MIME message. Providers parse with their own `mailparser`\n * dependency (Gmail/IMAP) and pass the result here, so the hub stays free of a\n * MIME-parser dependency while still owning the normalization logic.\n */\n parsed: ParsedMail\n /** External identifier of the receiving channel (typically the account's email). */\n accountIdentifier: string\n /** Deterministic id used when the MIME message carries no `Message-ID` header. */\n fallbackMessageId: string\n /** Compute the conversation grouping id from the resolved message id + references. */\n resolveConversationId: (context: { messageId: string; references: string[] }) => string\n /**\n * When the provider received the message (Gmail `internalDate`, IMAP\n * `INTERNALDATE`). Preferred over the MIME `Date` header for the message\n * timestamp: the header is written by the sender's client and can be forged\n * or skewed, and since #6095 the timestamp also dates the platform message\n * and the CRM interaction, so a bad header would pin a message in the future\n * or hide it in the past.\n */\n receivedAt?: Date\n /**\n * Fallback timestamp when neither `receivedAt` nor a usable Date header is\n * available.\n */\n fallbackDate?: Date\n /** Provider-specific fields merged into `channelMetadata`. */\n channelMetadata?: (parsed: ParsedMail) => Record<string, unknown>\n /** Provider-specific fields merged into `channelPayload`. */\n channelPayload?: (parsed: ParsedMail) => Record<string, unknown>\n}\n\n/**\n * A MIME `Date` header this far ahead of the clock is treated as bogus. Clock\n * skew between real mail servers is seconds to minutes; a day of tolerance\n * keeps legitimate mail while stopping a forged header from pinning a message\n * to the top of a `sent_at`-sorted inbox for weeks.\n */\nconst MAX_MIME_DATE_FUTURE_SKEW_MS = 24 * 60 * 60 * 1000\n\nfunction isValidDate(value: unknown): value is Date {\n return value instanceof Date && !Number.isNaN(value.getTime())\n}\n\n/**\n * Pick the timestamp for an inbound message.\n *\n * Order: the provider's receipt time; then the sender's MIME `Date` header,\n * unless it is unparsable or more than a day in the future; then the caller's\n * fallback; then now. Exported for tests.\n */\nexport function resolveInboundTimestamp(input: {\n receivedAt?: Date\n mimeDate?: Date\n fallbackDate?: Date\n now?: Date\n}): Date {\n if (isValidDate(input.receivedAt)) return input.receivedAt\n const now = input.now ?? new Date()\n if (isValidDate(input.mimeDate) && input.mimeDate.getTime() <= now.getTime() + MAX_MIME_DATE_FUTURE_SKEW_MS) {\n return input.mimeDate\n }\n if (isValidDate(input.fallbackDate)) return input.fallbackDate\n return now\n}\n\n/**\n * Build the hub's canonical `NormalizedInboundMessage` from a parsed MIME\n * message. Providers supply the bits that genuinely differ (message-id\n * fallback, conversation grouping, extra metadata) and inherit the shared\n * threading / attachment / header logic.\n */\nexport function normalizeMimeInbound(options: NormalizeMimeInboundOptions): NormalizedInboundMessage {\n const { parsed } = options\n\n const messageId = stripBrackets(parsed.messageId) ?? options.fallbackMessageId\n const inReplyTo = stripBrackets(parsed.inReplyTo)\n const references = parseReferences(parsed.references)\n const conversationId = options.resolveConversationId({ messageId, references })\n\n const from = parsed.from?.value?.[0]\n const subject = parsed.subject?.trim() || undefined\n const bodyHtml = parsed.html && typeof parsed.html === 'string' ? parsed.html : undefined\n const bodyText = typeof parsed.text === 'string' ? parsed.text : undefined\n const body = bodyHtml ?? bodyText ?? ''\n const bodyFormat: 'text' | 'html' = bodyHtml ? 'html' : 'text'\n\n const attachments = normalizeAttachments(parsed.attachments ?? [])\n\n const channelMetadata: Record<string, unknown> = {\n ...(options.channelMetadata?.(parsed) ?? {}),\n messageId,\n inReplyTo: inReplyTo ?? null,\n references,\n headers: extractHeaders(parsed.headers),\n }\n\n const channelPayload: Record<string, unknown> = {\n subject,\n from: from ? { address: from.address, name: from.name } : null,\n to: parsed.to?.value ?? [],\n cc: parsed.cc?.value ?? [],\n bcc: parsed.bcc?.value ?? [],\n html: bodyHtml ?? null,\n text: bodyText ?? null,\n messageId,\n ...(options.channelPayload?.(parsed) ?? {}),\n }\n\n return {\n externalMessageId: messageId,\n externalConversationId: conversationId,\n senderIdentifier: from?.address ?? options.accountIdentifier,\n senderDisplayName: from?.name?.trim() || undefined,\n subject,\n body,\n bodyFormat,\n attachments,\n timestamp: resolveInboundTimestamp({\n receivedAt: options.receivedAt,\n mimeDate: parsed.date ? new Date(parsed.date) : undefined,\n fallbackDate: options.fallbackDate,\n }),\n replyToExternalId: inReplyTo ?? undefined,\n channelPayload,\n channelContentType: 'email/mime',\n channelMetadata,\n }\n}\n\n// \u2500\u2500 Provider sync cursor helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Encode a provider channel-state object into an opaque base64 sync cursor. */\nexport function encodeCursor(state: unknown): string {\n return Buffer.from(JSON.stringify(state)).toString('base64')\n}\n\n/** Decode a base64 sync cursor back into its object form, or `null` if malformed. */\nexport function decodeCursor(value: string | null | undefined): unknown {\n if (!value) return null\n try {\n return JSON.parse(Buffer.from(value, 'base64').toString('utf-8'))\n } catch {\n return null\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,OAAO,YAAY;AAEnB,SAAS,kCAAkC;AAC3C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,wBAAwB,EAAE,MAAM,EAAE,WAAW,aAAa,CAAC;AAQvF,MAAM,sCAAsC,6BAA6B;AAelE,SAAS,kBAAkB,OAAoC;AACpE,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEO,SAAS,cAAc,OAA0B;AACtD,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,CAAC,MAAM,OAAO,CAAC,EAAE,KAAK,CAAC,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AAC9F,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,MACJ,MAAM,SAAS,EACf,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AAAA,EAC/B;AACA,SAAO,CAAC;AACV;AAEO,SAAS,mBAAmB,OAAsC;AACvE,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO;AAClC,SAAO,MAAM,OAAO,CAAC,UAA2B,OAAO,UAAU,QAAQ;AAC3E;AAcA,SAAS,eAAe,MAAc,KAAqB;AACz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I,CAAC,UAAU,wBAAwB,oBAAoB,KAAK,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,EAAE;AAC7G,MAAI,MAAM,GAAG,OAAQ,SAAQ,KAAK,OAAO,MAAM,GAAG,IAAI,CAAC,UAAU,wBAAwB,oBAAoB,KAAK,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,EAAE;AAClI,MAAI,MAAM,IAAI,OAAQ,SAAQ,KAAK,QAAQ,MAAM,IAAI,IAAI,CAAC,UAAU,wBAAwB,oBAAoB,KAAK,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,EAAE;AACrI,MAAI,MAAM,QAAS,SAAQ,KAAK,YAAY,iBAAiB,oBAAoB,MAAM,OAAO,CAAC,CAAC,EAAE;AAClG,UAAQ,KAAK,eAAe,eAAe,MAAM,SAAS,CAAC,EAAE;AAC7D,MAAI,MAAM,UAAW,SAAQ,KAAK,gBAAgB,eAAe,MAAM,SAAS,CAAC,EAAE;AACnF,MAAI,MAAM,cAAc,MAAM,WAAW,QAAQ;AAC/C,YAAQ,KAAK,eAAe,MAAM,WAAW,IAAI,cAAc,EAAE,KAAK,GAAG,CAAC,EAAE;AAAA,EAC9E;AACA,UAAQ,KAAK,mBAAmB;AAChC,UAAQ,KAAK,UAAS,oBAAI,KAAK,GAAE,YAAY,CAAC,EAAE;AAEhD,MAAI,MAAM,QAAQ,MAAM,MAAM;AAC5B,YAAQ,KAAK,kDAAkD,QAAQ,GAAG;AAC1E,UAAMA,YAAW,eAAe,MAAM,IAAI;AAC1C,UAAM,WAAW,eAAe,MAAM,IAAI;AAC1C,UAAM,OAAO;AAAA,MACX
|
|
4
|
+
"sourcesContent": ["import crypto from 'node:crypto'\nimport type { NormalizedInboundMessage, NormalizedAttachment } from './adapter'\nimport { EMAIL_MAX_ATTACHMENT_BYTES } from './email-capabilities'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('communication_channels').child({ component: 'email-mime' })\n\n/**\n * Aggregate ceiling for all attachments on a single inbound message. Inbound\n * mail is untrusted, so without a cap a malicious/large message would be fully\n * base64-buffered in memory (~1.33x raw bytes) and persisted. Allow a small\n * multiple of the per-attachment limit for legitimate multi-file emails.\n */\nconst TOTAL_INBOUND_ATTACHMENTS_MAX_BYTES = EMAIL_MAX_ATTACHMENT_BYTES * 2\n\n/**\n * Shared email MIME helpers for the email channel providers (Gmail, IMAP).\n * Outbound assembly, inbound parsing, header/address normalization,\n * and threading-id extraction all live here so every provider shares one\n * correct implementation instead of copy-pasting (which previously let Gmail's\n * `extractHeaders` drift into a Map-handling bug that IMAP had already fixed).\n *\n * Provider-specific transport (Gmail History API, IMAP UID sync)\n * stays in each package \u2014 this module only owns the format-level plumbing.\n */\n\n// \u2500\u2500 Outbound MIME helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function stringOrUndefined(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nexport function toAddressList(value: unknown): string[] {\n if (Array.isArray(value)) return value.map((v) => String(v).trim()).filter((v) => v.length > 0)\n if (typeof value === 'string') {\n return value\n .split(/[,;]\\s*/)\n .map((v) => v.trim())\n .filter((v) => v.length > 0)\n }\n return []\n}\n\nexport function referencesFromMeta(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined\n return value.filter((entry): entry is string => typeof entry === 'string')\n}\n\n/**\n * Strip every `<tag>\u2026</tag>` block (and its contents) for a single tag name.\n * Inbound HTML is untrusted, so the matcher must resist evasion: the close tag\n * allows trailing attributes/whitespace (`</script >`, `</style foo>`), the `i`\n * flag covers mixed case, and the replacement loops until the string is stable\n * so a payload split across nested or reconstructed tags cannot survive a\n * single pass (`<scr<script>ipt>` collapsing back into `<script>`).\n *\n * The opening tag is also matched when it is truncated or never closed \u2014 a bare\n * `<script` or an unterminated `<script>\u2026` running to end-of-input is removed\n * outright \u2014 so no prefix of the element name can leak into the output.\n */\nfunction stripTagBlocks(html: string, tag: string): string {\n const blockPattern = new RegExp(\n `<${tag}\\\\b[^>]*(?:>[\\\\s\\\\S]*?(?:<\\\\/${tag}[^>]*>|$)|$)`,\n 'gi',\n )\n let previous: string\n let current = html\n do {\n previous = current\n current = current.replace(blockPattern, ' ')\n } while (current !== previous)\n return current\n}\n\n/**\n * Drop HTML comments (`<!-- \u2026 -->`), including an unterminated comment running\n * to end-of-input. Comments are stripped first because they can wrap content\n * that would otherwise survive tag removal (`<!--<script-->`), and a naive\n * filter that ignores them leaves a tag fragment behind.\n */\nfunction stripHtmlComments(html: string): string {\n return html.replace(/<!--[\\s\\S]*?(?:-->|$)/g, ' ')\n}\n\nconst BASIC_HTML_ENTITIES: Record<string, string> = {\n ' ': ' ',\n '<': '<',\n '>': '>',\n '"': '\"',\n '&': '&',\n}\n\n/**\n * Decode the handful of HTML entities we surface in plaintext in ONE\n * left-to-right pass. A single pass cannot double-unescape: characters produced\n * by a replacement (e.g. the `&` from `&`) are never re-scanned, so\n * `&lt;` decodes to the literal `<` rather than collapsing into `<`.\n */\nfunction decodeBasicEntities(input: string): string {\n return input.replace(\n /&(?:nbsp|lt|gt|quot|amp);/gi,\n (match) => BASIC_HTML_ENTITIES[match.toLowerCase()] ?? match,\n )\n}\n\n/**\n * Remove every remaining `<\u2026>` tag, looping until the string is stable so a tag\n * reconstructed by a single pass (`<<div>div>`) cannot survive \u2014 the same\n * loop-until-stable shape `stripTagBlocks` uses. A raw `<` that is not part of a\n * tag (`a < b`) has no closing `>`, never matches, and is intentionally kept.\n */\nfunction stripRemainingTags(html: string): string {\n let previous: string\n let current = html\n do {\n previous = current\n current = current.replace(/<[^>]*>/g, '')\n } while (current !== previous)\n return current\n}\n\n/**\n * Convert untrusted inbound HTML to plaintext. Entities are decoded FIRST so any\n * entity-encoded markup (e.g. `<script>`) is normalized into real tag\n * syntax before the strippers run \u2014 otherwise decoding last would reintroduce a\n * `<script` fragment into the final output after sanitization had finished\n * (CodeQL `js/incomplete-multi-character-sanitization`). After decoding, all\n * tag removal (script/style blocks, then remaining tags) happens via\n * loop-until-stable passes, so no `<tag` prefix can leak into the plaintext.\n */\nexport function htmlToText(html: string): string {\n const decoded = decodeBasicEntities(html)\n const stripped = stripTagBlocks(stripTagBlocks(stripHtmlComments(decoded), 'style'), 'script')\n .replace(/<br\\s*\\/?>(?=\\s*)/gi, '\\n')\n .replace(/<\\/p\\s*>/gi, '\\n\\n')\n return stripRemainingTags(stripped)\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim()\n}\n\nexport function escapeQuotes(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')\n}\n\n/**\n * Collapse CR/LF/TAB in an email header value to a single space to prevent\n * RFC 5322 header injection \u2014 e.g. a Subject smuggling an extra\n * `Bcc:`/`Content-Type:` header or splitting the message into a body.\n * Collapsing (rather than folding) is safe for the short structured headers\n * we emit (Subject, addresses, Message-ID, References).\n */\nexport function sanitizeHeaderValue(value: string): string {\n return value.replace(/[\\r\\n\\t]+/g, ' ').trim()\n}\n\nexport function ensureBrackets(value: string): string {\n const trimmed = sanitizeHeaderValue(value)\n if (trimmed.startsWith('<') && trimmed.endsWith('>')) return trimmed\n return `<${trimmed}>`\n}\n\nfunction isPureAscii(value: string): boolean {\n // eslint-disable-next-line no-control-regex\n return /^[\\x00-\\x7F]*$/.test(value)\n}\n\n/**\n * Encode a single header value as an RFC 2047 \"B\" (base64) encoded-word when it\n * contains non-ASCII characters, so 8-bit text like \"Caf\u00E9\" survives strict MTAs\n * that treat header bytes as 7-bit ASCII. Pure-ASCII values are returned\n * unchanged. Apply only AFTER `sanitizeHeaderValue` so the CR/LF injection guard\n * still runs against the raw value.\n */\nexport function encodeHeaderWord(value: string): string {\n if (isPureAscii(value)) return value\n return `=?utf-8?B?${Buffer.from(value, 'utf-8').toString('base64')}?=`\n}\n\n/**\n * Encode the display-name part of a single address header value, leaving the\n * `<addr@domain>` untouched (per RFC 2047, encoded-words are not permitted\n * inside the addr-spec). Inputs without a bracketed address are treated as a\n * bare display name / address and encoded only when non-ASCII.\n */\nexport function encodeAddressHeaderWord(value: string): string {\n if (isPureAscii(value)) return value\n const match = value.match(/^(.*?)(\\s*<[^>]*>)\\s*$/)\n if (match) {\n const [, displayPart, addrPart] = match\n const displayName = displayPart.replace(/^\"|\"$/g, '').trim()\n if (!displayName) return value\n return `${encodeHeaderWord(displayName)}${addrPart}`\n }\n return encodeHeaderWord(value)\n}\n\n/**\n * Generate an RFC 5322 Message-ID rooted in the sender's domain. Used as a\n * downstream idempotency key, so entropy comes from `crypto.randomUUID()`\n * rather than `Math.random()`.\n */\nexport function generateMessageId(fromAddress: string, fallbackDomain = 'localhost'): string {\n const domain = fromAddress.split('@')[1] ?? fallbackDomain\n return `<${crypto.randomUUID()}@${domain}>`\n}\n\nexport interface AssembleRfc2822Input {\n from: string\n to: string[]\n cc: string[]\n bcc: string[]\n subject: string | undefined\n text: string | undefined\n html: string | undefined\n inReplyTo: string | undefined\n references: string[] | undefined\n messageId: string\n}\n\n/**\n * Render one MIME body part's CTE header + body content. Non-ASCII bodies are\n * base64-encoded (CRLF-wrapped at 76 cols) and labelled\n * `Content-Transfer-Encoding: base64` so 8-bit text survives strict MTAs;\n * pure-ASCII bodies stay `7bit` and verbatim.\n */\nfunction encodeBodyPart(content: string): { cte: string; body: string } {\n if (isPureAscii(content)) return { cte: '7bit', body: content }\n const base64 = Buffer.from(content, 'utf-8').toString('base64')\n const wrapped = base64.match(/.{1,76}/g)?.join('\\r\\n') ?? base64\n return { cte: 'base64', body: wrapped }\n}\n\n/**\n * Assemble a raw RFC2822 message (used by transports that send the encoded\n * message directly, e.g. Gmail `users.messages.send`). Emits a\n * `multipart/alternative` body when both html and text are present, otherwise a\n * single-part text or html body.\n */\nexport function assembleRfc2822(input: AssembleRfc2822Input): Buffer {\n const boundary = `omc_${crypto.randomUUID()}`\n const headers: string[] = []\n headers.push(`From: ${encodeAddressHeaderWord(sanitizeHeaderValue(input.from))}`)\n headers.push(`To: ${input.to.map((value) => encodeAddressHeaderWord(sanitizeHeaderValue(value))).join(', ')}`)\n if (input.cc.length) headers.push(`Cc: ${input.cc.map((value) => encodeAddressHeaderWord(sanitizeHeaderValue(value))).join(', ')}`)\n if (input.bcc.length) headers.push(`Bcc: ${input.bcc.map((value) => encodeAddressHeaderWord(sanitizeHeaderValue(value))).join(', ')}`)\n if (input.subject) headers.push(`Subject: ${encodeHeaderWord(sanitizeHeaderValue(input.subject))}`)\n headers.push(`Message-ID: ${ensureBrackets(input.messageId)}`)\n if (input.inReplyTo) headers.push(`In-Reply-To: ${ensureBrackets(input.inReplyTo)}`)\n if (input.references && input.references.length) {\n headers.push(`References: ${input.references.map(ensureBrackets).join(' ')}`)\n }\n headers.push('MIME-Version: 1.0')\n headers.push(`Date: ${new Date().toUTCString()}`)\n\n if (input.html && input.text) {\n headers.push(`Content-Type: multipart/alternative; boundary=\"${boundary}\"`)\n const textPart = encodeBodyPart(input.text)\n const htmlPart = encodeBodyPart(input.html)\n const body = [\n `--${boundary}`,\n 'Content-Type: text/plain; charset=utf-8',\n `Content-Transfer-Encoding: ${textPart.cte}`,\n '',\n textPart.body,\n `--${boundary}`,\n 'Content-Type: text/html; charset=utf-8',\n `Content-Transfer-Encoding: ${htmlPart.cte}`,\n '',\n htmlPart.body,\n `--${boundary}--`,\n '',\n ].join('\\r\\n')\n return Buffer.from(headers.join('\\r\\n') + '\\r\\n\\r\\n' + body, 'utf-8')\n }\n\n if (input.html) {\n const htmlPart = encodeBodyPart(input.html)\n headers.push('Content-Type: text/html; charset=utf-8')\n headers.push(`Content-Transfer-Encoding: ${htmlPart.cte}`)\n return Buffer.from(headers.join('\\r\\n') + '\\r\\n\\r\\n' + htmlPart.body, 'utf-8')\n }\n\n const textPart = encodeBodyPart(input.text ?? '')\n headers.push('Content-Type: text/plain; charset=utf-8')\n headers.push(`Content-Transfer-Encoding: ${textPart.cte}`)\n return Buffer.from(headers.join('\\r\\n') + '\\r\\n\\r\\n' + textPart.body, 'utf-8')\n}\n\n// \u2500\u2500 Inbound MIME parsing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface ParsedMail {\n messageId?: string | null\n inReplyTo?: string | null\n references?: string | string[] | null\n from?: { value?: Array<{ address?: string; name?: string }> }\n to?: { value?: Array<{ address?: string; name?: string }> }\n cc?: { value?: Array<{ address?: string; name?: string }> }\n bcc?: { value?: Array<{ address?: string; name?: string }> }\n subject?: string | null\n html?: string | false\n text?: string\n date?: string | Date | null\n attachments?: ParsedAttachment[]\n headers?: Map<string, unknown> | Record<string, unknown>\n}\n\nexport interface ParsedAttachment {\n content?: Buffer | Uint8Array\n contentType?: string\n filename?: string\n size?: number\n contentDisposition?: string\n cid?: string\n}\n\nexport function stripBrackets(value: string | undefined | null): string | undefined {\n if (!value) return undefined\n const trimmed = value.trim()\n if (!trimmed) return undefined\n if (trimmed.startsWith('<') && trimmed.endsWith('>')) return trimmed.slice(1, -1)\n return trimmed\n}\n\nexport function parseReferences(value: string | string[] | undefined | null): string[] {\n if (!value) return []\n if (Array.isArray(value)) return value.map((v) => stripBrackets(v)).filter((v): v is string => Boolean(v))\n return value\n .split(/\\s+/)\n .map((segment) => stripBrackets(segment))\n .filter((segment): segment is string => Boolean(segment))\n}\n\nexport function normalizeAttachments(attachments: ParsedAttachment[]): NormalizedAttachment[] {\n const out: NormalizedAttachment[] = []\n let totalBytes = 0\n for (const att of attachments) {\n if (!att.content) continue\n const byteLength = att.content.byteLength\n if (byteLength > EMAIL_MAX_ATTACHMENT_BYTES) {\n logger.warn('dropping oversized inbound attachment', { fileName: att.filename ?? 'attachment', bytes: byteLength, maxBytes: EMAIL_MAX_ATTACHMENT_BYTES })\n continue\n }\n if (totalBytes + byteLength > TOTAL_INBOUND_ATTACHMENTS_MAX_BYTES) {\n logger.warn('aggregate inbound attachment size exceeded; dropping remaining attachments', { maxBytes: TOTAL_INBOUND_ATTACHMENTS_MAX_BYTES })\n break\n }\n totalBytes += byteLength\n const base64 = Buffer.isBuffer(att.content)\n ? att.content.toString('base64')\n : Buffer.from(att.content).toString('base64')\n out.push({\n url: `data:${att.contentType ?? 'application/octet-stream'};base64,${base64}`,\n mimeType: att.contentType ?? 'application/octet-stream',\n fileName: att.filename ?? 'attachment',\n fileSize: att.size,\n inline: Boolean(att.contentDisposition && /inline/i.test(att.contentDisposition)) || Boolean(att.cid),\n })\n }\n return out\n}\n\nfunction stringifyHeaderValue(value: unknown): string | undefined {\n if (typeof value === 'string') return value\n if (Array.isArray(value)) return value.map((v) => String(v)).join(', ')\n if (value instanceof Date) return value.toISOString()\n if (value && typeof value === 'object') {\n try {\n return JSON.stringify(value)\n } catch {\n return undefined\n }\n }\n if (value === undefined || value === null) return undefined\n return String(value)\n}\n\n/**\n * Flatten parsed MIME headers to a `Record<string, string>`.\n *\n * mailparser returns `headers` as a `Map<string, unknown>`. `Object.entries` on\n * a Map yields an empty array (Maps have no enumerable own properties), so we\n * iterate Map entries directly, with a Record fallback for test fakes.\n */\nexport function extractHeaders(headers: ParsedMail['headers']): Record<string, string> {\n if (!headers) return {}\n const out: Record<string, string> = {}\n if (headers instanceof Map) {\n for (const [key, value] of headers.entries()) {\n const stringified = stringifyHeaderValue(value)\n if (stringified !== undefined) out[String(key)] = stringified\n }\n return out\n }\n for (const [key, value] of Object.entries(headers as Record<string, unknown>)) {\n const stringified = stringifyHeaderValue(value)\n if (stringified !== undefined) out[key] = stringified\n }\n return out\n}\n\nexport interface NormalizeMimeInboundOptions {\n /**\n * The parsed MIME message. Providers parse with their own `mailparser`\n * dependency (Gmail/IMAP) and pass the result here, so the hub stays free of a\n * MIME-parser dependency while still owning the normalization logic.\n */\n parsed: ParsedMail\n /** External identifier of the receiving channel (typically the account's email). */\n accountIdentifier: string\n /** Deterministic id used when the MIME message carries no `Message-ID` header. */\n fallbackMessageId: string\n /** Compute the conversation grouping id from the resolved message id + references. */\n resolveConversationId: (context: { messageId: string; references: string[] }) => string\n /**\n * When the provider received the message (Gmail `internalDate`, IMAP\n * `INTERNALDATE`). Preferred over the MIME `Date` header for the message\n * timestamp: the header is written by the sender's client and can be forged\n * or skewed, and since #6095 the timestamp also dates the platform message\n * and the CRM interaction, so a bad header would pin a message in the future\n * or hide it in the past.\n */\n receivedAt?: Date\n /**\n * Fallback timestamp when neither `receivedAt` nor a usable Date header is\n * available.\n */\n fallbackDate?: Date\n /** Provider-specific fields merged into `channelMetadata`. */\n channelMetadata?: (parsed: ParsedMail) => Record<string, unknown>\n /** Provider-specific fields merged into `channelPayload`. */\n channelPayload?: (parsed: ParsedMail) => Record<string, unknown>\n}\n\n/**\n * A MIME `Date` header this far ahead of the clock is treated as bogus. Clock\n * skew between real mail servers is seconds to minutes; a day of tolerance\n * keeps legitimate mail while stopping a forged header from pinning a message\n * to the top of a `sent_at`-sorted inbox for weeks.\n */\nconst MAX_MIME_DATE_FUTURE_SKEW_MS = 24 * 60 * 60 * 1000\n\nfunction isValidDate(value: unknown): value is Date {\n return value instanceof Date && !Number.isNaN(value.getTime())\n}\n\n/**\n * Pick the timestamp for an inbound message.\n *\n * Order: the provider's receipt time; then the sender's MIME `Date` header,\n * unless it is unparsable or more than a day in the future; then the caller's\n * fallback; then now. Exported for tests.\n */\nexport function resolveInboundTimestamp(input: {\n receivedAt?: Date\n mimeDate?: Date\n fallbackDate?: Date\n now?: Date\n}): Date {\n if (isValidDate(input.receivedAt)) return input.receivedAt\n const now = input.now ?? new Date()\n if (isValidDate(input.mimeDate) && input.mimeDate.getTime() <= now.getTime() + MAX_MIME_DATE_FUTURE_SKEW_MS) {\n return input.mimeDate\n }\n if (isValidDate(input.fallbackDate)) return input.fallbackDate\n return now\n}\n\n/**\n * Build the hub's canonical `NormalizedInboundMessage` from a parsed MIME\n * message. Providers supply the bits that genuinely differ (message-id\n * fallback, conversation grouping, extra metadata) and inherit the shared\n * threading / attachment / header logic.\n */\nexport function normalizeMimeInbound(options: NormalizeMimeInboundOptions): NormalizedInboundMessage {\n const { parsed } = options\n\n const messageId = stripBrackets(parsed.messageId) ?? options.fallbackMessageId\n const inReplyTo = stripBrackets(parsed.inReplyTo)\n const references = parseReferences(parsed.references)\n const conversationId = options.resolveConversationId({ messageId, references })\n\n const from = parsed.from?.value?.[0]\n const subject = parsed.subject?.trim() || undefined\n const bodyHtml = parsed.html && typeof parsed.html === 'string' ? parsed.html : undefined\n const bodyText = typeof parsed.text === 'string' ? parsed.text : undefined\n const body = bodyHtml ?? bodyText ?? ''\n const bodyFormat: 'text' | 'html' = bodyHtml ? 'html' : 'text'\n\n const attachments = normalizeAttachments(parsed.attachments ?? [])\n\n const channelMetadata: Record<string, unknown> = {\n ...(options.channelMetadata?.(parsed) ?? {}),\n messageId,\n inReplyTo: inReplyTo ?? null,\n references,\n headers: extractHeaders(parsed.headers),\n }\n\n const channelPayload: Record<string, unknown> = {\n subject,\n from: from ? { address: from.address, name: from.name } : null,\n to: parsed.to?.value ?? [],\n cc: parsed.cc?.value ?? [],\n bcc: parsed.bcc?.value ?? [],\n html: bodyHtml ?? null,\n text: bodyText ?? null,\n messageId,\n ...(options.channelPayload?.(parsed) ?? {}),\n }\n\n return {\n externalMessageId: messageId,\n externalConversationId: conversationId,\n senderIdentifier: from?.address ?? options.accountIdentifier,\n senderDisplayName: from?.name?.trim() || undefined,\n subject,\n body,\n bodyFormat,\n attachments,\n timestamp: resolveInboundTimestamp({\n receivedAt: options.receivedAt,\n mimeDate: parsed.date ? new Date(parsed.date) : undefined,\n fallbackDate: options.fallbackDate,\n }),\n replyToExternalId: inReplyTo ?? undefined,\n channelPayload,\n channelContentType: 'email/mime',\n channelMetadata,\n }\n}\n\n// \u2500\u2500 Provider sync cursor helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Encode a provider channel-state object into an opaque base64 sync cursor. */\nexport function encodeCursor(state: unknown): string {\n return Buffer.from(JSON.stringify(state)).toString('base64')\n}\n\n/** Decode a base64 sync cursor back into its object form, or `null` if malformed. */\nexport function decodeCursor(value: string | null | undefined): unknown {\n if (!value) return null\n try {\n return JSON.parse(Buffer.from(value, 'base64').toString('utf-8'))\n } catch {\n return null\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAO,YAAY;AAEnB,SAAS,kCAAkC;AAC3C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,wBAAwB,EAAE,MAAM,EAAE,WAAW,aAAa,CAAC;AAQvF,MAAM,sCAAsC,6BAA6B;AAelE,SAAS,kBAAkB,OAAoC;AACpE,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEO,SAAS,cAAc,OAA0B;AACtD,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,CAAC,MAAM,OAAO,CAAC,EAAE,KAAK,CAAC,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AAC9F,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,MACJ,MAAM,SAAS,EACf,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;AAAA,EAC/B;AACA,SAAO,CAAC;AACV;AAEO,SAAS,mBAAmB,OAAsC;AACvE,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO;AAClC,SAAO,MAAM,OAA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AA2C;AACtE,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI;AACF,WAAO,KAAK,MAAM,OAAO,KAAK,OAAO,QAAQ,EAAE,SAAS,OAAO,CAAC;AAAA,EAClE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;",
|
|
6
6
|
"names": ["textPart"]
|
|
7
7
|
}
|
|
@@ -114,6 +114,9 @@ function resolveCachePurgeRequest(args) {
|
|
|
114
114
|
"Choose a purge target: `--all`, `--segment <id>`, `--tag <tag1,tag2>`, `--key <key1,key2>`, `--id <token1,token2>`, or `--pattern <glob>`."
|
|
115
115
|
);
|
|
116
116
|
}
|
|
117
|
+
function isCacheHelpFlag(arg) {
|
|
118
|
+
return arg === "help" || arg === "--help" || arg === "-h";
|
|
119
|
+
}
|
|
117
120
|
function printCacheHelp() {
|
|
118
121
|
console.log("\u{1F9F9} Cache CLI");
|
|
119
122
|
console.log("");
|
|
@@ -299,10 +302,12 @@ const help = {
|
|
|
299
302
|
};
|
|
300
303
|
const cacheCommand = {
|
|
301
304
|
command: "cache",
|
|
305
|
+
// Prints subcommand-aware help itself, so the dispatcher must forward --help/-h here.
|
|
306
|
+
handlesHelp: true,
|
|
302
307
|
async run(rest) {
|
|
303
308
|
const [subcommand, ...subRest] = rest;
|
|
304
309
|
const args = parseArgs(subRest);
|
|
305
|
-
if (!subcommand ||
|
|
310
|
+
if (!subcommand || rest.some(isCacheHelpFlag)) {
|
|
306
311
|
printCacheHelp();
|
|
307
312
|
return;
|
|
308
313
|
}
|
|
@@ -324,6 +329,7 @@ const cacheCommand = {
|
|
|
324
329
|
var cli_default = [restoreDefaults, cacheCommand, help];
|
|
325
330
|
export {
|
|
326
331
|
STRUCTURAL_CACHE_REQUESTS,
|
|
327
|
-
cli_default as default
|
|
332
|
+
cli_default as default,
|
|
333
|
+
isCacheHelpFlag
|
|
328
334
|
};
|
|
329
335
|
//# sourceMappingURL=cli.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/modules/configs/cli.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ModuleCli } from '@open-mercato/shared/modules/registry'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { runWithCacheTenant, type CacheStrategy } from '@open-mercato/cache'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { ModuleConfigService } from './lib/module-config-service'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { STORED_DEFAULT_NOTIFICATION_DELIVERY_CONFIG, NOTIFICATIONS_DELIVERY_CONFIG_KEY } from '../notifications/lib/deliveryConfig'\nimport { Tenant } from '../directory/data/entities'\nimport {\n collectCacheStats,\n executeCachePurge,\n previewCachePurge,\n type CachePurgeRequest,\n} from './lib/cache-cli'\nimport { touchGeneratedBarrels } from './lib/touchGeneratedBarrels'\n\ntype ParsedArgs = Record<string, string | boolean>\n\nexport const STRUCTURAL_CACHE_REQUESTS: CachePurgeRequest[] = [\n { kind: 'pattern', pattern: 'nav:*' },\n { kind: 'segment', segment: 'admin-nav' },\n { kind: 'segment', segment: 'portal-nav' },\n]\n\ntype CacheScope = {\n label: string\n tenantId: string | null\n}\n\nfunction parseArgs(rest: string[]): ParsedArgs {\n const args: ParsedArgs = {}\n for (let i = 0; i < rest.length; i += 1) {\n const part = rest[i]\n if (!part?.startsWith('--')) continue\n const [rawKey, rawValue] = part.slice(2).split('=')\n if (!rawKey) continue\n if (rawValue !== undefined) {\n args[rawKey] = rawValue\n } else if (i + 1 < rest.length && !rest[i + 1]!.startsWith('--')) {\n args[rawKey] = rest[i + 1]!\n i += 1\n } else {\n args[rawKey] = true\n }\n }\n return args\n}\n\nfunction stringOption(args: ParsedArgs, ...keys: string[]): string | undefined {\n for (const key of keys) {\n const raw = args[key]\n if (typeof raw !== 'string') continue\n const trimmed = raw.trim()\n if (trimmed.length > 0) return trimmed\n }\n return undefined\n}\n\nfunction flagEnabled(args: ParsedArgs, ...keys: string[]): boolean {\n for (const key of keys) {\n const raw = args[key]\n if (raw === undefined) continue\n if (raw === true) return true\n if (typeof raw === 'string') {\n const parsed = parseBooleanToken(raw)\n return parsed === null ? true : parsed\n }\n }\n return false\n}\n\nfunction splitListOption(raw: string | undefined): string[] {\n if (!raw) return []\n const seen = new Set<string>()\n const values: string[] = []\n for (const item of raw.split(',')) {\n const trimmed = item.trim()\n if (!trimmed || seen.has(trimmed)) continue\n seen.add(trimmed)\n values.push(trimmed)\n }\n return values\n}\n\nasync function resolveCacheScopes(\n em: EntityManager,\n args: ParsedArgs,\n): Promise<CacheScope[]> {\n const explicitTenantId = stringOption(args, 'tenant', 'tenantId')\n const globalOnly = flagEnabled(args, 'global')\n const allTenants = flagEnabled(args, 'all-tenants', 'allTenants')\n\n if (explicitTenantId && globalOnly) {\n throw new Error('Cannot combine `--tenant` with `--global`.')\n }\n if (explicitTenantId && allTenants) {\n throw new Error('Cannot combine `--tenant` with `--all-tenants`.')\n }\n if (globalOnly && allTenants) {\n throw new Error('Cannot combine `--global` with `--all-tenants`.')\n }\n\n if (explicitTenantId) {\n return [{ label: `tenant:${explicitTenantId}`, tenantId: explicitTenantId }]\n }\n\n if (globalOnly) {\n return [{ label: 'global', tenantId: null }]\n }\n\n if (!allTenants) {\n return [{ label: 'global', tenantId: null }]\n }\n\n const tenants = await em.find(Tenant, { deletedAt: null }, { orderBy: { name: 'asc' } })\n const scopes: CacheScope[] = [{ label: 'global', tenantId: null }]\n const seen = new Set<string>()\n for (const tenant of tenants) {\n const tenantId = typeof tenant.id === 'string' ? tenant.id : ''\n if (!tenantId || seen.has(tenantId)) continue\n seen.add(tenantId)\n scopes.push({ label: `tenant:${tenantId}`, tenantId })\n }\n return scopes\n}\n\nfunction resolveCachePurgeRequest(args: ParsedArgs): CachePurgeRequest {\n if (flagEnabled(args, 'all')) return { kind: 'all' }\n\n const segment = stringOption(args, 'segment')\n if (segment) return { kind: 'segment', segment }\n\n const tags = splitListOption(stringOption(args, 'tag', 'tags'))\n if (tags.length > 0) return { kind: 'tags', tags }\n\n const keys = splitListOption(stringOption(args, 'key', 'keys'))\n if (keys.length > 0) return { kind: 'keys', keys }\n\n const ids = splitListOption(stringOption(args, 'id', 'ids'))\n if (ids.length > 0) return { kind: 'ids', ids }\n\n const pattern = stringOption(args, 'pattern')\n if (pattern) return { kind: 'pattern', pattern }\n\n throw new Error(\n 'Choose a purge target: `--all`, `--segment <id>`, `--tag <tag1,tag2>`, `--key <key1,key2>`, `--id <token1,token2>`, or `--pattern <glob>`.',\n )\n}\n\nfunction printCacheHelp() {\n console.log('\uD83E\uDDF9 Cache CLI')\n console.log('')\n console.log('\uD83D\uDE80 Usage:')\n console.log(' yarn mercato configs cache stats [--tenant <id> | --global | --all-tenants] [--json]')\n console.log(' yarn mercato configs cache purge --all [--tenant <id> | --global | --all-tenants] [--dry-run] [--json]')\n console.log(' yarn mercato configs cache purge --segment <segment> [--tenant <id> | --global | --all-tenants] [--dry-run] [--json]')\n console.log(' yarn mercato configs cache purge --tag <tag1,tag2> [--tenant <id> | --global | --all-tenants] [--dry-run] [--json]')\n console.log(' yarn mercato configs cache purge --key <key1,key2> [--tenant <id> | --global | --all-tenants] [--dry-run] [--json]')\n console.log(' yarn mercato configs cache purge --id <token1,token2> [--tenant <id> | --global | --all-tenants] [--dry-run] [--json]')\n console.log(' yarn mercato configs cache purge --pattern <glob> [--tenant <id> | --global | --all-tenants] [--dry-run] [--json]')\n console.log(' yarn mercato configs cache structural [--tenant <id> | --global | --all-tenants] [--touch-generated] [--dry-run] [--json]')\n console.log('')\n console.log('\u2139\uFE0F Notes:')\n console.log(' `stats` mirrors the cache admin page segment overview for CRUD/widget caches.')\n console.log(' `purge --id` removes every key whose name contains the provided token (for example a user id or entity id).')\n console.log(' `structural` targets navigation/sidebar caches. Add `--touch-generated` only for explicit stale-compiler recovery.')\n console.log(' When no scope flag is supplied, this command uses the global cache scope only.')\n}\n\nasync function disposeContainer(container: unknown) {\n const disposable = container as { dispose?: () => Promise<void> }\n if (typeof disposable.dispose === 'function') {\n await disposable.dispose()\n }\n}\n\nasync function runCacheStats(args: ParsedArgs) {\n const json = flagEnabled(args, 'json')\n const container = await createRequestContainer()\n try {\n const em = container.resolve('em') as EntityManager\n const cache = container.resolve('cache') as CacheStrategy\n const scopes = await resolveCacheScopes(em, args)\n const results = []\n for (const scope of scopes) {\n const stats = await runWithCacheTenant(scope.tenantId, async () => collectCacheStats(cache))\n results.push({ scope: scope.label, ...stats })\n }\n\n if (json) {\n console.log(JSON.stringify(results, null, 2))\n return\n }\n\n for (const result of results) {\n console.log(`\uD83D\uDD0E [cache] scope=${result.scope} totalKeys=${result.totalKeys} generatedAt=${result.generatedAt}`)\n if (result.segments.length === 0) {\n console.log(' \u2205 segments: none')\n continue\n }\n for (const segment of result.segments) {\n console.log(` \u2022 ${segment.segment} (${segment.keyCount})${segment.path ? ` ${segment.path}` : ''}`)\n }\n }\n } finally {\n await disposeContainer(container)\n }\n}\n\nasync function runCachePurgeRequest(\n args: ParsedArgs,\n request: CachePurgeRequest,\n emitOutput = true,\n) {\n const json = flagEnabled(args, 'json')\n const quiet = flagEnabled(args, 'quiet')\n const dryRun = flagEnabled(args, 'dry-run', 'dryRun')\n const container = await createRequestContainer()\n try {\n const em = container.resolve('em') as EntityManager\n const cache = container.resolve('cache') as CacheStrategy\n const scopes = await resolveCacheScopes(em, args)\n const results = []\n\n for (const scope of scopes) {\n const result = await runWithCacheTenant(scope.tenantId, async () =>\n dryRun ? previewCachePurge(cache, request) : executeCachePurge(cache, request)\n )\n results.push({\n scope: scope.label,\n dryRun,\n request,\n deleted: result.deleted,\n keyCount: result.keys.length,\n keys: result.keys,\n note: result.note,\n })\n }\n\n if (json && emitOutput) {\n console.log(JSON.stringify(results, null, 2))\n return results\n }\n\n if (quiet || !emitOutput) {\n return results\n }\n\n for (const result of results) {\n console.log(`${result.dryRun ? '\uD83E\uDDEA' : '\uD83E\uDDF9'} [cache] scope=${result.scope} deleted=${result.deleted}${result.dryRun ? ' (dry-run)' : ''}`)\n if (result.note) console.log(` \u2139\uFE0F note: ${result.note}`)\n if (result.keys.length > 0) {\n for (const key of result.keys) {\n console.log(` \u2022 ${key}`)\n }\n }\n }\n return results\n } finally {\n await disposeContainer(container)\n }\n}\n\nasync function runCachePurge(args: ParsedArgs) {\n await runCachePurgeRequest(args, resolveCachePurgeRequest(args))\n}\n\nasync function runStructuralCachePurge(args: ParsedArgs) {\n const json = flagEnabled(args, 'json')\n const structuralResults: Array<{\n request: CachePurgeRequest\n results: Awaited<ReturnType<typeof runCachePurgeRequest>>\n }> = []\n for (const request of STRUCTURAL_CACHE_REQUESTS) {\n const results = await runCachePurgeRequest(args, request, !json)\n structuralResults.push({ request, results })\n }\n if (json) {\n console.log(JSON.stringify(structuralResults, null, 2))\n }\n if (flagEnabled(args, 'touch-generated', 'touchGenerated')) {\n const quiet = flagEnabled(args, 'quiet')\n try {\n touchGeneratedBarrels({ quiet: quiet || json })\n } catch (err) {\n if (!quiet && !json) {\n console.warn(\n `[structural] failed to touch generated barrels: ${(err as Error).message ?? err}`,\n )\n }\n }\n }\n}\n\nfunction envDisablesAutoIndexing(): boolean {\n const raw =\n process.env.OM_DISABLE_VECTOR_SEARCH_AUTOINDEXING ??\n process.env.DISABLE_VECTOR_SEARCH_AUTOINDEXING\n if (!raw) return false\n return parseBooleanToken(raw) === true\n}\n\nconst restoreDefaults: ModuleCli = {\n command: 'restore-defaults',\n async run() {\n const container = await createRequestContainer()\n try {\n let service: ModuleConfigService\n try {\n service = (container.resolve('moduleConfigService') as ModuleConfigService)\n } catch {\n console.error('[configs] moduleConfigService is not registered in the container.')\n return\n }\n\n const disabledByEnv = envDisablesAutoIndexing()\n const defaultEnabled = !disabledByEnv\n await service.restoreDefaults(\n [\n {\n moduleId: 'vector',\n name: 'auto_index_enabled',\n value: defaultEnabled,\n },\n {\n moduleId: 'notifications',\n name: NOTIFICATIONS_DELIVERY_CONFIG_KEY,\n value: STORED_DEFAULT_NOTIFICATION_DELIVERY_CONFIG,\n },\n ],\n { force: true },\n )\n console.log(\n `[configs] Vector auto-indexing default set to ${defaultEnabled ? 'enabled' : 'disabled'}${\n disabledByEnv\n ? ' (forced by OM_DISABLE_VECTOR_SEARCH_AUTOINDEXING or legacy DISABLE_VECTOR_SEARCH_AUTOINDEXING)'\n : ''\n }.`,\n )\n } finally {\n const disposable = container as unknown as { dispose?: () => Promise<void> }\n if (typeof disposable.dispose === 'function') {\n await disposable.dispose()\n }\n }\n },\n}\n\nconst help: ModuleCli = {\n command: 'help',\n async run() {\n console.log('\u2699\uFE0F Configs CLI')\n console.log('')\n console.log('\uD83D\uDE80 Usage: yarn mercato configs restore-defaults')\n console.log(' Ensures global module configuration defaults exist.')\n console.log('')\n printCacheHelp()\n },\n}\n\nconst cacheCommand: ModuleCli = {\n command: 'cache',\n async run(rest) {\n const [subcommand, ...subRest] = rest\n const args = parseArgs(subRest)\n\n if (!subcommand || subcommand === 'help' || subcommand === '--help' || subcommand === '-h') {\n printCacheHelp()\n return\n }\n\n if (subcommand === 'stats') {\n await runCacheStats(args)\n return\n }\n\n if (subcommand === 'purge') {\n await runCachePurge(args)\n return\n }\n\n if (subcommand === 'structural') {\n await runStructuralCachePurge(args)\n return\n }\n\n throw new Error(`Unknown cache subcommand \"${subcommand}\".`)\n },\n}\n\nexport default [restoreDefaults, cacheCommand, help]\n"],
|
|
5
|
-
"mappings": "AAEA,SAAS,0BAA8C;AACvD,SAAS,8BAA8B;AAEvC,SAAS,yBAAyB;AAClC,SAAS,6CAA6C,yCAAyC;AAC/F,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,6BAA6B;AAI/B,MAAM,4BAAiD;AAAA,EAC5D,EAAE,MAAM,WAAW,SAAS,QAAQ;AAAA,EACpC,EAAE,MAAM,WAAW,SAAS,YAAY;AAAA,EACxC,EAAE,MAAM,WAAW,SAAS,aAAa;AAC3C;AAOA,SAAS,UAAU,MAA4B;AAC7C,QAA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AI,OAAO,WAAW,YAAY,YAAY;AAC5C,cAAM,WAAW,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AACF;AAEA,MAAM,OAAkB;AAAA,EACtB,SAAS;AAAA,EACT,MAAM,MAAM;AACV,YAAQ,IAAI,0BAAgB;AAC5B,YAAQ,IAAI,EAAE;AACd,YAAQ,IAAI,wDAAiD;AAC7D,YAAQ,IAAI,uDAAuD;AACnE,YAAQ,IAAI,EAAE;AACd,mBAAe;AAAA,EACjB;AACF;AAEA,MAAM,eAA0B;AAAA,EAC9B,SAAS;AAAA,
|
|
4
|
+
"sourcesContent": ["import type { ModuleCli } from '@open-mercato/shared/modules/registry'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { runWithCacheTenant, type CacheStrategy } from '@open-mercato/cache'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { ModuleConfigService } from './lib/module-config-service'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { STORED_DEFAULT_NOTIFICATION_DELIVERY_CONFIG, NOTIFICATIONS_DELIVERY_CONFIG_KEY } from '../notifications/lib/deliveryConfig'\nimport { Tenant } from '../directory/data/entities'\nimport {\n collectCacheStats,\n executeCachePurge,\n previewCachePurge,\n type CachePurgeRequest,\n} from './lib/cache-cli'\nimport { touchGeneratedBarrels } from './lib/touchGeneratedBarrels'\n\ntype ParsedArgs = Record<string, string | boolean>\n\nexport const STRUCTURAL_CACHE_REQUESTS: CachePurgeRequest[] = [\n { kind: 'pattern', pattern: 'nav:*' },\n { kind: 'segment', segment: 'admin-nav' },\n { kind: 'segment', segment: 'portal-nav' },\n]\n\ntype CacheScope = {\n label: string\n tenantId: string | null\n}\n\nfunction parseArgs(rest: string[]): ParsedArgs {\n const args: ParsedArgs = {}\n for (let i = 0; i < rest.length; i += 1) {\n const part = rest[i]\n if (!part?.startsWith('--')) continue\n const [rawKey, rawValue] = part.slice(2).split('=')\n if (!rawKey) continue\n if (rawValue !== undefined) {\n args[rawKey] = rawValue\n } else if (i + 1 < rest.length && !rest[i + 1]!.startsWith('--')) {\n args[rawKey] = rest[i + 1]!\n i += 1\n } else {\n args[rawKey] = true\n }\n }\n return args\n}\n\nfunction stringOption(args: ParsedArgs, ...keys: string[]): string | undefined {\n for (const key of keys) {\n const raw = args[key]\n if (typeof raw !== 'string') continue\n const trimmed = raw.trim()\n if (trimmed.length > 0) return trimmed\n }\n return undefined\n}\n\nfunction flagEnabled(args: ParsedArgs, ...keys: string[]): boolean {\n for (const key of keys) {\n const raw = args[key]\n if (raw === undefined) continue\n if (raw === true) return true\n if (typeof raw === 'string') {\n const parsed = parseBooleanToken(raw)\n return parsed === null ? true : parsed\n }\n }\n return false\n}\n\nfunction splitListOption(raw: string | undefined): string[] {\n if (!raw) return []\n const seen = new Set<string>()\n const values: string[] = []\n for (const item of raw.split(',')) {\n const trimmed = item.trim()\n if (!trimmed || seen.has(trimmed)) continue\n seen.add(trimmed)\n values.push(trimmed)\n }\n return values\n}\n\nasync function resolveCacheScopes(\n em: EntityManager,\n args: ParsedArgs,\n): Promise<CacheScope[]> {\n const explicitTenantId = stringOption(args, 'tenant', 'tenantId')\n const globalOnly = flagEnabled(args, 'global')\n const allTenants = flagEnabled(args, 'all-tenants', 'allTenants')\n\n if (explicitTenantId && globalOnly) {\n throw new Error('Cannot combine `--tenant` with `--global`.')\n }\n if (explicitTenantId && allTenants) {\n throw new Error('Cannot combine `--tenant` with `--all-tenants`.')\n }\n if (globalOnly && allTenants) {\n throw new Error('Cannot combine `--global` with `--all-tenants`.')\n }\n\n if (explicitTenantId) {\n return [{ label: `tenant:${explicitTenantId}`, tenantId: explicitTenantId }]\n }\n\n if (globalOnly) {\n return [{ label: 'global', tenantId: null }]\n }\n\n if (!allTenants) {\n return [{ label: 'global', tenantId: null }]\n }\n\n const tenants = await em.find(Tenant, { deletedAt: null }, { orderBy: { name: 'asc' } })\n const scopes: CacheScope[] = [{ label: 'global', tenantId: null }]\n const seen = new Set<string>()\n for (const tenant of tenants) {\n const tenantId = typeof tenant.id === 'string' ? tenant.id : ''\n if (!tenantId || seen.has(tenantId)) continue\n seen.add(tenantId)\n scopes.push({ label: `tenant:${tenantId}`, tenantId })\n }\n return scopes\n}\n\nfunction resolveCachePurgeRequest(args: ParsedArgs): CachePurgeRequest {\n if (flagEnabled(args, 'all')) return { kind: 'all' }\n\n const segment = stringOption(args, 'segment')\n if (segment) return { kind: 'segment', segment }\n\n const tags = splitListOption(stringOption(args, 'tag', 'tags'))\n if (tags.length > 0) return { kind: 'tags', tags }\n\n const keys = splitListOption(stringOption(args, 'key', 'keys'))\n if (keys.length > 0) return { kind: 'keys', keys }\n\n const ids = splitListOption(stringOption(args, 'id', 'ids'))\n if (ids.length > 0) return { kind: 'ids', ids }\n\n const pattern = stringOption(args, 'pattern')\n if (pattern) return { kind: 'pattern', pattern }\n\n throw new Error(\n 'Choose a purge target: `--all`, `--segment <id>`, `--tag <tag1,tag2>`, `--key <key1,key2>`, `--id <token1,token2>`, or `--pattern <glob>`.',\n )\n}\n\nexport function isCacheHelpFlag(arg: string): boolean {\n return arg === 'help' || arg === '--help' || arg === '-h'\n}\n\nfunction printCacheHelp() {\n console.log('\uD83E\uDDF9 Cache CLI')\n console.log('')\n console.log('\uD83D\uDE80 Usage:')\n console.log(' yarn mercato configs cache stats [--tenant <id> | --global | --all-tenants] [--json]')\n console.log(' yarn mercato configs cache purge --all [--tenant <id> | --global | --all-tenants] [--dry-run] [--json]')\n console.log(' yarn mercato configs cache purge --segment <segment> [--tenant <id> | --global | --all-tenants] [--dry-run] [--json]')\n console.log(' yarn mercato configs cache purge --tag <tag1,tag2> [--tenant <id> | --global | --all-tenants] [--dry-run] [--json]')\n console.log(' yarn mercato configs cache purge --key <key1,key2> [--tenant <id> | --global | --all-tenants] [--dry-run] [--json]')\n console.log(' yarn mercato configs cache purge --id <token1,token2> [--tenant <id> | --global | --all-tenants] [--dry-run] [--json]')\n console.log(' yarn mercato configs cache purge --pattern <glob> [--tenant <id> | --global | --all-tenants] [--dry-run] [--json]')\n console.log(' yarn mercato configs cache structural [--tenant <id> | --global | --all-tenants] [--touch-generated] [--dry-run] [--json]')\n console.log('')\n console.log('\u2139\uFE0F Notes:')\n console.log(' `stats` mirrors the cache admin page segment overview for CRUD/widget caches.')\n console.log(' `purge --id` removes every key whose name contains the provided token (for example a user id or entity id).')\n console.log(' `structural` targets navigation/sidebar caches. Add `--touch-generated` only for explicit stale-compiler recovery.')\n console.log(' When no scope flag is supplied, this command uses the global cache scope only.')\n}\n\nasync function disposeContainer(container: unknown) {\n const disposable = container as { dispose?: () => Promise<void> }\n if (typeof disposable.dispose === 'function') {\n await disposable.dispose()\n }\n}\n\nasync function runCacheStats(args: ParsedArgs) {\n const json = flagEnabled(args, 'json')\n const container = await createRequestContainer()\n try {\n const em = container.resolve('em') as EntityManager\n const cache = container.resolve('cache') as CacheStrategy\n const scopes = await resolveCacheScopes(em, args)\n const results = []\n for (const scope of scopes) {\n const stats = await runWithCacheTenant(scope.tenantId, async () => collectCacheStats(cache))\n results.push({ scope: scope.label, ...stats })\n }\n\n if (json) {\n console.log(JSON.stringify(results, null, 2))\n return\n }\n\n for (const result of results) {\n console.log(`\uD83D\uDD0E [cache] scope=${result.scope} totalKeys=${result.totalKeys} generatedAt=${result.generatedAt}`)\n if (result.segments.length === 0) {\n console.log(' \u2205 segments: none')\n continue\n }\n for (const segment of result.segments) {\n console.log(` \u2022 ${segment.segment} (${segment.keyCount})${segment.path ? ` ${segment.path}` : ''}`)\n }\n }\n } finally {\n await disposeContainer(container)\n }\n}\n\nasync function runCachePurgeRequest(\n args: ParsedArgs,\n request: CachePurgeRequest,\n emitOutput = true,\n) {\n const json = flagEnabled(args, 'json')\n const quiet = flagEnabled(args, 'quiet')\n const dryRun = flagEnabled(args, 'dry-run', 'dryRun')\n const container = await createRequestContainer()\n try {\n const em = container.resolve('em') as EntityManager\n const cache = container.resolve('cache') as CacheStrategy\n const scopes = await resolveCacheScopes(em, args)\n const results = []\n\n for (const scope of scopes) {\n const result = await runWithCacheTenant(scope.tenantId, async () =>\n dryRun ? previewCachePurge(cache, request) : executeCachePurge(cache, request)\n )\n results.push({\n scope: scope.label,\n dryRun,\n request,\n deleted: result.deleted,\n keyCount: result.keys.length,\n keys: result.keys,\n note: result.note,\n })\n }\n\n if (json && emitOutput) {\n console.log(JSON.stringify(results, null, 2))\n return results\n }\n\n if (quiet || !emitOutput) {\n return results\n }\n\n for (const result of results) {\n console.log(`${result.dryRun ? '\uD83E\uDDEA' : '\uD83E\uDDF9'} [cache] scope=${result.scope} deleted=${result.deleted}${result.dryRun ? ' (dry-run)' : ''}`)\n if (result.note) console.log(` \u2139\uFE0F note: ${result.note}`)\n if (result.keys.length > 0) {\n for (const key of result.keys) {\n console.log(` \u2022 ${key}`)\n }\n }\n }\n return results\n } finally {\n await disposeContainer(container)\n }\n}\n\nasync function runCachePurge(args: ParsedArgs) {\n await runCachePurgeRequest(args, resolveCachePurgeRequest(args))\n}\n\nasync function runStructuralCachePurge(args: ParsedArgs) {\n const json = flagEnabled(args, 'json')\n const structuralResults: Array<{\n request: CachePurgeRequest\n results: Awaited<ReturnType<typeof runCachePurgeRequest>>\n }> = []\n for (const request of STRUCTURAL_CACHE_REQUESTS) {\n const results = await runCachePurgeRequest(args, request, !json)\n structuralResults.push({ request, results })\n }\n if (json) {\n console.log(JSON.stringify(structuralResults, null, 2))\n }\n if (flagEnabled(args, 'touch-generated', 'touchGenerated')) {\n const quiet = flagEnabled(args, 'quiet')\n try {\n touchGeneratedBarrels({ quiet: quiet || json })\n } catch (err) {\n if (!quiet && !json) {\n console.warn(\n `[structural] failed to touch generated barrels: ${(err as Error).message ?? err}`,\n )\n }\n }\n }\n}\n\nfunction envDisablesAutoIndexing(): boolean {\n const raw =\n process.env.OM_DISABLE_VECTOR_SEARCH_AUTOINDEXING ??\n process.env.DISABLE_VECTOR_SEARCH_AUTOINDEXING\n if (!raw) return false\n return parseBooleanToken(raw) === true\n}\n\nconst restoreDefaults: ModuleCli = {\n command: 'restore-defaults',\n async run() {\n const container = await createRequestContainer()\n try {\n let service: ModuleConfigService\n try {\n service = (container.resolve('moduleConfigService') as ModuleConfigService)\n } catch {\n console.error('[configs] moduleConfigService is not registered in the container.')\n return\n }\n\n const disabledByEnv = envDisablesAutoIndexing()\n const defaultEnabled = !disabledByEnv\n await service.restoreDefaults(\n [\n {\n moduleId: 'vector',\n name: 'auto_index_enabled',\n value: defaultEnabled,\n },\n {\n moduleId: 'notifications',\n name: NOTIFICATIONS_DELIVERY_CONFIG_KEY,\n value: STORED_DEFAULT_NOTIFICATION_DELIVERY_CONFIG,\n },\n ],\n { force: true },\n )\n console.log(\n `[configs] Vector auto-indexing default set to ${defaultEnabled ? 'enabled' : 'disabled'}${\n disabledByEnv\n ? ' (forced by OM_DISABLE_VECTOR_SEARCH_AUTOINDEXING or legacy DISABLE_VECTOR_SEARCH_AUTOINDEXING)'\n : ''\n }.`,\n )\n } finally {\n const disposable = container as unknown as { dispose?: () => Promise<void> }\n if (typeof disposable.dispose === 'function') {\n await disposable.dispose()\n }\n }\n },\n}\n\nconst help: ModuleCli = {\n command: 'help',\n async run() {\n console.log('\u2699\uFE0F Configs CLI')\n console.log('')\n console.log('\uD83D\uDE80 Usage: yarn mercato configs restore-defaults')\n console.log(' Ensures global module configuration defaults exist.')\n console.log('')\n printCacheHelp()\n },\n}\n\nconst cacheCommand: ModuleCli = {\n command: 'cache',\n // Prints subcommand-aware help itself, so the dispatcher must forward --help/-h here.\n handlesHelp: true,\n async run(rest) {\n const [subcommand, ...subRest] = rest\n const args = parseArgs(subRest)\n\n // `handlesHelp` makes this command responsible for the guarantee the dispatcher gives\n // everywhere else, so a help flag anywhere wins over the subcommand \u2014 otherwise\n // `configs cache purge --help` would purge the cache it was only asked to describe.\n if (!subcommand || rest.some(isCacheHelpFlag)) {\n printCacheHelp()\n return\n }\n\n if (subcommand === 'stats') {\n await runCacheStats(args)\n return\n }\n\n if (subcommand === 'purge') {\n await runCachePurge(args)\n return\n }\n\n if (subcommand === 'structural') {\n await runStructuralCachePurge(args)\n return\n }\n\n throw new Error(`Unknown cache subcommand \"${subcommand}\".`)\n },\n}\n\nexport default [restoreDefaults, cacheCommand, help]\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,0BAA8C;AACvD,SAAS,8BAA8B;AAEvC,SAAS,yBAAyB;AAClC,SAAS,6CAA6C,yCAAyC;AAC/F,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,6BAA6B;AAI/B,MAAM,4BAAiD;AAAA,EAC5D,EAAE,MAAM,WAAW,SAAS,QAAQ;AAAA,EACpC,EAAE,MAAM,WAAW,SAAS,YAAY;AAAA,EACxC,EAAE,MAAM,WAAW,SAAS,aAAa;AAC3C;AAOA,SAAS,UAAU,MAA4B;AAC7C,QAAM,OAAmB,CAAC;AAC1B,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;AACvC,UAAM,OAAO,KAAK,CAAC;AACnB,QAAI,CAAC,MAAM,WAAW,IAAI,EAAG;AAC7B,UAAM,CAAC,QAAQ,QAAQ,IAAI,KAAK,MAAM,CAAC,EAAE,MAAM,GAAG;AAClD,QAAI,CAAC,OAAQ;AACb,QAAI,aAAa,QAAW;AAC1B,WAAK,MAAM,IAAI;AAAA,IACjB,WAAW,IAAI,IAAI,KAAK,UAAU,CAAC,KAAK,IAAI,CAAC,EAAG,WAAW,IAAI,GAAG;AAChE,WAAK,MAAM,IAAI,KAAK,IAAI,CAAC;AACzB,WAAK;AAAA,IACP,OAAO;AACL,WAAK,MAAM,IAAI;AAAA,IACjB;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,aAAa,SAAqB,MAAoC;AAC7E,aAAW,OAAO,MAAM;AACtB,UAAM,MAAM,KAAK,GAAG;AACpB,QAAI,OAAO,QAAQ,SAAU;AAC7B,UAAM,UAAU,IAAI,KAAK;AACzB,QAAI,QAAQ,SAAS,EAAG,QA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F;AAEA,QAAI,eAAe,SAAS;AAC1B,YAAM,cAAc,IAAI;AACxB;AAAA,IACF;AAEA,QAAI,eAAe,cAAc;AAC/B,YAAM,wBAAwB,IAAI;AAClC;AAAA,IACF;AAEA,UAAM,IAAI,MAAM,6BAA6B,UAAU,IAAI;AAAA,EAC7D;AACF;AAEA,IAAO,cAAQ,CAAC,iBAAiB,cAAc,IAAI;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -118,6 +118,9 @@ async function GET(req, ctx) {
|
|
|
118
118
|
if (isCrudHttpError(error)) {
|
|
119
119
|
return NextResponse.json(error.body, { status: error.status });
|
|
120
120
|
}
|
|
121
|
+
if (error instanceof z.ZodError) {
|
|
122
|
+
return NextResponse.json({ error: translate("customers.errors.validationFailed", "Validation failed"), details: error.issues }, { status: 400 });
|
|
123
|
+
}
|
|
121
124
|
logger.error("customers.companies.people.GET", { err: error });
|
|
122
125
|
return NextResponse.json({ error: translate("customers.errors.company_people_load_failed", "Failed to load linked people") }, { status: 500 });
|
|
123
126
|
}
|