@open-mercato/shared 0.6.7-develop.6860.1.f796b22e80 → 0.6.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/AGENTS.md +6 -57
- package/build.mjs +4 -2
- package/dist/lib/auth/server.js +2 -15
- package/dist/lib/auth/server.js.map +2 -2
- package/dist/lib/bootstrap/dynamicLoader.js +43 -117
- package/dist/lib/bootstrap/dynamicLoader.js.map +2 -2
- package/dist/lib/commands/command-bus.js +1 -5
- package/dist/lib/commands/command-bus.js.map +2 -2
- package/dist/lib/commands/command-interceptor-runner.js +2 -2
- package/dist/lib/commands/command-interceptor-runner.js.map +2 -2
- package/dist/lib/crud/enricher-runner.js +11 -2
- package/dist/lib/crud/enricher-runner.js.map +2 -2
- package/dist/lib/crud/factory.js +4 -63
- package/dist/lib/crud/factory.js.map +2 -2
- package/dist/lib/crud/interceptor-runner.js +2 -2
- package/dist/lib/crud/interceptor-runner.js.map +2 -2
- package/dist/lib/crud/mutation-guard-registry.js +2 -2
- package/dist/lib/crud/mutation-guard-registry.js.map +2 -2
- package/dist/lib/crud/types.js +0 -4
- package/dist/lib/crud/types.js.map +3 -3
- package/dist/lib/data/engine.js +11 -37
- package/dist/lib/data/engine.js.map +2 -2
- package/dist/lib/db/mikro.js +12 -3
- package/dist/lib/db/mikro.js.map +2 -2
- package/dist/lib/db/pg-errors.js +0 -42
- package/dist/lib/db/pg-errors.js.map +2 -2
- package/dist/lib/di/container.js +6 -48
- package/dist/lib/di/container.js.map +2 -2
- package/dist/lib/email/send.js +0 -56
- package/dist/lib/email/send.js.map +2 -2
- package/dist/lib/encryption/subscriber.js +10 -2
- package/dist/lib/encryption/subscriber.js.map +2 -2
- package/dist/lib/encryption/tenantDataEncryptionService.js +17 -52
- package/dist/lib/encryption/tenantDataEncryptionService.js.map +2 -2
- package/dist/lib/i18n/config.js +1 -1
- package/dist/lib/i18n/config.js.map +2 -2
- package/dist/lib/i18n/server.js +4 -4
- package/dist/lib/i18n/server.js.map +3 -3
- package/dist/lib/logger/index.js +3 -47
- package/dist/lib/logger/index.js.map +3 -3
- package/dist/lib/modules/registry.js +1 -5
- package/dist/lib/modules/registry.js.map +2 -2
- package/dist/lib/query/engine.js +40 -54
- package/dist/lib/query/engine.js.map +2 -2
- package/dist/lib/query/types.js.map +1 -1
- package/dist/lib/redis/connection.js +2 -7
- package/dist/lib/redis/connection.js.map +2 -2
- package/dist/lib/search/config.js +2 -61
- package/dist/lib/search/config.js.map +2 -2
- package/dist/lib/search/tokenize.js +11 -23
- package/dist/lib/search/tokenize.js.map +2 -2
- package/dist/lib/version.js +1 -1
- package/dist/lib/version.js.map +1 -1
- package/dist/lib/webhooks/index.js +1 -13
- package/dist/lib/webhooks/index.js.map +2 -2
- package/dist/lib/webhooks/verify.js +7 -12
- package/dist/lib/webhooks/verify.js.map +2 -2
- package/dist/modules/analytics.js.map +2 -2
- package/dist/modules/overrides.js +1 -50
- package/dist/modules/overrides.js.map +2 -2
- package/dist/modules/payment_gateways/types.js +1 -8
- package/dist/modules/payment_gateways/types.js.map +2 -2
- package/dist/modules/registry.js +0 -1
- package/dist/modules/registry.js.map +2 -2
- package/dist/security/enabledModulesRegistry.js +11 -56
- package/dist/security/enabledModulesRegistry.js.map +2 -2
- package/jest.config.cjs +1 -2
- package/package.json +9 -19
- package/src/lib/ai/llm-provider.ts +0 -33
- package/src/lib/auth/__tests__/server.test.ts +0 -23
- package/src/lib/auth/server.ts +2 -23
- package/src/lib/bootstrap/__tests__/dynamicLoader.commandInterceptors.test.ts +8 -63
- package/src/lib/bootstrap/__tests__/dynamicLoader.tsconfig.test.ts +1 -21
- package/src/lib/bootstrap/dynamicLoader.ts +65 -213
- package/src/lib/commands/__tests__/command-interceptor-runner.test.ts +0 -28
- package/src/lib/commands/command-bus.ts +1 -5
- package/src/lib/commands/command-interceptor-runner.ts +2 -2
- package/src/lib/crud/__tests__/crud-factory.test.ts +0 -298
- package/src/lib/crud/__tests__/mutation-guard-registry.test.ts +0 -26
- package/src/lib/crud/enricher-runner.ts +11 -2
- package/src/lib/crud/factory.ts +1 -69
- package/src/lib/crud/interceptor-runner.ts +2 -2
- package/src/lib/crud/mutation-guard-registry.ts +2 -2
- package/src/lib/crud/types.ts +0 -3
- package/src/lib/data/__tests__/engine.bulk-suppress.test.ts +3 -18
- package/src/lib/data/engine.ts +16 -50
- package/src/lib/db/__tests__/mikro.test.ts +25 -0
- package/src/lib/db/mikro.ts +38 -13
- package/src/lib/db/pg-errors.ts +0 -58
- package/src/lib/di/container.ts +8 -72
- package/src/lib/email/__tests__/send.test.ts +1 -37
- package/src/lib/email/send.ts +0 -79
- package/src/lib/encryption/__tests__/subscriber.test.ts +2 -54
- package/src/lib/encryption/__tests__/tenantDataEncryptionService.test.ts +0 -58
- package/src/lib/encryption/subscriber.ts +14 -2
- package/src/lib/encryption/tenantDataEncryptionService.ts +18 -64
- package/src/lib/i18n/config.ts +2 -2
- package/src/lib/i18n/server.ts +2 -6
- package/src/lib/logger/__tests__/logger.test.ts +0 -77
- package/src/lib/logger/index.ts +1 -59
- package/src/lib/modules/registry.ts +0 -10
- package/src/lib/query/__tests__/engine.test.ts +13 -65
- package/src/lib/query/engine.ts +58 -75
- package/src/lib/query/types.ts +5 -4
- package/src/lib/redis/__tests__/connection.test.ts +0 -16
- package/src/lib/redis/connection.ts +7 -10
- package/src/lib/search/__tests__/config.test.ts +0 -177
- package/src/lib/search/config.ts +8 -106
- package/src/lib/search/tokenize.ts +11 -33
- package/src/lib/webhooks/__tests__/verify.test.ts +1 -20
- package/src/lib/webhooks/index.ts +1 -19
- package/src/lib/webhooks/verify.ts +9 -17
- package/src/modules/__tests__/registry.test.ts +2 -10
- package/src/modules/analytics.ts +0 -7
- package/src/modules/customer-auth.ts +0 -1
- package/src/modules/encryption.ts +0 -3
- package/src/modules/navigation/backendChrome.ts +0 -15
- package/src/modules/overrides.ts +0 -103
- package/src/modules/payment_gateways/types.ts +0 -41
- package/src/modules/registry.ts +0 -3
- package/src/security/enabledModulesRegistry.ts +12 -64
- package/dist/lib/ai/safety-identifier.js +0 -32
- package/dist/lib/ai/safety-identifier.js.map +0 -7
- package/dist/lib/auth/organizationScope.js +0 -34
- package/dist/lib/auth/organizationScope.js.map +0 -7
- package/dist/lib/bootstrap/clientOnlyModules.js +0 -55
- package/dist/lib/bootstrap/clientOnlyModules.js.map +0 -7
- package/dist/lib/data/consistency.js +0 -19
- package/dist/lib/data/consistency.js.map +0 -7
- package/dist/lib/db/entityMetadata.js +0 -26
- package/dist/lib/db/entityMetadata.js.map +0 -7
- package/dist/lib/logger/extension.js +0 -29
- package/dist/lib/logger/extension.js.map +0 -7
- package/dist/lib/modules/surfaceFingerprint.js +0 -47
- package/dist/lib/modules/surfaceFingerprint.js.map +0 -7
- package/dist/lib/query/ciphertext-search-warning.js +0 -45
- package/dist/lib/query/ciphertext-search-warning.js.map +0 -7
- package/dist/lib/search/auto-indexing.js +0 -14
- package/dist/lib/search/auto-indexing.js.map +0 -7
- package/dist/lib/search/availability.js +0 -107
- package/dist/lib/search/availability.js.map +0 -7
- package/dist/lib/search/tokenLookup.js +0 -46
- package/dist/lib/search/tokenLookup.js.map +0 -7
- package/dist/lib/telemetry/runtime.js +0 -35
- package/dist/lib/telemetry/runtime.js.map +0 -7
- package/dist/lib/webhooks/body.js +0 -57
- package/dist/lib/webhooks/body.js.map +0 -7
- package/dist/lib/webhooks/inbound-types.js +0 -1
- package/dist/lib/webhooks/inbound-types.js.map +0 -7
- package/dist/modules/widgets/extension-points.js +0 -96
- package/dist/modules/widgets/extension-points.js.map +0 -7
- package/dist/security/featurePolicy.js +0 -62
- package/dist/security/featurePolicy.js.map +0 -7
- package/scripts/versionSource.cjs +0 -65
- package/src/lib/__tests__/versionSource.test.ts +0 -46
- package/src/lib/ai/__tests__/llm-provider-contract.test.ts +0 -59
- package/src/lib/ai/__tests__/safety-identifier.test.ts +0 -71
- package/src/lib/ai/safety-identifier.ts +0 -73
- package/src/lib/auth/__tests__/organizationScope.test.ts +0 -107
- package/src/lib/auth/organizationScope.ts +0 -65
- package/src/lib/bootstrap/__tests__/clientOnlyModules.test.ts +0 -189
- package/src/lib/bootstrap/__tests__/dynamicLoader.aliasResolver.test.ts +0 -98
- package/src/lib/bootstrap/__tests__/dynamicLoader.appDi.test.ts +0 -211
- package/src/lib/bootstrap/__tests__/dynamicLoader.generatedCacheRecovery.test.ts +0 -192
- package/src/lib/bootstrap/clientOnlyModules.ts +0 -85
- package/src/lib/crud/__tests__/crud-factory.cache-user-scope.test.ts +0 -171
- package/src/lib/data/__tests__/consistency.test.ts +0 -38
- package/src/lib/data/consistency.ts +0 -17
- package/src/lib/db/__tests__/entityMetadata.test.ts +0 -38
- package/src/lib/db/__tests__/pg-errors.test.ts +0 -48
- package/src/lib/db/entityMetadata.ts +0 -43
- package/src/lib/di/__tests__/container-app-di-absent.test.ts +0 -155
- package/src/lib/di/__tests__/container-app-di.test.ts +0 -173
- package/src/lib/di/__tests__/registrar-error-log.test.ts +0 -154
- package/src/lib/i18n/__tests__/config.test.ts +0 -8
- package/src/lib/i18n/__tests__/server-dictionary-cache.test.ts +0 -30
- package/src/lib/i18n/__tests__/server-unbootstrapped.test.ts +0 -29
- package/src/lib/logger/extension.ts +0 -59
- package/src/lib/modules/__tests__/surfaceFingerprint.test.ts +0 -122
- package/src/lib/modules/surfaceFingerprint.ts +0 -87
- package/src/lib/query/__tests__/ciphertext-search-warning.test.ts +0 -178
- package/src/lib/query/ciphertext-search-warning.ts +0 -95
- package/src/lib/search/__tests__/availability.test.ts +0 -211
- package/src/lib/search/__tests__/tokenLookup.test.ts +0 -206
- package/src/lib/search/__tests__/tokenize.test.ts +0 -49
- package/src/lib/search/auto-indexing.ts +0 -22
- package/src/lib/search/availability.ts +0 -232
- package/src/lib/search/tokenLookup.ts +0 -133
- package/src/lib/telemetry/runtime.ts +0 -72
- package/src/lib/webhooks/__tests__/body.test.ts +0 -95
- package/src/lib/webhooks/body.ts +0 -70
- package/src/lib/webhooks/inbound-types.ts +0 -125
- package/src/modules/__tests__/nav-group-order-override.test.ts +0 -183
- package/src/modules/payment_gateways/__tests__/types.test.ts +0 -37
- package/src/modules/widgets/__tests__/extension-points.test.ts +0 -101
- package/src/modules/widgets/extension-points.ts +0 -524
- package/src/security/__tests__/featurePolicy.test.ts +0 -166
- package/src/security/featurePolicy.ts +0 -89
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/modules/registry.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ReactNode } from 'react'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi/types'\nimport type { SyncCrudEventResult } from '../lib/crud/sync-event-types'\nimport type { DashboardWidgetModule } from './dashboard/widgets'\nimport type { InjectionAnyWidgetModule, ModuleInjectionTable } from './widgets/injection'\nimport type { IntegrationBundle, IntegrationDefinition } from './integrations/types'\nimport { createLogger } from '../lib/logger'\nimport {\n applyApiOverridesToManifests,\n applyModuleOverridesToModules,\n applyPageOverridesToManifests,\n composeApiRouteOverrides,\n composePageRouteOverrides,\n} from './overrides'\n\nconst logger = createLogger('shared').child({ component: 'cli-registry' })\n\n// Context passed to dynamic metadata guards\nexport type RouteVisibilityContext = { path?: string; auth?: any }\n\n/**\n * Portal sidebar navigation hint. When declared on a portal page's metadata,\n * the page is auto-listed in the portal sidebar (subject to RBAC) by the\n * `/api/customer_accounts/portal/nav` endpoint.\n *\n * Absence of `nav` means the page is routable but not auto-listed (useful for\n * detail pages, create forms, etc.).\n */\nexport type PortalNavMetadata = {\n label: string\n labelKey?: string\n group?: 'main' | 'account'\n order?: number\n icon?: string\n}\n\n// Metadata you can export from page.meta.ts or directly from a server page\nexport type PageMetadata = {\n requireAuth?: boolean\n /** @deprecated Use `requireFeatures` instead \u2014 role names are mutable and can be spoofed */\n requireRoles?: readonly string[]\n // Optional fine-grained feature requirements\n requireFeatures?: readonly string[]\n // Portal: require customer (portal user) authentication instead of staff auth\n requireCustomerAuth?: boolean\n // Portal: require customer-specific features (checked against CustomerRbacService)\n requireCustomerFeatures?: readonly string[]\n // Portal: optional sidebar presentation hint (auto-listed by portal nav endpoint)\n nav?: PortalNavMetadata\n // Titles and grouping (aliases supported)\n title?: string\n titleKey?: string\n pageTitle?: string\n pageTitleKey?: string\n group?: string\n groupKey?: string\n pageGroup?: string\n pageGroupKey?: string\n // Ordering and visuals\n order?: number\n pageOrder?: number\n priority?: number\n pagePriority?: number\n icon?: ReactNode\n navHidden?: boolean\n // Dynamic flags\n visible?: (ctx: RouteVisibilityContext) => boolean | Promise<boolean>\n enabled?: (ctx: RouteVisibilityContext) => boolean | Promise<boolean>\n // Optional static breadcrumb trail for header\n breadcrumb?: Array<{ label: string; labelKey?: string; href?: string }>\n // Navigation context for tiered navigation:\n // - 'main' (default): Main sidebar business operations\n // - 'admin': Collapsible \"Settings & Admin\" section at bottom of sidebar\n // - 'settings': Hidden from sidebar, only accessible via Settings hub page\n // - 'profile': Profile dropdown items\n pageContext?: 'main' | 'admin' | 'settings' | 'profile'\n placement?: {\n section: string\n sectionLabel?: string\n sectionLabelKey?: string\n order?: number\n }\n}\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\nexport type ApiHandler = (req: Request, ctx?: any) => Promise<Response> | Response\n\nexport type ModuleSubscriberHandler = (\n payload: any,\n ctx: any\n) => Promise<void | SyncCrudEventResult> | void | SyncCrudEventResult\n\nexport type ModuleWorkerHandler = (job: unknown, ctx: unknown) => Promise<void> | void\n\nexport type ModuleRoute = {\n pattern?: string\n path?: string\n requireAuth?: boolean\n /** @deprecated Use `requireFeatures` instead \u2014 role names are mutable and can be spoofed */\n requireRoles?: string[]\n // Optional fine-grained feature requirements\n requireFeatures?: string[]\n // Portal: require customer (portal user) authentication instead of staff auth\n requireCustomerAuth?: boolean\n // Portal: require customer-specific features (checked against CustomerRbacService)\n requireCustomerFeatures?: string[]\n // Portal: optional sidebar presentation hint (auto-listed by portal nav endpoint)\n nav?: PortalNavMetadata\n title?: string\n titleKey?: string\n group?: string\n groupKey?: string\n icon?: ReactNode\n order?: number\n priority?: number\n navHidden?: boolean\n visible?: (ctx: RouteVisibilityContext) => boolean | Promise<boolean>\n enabled?: (ctx: RouteVisibilityContext) => boolean | Promise<boolean>\n breadcrumb?: Array<{ label: string; labelKey?: string; href?: string }>\n pageContext?: 'main' | 'admin' | 'settings' | 'profile'\n placement?: {\n section: string\n sectionLabel?: string\n sectionLabelKey?: string\n order?: number\n }\n Component: (props: any) => ReactNode | Promise<ReactNode>\n}\n\nexport type ModuleRouteMetadata = Omit<ModuleRoute, 'Component'>\n\nexport type ModuleApiLegacy = {\n method: HttpMethod\n path: string\n handler: ApiHandler\n metadata?: Record<string, unknown>\n docs?: OpenApiMethodDoc\n}\n\nexport type ModuleApiRouteFile = {\n path: string\n handlers: Partial<Record<HttpMethod, ApiHandler>>\n requireAuth?: boolean\n /** @deprecated Use `requireFeatures` instead \u2014 role names are mutable and can be spoofed */\n requireRoles?: string[]\n // Optional fine-grained feature requirements for the entire route file\n // Note: per-method feature requirements should be expressed inside metadata\n requireFeatures?: string[]\n docs?: OpenApiRouteDoc\n metadata?: Partial<Record<HttpMethod, unknown>>\n}\n\nexport type ModuleApi = ModuleApiLegacy | ModuleApiRouteFile\n\nexport type RouteMatchParams = Record<string, string | string[]>\n\nexport type FrontendRouteManifestEntry = Omit<ModuleRoute, 'Component'> & {\n moduleId: string\n load: () => Promise<ModuleRoute['Component']>\n}\n\nexport type BackendRouteManifestEntry = Omit<ModuleRoute, 'Component'> & {\n moduleId: string\n load: () => Promise<ModuleRoute['Component']>\n}\n\nexport type ApiRouteManifestEntry = {\n moduleId: string\n kind: 'route-file' | 'legacy'\n path: string\n methods: HttpMethod[]\n method?: HttpMethod\n load: () => Promise<Record<string, unknown>>\n}\n\nexport type ModuleCli = {\n command: string\n run: (argv: string[]) => Promise<void> | void\n}\n\nexport type ModuleSubscriber = {\n id: string\n moduleId?: string\n event: string\n persistent?: boolean\n sync?: boolean\n priority?: number\n handler: ModuleSubscriberHandler\n}\n\nexport type ModuleWorker = {\n id: string\n moduleId?: string\n queue: string\n concurrency: number\n lockDuration?: number\n maxStalledCount?: number\n handler: ModuleWorkerHandler\n}\n\nexport type ModuleInfo = {\n name?: string\n title?: string\n version?: string\n description?: string\n author?: string\n license?: string\n homepage?: string\n copyright?: string\n // Optional hard dependencies: module ids that must be enabled\n requires?: string[]\n // Whether this module can be ejected into the app's src/modules/ for customization\n ejectable?: boolean\n}\n\nexport type ModuleDashboardWidgetEntry = {\n moduleId: string\n key: string\n source: 'app' | 'package'\n loader: () => Promise<DashboardWidgetModule<any>>\n}\n\nexport type ModuleInjectionWidgetEntry = {\n moduleId: string\n key: string\n source: 'app' | 'package'\n widgetId?: string\n loader: () => Promise<InjectionAnyWidgetModule<any, any>>\n}\n\nexport type Module = {\n id: string\n info?: ModuleInfo\n backendRoutes?: ModuleRoute[]\n frontendRoutes?: ModuleRoute[]\n apis?: ModuleApi[]\n cli?: ModuleCli[]\n translations?: Record<string, Record<string, string>>\n // Optional: per-module feature declarations discovered from acl.ts (module root)\n features?: Array<{ id: string; title: string; module: string }>\n // Auto-discovered event subscribers\n subscribers?: ModuleSubscriber[]\n // Auto-discovered queue workers\n workers?: ModuleWorker[]\n // Optional: per-module declared entity extensions and custom fields (static)\n // Extensions discovered from data/extensions.ts; Custom fields discovered from ce.ts (entities[].fields)\n entityExtensions?: import('./entities').EntityExtension[]\n customFieldSets?: import('./entities').CustomFieldSet[]\n // Optional: per-module declared custom entities (virtual/logical entities)\n // Discovered from ce.ts (module root). Each entry represents an entityId with optional label/description.\n customEntities?: Array<{ id: string; label?: string; description?: string }>\n dashboardWidgets?: ModuleDashboardWidgetEntry[]\n injectionWidgets?: ModuleInjectionWidgetEntry[]\n injectionTable?: ModuleInjectionTable\n // Optional: per-module vector search configuration (discovered from vector.ts)\n vector?: import('./vector').VectorModuleConfig\n // Optional: module-specific tenant setup configuration (from setup.ts)\n setup?: import('./setup').ModuleSetupConfig\n // Optional: default encryption maps owned by the module (from encryption.ts)\n defaultEncryptionMaps?: import('./encryption').ModuleEncryptionMap[]\n // Optional: integration marketplace declarations discovered from integration.ts\n integrations?: IntegrationDefinition[]\n bundles?: IntegrationBundle[]\n}\n\nfunction normPath(s: string) {\n return (s.startsWith('/') ? s : '/' + s).replace(/\\/+$/, '') || '/'\n}\n\n// 0 = literal (most specific), 1 = dynamic [param], 2 = catch-all [...param] or [[...param]]\nfunction segmentSpecificity(seg: string): 0 | 1 | 2 {\n if (seg.startsWith('[[...') || seg.startsWith('[...')) return 2\n if (seg.startsWith('[')) return 1\n return 0\n}\n\nfunction compareRouteSpecificity(aPattern: string, bPattern: string): number {\n const aSegs = aPattern.split('/')\n const bSegs = bPattern.split('/')\n const len = Math.max(aSegs.length, bSegs.length)\n for (let i = 0; i < len; i++) {\n const av = i < aSegs.length ? segmentSpecificity(aSegs[i]) : -1\n const bv = i < bSegs.length ? segmentSpecificity(bSegs[i]) : -1\n if (av !== bv) return av - bv\n }\n return 0\n}\n\nexport function sortRoutesBySpecificity<T extends { pattern?: string; path?: string }>(routes: T[]): T[] {\n return [...routes].sort((a, b) =>\n compareRouteSpecificity(a.pattern ?? a.path ?? '/', b.pattern ?? b.path ?? '/'),\n )\n}\n\n// Memoized per-array sorted view, so direct callers (e.g., the Next.js catch-all\n// routes that import generated `frontendRoutes`/`backendRoutes`/`apiRoutes`\n// arrays) match against a specificity-sorted view even if they never call\n// `register*RouteManifests`. Keyed by array reference; generated arrays are\n// module-level constants so this caches once per process.\nconst sortedRoutesCache = new WeakMap<object, readonly unknown[]>()\n\nfunction ensureSortedRoutes<T extends { pattern?: string; path?: string }>(routes: readonly T[]): readonly T[] {\n const cached = sortedRoutesCache.get(routes) as readonly T[] | undefined\n if (cached) return cached\n const sorted = sortRoutesBySpecificity([...routes])\n sortedRoutesCache.set(routes, sorted)\n return sorted\n}\n\nexport function matchRoutePattern(pattern: string, pathname: string): RouteMatchParams | undefined {\n const p = normPath(pattern)\n const u = normPath(pathname)\n const pSegs = p.split('/').slice(1)\n const uSegs = u.split('/').slice(1)\n const params: Record<string, string | string[]> = {}\n let i = 0\n for (let j = 0; j < pSegs.length; j++, i++) {\n const seg = pSegs[j]\n const mCatchAll = seg.match(/^\\[\\.\\.\\.(.+)\\]$/)\n const mOptCatch = seg.match(/^\\[\\[\\.\\.\\.(.+)\\]\\]$/)\n const mDyn = seg.match(/^\\[(.+)\\]$/)\n if (mCatchAll) {\n const key = mCatchAll[1]\n if (i >= uSegs.length) return undefined\n params[key] = uSegs.slice(i)\n return params\n } else if (mOptCatch) {\n const key = mOptCatch[1]\n params[key] = i < uSegs.length ? uSegs.slice(i) : []\n return params\n } else if (mDyn) {\n if (i >= uSegs.length) return undefined\n params[mDyn[1]] = uSegs[i]\n } else {\n if (i >= uSegs.length || uSegs[i].toLowerCase() !== seg.toLowerCase()) return undefined\n }\n }\n if (i !== uSegs.length) return undefined\n return params\n}\n\nfunction getPattern(r: ModuleRoute) {\n return r.pattern ?? r.path ?? '/'\n}\n\nexport function findFrontendMatch(modules: Module[], pathname: string): { route: ModuleRoute; params: Record<string, string | string[]> } | undefined {\n for (const m of modules) {\n const routes = m.frontendRoutes ?? []\n for (const r of routes) {\n const params = matchRoutePattern(getPattern(r), pathname)\n if (params) return { route: r, params }\n }\n }\n}\n\nexport function findBackendMatch(modules: Module[], pathname: string): { route: ModuleRoute; params: Record<string, string | string[]> } | undefined {\n for (const m of modules) {\n const routes = m.backendRoutes ?? []\n for (const r of routes) {\n const params = matchRoutePattern(getPattern(r), pathname)\n if (params) return { route: r, params }\n }\n }\n}\n\nexport function findApi(modules: Module[], method: HttpMethod, pathname: string): { handler: ApiHandler; params: Record<string, string | string[]>; requireAuth?: boolean; requireRoles?: string[]; metadata?: any } | undefined {\n for (const m of modules) {\n const apis = m.apis ?? []\n for (const a of apis) {\n if ('handlers' in a) {\n const params = matchRoutePattern(a.path, pathname)\n const handler = (a.handlers as any)[method]\n if (params && handler) return { handler, params, requireAuth: a.requireAuth, requireRoles: (a as any).requireRoles, metadata: (a as any).metadata }\n } else {\n const al = a as ModuleApiLegacy\n if (al.method !== method) continue\n const params = matchRoutePattern(al.path, pathname)\n if (params) {\n return { handler: al.handler, params, metadata: al.metadata }\n }\n }\n }\n }\n}\n\nexport function findRouteManifestMatch<T extends { pattern?: string; path?: string }>(\n routes: T[],\n pathname: string\n): { route: T; params: RouteMatchParams } | undefined {\n for (const route of ensureSortedRoutes(routes)) {\n const params = matchRoutePattern(route.pattern ?? route.path ?? '/', pathname)\n if (params) {\n return { route, params }\n }\n }\n}\n\nexport function findApiRouteManifestMatch<T extends { path: string; methods: HttpMethod[] }>(\n routes: T[],\n method: HttpMethod,\n pathname: string\n): { route: T; params: RouteMatchParams } | undefined {\n for (const route of ensureSortedRoutes(routes)) {\n if (!route.methods.includes(method)) continue\n const params = matchRoutePattern(route.path, pathname)\n if (params) {\n return { route, params }\n }\n }\n}\n\nexport function resolvePageRouteMetadata(pattern: string, metadata: PageMetadata | null | undefined): ModuleRouteMetadata {\n return {\n pattern: pattern || '/',\n requireAuth: metadata?.requireAuth,\n requireRoles: metadata?.requireRoles ? [...metadata.requireRoles] : undefined,\n requireFeatures: metadata?.requireFeatures ? [...metadata.requireFeatures] : undefined,\n requireCustomerAuth: metadata?.requireCustomerAuth,\n requireCustomerFeatures: metadata?.requireCustomerFeatures ? [...metadata.requireCustomerFeatures] : undefined,\n nav: metadata?.nav,\n title: metadata?.pageTitle ?? metadata?.title,\n titleKey: metadata?.pageTitleKey ?? metadata?.titleKey,\n group: metadata?.pageGroup ?? metadata?.group,\n groupKey: metadata?.pageGroupKey ?? metadata?.groupKey,\n icon: metadata?.icon,\n order: metadata?.pageOrder ?? metadata?.order,\n priority: metadata?.pagePriority ?? metadata?.priority,\n navHidden: metadata?.navHidden,\n visible: metadata?.visible,\n enabled: metadata?.enabled,\n breadcrumb: metadata?.breadcrumb,\n pageContext: metadata?.pageContext,\n placement: metadata?.placement,\n }\n}\n\nlet _backendRouteManifests: BackendRouteManifestEntry[] | null = null\n\nexport function registerBackendRouteManifests(routes: BackendRouteManifestEntry[]) {\n const pageOverrides = composePageRouteOverrides()\n const finalRoutes = Object.keys(pageOverrides).length === 0\n ? routes\n : applyPageOverridesToManifests(routes, pageOverrides, 'backend')\n _backendRouteManifests = sortRoutesBySpecificity(finalRoutes)\n}\n\nexport function getBackendRouteManifests(): BackendRouteManifestEntry[] {\n return _backendRouteManifests ?? []\n}\n\nlet _frontendRouteManifests: FrontendRouteManifestEntry[] | null = null\n\nexport function registerFrontendRouteManifests(routes: FrontendRouteManifestEntry[]) {\n const pageOverrides = composePageRouteOverrides()\n const finalRoutes = Object.keys(pageOverrides).length === 0\n ? routes\n : applyPageOverridesToManifests(routes, pageOverrides, 'frontend')\n _frontendRouteManifests = sortRoutesBySpecificity(finalRoutes)\n}\n\nexport function getFrontendRouteManifests(): FrontendRouteManifestEntry[] {\n return _frontendRouteManifests ?? []\n}\n\nlet _apiRouteManifests: ApiRouteManifestEntry[] | null = null\n\nexport function registerApiRouteManifests(routes: ApiRouteManifestEntry[]) {\n // Apply any `entry.overrides.routes.api` overrides registered through the\n // unified `modules.ts` dispatcher or programmatic API before storing the\n // manifest. The composer is cheap and returns an empty object when no\n // overrides exist, so this is a no-op for apps that do not opt in.\n const routeOverrides = composeApiRouteOverrides()\n const finalRoutes = Object.keys(routeOverrides).length === 0\n ? routes\n : applyApiOverridesToManifests(routes, routeOverrides)\n _apiRouteManifests = sortRoutesBySpecificity(finalRoutes)\n}\n\nexport function getApiRouteManifests(): ApiRouteManifestEntry[] {\n return _apiRouteManifests ?? []\n}\n\n// CLI modules registry - shared between CLI and module workers\nlet _cliModules: Module[] | null = null\n\nexport function registerCliModules(modules: Module[]) {\n if (_cliModules !== null && process.env.NODE_ENV === 'development') {\n logger.debug('CLI modules re-registered (this may occur during HMR)')\n }\n _cliModules = applyModuleOverridesToModules(modules)\n}\n\nexport function getCliModules(): Module[] {\n // Return empty array if not registered - allows generate command to work without bootstrap\n return _cliModules ?? []\n}\n\nexport function hasCliModules(): boolean {\n return _cliModules !== null && _cliModules.length > 0\n}\n\nexport function getDefaultEncryptionMaps(modules: Module[]): import('./encryption').ModuleEncryptionMap[] {\n const byEntityId = new Map<string, { moduleId: string; map: import('./encryption').ModuleEncryptionMap }>()\n\n for (const mod of modules) {\n for (const entry of mod.defaultEncryptionMaps ?? []) {\n const previous = byEntityId.get(entry.entityId)\n if (previous) {\n throw new Error(\n `[registry] Duplicate default encryption map for \"${entry.entityId}\" declared by \"${previous.moduleId}\" and \"${mod.id}\"`\n )\n }\n byEntityId.set(entry.entityId, {\n moduleId: mod.id,\n map: {\n entityId: entry.entityId,\n ...(entry.keyScope ? { keyScope: entry.keyScope } : {}),\n fields: entry.fields.map((field) => ({\n field: field.field,\n hashField: field.hashField ?? null,\n })),\n },\n })\n }\n }\n\n return Array.from(byEntityId.values(), ({ map }) => map)\n}\n\nfunction ensureLazyHandler<T extends (...args: any[]) => any>(\n loaded: unknown,\n kind: 'subscriber' | 'worker',\n id: string\n): T {\n const handler = typeof loaded === 'function'\n ? loaded\n : loaded && typeof loaded === 'object' && 'default' in loaded\n ? (loaded as Record<string, unknown>).default\n : null\n if (typeof handler !== 'function') {\n throw new Error(`[registry] Invalid ${kind} module \"${id}\" (missing default export handler)`)\n }\n return handler as T\n}\n\nexport function createLazyModuleSubscriber(\n loadModule: () => Promise<unknown>,\n id: string\n): ModuleSubscriberHandler {\n let handlerPromise: Promise<ModuleSubscriberHandler> | null = null\n return async (payload, ctx) => {\n handlerPromise ??= loadModule().then((loaded) =>\n ensureLazyHandler<ModuleSubscriberHandler>(loaded, 'subscriber', id)\n )\n const handler = await handlerPromise\n return handler(payload, ctx)\n }\n}\n\nexport function createLazyModuleWorker(\n loadModule: () => Promise<unknown>,\n id: string\n): ModuleWorkerHandler {\n let handlerPromise: Promise<ModuleWorkerHandler> | null = null\n return async (job, ctx) => {\n handlerPromise ??= loadModule().then((loaded) =>\n ensureLazyHandler<ModuleWorkerHandler>(loaded, 'worker', id)\n )\n const handler = await handlerPromise\n return handler(job, ctx)\n }\n}\n"],
|
|
5
|
-
"mappings": "AAMA,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,eAAe,CAAC;
|
|
4
|
+
"sourcesContent": ["import type { ReactNode } from 'react'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi/types'\nimport type { SyncCrudEventResult } from '../lib/crud/sync-event-types'\nimport type { DashboardWidgetModule } from './dashboard/widgets'\nimport type { InjectionAnyWidgetModule, ModuleInjectionTable } from './widgets/injection'\nimport type { IntegrationBundle, IntegrationDefinition } from './integrations/types'\nimport { createLogger } from '../lib/logger'\nimport {\n applyApiOverridesToManifests,\n applyModuleOverridesToModules,\n applyPageOverridesToManifests,\n composeApiRouteOverrides,\n composePageRouteOverrides,\n} from './overrides'\n\nconst logger = createLogger('shared').child({ component: 'cli-registry' })\n\n// Context passed to dynamic metadata guards\nexport type RouteVisibilityContext = { path?: string; auth?: any }\n\n/**\n * Portal sidebar navigation hint. When declared on a portal page's metadata,\n * the page is auto-listed in the portal sidebar (subject to RBAC) by the\n * `/api/customer_accounts/portal/nav` endpoint.\n *\n * Absence of `nav` means the page is routable but not auto-listed (useful for\n * detail pages, create forms, etc.).\n */\nexport type PortalNavMetadata = {\n label: string\n labelKey?: string\n group?: 'main' | 'account'\n order?: number\n icon?: string\n}\n\n// Metadata you can export from page.meta.ts or directly from a server page\nexport type PageMetadata = {\n requireAuth?: boolean\n /** @deprecated Use `requireFeatures` instead \u2014 role names are mutable and can be spoofed */\n requireRoles?: readonly string[]\n // Optional fine-grained feature requirements\n requireFeatures?: readonly string[]\n // Portal: require customer (portal user) authentication instead of staff auth\n requireCustomerAuth?: boolean\n // Portal: require customer-specific features (checked against CustomerRbacService)\n requireCustomerFeatures?: readonly string[]\n // Portal: optional sidebar presentation hint (auto-listed by portal nav endpoint)\n nav?: PortalNavMetadata\n // Titles and grouping (aliases supported)\n title?: string\n titleKey?: string\n pageTitle?: string\n pageTitleKey?: string\n group?: string\n groupKey?: string\n pageGroup?: string\n pageGroupKey?: string\n // Ordering and visuals\n order?: number\n pageOrder?: number\n priority?: number\n pagePriority?: number\n icon?: ReactNode\n navHidden?: boolean\n // Dynamic flags\n visible?: (ctx: RouteVisibilityContext) => boolean | Promise<boolean>\n enabled?: (ctx: RouteVisibilityContext) => boolean | Promise<boolean>\n // Optional static breadcrumb trail for header\n breadcrumb?: Array<{ label: string; labelKey?: string; href?: string }>\n // Navigation context for tiered navigation:\n // - 'main' (default): Main sidebar business operations\n // - 'admin': Collapsible \"Settings & Admin\" section at bottom of sidebar\n // - 'settings': Hidden from sidebar, only accessible via Settings hub page\n // - 'profile': Profile dropdown items\n pageContext?: 'main' | 'admin' | 'settings' | 'profile'\n placement?: {\n section: string\n sectionLabel?: string\n sectionLabelKey?: string\n order?: number\n }\n}\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\nexport type ApiHandler = (req: Request, ctx?: any) => Promise<Response> | Response\n\nexport type ModuleSubscriberHandler = (\n payload: any,\n ctx: any\n) => Promise<void | SyncCrudEventResult> | void | SyncCrudEventResult\n\nexport type ModuleWorkerHandler = (job: unknown, ctx: unknown) => Promise<void> | void\n\nexport type ModuleRoute = {\n pattern?: string\n path?: string\n requireAuth?: boolean\n /** @deprecated Use `requireFeatures` instead \u2014 role names are mutable and can be spoofed */\n requireRoles?: string[]\n // Optional fine-grained feature requirements\n requireFeatures?: string[]\n // Portal: require customer (portal user) authentication instead of staff auth\n requireCustomerAuth?: boolean\n // Portal: require customer-specific features (checked against CustomerRbacService)\n requireCustomerFeatures?: string[]\n // Portal: optional sidebar presentation hint (auto-listed by portal nav endpoint)\n nav?: PortalNavMetadata\n title?: string\n titleKey?: string\n group?: string\n groupKey?: string\n icon?: ReactNode\n order?: number\n priority?: number\n navHidden?: boolean\n visible?: (ctx: RouteVisibilityContext) => boolean | Promise<boolean>\n enabled?: (ctx: RouteVisibilityContext) => boolean | Promise<boolean>\n breadcrumb?: Array<{ label: string; labelKey?: string; href?: string }>\n pageContext?: 'main' | 'admin' | 'settings' | 'profile'\n placement?: {\n section: string\n sectionLabel?: string\n sectionLabelKey?: string\n order?: number\n }\n Component: (props: any) => ReactNode | Promise<ReactNode>\n}\n\nexport type ModuleRouteMetadata = Omit<ModuleRoute, 'Component'>\n\nexport type ModuleApiLegacy = {\n method: HttpMethod\n path: string\n handler: ApiHandler\n metadata?: Record<string, unknown>\n docs?: OpenApiMethodDoc\n}\n\nexport type ModuleApiRouteFile = {\n path: string\n handlers: Partial<Record<HttpMethod, ApiHandler>>\n requireAuth?: boolean\n /** @deprecated Use `requireFeatures` instead \u2014 role names are mutable and can be spoofed */\n requireRoles?: string[]\n // Optional fine-grained feature requirements for the entire route file\n // Note: per-method feature requirements should be expressed inside metadata\n requireFeatures?: string[]\n docs?: OpenApiRouteDoc\n metadata?: Partial<Record<HttpMethod, unknown>>\n}\n\nexport type ModuleApi = ModuleApiLegacy | ModuleApiRouteFile\n\nexport type RouteMatchParams = Record<string, string | string[]>\n\nexport type FrontendRouteManifestEntry = Omit<ModuleRoute, 'Component'> & {\n moduleId: string\n load: () => Promise<ModuleRoute['Component']>\n}\n\nexport type BackendRouteManifestEntry = Omit<ModuleRoute, 'Component'> & {\n moduleId: string\n load: () => Promise<ModuleRoute['Component']>\n}\n\nexport type ApiRouteManifestEntry = {\n moduleId: string\n kind: 'route-file' | 'legacy'\n path: string\n methods: HttpMethod[]\n method?: HttpMethod\n load: () => Promise<Record<string, unknown>>\n}\n\nexport type ModuleCli = {\n command: string\n run: (argv: string[]) => Promise<void> | void\n}\n\nexport type ModuleSubscriber = {\n id: string\n moduleId?: string\n event: string\n persistent?: boolean\n sync?: boolean\n priority?: number\n handler: ModuleSubscriberHandler\n}\n\nexport type ModuleWorker = {\n id: string\n moduleId?: string\n queue: string\n concurrency: number\n handler: ModuleWorkerHandler\n}\n\nexport type ModuleInfo = {\n name?: string\n title?: string\n version?: string\n description?: string\n author?: string\n license?: string\n homepage?: string\n copyright?: string\n // Optional hard dependencies: module ids that must be enabled\n requires?: string[]\n // Whether this module can be ejected into the app's src/modules/ for customization\n ejectable?: boolean\n}\n\nexport type ModuleDashboardWidgetEntry = {\n moduleId: string\n key: string\n source: 'app' | 'package'\n loader: () => Promise<DashboardWidgetModule<any>>\n}\n\nexport type ModuleInjectionWidgetEntry = {\n moduleId: string\n key: string\n source: 'app' | 'package'\n widgetId?: string\n loader: () => Promise<InjectionAnyWidgetModule<any, any>>\n}\n\nexport type Module = {\n id: string\n info?: ModuleInfo\n backendRoutes?: ModuleRoute[]\n frontendRoutes?: ModuleRoute[]\n apis?: ModuleApi[]\n cli?: ModuleCli[]\n translations?: Record<string, Record<string, string>>\n // Optional: per-module feature declarations discovered from acl.ts (module root)\n features?: Array<{ id: string; title: string; module: string }>\n // Auto-discovered event subscribers\n subscribers?: ModuleSubscriber[]\n // Auto-discovered queue workers\n workers?: ModuleWorker[]\n // Optional: per-module declared entity extensions and custom fields (static)\n // Extensions discovered from data/extensions.ts; Custom fields discovered from ce.ts (entities[].fields)\n entityExtensions?: import('./entities').EntityExtension[]\n customFieldSets?: import('./entities').CustomFieldSet[]\n // Optional: per-module declared custom entities (virtual/logical entities)\n // Discovered from ce.ts (module root). Each entry represents an entityId with optional label/description.\n customEntities?: Array<{ id: string; label?: string; description?: string }>\n dashboardWidgets?: ModuleDashboardWidgetEntry[]\n injectionWidgets?: ModuleInjectionWidgetEntry[]\n injectionTable?: ModuleInjectionTable\n // Optional: per-module vector search configuration (discovered from vector.ts)\n vector?: import('./vector').VectorModuleConfig\n // Optional: module-specific tenant setup configuration (from setup.ts)\n setup?: import('./setup').ModuleSetupConfig\n // Optional: default encryption maps owned by the module (from encryption.ts)\n defaultEncryptionMaps?: import('./encryption').ModuleEncryptionMap[]\n // Optional: integration marketplace declarations discovered from integration.ts\n integrations?: IntegrationDefinition[]\n bundles?: IntegrationBundle[]\n}\n\nfunction normPath(s: string) {\n return (s.startsWith('/') ? s : '/' + s).replace(/\\/+$/, '') || '/'\n}\n\n// 0 = literal (most specific), 1 = dynamic [param], 2 = catch-all [...param] or [[...param]]\nfunction segmentSpecificity(seg: string): 0 | 1 | 2 {\n if (seg.startsWith('[[...') || seg.startsWith('[...')) return 2\n if (seg.startsWith('[')) return 1\n return 0\n}\n\nfunction compareRouteSpecificity(aPattern: string, bPattern: string): number {\n const aSegs = aPattern.split('/')\n const bSegs = bPattern.split('/')\n const len = Math.max(aSegs.length, bSegs.length)\n for (let i = 0; i < len; i++) {\n const av = i < aSegs.length ? segmentSpecificity(aSegs[i]) : -1\n const bv = i < bSegs.length ? segmentSpecificity(bSegs[i]) : -1\n if (av !== bv) return av - bv\n }\n return 0\n}\n\nexport function sortRoutesBySpecificity<T extends { pattern?: string; path?: string }>(routes: T[]): T[] {\n return [...routes].sort((a, b) =>\n compareRouteSpecificity(a.pattern ?? a.path ?? '/', b.pattern ?? b.path ?? '/'),\n )\n}\n\n// Memoized per-array sorted view, so direct callers (e.g., the Next.js catch-all\n// routes that import generated `frontendRoutes`/`backendRoutes`/`apiRoutes`\n// arrays) match against a specificity-sorted view even if they never call\n// `register*RouteManifests`. Keyed by array reference; generated arrays are\n// module-level constants so this caches once per process.\nconst sortedRoutesCache = new WeakMap<object, readonly unknown[]>()\n\nfunction ensureSortedRoutes<T extends { pattern?: string; path?: string }>(routes: readonly T[]): readonly T[] {\n const cached = sortedRoutesCache.get(routes) as readonly T[] | undefined\n if (cached) return cached\n const sorted = sortRoutesBySpecificity([...routes])\n sortedRoutesCache.set(routes, sorted)\n return sorted\n}\n\nexport function matchRoutePattern(pattern: string, pathname: string): RouteMatchParams | undefined {\n const p = normPath(pattern)\n const u = normPath(pathname)\n const pSegs = p.split('/').slice(1)\n const uSegs = u.split('/').slice(1)\n const params: Record<string, string | string[]> = {}\n let i = 0\n for (let j = 0; j < pSegs.length; j++, i++) {\n const seg = pSegs[j]\n const mCatchAll = seg.match(/^\\[\\.\\.\\.(.+)\\]$/)\n const mOptCatch = seg.match(/^\\[\\[\\.\\.\\.(.+)\\]\\]$/)\n const mDyn = seg.match(/^\\[(.+)\\]$/)\n if (mCatchAll) {\n const key = mCatchAll[1]\n if (i >= uSegs.length) return undefined\n params[key] = uSegs.slice(i)\n return params\n } else if (mOptCatch) {\n const key = mOptCatch[1]\n params[key] = i < uSegs.length ? uSegs.slice(i) : []\n return params\n } else if (mDyn) {\n if (i >= uSegs.length) return undefined\n params[mDyn[1]] = uSegs[i]\n } else {\n if (i >= uSegs.length || uSegs[i].toLowerCase() !== seg.toLowerCase()) return undefined\n }\n }\n if (i !== uSegs.length) return undefined\n return params\n}\n\nfunction getPattern(r: ModuleRoute) {\n return r.pattern ?? r.path ?? '/'\n}\n\nexport function findFrontendMatch(modules: Module[], pathname: string): { route: ModuleRoute; params: Record<string, string | string[]> } | undefined {\n for (const m of modules) {\n const routes = m.frontendRoutes ?? []\n for (const r of routes) {\n const params = matchRoutePattern(getPattern(r), pathname)\n if (params) return { route: r, params }\n }\n }\n}\n\nexport function findBackendMatch(modules: Module[], pathname: string): { route: ModuleRoute; params: Record<string, string | string[]> } | undefined {\n for (const m of modules) {\n const routes = m.backendRoutes ?? []\n for (const r of routes) {\n const params = matchRoutePattern(getPattern(r), pathname)\n if (params) return { route: r, params }\n }\n }\n}\n\nexport function findApi(modules: Module[], method: HttpMethod, pathname: string): { handler: ApiHandler; params: Record<string, string | string[]>; requireAuth?: boolean; requireRoles?: string[]; metadata?: any } | undefined {\n for (const m of modules) {\n const apis = m.apis ?? []\n for (const a of apis) {\n if ('handlers' in a) {\n const params = matchRoutePattern(a.path, pathname)\n const handler = (a.handlers as any)[method]\n if (params && handler) return { handler, params, requireAuth: a.requireAuth, requireRoles: (a as any).requireRoles, metadata: (a as any).metadata }\n } else {\n const al = a as ModuleApiLegacy\n if (al.method !== method) continue\n const params = matchRoutePattern(al.path, pathname)\n if (params) {\n return { handler: al.handler, params, metadata: al.metadata }\n }\n }\n }\n }\n}\n\nexport function findRouteManifestMatch<T extends { pattern?: string; path?: string }>(\n routes: T[],\n pathname: string\n): { route: T; params: RouteMatchParams } | undefined {\n for (const route of ensureSortedRoutes(routes)) {\n const params = matchRoutePattern(route.pattern ?? route.path ?? '/', pathname)\n if (params) {\n return { route, params }\n }\n }\n}\n\nexport function findApiRouteManifestMatch<T extends { path: string; methods: HttpMethod[] }>(\n routes: T[],\n method: HttpMethod,\n pathname: string\n): { route: T; params: RouteMatchParams } | undefined {\n for (const route of ensureSortedRoutes(routes)) {\n if (!route.methods.includes(method)) continue\n const params = matchRoutePattern(route.path, pathname)\n if (params) {\n return { route, params }\n }\n }\n}\n\nexport function resolvePageRouteMetadata(pattern: string, metadata: PageMetadata | null | undefined): ModuleRouteMetadata {\n return {\n pattern: pattern || '/',\n requireAuth: metadata?.requireAuth,\n requireRoles: metadata?.requireRoles ? [...metadata.requireRoles] : undefined,\n requireFeatures: metadata?.requireFeatures ? [...metadata.requireFeatures] : undefined,\n requireCustomerAuth: metadata?.requireCustomerAuth,\n requireCustomerFeatures: metadata?.requireCustomerFeatures ? [...metadata.requireCustomerFeatures] : undefined,\n nav: metadata?.nav,\n title: metadata?.pageTitle ?? metadata?.title,\n titleKey: metadata?.pageTitleKey ?? metadata?.titleKey,\n group: metadata?.pageGroup ?? metadata?.group,\n groupKey: metadata?.pageGroupKey ?? metadata?.groupKey,\n icon: metadata?.icon,\n order: metadata?.pageOrder ?? metadata?.order,\n priority: metadata?.pagePriority ?? metadata?.priority,\n navHidden: metadata?.navHidden,\n visible: metadata?.visible,\n enabled: metadata?.enabled,\n breadcrumb: metadata?.breadcrumb,\n pageContext: metadata?.pageContext,\n placement: metadata?.placement,\n }\n}\n\nlet _backendRouteManifests: BackendRouteManifestEntry[] | null = null\n\nexport function registerBackendRouteManifests(routes: BackendRouteManifestEntry[]) {\n const pageOverrides = composePageRouteOverrides()\n const finalRoutes = Object.keys(pageOverrides).length === 0\n ? routes\n : applyPageOverridesToManifests(routes, pageOverrides, 'backend')\n _backendRouteManifests = sortRoutesBySpecificity(finalRoutes)\n}\n\nexport function getBackendRouteManifests(): BackendRouteManifestEntry[] {\n return _backendRouteManifests ?? []\n}\n\nlet _frontendRouteManifests: FrontendRouteManifestEntry[] | null = null\n\nexport function registerFrontendRouteManifests(routes: FrontendRouteManifestEntry[]) {\n const pageOverrides = composePageRouteOverrides()\n const finalRoutes = Object.keys(pageOverrides).length === 0\n ? routes\n : applyPageOverridesToManifests(routes, pageOverrides, 'frontend')\n _frontendRouteManifests = sortRoutesBySpecificity(finalRoutes)\n}\n\nexport function getFrontendRouteManifests(): FrontendRouteManifestEntry[] {\n return _frontendRouteManifests ?? []\n}\n\nlet _apiRouteManifests: ApiRouteManifestEntry[] | null = null\n\nexport function registerApiRouteManifests(routes: ApiRouteManifestEntry[]) {\n // Apply any `entry.overrides.routes.api` overrides registered through the\n // unified `modules.ts` dispatcher or programmatic API before storing the\n // manifest. The composer is cheap and returns an empty object when no\n // overrides exist, so this is a no-op for apps that do not opt in.\n const routeOverrides = composeApiRouteOverrides()\n const finalRoutes = Object.keys(routeOverrides).length === 0\n ? routes\n : applyApiOverridesToManifests(routes, routeOverrides)\n _apiRouteManifests = sortRoutesBySpecificity(finalRoutes)\n}\n\nexport function getApiRouteManifests(): ApiRouteManifestEntry[] {\n return _apiRouteManifests ?? []\n}\n\n// CLI modules registry - shared between CLI and module workers\nlet _cliModules: Module[] | null = null\n\nexport function registerCliModules(modules: Module[]) {\n if (_cliModules !== null && process.env.NODE_ENV === 'development') {\n logger.debug('CLI modules re-registered (this may occur during HMR)')\n }\n _cliModules = applyModuleOverridesToModules(modules)\n}\n\nexport function getCliModules(): Module[] {\n // Return empty array if not registered - allows generate command to work without bootstrap\n return _cliModules ?? []\n}\n\nexport function hasCliModules(): boolean {\n return _cliModules !== null && _cliModules.length > 0\n}\n\nexport function getDefaultEncryptionMaps(modules: Module[]): import('./encryption').ModuleEncryptionMap[] {\n const byEntityId = new Map<string, { moduleId: string; map: import('./encryption').ModuleEncryptionMap }>()\n\n for (const mod of modules) {\n for (const entry of mod.defaultEncryptionMaps ?? []) {\n const previous = byEntityId.get(entry.entityId)\n if (previous) {\n throw new Error(\n `[registry] Duplicate default encryption map for \"${entry.entityId}\" declared by \"${previous.moduleId}\" and \"${mod.id}\"`\n )\n }\n byEntityId.set(entry.entityId, {\n moduleId: mod.id,\n map: {\n entityId: entry.entityId,\n fields: entry.fields.map((field) => ({\n field: field.field,\n hashField: field.hashField ?? null,\n })),\n },\n })\n }\n }\n\n return Array.from(byEntityId.values(), ({ map }) => map)\n}\n\nfunction ensureLazyHandler<T extends (...args: any[]) => any>(\n loaded: unknown,\n kind: 'subscriber' | 'worker',\n id: string\n): T {\n const handler = typeof loaded === 'function'\n ? loaded\n : loaded && typeof loaded === 'object' && 'default' in loaded\n ? (loaded as Record<string, unknown>).default\n : null\n if (typeof handler !== 'function') {\n throw new Error(`[registry] Invalid ${kind} module \"${id}\" (missing default export handler)`)\n }\n return handler as T\n}\n\nexport function createLazyModuleSubscriber(\n loadModule: () => Promise<unknown>,\n id: string\n): ModuleSubscriberHandler {\n let handlerPromise: Promise<ModuleSubscriberHandler> | null = null\n return async (payload, ctx) => {\n handlerPromise ??= loadModule().then((loaded) =>\n ensureLazyHandler<ModuleSubscriberHandler>(loaded, 'subscriber', id)\n )\n const handler = await handlerPromise\n return handler(payload, ctx)\n }\n}\n\nexport function createLazyModuleWorker(\n loadModule: () => Promise<unknown>,\n id: string\n): ModuleWorkerHandler {\n let handlerPromise: Promise<ModuleWorkerHandler> | null = null\n return async (job, ctx) => {\n handlerPromise ??= loadModule().then((loaded) =>\n ensureLazyHandler<ModuleWor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UAAU,MAAM;AAAA,UAChB,QAAQ,MAAM,OAAO,IAAI,CAAC,WAAW;AAAA,YACnC,OAAO,MAAM;AAAA,YACb,WAAW,MAAM,aAAa;AAAA,UAChC,EAAE;AAAA,QACJ;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO,MAAM,KAAK,WAAW,OAAO,GAAG,CAAC,EAAE,IAAI,MAAM,GAAG;AACzD;AAEA,SAAS,kBACP,QACA,MACA,IACG;AACH,QAAM,UAAU,OAAO,WAAW,aAC9B,SACA,UAAU,OAAO,WAAW,YAAY,aAAa,SAClD,OAAmC,UACpC;AACN,MAAI,OAAO,YAAY,YAAY;AACjC,UAAM,IAAI,MAAM,sBAAsB,IAAI,YAAY,EAAE,oCAAoC;AAAA,EAC9F;AACA,SAAO;AACT;AAEO,SAAS,2BACd,YACA,IACyB;AACzB,MAAI,iBAA0D;AAC9D,SAAO,OAAO,SAAS,QAAQ;AAC7B,uBAAmB,WAAW,EAAE;AAAA,MAAK,CAAC,WACpC,kBAA2C,QAAQ,cAAc,EAAE;AAAA,IACrE;AACA,UAAM,UAAU,MAAM;AACtB,WAAO,QAAQ,SAAS,GAAG;AAAA,EAC7B;AACF;AAEO,SAAS,uBACd,YACA,IACqB;AACrB,MAAI,iBAAsD;AAC1D,SAAO,OAAO,KAAK,QAAQ;AACzB,uBAAmB,WAAW,EAAE;AAAA,MAAK,CAAC,WACpC,kBAAuC,QAAQ,UAAU,EAAE;AAAA,IAC7D;AACA,UAAM,UAAU,MAAM;AACtB,WAAO,QAAQ,KAAK,GAAG;AAAA,EACzB;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -6,57 +6,21 @@ function buildRegistry(modules) {
|
|
|
6
6
|
const enabledModuleSet = new Set(enabledModuleIds);
|
|
7
7
|
const featureToModule = /* @__PURE__ */ new Map();
|
|
8
8
|
const prefixToModule = /* @__PURE__ */ new Map();
|
|
9
|
-
const concreteFeatureIds = [];
|
|
10
|
-
const concreteFeatureSet = /* @__PURE__ */ new Set();
|
|
11
|
-
const addConcreteFeature = (featureId, owningModule, authoritative) => {
|
|
12
|
-
if (!featureId || featureId === "*" || featureId.endsWith(".*")) return;
|
|
13
|
-
if (!concreteFeatureSet.has(featureId)) {
|
|
14
|
-
concreteFeatureSet.add(featureId);
|
|
15
|
-
concreteFeatureIds.push(featureId);
|
|
16
|
-
}
|
|
17
|
-
if (authoritative || !featureToModule.has(featureId)) {
|
|
18
|
-
featureToModule.set(featureId, owningModule);
|
|
19
|
-
}
|
|
20
|
-
const dot = featureId.indexOf(".");
|
|
21
|
-
if (dot > 0) {
|
|
22
|
-
const prefix = featureId.slice(0, dot);
|
|
23
|
-
if (!prefixToModule.has(prefix)) prefixToModule.set(prefix, owningModule);
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
9
|
for (const mod of modules) {
|
|
27
10
|
const features = mod.features;
|
|
28
|
-
if (Array.isArray(features))
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
for (const roleFeatures of Object.values(customerDefaults)) {
|
|
38
|
-
if (!Array.isArray(roleFeatures)) continue;
|
|
39
|
-
for (const featureId of roleFeatures) {
|
|
40
|
-
if (typeof featureId === "string") addConcreteFeature(featureId, mod.id, false);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
if (Array.isArray(mod.frontendRoutes)) {
|
|
45
|
-
for (const route of mod.frontendRoutes) {
|
|
46
|
-
if (!Array.isArray(route.requireCustomerFeatures)) continue;
|
|
47
|
-
for (const featureId of route.requireCustomerFeatures) {
|
|
48
|
-
if (typeof featureId === "string") addConcreteFeature(featureId, mod.id, false);
|
|
49
|
-
}
|
|
11
|
+
if (!Array.isArray(features)) continue;
|
|
12
|
+
for (const feature of features) {
|
|
13
|
+
if (!feature || typeof feature.id !== "string" || !feature.id) continue;
|
|
14
|
+
const declared = typeof feature.module === "string" && feature.module.length > 0 ? feature.module : mod.id;
|
|
15
|
+
featureToModule.set(feature.id, declared);
|
|
16
|
+
const dot = feature.id.indexOf(".");
|
|
17
|
+
if (dot > 0) {
|
|
18
|
+
const prefix = feature.id.slice(0, dot);
|
|
19
|
+
if (!prefixToModule.has(prefix)) prefixToModule.set(prefix, declared);
|
|
50
20
|
}
|
|
51
21
|
}
|
|
52
22
|
}
|
|
53
|
-
return {
|
|
54
|
-
enabledModuleIds,
|
|
55
|
-
enabledModuleSet,
|
|
56
|
-
featureToModule,
|
|
57
|
-
prefixToModule,
|
|
58
|
-
concreteFeatureIds
|
|
59
|
-
};
|
|
23
|
+
return { enabledModuleIds, enabledModuleSet, featureToModule, prefixToModule };
|
|
60
24
|
}
|
|
61
25
|
function getRegistry() {
|
|
62
26
|
try {
|
|
@@ -88,13 +52,6 @@ function getEnabledModuleIds() {
|
|
|
88
52
|
const registry = getRegistry();
|
|
89
53
|
return registry ? [...registry.enabledModuleIds] : [];
|
|
90
54
|
}
|
|
91
|
-
function getConcreteFeatureIds() {
|
|
92
|
-
const registry = getRegistry();
|
|
93
|
-
return registry ? [...registry.concreteFeatureIds] : [];
|
|
94
|
-
}
|
|
95
|
-
function hasEnabledModulesRegistry() {
|
|
96
|
-
return getRegistry() !== null;
|
|
97
|
-
}
|
|
98
55
|
function filterGrantsByEnabledModules(granted) {
|
|
99
56
|
const registry = getRegistry();
|
|
100
57
|
if (!registry) return [...granted];
|
|
@@ -116,9 +73,7 @@ function filterGrantsByEnabledModules(granted) {
|
|
|
116
73
|
}
|
|
117
74
|
export {
|
|
118
75
|
filterGrantsByEnabledModules,
|
|
119
|
-
getConcreteFeatureIds,
|
|
120
76
|
getEnabledModuleIds,
|
|
121
|
-
getOwningModuleId
|
|
122
|
-
hasEnabledModulesRegistry
|
|
77
|
+
getOwningModuleId
|
|
123
78
|
};
|
|
124
79
|
//# sourceMappingURL=enabledModulesRegistry.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/security/enabledModulesRegistry.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Module-aware grant filtering.\n *\n * Features live under `<module>.<action>` (see AGENTS.md naming convention).\n * When a module is disabled in `modules.ts`, its routes/UI are absent but\n * roles may still carry the feature string. Anywhere we turn raw ACL\n * grants into \"what the user can currently act on\", we must drop grants\n * whose owning module is not enabled \u2014 otherwise stale grants re-open the\n * 404-class bug PR #1567 only partially fixed.\n *\n * Owning-module resolution:\n * - Most features follow the convention so `id.split('.')[0]` matches the\n * module id. For those, the prefix is correct.\n * - A few features (e.g. `analytics.view`) deliberately use a different\n * namespace from their owning module. For those, the registry's declared\n * `module` field on the `Module.features` entry is authoritative. We\n * consult it first and fall back to the prefix only when the feature is\n * unknown to the registry.\n *\n * This helper is server-only: it reads the enabled module set from the\n * bootstrapped module registry. The browser never imports it; instead,\n * server code pre-filters `BackendChromePayload.grantedFeatures` so\n * client-side `hasFeature` can stay a pure grant check.\n */\n\nimport { getModules } from '../lib/modules/registry'\nimport type { Module } from '../modules/registry'\n\ntype FeatureRegistry = {\n enabledModuleIds: string[]\n enabledModuleSet: Set<string>\n featureToModule: Map<string, string>\n prefixToModule: Map<string, string>\n
|
|
5
|
-
"mappings": "AAyBA,SAAS,kBAAkB;
|
|
4
|
+
"sourcesContent": ["/**\n * Module-aware grant filtering.\n *\n * Features live under `<module>.<action>` (see AGENTS.md naming convention).\n * When a module is disabled in `modules.ts`, its routes/UI are absent but\n * roles may still carry the feature string. Anywhere we turn raw ACL\n * grants into \"what the user can currently act on\", we must drop grants\n * whose owning module is not enabled \u2014 otherwise stale grants re-open the\n * 404-class bug PR #1567 only partially fixed.\n *\n * Owning-module resolution:\n * - Most features follow the convention so `id.split('.')[0]` matches the\n * module id. For those, the prefix is correct.\n * - A few features (e.g. `analytics.view`) deliberately use a different\n * namespace from their owning module. For those, the registry's declared\n * `module` field on the `Module.features` entry is authoritative. We\n * consult it first and fall back to the prefix only when the feature is\n * unknown to the registry.\n *\n * This helper is server-only: it reads the enabled module set from the\n * bootstrapped module registry. The browser never imports it; instead,\n * server code pre-filters `BackendChromePayload.grantedFeatures` so\n * client-side `hasFeature` can stay a pure grant check.\n */\n\nimport { getModules } from '../lib/modules/registry'\nimport type { Module } from '../modules/registry'\n\ntype FeatureRegistry = {\n enabledModuleIds: string[]\n enabledModuleSet: Set<string>\n featureToModule: Map<string, string>\n prefixToModule: Map<string, string>\n}\n\nlet cachedRegistry: FeatureRegistry | null = null\nlet cachedModulesRef: readonly Module[] | null = null\n\nfunction buildRegistry(modules: readonly Module[]): FeatureRegistry {\n const enabledModuleIds = modules.map((mod) => mod.id)\n const enabledModuleSet = new Set(enabledModuleIds)\n const featureToModule = new Map<string, string>()\n const prefixToModule = new Map<string, string>()\n for (const mod of modules) {\n const features = mod.features\n if (!Array.isArray(features)) continue\n for (const feature of features) {\n if (!feature || typeof feature.id !== 'string' || !feature.id) continue\n const declared = typeof feature.module === 'string' && feature.module.length > 0\n ? feature.module\n : mod.id\n featureToModule.set(feature.id, declared)\n const dot = feature.id.indexOf('.')\n if (dot > 0) {\n const prefix = feature.id.slice(0, dot)\n if (!prefixToModule.has(prefix)) prefixToModule.set(prefix, declared)\n }\n }\n }\n return { enabledModuleIds, enabledModuleSet, featureToModule, prefixToModule }\n}\n\nfunction getRegistry(): FeatureRegistry | null {\n try {\n const modules = getModules() as readonly Module[]\n if (cachedRegistry && cachedModulesRef === modules) return cachedRegistry\n cachedModulesRef = modules\n cachedRegistry = buildRegistry(modules)\n return cachedRegistry\n } catch {\n return null\n }\n}\n\nexport function getOwningModuleId(featureId: string): string {\n const registry = getRegistry()\n if (registry) {\n const direct = registry.featureToModule.get(featureId)\n if (direct) return direct\n if (featureId.endsWith('.*')) {\n const prefix = featureId.slice(0, -2)\n const fromPrefix = registry.prefixToModule.get(prefix)\n if (fromPrefix) return fromPrefix\n return prefix\n }\n }\n const dot = featureId.indexOf('.')\n return dot === -1 ? featureId : featureId.slice(0, dot)\n}\n\nexport function getEnabledModuleIds(): string[] {\n const registry = getRegistry()\n return registry ? [...registry.enabledModuleIds] : []\n}\n\n/**\n * Filters a raw granted-features list down to the grants whose owning\n * module is currently enabled. Expands `*` (superadmin) into one wildcard\n * per enabled module so the result is still safe to feed into a pure\n * `matchFeature` check, plus one wildcard per off-convention feature\n * prefix (e.g. `analytics.*`) whose declared owning module is enabled.\n * If the module registry is not populated (tests, CLI), returns the input\n * unchanged \u2014 preserves legacy behavior.\n */\nexport function filterGrantsByEnabledModules(granted: readonly string[]): string[] {\n const registry = getRegistry()\n if (!registry) return [...granted]\n const { enabledModuleIds, enabledModuleSet, prefixToModule } = registry\n const result: string[] = []\n for (const grant of granted) {\n if (grant === '*') {\n for (const id of enabledModuleIds) result.push(`${id}.*`)\n for (const [prefix, owningModule] of prefixToModule) {\n if (!enabledModuleSet.has(prefix) && enabledModuleSet.has(owningModule)) {\n result.push(`${prefix}.*`)\n }\n }\n continue\n }\n if (enabledModuleSet.has(getOwningModuleId(grant))) result.push(grant)\n }\n return result\n}\n"],
|
|
5
|
+
"mappings": "AAyBA,SAAS,kBAAkB;AAU3B,IAAI,iBAAyC;AAC7C,IAAI,mBAA6C;AAEjD,SAAS,cAAc,SAA6C;AAClE,QAAM,mBAAmB,QAAQ,IAAI,CAAC,QAAQ,IAAI,EAAE;AACpD,QAAM,mBAAmB,IAAI,IAAI,gBAAgB;AACjD,QAAM,kBAAkB,oBAAI,IAAoB;AAChD,QAAM,iBAAiB,oBAAI,IAAoB;AAC/C,aAAW,OAAO,SAAS;AACzB,UAAM,WAAW,IAAI;AACrB,QAAI,CAAC,MAAM,QAAQ,QAAQ,EAAG;AAC9B,eAAW,WAAW,UAAU;AAC9B,UAAI,CAAC,WAAW,OAAO,QAAQ,OAAO,YAAY,CAAC,QAAQ,GAAI;AAC/D,YAAM,WAAW,OAAO,QAAQ,WAAW,YAAY,QAAQ,OAAO,SAAS,IAC3E,QAAQ,SACR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W,SAAS,SAAS;AAC3B,QAAI,UAAU,KAAK;AACjB,iBAAW,MAAM,iBAAkB,QAAO,KAAK,GAAG,EAAE,IAAI;AACxD,iBAAW,CAAC,QAAQ,YAAY,KAAK,gBAAgB;AACnD,YAAI,CAAC,iBAAiB,IAAI,MAAM,KAAK,iBAAiB,IAAI,YAAY,GAAG;AACvE,iBAAO,KAAK,GAAG,MAAM,IAAI;AAAA,QAC3B;AAAA,MACF;AACA;AAAA,IACF;AACA,QAAI,iBAAiB,IAAI,kBAAkB,KAAK,CAAC,EAAG,QAAO,KAAK,KAAK;AAAA,EACvE;AACA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/jest.config.cjs
CHANGED
|
@@ -12,8 +12,7 @@ module.exports = {
|
|
|
12
12
|
'^@open-mercato/core/(.*)$': '<rootDir>/../core/src/$1',
|
|
13
13
|
},
|
|
14
14
|
transform: {
|
|
15
|
-
|
|
16
|
-
'^.+\\.(cjs|(t|j)sx?)$': [
|
|
15
|
+
'^.+\\.(t|j)sx?$': [
|
|
17
16
|
'<rootDir>/../../scripts/jest-mikroorm-transformer.cjs',
|
|
18
17
|
{
|
|
19
18
|
tsconfig: {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/shared",
|
|
3
|
-
"version": "0.6.7
|
|
3
|
+
"version": "0.6.7",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -48,18 +48,10 @@
|
|
|
48
48
|
"types": "./src/lib/events/patterns.ts",
|
|
49
49
|
"default": "./dist/lib/events/patterns.js"
|
|
50
50
|
},
|
|
51
|
-
"./lib/data/consistency": {
|
|
52
|
-
"types": "./src/lib/data/consistency.ts",
|
|
53
|
-
"default": "./dist/lib/data/consistency.js"
|
|
54
|
-
},
|
|
55
51
|
"./lib/logger": {
|
|
56
52
|
"types": "./src/lib/logger/index.ts",
|
|
57
53
|
"default": "./dist/lib/logger/index.js"
|
|
58
54
|
},
|
|
59
|
-
"./lib/search/tokenLookup": {
|
|
60
|
-
"types": "./src/lib/search/tokenLookup.ts",
|
|
61
|
-
"default": "./dist/lib/search/tokenLookup.js"
|
|
62
|
-
},
|
|
63
55
|
"./modules/generators": {
|
|
64
56
|
"types": "./src/modules/generators/index.ts",
|
|
65
57
|
"default": "./dist/modules/generators/index.js"
|
|
@@ -102,24 +94,23 @@
|
|
|
102
94
|
}
|
|
103
95
|
},
|
|
104
96
|
"dependencies": {
|
|
105
|
-
"@mikro-orm/core": "^7.1.
|
|
106
|
-
"@mikro-orm/decorators": "^7.1.
|
|
107
|
-
"@mikro-orm/postgresql": "^7.1.
|
|
108
|
-
"@open-mercato/cache": "0.6.7
|
|
97
|
+
"@mikro-orm/core": "^7.1.5",
|
|
98
|
+
"@mikro-orm/decorators": "^7.1.5",
|
|
99
|
+
"@mikro-orm/postgresql": "^7.1.5",
|
|
100
|
+
"@open-mercato/cache": "0.6.7",
|
|
109
101
|
"@types/sanitize-html": "^2.16.1",
|
|
110
102
|
"dotenv": "^17.4.2",
|
|
111
103
|
"pino": "^10.3.1",
|
|
112
104
|
"rate-limiter-flexible": "^11.2.0",
|
|
113
105
|
"re2js": "2.8.6",
|
|
114
106
|
"reflect-metadata": "^0.2.2",
|
|
115
|
-
"sanitize-html": "2.17.5",
|
|
116
|
-
"undici": "^8.
|
|
107
|
+
"sanitize-html": "^2.17.5",
|
|
108
|
+
"undici": "^8.7.0"
|
|
117
109
|
},
|
|
118
110
|
"devDependencies": {
|
|
119
111
|
"@types/jest": "^30.0.0",
|
|
120
112
|
"jest": "^30.4.2",
|
|
121
|
-
"ts-jest": "^29.4.
|
|
122
|
-
"ts-morph": "^28.0.0",
|
|
113
|
+
"ts-jest": "^29.4.11",
|
|
123
114
|
"typescript": "7.0.2"
|
|
124
115
|
},
|
|
125
116
|
"publishConfig": {
|
|
@@ -129,6 +120,5 @@
|
|
|
129
120
|
"type": "git",
|
|
130
121
|
"url": "https://github.com/open-mercato/open-mercato",
|
|
131
122
|
"directory": "packages/shared"
|
|
132
|
-
}
|
|
133
|
-
"stableVersion": "0.6.6"
|
|
123
|
+
}
|
|
134
124
|
}
|
|
@@ -62,16 +62,6 @@ export interface LlmCreateModelOptions {
|
|
|
62
62
|
* proxy); Google honors it when the SDK supports it (@ai-sdk/google ≥3.0).
|
|
63
63
|
*/
|
|
64
64
|
baseURL?: string
|
|
65
|
-
/**
|
|
66
|
-
* Optional opaque, non-reversible end-user identifier attached to the model
|
|
67
|
-
* call so provider-side abuse enforcement can target a single end user
|
|
68
|
-
* instead of the whole API-key organization. The runtime computes this as a
|
|
69
|
-
* tenant-salted HMAC (no PII leaves the platform); the adapter decides how to
|
|
70
|
-
* map it into per-call `providerOptions` via
|
|
71
|
-
* {@link LlmProvider.mapEndUserIdentifier}. Adapters without a mapping ignore
|
|
72
|
-
* it. Always optional — absent identifiers reproduce today's behavior.
|
|
73
|
-
*/
|
|
74
|
-
endUserIdentifier?: string
|
|
75
65
|
}
|
|
76
66
|
|
|
77
67
|
/**
|
|
@@ -156,27 +146,4 @@ export interface LlmProvider {
|
|
|
156
146
|
* behavior at `packages/ai-assistant/src/modules/ai_assistant/api/route/route.ts`.
|
|
157
147
|
*/
|
|
158
148
|
createModel(options: LlmCreateModelOptions): unknown
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* Optional. Maps a runtime-computed end-user identifier (see
|
|
162
|
-
* {@link LlmCreateModelOptions.endUserIdentifier}) into the AI SDK
|
|
163
|
-
* `providerOptions` fragment this provider understands — e.g. OpenAI returns
|
|
164
|
-
* `{ openai: { safetyIdentifier } }`, Anthropic returns
|
|
165
|
-
* `{ anthropic: { metadata: { userId } } }`. Keys MUST be the AI SDK
|
|
166
|
-
* provider-option names (camelCase); the SDK translates them to the
|
|
167
|
-
* provider's request-body fields and strips unknown keys. The runtime merges
|
|
168
|
-
* the returned fragment into the per-call `providerOptions`. Adapters that
|
|
169
|
-
* omit this method send no identifier (today's behavior). Implementations
|
|
170
|
-
* MUST be pure and stateless.
|
|
171
|
-
*/
|
|
172
|
-
mapEndUserIdentifier?(identifier: string): Record<string, unknown>
|
|
173
|
-
|
|
174
|
-
/**
|
|
175
|
-
* Optional. When `true`, the runtime may run input pre-moderation through
|
|
176
|
-
* this provider's moderation endpoint before the model call. Only providers
|
|
177
|
-
* that actually expose a moderation API (initially the OpenAI adapter) set
|
|
178
|
-
* this. Absent/`false` means the moderation gate is skipped for this provider
|
|
179
|
-
* and the surface relies on the provider's own server-side filtering.
|
|
180
|
-
*/
|
|
181
|
-
readonly supportsInputModeration?: boolean
|
|
182
149
|
}
|
|
@@ -161,27 +161,4 @@ describe('auth server integrity checks', () => {
|
|
|
161
161
|
|
|
162
162
|
await expect(getAuthFromRequest(request)).resolves.toBeNull()
|
|
163
163
|
})
|
|
164
|
-
|
|
165
|
-
it('reports a transient DB failure on the api-key path as "error" (retryable 503)', async () => {
|
|
166
|
-
const { resolveAuthFromRequestDetailed } = await import('@open-mercato/shared/lib/auth/server')
|
|
167
|
-
// Distinct secret so the shared api-key auth cache does not serve a prior miss.
|
|
168
|
-
findApiKeyBySecret.mockRejectedValue(Object.assign(new Error('sorry, too many clients already'), { code: '53300' }))
|
|
169
|
-
|
|
170
|
-
const request = new Request('https://example.test/api/test', {
|
|
171
|
-
headers: { 'x-api-key': 'transient-key' },
|
|
172
|
-
})
|
|
173
|
-
|
|
174
|
-
await expect(resolveAuthFromRequestDetailed(request)).resolves.toEqual({ auth: null, status: 'error' })
|
|
175
|
-
})
|
|
176
|
-
|
|
177
|
-
it('keeps a non-transient api-key failure as "missing" (unchanged 401 behavior)', async () => {
|
|
178
|
-
const { resolveAuthFromRequestDetailed } = await import('@open-mercato/shared/lib/auth/server')
|
|
179
|
-
findApiKeyBySecret.mockRejectedValue(new Error('unexpected non-db failure'))
|
|
180
|
-
|
|
181
|
-
const request = new Request('https://example.test/api/test', {
|
|
182
|
-
headers: { 'x-api-key': 'non-transient-key' },
|
|
183
|
-
})
|
|
184
|
-
|
|
185
|
-
await expect(resolveAuthFromRequestDetailed(request)).resolves.toEqual({ auth: null, status: 'missing' })
|
|
186
|
-
})
|
|
187
164
|
})
|
package/src/lib/auth/server.ts
CHANGED
|
@@ -2,7 +2,6 @@ import { cookies } from 'next/headers.js'
|
|
|
2
2
|
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
3
3
|
import { verifyJwt } from './jwt'
|
|
4
4
|
import { getSharedApiKeyAuthCache } from './apiKeyAuthCache'
|
|
5
|
-
import { isTransientDbError } from '@open-mercato/shared/lib/db/pg-errors'
|
|
6
5
|
|
|
7
6
|
const TENANT_COOKIE_NAME = 'om_selected_tenant'
|
|
8
7
|
const ORGANIZATION_COOKIE_NAME = 'om_selected_org'
|
|
@@ -254,14 +253,7 @@ async function resolveApiKeyAuth(secret: string): Promise<AuthContext> {
|
|
|
254
253
|
}
|
|
255
254
|
cache.setSuccess(secret, auth, record.expiresAt ? record.expiresAt.getTime() : null)
|
|
256
255
|
return auth
|
|
257
|
-
} catch
|
|
258
|
-
// A transient DB failure (pool exhausted, `max_connections` reached, DB
|
|
259
|
-
// restarting) means we could not confirm the key — NOT that it is invalid.
|
|
260
|
-
// Surface it so callers return a retryable 503 instead of masking it as an
|
|
261
|
-
// auth miss (401). Genuine misses already returned `null` above.
|
|
262
|
-
if (isTransientDbError(err)) {
|
|
263
|
-
throw new AuthResolutionUnavailableError(err)
|
|
264
|
-
}
|
|
256
|
+
} catch {
|
|
265
257
|
return null
|
|
266
258
|
}
|
|
267
259
|
}
|
|
@@ -373,20 +365,7 @@ export async function resolveAuthFromRequestDetailed(req: Request): Promise<Auth
|
|
|
373
365
|
if (!apiKey) {
|
|
374
366
|
return { auth: null, status: resolveUnauthenticatedStatus() }
|
|
375
367
|
}
|
|
376
|
-
|
|
377
|
-
try {
|
|
378
|
-
apiAuth = await resolveApiKeyAuth(apiKey)
|
|
379
|
-
} catch (err) {
|
|
380
|
-
// Only a transient canonical-resolution failure maps to 'error' (retryable
|
|
381
|
-
// 503), mirroring the interactive-token path above. Anything else is an
|
|
382
|
-
// unexpected bug — rethrow so it surfaces as a 500 rather than being masked
|
|
383
|
-
// as an auth failure.
|
|
384
|
-
if (!(err instanceof AuthResolutionUnavailableError)) {
|
|
385
|
-
throw err
|
|
386
|
-
}
|
|
387
|
-
hadUnavailableResolution = true
|
|
388
|
-
return { auth: null, status: resolveUnauthenticatedStatus() }
|
|
389
|
-
}
|
|
368
|
+
const apiAuth = await resolveApiKeyAuth(apiKey)
|
|
390
369
|
if (!apiAuth) {
|
|
391
370
|
return { auth: null, status: resolveUnauthenticatedStatus() }
|
|
392
371
|
}
|
|
@@ -13,34 +13,13 @@
|
|
|
13
13
|
* The .mjs stubs use module.exports because Jest's CJS runtime handles the
|
|
14
14
|
* dynamic import() and does not transform .mjs files; the loader consumes the
|
|
15
15
|
* named exports identically either way.
|
|
16
|
-
*
|
|
17
|
-
* The third case guards #4491: the compatibility fallback to an empty list must
|
|
18
|
-
* stay silent for an absent registry, but must report a registry that exists and
|
|
19
|
-
* fails to load — otherwise the #4327 condition can recur with no diagnostics.
|
|
20
16
|
*/
|
|
21
|
-
jest.mock('../../logger', () => {
|
|
22
|
-
const logger = {
|
|
23
|
-
debug: jest.fn(),
|
|
24
|
-
info: jest.fn(),
|
|
25
|
-
warn: jest.fn(),
|
|
26
|
-
error: jest.fn(),
|
|
27
|
-
child: () => logger,
|
|
28
|
-
}
|
|
29
|
-
return { createLogger: () => logger }
|
|
30
|
-
})
|
|
31
|
-
|
|
32
17
|
import fs from 'node:fs'
|
|
33
18
|
import os from 'node:os'
|
|
34
19
|
import path from 'node:path'
|
|
35
|
-
import { createLogger } from '../../logger'
|
|
36
20
|
import crypto from 'node:crypto'
|
|
37
21
|
import { loadBootstrapData } from '../dynamicLoader'
|
|
38
22
|
|
|
39
|
-
const mockedLogger = createLogger('shared') as unknown as {
|
|
40
|
-
debug: jest.Mock
|
|
41
|
-
error: jest.Mock
|
|
42
|
-
}
|
|
43
|
-
|
|
44
23
|
const GENERATED_MODULES: Record<string, { ts: string; compiled: string }> = {
|
|
45
24
|
'entities.ids.generated': { ts: 'export const E = {}', compiled: 'module.exports = { E: {} }' },
|
|
46
25
|
'modules.cli.generated': { ts: 'export const modules = []', compiled: 'module.exports = { modules: [] }' },
|
|
@@ -92,36 +71,21 @@ function writeGeneratedModule(generatedDir: string, baseName: string, source: {
|
|
|
92
71
|
}))
|
|
93
72
|
}
|
|
94
73
|
|
|
95
|
-
const createdAppRoots: string[] = []
|
|
96
|
-
|
|
97
|
-
function createAppRoot(overrides: Record<string, { ts: string; compiled: string }> = {}): string {
|
|
98
|
-
const appRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'om-bootstrap-4327-'))
|
|
99
|
-
const generatedDir = path.join(appRoot, '.mercato', 'generated')
|
|
100
|
-
fs.mkdirSync(generatedDir, { recursive: true })
|
|
101
|
-
fs.writeFileSync(path.join(appRoot, 'tsconfig.json'), APP_TSCONFIG)
|
|
102
|
-
for (const [baseName, source] of Object.entries({ ...GENERATED_MODULES, ...overrides })) {
|
|
103
|
-
writeGeneratedModule(generatedDir, baseName, source)
|
|
104
|
-
}
|
|
105
|
-
createdAppRoots.push(appRoot)
|
|
106
|
-
return appRoot
|
|
107
|
-
}
|
|
108
|
-
|
|
109
74
|
describe('loadBootstrapData — command interceptors reach worker/CLI bootstrap (#4327)', () => {
|
|
110
75
|
let appRoot: string
|
|
111
76
|
|
|
112
77
|
beforeAll(() => {
|
|
113
|
-
appRoot =
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
for (const
|
|
118
|
-
|
|
78
|
+
appRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'om-bootstrap-4327-'))
|
|
79
|
+
const generatedDir = path.join(appRoot, '.mercato', 'generated')
|
|
80
|
+
fs.mkdirSync(generatedDir, { recursive: true })
|
|
81
|
+
fs.writeFileSync(path.join(appRoot, 'tsconfig.json'), APP_TSCONFIG)
|
|
82
|
+
for (const [baseName, source] of Object.entries(GENERATED_MODULES)) {
|
|
83
|
+
writeGeneratedModule(generatedDir, baseName, source)
|
|
119
84
|
}
|
|
120
85
|
})
|
|
121
86
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
mockedLogger.error.mockClear()
|
|
87
|
+
afterAll(() => {
|
|
88
|
+
fs.rmSync(appRoot, { recursive: true, force: true })
|
|
125
89
|
})
|
|
126
90
|
|
|
127
91
|
it('returns commandInterceptorEntries from command-interceptors.generated', async () => {
|
|
@@ -141,24 +105,5 @@ describe('loadBootstrapData — command interceptors reach worker/CLI bootstrap
|
|
|
141
105
|
|
|
142
106
|
expect(data.commandInterceptorEntries).toEqual([])
|
|
143
107
|
expect(data.commandLoaderEntries).toEqual([])
|
|
144
|
-
expect(mockedLogger.error).not.toHaveBeenCalled()
|
|
145
|
-
})
|
|
146
|
-
|
|
147
|
-
it('logs an error when the generated file exists but fails to import (#4491)', async () => {
|
|
148
|
-
const brokenAppRoot = createAppRoot({
|
|
149
|
-
'command-interceptors.generated': {
|
|
150
|
-
ts: 'export const commandInterceptorEntries = []',
|
|
151
|
-
compiled: "throw new Error('command-interceptors.generated is broken')",
|
|
152
|
-
},
|
|
153
|
-
})
|
|
154
|
-
|
|
155
|
-
const data = await loadBootstrapData(brokenAppRoot)
|
|
156
|
-
|
|
157
|
-
expect(data.commandInterceptorEntries).toEqual([])
|
|
158
|
-
expect(mockedLogger.error).toHaveBeenCalledTimes(1)
|
|
159
|
-
const [message, fields] = mockedLogger.error.mock.calls[0] as [string, Record<string, unknown>]
|
|
160
|
-
expect(message).toContain('Failed to load generated registry')
|
|
161
|
-
expect(fields.file).toBe('command-interceptors.generated.ts')
|
|
162
|
-
expect((fields.err as Error).message).toContain('command-interceptors.generated is broken')
|
|
163
108
|
})
|
|
164
109
|
})
|
|
@@ -81,11 +81,7 @@ function loadBootstrapDataInNode(appRoot: string): {
|
|
|
81
81
|
return JSON.parse(execFileSync(
|
|
82
82
|
process.execPath,
|
|
83
83
|
['--import', 'tsx', '--input-type=module', '-e', script, appRoot],
|
|
84
|
-
{
|
|
85
|
-
cwd: process.cwd(),
|
|
86
|
-
encoding: 'utf8',
|
|
87
|
-
env: { ...process.env, OM_LOG_DESTINATION: 'stderr' },
|
|
88
|
-
},
|
|
84
|
+
{ cwd: process.cwd(), encoding: 'utf8' },
|
|
89
85
|
))
|
|
90
86
|
}
|
|
91
87
|
|
|
@@ -216,22 +212,6 @@ describe('dynamic loader app tsconfig and content-addressed cache', () => {
|
|
|
216
212
|
expect(after.inputHash).not.toBe(before.inputHash)
|
|
217
213
|
})
|
|
218
214
|
|
|
219
|
-
it('excludes client-only virtual inputs from cache dependencies', async () => {
|
|
220
|
-
const appRoot = createAppRoot()
|
|
221
|
-
const generatedDir = path.join(appRoot, '.mercato', 'generated')
|
|
222
|
-
fs.writeFileSync(path.join(generatedDir, 'modules.cli.generated.ts'), `
|
|
223
|
-
export const modules = [{ widget: () => import('./widget.client') }]
|
|
224
|
-
`)
|
|
225
|
-
|
|
226
|
-
loadBootstrapDataInNode(appRoot)
|
|
227
|
-
|
|
228
|
-
const metadata = readCacheMetadata(appRoot, 'modules.cli')
|
|
229
|
-
expect(Object.keys(metadata.dependencies)).not.toContain('om-client-only-stub:./widget.client')
|
|
230
|
-
expect(
|
|
231
|
-
fs.readFileSync(path.join(generatedDir, 'modules.cli.generated.mjs'), 'utf8'),
|
|
232
|
-
).toContain('clientOnlyModuleUnavailable')
|
|
233
|
-
})
|
|
234
|
-
|
|
235
215
|
it('invalidates compiled output when only a bundled local dependency changes', async () => {
|
|
236
216
|
const appRoot = createAppRoot()
|
|
237
217
|
const generatedSourcePath = path.join(
|