@open-mercato/shared 0.9.1-develop.7573.1.d0ccc51d5b → 0.9.1-develop.7574.1.837288eec1

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.
@@ -1,3 +1,3 @@
1
1
  [generate-countries] up to date (259 countries)
2
- [build:shared] found 320 entry points
2
+ [build:shared] found 321 entry points
3
3
  [build:shared] built successfully
package/AGENTS.md CHANGED
@@ -45,7 +45,7 @@ yarn workspace @open-mercato/shared build
45
45
  | `crud/` | When building CRUD routes | `@open-mercato/shared/lib/crud` |
46
46
  | `custom-fields/` | When handling custom field payloads | `@open-mercato/shared/lib/custom-fields` |
47
47
  | `data/` | When you need `DataEngine` or `QueryEngine` types | `@open-mercato/shared/lib/data/engine` |
48
- | `db/` | When resolving the ORM/connection-pool config (`resolvePoolConfig`, pool/timeout env knobs) | `@open-mercato/shared/lib/db/mikro` |
48
+ | `db/` | When resolving the ORM/connection-pool config (`resolvePoolConfig`, pool/timeout env knobs); when serializing a bounded write across processes under a Postgres transaction advisory lock (`withAdvisoryXactLock` — pass the request EntityManager; `fn` does all DB I/O on `txEm`, flushes its own writes, makes at most one external call, never nests `transactional` or forks; `maxConcurrentHolders` caps holders per process) | `@open-mercato/shared/lib/db/mikro`, `@open-mercato/shared/lib/db/advisoryLock` |
49
49
  | `delivery/` | When scheduling delivery/retry attempts — exponential backoff with jitter for delivery pipelines (currently the push delivery worker) | `@open-mercato/shared/lib/delivery/retry` (`calculateBackoffDelayMs`) |
50
50
  | `di/` | When setting up dependency injection (Awilix). The app-level hook (`src/di.ts` → `register`) is wired explicitly in BOTH bootstrap paths — `src/bootstrap.ts` for the Next.js runtime, `bootstrapFromAppRoot()` for worker/scheduler/CLI processes. Never rely on the legacy `import('@/di')` fallback: the alias does not exist outside the app bundler | `@open-mercato/shared/lib/di` |
51
51
  | `encryption/` | When querying encrypted entities (MUST use instead of raw `em.find`) | `@open-mercato/shared/lib/encryption/find` |
