@open-mercato/core 0.11.1-develop.8557.1.e615240a3e → 0.11.1-develop.8572.1.85986dc508
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/api_keys/di.js +6 -2
- package/dist/modules/api_keys/di.js.map +2 -2
- package/dist/modules/api_keys/services/oneTimeIssuerService.js +47 -0
- package/dist/modules/api_keys/services/oneTimeIssuerService.js.map +7 -0
- package/dist/modules/audit_logs/di.js +2 -1
- package/dist/modules/audit_logs/di.js.map +2 -2
- package/dist/modules/audit_logs/services/actionLogService.js +65 -1
- package/dist/modules/audit_logs/services/actionLogService.js.map +2 -2
- package/dist/modules/auth/cli.js +1 -0
- package/dist/modules/auth/cli.js.map +2 -2
- package/dist/modules/auth/commands/users.js +10 -2
- package/dist/modules/auth/commands/users.js.map +2 -2
- package/dist/modules/auth/lib/setup-app.js +19 -5
- package/dist/modules/auth/lib/setup-app.js.map +2 -2
- package/dist/modules/catalog/lib/productScopeReindex.js +1 -1
- package/dist/modules/catalog/lib/productScopeReindex.js.map +2 -2
- package/dist/modules/configs/cli.js +26 -29
- package/dist/modules/configs/cli.js.map +2 -2
- package/dist/modules/configs/di.js +3 -1
- package/dist/modules/configs/di.js.map +2 -2
- package/dist/modules/configs/lib/instance-config-initializer.js +44 -0
- package/dist/modules/configs/lib/instance-config-initializer.js.map +7 -0
- package/dist/modules/configs/lib/instance-defaults.js +204 -0
- package/dist/modules/configs/lib/instance-defaults.js.map +7 -0
- package/dist/modules/configs/lib/module-config-service.js +115 -1
- package/dist/modules/configs/lib/module-config-service.js.map +2 -2
- package/dist/modules/entities/api/definitions.batch.js +55 -25
- package/dist/modules/entities/api/definitions.batch.js.map +2 -2
- package/dist/modules/entities/api/definitions.js +35 -8
- package/dist/modules/entities/api/definitions.js.map +2 -2
- package/dist/modules/entities/backend/entities/user/[entityId]/page.js +14 -8
- package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
- package/dist/modules/notifications/lib/deliveryConfig.js +19 -12
- package/dist/modules/notifications/lib/deliveryConfig.js.map +2 -2
- package/dist/modules/notifications/setup.js +10 -0
- package/dist/modules/notifications/setup.js.map +2 -2
- package/dist/modules/payment_gateways/lib/gateway-service.js +1 -1
- package/dist/modules/payment_gateways/lib/gateway-service.js.map +2 -2
- package/dist/modules/query_index/api/purge.js +1 -1
- package/dist/modules/query_index/api/purge.js.map +2 -2
- package/dist/modules/query_index/api/reindex.js +1 -1
- package/dist/modules/query_index/api/reindex.js.map +2 -2
- package/dist/modules/query_index/cli.js +2 -2
- package/dist/modules/query_index/cli.js.map +2 -2
- package/dist/modules/query_index/lib/engine.js +5 -1
- package/dist/modules/query_index/lib/engine.js.map +2 -2
- package/dist/modules/query_index/subscribers/purge.js +3 -3
- package/dist/modules/query_index/subscribers/purge.js.map +2 -2
- package/dist/modules/query_index/subscribers/reindex.js +11 -13
- package/dist/modules/query_index/subscribers/reindex.js.map +2 -2
- package/dist/modules/translations/components/TranslationManager.js +47 -10
- package/dist/modules/translations/components/TranslationManager.js.map +2 -2
- package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js +8 -1
- package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js.map +2 -2
- package/dist/modules/workflows/ai-tools/authoring-pack.js +1 -1
- package/dist/modules/workflows/ai-tools/authoring-pack.js.map +2 -2
- package/dist/modules/workflows/api/instances/[id]/advance/route.js +1 -0
- package/dist/modules/workflows/api/instances/[id]/advance/route.js.map +2 -2
- package/dist/modules/workflows/api/instances/route.js +1 -1
- package/dist/modules/workflows/api/instances/route.js.map +2 -2
- package/dist/modules/workflows/api/instances/validate-start/route.js +3 -1
- package/dist/modules/workflows/api/instances/validate-start/route.js.map +2 -2
- package/dist/modules/workflows/components/fields/ActivityConfigFields.js +2 -0
- package/dist/modules/workflows/components/fields/ActivityConfigFields.js.map +2 -2
- package/dist/modules/workflows/di.js +3 -1
- package/dist/modules/workflows/di.js.map +2 -2
- package/dist/modules/workflows/events.js +13 -0
- package/dist/modules/workflows/events.js.map +2 -2
- package/dist/modules/workflows/lib/activity-executor.js +48 -15
- package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
- package/dist/modules/workflows/lib/condition-handler.js +1 -1
- package/dist/modules/workflows/lib/condition-handler.js.map +2 -2
- package/dist/modules/workflows/lib/error-handler.js +1 -1
- package/dist/modules/workflows/lib/error-handler.js.map +2 -2
- package/dist/modules/workflows/lib/event-trigger-service.js +1 -1
- package/dist/modules/workflows/lib/event-trigger-service.js.map +2 -2
- package/dist/modules/workflows/lib/example-definition-authoring.js +90 -0
- package/dist/modules/workflows/lib/example-definition-authoring.js.map +7 -0
- package/dist/modules/workflows/lib/named-rules.js +42 -0
- package/dist/modules/workflows/lib/named-rules.js.map +7 -0
- package/dist/modules/workflows/lib/owned-definition.js +2 -0
- package/dist/modules/workflows/lib/owned-definition.js.map +2 -2
- package/dist/modules/workflows/lib/parallel-handler.js +1 -1
- package/dist/modules/workflows/lib/parallel-handler.js.map +2 -2
- package/dist/modules/workflows/lib/signal-handler.js +1 -0
- package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
- package/dist/modules/workflows/lib/start-validator.js +87 -85
- package/dist/modules/workflows/lib/start-validator.js.map +2 -2
- package/dist/modules/workflows/lib/step-handler.js +1 -1
- package/dist/modules/workflows/lib/step-handler.js.map +2 -2
- package/dist/modules/workflows/lib/task-handler.js +1 -0
- package/dist/modules/workflows/lib/task-handler.js.map +2 -2
- package/dist/modules/workflows/lib/timer-handler.js +1 -0
- package/dist/modules/workflows/lib/timer-handler.js.map +2 -2
- package/dist/modules/workflows/lib/transition-handler.js +48 -166
- package/dist/modules/workflows/lib/transition-handler.js.map +3 -3
- package/dist/modules/workflows/lib/workflow-executor.js +3 -2
- package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
- package/package.json +8 -8
- package/src/modules/api_keys/di.ts +7 -2
- package/src/modules/api_keys/services/oneTimeIssuerService.ts +61 -0
- package/src/modules/audit_logs/di.ts +1 -0
- package/src/modules/audit_logs/services/actionLogService.ts +132 -1
- package/src/modules/auth/cli.ts +1 -0
- package/src/modules/auth/commands/users.ts +10 -2
- package/src/modules/auth/i18n/de.json +2 -0
- package/src/modules/auth/i18n/en.json +2 -0
- package/src/modules/auth/i18n/es.json +2 -0
- package/src/modules/auth/i18n/ko.json +2 -0
- package/src/modules/auth/i18n/pl.json +2 -0
- package/src/modules/auth/lib/setup-app.ts +30 -7
- package/src/modules/catalog/lib/productScopeReindex.ts +1 -1
- package/src/modules/configs/cli.ts +39 -37
- package/src/modules/configs/di.ts +2 -0
- package/src/modules/configs/lib/instance-config-initializer.ts +56 -0
- package/src/modules/configs/lib/instance-defaults.ts +262 -0
- package/src/modules/configs/lib/module-config-service.ts +156 -0
- package/src/modules/entities/api/definitions.batch.ts +65 -27
- package/src/modules/entities/api/definitions.ts +40 -11
- package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +14 -7
- package/src/modules/notifications/lib/deliveryConfig.ts +20 -11
- package/src/modules/notifications/setup.ts +11 -0
- package/src/modules/payment_gateways/lib/gateway-service.ts +2 -2
- package/src/modules/query_index/api/purge.ts +1 -1
- package/src/modules/query_index/api/reindex.ts +1 -1
- package/src/modules/query_index/cli.ts +2 -2
- package/src/modules/query_index/lib/engine.ts +5 -1
- package/src/modules/query_index/subscribers/purge.ts +5 -4
- package/src/modules/query_index/subscribers/reindex.ts +14 -15
- package/src/modules/translations/components/TranslationManager.tsx +49 -10
- package/src/modules/translations/i18n/de.json +1 -0
- package/src/modules/translations/i18n/en.json +1 -0
- package/src/modules/translations/i18n/es.json +1 -0
- package/src/modules/translations/i18n/ko.json +1 -0
- package/src/modules/translations/i18n/pl.json +1 -0
- package/src/modules/wms/components/backend/CompletePutawayTaskDialog.tsx +8 -1
- package/src/modules/wms/i18n/de.json +1 -0
- package/src/modules/wms/i18n/en.json +1 -0
- package/src/modules/wms/i18n/es.json +1 -0
- package/src/modules/wms/i18n/ko.json +1 -0
- package/src/modules/wms/i18n/pl.json +1 -0
- package/src/modules/workflows/ai-tools/authoring-pack.ts +3 -1
- package/src/modules/workflows/api/instances/[id]/advance/route.ts +1 -0
- package/src/modules/workflows/api/instances/route.ts +1 -1
- package/src/modules/workflows/api/instances/validate-start/route.ts +3 -1
- package/src/modules/workflows/components/fields/ActivityConfigFields.tsx +2 -0
- package/src/modules/workflows/di.ts +2 -0
- package/src/modules/workflows/events.ts +14 -0
- package/src/modules/workflows/lib/activity-executor.ts +64 -40
- package/src/modules/workflows/lib/condition-handler.ts +1 -1
- package/src/modules/workflows/lib/error-handler.ts +1 -1
- package/src/modules/workflows/lib/event-trigger-service.ts +1 -1
- package/src/modules/workflows/lib/example-definition-authoring.ts +114 -0
- package/src/modules/workflows/lib/named-rules.ts +54 -0
- package/src/modules/workflows/lib/owned-definition.ts +4 -1
- package/src/modules/workflows/lib/parallel-handler.ts +1 -1
- package/src/modules/workflows/lib/signal-handler.ts +1 -0
- package/src/modules/workflows/lib/start-validator.ts +96 -94
- package/src/modules/workflows/lib/step-handler.ts +1 -1
- package/src/modules/workflows/lib/task-handler.ts +1 -0
- package/src/modules/workflows/lib/timer-handler.ts +1 -0
- package/src/modules/workflows/lib/transition-handler.ts +74 -238
- package/src/modules/workflows/lib/workflow-executor.ts +7 -4
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { tryGetModules } from '@open-mercato/shared/lib/modules/registry'
|
|
2
|
+
import type { Module } from '@open-mercato/shared/modules/registry'
|
|
3
|
+
import {
|
|
4
|
+
SEARCH_AUTO_INDEX_CONFIG_KEY,
|
|
5
|
+
SEARCH_AUTO_INDEX_CONFIG_MODULE,
|
|
6
|
+
} from '@open-mercato/shared/lib/search/auto-indexing'
|
|
7
|
+
import { moduleConfigKeySchema } from '../data/validators'
|
|
8
|
+
|
|
9
|
+
export type ResolvedInstanceConfigDefault = {
|
|
10
|
+
ownerModuleId: string
|
|
11
|
+
moduleId: string
|
|
12
|
+
name: string
|
|
13
|
+
value: unknown
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const RESERVED_LEGACY_NAMESPACE_OWNER = 'search'
|
|
17
|
+
const RESERVED_LEGACY_NAMESPACE = SEARCH_AUTO_INDEX_CONFIG_MODULE
|
|
18
|
+
const RESERVED_LEGACY_KEY = SEARCH_AUTO_INDEX_CONFIG_KEY
|
|
19
|
+
|
|
20
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
21
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
22
|
+
return false
|
|
23
|
+
}
|
|
24
|
+
const proto = Object.getPrototypeOf(value)
|
|
25
|
+
return proto === Object.prototype || proto === null
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Validates that a default value is a finite JSON value (no NaN, +/-Infinity,
|
|
30
|
+
* BigInt, functions, symbols, circular references, non-plain class instances,
|
|
31
|
+
* top-level undefined, or array undefined elements) and returns a detached clone.
|
|
32
|
+
* Error messages intentionally omit the raw value.
|
|
33
|
+
*/
|
|
34
|
+
export function validateAndCloneFiniteJsonValue(
|
|
35
|
+
value: unknown,
|
|
36
|
+
ownerLabel: string,
|
|
37
|
+
keyLabel: string,
|
|
38
|
+
ancestors: Set<object> = new Set(),
|
|
39
|
+
): unknown {
|
|
40
|
+
if (value === undefined) {
|
|
41
|
+
throw new Error(
|
|
42
|
+
`[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": value must be a finite JSON value (undefined is not allowed).`,
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
if (value === null || typeof value === 'boolean' || typeof value === 'string') {
|
|
46
|
+
return value
|
|
47
|
+
}
|
|
48
|
+
if (typeof value === 'number') {
|
|
49
|
+
if (!Number.isFinite(value)) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
`[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": numeric value must be finite.`,
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
return value
|
|
55
|
+
}
|
|
56
|
+
if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol') {
|
|
57
|
+
throw new Error(
|
|
58
|
+
`[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": unsupported JSON value type "${typeof value}".`,
|
|
59
|
+
)
|
|
60
|
+
}
|
|
61
|
+
if (Array.isArray(value)) {
|
|
62
|
+
if (ancestors.has(value)) {
|
|
63
|
+
throw new Error(
|
|
64
|
+
`[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": circular reference detected.`,
|
|
65
|
+
)
|
|
66
|
+
}
|
|
67
|
+
ancestors.add(value)
|
|
68
|
+
try {
|
|
69
|
+
const cloned: unknown[] = new Array(value.length)
|
|
70
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
71
|
+
if (!(i in value)) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
`[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": sparse arrays are not valid JSON.`,
|
|
74
|
+
)
|
|
75
|
+
}
|
|
76
|
+
cloned[i] = validateAndCloneFiniteJsonValue(value[i], ownerLabel, keyLabel, ancestors)
|
|
77
|
+
}
|
|
78
|
+
return cloned
|
|
79
|
+
} finally {
|
|
80
|
+
ancestors.delete(value)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (!isPlainObject(value)) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
`[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": value must be a plain JSON object.`,
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
if (Object.getOwnPropertySymbols(value).length > 0) {
|
|
89
|
+
throw new Error(
|
|
90
|
+
`[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": symbol keys are not allowed in JSON defaults.`,
|
|
91
|
+
)
|
|
92
|
+
}
|
|
93
|
+
if (ancestors.has(value)) {
|
|
94
|
+
throw new Error(
|
|
95
|
+
`[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": circular reference detected.`,
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
ancestors.add(value)
|
|
99
|
+
try {
|
|
100
|
+
const entries: Array<[string, unknown]> = []
|
|
101
|
+
for (const [propKey, propValue] of Object.entries(value)) {
|
|
102
|
+
if (propValue === undefined) {
|
|
103
|
+
continue
|
|
104
|
+
}
|
|
105
|
+
entries.push([propKey, validateAndCloneFiniteJsonValue(propValue, ownerLabel, keyLabel, ancestors)])
|
|
106
|
+
}
|
|
107
|
+
return Object.fromEntries(entries)
|
|
108
|
+
} finally {
|
|
109
|
+
ancestors.delete(value)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function compareConfigKeys(
|
|
114
|
+
left: { moduleId: string; name: string },
|
|
115
|
+
right: { moduleId: string; name: string },
|
|
116
|
+
): number {
|
|
117
|
+
if (left.moduleId !== right.moduleId) {
|
|
118
|
+
return left.moduleId < right.moduleId ? -1 : 1
|
|
119
|
+
}
|
|
120
|
+
if (left.name !== right.name) {
|
|
121
|
+
return left.name < right.name ? -1 : 1
|
|
122
|
+
}
|
|
123
|
+
return 0
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function isAllowedLegacyStorageNamespace(
|
|
127
|
+
ownerModuleId: string,
|
|
128
|
+
storageNamespace: string,
|
|
129
|
+
name: string,
|
|
130
|
+
): boolean {
|
|
131
|
+
return (
|
|
132
|
+
ownerModuleId === RESERVED_LEGACY_NAMESPACE_OWNER &&
|
|
133
|
+
storageNamespace === RESERVED_LEGACY_NAMESPACE &&
|
|
134
|
+
name === RESERVED_LEGACY_KEY
|
|
135
|
+
)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Collects, validates, and deterministically orders instance configuration defaults
|
|
140
|
+
* contributed by enabled modules' `setup.instanceConfigDefaults` providers.
|
|
141
|
+
*
|
|
142
|
+
* Fails before any persistence occurs if the module registry is uninitialized,
|
|
143
|
+
* a provider is non-synchronous or returns malformed descriptors, an unauthorized
|
|
144
|
+
* cross-namespace write is attempted, or normalized final keys collide.
|
|
145
|
+
*/
|
|
146
|
+
export function collectInstanceConfigDefaults(
|
|
147
|
+
modules?: readonly Module[],
|
|
148
|
+
): ResolvedInstanceConfigDefault[] {
|
|
149
|
+
const enabledModules = modules ?? tryGetModules()
|
|
150
|
+
if (!enabledModules) {
|
|
151
|
+
throw new Error(
|
|
152
|
+
'[configs] Cannot resolve instance config defaults: enabled module registry is not initialized.',
|
|
153
|
+
)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const resolved: ResolvedInstanceConfigDefault[] = []
|
|
157
|
+
const seenKeys = new Map<string, string>()
|
|
158
|
+
|
|
159
|
+
for (const mod of enabledModules) {
|
|
160
|
+
const ownerModuleId = typeof mod?.id === 'string' ? mod.id.trim() : ''
|
|
161
|
+
const provider = mod?.setup?.instanceConfigDefaults
|
|
162
|
+
if (provider === undefined) continue
|
|
163
|
+
|
|
164
|
+
if (!ownerModuleId) {
|
|
165
|
+
throw new Error(
|
|
166
|
+
'[configs] Invalid instanceConfigDefaults contribution: owning module has an empty id.',
|
|
167
|
+
)
|
|
168
|
+
}
|
|
169
|
+
if (typeof provider !== 'function') {
|
|
170
|
+
throw new Error(
|
|
171
|
+
`[configs] Invalid instanceConfigDefaults provider on module "${ownerModuleId}": expected a synchronous function.`,
|
|
172
|
+
)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const rawEntries = provider()
|
|
176
|
+
if (
|
|
177
|
+
rawEntries !== null &&
|
|
178
|
+
typeof rawEntries === 'object' &&
|
|
179
|
+
typeof (rawEntries as { then?: unknown }).then === 'function'
|
|
180
|
+
) {
|
|
181
|
+
// Prevent unhandled rejection noise when an accidentally async provider rejects.
|
|
182
|
+
;(rawEntries as unknown as PromiseLike<unknown>).then(undefined, () => {})
|
|
183
|
+
throw new Error(
|
|
184
|
+
`[configs] Invalid instanceConfigDefaults provider on module "${ownerModuleId}": provider must be synchronous and cannot return a Promise.`,
|
|
185
|
+
)
|
|
186
|
+
}
|
|
187
|
+
if (!Array.isArray(rawEntries)) {
|
|
188
|
+
throw new Error(
|
|
189
|
+
`[configs] Invalid instanceConfigDefaults provider on module "${ownerModuleId}": expected an array of default entries.`,
|
|
190
|
+
)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
for (let index = 0; index < rawEntries.length; index += 1) {
|
|
194
|
+
const entry = rawEntries[index]
|
|
195
|
+
if (!isPlainObject(entry)) {
|
|
196
|
+
throw new Error(
|
|
197
|
+
`[configs] Invalid instance config default entry #${index} from module "${ownerModuleId}": expected a plain object.`,
|
|
198
|
+
)
|
|
199
|
+
}
|
|
200
|
+
if (typeof entry.name !== 'string') {
|
|
201
|
+
throw new Error(
|
|
202
|
+
`[configs] Invalid instance config default entry #${index} from module "${ownerModuleId}": "name" must be a string.`,
|
|
203
|
+
)
|
|
204
|
+
}
|
|
205
|
+
if (
|
|
206
|
+
entry.legacyStorageNamespace !== undefined &&
|
|
207
|
+
typeof entry.legacyStorageNamespace !== 'string'
|
|
208
|
+
) {
|
|
209
|
+
throw new Error(
|
|
210
|
+
`[configs] Invalid instance config default "${entry.name}" from module "${ownerModuleId}": "legacyStorageNamespace" must be a string when provided.`,
|
|
211
|
+
)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const rawNamespace = entry.legacyStorageNamespace ?? ownerModuleId
|
|
215
|
+
const parsedKey = moduleConfigKeySchema.safeParse({
|
|
216
|
+
moduleId: rawNamespace,
|
|
217
|
+
name: entry.name,
|
|
218
|
+
})
|
|
219
|
+
if (!parsedKey.success) {
|
|
220
|
+
throw new Error(
|
|
221
|
+
`[configs] Invalid instance config default key from module "${ownerModuleId}" (entry #${index}): ${parsedKey.error.issues[0]?.message ?? 'invalid key'}.`,
|
|
222
|
+
)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const { moduleId, name } = parsedKey.data
|
|
226
|
+
|
|
227
|
+
if (entry.legacyStorageNamespace !== undefined) {
|
|
228
|
+
if (!isAllowedLegacyStorageNamespace(ownerModuleId, moduleId, name)) {
|
|
229
|
+
throw new Error(
|
|
230
|
+
`[configs] Unauthorized cross-namespace instance config default "${moduleId}.${name}" declared by module "${ownerModuleId}".`,
|
|
231
|
+
)
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const keyLabel = `${moduleId}.${name}`
|
|
236
|
+
const sanitizedValue = validateAndCloneFiniteJsonValue(
|
|
237
|
+
entry.value,
|
|
238
|
+
ownerModuleId,
|
|
239
|
+
keyLabel,
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
const dedupeKey = JSON.stringify([moduleId, name])
|
|
243
|
+
const previousOwner = seenKeys.get(dedupeKey)
|
|
244
|
+
if (previousOwner !== undefined) {
|
|
245
|
+
throw new Error(
|
|
246
|
+
`[configs] Duplicate instance config default key "${keyLabel}" declared by module "${ownerModuleId}" (already declared by "${previousOwner}").`,
|
|
247
|
+
)
|
|
248
|
+
}
|
|
249
|
+
seenKeys.set(dedupeKey, ownerModuleId)
|
|
250
|
+
|
|
251
|
+
resolved.push({
|
|
252
|
+
ownerModuleId,
|
|
253
|
+
moduleId,
|
|
254
|
+
name,
|
|
255
|
+
value: sanitizedValue,
|
|
256
|
+
})
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
resolved.sort(compareConfigKeys)
|
|
261
|
+
return resolved
|
|
262
|
+
}
|
|
@@ -2,8 +2,10 @@ import type { EntityManager } from '@mikro-orm/postgresql'
|
|
|
2
2
|
import { getCurrentCacheTenant, runWithCacheTenant } from '@open-mercato/cache'
|
|
3
3
|
import type { CacheStrategy } from '@open-mercato/cache'
|
|
4
4
|
import type { AppContainer } from '@open-mercato/shared/lib/di/container'
|
|
5
|
+
import { isUniqueViolation } from '@open-mercato/shared/lib/db/pg-errors'
|
|
5
6
|
import { ModuleConfig } from '../data/entities'
|
|
6
7
|
import { moduleConfigKeySchema } from '../data/validators'
|
|
8
|
+
import { compareConfigKeys, validateAndCloneFiniteJsonValue } from './instance-defaults'
|
|
7
9
|
|
|
8
10
|
const CACHE_VERSION = 'v3'
|
|
9
11
|
const CACHE_TTL_MS = 60_000
|
|
@@ -119,6 +121,11 @@ export type ModuleConfigDefault = {
|
|
|
119
121
|
value: unknown
|
|
120
122
|
}
|
|
121
123
|
|
|
124
|
+
export type RestoreDefaultsStrictOptions = {
|
|
125
|
+
force?: boolean
|
|
126
|
+
maxConflictRetries?: number
|
|
127
|
+
}
|
|
128
|
+
|
|
122
129
|
export type ModuleConfigService = {
|
|
123
130
|
getRecord(moduleId: string, name: string, scope?: ConfigScope): Promise<ModuleConfigRecord | null>
|
|
124
131
|
getValue<T = unknown>(
|
|
@@ -128,9 +135,152 @@ export type ModuleConfigService = {
|
|
|
128
135
|
): Promise<T | null>
|
|
129
136
|
setValue(moduleId: string, name: string, value: unknown, scope?: ConfigScope): Promise<ModuleConfigRecord | null>
|
|
130
137
|
restoreDefaults(defaults: ModuleConfigDefault[], options?: { force?: boolean }): Promise<void>
|
|
138
|
+
restoreDefaultsStrict?(
|
|
139
|
+
defaults: readonly ModuleConfigDefault[],
|
|
140
|
+
options?: RestoreDefaultsStrictOptions,
|
|
141
|
+
): Promise<ModuleConfigRecord[]>
|
|
131
142
|
invalidate(moduleId: string, name?: string, scope?: ConfigScope): Promise<void>
|
|
132
143
|
}
|
|
133
144
|
|
|
145
|
+
function prepareStrictDefaults(
|
|
146
|
+
defaults: readonly ModuleConfigDefault[],
|
|
147
|
+
): Array<{ moduleId: string; name: string; value: unknown }> {
|
|
148
|
+
if (!Array.isArray(defaults)) {
|
|
149
|
+
throw new Error('[configs] Invalid instance config defaults catalog: expected an array.')
|
|
150
|
+
}
|
|
151
|
+
const seen = new Set<string>()
|
|
152
|
+
const validated: Array<{ moduleId: string; name: string; value: unknown }> = []
|
|
153
|
+
for (let index = 0; index < defaults.length; index += 1) {
|
|
154
|
+
const entry = defaults[index]
|
|
155
|
+
const parsedKey = moduleConfigKeySchema.safeParse({
|
|
156
|
+
moduleId: entry?.moduleId,
|
|
157
|
+
name: entry?.name,
|
|
158
|
+
})
|
|
159
|
+
if (!parsedKey.success) {
|
|
160
|
+
throw new Error(
|
|
161
|
+
`[configs] Invalid instance config default key at index ${index}: ${parsedKey.error.issues[0]?.message ?? 'invalid key'}.`,
|
|
162
|
+
)
|
|
163
|
+
}
|
|
164
|
+
const { moduleId, name } = parsedKey.data
|
|
165
|
+
const keyLabel = `${moduleId}.${name}`
|
|
166
|
+
const dedupeKey = JSON.stringify([moduleId, name])
|
|
167
|
+
if (seen.has(dedupeKey)) {
|
|
168
|
+
throw new Error(`[configs] Duplicate instance config default key "${keyLabel}".`)
|
|
169
|
+
}
|
|
170
|
+
seen.add(dedupeKey)
|
|
171
|
+
const value = validateAndCloneFiniteJsonValue(entry.value, moduleId, keyLabel)
|
|
172
|
+
validated.push({ moduleId, name, value })
|
|
173
|
+
}
|
|
174
|
+
validated.sort(compareConfigKeys)
|
|
175
|
+
return validated
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Strictly restores instance-scoped module configuration defaults in a single
|
|
180
|
+
* transaction on a fresh EntityManager.
|
|
181
|
+
*
|
|
182
|
+
* - An empty catalog is a successful no-op.
|
|
183
|
+
* - All keys and finite JSON values are validated before any DB writes occur.
|
|
184
|
+
* - Missing EntityManager, lookup, persistence, flush, or commit errors propagate
|
|
185
|
+
* with transaction rollback and zero cache writes.
|
|
186
|
+
* - Concurrent unique-index conflicts (SQLSTATE 23505) retry with a fresh EM fork.
|
|
187
|
+
* - Cache entries are published only after the transaction commits.
|
|
188
|
+
*/
|
|
189
|
+
export async function restoreInstanceDefaultsStrict(
|
|
190
|
+
container: AppContainer,
|
|
191
|
+
defaults: readonly ModuleConfigDefault[],
|
|
192
|
+
options?: RestoreDefaultsStrictOptions,
|
|
193
|
+
): Promise<ModuleConfigRecord[]> {
|
|
194
|
+
const validated = prepareStrictDefaults(defaults)
|
|
195
|
+
if (validated.length === 0) return []
|
|
196
|
+
|
|
197
|
+
const em = resolveEm(container)
|
|
198
|
+
if (!em) {
|
|
199
|
+
throw new Error(
|
|
200
|
+
'[configs] Cannot restore instance defaults: EntityManager is not registered in the container.',
|
|
201
|
+
)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const force = options?.force ?? true
|
|
205
|
+
const maxAttempts = Number.isFinite(options?.maxConflictRetries)
|
|
206
|
+
? Math.max(1, Math.trunc(options!.maxConflictRetries!))
|
|
207
|
+
: 3
|
|
208
|
+
let committedRecords: ModuleConfigRecord[] | null = null
|
|
209
|
+
|
|
210
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
211
|
+
const freshEm =
|
|
212
|
+
typeof (em as { fork?: unknown }).fork === 'function'
|
|
213
|
+
? (em.fork({
|
|
214
|
+
clear: true,
|
|
215
|
+
freshEventManager: true,
|
|
216
|
+
useContext: false,
|
|
217
|
+
}) as EntityManager)
|
|
218
|
+
: em
|
|
219
|
+
|
|
220
|
+
if (typeof (freshEm as { transactional?: unknown }).transactional !== 'function') {
|
|
221
|
+
throw new Error(
|
|
222
|
+
'[configs] Cannot restore instance defaults: EntityManager does not support transactions.',
|
|
223
|
+
)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
try {
|
|
227
|
+
committedRecords = await freshEm.transactional(async (txEm) => {
|
|
228
|
+
const repo = txEm.getRepository(ModuleConfig)
|
|
229
|
+
const touched: ModuleConfig[] = []
|
|
230
|
+
for (const entry of validated) {
|
|
231
|
+
const existing = await repo.findOne({
|
|
232
|
+
moduleId: entry.moduleId,
|
|
233
|
+
name: entry.name,
|
|
234
|
+
tenantId: null,
|
|
235
|
+
})
|
|
236
|
+
const now = new Date()
|
|
237
|
+
if (!existing) {
|
|
238
|
+
const created = repo.create({
|
|
239
|
+
moduleId: entry.moduleId,
|
|
240
|
+
name: entry.name,
|
|
241
|
+
valueJson: entry.value,
|
|
242
|
+
tenantId: null,
|
|
243
|
+
organizationId: null,
|
|
244
|
+
createdAt: now,
|
|
245
|
+
updatedAt: now,
|
|
246
|
+
})
|
|
247
|
+
txEm.persist(created)
|
|
248
|
+
touched.push(created)
|
|
249
|
+
} else if (force) {
|
|
250
|
+
existing.valueJson = entry.value
|
|
251
|
+
existing.updatedAt = now
|
|
252
|
+
txEm.persist(existing)
|
|
253
|
+
touched.push(existing)
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (touched.length > 0) {
|
|
257
|
+
await txEm.flush()
|
|
258
|
+
}
|
|
259
|
+
return touched.map((entity) => toRecord(entity, 'instance'))
|
|
260
|
+
})
|
|
261
|
+
break
|
|
262
|
+
} catch (error) {
|
|
263
|
+
if (isUniqueViolation(error) && attempt < maxAttempts) {
|
|
264
|
+
continue
|
|
265
|
+
}
|
|
266
|
+
throw error
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const records = committedRecords ?? []
|
|
271
|
+
const cache = resolveCache(container)
|
|
272
|
+
for (const record of records) {
|
|
273
|
+
await writeCache(
|
|
274
|
+
cache,
|
|
275
|
+
cacheKey(record.moduleId, record.name, null),
|
|
276
|
+
{ found: true, record },
|
|
277
|
+
record.moduleId,
|
|
278
|
+
null,
|
|
279
|
+
)
|
|
280
|
+
}
|
|
281
|
+
return records
|
|
282
|
+
}
|
|
283
|
+
|
|
134
284
|
export function createModuleConfigService(container: AppContainer): ModuleConfigService {
|
|
135
285
|
const loadRow = async (
|
|
136
286
|
cache: CacheStrategy | null,
|
|
@@ -270,11 +420,17 @@ export function createModuleConfigService(container: AppContainer): ModuleConfig
|
|
|
270
420
|
await deleteCacheByModule(cache, moduleId, [tenantId, getCurrentCacheTenant(), null])
|
|
271
421
|
}
|
|
272
422
|
|
|
423
|
+
const restoreDefaultsStrict = async (
|
|
424
|
+
defaults: readonly ModuleConfigDefault[],
|
|
425
|
+
options?: RestoreDefaultsStrictOptions,
|
|
426
|
+
): Promise<ModuleConfigRecord[]> => restoreInstanceDefaultsStrict(container, defaults, options)
|
|
427
|
+
|
|
273
428
|
return {
|
|
274
429
|
getRecord,
|
|
275
430
|
getValue,
|
|
276
431
|
setValue,
|
|
277
432
|
restoreDefaults,
|
|
433
|
+
restoreDefaultsStrict,
|
|
278
434
|
invalidate,
|
|
279
435
|
}
|
|
280
436
|
}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util'
|
|
1
2
|
import { NextResponse } from 'next/server'
|
|
2
3
|
import type { CacheStrategy } from '@open-mercato/cache'
|
|
3
4
|
import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
4
5
|
import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
|
|
6
|
+
import { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
7
|
+
import { normalizeCustomFieldOptions } from '@open-mercato/shared/modules/entities/options'
|
|
5
8
|
import { CustomFieldDef, CustomFieldEntityConfig } from '@open-mercato/core/modules/entities/data/entities'
|
|
6
9
|
import { customFieldEntityConfigSchema, upsertCustomFieldDefSchema } from '@open-mercato/core/modules/entities/data/validators'
|
|
7
10
|
import { z } from 'zod'
|
|
@@ -23,6 +26,7 @@ import {
|
|
|
23
26
|
resolveDefinitionMutationScope,
|
|
24
27
|
selectVisibleDefinitionWinner,
|
|
25
28
|
} from '../lib/definition-scope'
|
|
29
|
+
import { createVisibleDefinitionScopeClause } from '../lib/definition-scope-where'
|
|
26
30
|
|
|
27
31
|
export const metadata = {
|
|
28
32
|
POST: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },
|
|
@@ -33,6 +37,9 @@ const MAX_DEFINITIONS_PER_BATCH = 1000
|
|
|
33
37
|
const batchSchema = z
|
|
34
38
|
.object({
|
|
35
39
|
entityId: z.string().regex(/^[a-z0-9_]+:[a-z0-9_]+$/),
|
|
40
|
+
preserveOrder: z.boolean().optional().describe(
|
|
41
|
+
'Keep existing priorities, append new definitions, and leave unchanged visible definitions untouched.',
|
|
42
|
+
),
|
|
36
43
|
definitions: z
|
|
37
44
|
.array(
|
|
38
45
|
upsertCustomFieldDefSchema
|
|
@@ -64,6 +71,24 @@ function cloneFieldsets(fieldsets?: IncomingFieldset): IncomingFieldset {
|
|
|
64
71
|
}))
|
|
65
72
|
}
|
|
66
73
|
|
|
74
|
+
function normalizeDefinitionConfig(key: string, kind: string, input: Record<string, unknown> | null | undefined) {
|
|
75
|
+
const config = { ...input }
|
|
76
|
+
if (config.label == null || String(config.label).trim() === '') config.label = key
|
|
77
|
+
if (config.formEditable === undefined) config.formEditable = true
|
|
78
|
+
if (config.listVisible === undefined) config.listVisible = true
|
|
79
|
+
if (kind === 'multiline' && (config.editor == null || String(config.editor).trim() === '')) {
|
|
80
|
+
config.editor = 'markdown'
|
|
81
|
+
}
|
|
82
|
+
delete config.priority
|
|
83
|
+
return config
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function comparableDefinitionConfig(config: Record<string, unknown>) {
|
|
87
|
+
return Array.isArray(config.options)
|
|
88
|
+
? { ...config, options: normalizeCustomFieldOptions(config.options) }
|
|
89
|
+
: config
|
|
90
|
+
}
|
|
91
|
+
|
|
67
92
|
export async function POST(req: Request) {
|
|
68
93
|
const auth = await getAuthFromRequest(req)
|
|
69
94
|
if (!auth || !auth.orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
@@ -72,7 +97,7 @@ export async function POST(req: Request) {
|
|
|
72
97
|
|
|
73
98
|
const parsed = batchSchema.safeParse(body)
|
|
74
99
|
if (!parsed.success) return NextResponse.json({ error: 'Validation failed', details: parsed.error.flatten() }, { status: 400 })
|
|
75
|
-
const { entityId, definitions, fieldsets, singleFieldsetPerRecord } = parsed.data
|
|
100
|
+
const { entityId, definitions, fieldsets, singleFieldsetPerRecord, preserveOrder = false } = parsed.data
|
|
76
101
|
|
|
77
102
|
const container = await createRequestContainer()
|
|
78
103
|
const scope = await resolveDefinitionMutationScope({ auth, container, request: req })
|
|
@@ -132,40 +157,53 @@ export async function POST(req: Request) {
|
|
|
132
157
|
for (const existing of existingDefs) defByKey.set(existing.key, existing)
|
|
133
158
|
}
|
|
134
159
|
|
|
135
|
-
const
|
|
136
|
-
const inactiveKeys = definitions.filter((
|
|
137
|
-
if (inactiveKeys.length > 0) {
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
-
{
|
|
141
|
-
scope,
|
|
142
|
-
|
|
143
|
-
)
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
160
|
+
const visibleByKey = new Map<string, CustomFieldDef>()
|
|
161
|
+
const inactiveKeys = definitions.filter((definition) => definition.isActive === false).map((definition) => definition.key)
|
|
162
|
+
if ((preserveOrder && keys.length > 0) || inactiveKeys.length > 0) {
|
|
163
|
+
const visibility = { deletedAt: null, isActive: true }
|
|
164
|
+
const where = preserveOrder
|
|
165
|
+
? { entityId, ...createVisibleDefinitionScopeClause(scope), ...visibility }
|
|
166
|
+
: createVisibleDefinitionWhere(entityId, { $in: inactiveKeys }, scope, visibility)
|
|
167
|
+
const visibleDefinitions = await findWithDecryption<CustomFieldDef>(em, CustomFieldDef, where, undefined, scope)
|
|
168
|
+
for (const visible of visibleDefinitions) {
|
|
169
|
+
const previous = visibleByKey.get(visible.key)
|
|
170
|
+
if (!previous) visibleByKey.set(visible.key, visible)
|
|
171
|
+
else {
|
|
172
|
+
const winner = selectVisibleDefinitionWinner([previous, visible])
|
|
173
|
+
if (winner) visibleByKey.set(visible.key, winner)
|
|
174
|
+
}
|
|
148
175
|
}
|
|
149
|
-
|
|
150
|
-
|
|
176
|
+
}
|
|
177
|
+
let nextPriority = 0
|
|
178
|
+
if (preserveOrder) {
|
|
179
|
+
for (const visible of visibleByKey.values()) {
|
|
180
|
+
const priority = Number(visible.configJson?.priority ?? 0)
|
|
181
|
+
if (Number.isFinite(priority)) nextPriority = Math.max(nextPriority, priority + 1)
|
|
151
182
|
}
|
|
152
183
|
}
|
|
153
184
|
|
|
154
185
|
for (const [idx, d] of definitions.entries()) {
|
|
155
|
-
const where
|
|
186
|
+
const where = createExactDefinitionWhere(entityId, d.key, scope)
|
|
156
187
|
let def = defByKey.get(d.key)
|
|
157
|
-
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
188
|
+
const visible = visibleByKey.get(d.key)
|
|
189
|
+
const cfg = normalizeDefinitionConfig(d.key, d.kind, d.configJson)
|
|
190
|
+
if (preserveOrder) {
|
|
191
|
+
const previous = def ?? visible
|
|
192
|
+
if (
|
|
193
|
+
d.isActive !== false && previous && previous.isActive !== false && !previous.deletedAt &&
|
|
194
|
+
previous.kind === d.kind && isDeepStrictEqual(
|
|
195
|
+
comparableDefinitionConfig(cfg),
|
|
196
|
+
comparableDefinitionConfig(normalizeDefinitionConfig(d.key, previous.kind, previous.configJson)),
|
|
197
|
+
)
|
|
198
|
+
) continue
|
|
199
|
+
if (!previous) cfg.priority = nextPriority++
|
|
200
|
+
else if (previous.configJson?.priority !== undefined) cfg.priority = previous.configJson.priority
|
|
201
|
+
} else {
|
|
202
|
+
cfg.priority = idx
|
|
203
|
+
}
|
|
165
204
|
|
|
166
205
|
if (d.isActive === false) {
|
|
167
206
|
const now = new Date()
|
|
168
|
-
const inherited = inheritedByKey.get(d.key)
|
|
169
207
|
if (!def) {
|
|
170
208
|
def = createScopedDefinitionTombstone(
|
|
171
209
|
em,
|
|
@@ -173,7 +211,7 @@ export async function POST(req: Request) {
|
|
|
173
211
|
entityId,
|
|
174
212
|
key: d.key,
|
|
175
213
|
kind: d.kind,
|
|
176
|
-
configJson:
|
|
214
|
+
configJson: visible?.configJson ?? cfg,
|
|
177
215
|
},
|
|
178
216
|
scope,
|
|
179
217
|
now,
|