@open-mercato/shared 0.6.8-develop.6889.1.af4501ca97 → 0.6.8-develop.6892.1.f179677788

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.
Files changed (32) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +5 -0
  3. package/dist/lib/bootstrap/dynamicLoader.js +40 -4
  4. package/dist/lib/bootstrap/dynamicLoader.js.map +2 -2
  5. package/dist/lib/bootstrap/factory.js +18 -13
  6. package/dist/lib/bootstrap/factory.js.map +2 -2
  7. package/dist/lib/encryption/find.js +22 -0
  8. package/dist/lib/encryption/find.js.map +2 -2
  9. package/dist/lib/encryption/likeFilterWarning.js +66 -0
  10. package/dist/lib/encryption/likeFilterWarning.js.map +7 -0
  11. package/dist/lib/i18n/dictionary-cache.js +5 -0
  12. package/dist/lib/i18n/dictionary-cache.js.map +2 -2
  13. package/dist/lib/modules/registry.js +31 -5
  14. package/dist/lib/modules/registry.js.map +2 -2
  15. package/dist/lib/query/ciphertext-search-warning.js +7 -1
  16. package/dist/lib/query/ciphertext-search-warning.js.map +2 -2
  17. package/dist/lib/version.js +1 -1
  18. package/dist/lib/version.js.map +1 -1
  19. package/package.json +2 -2
  20. package/src/lib/bootstrap/__tests__/dynamicLoader.test.ts +126 -0
  21. package/src/lib/bootstrap/__tests__/factory.test.ts +78 -0
  22. package/src/lib/bootstrap/dynamicLoader.ts +52 -4
  23. package/src/lib/bootstrap/factory.ts +21 -15
  24. package/src/lib/bootstrap/types.ts +6 -0
  25. package/src/lib/encryption/__tests__/likeFilterWarning.test.ts +167 -0
  26. package/src/lib/encryption/find.ts +22 -0
  27. package/src/lib/encryption/likeFilterWarning.ts +102 -0
  28. package/src/lib/i18n/__tests__/dictionary-cache.test.ts +23 -0
  29. package/src/lib/i18n/dictionary-cache.ts +5 -0
  30. package/src/lib/modules/__tests__/registry.test.ts +26 -0
  31. package/src/lib/modules/registry.ts +36 -7
  32. package/src/lib/query/ciphertext-search-warning.ts +17 -6
@@ -1,2 +1,2 @@
1
- [build:shared] found 257 entry points
1
+ [build:shared] found 258 entry points
2
2
  [build:shared] built successfully
package/AGENTS.md CHANGED
@@ -121,6 +121,11 @@ index stores hashes of the plaintext, so it keeps matching. Issue #2990.
121
121
  `em.find` / Kysely list routes must wire it themselves. When the fallback would run
122
122
  `ILIKE` against an encrypted column, both query engines now log a warning
123
123
  (`lib/query/ciphertext-search-warning`) instead of degrading silently.
124
+ - The `…WithDecryption` helpers log the same warning outside production when the `where`
125
+ clause targets an encryption-map property with `$like`/`$ilike`/`$re`
126
+ (`lib/encryption/likeFilterWarning`). It is a development aid — the map lookup costs an
127
+ uncached read, so it is skipped in production. A search that only breaks under a
128
+ production-only encryption map still needs a test.
124
129
 
125
130
  ### Boolean Parsing — MUST use instead of ad-hoc parsing
126
131
 
@@ -11,7 +11,38 @@ import fs from "node:fs";
11
11
  import crypto from "node:crypto";
12
12
  import { createRequire } from "node:module";
13
13
  import { pathToFileURL } from "node:url";
14
+ let activeBootstrapLoads = 0;
15
+ let esbuildRuntime = null;
16
+ let esbuildStopPromise = null;
14
17
  const logger = createLogger("shared").child({ component: "bootstrap" });