@@ -0,0 +1,172 @@
1
+ import { calculateBackoffDelayMs } from "../delivery/retry.js";
2
+ import { isTransientLockDbError } from "./pg-errors.js";
3
+ const ADVISORY_LOCK_UNAVAILABLE_BRAND = /* @__PURE__ */ Symbol.for("@open-mercato/shared:AdvisoryLockUnavailableError");
4
+ const ADVISORY_LOCK_UNAVAILABLE_MESSAGES = {
5
+ deadline: "[internal] Advisory lock not acquired before the wait deadline",
6
+ transient_db: "[internal] Advisory lock transaction failed with a transient database error",
7
+ commit_unknown: "[internal] Advisory lock transaction failed after its callback returned; the commit outcome is unknown"
8
+ };
9
+ class AdvisoryLockUnavailableError extends Error {
10
+ static [Symbol.hasInstance](value) {
11
+ return typeof value === "object" && value !== null && Reflect.get(value, ADVISORY_LOCK_UNAVAILABLE_BRAND) === true;
12
+ }
13
+ constructor(reason, key, cause) {
14
+ super(ADVISORY_LOCK_UNAVAILABLE_MESSAGES[reason], cause === void 0 ? void 0 : { cause });
15
+ Object.defineProperty(this, ADVISORY_LOCK_UNAVAILABLE_BRAND, { value: true, enumerable: false });
16
+ this.name = "AdvisoryLockUnavailableError";
17
+ this.reason = reason;
18
+ this.key = key;
19
+ }
20
+ }
21
+ const DEFAULT_WAIT_DEADLINE_MS = 15e3;
22
+ const BACKOFF_ATTEMPT_CAP = 5;
23
+ const BACKOFF_OPTIONS = { baseDelayMs: 50, maxJitterMs: 25 };
24
+ const KEY_NAMESPACE_PATTERN = /^[a-z][a-z0-9_]*$/;
25
+ const ADVISORY_LOCK_SQL = "select pg_try_advisory_xact_lock(hashtextextended(?, 0)) as locked";
26
+ const LOCK_FORK_OPTIONS = {
27
+ disableContextResolution: true,
28
+ clear: true,
29
+ useContext: false,
30
+ disableTransactions: false,
31
+ cloneEventManager: true
32
+ };
33
+ const GLOBAL_SLOTS_KEY = "__openMercatoAdvisoryLockSlots__";
34
+ const NOT_ACQUIRED = { acquired: false };
35
+ const releaseNothing = () => void 0;
36
+ function getSlotRegistry() {
37
+ const globals = globalThis;
38
+ const existing = globals[GLOBAL_SLOTS_KEY];
39
+ if (existing instanceof Map) return existing;
40
+ const created = /* @__PURE__ */ new Map();
41
+ globals[GLOBAL_SLOTS_KEY] = created;
42
+ return created;
43
+ }
44
+ function getNamespaceSlots(namespace) {
45
+ const registry = getSlotRegistry();
46
+ const existing = registry.get(namespace);
47
+ if (existing) return existing;
48
+ const created = { held: 0, waiters: [] };
49
+ registry.set(namespace, created);
50
+ return created;
51
+ }
52
+ function handOffSlots(slots) {
53
+ let index = 0;
54
+ while (index < slots.waiters.length) {
55
+ const waiter = slots.waiters[index];
56
+ if (slots.held >= waiter.limit) {
57
+ index += 1;
58
+ continue;
59
+ }
60
+ slots.waiters.splice(index, 1);
61
+ slots.held += 1;
62
+ waiter.grant();
63
+ }
64
+ }
65
+ function createSlotRelease(slots) {
66
+ let released = false;
67
+ return () => {
68
+ if (released) return;
69
+ released = true;
70
+ slots.held -= 1;
71
+ handOffSlots(slots);
72
+ };
73
+ }
74
+ function acquireSlot(namespace, limit, key, deadlineAt) {
75
+ const slots = getNamespaceSlots(namespace);
76
+ if (slots.held < limit) {
77
+ slots.held += 1;
78
+ return Promise.resolve(createSlotRelease(slots));
79
+ }
80
+ const remainingMs = deadlineAt - Date.now();
81
+ if (remainingMs <= 0) return Promise.reject(new AdvisoryLockUnavailableError("deadline", key));
82
+ return new Promise((resolve, reject) => {
83
+ const waiter = {
84
+ limit,
85
+ grant: () => {
86
+ clearTimeout(deadlineTimer);
87
+ resolve(createSlotRelease(slots));
88
+ }
89
+ };
90
+ const deadlineTimer = setTimeout(() => {
91
+ const position = slots.waiters.indexOf(waiter);
92
+ if (position >= 0) slots.waiters.splice(position, 1);
93
+ reject(new AdvisoryLockUnavailableError("deadline", key));
94
+ }, remainingMs);
95
+ slots.waiters.push(waiter);
96
+ });
97
+ }
98
+ function parseKeyNamespace(key) {
99
+ const separator = typeof key === "string" ? key.indexOf(":") : -1;
100
+ if (typeof key === "string" && separator > 0 && separator < key.length - 1) {
101
+ const namespace = key.slice(0, separator);
102
+ if (KEY_NAMESPACE_PATTERN.test(namespace)) return namespace;
103
+ }
104
+ throw new TypeError('[internal] Advisory lock key must be "<namespace>:<parts>" with a namespace matching ^[a-z][a-z0-9_]*$');
105
+ }
106
+ function resolveWaitDeadlineMs(value) {
107
+ if (value === void 0) return DEFAULT_WAIT_DEADLINE_MS;
108
+ if (Number.isFinite(value) && value >= 0) return value;
109
+ throw new TypeError("[internal] Advisory lock waitDeadlineMs must be a finite number of at least 0");
110
+ }
111
+ function resolveMaxConcurrentHolders(value) {
112
+ if (value === void 0) return null;
113
+ if (Number.isInteger(value) && value > 0) return value;
114
+ throw new TypeError("[internal] Advisory lock maxConcurrentHolders must be a positive integer");
115
+ }
116
+ function sleep(delayMs) {
117
+ return new Promise((resolve) => setTimeout(resolve, delayMs));
118
+ }
119
+ async function attemptLock(lockEm, key, fn) {
120
+ const callback = { thrown: false, returned: false, error: void 0 };
121
+ try {
122
+ return await lockEm.transactional(async (txEm) => {
123
+ const rows = await txEm.execute(ADVISORY_LOCK_SQL, [key]);
124
+ if (rows[0]?.locked !== true) return NOT_ACQUIRED;
125
+ try {
126
+ const value = await fn(txEm);
127
+ callback.returned = true;
128
+ return { acquired: true, value };
129
+ } catch (error) {
130
+ callback.thrown = true;
131
+ callback.error = error;
132
+ throw error;
133
+ }
134
+ });
135
+ } catch (error) {
136
+ if (callback.thrown) throw callback.error;
137
+ if (isTransientLockDbError(error)) {
138
+ throw new AdvisoryLockUnavailableError(callback.returned ? "commit_unknown" : "transient_db", key, error);
139
+ }
140
+ throw error;
141
+ }
142
+ }
143
+ async function withAdvisoryXactLock(em, key, fn, options = {}) {
144
+ const namespace = parseKeyNamespace(key);
145
+ const waitDeadlineMs = resolveWaitDeadlineMs(options.waitDeadlineMs);
146
+ const maxConcurrentHolders = resolveMaxConcurrentHolders(options.maxConcurrentHolders);
147
+ const deadlineAt = Date.now() + waitDeadlineMs;
148
+ const lockEm = em.fork(LOCK_FORK_OPTIONS);
149
+ for (let attempt = 1; ; attempt += 1) {
150
+ const releaseSlot = maxConcurrentHolders === null ? releaseNothing : await acquireSlot(namespace, maxConcurrentHolders, key, deadlineAt);
151
+ let outcome;
152
+ try {
153
+ outcome = await attemptLock(lockEm, key, fn);
154
+ } finally {
155
+ releaseSlot();
156
+ }
157
+ if (outcome.acquired) return outcome.value;
158
+ const remainingMs = deadlineAt - Date.now();
159
+ if (remainingMs <= 0) throw new AdvisoryLockUnavailableError("deadline", key);
160
+ await sleep(Math.min(calculateBackoffDelayMs(Math.min(attempt, BACKOFF_ATTEMPT_CAP), BACKOFF_OPTIONS), remainingMs));
161
+ if (options.onWait) {
162
+ const waitResult = await options.onWait();
163
+ if (waitResult.done) return waitResult.value;
164
+ }
165
+ if (Date.now() >= deadlineAt) throw new AdvisoryLockUnavailableError("deadline", key);
166
+ }
167
+ }
168
+ export {
169
+ AdvisoryLockUnavailableError,
170
+ withAdvisoryXactLock
171
+ };
172
+ //# sourceMappingURL=advisoryLock.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/lib/db/advisoryLock.ts"],
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { calculateBackoffDelayMs } from '../delivery/retry'\nimport { isTransientLockDbError } from './pg-errors'\n\n/** @internal */\nexport type AdvisoryLockWaitResult<T> = { done: true; value: T } | { done: false }\n\nexport type AdvisoryLockOptions<T> = {\n /** Total waiting budget from the call start. Default 15_000. */\n waitDeadlineMs?: number\n /** @internal Called after each failed attempt, with no connection held; `done: true` short-circuits. */\n onWait?: () => Promise<AdvisoryLockWaitResult<T>>\n /** Per process and key namespace: at most this many lock transactions at once (attempts included).\n * Waiting for a slot holds no connection and counts against `waitDeadlineMs`. Default: unlimited. */\n maxConcurrentHolders?: number\n}\n\nconst ADVISORY_LOCK_UNAVAILABLE_BRAND = Symbol.for('@open-mercato/shared:AdvisoryLockUnavailableError')\n\n/**\n * The helper's own work failed with an error `isTransientLockDbError` accepts (kept as `cause`), or\n * the wait ran out. `deadline`: the wait budget ran out (contention or no free holder slot), so `fn`\n * never ran. `transient_db`: the begin or the lock query failed, so `fn` never ran. `commit_unknown`:\n * `fn` returned and the flush or commit after it failed, so its writes may or may not be committed.\n * `reason` is additive-only; branch on it, never on the message.\n */\nexport type AdvisoryLockUnavailableReason = 'deadline' | 'transient_db' | 'commit_unknown'\n\nconst ADVISORY_LOCK_UNAVAILABLE_MESSAGES: Record<AdvisoryLockUnavailableReason, string> = {\n deadline: '[internal] Advisory lock not acquired before the wait deadline',\n transient_db: '[internal] Advisory lock transaction failed with a transient database error',\n commit_unknown: '[internal] Advisory lock transaction failed after its callback returned; the commit outcome is unknown',\n}\n\nexport class AdvisoryLockUnavailableError extends Error {\n static [Symbol.hasInstance](value: unknown): boolean {\n return typeof value === 'object' && value !== null && Reflect.get(value, ADVISORY_LOCK_UNAVAILABLE_BRAND) === true\n }\n\n readonly reason: AdvisoryLockUnavailableReason\n readonly key: string\n constructor(reason: AdvisoryLockUnavailableReason, key: string, cause?: unknown) {\n super(ADVISORY_LOCK_UNAVAILABLE_MESSAGES[reason], cause === undefined ? undefined : { cause })\n Object.defineProperty(this, ADVISORY_LOCK_UNAVAILABLE_BRAND, { value: true, enumerable: false })\n this.name = 'AdvisoryLockUnavailableError'\n this.reason = reason\n this.key = key\n }\n}\n\nconst DEFAULT_WAIT_DEADLINE_MS = 15_000\nconst BACKOFF_ATTEMPT_CAP = 5\nconst BACKOFF_OPTIONS = { baseDelayMs: 50, maxJitterMs: 25 }\nconst KEY_NAMESPACE_PATTERN = /^[a-z][a-z0-9_]*$/\nconst ADVISORY_LOCK_SQL = 'select pg_try_advisory_xact_lock(hashtextextended(?, 0)) as locked'\n\n/**\n * `disableContextResolution` keeps the fork off an outer transaction resolved from the\n * async context, `useContext: false` keeps the fork's own transaction from joining one\n * later, `disableTransactions: false` keeps a source EntityManager with transactions disabled\n * from turning the lock into a statement-scoped no-op, and the cloned event manager carries\n * the request's subscribers (tenant field encryption among them) into the lock transaction.\n */\nconst LOCK_FORK_OPTIONS = {\n disableContextResolution: true,\n clear: true,\n useContext: false,\n disableTransactions: false,\n cloneEventManager: true,\n}\n\n/**\n * Holder slots live on `globalThis` so duplicated module instances in one process (dev\n * HMR, standalone server chunks) count against one limit. The map is created once and\n * never replaced; each namespace entry is created on first use and kept.\n */\nconst GLOBAL_SLOTS_KEY = '__openMercatoAdvisoryLockSlots__'\n\ntype SlotWaiter = {\n limit: number\n grant: () => void\n}\n\ntype NamespaceSlots = {\n held: number\n waiters: SlotWaiter[]\n}\n\ntype SlotRelease = () => void\n\ntype AttemptOutcome<T> = { acquired: true; value: T } | { acquired: false }\n\nconst NOT_ACQUIRED: AttemptOutcome<never> = { acquired: false }\n\nconst releaseNothing: SlotRelease = () => undefined\n\nfunction getSlotRegistry(): Map<string, NamespaceSlots> {\n const globals = globalThis as Record<string, unknown>\n const existing = globals[GLOBAL_SLOTS_KEY]\n if (existing instanceof Map) return existing as Map<string, NamespaceSlots>\n const created = new Map<string, NamespaceSlots>()\n globals[GLOBAL_SLOTS_KEY] = created\n return created\n}\n\nfunction getNamespaceSlots(namespace: string): NamespaceSlots {\n const registry = getSlotRegistry()\n const existing = registry.get(namespace)\n if (existing) return existing\n const created: NamespaceSlots = { held: 0, waiters: [] }\n registry.set(namespace, created)\n return created\n}\n\nfunction handOffSlots(slots: NamespaceSlots): void {\n let index = 0\n while (index < slots.waiters.length) {\n const waiter = slots.waiters[index]\n if (slots.held >= waiter.limit) {\n index += 1\n continue\n }\n slots.waiters.splice(index, 1)\n slots.held += 1\n waiter.grant()\n }\n}\n\nfunction createSlotRelease(slots: NamespaceSlots): SlotRelease {\n let released = false\n return () => {\n if (released) return\n released = true\n slots.held -= 1\n handOffSlots(slots)\n }\n}\n\nfunction acquireSlot(namespace: string, limit: number, key: string, deadlineAt: number): Promise<SlotRelease> {\n const slots = getNamespaceSlots(namespace)\n if (slots.held < limit) {\n slots.held += 1\n return Promise.resolve(createSlotRelease(slots))\n }\n const remainingMs = deadlineAt - Date.now()\n if (remainingMs <= 0) return Promise.reject(new AdvisoryLockUnavailableError('deadline', key))\n return new Promise<SlotRelease>((resolve, reject) => {\n const waiter: SlotWaiter = {\n limit,\n grant: () => {\n clearTimeout(deadlineTimer)\n resolve(createSlotRelease(slots))\n },\n }\n const deadlineTimer = setTimeout(() => {\n const position = slots.waiters.indexOf(waiter)\n if (position >= 0) slots.waiters.splice(position, 1)\n reject(new AdvisoryLockUnavailableError('deadline', key))\n }, remainingMs)\n slots.waiters.push(waiter)\n })\n}\n\nfunction parseKeyNamespace(key: unknown): string {\n const separator = typeof key === 'string' ? key.indexOf(':') : -1\n if (typeof key === 'string' && separator > 0 && separator < key.length - 1) {\n const namespace = key.slice(0, separator)\n if (KEY_NAMESPACE_PATTERN.test(namespace)) return namespace\n }\n throw new TypeError('[internal] Advisory lock key must be \"<namespace>:<parts>\" with a namespace matching ^[a-z][a-z0-9_]*$')\n}\n\nfunction resolveWaitDeadlineMs(value: number | undefined): number {\n if (value === undefined) return DEFAULT_WAIT_DEADLINE_MS\n if (Number.isFinite(value) && value >= 0) return value\n throw new TypeError('[internal] Advisory lock waitDeadlineMs must be a finite number of at least 0')\n}\n\nfunction resolveMaxConcurrentHolders(value: number | undefined): number | null {\n if (value === undefined) return null\n if (Number.isInteger(value) && value > 0) return value\n throw new TypeError('[internal] Advisory lock maxConcurrentHolders must be a positive integer')\n}\n\nfunction sleep(delayMs: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, delayMs))\n}\n\nasync function attemptLock<T>(\n lockEm: EntityManager,\n key: string,\n fn: (txEm: EntityManager) => Promise<T>,\n): Promise<AttemptOutcome<T>> {\n const callback: { thrown: boolean; returned: boolean; error: unknown } = { thrown: false, returned: false, error: undefined }\n try {\n return await lockEm.transactional(async (txEm): Promise<AttemptOutcome<T>> => {\n const rows = await txEm.execute<Array<{ locked: boolean }>>(ADVISORY_LOCK_SQL, [key])\n if (rows[0]?.locked !== true) return NOT_ACQUIRED\n try {\n const value = await fn(txEm)\n callback.returned = true\n return { acquired: true, value }\n } catch (error) {\n callback.thrown = true\n callback.error = error\n throw error\n }\n })\n } catch (error) {\n if (callback.thrown) throw callback.error\n if (isTransientLockDbError(error)) {\n throw new AdvisoryLockUnavailableError(callback.returned ? 'commit_unknown' : 'transient_db', key, error)\n }\n throw error\n }\n}\n\n/**\n * Runs `fn` in one transaction that holds `pg_try_advisory_xact_lock(hashtextextended(key, 0))`.\n * - `key` is `<namespace>:<parts>` with namespace `^[a-z][a-z0-9_]*$`; anything else throws `TypeError`.\n * - `waitDeadlineMs` must be a finite number \u2265 0 and `maxConcurrentHolders` a positive integer;\n * anything else throws `TypeError` before any connection is taken.\n * - Pass the request (container) EntityManager. The helper forks it with\n * `{ disableContextResolution: true, clear: true, useContext: false, disableTransactions: false, cloneEventManager: true }`,\n * so the lock transaction never nests in a caller's transaction and commits on its own.\n * - `fn` MUST do all DB I/O on `txEm`, MUST flush its own writes, MUST be bounded (\u2264 one external\n * call), MUST NOT call `transactional` again (it only opens a savepoint in the lock transaction) and\n * MUST NOT fork or use `getConnection().execute` (another pooled connection, outside the lock).\n * - `txEm` carries the request EntityManager's subscribers (cloned event manager).\n * - A failed attempt ends its empty transaction, so waiters hold no connection between attempts.\n * They back off 50 ms doubling up to 800 ms (plus up to 24 ms jitter), never past\n * `waitDeadlineMs` measured from the call start, then retry.\n * - With `maxConcurrentHolders`, each attempt first takes a per-process slot for the key\n * namespace and gives it back when the attempt fails or the lock transaction settles.\n * - Errors from the helper's own begin, lock query and commit that `isTransientLockDbError` accepts,\n * and the deadline, throw `AdvisoryLockUnavailableError` (its `reason` says whether `fn` ran); any\n * other error from them, and every error thrown by `fn`, propagates unchanged (a throw from `fn`\n * rolls back).\n */\nexport async function withAdvisoryXactLock<T>(\n em: EntityManager,\n key: string,\n fn: (txEm: EntityManager) => Promise<T>,\n options: AdvisoryLockOptions<T> = {},\n): Promise<T> {\n const namespace = parseKeyNamespace(key)\n const waitDeadlineMs = resolveWaitDeadlineMs(options.waitDeadlineMs)\n const maxConcurrentHolders = resolveMaxConcurrentHolders(options.maxConcurrentHolders)\n const deadlineAt = Date.now() + waitDeadlineMs\n const lockEm = em.fork(LOCK_FORK_OPTIONS)\n for (let attempt = 1; ; attempt += 1) {\n const releaseSlot = maxConcurrentHolders === null\n ? releaseNothing\n : await acquireSlot(namespace, maxConcurrentHolders, key, deadlineAt)\n let outcome: AttemptOutcome<T>\n try {\n outcome = await attemptLock(lockEm, key, fn)\n } finally {\n releaseSlot()\n }\n if (outcome.acquired) return outcome.value\n const remainingMs = deadlineAt - Date.now()\n if (remainingMs <= 0) throw new AdvisoryLockUnavailableError('deadline', key)\n await sleep(Math.min(calculateBackoffDelayMs(Math.min(attempt, BACKOFF_ATTEMPT_CAP), BACKOFF_OPTIONS), remainingMs))\n if (options.onWait) {\n const waitResult = await options.onWait()\n if (waitResult.done) return waitResult.value\n }\n if (Date.now() >= deadlineAt) throw new AdvisoryLockUnavailableError('deadline', key)\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,+BAA+B;AACxC,SAAS,8BAA8B;AAevC,MAAM,kCAAkC,uBAAO,IAAI,mDAAmD;AAWtG,MAAM,qCAAoF;AAAA,EACxF,UAAU;AAAA,EACV,cAAc;AAAA,EACd,gBAAgB;AAClB;AAEO,MAAM,qCAAqC,MAAM;AAAA,EACtD,QAAQ,OAAO,WAAW,EAAE,OAAyB;AACnD,WAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,QAAQ,IAAI,OAAO,+BAA+B,MAAM;AAAA,EAChH;AAAA,EAIA,YAAY,QAAuC,KAAa,OAAiB;AAC/E,UAAM,mCAAmC,MAAM,GAAG,UAAU,SAAY,SAAY,EAAE,MAAM,CAAC;AAC7F,WAAO,eAAe,MAAM,iCAAiC,EAAE,OAAO,MAAM,YAAY,MAAM,CAAC;AAC/F,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,MAAM;AAAA,EACb;AACF;AAEA,MAAM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IAC7C,UAAE;AACA,kBAAY;AAAA,IACd;AACA,QAAI,QAAQ,SAAU,QAAO,QAAQ;AACrC,UAAM,cAAc,aAAa,KAAK,IAAI;AAC1C,QAAI,eAAe,EAAG,OAAM,IAAI,6BAA6B,YAAY,GAAG;AAC5E,UAAM,MAAM,KAAK,IAAI,wBAAwB,KAAK,IAAI,SAAS,mBAAmB,GAAG,eAAe,GAAG,WAAW,CAAC;AACnH,QAAI,QAAQ,QAAQ;AAClB,YAAM,aAAa,MAAM,QAAQ,OAAO;AACxC,UAAI,WAAW,KAAM,QAAO,WAAW;AAAA,IACzC;AACA,QAAI,KAAK,IAAI,KAAK,WAAY,OAAM,IAAI,6BAA6B,YAAY,GAAG;AAAA,EACtF;AACF;",
6
+ "names": []
7
+ }
@@ -89,10 +89,24 @@ function isTransientDbError(err) {
89
89
  }
90
90
  return false;
91
91
  }
92
+ const TRANSIENT_LOCK_SQLSTATES = /* @__PURE__ */ new Set(["55P03", "57014", "25P03"]);
93
+ const TRANSIENT_LOCK_MESSAGE_PATTERNS = [
94
+ /timeout exceeded when trying to connect/i,
95
+ /client has encountered a connection error and is not queryable/i
96
+ ];
97
+ function isTransientLockDbError(err) {
98
+ return pgErrorCandidates(err).some((candidate) => {
99
+ if (isTransientDbError(candidate)) return true;
100
+ if (typeof candidate.code === "string" && TRANSIENT_LOCK_SQLSTATES.has(candidate.code)) return true;
101
+ const message = candidate.message;
102
+ return typeof message === "string" && TRANSIENT_LOCK_MESSAGE_PATTERNS.some((pattern) => pattern.test(message));
103
+ });
104
+ }
92
105
  export {
93
106
  getForeignKeyViolationConstraint,
94
107
  isForeignKeyViolation,
95
108
  isTransientDbError,
109
+ isTransientLockDbError,
96
110
  isUniqueViolation,
97
111
  readPgSqlState
98
112
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/db/pg-errors.ts"],
4
- "sourcesContent": ["/**\n * Detect a Postgres unique-constraint violation (SQLSTATE 23505) regardless of\n * the ORM/driver layer that surfaces it. Shared across modules so duplicate-insert\n * handling stays consistent platform-wide.\n */\nexport function isUniqueViolation(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false\n const code = (err as { code?: string }).code\n if (code === '23505') return true // Postgres unique_violation\n const message = (err as { message?: string }).message\n return typeof message === 'string' && /duplicate key value|unique constraint/i.test(message)\n}\n\nconst FOREIGN_KEY_VIOLATION_MESSAGE = /violates foreign key constraint(?: \"([^\"]+)\")?/i\n\nconst MAX_ERROR_CHAIN_DEPTH = 4\n\n/**\n * MikroORM wraps driver errors and copies the pg fields onto the wrapper, but\n * the original error may also sit behind `cause` (Node) or `previous`\n * (MikroORM), possibly re-wrapped by a transaction helper. Walk that chain,\n * breadth-first with a small depth cap, so a check works on any layer.\n */\nfunction pgErrorCandidates(err: unknown): Array<Record<string, unknown>> {\n const found: Array<Record<string, unknown>> = []\n const seen = new Set<unknown>()\n let layer: unknown[] = [err]\n for (let depth = 0; depth < MAX_ERROR_CHAIN_DEPTH && layer.length > 0; depth += 1) {\n const next: unknown[] = []\n for (const candidate of layer) {\n if (!candidate || typeof candidate !== 'object' || seen.has(candidate)) continue\n seen.add(candidate)\n const record = candidate as Record<string, unknown>\n found.push(record)\n next.push(record.cause, record.previous)\n }\n layer = next\n }\n return found\n}\n\n/**\n * Detect a Postgres foreign-key violation (SQLSTATE 23503): the row is still\n * referenced by a dependent table, or the payload references a parent that\n * does not exist. Looks through MikroORM's driver-error wrapping.\n */\nexport function isForeignKeyViolation(err: unknown): boolean {\n return pgErrorCandidates(err).some((candidate) => {\n if (candidate.code === '23503') return true // Postgres foreign_key_violation\n return typeof candidate.message === 'string' && FOREIGN_KEY_VIOLATION_MESSAGE.test(candidate.message)\n })\n}\n\n/**\n * Name of the constraint behind a foreign-key violation, read from the pg\n * `constraint` field on any layer of the wrapper chain, or parsed out of the\n * quoted constraint in the driver message when the field is missing.\n */\nexport function getForeignKeyViolationConstraint(err: unknown): string | null {\n for (const candidate of pgErrorCandidates(err)) {\n if (typeof candidate.constraint === 'string' && candidate.constraint.length > 0) return candidate.constraint\n }\n for (const candidate of pgErrorCandidates(err)) {\n if (typeof candidate.message !== 'string') continue\n const match = FOREIGN_KEY_VIOLATION_MESSAGE.exec(candidate.message)\n if (match?.[1]) return match[1]\n }\n return null\n}\n\n/**\n * A Postgres SQLSTATE is always exactly 5 characters from `[0-9A-Z]`, and every\n * class in the standard SQLSTATE table carries at least one digit. Node system\n * errors (`ECONNREFUSED`), Node internal errors (`ERR_INVALID_ARG_TYPE`), and the\n * five-letter Node errno codes (`EPIPE`, `EPERM`, `EBUSY`) would otherwise be\n * misread as a SQLSTATE, since they also populate a string `code` field; the\n * digit requirement rules those out without excluding any real SQLSTATE.\n */\nconst SQLSTATE_PATTERN = /^(?=.*[0-9])[0-9A-Z]{5}$/\n\n/**\n * The Postgres SQLSTATE behind an error, read from the pg `code` field on any\n * layer of the driver-error wrapper chain (see `pgErrorCandidates`). Returns\n * `null` when no layer carries a `code` matching the SQLSTATE shape, which\n * also covers non-Postgres errors whose `code` is a Node error code.\n */\nexport function readPgSqlState(err: unknown): string | null {\n for (const candidate of pgErrorCandidates(err)) {\n if (typeof candidate.code === 'string' && SQLSTATE_PATTERN.test(candidate.code)) return candidate.code\n }\n return null\n}\n\n/**\n * Postgres SQLSTATEs for transient connection / availability failures \u2014 the\n * database (or its connection pool) is temporarily unreachable and the request\n * can succeed on retry. Deliberately scoped to connection/availability codes;\n * query-level conflicts (deadlock 40P01, serialization 40001, lock_not_available\n * 55P03) are NOT included because they do not mean \"service unavailable\".\n */\nconst TRANSIENT_CONNECTION_SQLSTATES = new Set([\n '53300', // too_many_connections\n '53400', // configuration_limit_exceeded\n '57P01', // admin_shutdown\n '57P02', // crash_shutdown\n '57P03', // cannot_connect_now (db starting up)\n '08000', // connection_exception\n '08001', // sqlclient_unable_to_establish_sqlconnection\n '08003', // connection_does_not_exist\n '08006', // connection_failure\n])\n\n/**\n * Postgres-driver / connection-pool messages that describe a transient DB\n * connection failure when the SQLSTATE is dropped by the ORM wrapper. These are\n * intentionally DB-specific phrases only. Bare socket codes (ECONNREFUSED,\n * ETIMEDOUT, \u2026) are deliberately NOT matched: they can originate from any\n * outbound socket (HTTP, cache, queue), so keying off them would falsely\n * attribute unrelated failures to the database.\n */\nconst TRANSIENT_DB_MESSAGE_PATTERNS = [\n /too many clients already/i,\n /unable to acquire a connection/i,\n /timeout acquiring a connection/i,\n /connection terminated/i,\n /the database system is (starting up|shutting down|in recovery)/i,\n]\n\n/**\n * Detect a transient Postgres connection / availability failure (pool exhaustion,\n * `max_connections` reached, DB restarting) via its SQLSTATE or a DB-specific\n * driver message. Gates retryable 503 responses so callers do not report a\n * temporary infrastructure blip as an auth failure (401) or an unexpected server\n * error (500). Scoped to unambiguous DB signals so generic socket errors from\n * non-DB calls are never misclassified.\n */\nexport function isTransientDbError(err: unknown): boolean {\n if (!err || typeof err !== 'object') {\n return false\n }\n const code = (err as { code?: string }).code\n if (typeof code === 'string' && TRANSIENT_CONNECTION_SQLSTATES.has(code)) {\n return true\n }\n const message = (err as { message?: string }).message\n if (typeof message === 'string' && TRANSIENT_DB_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) {\n return true\n }\n return false\n}\n"],
5
- "mappings": "AAKO,SAAS,kBAAkB,KAAuB;AACvD,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,OAAQ,IAA0B;AACxC,MAAI,SAAS,QAAS,QAAO;AAC7B,QAAM,UAAW,IAA6B;AAC9C,SAAO,OAAO,YAAY,YAAY,yCAAyC,KAAK,OAAO;AAC7F;AAEA,MAAM,gCAAgC;AAEtC,MAAM,wBAAwB;AAQ9B,SAAS,kBAAkB,KAA8C;AACvE,QAAM,QAAwC,CAAC;AAC/C,QAAM,OAAO,oBAAI,IAAa;AAC9B,MAAI,QAAmB,CAAC,GAAG;AAC3B,WAAS,QAAQ,GAAG,QAAQ,yBAAyB,MAAM,SAAS,GAAG,SAAS,GAAG;A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gCAAgC;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAUO,SAAS,mBAAmB,KAAuB;AACxD,MAAI,CAAC,OAAO,OAAO,QAAQ,UAAU;AACnC,WAAO;AAAA,EACT;AACA,QAAM,OAAQ,IAA0B;AACxC,MAAI,OAAO,SAAS,YAAY,+BAA+B,IAAI,IAAI,GAAG;AACxE,WAAO;AAAA,EACT;AACA,QAAM,UAAW,IAA6B;AAC9C,MAAI,OAAO,YAAY,YAAY,8BAA8B,KAAK,CAAC,YAAY,QAAQ,KAAK,OAAO,CAAC,GAAG;AACzG,WAAO;AAAA,EACT;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["/**\n * Detect a Postgres unique-constraint violation (SQLSTATE 23505) regardless of\n * the ORM/driver layer that surfaces it. Shared across modules so duplicate-insert\n * handling stays consistent platform-wide.\n */\nexport function isUniqueViolation(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false\n const code = (err as { code?: string }).code\n if (code === '23505') return true // Postgres unique_violation\n const message = (err as { message?: string }).message\n return typeof message === 'string' && /duplicate key value|unique constraint/i.test(message)\n}\n\nconst FOREIGN_KEY_VIOLATION_MESSAGE = /violates foreign key constraint(?: \"([^\"]+)\")?/i\n\nconst MAX_ERROR_CHAIN_DEPTH = 4\n\n/**\n * MikroORM wraps driver errors and copies the pg fields onto the wrapper, but\n * the original error may also sit behind `cause` (Node) or `previous`\n * (MikroORM), possibly re-wrapped by a transaction helper. Walk that chain,\n * breadth-first with a small depth cap, so a check works on any layer.\n */\nfunction pgErrorCandidates(err: unknown): Array<Record<string, unknown>> {\n const found: Array<Record<string, unknown>> = []\n const seen = new Set<unknown>()\n let layer: unknown[] = [err]\n for (let depth = 0; depth < MAX_ERROR_CHAIN_DEPTH && layer.length > 0; depth += 1) {\n const next: unknown[] = []\n for (const candidate of layer) {\n if (!candidate || typeof candidate !== 'object' || seen.has(candidate)) continue\n seen.add(candidate)\n const record = candidate as Record<string, unknown>\n found.push(record)\n next.push(record.cause, record.previous)\n }\n layer = next\n }\n return found\n}\n\n/**\n * Detect a Postgres foreign-key violation (SQLSTATE 23503): the row is still\n * referenced by a dependent table, or the payload references a parent that\n * does not exist. Looks through MikroORM's driver-error wrapping.\n */\nexport function isForeignKeyViolation(err: unknown): boolean {\n return pgErrorCandidates(err).some((candidate) => {\n if (candidate.code === '23503') return true // Postgres foreign_key_violation\n return typeof candidate.message === 'string' && FOREIGN_KEY_VIOLATION_MESSAGE.test(candidate.message)\n })\n}\n\n/**\n * Name of the constraint behind a foreign-key violation, read from the pg\n * `constraint` field on any layer of the wrapper chain, or parsed out of the\n * quoted constraint in the driver message when the field is missing.\n */\nexport function getForeignKeyViolationConstraint(err: unknown): string | null {\n for (const candidate of pgErrorCandidates(err)) {\n if (typeof candidate.constraint === 'string' && candidate.constraint.length > 0) return candidate.constraint\n }\n for (const candidate of pgErrorCandidates(err)) {\n if (typeof candidate.message !== 'string') continue\n const match = FOREIGN_KEY_VIOLATION_MESSAGE.exec(candidate.message)\n if (match?.[1]) return match[1]\n }\n return null\n}\n\n/**\n * A Postgres SQLSTATE is always exactly 5 characters from `[0-9A-Z]`, and every\n * class in the standard SQLSTATE table carries at least one digit. Node system\n * errors (`ECONNREFUSED`), Node internal errors (`ERR_INVALID_ARG_TYPE`), and the\n * five-letter Node errno codes (`EPIPE`, `EPERM`, `EBUSY`) would otherwise be\n * misread as a SQLSTATE, since they also populate a string `code` field; the\n * digit requirement rules those out without excluding any real SQLSTATE.\n */\nconst SQLSTATE_PATTERN = /^(?=.*[0-9])[0-9A-Z]{5}$/\n\n/**\n * The Postgres SQLSTATE behind an error, read from the pg `code` field on any\n * layer of the driver-error wrapper chain (see `pgErrorCandidates`). Returns\n * `null` when no layer carries a `code` matching the SQLSTATE shape, which\n * also covers non-Postgres errors whose `code` is a Node error code.\n */\nexport function readPgSqlState(err: unknown): string | null {\n for (const candidate of pgErrorCandidates(err)) {\n if (typeof candidate.code === 'string' && SQLSTATE_PATTERN.test(candidate.code)) return candidate.code\n }\n return null\n}\n\n/**\n * Postgres SQLSTATEs for transient connection / availability failures \u2014 the\n * database (or its connection pool) is temporarily unreachable and the request\n * can succeed on retry. Deliberately scoped to connection/availability codes;\n * query-level conflicts (deadlock 40P01, serialization 40001, lock_not_available\n * 55P03) are NOT included because they do not mean \"service unavailable\".\n */\nconst TRANSIENT_CONNECTION_SQLSTATES = new Set([\n '53300', // too_many_connections\n '53400', // configuration_limit_exceeded\n '57P01', // admin_shutdown\n '57P02', // crash_shutdown\n '57P03', // cannot_connect_now (db starting up)\n '08000', // connection_exception\n '08001', // sqlclient_unable_to_establish_sqlconnection\n '08003', // connection_does_not_exist\n '08006', // connection_failure\n])\n\n/**\n * Postgres-driver / connection-pool messages that describe a transient DB\n * connection failure when the SQLSTATE is dropped by the ORM wrapper. These are\n * intentionally DB-specific phrases only. Bare socket codes (ECONNREFUSED,\n * ETIMEDOUT, \u2026) are deliberately NOT matched: they can originate from any\n * outbound socket (HTTP, cache, queue), so keying off them would falsely\n * attribute unrelated failures to the database.\n */\nconst TRANSIENT_DB_MESSAGE_PATTERNS = [\n /too many clients already/i,\n /unable to acquire a connection/i,\n /timeout acquiring a connection/i,\n /connection terminated/i,\n /the database system is (starting up|shutting down|in recovery)/i,\n]\n\n/**\n * Detect a transient Postgres connection / availability failure (pool exhaustion,\n * `max_connections` reached, DB restarting) via its SQLSTATE or a DB-specific\n * driver message. Gates retryable 503 responses so callers do not report a\n * temporary infrastructure blip as an auth failure (401) or an unexpected server\n * error (500). Scoped to unambiguous DB signals so generic socket errors from\n * non-DB calls are never misclassified.\n */\nexport function isTransientDbError(err: unknown): boolean {\n if (!err || typeof err !== 'object') {\n return false\n }\n const code = (err as { code?: string }).code\n if (typeof code === 'string' && TRANSIENT_CONNECTION_SQLSTATES.has(code)) {\n return true\n }\n const message = (err as { message?: string }).message\n if (typeof message === 'string' && TRANSIENT_DB_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) {\n return true\n }\n return false\n}\n\n/**\n * SQLSTATEs that end a lock transaction early but say nothing about the data it\n * would have written, so the work can be retried: lock_not_available (55P03,\n * raised by `DB_LOCK_TIMEOUT_MS`), query_canceled (57014, raised by the opt-in\n * `DB_STATEMENT_TIMEOUT_MS`) and idle_in_transaction_session_timeout (25P03).\n */\nconst TRANSIENT_LOCK_SQLSTATES = new Set(['55P03', '57014', '25P03'])\n\n/**\n * Driver messages for a connection that never arrived or was lost mid-transaction:\n * the pg-pool acquire timeout (`connectionTimeoutMillis`) and node-postgres's\n * error for a client whose connection already failed.\n */\nconst TRANSIENT_LOCK_MESSAGE_PATTERNS = [\n /timeout exceeded when trying to connect/i,\n /client has encountered a connection error and is not queryable/i,\n]\n\n/**\n * @internal Detect a transient failure of a short lock transaction: everything\n * `isTransientDbError` matches, plus lock, statement and idle-in-transaction\n * timeouts, the pg-pool acquire timeout and node-postgres's \"not queryable\"\n * error. Checks every layer of the driver-error wrapper chain (`cause` /\n * `previous`, see `pgErrorCandidates`). `isTransientDbError` keeps its narrower\n * scope because its callers answer 503 \"service unavailable\".\n */\nexport function isTransientLockDbError(err: unknown): boolean {\n return pgErrorCandidates(err).some((candidate) => {\n if (isTransientDbError(candidate)) return true\n if (typeof candidate.code === 'string' && TRANSIENT_LOCK_SQLSTATES.has(candidate.code)) return true\n const message = candidate.message\n return typeof message === 'string' && TRANSIENT_LOCK_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))\n })\n}\n"],
5
+ "mappings": "AAKO,SAAS,kBAAkB,KAAuB;AACvD,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,OAAQ,IAA0B;AACxC,MAAI,SAAS,QAAS,QAAO;AAC7B,QAAM,UAAW,IAA6B;AAC9C,SAAO,OAAO,YAAY,YAAY,yCAAyC,KAAK,OAAO;AAC7F;AAEA,MAAM,gCAAgC;AAEtC,MAAM,wBAAwB;AAQ9B,SAAS,kBAAkB,KAA8C;AACvE,QAAM,QAAwC,CAAC;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AA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AACF,CAAC;AAUD,MAAM,gCAAgC;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAUO,SAAS,mBAAmB,KAAuB;AACxD,MAAI,CAAC,OAAO,OAAO,QAAQ,UAAU;AACnC,WAAO;AAAA,EACT;AACA,QAAM,OAAQ,IAA0B;AACxC,MAAI,OAAO,SAAS,YAAY,+BAA+B,IAAI,IAAI,GAAG;AACxE,WAAO;AAAA,EACT;AACA,QAAM,UAAW,IAA6B;AAC9C,MAAI,OAAO,YAAY,YAAY,8BAA8B,KAAK,CAAC,YAAY,QAAQ,KAAK,OAAO,CAAC,GAAG;AACzG,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAQA,MAAM,2BAA2B,oBAAI,IAAI,CAAC,SAAS,SAAS,OAAO,CAAC;AAOpE,MAAM,kCAAkC;AAAA,EACtC;AAAA,EACA;AACF;AAUO,SAAS,uBAAuB,KAAuB;AAC5D,SAAO,kBAAkB,GAAG,EAAE,KAAK,CAAC,cAAc;AAChD,QAAI,mBAAmB,SAAS,EAAG,QAAO;AAC1C,QAAI,OAAO,UAAU,SAAS,YAAY,yBAAyB,IAAI,UAAU,IAAI,EAAG,QAAO;AAC/F,UAAM,UAAU,UAAU;AAC1B,WAAO,OAAO,YAAY,YAAY,gCAAgC,KAAK,CAAC,YAAY,QAAQ,KAAK,OAAO,CAAC;AAAA,EAC/G,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,4 @@
1
- const APP_VERSION = "0.9.1-develop.7573.1.d0ccc51d5b";
1
+ const APP_VERSION = "0.9.1-develop.7574.1.837288eec1";
2
2
  const appVersion = APP_VERSION;
3
3
  export {
4
4
  APP_VERSION,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/version.ts"],
4
- "sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.9.1-develop.7573.1.d0ccc51d5b';\nexport const appVersion = APP_VERSION;\n"],
4
+ "sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.9.1-develop.7574.1.837288eec1';\nexport const appVersion = APP_VERSION;\n"],
5
5
  "mappings": "AACO,MAAM,cAAc;AACpB,MAAM,aAAa;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/integrations/types.ts"],