18
+ async function getEsbuildRuntime() {
19
+ if (esbuildStopPromise) await esbuildStopPromise;
20
+ if (esbuildRuntime) return esbuildRuntime;
21
+ const loadedRuntime = await import("esbuild");
22
+ esbuildRuntime ??= loadedRuntime;
23
+ return esbuildRuntime;
24
+ }
25
+ async function withEsbuildLifecycle(load) {
26
+ activeBootstrapLoads += 1;
27
+ try {
28
+ return await load();
29
+ } finally {
30
+ activeBootstrapLoads -= 1;
31
+ if (activeBootstrapLoads === 0 && esbuildRuntime) {
32
+ const runtimeToStop = esbuildRuntime;
33
+ esbuildRuntime = null;
34
+ const stopPromise = runtimeToStop.stop().catch((err) => {
35
+ logger.warn("Failed to stop the bootstrap compiler service", { err });
36
+ });
37
+ esbuildStopPromise = stopPromise;
38
+ try {
39
+ await stopPromise;
40
+ } finally {
41
+ if (esbuildStopPromise === stopPromise) esbuildStopPromise = null;
42
+ }
43
+ }
44
+ }
45
+ }
15
46
  class GeneratedFileNotFoundError extends Error {
16
47
  constructor(filePath) {
17
48
  super(`Generated file not found: ${filePath}`);
@@ -221,7 +252,7 @@ async function compileAndImport(tsPath, options = {}) {
221
252
  const needsCompile = !cacheIsValid(appRoot, jsPath, metadataPath, expectedInputHash);
222
253
  if (needsCompile) {
223
254
  fs.mkdirSync(path.dirname(jsPath), { recursive: true });
224
- const esbuild = await import("esbuild");
255
+ const esbuild = await getEsbuildRuntime();
225
256
  const result = await esbuild.build({
226
257
  entryPoints: [tsPath],
227
258
  outfile: jsPath,
@@ -320,7 +351,7 @@ async function loadAppDiRegistrar(appDir) {
320
351
  return null;
321
352
  }
322
353
  }
323
- async function loadBootstrapData(appRoot) {
354
+ async function loadBootstrapDataWithActiveEsbuild(appRoot) {
324
355
  const resolved = resolveAppRootOrThrow(appRoot);
325
356
  const { generatedDir } = resolved;
326
357
  ensureMikroOrmV7GeneratedCacheCompatibility(resolved.appDir);
@@ -368,11 +399,16 @@ async function loadBootstrapData(appRoot) {
368
399
  componentOverrideEntries: []
369
400
  };
370
401
  }
402
+ async function loadBootstrapData(appRoot) {
403
+ return withEsbuildLifecycle(() => loadBootstrapDataWithActiveEsbuild(appRoot));
404
+ }
371
405
  async function bootstrapFromAppRoot(appRoot) {
372
406
  const { createBootstrap, waitForAsyncRegistration } = await import("./factory.js");
373
407
  const resolved = resolveAppRootOrThrow(appRoot);
374
- const data = await loadBootstrapData(resolved.appDir);
375
- const appDiRegistrar = await loadAppDiRegistrar(resolved.appDir);
408
+ const { data, appDiRegistrar } = await withEsbuildLifecycle(async () => ({
409
+ data: await loadBootstrapData(resolved.appDir),
410
+ appDiRegistrar: await loadAppDiRegistrar(resolved.appDir)
411
+ }));
376
412
  const bootstrap = createBootstrap(data, appDiRegistrar ? { appDiRegistrar } : {});
377
413
  bootstrap();
378
414
  await waitForAsyncRegistration();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/bootstrap/dynamicLoader.ts"],
4
- "sourcesContent": ["import type { BootstrapData } from './types'\nimport type { AppDiRegistrar } from '../di/container'\nimport { findAppRoot, type AppRoot } from './appResolver'\nimport { registerEntityIds } from '../encryption/entityIds'\nimport { createLogger } from '../logger'\nimport {\n ensureMikroOrmV7GeneratedCacheCompatibility,\n recoverMikroOrmV7GeneratedCacheFromImportError,\n} from './generatedCacheRecovery'\nimport { CLIENT_ONLY_STUB_NAMESPACE, createClientOnlyStubPlugin } from './clientOnlyModules'\nimport path from 'node:path'\nimport fs from 'node:fs'\nimport crypto from 'node:crypto'\nimport { createRequire } from 'node:module'\nimport { pathToFileURL } from 'node:url'\n\nconst logger = createLogger('shared').child({ component: 'bootstrap' })\n\n/**\n * Thrown when an expected generated source file is absent.\n *\n * Optional registries treat this as the supported compatibility case (an app\n * that never generated the file), which is what makes it distinguishable from\n * a file that exists but fails to compile or import.\n */\nclass GeneratedFileNotFoundError extends Error {\n readonly filePath: string\n\n constructor(filePath: string) {\n super(`Generated file not found: ${filePath}`)\n this.name = 'GeneratedFileNotFoundError'\n this.filePath = filePath\n }\n}\n\n/**\n * esbuild plugins for the CLI bundle, in resolution order. The client-only stub must come\n * first so it wins over the alias and external plugins for `*.client` dynamic imports.\n *\n * Exported so the wiring itself is testable: a test that only exercises\n * `createClientOnlyStubPlugin` in isolation stays green if the plugin is dropped from this\n * list, which would silently reintroduce #4623.\n */\nexport function createCliBundlePlugins(appRoot: string): import('esbuild').Plugin[] {\n // Plugin to resolve the @/ alias the way the app tsconfig maps it:\n // `@/.mercato/*` to the app root, every other `@/*` to the app's src/ directory.\n const aliasPlugin: import('esbuild').Plugin = {\n name: 'alias-resolver',\n setup(build) {\n build.onResolve({ filter: /^@\\// }, (args) => {\n const rest = args.path.slice('@/'.length)\n const bases = rest.startsWith('.mercato/')\n ? [path.join(appRoot, rest)]\n : [path.join(appRoot, 'src', rest), path.join(appRoot, rest)]\n for (const base of bases) {\n if (fs.existsSync(base) && fs.statSync(base).isFile()) {\n return { path: base }\n }\n for (const suffix of ['.ts', '.tsx', '/index.ts', '/index.tsx']) {\n if (fs.existsSync(base + suffix)) {\n return { path: base + suffix }\n }\n }\n }\n // Nothing matched \u2014 hand esbuild the literal mapping so it reports the\n // missing file against the path the app author actually wrote.\n return { path: path.join(appRoot, rest) }\n })\n },\n }\n\n // Plugin to mark non-JSON package imports as external\n const externalNonJsonPlugin: import('esbuild').Plugin = {\n name: 'external-non-json',\n setup(build) {\n // Mark all package imports as external EXCEPT JSON files\n // Filter matches paths that don't start with . or / (package imports like @open-mercato/shared)\n build.onResolve({ filter: /^[^./]/ }, (args) => {\n // Skip Windows absolute paths (e.g., C:\\...) - they're local files, not packages\n if (/^[a-zA-Z]:/.test(args.path)) {\n return null // Let esbuild handle it\n }\n // If it's a JSON file, let esbuild bundle it\n if (args.path.endsWith('.json')) {\n return null // Let esbuild handle it\n }\n // Otherwise mark as external\n return { path: args.path, external: true }\n })\n },\n }\n\n return [createClientOnlyStubPlugin(), aliasPlugin, externalNonJsonPlugin]\n}\n\nconst DYNAMIC_LOADER_CACHE_VERSION = 4\n\ntype DynamicLoaderCacheMetadata = {\n version: number\n inputHash: string\n outputHash: string\n dependencies: Record<string, string>\n}\n\nfunction cacheMetadataPath(jsPath: string): string {\n return `${jsPath}.cache.json`\n}\n\nfunction contentHash(content: Buffer | string): string {\n return crypto.createHash('sha256').update(content).digest('hex')\n}\n\nfunction parseJsonConfig(content: string): unknown {\n let normalized = ''\n let inString = false\n let escaped = false\n\n for (let index = 0; index < content.length; index += 1) {\n const character = content[index]\n const nextCharacter = content[index + 1]\n\n if (inString) {\n normalized += character\n if (escaped) {\n escaped = false\n } else if (character === '\\\\') {\n escaped = true\n } else if (character === '\"') {\n inString = false\n }\n continue\n }\n\n if (character === '\"') {\n inString = true\n normalized += character\n continue\n }\n\n if (character === '/' && nextCharacter === '/') {\n while (index < content.length && content[index] !== '\\n') index += 1\n normalized += '\\n'\n continue\n }\n\n if (character === '/' && nextCharacter === '*') {\n index += 2\n while (index < content.length && !(content[index] === '*' && content[index + 1] === '/')) {\n index += 1\n }\n index += 1\n continue\n }\n\n if (character === ',') {\n let lookahead = index + 1\n while (lookahead < content.length && /\\s/.test(content[lookahead])) lookahead += 1\n if (content[lookahead] === '}' || content[lookahead] === ']') continue\n }\n\n normalized += character\n }\n\n return JSON.parse(normalized)\n}\n\nfunction resolveExistingConfigPath(candidate: string): string | null {\n for (const configPath of [candidate, `${candidate}.json`, path.join(candidate, 'tsconfig.json')]) {\n if (fs.existsSync(configPath) && fs.statSync(configPath).isFile()) return configPath\n }\n return null\n}\n\nfunction resolvePackageConfig(configPath: string, reference: string): string | null {\n try {\n const resolved = createRequire(pathToFileURL(configPath)).resolve(reference)\n return path.extname(resolved) === '.json' ? resolved : null\n } catch {\n return null\n }\n}\n\nfunction resolveExtendedConfig(configPath: string, reference: string): string {\n if (path.isAbsolute(reference) || reference.startsWith('.')) {\n const resolved = resolveExistingConfigPath(path.resolve(path.dirname(configPath), reference))\n if (resolved) return resolved\n } else {\n for (const packageReference of [reference, `${reference}/tsconfig.json`]) {\n const resolved = resolvePackageConfig(configPath, packageReference)\n if (resolved) return resolved\n }\n }\n\n throw new Error(`[internal] TypeScript config extends target not found: ${reference}`)\n}\n\nfunction collectTsconfigPaths(entryPath: string, visited: Set<string> = new Set()): string[] {\n const configPath = path.resolve(entryPath)\n if (visited.has(configPath)) return []\n visited.add(configPath)\n\n const parsed = parseJsonConfig(fs.readFileSync(configPath, 'utf8'))\n if (typeof parsed !== 'object' || parsed === null || !('extends' in parsed)) return [configPath]\n\n const extendsValue = parsed.extends\n const references = typeof extendsValue === 'string'\n ? [extendsValue]\n : Array.isArray(extendsValue) && extendsValue.every((value) => typeof value === 'string')\n ? extendsValue\n : []\n\n return [\n ...references.flatMap((reference) => collectTsconfigPaths(\n resolveExtendedConfig(configPath, reference),\n visited,\n )),\n configPath,\n ]\n}\n\nfunction hashFilesRelativeTo(appRoot: string, filePaths: string[]): Record<string, string> {\n return Object.fromEntries(filePaths.map((filePath) => [\n path.relative(appRoot, filePath).split(path.sep).join('/'),\n contentHash(fs.readFileSync(filePath)),\n ]))\n}\n\nfunction cacheInputHash(tsPath: string, appRoot: string, tsconfigPaths: string[]): string {\n const hash = crypto.createHash('sha256')\n hash.update(JSON.stringify({\n version: DYNAMIC_LOADER_CACHE_VERSION,\n sourceHash: contentHash(fs.readFileSync(tsPath)),\n tsconfigHashes: hashFilesRelativeTo(appRoot, tsconfigPaths),\n }))\n return hash.digest('hex')\n}\n\nfunction dependenciesAreValid(appRoot: string, dependencies: Record<string, string>): boolean {\n return Object.entries(dependencies).every(([relativePath, expectedHash]) => {\n const dependencyPath = path.resolve(appRoot, relativePath)\n return fs.existsSync(dependencyPath)\n && contentHash(fs.readFileSync(dependencyPath)) === expectedHash\n })\n}\n\nfunction collectDependencyHashes(\n appRoot: string,\n inputs: Record<string, unknown>,\n): Record<string, string> {\n return Object.fromEntries(\n Object.keys(inputs)\n .filter((inputPath) => !inputPath.startsWith(`${CLIENT_ONLY_STUB_NAMESPACE}:`))\n .map((inputPath) => {\n const absolutePath = path.isAbsolute(inputPath)\n ? inputPath\n : path.resolve(appRoot, inputPath)\n const relativePath = path.relative(appRoot, absolutePath).split(path.sep).join('/')\n return [relativePath, contentHash(fs.readFileSync(absolutePath))]\n })\n .sort(([left], [right]) => left.localeCompare(right)),\n )\n}\n\nfunction readCacheMetadata(metadataPath: string): DynamicLoaderCacheMetadata | null {\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(metadataPath, 'utf8'))\n if (\n typeof parsed === 'object'\n && parsed !== null\n && 'version' in parsed\n && parsed.version === DYNAMIC_LOADER_CACHE_VERSION\n && 'inputHash' in parsed\n && typeof parsed.inputHash === 'string'\n && 'outputHash' in parsed\n && typeof parsed.outputHash === 'string'\n && 'dependencies' in parsed\n && typeof parsed.dependencies === 'object'\n && parsed.dependencies !== null\n && Object.values(parsed.dependencies).every((hash) => typeof hash === 'string')\n ) {\n return {\n version: parsed.version,\n inputHash: parsed.inputHash,\n outputHash: parsed.outputHash,\n dependencies: parsed.dependencies as Record<string, string>,\n }\n }\n } catch {\n return null\n }\n return null\n}\n\nfunction cacheIsValid(\n appRoot: string,\n jsPath: string,\n metadataPath: string,\n expectedInputHash: string,\n): boolean {\n if (!fs.existsSync(jsPath)) return false\n const metadata = readCacheMetadata(metadataPath)\n if (!metadata || metadata.inputHash !== expectedInputHash) return false\n return contentHash(fs.readFileSync(jsPath)) === metadata.outputHash\n && dependenciesAreValid(appRoot, metadata.dependencies)\n}\n\n/**\n * Options for `compileAndImport`.\n *\n * Both paths default to the generated-registry layout (`<appRoot>/.mercato/generated/<file>.ts`\n * compiled to a `.mjs` sibling). Sources that live elsewhere in the app \u2014 `src/di.ts` \u2014 MUST pass\n * both explicitly: the default app root is derived by walking three directories up from the source,\n * which only holds inside `.mercato/generated`.\n */\ntype CompileAndImportOptions = {\n appRoot?: string\n outFile?: string\n allowRecovery?: boolean\n}\n\n/**\n * Compile a TypeScript file to JavaScript using esbuild bundler.\n * This bundles the file and all its dependencies, handling JSON imports properly.\n * The compiled file is written next to the source file with a .mjs extension unless\n * `outFile` says otherwise.\n */\nasync function compileAndImport(\n tsPath: string,\n options: CompileAndImportOptions = {},\n): Promise<Record<string, unknown>> {\n const allowRecovery = options.allowRecovery ?? true\n const jsPath = options.outFile ?? tsPath.replace(/\\.ts$/, '.mjs')\n const appRoot = options.appRoot ?? path.dirname(path.dirname(path.dirname(tsPath)))\n const appTsconfig = path.join(appRoot, 'tsconfig.json')\n const metadataPath = cacheMetadataPath(jsPath)\n\n const tsExists = fs.existsSync(tsPath)\n const tsconfigExists = fs.existsSync(appTsconfig)\n\n if (!tsExists) {\n throw new GeneratedFileNotFoundError(tsPath)\n }\n if (!tsconfigExists) {\n throw new Error(`App TypeScript config not found: ${appTsconfig}`)\n }\n\n const tsconfigPaths = collectTsconfigPaths(appTsconfig)\n const expectedInputHash = cacheInputHash(tsPath, appRoot, tsconfigPaths)\n const needsCompile = !cacheIsValid(appRoot, jsPath, metadataPath, expectedInputHash)\n\n if (needsCompile) {\n fs.mkdirSync(path.dirname(jsPath), { recursive: true })\n // Dynamically import esbuild only when needed\n const esbuild = await import('esbuild')\n\n // Use esbuild.build with bundling to handle JSON imports\n const result = await esbuild.build({\n entryPoints: [tsPath],\n outfile: jsPath,\n absWorkingDir: appRoot,\n bundle: true,\n metafile: true,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n tsconfig: appTsconfig,\n plugins: createCliBundlePlugins(appRoot),\n // Allow JSON imports\n loader: { '.json': 'json' },\n })\n const metadata: DynamicLoaderCacheMetadata = {\n version: DYNAMIC_LOADER_CACHE_VERSION,\n inputHash: expectedInputHash,\n outputHash: contentHash(fs.readFileSync(jsPath)),\n dependencies: {\n ...collectDependencyHashes(appRoot, result.metafile.inputs),\n ...hashFilesRelativeTo(appRoot, tsconfigPaths),\n },\n }\n fs.writeFileSync(metadataPath, JSON.stringify(metadata))\n }\n\n // Import the compiled JavaScript\n try {\n const outputHash = contentHash(fs.readFileSync(jsPath))\n const fileUrl = `${pathToFileURL(jsPath).href}?cache=${outputHash}`\n return await import(fileUrl)\n } catch (error) {\n if (!allowRecovery) {\n throw error\n }\n\n const recovered = recoverMikroOrmV7GeneratedCacheFromImportError(appRoot, error)\n if (!recovered.applied) {\n throw error\n }\n\n return compileAndImport(tsPath, { ...options, allowRecovery: false })\n }\n}\n\n\n/**\n * Load a generated registry that older apps may not have generated yet.\n *\n * An absent source file is the supported compatibility case and resolves to\n * `fallback` quietly. Any other failure \u2014 a compile error, a broken import, a\n * runtime throw at module scope \u2014 still resolves to `fallback` so bootstrap\n * keeps working, but is reported at error level: a registry that silently\n * degrades to nothing is exactly how command interceptors stopped applying in\n * worker/CLI processes (#4327, #4491).\n */\nasync function loadOptionalGeneratedModule(\n tsPath: string,\n fallback: Record<string, unknown>,\n): Promise<Record<string, unknown>> {\n try {\n return await compileAndImport(tsPath)\n } catch (error) {\n if (error instanceof GeneratedFileNotFoundError) {\n logger.debug('Optional generated registry not present, using empty fallback', {\n file: path.basename(tsPath),\n })\n return fallback\n }\n\n logger.error('Failed to load generated registry, continuing without its entries', {\n file: path.basename(tsPath),\n filePath: tsPath,\n err: error,\n })\n return fallback\n }\n}\n\nfunction resolveAppRootOrThrow(appRoot?: string): AppRoot {\n const resolved: AppRoot | null = appRoot\n ? {\n generatedDir: path.join(appRoot, '.mercato', 'generated'),\n appDir: appRoot,\n mercatoDir: path.join(appRoot, '.mercato'),\n }\n : findAppRoot()\n\n if (!resolved) {\n throw new Error(\n 'Could not find app root with .mercato/generated directory. ' +\n 'Make sure you run this command from within a Next.js app directory, ' +\n 'or run \"yarn mercato generate\" first to create the generated files.',\n )\n }\n\n return resolved\n}\n\n/**\n * Load the app-level DI registrar (`src/di.ts`) for the dynamic bootstrap path.\n *\n * The Next.js runtime imports `@/di` statically from its own `src/bootstrap.ts` and hands the\n * registrar to `createBootstrap`. Worker, scheduler and CLI processes bootstrap through\n * `bootstrapFromAppRoot` instead, where the `@/` alias does not exist \u2014 so without this the app's\n * DI registrations silently never ran there, and every request container paid a failed\n * `import('@/di')` resolution (the compatibility fallback in `lib/di/container.ts`).\n *\n * An absent `src/di.ts` is the supported case and resolves to `null` quietly. A file that exists\n * but cannot be compiled, imported, or does not export `register` is reported at error level and\n * still resolves to `null`, so a broken app DI module degrades the same way a broken generated\n * registry does (#4327, #4491) instead of taking the whole process down.\n */\nasync function loadAppDiRegistrar(appDir: string): Promise<AppDiRegistrar | null> {\n const tsPath = path.join(appDir, 'src', 'di.ts')\n if (!fs.existsSync(tsPath)) {\n logger.debug('App-level DI module not present, skipping its registrations', { filePath: tsPath })\n return null\n }\n\n try {\n const appDiModule = await compileAndImport(tsPath, {\n appRoot: appDir,\n outFile: path.join(appDir, '.mercato', 'generated', 'app-di.compiled.mjs'),\n })\n const register = appDiModule.register\n if (typeof register !== 'function') {\n logger.error('App-level DI module exports no register(); its registrations are skipped', {\n filePath: tsPath,\n })\n return null\n }\n return register as AppDiRegistrar\n } catch (error) {\n logger.error('Failed to load the app-level DI module; its registrations are skipped', {\n filePath: tsPath,\n err: error,\n })\n return null\n }\n}\n\n/**\n * Dynamically load bootstrap data from a resolved app directory.\n *\n * IMPORTANT: This only works in unbundled contexts (CLI, tsx).\n * Do NOT use this in Next.js bundled code - use static imports instead.\n *\n * For CLI context, we skip loading modules.generated.ts which has Next.js dependencies.\n * CLI commands are discovered separately via the CLI module system.\n *\n * @param appRoot - Optional explicit app root path. If not provided, will search from cwd.\n * @returns The loaded bootstrap data\n * @throws Error if app root cannot be found or generated files are missing\n */\nexport async function loadBootstrapData(appRoot?: string): Promise<BootstrapData> {\n const resolved = resolveAppRootOrThrow(appRoot)\n\n const { generatedDir } = resolved\n\n ensureMikroOrmV7GeneratedCacheCompatibility(resolved.appDir)\n\n // IMPORTANT: Load entity IDs FIRST and register them before loading modules.\n // This is because modules (e.g., ce.ts files) use E.xxx.xxx at module scope,\n // and they need entity IDs to be available when they're imported.\n const entityIdsModule = await compileAndImport(path.join(generatedDir, 'entities.ids.generated.ts'))\n registerEntityIds(entityIdsModule.E as BootstrapData['entityIds'])\n\n // Now load the rest of the generated files.\n // modules.cli.generated.ts excludes Next.js-dependent code (routes, APIs, widgets)\n const [\n modulesModule,\n entitiesModule,\n diModule,\n searchModule,\n commandLoadersModule,\n commandInterceptorsModule,\n workflowsModule,\n ] = await Promise.all([\n compileAndImport(path.join(generatedDir, 'modules.cli.generated.ts')),\n compileAndImport(path.join(generatedDir, 'entities.generated.ts')),\n compileAndImport(path.join(generatedDir, 'di.generated.ts')),\n loadOptionalGeneratedModule(path.join(generatedDir, 'search.generated.ts'), { searchModuleConfigs: [] }),\n loadOptionalGeneratedModule(path.join(generatedDir, 'command-loaders.generated.ts'), { commandLoaderEntries: [] }),\n loadOptionalGeneratedModule(path.join(generatedDir, 'command-interceptors.generated.ts'), {\n commandInterceptorEntries: [],\n }),\n loadOptionalGeneratedModule(path.join(generatedDir, 'workflows.generated.ts'), { allCodeWorkflows: [] }),\n ])\n\n return {\n modules: modulesModule.modules as BootstrapData['modules'],\n entities: entitiesModule.entities as BootstrapData['entities'],\n diRegistrars: diModule.diRegistrars as BootstrapData['diRegistrars'],\n entityIds: entityIdsModule.E as BootstrapData['entityIds'],\n // Search configs are needed by workers for indexing\n searchModuleConfigs: (searchModule.searchModuleConfigs ?? []) as BootstrapData['searchModuleConfigs'],\n commandLoaderEntries: (commandLoadersModule.commandLoaderEntries ?? []) as BootstrapData['commandLoaderEntries'],\n // Command interceptors must apply in worker/CLI processes too \u2014 the\n // interceptor registry is per-process, so relying on the Next.js runtime's\n // registration silently no-ops every interceptor for queued/CLI commands\n // (#4327).\n commandInterceptorEntries: (commandInterceptorsModule.commandInterceptorEntries ??\n []) as BootstrapData['commandInterceptorEntries'],\n // Code workflow definitions are needed by workers to resume code-defined instances\n codeWorkflows: (workflowsModule.allCodeWorkflows ?? []) as BootstrapData['codeWorkflows'],\n // Empty UI-related data - not needed for CLI\n dashboardWidgetEntries: [],\n injectionWidgetEntries: [],\n injectionTables: [],\n interceptorEntries: [],\n componentOverrideEntries: [],\n }\n}\n\n/**\n * Create and execute bootstrap in CLI context.\n *\n * This is a convenience function that finds the app root, loads the generated\n * data dynamically, and runs bootstrap. Use this in CLI entry points.\n *\n * Returns the loaded bootstrap data so the CLI can register modules directly\n * (avoids module resolution issues when importing @open-mercato/cli/mercato).\n *\n * @param appRoot - Optional explicit app root path\n * @returns The loaded bootstrap data (modules, entities, etc.)\n */\nexport async function bootstrapFromAppRoot(appRoot?: string): Promise<BootstrapData> {\n const { createBootstrap, waitForAsyncRegistration } = await import('./factory.js')\n const resolved = resolveAppRootOrThrow(appRoot)\n const data = await loadBootstrapData(resolved.appDir)\n const appDiRegistrar = await loadAppDiRegistrar(resolved.appDir)\n const bootstrap = createBootstrap(data, appDiRegistrar ? { appDiRegistrar } : {})\n bootstrap()\n // In CLI context, wait for async registrations (UI widgets, search configs, etc.)\n await waitForAsyncRegistration()\n\n return data\n}\n"],
5
- "mappings": "AAEA,SAAS,mBAAiC;AAC1C,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B,kCAAkC;AACvE,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,OAAO,YAAY;AACnB,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAE9B,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,YAAY,CAAC;AAStE,MAAM,mCAAmC,MAAM;AAAA,EAG7C,YAAY,UAAkB;AAC5B,UAAM,6BAA6B,QAAQ,EAAE;AAC7C,SAAK,OAAO;AACZ,SAAK,WAAW;AAAA,EAClB;AACF;AAUO,SAAS,uBAAuB,SAA6C;AAGlF,QAAM,cAAwC;AAAA,IAC5C,MAAM;AAAA,IACN,MAAM,OAAO;AACX,YAAM,UAAU,EAAE,QAAQ,OAAO,GAAG,CAAC,SAAS;AAC5C,cAAM,OAAO,KAAK,KAAK,MAAM,KAAK,MAAM;AACxC,cAAM,QAAQ,KAAK,WAAW,WAAW,IACrC,CAAC,KAAK,KAAK,SAAS,IAAI,CAAC,IACzB,CAAC,KAAK,KAAK,SAAS,OAAO,IAAI,GAAG,KAAK,KAAK,SAAS,IAAI,CAAC;AAC9D,mBAAW,QAAQ,OAAO;AACxB,cAAI,GAAG,WAAW,IAAI,KAAK,GAAG,SAAS,IAAI,EAAE,OAAO,GAAG;AACrD,mBAAO,EAAE,MAAM,KAAK;AAAA,UACtB;AACA,qBAAW,UAAU,CAAC,OAAO,QAAQ,aAAa,YAAY,GAAG;AAC/D,gBAAI,GAAG,WAAW,OAAO,MAAM,GAAG;AAChC,qBAAO,EAAE,MAAM,OAAO,OAAO;AAAA,YAC/B;AAAA,UACF;AAAA,QACF;AAGA,eAAO,EAAE,MAAM,KAAK,KAAK,SAAS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B,EAAE,eAAe,IAAI,CAAC,CAAC;AAChF,YAAU;AAEV,QAAM,yBAAyB;AAE/B,SAAO;AACT;",
4
+ "sourcesContent": ["import type { BootstrapData } from './types'\nimport type { AppDiRegistrar } from '../di/container'\nimport { findAppRoot, type AppRoot } from './appResolver'\nimport { registerEntityIds } from '../encryption/entityIds'\nimport { createLogger } from '../logger'\nimport {\n ensureMikroOrmV7GeneratedCacheCompatibility,\n recoverMikroOrmV7GeneratedCacheFromImportError,\n} from './generatedCacheRecovery'\nimport { CLIENT_ONLY_STUB_NAMESPACE, createClientOnlyStubPlugin } from './clientOnlyModules'\nimport path from 'node:path'\nimport fs from 'node:fs'\nimport crypto from 'node:crypto'\nimport { createRequire } from 'node:module'\nimport { pathToFileURL } from 'node:url'\n\nlet activeBootstrapLoads = 0\nlet esbuildRuntime: typeof import('esbuild') | null = null\nlet esbuildStopPromise: Promise<void> | null = null\n\nconst logger = createLogger('shared').child({ component: 'bootstrap' })\n\nasync function getEsbuildRuntime(): Promise<typeof import('esbuild')> {\n if (esbuildStopPromise) await esbuildStopPromise\n if (esbuildRuntime) return esbuildRuntime\n\n const loadedRuntime = await import('esbuild')\n esbuildRuntime ??= loadedRuntime\n return esbuildRuntime\n}\n\nasync function withEsbuildLifecycle<T>(load: () => Promise<T>): Promise<T> {\n activeBootstrapLoads += 1\n\n try {\n return await load()\n } finally {\n activeBootstrapLoads -= 1\n if (activeBootstrapLoads === 0 && esbuildRuntime) {\n // esbuild keeps a helper process alive after build(). Bootstrap compilation\n // is a bounded phase, so release it once every concurrent loader is done.\n // A later build() call transparently starts a fresh helper process.\n const runtimeToStop = esbuildRuntime\n esbuildRuntime = null\n const stopPromise = runtimeToStop.stop().catch((err) => {\n logger.warn('Failed to stop the bootstrap compiler service', { err })\n })\n esbuildStopPromise = stopPromise\n try {\n await stopPromise\n } finally {\n if (esbuildStopPromise === stopPromise) esbuildStopPromise = null\n }\n }\n }\n}\n\n/**\n * Thrown when an expected generated source file is absent.\n *\n * Optional registries treat this as the supported compatibility case (an app\n * that never generated the file), which is what makes it distinguishable from\n * a file that exists but fails to compile or import.\n */\nclass GeneratedFileNotFoundError extends Error {\n readonly filePath: string\n\n constructor(filePath: string) {\n super(`Generated file not found: ${filePath}`)\n this.name = 'GeneratedFileNotFoundError'\n this.filePath = filePath\n }\n}\n\n/**\n * esbuild plugins for the CLI bundle, in resolution order. The client-only stub must come\n * first so it wins over the alias and external plugins for `*.client` dynamic imports.\n *\n * Exported so the wiring itself is testable: a test that only exercises\n * `createClientOnlyStubPlugin` in isolation stays green if the plugin is dropped from this\n * list, which would silently reintroduce #4623.\n */\nexport function createCliBundlePlugins(appRoot: string): import('esbuild').Plugin[] {\n // Plugin to resolve the @/ alias the way the app tsconfig maps it:\n // `@/.mercato/*` to the app root, every other `@/*` to the app's src/ directory.\n const aliasPlugin: import('esbuild').Plugin = {\n name: 'alias-resolver',\n setup(build) {\n build.onResolve({ filter: /^@\\// }, (args) => {\n const rest = args.path.slice('@/'.length)\n const bases = rest.startsWith('.mercato/')\n ? [path.join(appRoot, rest)]\n : [path.join(appRoot, 'src', rest), path.join(appRoot, rest)]\n for (const base of bases) {\n if (fs.existsSync(base) && fs.statSync(base).isFile()) {\n return { path: base }\n }\n for (const suffix of ['.ts', '.tsx', '/index.ts', '/index.tsx']) {\n if (fs.existsSync(base + suffix)) {\n return { path: base + suffix }\n }\n }\n }\n // Nothing matched \u2014 hand esbuild the literal mapping so it reports the\n // missing file against the path the app author actually wrote.\n return { path: path.join(appRoot, rest) }\n })\n },\n }\n\n // Plugin to mark non-JSON package imports as external\n const externalNonJsonPlugin: import('esbuild').Plugin = {\n name: 'external-non-json',\n setup(build) {\n // Mark all package imports as external EXCEPT JSON files\n // Filter matches paths that don't start with . or / (package imports like @open-mercato/shared)\n build.onResolve({ filter: /^[^./]/ }, (args) => {\n // Skip Windows absolute paths (e.g., C:\\...) - they're local files, not packages\n if (/^[a-zA-Z]:/.test(args.path)) {\n return null // Let esbuild handle it\n }\n // If it's a JSON file, let esbuild bundle it\n if (args.path.endsWith('.json')) {\n return null // Let esbuild handle it\n }\n // Otherwise mark as external\n return { path: args.path, external: true }\n })\n },\n }\n\n return [createClientOnlyStubPlugin(), aliasPlugin, externalNonJsonPlugin]\n}\n\nconst DYNAMIC_LOADER_CACHE_VERSION = 4\n\ntype DynamicLoaderCacheMetadata = {\n version: number\n inputHash: string\n outputHash: string\n dependencies: Record<string, string>\n}\n\nfunction cacheMetadataPath(jsPath: string): string {\n return `${jsPath}.cache.json`\n}\n\nfunction contentHash(content: Buffer | string): string {\n return crypto.createHash('sha256').update(content).digest('hex')\n}\n\nfunction parseJsonConfig(content: string): unknown {\n let normalized = ''\n let inString = false\n let escaped = false\n\n for (let index = 0; index < content.length; index += 1) {\n const character = content[index]\n const nextCharacter = content[index + 1]\n\n if (inString) {\n normalized += character\n if (escaped) {\n escaped = false\n } else if (character === '\\\\') {\n escaped = true\n } else if (character === '\"') {\n inString = false\n }\n continue\n }\n\n if (character === '\"') {\n inString = true\n normalized += character\n continue\n }\n\n if (character === '/' && nextCharacter === '/') {\n while (index < content.length && content[index] !== '\\n') index += 1\n normalized += '\\n'\n continue\n }\n\n if (character === '/' && nextCharacter === '*') {\n index += 2\n while (index < content.length && !(content[index] === '*' && content[index + 1] === '/')) {\n index += 1\n }\n index += 1\n continue\n }\n\n if (character === ',') {\n let lookahead = index + 1\n while (lookahead < content.length && /\\s/.test(content[lookahead])) lookahead += 1\n if (content[lookahead] === '}' || content[lookahead] === ']') continue\n }\n\n normalized += character\n }\n\n return JSON.parse(normalized)\n}\n\nfunction resolveExistingConfigPath(candidate: string): string | null {\n for (const configPath of [candidate, `${candidate}.json`, path.join(candidate, 'tsconfig.json')]) {\n if (fs.existsSync(configPath) && fs.statSync(configPath).isFile()) return configPath\n }\n return null\n}\n\nfunction resolvePackageConfig(configPath: string, reference: string): string | null {\n try {\n const resolved = createRequire(pathToFileURL(configPath)).resolve(reference)\n return path.extname(resolved) === '.json' ? resolved : null\n } catch {\n return null\n }\n}\n\nfunction resolveExtendedConfig(configPath: string, reference: string): string {\n if (path.isAbsolute(reference) || reference.startsWith('.')) {\n const resolved = resolveExistingConfigPath(path.resolve(path.dirname(configPath), reference))\n if (resolved) return resolved\n } else {\n for (const packageReference of [reference, `${reference}/tsconfig.json`]) {\n const resolved = resolvePackageConfig(configPath, packageReference)\n if (resolved) return resolved\n }\n }\n\n throw new Error(`[internal] TypeScript config extends target not found: ${reference}`)\n}\n\nfunction collectTsconfigPaths(entryPath: string, visited: Set<string> = new Set()): string[] {\n const configPath = path.resolve(entryPath)\n if (visited.has(configPath)) return []\n visited.add(configPath)\n\n const parsed = parseJsonConfig(fs.readFileSync(configPath, 'utf8'))\n if (typeof parsed !== 'object' || parsed === null || !('extends' in parsed)) return [configPath]\n\n const extendsValue = parsed.extends\n const references = typeof extendsValue === 'string'\n ? [extendsValue]\n : Array.isArray(extendsValue) && extendsValue.every((value) => typeof value === 'string')\n ? extendsValue\n : []\n\n return [\n ...references.flatMap((reference) => collectTsconfigPaths(\n resolveExtendedConfig(configPath, reference),\n visited,\n )),\n configPath,\n ]\n}\n\nfunction hashFilesRelativeTo(appRoot: string, filePaths: string[]): Record<string, string> {\n return Object.fromEntries(filePaths.map((filePath) => [\n path.relative(appRoot, filePath).split(path.sep).join('/'),\n contentHash(fs.readFileSync(filePath)),\n ]))\n}\n\nfunction cacheInputHash(tsPath: string, appRoot: string, tsconfigPaths: string[]): string {\n const hash = crypto.createHash('sha256')\n hash.update(JSON.stringify({\n version: DYNAMIC_LOADER_CACHE_VERSION,\n sourceHash: contentHash(fs.readFileSync(tsPath)),\n tsconfigHashes: hashFilesRelativeTo(appRoot, tsconfigPaths),\n }))\n return hash.digest('hex')\n}\n\nfunction dependenciesAreValid(appRoot: string, dependencies: Record<string, string>): boolean {\n return Object.entries(dependencies).every(([relativePath, expectedHash]) => {\n const dependencyPath = path.resolve(appRoot, relativePath)\n return fs.existsSync(dependencyPath)\n && contentHash(fs.readFileSync(dependencyPath)) === expectedHash\n })\n}\n\nfunction collectDependencyHashes(\n appRoot: string,\n inputs: Record<string, unknown>,\n): Record<string, string> {\n return Object.fromEntries(\n Object.keys(inputs)\n .filter((inputPath) => !inputPath.startsWith(`${CLIENT_ONLY_STUB_NAMESPACE}:`))\n .map((inputPath) => {\n const absolutePath = path.isAbsolute(inputPath)\n ? inputPath\n : path.resolve(appRoot, inputPath)\n const relativePath = path.relative(appRoot, absolutePath).split(path.sep).join('/')\n return [relativePath, contentHash(fs.readFileSync(absolutePath))]\n })\n .sort(([left], [right]) => left.localeCompare(right)),\n )\n}\n\nfunction readCacheMetadata(metadataPath: string): DynamicLoaderCacheMetadata | null {\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(metadataPath, 'utf8'))\n if (\n typeof parsed === 'object'\n && parsed !== null\n && 'version' in parsed\n && parsed.version === DYNAMIC_LOADER_CACHE_VERSION\n && 'inputHash' in parsed\n && typeof parsed.inputHash === 'string'\n && 'outputHash' in parsed\n && typeof parsed.outputHash === 'string'\n && 'dependencies' in parsed\n && typeof parsed.dependencies === 'object'\n && parsed.dependencies !== null\n && Object.values(parsed.dependencies).every((hash) => typeof hash === 'string')\n ) {\n return {\n version: parsed.version,\n inputHash: parsed.inputHash,\n outputHash: parsed.outputHash,\n dependencies: parsed.dependencies as Record<string, string>,\n }\n }\n } catch {\n return null\n }\n return null\n}\n\nfunction cacheIsValid(\n appRoot: string,\n jsPath: string,\n metadataPath: string,\n expectedInputHash: string,\n): boolean {\n if (!fs.existsSync(jsPath)) return false\n const metadata = readCacheMetadata(metadataPath)\n if (!metadata || metadata.inputHash !== expectedInputHash) return false\n return contentHash(fs.readFileSync(jsPath)) === metadata.outputHash\n && dependenciesAreValid(appRoot, metadata.dependencies)\n}\n\n/**\n * Options for `compileAndImport`.\n *\n * Both paths default to the generated-registry layout (`<appRoot>/.mercato/generated/<file>.ts`\n * compiled to a `.mjs` sibling). Sources that live elsewhere in the app \u2014 `src/di.ts` \u2014 MUST pass\n * both explicitly: the default app root is derived by walking three directories up from the source,\n * which only holds inside `.mercato/generated`.\n */\ntype CompileAndImportOptions = {\n appRoot?: string\n outFile?: string\n allowRecovery?: boolean\n}\n\n/**\n * Compile a TypeScript file to JavaScript using esbuild bundler.\n * This bundles the file and all its dependencies, handling JSON imports properly.\n * The compiled file is written next to the source file with a .mjs extension unless\n * `outFile` says otherwise.\n */\nasync function compileAndImport(\n tsPath: string,\n options: CompileAndImportOptions = {},\n): Promise<Record<string, unknown>> {\n const allowRecovery = options.allowRecovery ?? true\n const jsPath = options.outFile ?? tsPath.replace(/\\.ts$/, '.mjs')\n const appRoot = options.appRoot ?? path.dirname(path.dirname(path.dirname(tsPath)))\n const appTsconfig = path.join(appRoot, 'tsconfig.json')\n const metadataPath = cacheMetadataPath(jsPath)\n\n const tsExists = fs.existsSync(tsPath)\n const tsconfigExists = fs.existsSync(appTsconfig)\n\n if (!tsExists) {\n throw new GeneratedFileNotFoundError(tsPath)\n }\n if (!tsconfigExists) {\n throw new Error(`App TypeScript config not found: ${appTsconfig}`)\n }\n\n const tsconfigPaths = collectTsconfigPaths(appTsconfig)\n const expectedInputHash = cacheInputHash(tsPath, appRoot, tsconfigPaths)\n const needsCompile = !cacheIsValid(appRoot, jsPath, metadataPath, expectedInputHash)\n\n if (needsCompile) {\n fs.mkdirSync(path.dirname(jsPath), { recursive: true })\n // Dynamically import esbuild only when needed\n const esbuild = await getEsbuildRuntime()\n\n // Use esbuild.build with bundling to handle JSON imports\n const result = await esbuild.build({\n entryPoints: [tsPath],\n outfile: jsPath,\n absWorkingDir: appRoot,\n bundle: true,\n metafile: true,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n tsconfig: appTsconfig,\n plugins: createCliBundlePlugins(appRoot),\n // Allow JSON imports\n loader: { '.json': 'json' },\n })\n const metadata: DynamicLoaderCacheMetadata = {\n version: DYNAMIC_LOADER_CACHE_VERSION,\n inputHash: expectedInputHash,\n outputHash: contentHash(fs.readFileSync(jsPath)),\n dependencies: {\n ...collectDependencyHashes(appRoot, result.metafile.inputs),\n ...hashFilesRelativeTo(appRoot, tsconfigPaths),\n },\n }\n fs.writeFileSync(metadataPath, JSON.stringify(metadata))\n }\n\n // Import the compiled JavaScript\n try {\n const outputHash = contentHash(fs.readFileSync(jsPath))\n const fileUrl = `${pathToFileURL(jsPath).href}?cache=${outputHash}`\n return await import(fileUrl)\n } catch (error) {\n if (!allowRecovery) {\n throw error\n }\n\n const recovered = recoverMikroOrmV7GeneratedCacheFromImportError(appRoot, error)\n if (!recovered.applied) {\n throw error\n }\n\n return compileAndImport(tsPath, { ...options, allowRecovery: false })\n }\n}\n\n\n/**\n * Load a generated registry that older apps may not have generated yet.\n *\n * An absent source file is the supported compatibility case and resolves to\n * `fallback` quietly. Any other failure \u2014 a compile error, a broken import, a\n * runtime throw at module scope \u2014 still resolves to `fallback` so bootstrap\n * keeps working, but is reported at error level: a registry that silently\n * degrades to nothing is exactly how command interceptors stopped applying in\n * worker/CLI processes (#4327, #4491).\n */\nasync function loadOptionalGeneratedModule(\n tsPath: string,\n fallback: Record<string, unknown>,\n): Promise<Record<string, unknown>> {\n try {\n return await compileAndImport(tsPath)\n } catch (error) {\n if (error instanceof GeneratedFileNotFoundError) {\n logger.debug('Optional generated registry not present, using empty fallback', {\n file: path.basename(tsPath),\n })\n return fallback\n }\n\n logger.error('Failed to load generated registry, continuing without its entries', {\n file: path.basename(tsPath),\n filePath: tsPath,\n err: error,\n })\n return fallback\n }\n}\n\nfunction resolveAppRootOrThrow(appRoot?: string): AppRoot {\n const resolved: AppRoot | null = appRoot\n ? {\n generatedDir: path.join(appRoot, '.mercato', 'generated'),\n appDir: appRoot,\n mercatoDir: path.join(appRoot, '.mercato'),\n }\n : findAppRoot()\n\n if (!resolved) {\n throw new Error(\n 'Could not find app root with .mercato/generated directory. ' +\n 'Make sure you run this command from within a Next.js app directory, ' +\n 'or run \"yarn mercato generate\" first to create the generated files.',\n )\n }\n\n return resolved\n}\n\n/**\n * Load the app-level DI registrar (`src/di.ts`) for the dynamic bootstrap path.\n *\n * The Next.js runtime imports `@/di` statically from its own `src/bootstrap.ts` and hands the\n * registrar to `createBootstrap`. Worker, scheduler and CLI processes bootstrap through\n * `bootstrapFromAppRoot` instead, where the `@/` alias does not exist \u2014 so without this the app's\n * DI registrations silently never ran there, and every request container paid a failed\n * `import('@/di')` resolution (the compatibility fallback in `lib/di/container.ts`).\n *\n * An absent `src/di.ts` is the supported case and resolves to `null` quietly. A file that exists\n * but cannot be compiled, imported, or does not export `register` is reported at error level and\n * still resolves to `null`, so a broken app DI module degrades the same way a broken generated\n * registry does (#4327, #4491) instead of taking the whole process down.\n */\nasync function loadAppDiRegistrar(appDir: string): Promise<AppDiRegistrar | null> {\n const tsPath = path.join(appDir, 'src', 'di.ts')\n if (!fs.existsSync(tsPath)) {\n logger.debug('App-level DI module not present, skipping its registrations', { filePath: tsPath })\n return null\n }\n\n try {\n const appDiModule = await compileAndImport(tsPath, {\n appRoot: appDir,\n outFile: path.join(appDir, '.mercato', 'generated', 'app-di.compiled.mjs'),\n })\n const register = appDiModule.register\n if (typeof register !== 'function') {\n logger.error('App-level DI module exports no register(); its registrations are skipped', {\n filePath: tsPath,\n })\n return null\n }\n return register as AppDiRegistrar\n } catch (error) {\n logger.error('Failed to load the app-level DI module; its registrations are skipped', {\n filePath: tsPath,\n err: error,\n })\n return null\n }\n}\n\n/**\n * Dynamically load bootstrap data from a resolved app directory.\n *\n * IMPORTANT: This only works in unbundled contexts (CLI, tsx).\n * Do NOT use this in Next.js bundled code - use static imports instead.\n *\n * For CLI context, we skip loading modules.generated.ts which has Next.js dependencies.\n * CLI commands are discovered separately via the CLI module system.\n *\n * @param appRoot - Optional explicit app root path. If not provided, will search from cwd.\n * @returns The loaded bootstrap data\n * @throws Error if app root cannot be found or generated files are missing\n */\nasync function loadBootstrapDataWithActiveEsbuild(appRoot?: string): Promise<BootstrapData> {\n const resolved = resolveAppRootOrThrow(appRoot)\n\n const { generatedDir } = resolved\n\n ensureMikroOrmV7GeneratedCacheCompatibility(resolved.appDir)\n\n // IMPORTANT: Load entity IDs FIRST and register them before loading modules.\n // This is because modules (e.g., ce.ts files) use E.xxx.xxx at module scope,\n // and they need entity IDs to be available when they're imported.\n const entityIdsModule = await compileAndImport(path.join(generatedDir, 'entities.ids.generated.ts'))\n registerEntityIds(entityIdsModule.E as BootstrapData['entityIds'])\n\n // Now load the rest of the generated files.\n // modules.cli.generated.ts excludes Next.js-dependent code (routes, APIs, widgets)\n const [\n modulesModule,\n entitiesModule,\n diModule,\n searchModule,\n commandLoadersModule,\n commandInterceptorsModule,\n workflowsModule,\n ] = await Promise.all([\n compileAndImport(path.join(generatedDir, 'modules.cli.generated.ts')),\n compileAndImport(path.join(generatedDir, 'entities.generated.ts')),\n compileAndImport(path.join(generatedDir, 'di.generated.ts')),\n loadOptionalGeneratedModule(path.join(generatedDir, 'search.generated.ts'), { searchModuleConfigs: [] }),\n loadOptionalGeneratedModule(path.join(generatedDir, 'command-loaders.generated.ts'), { commandLoaderEntries: [] }),\n loadOptionalGeneratedModule(path.join(generatedDir, 'command-interceptors.generated.ts'), {\n commandInterceptorEntries: [],\n }),\n loadOptionalGeneratedModule(path.join(generatedDir, 'workflows.generated.ts'), { allCodeWorkflows: [] }),\n ])\n\n return {\n modules: modulesModule.modules as BootstrapData['modules'],\n entities: entitiesModule.entities as BootstrapData['entities'],\n diRegistrars: diModule.diRegistrars as BootstrapData['diRegistrars'],\n entityIds: entityIdsModule.E as BootstrapData['entityIds'],\n // Search configs are needed by workers for indexing\n searchModuleConfigs: (searchModule.searchModuleConfigs ?? []) as BootstrapData['searchModuleConfigs'],\n commandLoaderEntries: (commandLoadersModule.commandLoaderEntries ?? []) as BootstrapData['commandLoaderEntries'],\n // Command interceptors must apply in worker/CLI processes too \u2014 the\n // interceptor registry is per-process, so relying on the Next.js runtime's\n // registration silently no-ops every interceptor for queued/CLI commands\n // (#4327).\n commandInterceptorEntries: (commandInterceptorsModule.commandInterceptorEntries ??\n []) as BootstrapData['commandInterceptorEntries'],\n // Code workflow definitions are needed by workers to resume code-defined instances\n codeWorkflows: (workflowsModule.allCodeWorkflows ?? []) as BootstrapData['codeWorkflows'],\n // Empty UI-related data - not needed for CLI\n dashboardWidgetEntries: [],\n injectionWidgetEntries: [],\n injectionTables: [],\n interceptorEntries: [],\n componentOverrideEntries: [],\n }\n}\n\nexport async function loadBootstrapData(appRoot?: string): Promise<BootstrapData> {\n return withEsbuildLifecycle(() => loadBootstrapDataWithActiveEsbuild(appRoot))\n}\n\n/**\n * Create and execute bootstrap in CLI context.\n *\n * This is a convenience function that finds the app root, loads the generated\n * data dynamically, and runs bootstrap. Use this in CLI entry points.\n *\n * Returns the loaded bootstrap data so the CLI can register modules directly\n * (avoids module resolution issues when importing @open-mercato/cli/mercato).\n *\n * @param appRoot - Optional explicit app root path\n * @returns The loaded bootstrap data (modules, entities, etc.)\n */\nexport async function bootstrapFromAppRoot(appRoot?: string): Promise<BootstrapData> {\n const { createBootstrap, waitForAsyncRegistration } = await import('./factory.js')\n const resolved = resolveAppRootOrThrow(appRoot)\n // Both loads compile through esbuild, so they share one lifecycle scope: without it\n // `loadBootstrapData` releases the esbuild helper process and `loadAppDiRegistrar`\n // silently starts a second one that nothing ever stops.\n const { data, appDiRegistrar } = await withEsbuildLifecycle(async () => ({\n data: await loadBootstrapData(resolved.appDir),\n appDiRegistrar: await loadAppDiRegistrar(resolved.appDir),\n }))\n const bootstrap = createBootstrap(data, appDiRegistrar ? { appDiRegistrar } : {})\n bootstrap()\n // In CLI context, wait for async registrations (UI widgets, search configs, etc.)\n await waitForAsyncRegistration()\n\n return data\n}\n"],
5
+ "mappings": "AAEA,SAAS,mBAAiC;AAC1C,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B,kCAAkC;AACvE,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,OAAO,YAAY;AACnB,SAAS,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,IACzB,iBAAiB,CAAC;AAAA,IAClB,oBAAoB,CAAC;AAAA,IACrB,0BAA0B,CAAC;AAAA,EAC7B;AACF;AAEA,eAAsB,kBAAkB,SAA0C;AAChF,SAAO,qBAAqB,MAAM,mCAAmC,OAAO,CAAC;AAC/E;AAcA,eAAsB,qBAAqB,SAA0C;AACnF,QAAM,EAAE,iBAAiB,yBAAyB,IAAI,MAAM,OAAO,cAAc;AACjF,QAAM,WAAW,sBAAsB,OAAO;AAI9C,QAAM,EAAE,MAAM,eAAe,IAAI,MAAM,qBAAqB,aAAa;AAAA,IACvE,MAAM,MAAM,kBAAkB,SAAS,MAAM;AAAA,IAC7C,gBAAgB,MAAM,mBAAmB,SAAS,MAAM;AAAA,EAC1D,EAAE;AACF,QAAM,YAAY,gBAAgB,MAAM,iBAAiB,EAAE,eAAe,IAAI,CAAC,CAAC;AAChF,YAAU;AAEV,QAAM,yBAAyB;AAE/B,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -15,15 +15,16 @@ import { registerCommandLoaders } from "../commands/registry.js";
15
15
  import { registerNotificationHandlers } from "../notifications/handler-registry.js";
16
16
  import { clearRegisteredIntegrations, registerBundles, registerIntegrations } from "../../modules/integrations/types.js";
17
17
  import { applyComponentOverridesToEntries } from "../../modules/overrides.js";
18
- let _bootstrapped = false;
18
+ const _bootstrappedKeys = /* @__PURE__ */ new Set();
19
19
  let _asyncRegistrationPromise = null;
20
20
  function createBootstrap(data, options = {}) {
21
21
  return function bootstrap() {
22
+ const registrationKey = options.registrationKey ?? "default";
22
23
  if (options.appDiRegistrar) {
23
24
  registerAppDiRegistrar(options.appDiRegistrar);
24
25
  }
25
- if (_bootstrapped && process.env.NODE_ENV !== "development") return;
26
- _bootstrapped = true;
26
+ if (_bootstrappedKeys.has(registrationKey) && process.env.NODE_ENV !== "development") return;
27
+ _bootstrappedKeys.add(registrationKey);
27
28
  registerOrmEntities(data.entities);
28
29
  registerDiRegistrars(data.diRegistrars.filter((r) => r != null));
29
30
  registerModules(data.modules);
@@ -84,26 +85,30 @@ async function waitForAsyncRegistration() {
84
85
  }
85
86
  async function registerWidgetsAndOptionalPackages(data, options) {
86
87
  try {
87
- const [dashboardRegistry, injectionRegistry, coreInjection] = await Promise.all([
88
- import("@open-mercato/ui/backend/dashboard/widgetRegistry"),
89
- import("@open-mercato/ui/backend/injection/widgetRegistry"),
90
- import("@open-mercato/core/modules/widgets/lib/injection")
91
- ]);
92
- dashboardRegistry.registerDashboardWidgets(data.dashboardWidgetEntries);
93
- injectionRegistry.registerInjectionWidgets(data.injectionWidgetEntries);
94
- coreInjection.registerCoreInjectionWidgets(data.injectionWidgetEntries);
88
+ const coreInjection = await import("@open-mercato/core/modules/widgets/lib/injection");
89
+ if (!options.skipCoreInjectionWidgets) {
90
+ coreInjection.registerCoreInjectionWidgets(data.injectionWidgetEntries);
91
+ }
95
92
  coreInjection.registerCoreInjectionTables(data.injectionTables);
96
93
  coreInjection.registerEnabledModuleIds(
97
94
  data.modules.map((module) => module.id).filter((id) => typeof id === "string" && id.length > 0)
98
95
  );
96
+ if (!options.skipUiRegistries) {
97
+ const [dashboardRegistry, injectionRegistry] = await Promise.all([
98
+ import("@open-mercato/ui/backend/dashboard/widgetRegistry"),
99
+ import("@open-mercato/ui/backend/injection/widgetRegistry")
100
+ ]);
101
+ dashboardRegistry.registerDashboardWidgets(data.dashboardWidgetEntries);
102
+ injectionRegistry.registerInjectionWidgets(data.injectionWidgetEntries);
103
+ }
99
104
  } catch {
100
105
  }
101
106
  }
102
107
  function isBootstrapped() {
103
- return _bootstrapped;
108
+ return _bootstrappedKeys.size > 0;
104
109
  }
105
110
  function resetBootstrapState() {
106
- _bootstrapped = false;
111
+ _bootstrappedKeys.clear();
107
112
  }
108
113
  export {
109
114
  createBootstrap,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/bootstrap/factory.ts"],
4
- "sourcesContent": ["import type { BootstrapData, BootstrapOptions } from './types'\nimport { registerOrmEntities } from '../db/mikro'\nimport { registerAppDiRegistrar, registerDiRegistrars } from '../di/container'\nimport { registerModules } from '../modules/registry'\nimport { registerEntityIds } from '../encryption/entityIds'\nimport { registerEntityFields } from '../encryption/entityFields'\nimport { registerSearchModuleConfigs } from '../../modules/search'\nimport { registerAnalyticsModuleConfigs } from '../../modules/analytics'\nimport { registerCodeWorkflowEntries } from '../../modules/workflows/code-registry'\nimport { registerResponseEnrichers } from '../crud/enricher-registry'\nimport { registerApiInterceptors } from '../crud/interceptor-registry'\nimport { registerComponentOverrides } from '../../modules/widgets/component-registry'\nimport { registerMutationGuards } from '../crud/mutation-guard-store'\nimport { registerCommandInterceptors } from '../commands/command-interceptor-store'\nimport { registerCommandLoaders } from '../commands/registry'\nimport { registerNotificationHandlers } from '../notifications/handler-registry'\nimport { clearRegisteredIntegrations, registerBundles, registerIntegrations } from '../../modules/integrations/types'\nimport { applyComponentOverridesToEntries } from '../../modules/overrides'\n\nlet _bootstrapped = false\n\n// Store the async registration promise so callers can await it if needed\nlet _asyncRegistrationPromise: Promise<void> | null = null\n\n/**\n * Creates a bootstrap function that registers all application dependencies.\n *\n * The returned function should be called once at application startup.\n * In development mode, it can be called multiple times (for HMR).\n *\n * @param data - All generated registry data from .mercato/generated/\n * @param options - Optional configuration\n * @returns A bootstrap function to call at app startup\n */\nexport function createBootstrap(data: BootstrapData, options: BootstrapOptions = {}) {\n return function bootstrap(): void {\n if (options.appDiRegistrar) {\n registerAppDiRegistrar(options.appDiRegistrar)\n }\n // In development, always re-run registrations to handle HMR\n // (Module state may be reset when Turbopack reloads packages)\n if (_bootstrapped && process.env.NODE_ENV !== 'development') return\n _bootstrapped = true\n\n // === 1. Foundation: ORM entities and DI registrars ===\n registerOrmEntities(data.entities)\n registerDiRegistrars(data.diRegistrars.filter((r): r is NonNullable<typeof r> => r != null))\n\n // === 2. Modules registry (required by i18n, query engine, dashboards, CLI) ===\n registerModules(data.modules)\n clearRegisteredIntegrations()\n for (const module of data.modules) {\n if (module.integrations?.length) {\n registerIntegrations(module.integrations)\n }\n if (module.bundles?.length) {\n registerBundles(module.bundles)\n }\n }\n\n // === 3. Entity IDs (required by encryption, indexing, entity links) ===\n registerEntityIds(data.entityIds)\n\n // === 4. Entity fields registry (for encryption manager, Turbopack compatibility) ===\n if (data.entityFieldsRegistry) {\n registerEntityFields(data.entityFieldsRegistry)\n }\n\n // === 5. Search module configs (for search service registration in DI) ===\n if (data.searchModuleConfigs) {\n registerSearchModuleConfigs(data.searchModuleConfigs)\n }\n\n // === 6. Analytics module configs (for dashboard widgets and analytics API) ===\n if (data.analyticsModuleConfigs) {\n registerAnalyticsModuleConfigs(data.analyticsModuleConfigs)\n }\n\n // === 6a. Code workflow definitions (so CLI/worker processes resolve them like the app runtime) ===\n if (data.codeWorkflows?.length) {\n registerCodeWorkflowEntries(data.codeWorkflows)\n }\n\n // === 6b. Response enrichers (for CRUD response enrichment) ===\n if (data.enricherEntries) {\n registerResponseEnrichers(data.enricherEntries)\n }\n\n // === 6c. API interceptors (for CRUD route interception) ===\n if (data.interceptorEntries) {\n registerApiInterceptors(data.interceptorEntries)\n }\n\n // === 6d. Component overrides (for page/component replacement) ===\n if (data.componentOverrideEntries) {\n const finalEntries = applyComponentOverridesToEntries(data.componentOverrideEntries)\n const allOverrides = finalEntries.flatMap((entry) => entry.componentOverrides ?? [])\n registerComponentOverrides(allOverrides)\n }\n\n // === 6e. Mutation guards (for CRUD mutation lifecycle) ===\n if (data.guardEntries) {\n registerMutationGuards(data.guardEntries)\n }\n\n // === 6f. Command interceptors (for command bus lifecycle) ===\n if (data.commandInterceptorEntries) {\n registerCommandInterceptors(data.commandInterceptorEntries)\n }\n\n // === 6f.1. Command loaders (for lazy command handler registration) ===\n if (data.commandLoaderEntries) {\n registerCommandLoaders(data.commandLoaderEntries)\n }\n\n // === 6g. Notification handlers (reactive notification side-effects) ===\n if (data.notificationHandlerEntries) {\n registerNotificationHandlers(data.notificationHandlerEntries)\n }\n\n // === 7-8. UI Widgets and Optional packages (async to avoid circular deps) ===\n // Store the promise so CLI context can await it\n _asyncRegistrationPromise = registerWidgetsAndOptionalPackages(data, options)\n void _asyncRegistrationPromise\n\n options.onRegistrationComplete?.()\n }\n}\n\n/**\n * Wait for async registrations (CLI modules, widgets, etc.) to complete.\n * Call this after bootstrap() in CLI context where you need modules immediately.\n */\nexport async function waitForAsyncRegistration(): Promise<void> {\n if (_asyncRegistrationPromise) {\n await _asyncRegistrationPromise\n }\n}\n\nasync function registerWidgetsAndOptionalPackages(data: BootstrapData, options: BootstrapOptions): Promise<void> {\n // Register UI widgets (dynamic imports to avoid circular deps with ui/core packages)\n try {\n const [dashboardRegistry, injectionRegistry, coreInjection] = await Promise.all([\n import('@open-mercato/ui/backend/dashboard/widgetRegistry'),\n import('@open-mercato/ui/backend/injection/widgetRegistry'),\n import('@open-mercato/core/modules/widgets/lib/injection'),\n ])\n\n dashboardRegistry.registerDashboardWidgets(data.dashboardWidgetEntries)\n injectionRegistry.registerInjectionWidgets(data.injectionWidgetEntries)\n coreInjection.registerCoreInjectionWidgets(data.injectionWidgetEntries)\n coreInjection.registerCoreInjectionTables(data.injectionTables)\n coreInjection.registerEnabledModuleIds(\n data.modules.map((module) => module.id).filter((id): id is string => typeof id === 'string' && id.length > 0),\n )\n } catch {\n // UI packages may not be available in all contexts\n }\n\n // Note: Search module configs are registered synchronously in the main bootstrap.\n // The actual registerSearchModule() call happens in core/bootstrap.ts when the\n // DI container is created, using getSearchModuleConfigs() from the global registry.\n\n // Note: CLI module registration is handled separately in CLI context\n // via bootstrapFromAppRoot in dynamicLoader. We don't import CLI here\n // to avoid Turbopack tracing through the CLI package in Next.js context.\n}\n\n/**\n * Check if bootstrap has been called.\n */\nexport function isBootstrapped(): boolean {\n return _bootstrapped\n}\n\n/**\n * Reset bootstrap state. Useful for testing.\n */\nexport function resetBootstrapState(): void {\n _bootstrapped = false\n}\n"],
5
- "mappings": "AACA,SAAS,2BAA2B;AACpC,SAAS,wBAAwB,4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;AAAA,EAER;AASF;AAKO,SAAS,iBAA0B;AACxC,SAAO;AACT;AAKO,SAAS,sBAA4B;AAC1C,kBAAgB;AAClB;",
4
+ "sourcesContent": ["import type { BootstrapData, BootstrapOptions } from './types'\nimport { registerOrmEntities } from '../db/mikro'\nimport { registerAppDiRegistrar, registerDiRegistrars } from '../di/container'\nimport { registerModules } from '../modules/registry'\nimport { registerEntityIds } from '../encryption/entityIds'\nimport { registerEntityFields } from '../encryption/entityFields'\nimport { registerSearchModuleConfigs } from '../../modules/search'\nimport { registerAnalyticsModuleConfigs } from '../../modules/analytics'\nimport { registerCodeWorkflowEntries } from '../../modules/workflows/code-registry'\nimport { registerResponseEnrichers } from '../crud/enricher-registry'\nimport { registerApiInterceptors } from '../crud/interceptor-registry'\nimport { registerComponentOverrides } from '../../modules/widgets/component-registry'\nimport { registerMutationGuards } from '../crud/mutation-guard-store'\nimport { registerCommandInterceptors } from '../commands/command-interceptor-store'\nimport { registerCommandLoaders } from '../commands/registry'\nimport { registerNotificationHandlers } from '../notifications/handler-registry'\nimport { clearRegisteredIntegrations, registerBundles, registerIntegrations } from '../../modules/integrations/types'\nimport { applyComponentOverridesToEntries } from '../../modules/overrides'\n\nconst _bootstrappedKeys = new Set<string>()\n\n// Store the async registration promise so callers can await it if needed\nlet _asyncRegistrationPromise: Promise<void> | null = null\n\n/**\n * Creates a bootstrap function that registers all application dependencies.\n *\n * The returned function should be called once at application startup.\n * In development mode, it can be called multiple times (for HMR).\n *\n * @param data - All generated registry data from .mercato/generated/\n * @param options - Optional configuration\n * @returns A bootstrap function to call at app startup\n */\nexport function createBootstrap(data: BootstrapData, options: BootstrapOptions = {}) {\n return function bootstrap(): void {\n const registrationKey = options.registrationKey ?? 'default'\n if (options.appDiRegistrar) {\n registerAppDiRegistrar(options.appDiRegistrar)\n }\n // In development, always re-run registrations to handle HMR\n // (Module state may be reset when Turbopack reloads packages)\n if (_bootstrappedKeys.has(registrationKey) && process.env.NODE_ENV !== 'development') return\n _bootstrappedKeys.add(registrationKey)\n\n // === 1. Foundation: ORM entities and DI registrars ===\n registerOrmEntities(data.entities)\n registerDiRegistrars(data.diRegistrars.filter((r): r is NonNullable<typeof r> => r != null))\n\n // === 2. Modules registry (required by i18n, query engine, dashboards, CLI) ===\n registerModules(data.modules)\n clearRegisteredIntegrations()\n for (const module of data.modules) {\n if (module.integrations?.length) {\n registerIntegrations(module.integrations)\n }\n if (module.bundles?.length) {\n registerBundles(module.bundles)\n }\n }\n\n // === 3. Entity IDs (required by encryption, indexing, entity links) ===\n registerEntityIds(data.entityIds)\n\n // === 4. Entity fields registry (for encryption manager, Turbopack compatibility) ===\n if (data.entityFieldsRegistry) {\n registerEntityFields(data.entityFieldsRegistry)\n }\n\n // === 5. Search module configs (for search service registration in DI) ===\n if (data.searchModuleConfigs) {\n registerSearchModuleConfigs(data.searchModuleConfigs)\n }\n\n // === 6. Analytics module configs (for dashboard widgets and analytics API) ===\n if (data.analyticsModuleConfigs) {\n registerAnalyticsModuleConfigs(data.analyticsModuleConfigs)\n }\n\n // === 6a. Code workflow definitions (so CLI/worker processes resolve them like the app runtime) ===\n if (data.codeWorkflows?.length) {\n registerCodeWorkflowEntries(data.codeWorkflows)\n }\n\n // === 6b. Response enrichers (for CRUD response enrichment) ===\n if (data.enricherEntries) {\n registerResponseEnrichers(data.enricherEntries)\n }\n\n // === 6c. API interceptors (for CRUD route interception) ===\n if (data.interceptorEntries) {\n registerApiInterceptors(data.interceptorEntries)\n }\n\n // === 6d. Component overrides (for page/component replacement) ===\n if (data.componentOverrideEntries) {\n const finalEntries = applyComponentOverridesToEntries(data.componentOverrideEntries)\n const allOverrides = finalEntries.flatMap((entry) => entry.componentOverrides ?? [])\n registerComponentOverrides(allOverrides)\n }\n\n // === 6e. Mutation guards (for CRUD mutation lifecycle) ===\n if (data.guardEntries) {\n registerMutationGuards(data.guardEntries)\n }\n\n // === 6f. Command interceptors (for command bus lifecycle) ===\n if (data.commandInterceptorEntries) {\n registerCommandInterceptors(data.commandInterceptorEntries)\n }\n\n // === 6f.1. Command loaders (for lazy command handler registration) ===\n if (data.commandLoaderEntries) {\n registerCommandLoaders(data.commandLoaderEntries)\n }\n\n // === 6g. Notification handlers (reactive notification side-effects) ===\n if (data.notificationHandlerEntries) {\n registerNotificationHandlers(data.notificationHandlerEntries)\n }\n\n // === 7-8. UI Widgets and Optional packages (async to avoid circular deps) ===\n // Store the promise so CLI context can await it\n _asyncRegistrationPromise = registerWidgetsAndOptionalPackages(data, options)\n void _asyncRegistrationPromise\n\n options.onRegistrationComplete?.()\n }\n}\n\n/**\n * Wait for async registrations (CLI modules, widgets, etc.) to complete.\n * Call this after bootstrap() in CLI context where you need modules immediately.\n */\nexport async function waitForAsyncRegistration(): Promise<void> {\n if (_asyncRegistrationPromise) {\n await _asyncRegistrationPromise\n }\n}\n\nasync function registerWidgetsAndOptionalPackages(data: BootstrapData, options: BootstrapOptions): Promise<void> {\n // Register widget data required by server-side injection independently from\n // browser-facing UI registries. API-only bootstraps avoid loading @open-mercato/ui.\n try {\n const coreInjection = await import('@open-mercato/core/modules/widgets/lib/injection')\n if (!options.skipCoreInjectionWidgets) {\n coreInjection.registerCoreInjectionWidgets(data.injectionWidgetEntries)\n }\n coreInjection.registerCoreInjectionTables(data.injectionTables)\n coreInjection.registerEnabledModuleIds(\n data.modules.map((module) => module.id).filter((id): id is string => typeof id === 'string' && id.length > 0),\n )\n\n if (!options.skipUiRegistries) {\n const [dashboardRegistry, injectionRegistry] = await Promise.all([\n import('@open-mercato/ui/backend/dashboard/widgetRegistry'),\n import('@open-mercato/ui/backend/injection/widgetRegistry'),\n ])\n dashboardRegistry.registerDashboardWidgets(data.dashboardWidgetEntries)\n injectionRegistry.registerInjectionWidgets(data.injectionWidgetEntries)\n }\n } catch {\n // UI packages may not be available in all contexts\n }\n\n // Note: Search module configs are registered synchronously in the main bootstrap.\n // The actual registerSearchModule() call happens in core/bootstrap.ts when the\n // DI container is created, using getSearchModuleConfigs() from the global registry.\n\n // Note: CLI module registration is handled separately in CLI context\n // via bootstrapFromAppRoot in dynamicLoader. We don't import CLI here\n // to avoid Turbopack tracing through the CLI package in Next.js context.\n}\n\n/**\n * Check if bootstrap has been called.\n */\nexport function isBootstrapped(): boolean {\n return _bootstrappedKeys.size > 0\n}\n\n/**\n * Reset bootstrap state. Useful for testing.\n */\nexport function resetBootstrapState(): void {\n _bootstrappedKeys.clear()\n}\n"],
5
+ "mappings": "AACA,SAAS,2BAA2B;AACpC,SAAS,wBAAwB,4BAA4B;AAC7D,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAC5C,SAAS,sCAAsC;AAC/C,SAAS,mCAAmC;AAC5C,SAAS,iCAAiC;AAC1C,SAAS,+BAA+B;AACxC,SAAS,kCAAkC;AAC3C,SAAS,8BAA8B;AACvC,SAAS,mCAAmC;AAC5C,SAAS,8BAA8B;AACvC,SAAS,oCAAoC;AAC7C,SAAS,6BAA6B,iBAAiB,4BAA4B;AACnF,SAAS,wCAAwC;AAEjD,MAAM,oBAAoB,oBAAI,IAAY;AAG1C,IAAI,4BAAkD;AAY/C,SAAS,gBAAgB,MAAqB,UAA4B,CAAC,GAAG;AACnF,SAAO,SAAS,YAAkB;AAChC,UAAM,kBAAkB,QAAQ,mBAAmB;AACnD,QAAI,QAAQ,gBAAgB;AAC1B,6BAAuB,QAAQ,cAAc;AAAA,IAC/C;AAGA,QAAI,kBAAkB,IAAI,eAAe,KAAK,QAAQ,IAAI,aAAa,cAAe;AACtF,sBAAkB,IAAI,eAAe;AAGrC,wBAAoB,KAAK,QAAQ;AACjC,yBAAqB,KAAK,aAAa,OAAO,CAAC,MAAkC,KAAK,IAAI,CAAC;AAG3F,oBAAgB,KAAK,OAAO;AAC5B,gCAA4B;AAC5B,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,OAAO,cAAc,QAAQ;AAC/B,6BAAqB,OAAO,YAAY;AAAA,MAC1C;AACA,UAAI,OAA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BAAc,6BAA6B,KAAK,sBAAsB;AAAA,IACxE;AACA,kBAAc,4BAA4B,KAAK,eAAe;AAC9D,kBAAc;AAAA,MACZ,KAAK,QAAQ,IAAI,CAAC,WAAW,OAAO,EAAE,EAAE,OAAO,CAAC,OAAqB,OAAO,OAAO,YAAY,GAAG,SAAS,CAAC;AAAA,IAC9G;AAEA,QAAI,CAAC,QAAQ,kBAAkB;AAC7B,YAAM,CAAC,mBAAmB,iBAAiB,IAAI,MAAM,QAAQ,IAAI;AAAA,QAC/D,OAAO,mDAAmD;AAAA,QAC1D,OAAO,mDAAmD;AAAA,MAC5D,CAAC;AACD,wBAAkB,yBAAyB,KAAK,sBAAsB;AACtE,wBAAkB,yBAAyB,KAAK,sBAAsB;AAAA,IACxE;AAAA,EACF,QAAQ;AAAA,EAER;AASF;AAKO,SAAS,iBAA0B;AACxC,SAAO,kBAAkB,OAAO;AAClC;AAKO,SAAS,sBAA4B;AAC1C,oBAAkB,MAAM;AAC1B;",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,13 @@
1
+ import { warnOnEncryptedLikeFilter } from "./likeFilterWarning.js";
1
2
  import { decryptEntitiesWithFallbackScope } from "./subscriber.js";
2
3
  async function findWithDecryption(em, entityName, where, options, scope) {
4
+ await warnOnEncryptedLikeFilter({
5
+ em,
6
+ entityName,
7
+ where,
8
+ tenantId: scope?.tenantId,
9
+ encryptionService: scope?.encryptionService
10
+ });
3
11
  const records = await em.find(entityName, where, options);
4
12
  if (!Array.isArray(records) || records.length === 0) return records ?? [];
5
13
  await decryptEntitiesWithFallbackScope(records, {
@@ -11,6 +19,13 @@ async function findWithDecryption(em, entityName, where, options, scope) {
11
19
  return records;
12
20
  }
13
21
  async function findOneWithDecryption(em, entityName, where, options, scope) {
22
+ await warnOnEncryptedLikeFilter({
23
+ em,
24
+ entityName,
25
+ where,
26
+ tenantId: scope?.tenantId,
27
+ encryptionService: scope?.encryptionService
28
+ });
14
29
  const record = await em.findOne(entityName, where, options);
15
30
  if (!record) return record;
16
31
  await decryptEntitiesWithFallbackScope(record, {
@@ -22,6 +37,13 @@ async function findOneWithDecryption(em, entityName, where, options, scope) {
22
37
  return record;
23
38
  }
24
39
  async function findAndCountWithDecryption(em, entityName, where, options, scope) {
40
+ await warnOnEncryptedLikeFilter({
41
+ em,
42
+ entityName,
43
+ where,
44
+ tenantId: scope?.tenantId,
45
+ encryptionService: scope?.encryptionService
46
+ });
25
47
  const [recordsRaw, count] = await em.findAndCount(
26
48
  entityName,
27
49
  where,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/encryption/find.ts"],
4
- "sourcesContent": ["import type {\n EntityManager,\n EntityName,\n FilterQuery,\n FindOneOptions,\n FindOptions,\n} from '@mikro-orm/postgresql'\nimport { decryptEntitiesWithFallbackScope } from './subscriber'\nimport type { TenantDataEncryptionService } from './tenantDataEncryptionService'\n\nexport type DecryptionScope = {\n tenantId?: string | null\n organizationId?: string | null\n encryptionService?: TenantDataEncryptionService | null\n}\n\ntype AnyFindOptions<Entity extends object, Hint extends string = any> = FindOptions<Entity, Hint, any, any>\ntype AnyFindOneOptions<Entity extends object, Hint extends string = any> = FindOneOptions<Entity, Hint, any, any>\n\nexport async function findWithDecryption<Entity extends object, Hint extends string = any>(\n em: EntityManager,\n entityName: EntityName<Entity>,\n where: FilterQuery<Entity>,\n options?: AnyFindOptions<Entity, Hint>,\n scope?: DecryptionScope,\n): Promise<Entity[]> {\n const records = (await em.find<Entity, Hint, any, any>(entityName as any, where as any, options as any)) as any as\n | Entity[]\n | undefined\n if (!Array.isArray(records) || records.length === 0) return records ?? []\n await decryptEntitiesWithFallbackScope(records, {\n em,\n tenantId: scope?.tenantId ?? null,\n organizationId: scope?.organizationId ?? null,\n encryptionService: scope?.encryptionService ?? null,\n })\n return records\n}\n\nexport async function findOneWithDecryption<Entity extends object, Hint extends string = any>( // NOSONAR \u2014 returns null or decrypted entity; same variable name, different values\n em: EntityManager,\n entityName: EntityName<Entity>,\n where: FilterQuery<Entity>,\n options?: AnyFindOneOptions<Entity, Hint>,\n scope?: DecryptionScope,\n): Promise<Entity | null> {\n const record = (await em.findOne<Entity, Hint, any, any>(entityName as any, where as any, options as any)) as any as\n | Entity\n | null\n if (!record) return record\n await decryptEntitiesWithFallbackScope(record, {\n em,\n tenantId: scope?.tenantId ?? null,\n organizationId: scope?.organizationId ?? null,\n encryptionService: scope?.encryptionService ?? null,\n })\n return record\n}\n\nexport async function findAndCountWithDecryption<Entity extends object, Hint extends string = any>(\n em: EntityManager,\n entityName: EntityName<Entity>,\n where: FilterQuery<Entity>,\n options?: AnyFindOptions<Entity, Hint>,\n scope?: DecryptionScope,\n): Promise<[Entity[], number]> {\n const [recordsRaw, count] = await em.findAndCount<Entity, Hint, any, any>(\n entityName as any,\n where as any,\n options as any,\n ) as any as [Entity[] | undefined, number]\n const records = Array.isArray(recordsRaw) ? recordsRaw : []\n if (!records.length) return [records, count]\n await decryptEntitiesWithFallbackScope(records, {\n em,\n tenantId: scope?.tenantId ?? null,\n organizationId: scope?.organizationId ?? null,\n encryptionService: scope?.encryptionService ?? null,\n })\n return [records, count]\n}\n"],
5
- "mappings": "AAOA,SAAS,wCAAwC;AAYjD,eAAsB,mBACpB,IACA,YACA,OACA,SACA,OACmB;AACnB,QAAM,UAAW,MAAM,GAAG,KAA6B,YAAmB,OAAc,OAAc;AAGtG,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,EAAG,QAAO,WAAW,CAAC;AACxE,QAAM,iCAAiC,SAAS;AAAA,IAC9C;AAAA,IACA,UAAU,OAAO,YAAY;AAAA,IAC7B,gBAAgB,OAAO,kBAAkB;AAAA,IACzC,mBAAmB,OAAO,qBAAqB;AAAA,EACjD,CAAC;AACD,SAAO;AACT;AAEA,eAAsB,sBACpB,IACA,YACA,OACA,SACA,OACwB;AACxB,QAAM,SAAU,MAAM,GAAG,QAAgC,YAAmB,OAAc,OAAc;AAGxG,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,iCAAiC,QAAQ;AAAA,IAC7C;AAAA,IACA,UAAU,OAAO,YAAY;AAAA,IAC7B,gBAAgB,OAAO,kBAAkB;AAAA,IACzC,mBAAmB,OAAO,qBAAqB;AAAA,EACjD,CAAC;AACD,SAAO;AACT;AAEA,eAAsB,2BACpB,IACA,YACA,OACA,SACA,OAC6B;AAC7B,QAAM,CAAC,YAAY,KAAK,IAAI,MAAM,GAAG;AAAA,IACnC;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,QAAM,UAAU,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC;AAC1D,MAAI,CAAC,QAAQ,OAAQ,QAAO,CAAC,SAAS,KAAK;AAC3C,QAAM,iCAAiC,SAAS;AAAA,IAC9C;AAAA,IACA,UAAU,OAAO,YAAY;AAAA,IAC7B,gBAAgB,OAAO,kBAAkB;AAAA,IACzC,mBAAmB,OAAO,qBAAqB;AAAA,EACjD,CAAC;AACD,SAAO,CAAC,SAAS,KAAK;AACxB;",
4
+ "sourcesContent": ["import type {\n EntityManager,\n EntityName,\n FilterQuery,\n FindOneOptions,\n FindOptions,\n} from '@mikro-orm/postgresql'\nimport { warnOnEncryptedLikeFilter } from './likeFilterWarning'\nimport { decryptEntitiesWithFallbackScope } from './subscriber'\nimport type { TenantDataEncryptionService } from './tenantDataEncryptionService'\n\nexport type DecryptionScope = {\n tenantId?: string | null\n organizationId?: string | null\n encryptionService?: TenantDataEncryptionService | null\n}\n\ntype AnyFindOptions<Entity extends object, Hint extends string = any> = FindOptions<Entity, Hint, any, any>\ntype AnyFindOneOptions<Entity extends object, Hint extends string = any> = FindOneOptions<Entity, Hint, any, any>\n\nexport async function findWithDecryption<Entity extends object, Hint extends string = any>(\n em: EntityManager,\n entityName: EntityName<Entity>,\n where: FilterQuery<Entity>,\n options?: AnyFindOptions<Entity, Hint>,\n scope?: DecryptionScope,\n): Promise<Entity[]> {\n await warnOnEncryptedLikeFilter({\n em,\n entityName,\n where,\n tenantId: scope?.tenantId,\n encryptionService: scope?.encryptionService,\n })\n const records = (await em.find<Entity, Hint, any, any>(entityName as any, where as any, options as any)) as any as\n | Entity[]\n | undefined\n if (!Array.isArray(records) || records.length === 0) return records ?? []\n await decryptEntitiesWithFallbackScope(records, {\n em,\n tenantId: scope?.tenantId ?? null,\n organizationId: scope?.organizationId ?? null,\n encryptionService: scope?.encryptionService ?? null,\n })\n return records\n}\n\nexport async function findOneWithDecryption<Entity extends object, Hint extends string = any>( // NOSONAR \u2014 returns null or decrypted entity; same variable name, different values\n em: EntityManager,\n entityName: EntityName<Entity>,\n where: FilterQuery<Entity>,\n options?: AnyFindOneOptions<Entity, Hint>,\n scope?: DecryptionScope,\n): Promise<Entity | null> {\n await warnOnEncryptedLikeFilter({\n em,\n entityName,\n where,\n tenantId: scope?.tenantId,\n encryptionService: scope?.encryptionService,\n })\n const record = (await em.findOne<Entity, Hint, any, any>(entityName as any, where as any, options as any)) as any as\n | Entity\n | null\n if (!record) return record\n await decryptEntitiesWithFallbackScope(record, {\n em,\n tenantId: scope?.tenantId ?? null,\n organizationId: scope?.organizationId ?? null,\n encryptionService: scope?.encryptionService ?? null,\n })\n return record\n}\n\nexport async function findAndCountWithDecryption<Entity extends object, Hint extends string = any>(\n em: EntityManager,\n entityName: EntityName<Entity>,\n where: FilterQuery<Entity>,\n options?: AnyFindOptions<Entity, Hint>,\n scope?: DecryptionScope,\n): Promise<[Entity[], number]> {\n await warnOnEncryptedLikeFilter({\n em,\n entityName,\n where,\n tenantId: scope?.tenantId,\n encryptionService: scope?.encryptionService,\n })\n const [recordsRaw, count] = await em.findAndCount<Entity, Hint, any, any>(\n entityName as any,\n where as any,\n options as any,\n ) as any as [Entity[] | undefined, number]\n const records = Array.isArray(recordsRaw) ? recordsRaw : []\n if (!records.length) return [records, count]\n await decryptEntitiesWithFallbackScope(records, {\n em,\n tenantId: scope?.tenantId ?? null,\n organizationId: scope?.organizationId ?? null,\n encryptionService: scope?.encryptionService ?? null,\n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AA,IACA;AAAA,EACF;AACA,QAAM,UAAU,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC;AAC1D,MAAI,CAAC,QAAQ,OAAQ,QAAO,CAAC,SAAS,KAAK;AAC3C,QAAM,iCAAiC,SAAS;AAAA,IAC9C;AAAA,IACA,UAAU,OAAO,YAAY;AAAA,IAC7B,gBAAgB,OAAO,kBAAkB;AAAA,IACzC,mBAAmB,OAAO,qBAAqB;AAAA,EACjD,CAAC;AACD,SAAO,CAAC,SAAS,KAAK;AACxB;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,66 @@
1
+ import { warnOnCiphertextLikeFallback } from "../query/ciphertext-search-warning.js";
2
+ import { resolveTenantEncryptionService } from "./customFieldValues.js";
3
+ import { resolveEntityIdFromMetadata } from "./entityIds.js";
4
+ const LIKE_OPERATORS = /* @__PURE__ */ new Set(["$like", "$ilike", "$re", "$fulltext"]);
5
+ const LOGICAL_OPERATORS = /* @__PURE__ */ new Set(["$and", "$or", "$not", "$every", "$some", "$none"]);
6
+ const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
7
+ const isOperatorObject = (value) => {
8
+ if (!isPlainObject(value)) return false;
9
+ const keys = Object.keys(value);
10
+ return keys.length > 0 && keys.every((key) => key.startsWith("$"));
11
+ };
12
+ function walkFilter(node, field, out) {
13
+ if (Array.isArray(node)) {
14
+ for (const item of node) walkFilter(item, field, out);
15
+ return;
16
+ }
17
+ if (!isPlainObject(node)) return;
18
+ for (const [key, value] of Object.entries(node)) {
19
+ if (LIKE_OPERATORS.has(key)) {
20
+ if (field) out.add(field);
21
+ continue;
22
+ }
23
+ if (LOGICAL_OPERATORS.has(key)) {
24
+ walkFilter(value, field, out);
25
+ continue;
26
+ }
27
+ if (key.startsWith("$")) continue;
28
+ if (isOperatorObject(value)) walkFilter(value, key, out);
29
+ }
30
+ }
31
+ function collectLikeFilterFields(where) {
32
+ const found = /* @__PURE__ */ new Set();
33
+ walkFilter(where, null, found);
34
+ return Array.from(found);
35
+ }
36
+ const isWarningEnabled = () => process.env.NODE_ENV !== "production";
37
+ function resolveEntityId(em, entityName) {
38
+ const metadata = em?.getMetadata?.();
39
+ if (!metadata || typeof metadata.find !== "function") return null;
40
+ const name = typeof entityName === "string" ? entityName : entityName?.name;
41
+ if (!name) return null;
42
+ return resolveEntityIdFromMetadata(metadata.find(name) ?? void 0);
43
+ }
44
+ async function warnOnEncryptedLikeFilter(params) {
45
+ if (!isWarningEnabled()) return;
46
+ const fields = collectLikeFilterFields(params.where);
47
+ if (!fields.length) return;
48
+ try {
49
+ const entity = resolveEntityId(params.em, params.entityName);
50
+ if (!entity) return;
51
+ const service = params.encryptionService ?? resolveTenantEncryptionService(params.em);
52
+ await warnOnCiphertextLikeFallback({
53
+ entity,
54
+ fields,
55
+ tenantId: params.tenantId ?? null,
56
+ reason: "raw-orm-filter",
57
+ service
58
+ });
59
+ } catch {
60
+ }
61
+ }
62
+ export {
63
+ collectLikeFilterFields,
64
+ warnOnEncryptedLikeFilter
65
+ };
66
+ //# sourceMappingURL=likeFilterWarning.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/lib/encryption/likeFilterWarning.ts"],
4
+ "sourcesContent": ["import type { EntityManager, EntityName } from '@mikro-orm/postgresql'\nimport { warnOnCiphertextLikeFallback } from '../query/ciphertext-search-warning'\nimport { resolveTenantEncryptionService } from './customFieldValues'\nimport { resolveEntityIdFromMetadata } from './entityIds'\nimport type { TenantDataEncryptionService } from './tenantDataEncryptionService'\n\nconst LIKE_OPERATORS = new Set(['$like', '$ilike', '$re', '$fulltext'])\nconst LOGICAL_OPERATORS = new Set(['$and', '$or', '$not', '$every', '$some', '$none'])\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)\n\n// An operator object holds only `$`-prefixed keys. Anything else is a nested\n// relation filter, whose property names belong to another entity's encryption\n// map \u2014 attributing them to the root entity would produce false warnings.\nconst isOperatorObject = (value: unknown): value is Record<string, unknown> => {\n if (!isPlainObject(value)) return false\n const keys = Object.keys(value)\n return keys.length > 0 && keys.every((key) => key.startsWith('$'))\n}\n\nfunction walkFilter(node: unknown, field: string | null, out: Set<string>): void {\n if (Array.isArray(node)) {\n for (const item of node) walkFilter(item, field, out)\n return\n }\n if (!isPlainObject(node)) return\n for (const [key, value] of Object.entries(node)) {\n if (LIKE_OPERATORS.has(key)) {\n if (field) out.add(field)\n continue\n }\n if (LOGICAL_OPERATORS.has(key)) {\n walkFilter(value, field, out)\n continue\n }\n if (key.startsWith('$')) continue\n if (isOperatorObject(value)) walkFilter(value, key, out)\n }\n}\n\n/**\n * Lists the root-entity properties a filter targets with a string-matching\n * operator (`$like`, `$ilike`, `$re`, `$fulltext`), including inside\n * `$and`/`$or`/`$not` branches.\n */\nexport function collectLikeFilterFields(where: unknown): string[] {\n const found = new Set<string>()\n walkFilter(where, null, found)\n return Array.from(found)\n}\n\n// The map lookup behind the warning issues an uncached read against\n// `encryption_maps`, and this path runs on every matching query rather than in a\n// rare fallback branch \u2014 so the check stays out of production entirely.\nconst isWarningEnabled = (): boolean => process.env.NODE_ENV !== 'production'\n\nfunction resolveEntityId(em: EntityManager, entityName: EntityName<any>): string | null {\n const metadata = (em as any)?.getMetadata?.()\n if (!metadata || typeof metadata.find !== 'function') return null\n const name = typeof entityName === 'string' ? entityName : (entityName as any)?.name\n if (!name) return null\n return resolveEntityIdFromMetadata(metadata.find(name) ?? undefined)\n}\n\n/**\n * Warn, outside production, when a `where` clause matches an encrypted-at-rest\n * column with a string operator.\n *\n * Decryption happens on load, not on filter, so the predicate compares a\n * plaintext pattern against ciphertext: it matches nothing and does not raise,\n * which is indistinguishable from a genuine empty result. The query engines\n * already warn about their own `ILIKE` fallback; this covers the raw-ORM path\n * that never reaches them. Issue #5051, related to #2990.\n *\n * Never throws and never blocks the query.\n */\nexport async function warnOnEncryptedLikeFilter(params: {\n em: EntityManager\n entityName: EntityName<any>\n where: unknown\n tenantId?: string | null\n encryptionService?: TenantDataEncryptionService | null\n}): Promise<void> {\n if (!isWarningEnabled()) return\n const fields = collectLikeFilterFields(params.where)\n if (!fields.length) return\n try {\n const entity = resolveEntityId(params.em, params.entityName)\n if (!entity) return\n const service = params.encryptionService ?? resolveTenantEncryptionService(params.em)\n await warnOnCiphertextLikeFallback({\n entity,\n fields,\n tenantId: params.tenantId ?? null,\n reason: 'raw-orm-filter',\n service,\n })\n } catch {\n // A diagnostic must never break the query it is diagnosing.\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,oCAAoC;AAC7C,SAAS,sCAAsC;AAC/C,SAAS,mCAAmC;AAG5C,MAAM,iBAAiB,oBAAI,IAAI,CAAC,SAAS,UAAU,OAAO,WAAW,CAAC;AACtE,MAAM,oBAAoB,oBAAI,IAAI,CAAC,QAAQ,OAAO,QAAQ,UAAU,SAAS,OAAO,CAAC;AAErF,MAAM,gBAAgB,CAAC,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,KAAK,EAAE,iBAAiB;AAK7F,MAAM,mBAAmB,CAAC,UAAqD;AAC7E,MAAI,CAAC,cAAc,KAAK,EAAG,QAAO;AAClC,QAAM,OAAO,OAAO,KAAK,KAAK;AAC9B,SAAO,KAAK,SAAS,KAAK,KAAK,MAAM,CAAC,QAAQ,IAAI,WAAW,GAAG,CAAC;AACnE;AAEA,SAAS,WAAW,MAAe,OAAsB,KAAwB;AAC/E,MAAI,MAAM,QAAQ,IAAI,GAAG;AACvB,eAAW,QAAQ,KAAM,YAAW,MAAM,OAAO,GAAG;AACpD;AAAA,EACF;AACA,MAAI,CAAC,cAAc,IAAI,EAAG;AAC1B,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG;AAC/C,QAAI,eAAe,IAAI,GAAG,GAAG;AAC3B,UAAI,MAAO,KAAI,IAAI,KAAK;AACxB;AAAA,IACF;AACA,QAAI,kBAAkB,IAAI,GAAG,GAAG;AAC9B,iBAAW,OAAO,OAAO,GAAG;AAC5B;AAAA,IACF;AACA,QAAI,IAAI,WAAW,GAAG,EAAG;AACzB,QAAI,iBAAiB,KAAK,EAAG,YAAW,OAAO,KAAK,GAAG;AAAA,EACzD;AACF;AAOO,SAAS,wBAAwB,OAA0B;AAChE,QAAM,QAAQ,oBAAI,IAAY;AAC9B,aAAW,OAAO,MAAM,KAAK;AAC7B,SAAO,MAAM,KAAK,KAAK;AACzB;AAKA,MAAM,mBAAmB,MAAe,QAAQ,IAAI,aAAa;AAEjE,SAAS,gBAAgB,IAAmB,YAA4C;AACtF,QAAM,WAAY,IAAY,cAAc;AAC5C,MAAI,CAAC,YAAY,OAAO,SAAS,SAAS,WAAY,QAAO;AAC7D,QAAM,OAAO,OAAO,eAAe,WAAW,aAAc,YAAoB;AAChF,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,4BAA4B,SAAS,KAAK,IAAI,KAAK,MAAS;AACrE;AAcA,eAAsB,0BAA0B,QAM9B;AAChB,MAAI,CAAC,iBAAiB,EAAG;AACzB,QAAM,SAAS,wBAAwB,OAAO,KAAK;AACnD,MAAI,CAAC,OAAO,OAAQ;AACpB,MAAI;AACF,UAAM,SAAS,gBAAgB,OAAO,IAAI,OAAO,UAAU;AAC3D,QAAI,CAAC,OAAQ;AACb,UAAM,UAAU,OAAO,qBAAqB,+BAA+B,OAAO,EAAE;AACpF,UAAM,6BAA6B;AAAA,MACjC;AAAA,MACA;AAAA,MACA,UAAU,OAAO,YAAY;AAAA,MAC7B,QAAQ;AAAA,MACR;AAAA,IACF,CAAC;AAAA,EACH,QAAQ;AAAA,EAER;AACF;",
6
+ "names": []
7
+ }
@@ -15,9 +15,14 @@ function setCachedDictionary(locale, dict) {
15
15
  function invalidateDictionaryCache() {
16
16
  getCache().clear();
17
17
  }
18
+ function invalidateDictionaryCacheLocales(locales) {
19
+ const cache = getCache();
20
+ for (const locale of locales) cache.delete(locale);
21
+ }
18
22
  export {
19
23
  getCachedDictionary,
20
24
  invalidateDictionaryCache,
25
+ invalidateDictionaryCacheLocales,
21
26
  setCachedDictionary
22
27
  };
23
28
  //# sourceMappingURL=dictionary-cache.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/i18n/dictionary-cache.ts"],
4
- "sourcesContent": ["import type { Locale } from './config'\nimport type { Dict } from './context'\n\n// Process-level cache of flattened, module-merged translation dictionaries\n// keyed by locale. Locale dictionaries are immutable at runtime, so the\n// flatten+merge work in loadDictionary() only needs to run once per locale.\n//\n// Stored on globalThis for the same reason the module registry is: tsx/esbuild\n// can load this file as multiple module instances when mixing dynamic and\n// static imports, and the cache plus its invalidation must stay coherent across\n// those instances. See ../modules/registry.ts for the original workaround.\nconst GLOBAL_KEY = '__openMercatoI18nDictionaryCache__'\n\nfunction getCache(): Map<Locale, Dict> {\n const globalScope = globalThis as any\n if (!globalScope[GLOBAL_KEY]) {\n globalScope[GLOBAL_KEY] = new Map<Locale, Dict>()\n }\n return globalScope[GLOBAL_KEY]\n}\n\nexport function getCachedDictionary(locale: Locale): Dict | undefined {\n return getCache().get(locale)\n}\n\nexport function setCachedDictionary(locale: Locale, dict: Dict): void {\n getCache().set(locale, dict)\n}\n\n// Invalidate every cached locale dictionary. Called whenever the inputs to a\n// dictionary build change: module registration (module translations) and the\n// app dictionary loader registration (base translations).\nexport function invalidateDictionaryCache(): void {\n getCache().clear()\n}\n"],
5
- "mappings": "AAWA,MAAM,aAAa;AAEnB,SAAS,WAA8B;AACrC,QAAM,cAAc;AACpB,MAAI,CAAC,YAAY,UAAU,GAAG;AAC5B,gBAAY,UAAU,IAAI,oBAAI,IAAkB;AAAA,EAClD;AACA,SAAO,YAAY,UAAU;AAC/B;AAEO,SAAS,oBAAoB,QAAkC;AACpE,SAAO,SAAS,EAAE,IAAI,MAAM;AAC9B;AAEO,SAAS,oBAAoB,QAAgB,MAAkB;AACpE,WAAS,EAAE,IAAI,QAAQ,IAAI;AAC7B;AAKO,SAAS,4BAAkC;AAChD,WAAS,EAAE,MAAM;AACnB;",
4
+ "sourcesContent": ["import type { Locale } from './config'\nimport type { Dict } from './context'\n\n// Process-level cache of flattened, module-merged translation dictionaries\n// keyed by locale. Locale dictionaries are immutable at runtime, so the\n// flatten+merge work in loadDictionary() only needs to run once per locale.\n//\n// Stored on globalThis for the same reason the module registry is: tsx/esbuild\n// can load this file as multiple module instances when mixing dynamic and\n// static imports, and the cache plus its invalidation must stay coherent across\n// those instances. See ../modules/registry.ts for the original workaround.\nconst GLOBAL_KEY = '__openMercatoI18nDictionaryCache__'\n\nfunction getCache(): Map<Locale, Dict> {\n const globalScope = globalThis as any\n if (!globalScope[GLOBAL_KEY]) {\n globalScope[GLOBAL_KEY] = new Map<Locale, Dict>()\n }\n return globalScope[GLOBAL_KEY]\n}\n\nexport function getCachedDictionary(locale: Locale): Dict | undefined {\n return getCache().get(locale)\n}\n\nexport function setCachedDictionary(locale: Locale, dict: Dict): void {\n getCache().set(locale, dict)\n}\n\n// Invalidate every cached locale dictionary. Called whenever the inputs to a\n// dictionary build change: module registration (module translations) and the\n// app dictionary loader registration (base translations).\nexport function invalidateDictionaryCache(): void {\n getCache().clear()\n}\n\nexport function invalidateDictionaryCacheLocales(locales: readonly Locale[]): void {\n const cache = getCache()\n for (const locale of locales) cache.delete(locale)\n}\n"],
5
+ "mappings": "AAWA,MAAM,aAAa;AAEnB,SAAS,WAA8B;AACrC,QAAM,cAAc;AACpB,MAAI,CAAC,YAAY,UAAU,GAAG;AAC5B,gBAAY,UAAU,IAAI,oBAAI,IAAkB;AAAA,EAClD;AACA,SAAO,YAAY,UAAU;AAC/B;AAEO,SAAS,oBAAoB,QAAkC;AACpE,SAAO,SAAS,EAAE,IAAI,MAAM;AAC9B;AAEO,SAAS,oBAAoB,QAAgB,MAAkB;AACpE,WAAS,EAAE,IAAI,QAAQ,IAAI;AAC7B;AAKO,SAAS,4BAAkC;AAChD,WAAS,EAAE,MAAM;AACnB;AAEO,SAAS,iCAAiC,SAAkC;AACjF,QAAM,QAAQ,SAAS;AACvB,aAAW,UAAU,QAAS,OAAM,OAAO,MAAM;AACnD;",
6
6
  "names": []
7
7
  }