4
- "sourcesContent": ["export type IntegrationScope = {\n organizationId: string\n tenantId: string\n /**\n * Optional per-user secret scoping. When set, credential lookups and writes\n * are scoped to a single user \u2014 used by per-user channels (Gmail, IMAP)\n * so two users on the same tenant don't share one row.\n *\n * When `undefined`/`null`, behaviour is unchanged \u2014 tenant-wide credentials\n * (e.g. shared Stripe/Akeneo API keys) keep working exactly as before.\n *\n * Stored on `IntegrationCredentials.user_id` (added 2026-05-26 by the email\n * integration spec). Backed by the partial unique index\n * `integration_credentials_user_lookup_idx` across integration, organization,\n * tenant, and user where `user_id IS NOT NULL AND deleted_at IS NULL`.\n */\n userId?: string | null\n}\n\nexport type IntegrationCategory =\n | 'payment'\n | 'shipping'\n | 'data_sync'\n | 'communication'\n | 'webhook'\n | 'storage'\n | 'other'\n\nexport type IntegrationHubId =\n | 'payment_gateways'\n | 'shipping_carriers'\n | 'data_sync'\n | 'communication_channels'\n | 'webhook_endpoints'\n | 'storage_hubs'\n | string\n\nexport type CredentialFieldType =\n | 'text'\n | 'secret'\n | 'select'\n | 'boolean'\n | 'url'\n | 'oauth'\n | 'ssh_keypair'\n\nexport interface CredentialFieldOption {\n value: string\n label: string\n}\n\nexport interface CredentialFieldVisibleWhen {\n field: string\n equals: string | number | boolean\n}\n\nexport interface IntegrationCredentialWebhookHelp {\n kind: 'webhook_setup'\n title: string\n summary: string\n endpointPath: string\n dashboardPathLabel: string\n steps: string[]\n events?: string[]\n localDevelopment?: {\n tunnelCommand: string\n publicUrlExample: string\n note?: string\n }\n}\n\nexport interface IntegrationCredentialFieldBase {\n key: string\n label: string\n required?: boolean\n placeholder?: string\n helpText?: string\n helpDetails?: IntegrationCredentialWebhookHelp\n visibleWhen?: CredentialFieldVisibleWhen\n}\n\nexport interface IntegrationCredentialFieldText extends IntegrationCredentialFieldBase {\n type: Extract<CredentialFieldType, 'text' | 'secret' | 'url'>\n}\n\nexport interface IntegrationCredentialFieldBoolean extends IntegrationCredentialFieldBase {\n type: Extract<CredentialFieldType, 'boolean'>\n}\n\nexport interface IntegrationCredentialFieldSelect extends IntegrationCredentialFieldBase {\n type: Extract<CredentialFieldType, 'select'>\n options: CredentialFieldOption[]\n}\n\nexport interface IntegrationCredentialFieldOauth extends IntegrationCredentialFieldBase {\n type: Extract<CredentialFieldType, 'oauth'>\n authUrl?: string\n tokenUrl?: string\n scopes?: string[]\n clientIdField?: string\n clientSecretField?: string\n}\n\nexport interface IntegrationCredentialFieldSshKeypair extends IntegrationCredentialFieldBase {\n type: Extract<CredentialFieldType, 'ssh_keypair'>\n algorithm?: 'ed25519' | 'rsa'\n rsaBits?: 2048 | 3072 | 4096\n}\n\nexport type IntegrationCredentialField =\n | IntegrationCredentialFieldText\n | IntegrationCredentialFieldBoolean\n | IntegrationCredentialFieldSelect\n | IntegrationCredentialFieldOauth\n | IntegrationCredentialFieldSshKeypair\n\nexport interface IntegrationCredentialsSchema {\n fields: IntegrationCredentialField[]\n}\n\nexport interface IntegrationHealthCheckConfig {\n service: string\n}\n\nexport interface ApiVersionDefinition {\n id: string\n label: string\n status: 'stable' | 'deprecated' | 'experimental'\n default?: boolean\n changelog?: string\n deprecatedAt?: string\n sunsetAt?: string\n migrationGuide?: string\n}\n\nexport interface IntegrationBundle {\n id: string\n title: string\n description: string\n icon?: string\n package?: string\n version?: string\n author?: string\n credentials: IntegrationCredentialsSchema\n healthCheck?: IntegrationHealthCheckConfig\n}\n\nexport interface IntegrationDetailPageConfig {\n /**\n * UMES widget spot rendered on the integration detail page.\n * Widgets registered here can render inline blocks, grouped panels,\n * or additional tabs via `placement.kind`.\n */\n widgetSpotId?: string\n /**\n * Built-in tabs to hide for this integration detail page.\n * Provider modules can replace these with injected tabs using the same spot.\n */\n hiddenTabs?: IntegrationDetailBuiltInTab[]\n}\n\nexport type IntegrationDetailBuiltInTab =\n | 'credentials'\n | 'version'\n | 'health'\n | 'logs'\n | 'data-sync-schedule'\n\nexport interface IntegrationDefaultStateConfig {\n isEnabled?: boolean\n}\n\nexport interface IntegrationDefinition {\n id: string\n title: string\n icon?: string\n buildExternalUrl?: (externalId: string) => string\n bundleId?: string\n apiVersions?: ApiVersionDefinition[]\n description?: string\n category?: IntegrationCategory | string\n hub?: IntegrationHubId\n providerKey?: string\n docsUrl?: string\n package?: string\n version?: string\n author?: string\n company?: string\n license?: string\n tags?: string[]\n detailPage?: IntegrationDetailPageConfig\n defaultState?: IntegrationDefaultStateConfig\n credentials?: IntegrationCredentialsSchema\n healthCheck?: IntegrationHealthCheckConfig\n}\n\nexport interface ExternalIdEnrichment {\n _integrations: Record<string, ExternalIdMapping>\n}\n\nexport interface ExternalIdMapping {\n externalId: string\n externalUrl?: string\n lastSyncedAt?: string\n syncStatus: 'synced' | 'pending' | 'error' | 'not_synced'\n}\n\ntype IntegrationRegistryState = {\n integrations: Map<string, IntegrationDefinition>\n bundles: Map<string, IntegrationBundle>\n}\n\nconst GLOBAL_INTEGRATION_REGISTRY_KEY = '__openMercatoIntegrationRegistry__' as const\n\ntype GlobalIntegrationRegistry = typeof globalThis & {\n [GLOBAL_INTEGRATION_REGISTRY_KEY]?: IntegrationRegistryState\n}\n\nfunction getIntegrationRegistryState(): IntegrationRegistryState {\n const globalRegistry = globalThis as GlobalIntegrationRegistry\n if (!globalRegistry[GLOBAL_INTEGRATION_REGISTRY_KEY]) {\n globalRegistry[GLOBAL_INTEGRATION_REGISTRY_KEY] = {\n integrations: new Map<string, IntegrationDefinition>(),\n bundles: new Map<string, IntegrationBundle>(),\n }\n }\n return globalRegistry[GLOBAL_INTEGRATION_REGISTRY_KEY]\n}\n\nexport function registerIntegration(definition: IntegrationDefinition): void {\n getIntegrationRegistryState().integrations.set(definition.id, definition)\n}\n\nexport function registerIntegrations(definitions: IntegrationDefinition[]): void {\n const registry = getIntegrationRegistryState().integrations\n for (const definition of definitions) {\n registry.set(definition.id, definition)\n }\n}\n\nexport function registerBundle(bundle: IntegrationBundle): void {\n getIntegrationRegistryState().bundles.set(bundle.id, bundle)\n}\n\nexport function registerBundles(bundles: IntegrationBundle[]): void {\n const registry = getIntegrationRegistryState().bundles\n for (const bundle of bundles) {\n registry.set(bundle.id, bundle)\n }\n}\n\nexport function clearRegisteredIntegrations(): void {\n const registry = getIntegrationRegistryState()\n registry.integrations.clear()\n registry.bundles.clear()\n}\n\nexport function getIntegration(integrationId: string): IntegrationDefinition | undefined {\n return getIntegrationRegistryState().integrations.get(integrationId)\n}\n\nexport function getAllIntegrations(): IntegrationDefinition[] {\n return Array.from(getIntegrationRegistryState().integrations.values())\n}\n\nexport function getBundle(bundleId: string): IntegrationBundle | undefined {\n return getIntegrationRegistryState().bundles.get(bundleId)\n}\n\nexport function getAllBundles(): IntegrationBundle[] {\n return Array.from(getIntegrationRegistryState().bundles.values())\n}\n\nexport function getBundleIntegrations(bundleId: string): IntegrationDefinition[] {\n return Array.from(getIntegrationRegistryState().integrations.values()).filter((integration) => integration.bundleId === bundleId)\n}\n\nexport function resolveIntegrationCredentialsSchema(integrationId: string): IntegrationCredentialsSchema | undefined {\n const registry = getIntegrationRegistryState()\n const definition = registry.integrations.get(integrationId)\n if (!definition) return undefined\n\n if (definition.credentials && definition.credentials.fields.length > 0) {\n return definition.credentials\n }\n\n if (!definition.bundleId) return definition.credentials\n return registry.bundles.get(definition.bundleId)?.credentials\n}\n\nexport function getIntegrationTitle(integrationId: string): string {\n return getIntegrationRegistryState().integrations.get(integrationId)?.title ?? integrationId\n}\n\nexport const LEGACY_INTEGRATION_DETAIL_TABS_SPOT_ID = 'integrations.detail:tabs'\n\nexport function buildIntegrationDetailWidgetSpotId(integrationId: string): string {\n return `integrations.detail:${integrationId}`\n}\n"],
5
- "mappings": "AAoNA,MAAM,kCAAkC;AAMxC,SAAS,8BAAwD;AAC/D,QAAM,iBAAiB;AACvB,MAAI,CAAC,eAAe,+BAA+B,GAAG;AACpD,mBAAe,+BAA+B,IAAI;AAAA,MAChD,cAAc,oBAAI,IAAmC;AAAA,MACrD,SAAS,oBAAI,IAA+B;AAAA,IAC9C;AAAA,EACF;AACA,SAAO,eAAe,+BAA+B;AACvD;AAEO,SAAS,oBAAoB,YAAyC;AAC3E,8BAA4B,EAAE,aAAa,IAAI,WAAW,IAAI,UAAU;AAC1E;AAEO,SAAS,qBAAqB,aAA4C;AAC/E,QAAM,WAAW,4BAA4B,EAAE;AAC/C,aAAW,cAAc,aAAa;AACpC,aAAS,IAAI,WAAW,IAAI,UAAU;AAAA,EACxC;AACF;AAEO,SAAS,eAAe,QAAiC;AAC9D,8BAA4B,EAAE,QAAQ,IAAI,OAAO,IAAI,MAAM;AAC7D;AAEO,SAAS,gBAAgB,SAAoC;AAClE,QAAM,WAAW,4BAA4B,EAAE;AAC/C,aAAW,UAAU,SAAS;AAC5B,aAAS,IAAI,OAAO,IAAI,MAAM;AAAA,EAChC;AACF;AAEO,SAAS,8BAAoC;AAClD,QAAM,WAAW,4BAA4B;AAC7C,WAAS,aAAa,MAAM;AAC5B,WAAS,QAAQ,MAAM;AACzB;AAEO,SAAS,eAAe,eAA0D;AACvF,SAAO,4BAA4B,EAAE,aAAa,IAAI,aAAa;AACrE;AAEO,SAAS,qBAA8C;AAC5D,SAAO,MAAM,KAAK,4BAA4B,EAAE,aAAa,OAAO,CAAC;AACvE;AAEO,SAAS,UAAU,UAAiD;AACzE,SAAO,4BAA4B,EAAE,QAAQ,IAAI,QAAQ;AAC3D;AAEO,SAAS,gBAAqC;AACnD,SAAO,MAAM,KAAK,4BAA4B,EAAE,QAAQ,OAAO,CAAC;AAClE;AAEO,SAAS,sBAAsB,UAA2C;AAC/E,SAAO,MAAM,KAAK,4BAA4B,EAAE,aAAa,OAAO,CAAC,EAAE,OAAO,CAAC,gBAAgB,YAAY,aAAa,QAAQ;AAClI;AAEO,SAAS,oCAAoC,eAAiE;AACnH,QAAM,WAAW,4BAA4B;AAC7C,QAAM,aAAa,SAAS,aAAa,IAAI,aAAa;AAC1D,MAAI,CAAC,WAAY,QAAO;AAExB,MAAI,WAAW,eAAe,WAAW,YAAY,OAAO,SAAS,GAAG;AACtE,WAAO,WAAW;AAAA,EACpB;AAEA,MAAI,CAAC,WAAW,SAAU,QAAO,WAAW;AAC5C,SAAO,SAAS,QAAQ,IAAI,WAAW,QAAQ,GAAG;AACpD;AAEO,SAAS,oBAAoB,eAA+B;AACjE,SAAO,4BAA4B,EAAE,aAAa,IAAI,aAAa,GAAG,SAAS;AACjF;AAEO,MAAM,yCAAyC;AAE/C,SAAS,mCAAmC,eAA+B;AAChF,SAAO,uBAAuB,aAAa;AAC7C;",
4
+ "sourcesContent": ["export type IntegrationScope = {\n organizationId: string\n tenantId: string\n /**\n * Optional per-user secret scoping. When set, credential lookups and writes\n * are scoped to a single user \u2014 used by per-user channels (Gmail, IMAP)\n * so two users on the same tenant don't share one row.\n *\n * When `undefined`/`null`, behaviour is unchanged \u2014 tenant-wide credentials\n * (e.g. shared Stripe/Akeneo API keys) keep working exactly as before.\n *\n * Stored on `IntegrationCredentials.user_id` (added 2026-05-26 by the email\n * integration spec). Backed by the partial unique index\n * `integration_credentials_user_lookup_idx` across integration, organization,\n * tenant, and user where `user_id IS NOT NULL AND deleted_at IS NULL`.\n */\n userId?: string | null\n}\n\nexport type IntegrationCategory =\n | 'payment'\n | 'shipping'\n | 'data_sync'\n | 'communication'\n | 'webhook'\n | 'storage'\n | 'other'\n\nexport type IntegrationHubId =\n | 'payment_gateways'\n | 'shipping_carriers'\n | 'data_sync'\n | 'communication_channels'\n | 'webhook_endpoints'\n | 'storage_hubs'\n | string\n\nexport type CredentialFieldType =\n | 'text'\n | 'secret'\n | 'select'\n | 'boolean'\n | 'url'\n | 'oauth'\n | 'ssh_keypair'\n\nexport interface CredentialFieldOption {\n value: string\n label: string\n}\n\nexport interface CredentialFieldVisibleWhen {\n field: string\n equals: string | number | boolean\n}\n\nexport interface IntegrationCredentialWebhookHelp {\n kind: 'webhook_setup'\n title: string\n summary: string\n endpointPath: string\n dashboardPathLabel: string\n steps: string[]\n events?: string[]\n localDevelopment?: {\n tunnelCommand: string\n publicUrlExample: string\n note?: string\n }\n}\n\nexport interface IntegrationCredentialFieldBase {\n key: string\n label: string\n required?: boolean\n placeholder?: string\n helpText?: string\n helpDetails?: IntegrationCredentialWebhookHelp\n visibleWhen?: CredentialFieldVisibleWhen\n}\n\nexport interface IntegrationCredentialFieldText extends IntegrationCredentialFieldBase {\n type: Extract<CredentialFieldType, 'text' | 'secret' | 'url'>\n}\n\nexport interface IntegrationCredentialFieldBoolean extends IntegrationCredentialFieldBase {\n type: Extract<CredentialFieldType, 'boolean'>\n}\n\nexport interface IntegrationCredentialFieldSelect extends IntegrationCredentialFieldBase {\n type: Extract<CredentialFieldType, 'select'>\n options: CredentialFieldOption[]\n}\n\nexport interface IntegrationCredentialFieldOauth extends IntegrationCredentialFieldBase {\n type: Extract<CredentialFieldType, 'oauth'>\n authUrl?: string\n tokenUrl?: string\n scopes?: string[]\n clientIdField?: string\n clientSecretField?: string\n}\n\nexport interface IntegrationCredentialFieldSshKeypair extends IntegrationCredentialFieldBase {\n type: Extract<CredentialFieldType, 'ssh_keypair'>\n algorithm?: 'ed25519' | 'rsa'\n rsaBits?: 2048 | 3072 | 4096\n}\n\nexport type IntegrationCredentialField =\n | IntegrationCredentialFieldText\n | IntegrationCredentialFieldBoolean\n | IntegrationCredentialFieldSelect\n | IntegrationCredentialFieldOauth\n | IntegrationCredentialFieldSshKeypair\n\nexport interface IntegrationCredentialsSchema {\n fields: IntegrationCredentialField[]\n}\n\nexport interface IntegrationHealthCheckConfig {\n service: string\n}\n\nexport interface ApiVersionDefinition {\n id: string\n label: string\n status: 'stable' | 'deprecated' | 'experimental'\n default?: boolean\n changelog?: string\n deprecatedAt?: string\n sunsetAt?: string\n migrationGuide?: string\n}\n\nexport interface IntegrationBundle {\n id: string\n title: string\n description: string\n icon?: string\n package?: string\n version?: string\n author?: string\n credentials: IntegrationCredentialsSchema\n healthCheck?: IntegrationHealthCheckConfig\n}\n\nexport interface IntegrationDetailPageConfig {\n /**\n * UMES widget spot rendered on the integration detail page.\n * Widgets registered here can render inline blocks, grouped panels,\n * or additional tabs via `placement.kind`.\n */\n widgetSpotId?: string\n /**\n * Built-in tabs to hide for this integration detail page.\n * Provider modules can replace these with injected tabs using the same spot.\n */\n hiddenTabs?: IntegrationDetailBuiltInTab[]\n /**\n * Detail-page tab that holds the provider's Connect / Reconnect controls (a built-in tab id or\n * an injected tab id). The OAuth reauth banner links to `?tab=<connectTabId>` while that tab is\n * visible and the viewer holds `integrations.credentials.manage`.\n */\n connectTabId?: string\n}\n\nexport type IntegrationDetailBuiltInTab =\n | 'credentials'\n | 'version'\n | 'health'\n | 'logs'\n | 'data-sync-schedule'\n\nexport interface IntegrationDefaultStateConfig {\n isEnabled?: boolean\n}\n\nexport interface IntegrationDefinition {\n id: string\n title: string\n icon?: string\n buildExternalUrl?: (externalId: string) => string\n bundleId?: string\n apiVersions?: ApiVersionDefinition[]\n description?: string\n category?: IntegrationCategory | string\n hub?: IntegrationHubId\n providerKey?: string\n docsUrl?: string\n package?: string\n version?: string\n author?: string\n company?: string\n license?: string\n tags?: string[]\n detailPage?: IntegrationDetailPageConfig\n defaultState?: IntegrationDefaultStateConfig\n credentials?: IntegrationCredentialsSchema\n healthCheck?: IntegrationHealthCheckConfig\n}\n\nexport interface ExternalIdEnrichment {\n _integrations: Record<string, ExternalIdMapping>\n}\n\nexport interface ExternalIdMapping {\n externalId: string\n externalUrl?: string\n lastSyncedAt?: string\n syncStatus: 'synced' | 'pending' | 'error' | 'not_synced'\n}\n\ntype IntegrationRegistryState = {\n integrations: Map<string, IntegrationDefinition>\n bundles: Map<string, IntegrationBundle>\n}\n\nconst GLOBAL_INTEGRATION_REGISTRY_KEY = '__openMercatoIntegrationRegistry__' as const\n\ntype GlobalIntegrationRegistry = typeof globalThis & {\n [GLOBAL_INTEGRATION_REGISTRY_KEY]?: IntegrationRegistryState\n}\n\nfunction getIntegrationRegistryState(): IntegrationRegistryState {\n const globalRegistry = globalThis as GlobalIntegrationRegistry\n if (!globalRegistry[GLOBAL_INTEGRATION_REGISTRY_KEY]) {\n globalRegistry[GLOBAL_INTEGRATION_REGISTRY_KEY] = {\n integrations: new Map<string, IntegrationDefinition>(),\n bundles: new Map<string, IntegrationBundle>(),\n }\n }\n return globalRegistry[GLOBAL_INTEGRATION_REGISTRY_KEY]\n}\n\nexport function registerIntegration(definition: IntegrationDefinition): void {\n getIntegrationRegistryState().integrations.set(definition.id, definition)\n}\n\nexport function registerIntegrations(definitions: IntegrationDefinition[]): void {\n const registry = getIntegrationRegistryState().integrations\n for (const definition of definitions) {\n registry.set(definition.id, definition)\n }\n}\n\nexport function registerBundle(bundle: IntegrationBundle): void {\n getIntegrationRegistryState().bundles.set(bundle.id, bundle)\n}\n\nexport function registerBundles(bundles: IntegrationBundle[]): void {\n const registry = getIntegrationRegistryState().bundles\n for (const bundle of bundles) {\n registry.set(bundle.id, bundle)\n }\n}\n\nexport function clearRegisteredIntegrations(): void {\n const registry = getIntegrationRegistryState()\n registry.integrations.clear()\n registry.bundles.clear()\n}\n\nexport function getIntegration(integrationId: string): IntegrationDefinition | undefined {\n return getIntegrationRegistryState().integrations.get(integrationId)\n}\n\nexport function getAllIntegrations(): IntegrationDefinition[] {\n return Array.from(getIntegrationRegistryState().integrations.values())\n}\n\nexport function getBundle(bundleId: string): IntegrationBundle | undefined {\n return getIntegrationRegistryState().bundles.get(bundleId)\n}\n\nexport function getAllBundles(): IntegrationBundle[] {\n return Array.from(getIntegrationRegistryState().bundles.values())\n}\n\nexport function getBundleIntegrations(bundleId: string): IntegrationDefinition[] {\n return Array.from(getIntegrationRegistryState().integrations.values()).filter((integration) => integration.bundleId === bundleId)\n}\n\nexport function resolveIntegrationCredentialsSchema(integrationId: string): IntegrationCredentialsSchema | undefined {\n const registry = getIntegrationRegistryState()\n const definition = registry.integrations.get(integrationId)\n if (!definition) return undefined\n\n if (definition.credentials && definition.credentials.fields.length > 0) {\n return definition.credentials\n }\n\n if (!definition.bundleId) return definition.credentials\n return registry.bundles.get(definition.bundleId)?.credentials\n}\n\nexport function getIntegrationTitle(integrationId: string): string {\n return getIntegrationRegistryState().integrations.get(integrationId)?.title ?? integrationId\n}\n\nexport const LEGACY_INTEGRATION_DETAIL_TABS_SPOT_ID = 'integrations.detail:tabs'\n\nexport function buildIntegrationDetailWidgetSpotId(integrationId: string): string {\n return `integrations.detail:${integrationId}`\n}\n"],
5
+ "mappings": "AA0NA,MAAM,kCAAkC;AAMxC,SAAS,8BAAwD;AAC/D,QAAM,iBAAiB;AACvB,MAAI,CAAC,eAAe,+BAA+B,GAAG;AACpD,mBAAe,+BAA+B,IAAI;AAAA,MAChD,cAAc,oBAAI,IAAmC;AAAA,MACrD,SAAS,oBAAI,IAA+B;AAAA,IAC9C;AAAA,EACF;AACA,SAAO,eAAe,+BAA+B;AACvD;AAEO,SAAS,oBAAoB,YAAyC;AAC3E,8BAA4B,EAAE,aAAa,IAAI,WAAW,IAAI,UAAU;AAC1E;AAEO,SAAS,qBAAqB,aAA4C;AAC/E,QAAM,WAAW,4BAA4B,EAAE;AAC/C,aAAW,cAAc,aAAa;AACpC,aAAS,IAAI,WAAW,IAAI,UAAU;AAAA,EACxC;AACF;AAEO,SAAS,eAAe,QAAiC;AAC9D,8BAA4B,EAAE,QAAQ,IAAI,OAAO,IAAI,MAAM;AAC7D;AAEO,SAAS,gBAAgB,SAAoC;AAClE,QAAM,WAAW,4BAA4B,EAAE;AAC/C,aAAW,UAAU,SAAS;AAC5B,a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"0.9.1-develop.7574.1.837288eec1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -8,6 +8,7 @@
8
8
  "build": "node build.mjs",
9
9
  "watch": "node watch.mjs",
10
10
  "test": "jest --config jest.config.cjs",
11
+ "test:pg-integration": "cross-env OM_PG_INTEGRATION=1 jest --config jest.config.cjs --runInBand 'src/lib/db/__tests__/advisoryLock\\.integration\\.test\\.ts$'",
11
12
  "typecheck": "tsc --noEmit"
12
13
  },
13
14
  "exports": {
@@ -64,6 +65,10 @@
64
65
  "types": "./src/lib/db/duplicateEntityClassNames.ts",
65
66
  "default": "./dist/lib/db/duplicateEntityClassNames.js"
66
67
  },
68
+ "./lib/db/advisoryLock": {
69
+ "types": "./src/lib/db/advisoryLock.ts",
70
+ "default": "./dist/lib/db/advisoryLock.js"
71
+ },
67
72
  "./lib/data/consistency": {
68
73
  "types": "./src/lib/data/consistency.ts",
69
74
  "default": "./dist/lib/data/consistency.js"
@@ -121,7 +126,7 @@
121
126
  "@mikro-orm/core": "^7.1.14",
122
127
  "@mikro-orm/decorators": "^7.1.14",
123
128
  "@mikro-orm/postgresql": "^7.1.14",
124
- "@open-mercato/cache": "0.9.1-develop.7573.1.d0ccc51d5b",
129
+ "@open-mercato/cache": "0.9.1-develop.7574.1.837288eec1",
125
130
  "@types/html-to-text": "^9.0.4",
126
131
  "@types/sanitize-html": "^2.16.1",
127
132
  "dotenv": "^17.4.2",
@@ -136,8 +141,10 @@
136
141
  },
137
142
  "devDependencies": {
138
143
  "@types/jest": "^30.0.0",
144
+ "cross-env": "^10.1.0",
139
145
  "jest": "^30.4.2",
140
146
  "language-subtag-registry": "^0.3.20",
147
+ "testcontainers": "^12.0.3",
141
148
  "ts-jest": "^29.4.12",
142
149
  "ts-morph": "^28.0.0",
143
150
  "typescript": "7.0.2"