@open-mercato/core 0.6.8-develop.6899.1.433952fd93 → 0.6.8-develop.6903.1.0ec850a22b

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.
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
2
2
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
3
3
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
4
4
  import { resolveFeatureCheckContext, resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
5
+ import { getCommandInterceptorHttpRejection } from "@open-mercato/shared/lib/commands/errors";
5
6
  import { z } from "zod";
6
7
  import { createLogger } from "@open-mercato/shared/lib/logger";
7
8
  const logger = createLogger("audit_logs").child({ component: "undo" });
@@ -79,6 +80,10 @@ async function POST(req) {
79
80
  await commandBus.undo(undoToken, ctx);
80
81
  return NextResponse.json({ ok: true, logId: target.id });
81
82
  } catch (err) {
83
+ const interceptorRejection = getCommandInterceptorHttpRejection(err);
84
+ if (interceptorRejection) {
85
+ return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status });
86
+ }
82
87
  logger.error("Undo failed", { err });
83
88
  return NextResponse.json({ error: "Undo failed" }, { status: 400 });
84
89
  }
@@ -111,7 +116,12 @@ const openApi = {
111
116
  errors: [
112
117
  { status: 400, description: "Invalid or unavailable undo token", schema: errorSchema },
113
118
  { status: 401, description: "Authentication required", schema: errorSchema },
114
- { status: 403, description: "Undo blocked by organization or tenant scope", schema: errorSchema }
119
+ { status: 403, description: "Undo blocked by organization or tenant scope", schema: errorSchema },
120
+ {
121
+ status: 422,
122
+ description: "Undo deliberately blocked by a beforeUndo command interceptor. The interceptor chooses the status (any 4xx/5xx) and may replace the body.",
123
+ schema: errorSchema
124
+ }
115
125
  ]
116
126
  }
117
127
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/audit_logs/api/audit-logs/actions/undo/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { getAuthFromRequest, type AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { resolveFeatureCheckContext, resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CommandBus } from '@open-mercato/shared/lib/commands/command-bus'\nimport { ActionLogService } from '@open-mercato/core/modules/audit_logs/services/actionLogService'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport type { AwilixContainer } from 'awilix'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('audit_logs').child({ component: 'undo' })\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['audit_logs.undo_self'] },\n}\n\ntype UndoRequestBody = {\n undoToken?: string\n}\n\nconst undoRequestSchema = z.object({\n undoToken: z.string().min(1).describe('Undo token issued by the action log entry'),\n})\n\nconst undoResponseSchema = z.object({\n ok: z.literal(true),\n logId: z.string().describe('Identifier of the action log that was undone'),\n})\n\nconst errorSchema = z.object({\n error: z.string(),\n})\n\nexport async function POST(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const body = (await req.json().catch(() => null)) as UndoRequestBody | null\n const undoToken = body?.undoToken?.trim()\n if (!undoToken) return NextResponse.json({ error: 'Invalid undo token' }, { status: 400 })\n\n const container = await createRequestContainer()\n const commandBus = (container.resolve('commandBus') as CommandBus)\n const logs = (container.resolve('actionLogService') as ActionLogService)\n let rbac: RbacService | null = null\n try {\n rbac = (container.resolve('rbacService') as RbacService)\n } catch {\n rbac = null\n }\n\n const { organizationId } = await resolveFeatureCheckContext({ container, auth, request: req })\n\n const canUndoTenant = rbac\n ? await rbac.userHasAllFeatures(auth.sub, ['audit_logs.undo_tenant'], {\n tenantId: auth.tenantId ?? null,\n organizationId,\n })\n : false\n\n const target = await logs.findByUndoToken(undoToken)\n if (!target || target.executionState !== 'done') {\n return NextResponse.json({ error: 'Undo token not available' }, { status: 400 })\n }\n if (target.actorUserId && target.actorUserId !== auth.sub && !canUndoTenant) {\n return NextResponse.json({ error: 'Undo token not available' }, { status: 400 })\n }\n // Fail closed on tenant scope: `audit_logs.undo_tenant` only widens scope WITHIN a\n // tenant, never across tenants, so a tenant-scoped target always requires a caller\n // bound to that same tenant. A caller whose tenantId is null (tenant-less global\n // account or unscoped API key) must never undo a tenant-scoped row (issue #2685).\n if (target.tenantId && target.tenantId !== (auth.tenantId ?? null)) {\n return NextResponse.json({ error: 'Undo token not available' }, { status: 400 })\n }\n const scopedOrgId = canUndoTenant ? organizationId ?? null : organizationId ?? auth.orgId ?? null\n // Tenant-level undoers may undo across organizations within the tenant, so an\n // unresolved (null) caller org is allowed and only an explicit mismatch is rejected.\n // Every other caller must resolve to the target's own organization \u2014 a null caller\n // org must not bypass an org-scoped target (issue #2685).\n const orgScopeMismatch = canUndoTenant\n ? Boolean(target.organizationId && scopedOrgId && target.organizationId !== scopedOrgId)\n : Boolean(target.organizationId && target.organizationId !== scopedOrgId)\n if (orgScopeMismatch) {\n return NextResponse.json({ error: 'Undo token not available' }, { status: 400 })\n }\n\n const lookupActorId = canUndoTenant ? (target.actorUserId ?? auth.sub) : auth.sub\n // Scope the latest-undoable re-lookup to the target row's own organization, not\n // the caller's currently-resolved org. The actor/tenant/org guards above already\n // authorized the caller for this row; reusing the caller's scope here breaks undo\n // for tenant-level rows (organization create/update/delete/reparent log with a\n // null organization_id) whenever the caller resolves to a concrete home org, so\n // the lookup never matches and returns \"Undo token not available\" (issue #2398).\n const lookupOrgId = target.organizationId ?? null\n let latest = null\n if (target.resourceKind || target.resourceId) {\n latest = await logs.latestUndoableForResource({\n actorUserId: lookupActorId,\n tenantId: auth.tenantId ?? null,\n organizationId: lookupOrgId,\n resourceKind: target.resourceKind ?? undefined,\n resourceId: target.resourceId ?? undefined,\n })\n }\n if (!latest) {\n latest = await logs.latestUndoableForActor(lookupActorId, {\n tenantId: auth.tenantId ?? null,\n organizationId: lookupOrgId,\n })\n }\n if (!latest || latest.id !== target.id) {\n return NextResponse.json({ error: 'Undo token not available' }, { status: 400 })\n }\n\n try {\n const ctx = await createRuntimeContext(container, auth, req)\n await commandBus.undo(undoToken, ctx)\n return NextResponse.json({ ok: true, logId: target.id })\n } catch (err) {\n logger.error('Undo failed', { err })\n return NextResponse.json({ error: 'Undo failed' }, { status: 400 })\n }\n}\n\nasync function createRuntimeContext(container: AwilixContainer, auth: AuthContext, request: Request): Promise<CommandRuntimeContext> {\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n return {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: scope.selectedId,\n organizationIds: scope.filterIds,\n request,\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Undo a recent action',\n description: 'Executes the undo operation for the most recent undoable action belonging to the caller.',\n methods: {\n POST: {\n summary: 'Undo action by token',\n description:\n 'Replays the undo handler registered for a command. The provided undo token must match the latest undoable log entry accessible to the caller.',\n requestBody: {\n contentType: 'application/json',\n schema: undoRequestSchema,\n },\n responses: [\n { status: 200, description: 'Undo applied successfully', schema: undoResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid or unavailable undo token', schema: errorSchema },\n { status: 401, description: 'Authentication required', schema: errorSchema },\n { status: 403, description: 'Undo blocked by organization or tenant scope', schema: errorSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,0BAA4C;AACrD,SAAS,8BAA8B;AACvC,SAAS,4BAA4B,0CAA0C;AAM/E,SAAS,SAAS;AAElB,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,YAAY,EAAE,MAAM,EAAE,WAAW,OAAO,CAAC;AAE9D,MAAM,WAAW;A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thContext } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { resolveFeatureCheckContext, resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CommandBus } from '@open-mercato/shared/lib/commands/command-bus'\nimport { ActionLogService } from '@open-mercato/core/modules/audit_logs/services/actionLogService'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport type { AwilixContainer } from 'awilix'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('audit_logs').child({ component: 'undo' })\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['audit_logs.undo_self'] },\n}\n\ntype UndoRequestBody = {\n undoToken?: string\n}\n\nconst undoRequestSchema = z.object({\n undoToken: z.string().min(1).describe('Undo token issued by the action log entry'),\n})\n\nconst undoResponseSchema = z.object({\n ok: z.literal(true),\n logId: z.string().describe('Identifier of the action log that was undone'),\n})\n\nconst errorSchema = z.object({\n error: z.string(),\n})\n\nexport async function POST(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const body = (await req.json().catch(() => null)) as UndoRequestBody | null\n const undoToken = body?.undoToken?.trim()\n if (!undoToken) return NextResponse.json({ error: 'Invalid undo token' }, { status: 400 })\n\n const container = await createRequestContainer()\n const commandBus = (container.resolve('commandBus') as CommandBus)\n const logs = (container.resolve('actionLogService') as ActionLogService)\n let rbac: RbacService | null = null\n try {\n rbac = (container.resolve('rbacService') as RbacService)\n } catch {\n rbac = null\n }\n\n const { organizationId } = await resolveFeatureCheckContext({ container, auth, request: req })\n\n const canUndoTenant = rbac\n ? await rbac.userHasAllFeatures(auth.sub, ['audit_logs.undo_tenant'], {\n tenantId: auth.tenantId ?? null,\n organizationId,\n })\n : false\n\n const target = await logs.findByUndoToken(undoToken)\n if (!target || target.executionState !== 'done') {\n return NextResponse.json({ error: 'Undo token not available' }, { status: 400 })\n }\n if (target.actorUserId && target.actorUserId !== auth.sub && !canUndoTenant) {\n return NextResponse.json({ error: 'Undo token not available' }, { status: 400 })\n }\n // Fail closed on tenant scope: `audit_logs.undo_tenant` only widens scope WITHIN a\n // tenant, never across tenants, so a tenant-scoped target always requires a caller\n // bound to that same tenant. A caller whose tenantId is null (tenant-less global\n // account or unscoped API key) must never undo a tenant-scoped row (issue #2685).\n if (target.tenantId && target.tenantId !== (auth.tenantId ?? null)) {\n return NextResponse.json({ error: 'Undo token not available' }, { status: 400 })\n }\n const scopedOrgId = canUndoTenant ? organizationId ?? null : organizationId ?? auth.orgId ?? null\n // Tenant-level undoers may undo across organizations within the tenant, so an\n // unresolved (null) caller org is allowed and only an explicit mismatch is rejected.\n // Every other caller must resolve to the target's own organization \u2014 a null caller\n // org must not bypass an org-scoped target (issue #2685).\n const orgScopeMismatch = canUndoTenant\n ? Boolean(target.organizationId && scopedOrgId && target.organizationId !== scopedOrgId)\n : Boolean(target.organizationId && target.organizationId !== scopedOrgId)\n if (orgScopeMismatch) {\n return NextResponse.json({ error: 'Undo token not available' }, { status: 400 })\n }\n\n const lookupActorId = canUndoTenant ? (target.actorUserId ?? auth.sub) : auth.sub\n // Scope the latest-undoable re-lookup to the target row's own organization, not\n // the caller's currently-resolved org. The actor/tenant/org guards above already\n // authorized the caller for this row; reusing the caller's scope here breaks undo\n // for tenant-level rows (organization create/update/delete/reparent log with a\n // null organization_id) whenever the caller resolves to a concrete home org, so\n // the lookup never matches and returns \"Undo token not available\" (issue #2398).\n const lookupOrgId = target.organizationId ?? null\n let latest = null\n if (target.resourceKind || target.resourceId) {\n latest = await logs.latestUndoableForResource({\n actorUserId: lookupActorId,\n tenantId: auth.tenantId ?? null,\n organizationId: lookupOrgId,\n resourceKind: target.resourceKind ?? undefined,\n resourceId: target.resourceId ?? undefined,\n })\n }\n if (!latest) {\n latest = await logs.latestUndoableForActor(lookupActorId, {\n tenantId: auth.tenantId ?? null,\n organizationId: lookupOrgId,\n })\n }\n if (!latest || latest.id !== target.id) {\n return NextResponse.json({ error: 'Undo token not available' }, { status: 400 })\n }\n\n try {\n const ctx = await createRuntimeContext(container, auth, req)\n await commandBus.undo(undoToken, ctx)\n return NextResponse.json({ ok: true, logId: target.id })\n } catch (err) {\n // A beforeUndo interceptor that blocked with an explicit status is a deliberate business\n // rejection, not an undo failure \u2014 surface its status and message (issue #5045).\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n logger.error('Undo failed', { err })\n return NextResponse.json({ error: 'Undo failed' }, { status: 400 })\n }\n}\n\nasync function createRuntimeContext(container: AwilixContainer, auth: AuthContext, request: Request): Promise<CommandRuntimeContext> {\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n return {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: scope.selectedId,\n organizationIds: scope.filterIds,\n request,\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Undo a recent action',\n description: 'Executes the undo operation for the most recent undoable action belonging to the caller.',\n methods: {\n POST: {\n summary: 'Undo action by token',\n description:\n 'Replays the undo handler registered for a command. The provided undo token must match the latest undoable log entry accessible to the caller.',\n requestBody: {\n contentType: 'application/json',\n schema: undoRequestSchema,\n },\n responses: [\n { status: 200, description: 'Undo applied successfully', schema: undoResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid or unavailable undo token', schema: errorSchema },\n { status: 401, description: 'Authentication required', schema: errorSchema },\n { status: 403, description: 'Undo blocked by organization or tenant scope', schema: errorSchema },\n {\n status: 422,\n description:\n 'Undo deliberately blocked by a beforeUndo command interceptor. The interceptor chooses the status (any 4xx/5xx) and may replace the body.',\n schema: errorSch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QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,6BAA6B,QAAQ,mBAAmB;AAAA,MACtF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,qCAAqC,QAAQ,YAAY;AAAA,QACrF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,YAAY;AAAA,QAC3E,EAAE,QAAQ,KAAK,aAAa,gDAAgD,QAAQ,YAAY;AAAA,QAChG;AAAA,UACE,QAAQ;AAAA,UACR,aACE;AAAA,UACF,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -84,6 +84,7 @@ async function GET(req) {
84
84
  widgets
85
85
  );
86
86
  const allowedWidgets = widgets.filter((w) => allowedIds.includes(w.metadata.id));
87
+ const hasRegisteredWidgets = widgets.length > 0;
87
88
  let layout = await loadScopeLayout(em, scope);
88
89
  let items = layout ? normalizeLayoutItems(layout.layoutJson) : [];
89
90
  let hasChanged = false;
@@ -97,15 +98,17 @@ async function GET(req) {
97
98
  size: widget.metadata.defaultSize ?? DEFAULT_SIZE,
98
99
  settings: widget.metadata.defaultSettings ?? void 0
99
100
  }));
100
- layout = em.create(DashboardLayout, {
101
- userId: scope.userId,
102
- tenantId: scope.tenantId,
103
- organizationId: scope.organizationId,
104
- layoutJson: items
105
- });
106
- em.persist(layout);
107
- hasChanged = true;
108
- } else {
101
+ if (hasRegisteredWidgets) {
102
+ layout = em.create(DashboardLayout, {
103
+ userId: scope.userId,
104
+ tenantId: scope.tenantId,
105
+ organizationId: scope.organizationId,
106
+ layoutJson: items
107
+ });
108
+ em.persist(layout);
109
+ hasChanged = true;
110
+ }
111
+ } else if (hasRegisteredWidgets) {
109
112
  const existingLayout = layout;
110
113
  const filtered = items.filter((item) => allowedIds.includes(item.widgetId));
111
114
  if (filtered.length !== items.length) {
@@ -214,6 +217,9 @@ async function PUT(req) {
214
217
  return NextResponse.json(guardResult.body, { status: guardResult.status });
215
218
  }
216
219
  const widgets = await loadAllWidgets();
220
+ if (widgets.length === 0) {
221
+ return NextResponse.json({ error: "Widget registry unavailable" }, { status: 503 });
222
+ }
217
223
  const effectiveFeatures = await rbac.getEffectiveFeatures(scope.userId, {
218
224
  tenantId: scope.tenantId,
219
225
  organizationId: scope.organizationId
@@ -301,7 +307,8 @@ const layoutPutDoc = {
301
307
  errors: [
302
308
  { status: 400, description: "Invalid layout payload", schema: dashboardsErrorSchema },
303
309
  { status: 401, description: "Authentication required", schema: dashboardsErrorSchema },
304
- { status: 403, description: "Missing dashboards.configure feature", schema: dashboardsErrorSchema }
310
+ { status: 403, description: "Missing dashboards.configure feature", schema: dashboardsErrorSchema },
311
+ { status: 503, description: "Widget registry unavailable \u2014 the layout was not saved", schema: dashboardsErrorSchema }
305
312
  ]
306
313
  };
307
314
  const openApi = {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/dashboards/api/layout/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { randomUUID } from 'node:crypto'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { DashboardLayout } from '@open-mercato/core/modules/dashboards/data/entities'\nimport { dashboardLayoutSchema } from '@open-mercato/core/modules/dashboards/data/validators'\nimport { loadAllWidgets } from '@open-mercato/core/modules/dashboards/lib/widgets'\nimport { resolveAllowedWidgetIds } from '@open-mercato/core/modules/dashboards/lib/access'\nimport { authorizeFeatures } from '@open-mercato/shared/security/featurePolicy'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n dashboardsTag,\n dashboardsErrorSchema,\n dashboardsOkSchema,\n dashboardLayoutStateSchema,\n} from '../openapi'\n\nconst DEFAULT_SIZE = 'md'\nconst RESOURCE_KIND = 'dashboards.layout'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['dashboards.view'] },\n PUT: { requireAuth: true, requireFeatures: ['dashboards.configure'] },\n}\n\ntype LayoutScope = {\n userId: string\n tenantId: string | null\n organizationId: string | null\n}\n\nasync function loadScopeLayout(em: any, scope: LayoutScope): Promise<DashboardLayout | null> {\n return await em.findOne(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n })\n}\n\nfunction normalizeLayoutItems(items: any[]) {\n const list = Array.isArray(items) ? items : []\n const seenIds = new Set<string>()\n const sanitized = list\n .filter((item) => item && typeof item === 'object')\n .map((item) => ({\n id: String(item.id),\n widgetId: String(item.widgetId),\n order: Number.isInteger(item.order) ? Number(item.order) : undefined,\n priority: Number.isInteger(item.priority) ? Number(item.priority) : undefined,\n size: typeof item.size === 'string' ? item.size : undefined,\n settings: item.settings,\n }))\n .filter((item) => {\n if (!item.id || !item.widgetId) return false\n if (seenIds.has(item.id)) return false\n seenIds.add(item.id)\n return true\n })\n .sort((a, b) => {\n const aOrder = a.order ?? a.priority ?? 0\n const bOrder = b.order ?? b.priority ?? 0\n return aOrder - bOrder\n })\n .map((item, idx) => ({ ...item, order: idx, priority: idx }))\n return sanitized\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n // Use a fresh fork to avoid carrying over pending entities from other operations\n const em = (container.resolve('em') as any).fork({ clear: true, freshEventManager: true, useContext: true })\n const rbac = container.resolve('rbacService') as any\n const url = new URL(req.url)\n\n const scope: LayoutScope = {\n userId: String(auth.sub),\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n }\n\n const effectiveFeatures = await rbac.getEffectiveFeatures(scope.userId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n const widgets = await loadAllWidgets()\n const allowedIds = await resolveAllowedWidgetIds(\n em,\n {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n features: effectiveFeatures,\n isSuperAdmin: false,\n },\n widgets,\n )\n const allowedWidgets = widgets.filter((w) => allowedIds.includes(w.metadata.id))\n\n let layout = await loadScopeLayout(em, scope)\n let items = layout ? normalizeLayoutItems(layout.layoutJson) : []\n let hasChanged = false\n\n if (!layout) {\n const defaults = allowedWidgets.filter((widget) => widget.metadata.defaultEnabled)\n items = defaults.map((widget, index) => ({\n id: randomUUID(),\n widgetId: widget.metadata.id,\n order: index,\n priority: index,\n size: widget.metadata.defaultSize ?? DEFAULT_SIZE,\n settings: widget.metadata.defaultSettings ?? undefined,\n }))\n layout = em.create(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n layoutJson: items,\n })\n em.persist(layout)\n hasChanged = true\n } else {\n const existingLayout = layout\n const filtered = items.filter((item) => allowedIds.includes(item.widgetId))\n if (filtered.length !== items.length) {\n hasChanged = true\n items = filtered\n }\n items = items.map((item, index) => (item.order !== index || item.priority !== index ? { ...item, order: index, priority: index } : item))\n if (\n existingLayout.layoutJson.length !== items.length ||\n items.some((item, idx) => existingLayout.layoutJson[idx]?.id !== item.id)\n ) {\n hasChanged = true\n }\n existingLayout.layoutJson = items\n layout = existingLayout\n }\n\n if (hasChanged) {\n await em.flush()\n }\n\n const canConfigure = authorizeFeatures(['dashboards.configure'], {\n grantedFeatures: effectiveFeatures,\n })\n\n let userEmail: string | null = null\n let userName: string | null = null\n let userLabel: string | null = null\n const user = await findOneWithDecryption(\n em,\n User,\n { id: scope.userId, deletedAt: null },\n undefined,\n { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId ?? null },\n )\n if (user) {\n userName = user.name?.trim() ?? null\n userEmail = user.email ?? null\n userLabel = (userName && userName.length > 0 ? userName : userEmail) ?? null\n }\n if (!userLabel) {\n userLabel = scope.userId\n }\n\n const response = {\n layout: { items },\n allowedWidgetIds: allowedIds,\n canConfigure,\n context: {\n ...scope,\n userName,\n userEmail,\n userLabel,\n },\n widgets: allowedWidgets.map((widget) => ({\n id: widget.metadata.id,\n title: widget.metadata.title,\n description: widget.metadata.description ?? null,\n defaultSize: widget.metadata.defaultSize ?? DEFAULT_SIZE,\n defaultEnabled: !!widget.metadata.defaultEnabled,\n defaultSettings: widget.metadata.defaultSettings ?? null,\n features: widget.metadata.features ?? [],\n moduleId: widget.moduleId,\n icon: widget.metadata.icon ?? null,\n loaderKey: widget.key,\n supportsRefresh: !!widget.metadata.supportsRefresh,\n })),\n }\n\n return NextResponse.json(response)\n}\n\nexport async function PUT(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })\n }\n const parsed = dashboardLayoutSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid layout payload', issues: parsed.error.issues }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const { resolve } = container\n const em = (resolve('em') as any).fork({ clear: true, freshEventManager: true, useContext: true })\n const rbac = resolve('rbacService') as any\n\n const scope: LayoutScope = {\n userId: String(auth.sub),\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n }\n\n const canConfigure = await rbac.userHasAllFeatures(\n scope.userId,\n ['dashboards.configure'],\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n if (!canConfigure) {\n return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n }\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: scope.tenantId ?? '',\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: RESOURCE_KIND,\n resourceId: scope.userId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: { items: parsed.data.items },\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const widgets = await loadAllWidgets()\n const effectiveFeatures = await rbac.getEffectiveFeatures(scope.userId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n const allowedIds = await resolveAllowedWidgetIds(\n em,\n {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n features: effectiveFeatures,\n isSuperAdmin: false,\n },\n widgets,\n )\n const allowedSet = new Set(allowedIds)\n\n const payloadItems = parsed.data.items\n const sanitized = payloadItems\n .map((item, index) => ({\n id: item.id,\n widgetId: item.widgetId,\n order: index,\n priority: index,\n size: item.size ?? DEFAULT_SIZE,\n settings: item.settings,\n }))\n .filter((item) => allowedSet.has(item.widgetId))\n\n const uniqueIds = new Set(sanitized.map((item) => item.id))\n if (uniqueIds.size !== sanitized.length) {\n return NextResponse.json({ error: 'Layout item IDs must be unique' }, { status: 400 })\n }\n\n let layout = await loadScopeLayout(em, scope)\n if (!layout) {\n layout = em.create(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n layoutJson: sanitized,\n })\n em.persist(layout)\n } else {\n layout.layoutJson = sanitized\n }\n await em.flush()\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: scope.tenantId ?? '',\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: RESOURCE_KIND,\n resourceId: scope.userId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({ ok: true })\n}\n\nconst layoutGetDoc: OpenApiMethodDoc = {\n summary: 'Load the current dashboard layout',\n description: 'Returns the saved widget layout together with the widgets the current user is allowed to place.',\n tags: [dashboardsTag],\n responses: [\n {\n status: 200,\n description: 'Current dashboard layout and available widgets.',\n schema: dashboardLayoutStateSchema,\n },\n ],\n errors: [\n { status: 401, description: 'Authentication required', schema: dashboardsErrorSchema },\n ],\n}\n\nconst layoutPutDoc: OpenApiMethodDoc = {\n summary: 'Persist dashboard layout changes',\n description: 'Saves the provided widget ordering, sizes, and settings for the current user.',\n tags: [dashboardsTag],\n requestBody: {\n contentType: 'application/json',\n schema: dashboardLayoutSchema,\n description: 'List of dashboard widgets with ordering, sizing, and settings.',\n },\n responses: [\n { status: 200, description: 'Layout updated successfully.', schema: dashboardsOkSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid layout payload', schema: dashboardsErrorSchema },\n { status: 401, description: 'Authentication required', schema: dashboardsErrorSchema },\n { status: 403, description: 'Missing dashboards.configure feature', schema: dashboardsErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dashboardsTag,\n summary: 'Manage personal dashboard layout',\n methods: {\n GET: layoutGetDoc,\n PUT: layoutPutDoc,\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,yBAAyB;AAClC,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,eAAe;AACrB,MAAM,gBAAgB;AAEf,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,iBAAiB,EAAE;AAAA,EAC/D,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,sBAAsB,EAAE;AACtE;AAQA,eAAe,gBAAgB,IAAS,OAAqD;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AAI,KAAK,CAAC;AACvC;AAEA,MAAM,eAAiC;AAAA,EACrC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,aAAa;AAAA,EACpB,WAAW;AAAA,IACT;AAAA,MACE,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,QAAQ;AAAA,IACV;AAAA,EACF;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,sBAAsB;AAAA,EACvF;AACF;AAEA,MAAM,eAAiC;AAAA,EACrC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,aAAa;AAAA,EACpB,aAAa;AAAA,IACX,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,gCAAgC,QAAQ,mBAAmB;AAAA,EACzF;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,sBAAsB;AAAA,IACpF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,sBAAsB;AAAA,IACrF,EAAE,QAAQ,KAAK,aAAa,wCAAwC,QAAQ,sBAAsB;AAAA,EACpG;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,IACL,KAAK;AAAA,EACP;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { randomUUID } from 'node:crypto'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { DashboardLayout } from '@open-mercato/core/modules/dashboards/data/entities'\nimport { dashboardLayoutSchema } from '@open-mercato/core/modules/dashboards/data/validators'\nimport { loadAllWidgets } from '@open-mercato/core/modules/dashboards/lib/widgets'\nimport { resolveAllowedWidgetIds } from '@open-mercato/core/modules/dashboards/lib/access'\nimport { authorizeFeatures } from '@open-mercato/shared/security/featurePolicy'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n dashboardsTag,\n dashboardsErrorSchema,\n dashboardsOkSchema,\n dashboardLayoutStateSchema,\n} from '../openapi'\n\nconst DEFAULT_SIZE = 'md'\nconst RESOURCE_KIND = 'dashboards.layout'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['dashboards.view'] },\n PUT: { requireAuth: true, requireFeatures: ['dashboards.configure'] },\n}\n\ntype LayoutScope = {\n userId: string\n tenantId: string | null\n organizationId: string | null\n}\n\nasync function loadScopeLayout(em: any, scope: LayoutScope): Promise<DashboardLayout | null> {\n return await em.findOne(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n })\n}\n\nfunction normalizeLayoutItems(items: any[]) {\n const list = Array.isArray(items) ? items : []\n const seenIds = new Set<string>()\n const sanitized = list\n .filter((item) => item && typeof item === 'object')\n .map((item) => ({\n id: String(item.id),\n widgetId: String(item.widgetId),\n order: Number.isInteger(item.order) ? Number(item.order) : undefined,\n priority: Number.isInteger(item.priority) ? Number(item.priority) : undefined,\n size: typeof item.size === 'string' ? item.size : undefined,\n settings: item.settings,\n }))\n .filter((item) => {\n if (!item.id || !item.widgetId) return false\n if (seenIds.has(item.id)) return false\n seenIds.add(item.id)\n return true\n })\n .sort((a, b) => {\n const aOrder = a.order ?? a.priority ?? 0\n const bOrder = b.order ?? b.priority ?? 0\n return aOrder - bOrder\n })\n .map((item, idx) => ({ ...item, order: idx, priority: idx }))\n return sanitized\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n // Use a fresh fork to avoid carrying over pending entities from other operations\n const em = (container.resolve('em') as any).fork({ clear: true, freshEventManager: true, useContext: true })\n const rbac = container.resolve('rbacService') as any\n const url = new URL(req.url)\n\n const scope: LayoutScope = {\n userId: String(auth.sub),\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n }\n\n const effectiveFeatures = await rbac.getEffectiveFeatures(scope.userId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n const widgets = await loadAllWidgets()\n const allowedIds = await resolveAllowedWidgetIds(\n em,\n {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n features: effectiveFeatures,\n isSuperAdmin: false,\n },\n widgets,\n )\n const allowedWidgets = widgets.filter((w) => allowedIds.includes(w.metadata.id))\n\n // An empty widget registry means the module registry has not been populated yet\n // (a boot race), not that this app has no widgets. Every write below is derived\n // from it, so a read request must persist nothing until it recovers \u2014 otherwise a\n // restart-recoverable glitch is written into saved layouts for good (#5041).\n // Note this keys off the registry, not off `allowedIds`: a user whose allowlist is\n // legitimately empty on a healthy registry is still pruned and seeded as before.\n const hasRegisteredWidgets = widgets.length > 0\n\n let layout = await loadScopeLayout(em, scope)\n let items = layout ? normalizeLayoutItems(layout.layoutJson) : []\n let hasChanged = false\n\n if (!layout) {\n const defaults = allowedWidgets.filter((widget) => widget.metadata.defaultEnabled)\n items = defaults.map((widget, index) => ({\n id: randomUUID(),\n widgetId: widget.metadata.id,\n order: index,\n priority: index,\n size: widget.metadata.defaultSize ?? DEFAULT_SIZE,\n settings: widget.metadata.defaultSettings ?? undefined,\n }))\n if (hasRegisteredWidgets) {\n layout = em.create(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n layoutJson: items,\n })\n em.persist(layout)\n hasChanged = true\n }\n } else if (hasRegisteredWidgets) {\n const existingLayout = layout\n const filtered = items.filter((item) => allowedIds.includes(item.widgetId))\n if (filtered.length !== items.length) {\n hasChanged = true\n items = filtered\n }\n items = items.map((item, index) => (item.order !== index || item.priority !== index ? { ...item, order: index, priority: index } : item))\n if (\n existingLayout.layoutJson.length !== items.length ||\n items.some((item, idx) => existingLayout.layoutJson[idx]?.id !== item.id)\n ) {\n hasChanged = true\n }\n existingLayout.layoutJson = items\n layout = existingLayout\n }\n\n if (hasChanged) {\n await em.flush()\n }\n\n const canConfigure = authorizeFeatures(['dashboards.configure'], {\n grantedFeatures: effectiveFeatures,\n })\n\n let userEmail: string | null = null\n let userName: string | null = null\n let userLabel: string | null = null\n const user = await findOneWithDecryption(\n em,\n User,\n { id: scope.userId, deletedAt: null },\n undefined,\n { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId ?? null },\n )\n if (user) {\n userName = user.name?.trim() ?? null\n userEmail = user.email ?? null\n userLabel = (userName && userName.length > 0 ? userName : userEmail) ?? null\n }\n if (!userLabel) {\n userLabel = scope.userId\n }\n\n const response = {\n layout: { items },\n allowedWidgetIds: allowedIds,\n canConfigure,\n context: {\n ...scope,\n userName,\n userEmail,\n userLabel,\n },\n widgets: allowedWidgets.map((widget) => ({\n id: widget.metadata.id,\n title: widget.metadata.title,\n description: widget.metadata.description ?? null,\n defaultSize: widget.metadata.defaultSize ?? DEFAULT_SIZE,\n defaultEnabled: !!widget.metadata.defaultEnabled,\n defaultSettings: widget.metadata.defaultSettings ?? null,\n features: widget.metadata.features ?? [],\n moduleId: widget.moduleId,\n icon: widget.metadata.icon ?? null,\n loaderKey: widget.key,\n supportsRefresh: !!widget.metadata.supportsRefresh,\n })),\n }\n\n return NextResponse.json(response)\n}\n\nexport async function PUT(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })\n }\n const parsed = dashboardLayoutSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid layout payload', issues: parsed.error.issues }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const { resolve } = container\n const em = (resolve('em') as any).fork({ clear: true, freshEventManager: true, useContext: true })\n const rbac = resolve('rbacService') as any\n\n const scope: LayoutScope = {\n userId: String(auth.sub),\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n }\n\n const canConfigure = await rbac.userHasAllFeatures(\n scope.userId,\n ['dashboards.configure'],\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n if (!canConfigure) {\n return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n }\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: scope.tenantId ?? '',\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: RESOURCE_KIND,\n resourceId: scope.userId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: { items: parsed.data.items },\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const widgets = await loadAllWidgets()\n // The allowlist below is derived from the registry, and this handler persists the\n // filtered result unconditionally. An empty registry \u2014 the boot race behind #5041 \u2014\n // would drop every submitted item and save `[]` while answering `{ ok: true }`, so a\n // stale tab reordering a widget could erase the layout it just rendered. Fail the\n // write instead: the save is explicit, so the client must learn it did not happen\n // and retry, rather than be told a wipe succeeded.\n if (widgets.length === 0) {\n return NextResponse.json({ error: 'Widget registry unavailable' }, { status: 503 })\n }\n const effectiveFeatures = await rbac.getEffectiveFeatures(scope.userId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n const allowedIds = await resolveAllowedWidgetIds(\n em,\n {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n features: effectiveFeatures,\n isSuperAdmin: false,\n },\n widgets,\n )\n const allowedSet = new Set(allowedIds)\n\n const payloadItems = parsed.data.items\n const sanitized = payloadItems\n .map((item, index) => ({\n id: item.id,\n widgetId: item.widgetId,\n order: index,\n priority: index,\n size: item.size ?? DEFAULT_SIZE,\n settings: item.settings,\n }))\n .filter((item) => allowedSet.has(item.widgetId))\n\n const uniqueIds = new Set(sanitized.map((item) => item.id))\n if (uniqueIds.size !== sanitized.length) {\n return NextResponse.json({ error: 'Layout item IDs must be unique' }, { status: 400 })\n }\n\n let layout = await loadScopeLayout(em, scope)\n if (!layout) {\n layout = em.create(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n layoutJson: sanitized,\n })\n em.persist(layout)\n } else {\n layout.layoutJson = sanitized\n }\n await em.flush()\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: scope.tenantId ?? '',\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: RESOURCE_KIND,\n resourceId: scope.userId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({ ok: true })\n}\n\nconst layoutGetDoc: OpenApiMethodDoc = {\n summary: 'Load the current dashboard layout',\n description: 'Returns the saved widget layout together with the widgets the current user is allowed to place.',\n tags: [dashboardsTag],\n responses: [\n {\n status: 200,\n description: 'Current dashboard layout and available widgets.',\n schema: dashboardLayoutStateSchema,\n },\n ],\n errors: [\n { status: 401, description: 'Authentication required', schema: dashboardsErrorSchema },\n ],\n}\n\nconst layoutPutDoc: OpenApiMethodDoc = {\n summary: 'Persist dashboard layout changes',\n description: 'Saves the provided widget ordering, sizes, and settings for the current user.',\n tags: [dashboardsTag],\n requestBody: {\n contentType: 'application/json',\n schema: dashboardLayoutSchema,\n description: 'List of dashboard widgets with ordering, sizing, and settings.',\n },\n responses: [\n { status: 200, description: 'Layout updated successfully.', schema: dashboardsOkSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid layout payload', schema: dashboardsErrorSchema },\n { status: 401, description: 'Authentication required', schema: dashboardsErrorSchema },\n { status: 403, description: 'Missing dashboards.configure feature', schema: dashboardsErrorSchema },\n { status: 503, description: 'Widget registry unavailable \u2014 the layout was not saved', schema: dashboardsErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dashboardsTag,\n summary: 'Manage personal dashboard layout',\n methods: {\n GET: layoutGetDoc,\n PUT: layoutPutDoc,\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,yBAAyB;AAClC,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,eAAe;AACrB,MAAM,gBAAgB;AAEf,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,iBAAiB,EAAE;AAAA,EAC/D,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,sBAAsB,EAAE;AACtE;AAQA,eAAe,gBAAgB,IAAS,OAAqD;AAC3F,SAAO,MAAM,GAAG,QAAQ,iBAAiB;AAAA,IACvC,QAAQ,MAAM;AAAA,IACd,UAAU,MAAM;AAAA,IAChB,gBAAgB,MAAM;AAAA,IACtB,WAAW;AAAA,EACb,CAAC;AACH;AAEA,SAAS,qBAAqB,OAAc;AAC1C,QAAM,OAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC;AAC7C,QAAM,UAAU,oBAAI,IAAY;AAChC,QAAM,YAAY,KACf,OAAO,CAAC,SAAS,QAAQ,OAAO,SAAS,QAAQ,EACjD,IAAI,CAAC,UAAU;AAAA,IACd,IAAI,OAAO,KAAK,EAAE;AAAA,I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;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,sBAAsB;AAAA,EACvF;AACF;AAEA,MAAM,eAAiC;AAAA,EACrC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,aAAa;AAAA,EACpB,aAAa;AAAA,IACX,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,gCAAgC,QAAQ,mBAAmB;AAAA,EACzF;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,sBAAsB;AAAA,IACpF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,sBAAsB;AAAA,IACrF,EAAE,QAAQ,KAAK,aAAa,wCAAwC,QAAQ,sBAAsB;AAAA,IAClG,EAAE,QAAQ,KAAK,aAAa,+DAA0D,QAAQ,sBAAsB;AAAA,EACtH;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,IACL,KAAK;AAAA,EACP;AACF;",
6
6
  "names": []
7
7
  }
@@ -7,7 +7,7 @@ function invalidateWidgetCache() {
7
7
  }
8
8
  async function loadWidgetEntries() {
9
9
  if (!widgetEntriesPromise) {
10
- widgetEntriesPromise = Promise.resolve().then(() => {
10
+ const pending = Promise.resolve().then(() => {
11
11
  const list = getModules();
12
12
  const entries = list.flatMap((mod) => {
13
13
  const moduleEntries = mod.dashboardWidgets ?? [];
@@ -18,6 +18,20 @@ async function loadWidgetEntries() {
18
18
  });
19
19
  return applyDashboardWidgetOverridesToEntries(entries);
20
20
  });
21
+ widgetEntriesPromise = pending;
22
+ const forgetWhenUnusable = (entries) => {
23
+ if (widgetEntriesPromise === pending && (entries === null || entries.length === 0)) {
24
+ widgetEntriesPromise = null;
25
+ }
26
+ };
27
+ try {
28
+ const entries = await pending;
29
+ forgetWhenUnusable(entries);
30
+ return entries;
31
+ } catch (err) {
32
+ forgetWhenUnusable(null);
33
+ throw err;
34
+ }
21
35
  }
22
36
  return widgetEntriesPromise;
23
37
  }
@@ -49,6 +63,9 @@ async function loadEntry(entry) {
49
63
  if (!widgetCache.has(entry.key)) {
50
64
  const promise = entry.loader().then((mod) => ensureValidWidgetModule(mod, entry.key, entry.moduleId));
51
65
  widgetCache.set(entry.key, promise);
66
+ promise.catch(() => {
67
+ if (widgetCache.get(entry.key) === promise) widgetCache.delete(entry.key);
68
+ });
52
69
  }
53
70
  return widgetCache.get(entry.key);
54
71
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/dashboards/lib/widgets.ts"],
4
- "sourcesContent": ["import type { Module, ModuleDashboardWidgetEntry } from '@open-mercato/shared/modules/registry'\nimport type { DashboardWidgetMetadata, DashboardWidgetModule } from '@open-mercato/shared/modules/dashboard/widgets'\nimport { applyDashboardWidgetOverridesToEntries } from '@open-mercato/shared/modules/overrides'\nimport { getModules } from '@open-mercato/shared/lib/i18n/server'\n\ntype LoadedWidgetModule = DashboardWidgetModule<any> & { metadata: DashboardWidgetMetadata }\n\ntype WidgetEntry = ModuleDashboardWidgetEntry & { moduleId: string }\n\nlet widgetEntriesPromise: Promise<WidgetEntry[]> | null = null\n\n/**\n * Invalidate the widget entries and widget module cache.\n * Call this when the generated registry is updated or modules are reloaded.\n */\nexport function invalidateWidgetCache() {\n widgetEntriesPromise = null;\n widgetCache.clear();\n}\nasync function loadWidgetEntries(): Promise<WidgetEntry[]> {\n if (!widgetEntriesPromise) {\n widgetEntriesPromise = Promise.resolve().then(() => {\n const list = getModules() as Module[]\n const entries = list.flatMap((mod) => {\n const moduleEntries = mod.dashboardWidgets ?? []\n return moduleEntries.map((entry) => ({\n ...entry,\n moduleId: mod.id,\n }))\n })\n return applyDashboardWidgetOverridesToEntries(entries) as WidgetEntry[]\n })\n }\n return widgetEntriesPromise\n}\n\nconst widgetCache = new Map<string, Promise<LoadedWidgetModule>>()\n\nfunction ensureValidWidgetModule(mod: any, key: string, moduleId: string): LoadedWidgetModule {\n if (!mod || typeof mod !== 'object') {\n throw new Error(`Invalid dashboard widget module \"${key}\" from \"${moduleId}\" (expected object export)`)\n }\n const widget = (mod.default ?? mod) as DashboardWidgetModule<any>\n if (!widget || typeof widget !== 'object') {\n throw new Error(`Invalid dashboard widget export \"${key}\" from \"${moduleId}\" (missing default export)`)\n }\n if (!widget.metadata || typeof widget.metadata !== 'object') {\n throw new Error(`Dashboard widget \"${key}\" from \"${moduleId}\" is missing metadata`)\n }\n const { metadata } = widget\n if (typeof metadata.id !== 'string' || metadata.id.length === 0) {\n throw new Error(`Dashboard widget \"${key}\" from \"${moduleId}\" metadata.id must be a non-empty string`)\n }\n if (typeof metadata.title !== 'string' || metadata.title.length === 0) {\n throw new Error(`Dashboard widget \"${metadata.id}\" from \"${moduleId}\" must have a title`)\n }\n return {\n ...widget,\n metadata,\n }\n}\n\nasync function loadEntry(entry: WidgetEntry): Promise<LoadedWidgetModule> {\n if (!widgetCache.has(entry.key)) {\n const promise = entry.loader()\n .then((mod) => ensureValidWidgetModule(mod, entry.key, entry.moduleId))\n widgetCache.set(entry.key, promise)\n }\n return widgetCache.get(entry.key)!\n}\n\nexport async function loadAllWidgets(): Promise<Array<LoadedWidgetModule & { moduleId: string; key: string }>> {\n const widgetEntries = await loadWidgetEntries()\n const loaded = await Promise.all(widgetEntries.map(async (entry) => {\n const widget = await loadEntry(entry)\n return { ...widget, moduleId: entry.moduleId, key: entry.key }\n }))\n const byId = new Map<string, LoadedWidgetModule & { moduleId: string; key: string }>()\n for (const widget of loaded) {\n if (!byId.has(widget.metadata.id)) {\n byId.set(widget.metadata.id, widget)\n }\n }\n return Array.from(byId.values())\n}\n\nexport async function loadWidgetById(widgetId: string): Promise<(LoadedWidgetModule & { moduleId: string; key: string }) | null> {\n const widgetEntries = await loadWidgetEntries()\n for (const entry of widgetEntries) {\n const widget = await loadEntry(entry)\n if (widget.metadata.id === widgetId) {\n return { ...widget, moduleId: entry.moduleId, key: entry.key }\n }\n }\n return null\n}\n"],
5
- "mappings": "AAEA,SAAS,8CAA8C;AACvD,SAAS,kBAAkB;AAM3B,IAAI,uBAAsD;AAMnD,SAAS,wBAAwB;AACtC,yBAAuB;AACvB,cAAY,MAAM;AACpB;AACA,eAAe,oBAA4C;AACzD,MAAI,CAAC,sBAAsB;AACzB,2BAAuB,QAAQ,QAAQ,EAAE,KAAK,MAAM;AAClD,YAAM,OAAO,WAAW;AACxB,YAAM,UAAU,KAAK,QAAQ,CAAC,QAAQ;AACpC,cAAM,gBAAgB,IAAI,oBAAoB,CAAC;AAC/C,eAAO,cAAc,IAAI,CAAC,WAAW;AAAA,UACnC,GAAG;AAAA,UACH,UAAU,IAAI;AAAA,QAChB,EAAE;AAAA,MACJ,CAAC;AACD,aAAO,uCAAuC,OAAO;AAAA,IACvD,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEA,MAAM,cAAc,oBAAI,IAAyC;AAEjE,SAAS,wBAAwB,KAAU,KAAa,UAAsC;AAC5F,MAAI,CAAC,OAAO,OAAO,QAAQ,UAAU;AACnC,UAAM,IAAI,MAAM,oCAAoC,GAAG,WAAW,QAAQ,4BAA4B;AAAA,EACxG;AACA,QAAM,SAAU,IAAI,WAAW;AAC/B,MAAI,CAAC,UAAU,OAAO,WAAW,UAAU;AACzC,UAAM,IAAI,MAAM,oCAAoC,GAAG,WAAW,QAAQ,4BAA4B;AAAA,EACxG;AACA,MAAI,CAAC,OAAO,YAAY,OAAO,OAAO,aAAa,UAAU;AAC3D,UAAM,IAAI,MAAM,qBAAqB,GAAG,WAAW,QAAQ,uBAAuB;AAAA,EACpF;AACA,QAAM,EAAE,SAAS,IAAI;AACrB,MAAI,OAAO,SAAS,OAAO,YAAY,SAAS,GAAG,WAAW,GAAG;AAC/D,UAAM,IAAI,MAAM,qBAAqB,GAAG,WAAW,Q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 "sourcesContent": ["import type { Module, ModuleDashboardWidgetEntry } from '@open-mercato/shared/modules/registry'\nimport type { DashboardWidgetMetadata, DashboardWidgetModule } from '@open-mercato/shared/modules/dashboard/widgets'\nimport { applyDashboardWidgetOverridesToEntries } from '@open-mercato/shared/modules/overrides'\nimport { getModules } from '@open-mercato/shared/lib/i18n/server'\n\ntype LoadedWidgetModule = DashboardWidgetModule<any> & { metadata: DashboardWidgetMetadata }\n\ntype WidgetEntry = ModuleDashboardWidgetEntry & { moduleId: string }\n\nlet widgetEntriesPromise: Promise<WidgetEntry[]> | null = null\n\n/**\n * Invalidate the widget entries and widget module cache.\n * Call this when the generated registry is updated or modules are reloaded.\n */\nexport function invalidateWidgetCache() {\n widgetEntriesPromise = null;\n widgetCache.clear();\n}\n/**\n * An empty resolution means the module registry was not populated yet \u2014 a boot\n * race, not \"this app has no dashboard widgets\". Memoizing it would serve an\n * empty registry for the lifetime of the process, so the entry is dropped and\n * the next call retries. A rejected resolution is dropped for the same reason.\n */\nasync function loadWidgetEntries(): Promise<WidgetEntry[]> {\n if (!widgetEntriesPromise) {\n const pending = Promise.resolve().then(() => {\n const list = getModules() as Module[]\n const entries = list.flatMap((mod) => {\n const moduleEntries = mod.dashboardWidgets ?? []\n return moduleEntries.map((entry) => ({\n ...entry,\n moduleId: mod.id,\n }))\n })\n return applyDashboardWidgetOverridesToEntries(entries) as WidgetEntry[]\n })\n widgetEntriesPromise = pending\n const forgetWhenUnusable = (entries: WidgetEntry[] | null) => {\n if (widgetEntriesPromise === pending && (entries === null || entries.length === 0)) {\n widgetEntriesPromise = null\n }\n }\n try {\n const entries = await pending\n forgetWhenUnusable(entries)\n return entries\n } catch (err) {\n forgetWhenUnusable(null)\n throw err\n }\n }\n return widgetEntriesPromise\n}\n\nconst widgetCache = new Map<string, Promise<LoadedWidgetModule>>()\n\nfunction ensureValidWidgetModule(mod: any, key: string, moduleId: string): LoadedWidgetModule {\n if (!mod || typeof mod !== 'object') {\n throw new Error(`Invalid dashboard widget module \"${key}\" from \"${moduleId}\" (expected object export)`)\n }\n const widget = (mod.default ?? mod) as DashboardWidgetModule<any>\n if (!widget || typeof widget !== 'object') {\n throw new Error(`Invalid dashboard widget export \"${key}\" from \"${moduleId}\" (missing default export)`)\n }\n if (!widget.metadata || typeof widget.metadata !== 'object') {\n throw new Error(`Dashboard widget \"${key}\" from \"${moduleId}\" is missing metadata`)\n }\n const { metadata } = widget\n if (typeof metadata.id !== 'string' || metadata.id.length === 0) {\n throw new Error(`Dashboard widget \"${key}\" from \"${moduleId}\" metadata.id must be a non-empty string`)\n }\n if (typeof metadata.title !== 'string' || metadata.title.length === 0) {\n throw new Error(`Dashboard widget \"${metadata.id}\" from \"${moduleId}\" must have a title`)\n }\n return {\n ...widget,\n metadata,\n }\n}\n\nasync function loadEntry(entry: WidgetEntry): Promise<LoadedWidgetModule> {\n if (!widgetCache.has(entry.key)) {\n const promise = entry.loader()\n .then((mod) => ensureValidWidgetModule(mod, entry.key, entry.moduleId))\n widgetCache.set(entry.key, promise)\n // Same policy as the entries cache above: a rejected resolution is a transient\n // failure (a dynamic import that lost a race), not a permanent fact about the\n // widget. Memoizing it would make loadAllWidgets() reject for the lifetime of the\n // process. The identity check mirrors `widgetEntriesPromise === pending`, so a\n // concurrent invalidateWidgetCache() is never clobbered.\n promise.catch(() => {\n if (widgetCache.get(entry.key) === promise) widgetCache.delete(entry.key)\n })\n }\n return widgetCache.get(entry.key)!\n}\n\nexport async function loadAllWidgets(): Promise<Array<LoadedWidgetModule & { moduleId: string; key: string }>> {\n const widgetEntries = await loadWidgetEntries()\n const loaded = await Promise.all(widgetEntries.map(async (entry) => {\n const widget = await loadEntry(entry)\n return { ...widget, moduleId: entry.moduleId, key: entry.key }\n }))\n const byId = new Map<string, LoadedWidgetModule & { moduleId: string; key: string }>()\n for (const widget of loaded) {\n if (!byId.has(widget.metadata.id)) {\n byId.set(widget.metadata.id, widget)\n }\n }\n return Array.from(byId.values())\n}\n\nexport async function loadWidgetById(widgetId: string): Promise<(LoadedWidgetModule & { moduleId: string; key: string }) | null> {\n const widgetEntries = await loadWidgetEntries()\n for (const entry of widgetEntries) {\n const widget = await loadEntry(entry)\n if (widget.metadata.id === widgetId) {\n return { ...widget, moduleId: entry.moduleId, key: entry.key }\n }\n }\n return null\n}\n"],
5
+ "mappings": "AAEA,SAAS,8CAA8C;AACvD,SAAS,kBAAkB;AAM3B,IAAI,uBAAsD;AAMnD,SAAS,wBAAwB;AACtC,yBAAuB;AACvB,cAAY,MAAM;AACpB;AAOA,eAAe,oBAA4C;AACzD,MAAI,CAAC,sBAAsB;AACzB,UAAM,UAAU,QAAQ,QAAQ,EAAE,KAAK,MAAM;AAC3C,YAAM,OAAO,WAAW;AACxB,YAAM,UAAU,KAAK,QAAQ,CAAC,QAAQ;AACpC,cAAM,gBAAgB,IAAI,oBAAoB,CAAC;AAC/C,eAAO,cAAc,IAAI,CAAC,WAAW;AAAA,UACnC,GAAG;AAAA,UACH,UAAU,IAAI;AAAA,QAChB,EAAE;AAAA,MACJ,CAAC;AACD,aAAO,uCAAuC,OAAO;AAAA,IACvD,CAAC;AACD,2BAAuB;AACvB,UAAM,qBAAqB,CAAC,YAAkC;AAC5D,UAAI,yBAAyB,YAAY,YAAY,QAAQ,QAAQ,WAAW,IAAI;AAClF,+BAAuB;AAAA,MACzB;AAAA,IACF;AACA,QAAI;AACF,YAAM,UAAU,MAAM;AACtB,yBAAmB,OAAO;AAC1B,aAAO;AAAA,IACT,SAAS,KAAK;AACZ,yBAAmB,IAAI;AACvB,YAAM;AAAA,IACR;AAAA,EACF;AACA,SAAO;AACT;AAEA,MAAM,cAAc,oBAAI,IAAyC;AAEjE,SAAS,wBAAwB,KAAU,KAAa,UAAsC;AAC5F,MAAI,CAAC,OAAO,OAAO,QAAQ,UAAU;AACnC,UAAM,IAAI,MAAM,oCAAoC,GAAG,WAAW,QAAQ,4BAA4B;AAAA,EACxG;AACA,QAAM,SAAU,IAAI,WAAW;AAC/B,MAAI,CAAC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AI,IAAoE;AACrF,aAAW,UAAU,QAAQ;AAC3B,QAAI,CAAC,KAAK,IAAI,OAAO,SAAS,EAAE,GAAG;AACjC,WAAK,IAAI,OAAO,SAAS,IAAI,MAAM;AAAA,IACrC;AAAA,EACF;AACA,SAAO,MAAM,KAAK,KAAK,OAAO,CAAC;AACjC;AAEA,eAAsB,eAAe,UAA4F;AAC/H,QAAM,gBAAgB,MAAM,kBAAkB;AAC9C,aAAW,SAAS,eAAe;AACjC,UAAM,SAAS,MAAM,UAAU,KAAK;AACpC,QAAI,OAAO,SAAS,OAAO,UAAU;AACnC,aAAO,EAAE,GAAG,QAAQ,UAAU,MAAM,UAAU,KAAK,MAAM,IAAI;AAAA,IAC/D;AAAA,EACF;AACA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/core",
3
- "version": "0.6.8-develop.6899.1.433952fd93",
3
+ "version": "0.6.8-develop.6903.1.0ec850a22b",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -254,16 +254,16 @@
254
254
  "zod": "^4.4.3"
255
255
  },
256
256
  "peerDependencies": {
257
- "@open-mercato/ai-assistant": "0.6.8-develop.6899.1.433952fd93",
258
- "@open-mercato/shared": "0.6.8-develop.6899.1.433952fd93",
259
- "@open-mercato/ui": "0.6.8-develop.6899.1.433952fd93",
257
+ "@open-mercato/ai-assistant": "0.6.8-develop.6903.1.0ec850a22b",
258
+ "@open-mercato/shared": "0.6.8-develop.6903.1.0ec850a22b",
259
+ "@open-mercato/ui": "0.6.8-develop.6903.1.0ec850a22b",
260
260
  "react": "^19.0.0",
261
261
  "react-dom": "^19.0.0"
262
262
  },
263
263
  "devDependencies": {
264
- "@open-mercato/ai-assistant": "0.6.8-develop.6899.1.433952fd93",
265
- "@open-mercato/shared": "0.6.8-develop.6899.1.433952fd93",
266
- "@open-mercato/ui": "0.6.8-develop.6899.1.433952fd93",
264
+ "@open-mercato/ai-assistant": "0.6.8-develop.6903.1.0ec850a22b",
265
+ "@open-mercato/shared": "0.6.8-develop.6903.1.0ec850a22b",
266
+ "@open-mercato/ui": "0.6.8-develop.6903.1.0ec850a22b",
267
267
  "@testing-library/dom": "^10.4.1",
268
268
  "@testing-library/jest-dom": "^7.0.0",
269
269
  "@testing-library/react": "^16.3.1",
@@ -6,6 +6,7 @@ import type { RbacService } from '@open-mercato/core/modules/auth/services/rbacS
6
6
  import { CommandBus } from '@open-mercato/shared/lib/commands/command-bus'
7
7
  import { ActionLogService } from '@open-mercato/core/modules/audit_logs/services/actionLogService'
8
8
  import type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'
9
+ import { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'
9
10
  import type { AwilixContainer } from 'awilix'
10
11
  import { z } from 'zod'
11
12
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
@@ -120,6 +121,12 @@ export async function POST(req: Request) {
120
121
  await commandBus.undo(undoToken, ctx)
121
122
  return NextResponse.json({ ok: true, logId: target.id })
122
123
  } catch (err) {
124
+ // A beforeUndo interceptor that blocked with an explicit status is a deliberate business
125
+ // rejection, not an undo failure — surface its status and message (issue #5045).
126
+ const interceptorRejection = getCommandInterceptorHttpRejection(err)
127
+ if (interceptorRejection) {
128
+ return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })
129
+ }
123
130
  logger.error('Undo failed', { err })
124
131
  return NextResponse.json({ error: 'Undo failed' }, { status: 400 })
125
132
  }
@@ -156,6 +163,12 @@ export const openApi: OpenApiRouteDoc = {
156
163
  { status: 400, description: 'Invalid or unavailable undo token', schema: errorSchema },
157
164
  { status: 401, description: 'Authentication required', schema: errorSchema },
158
165
  { status: 403, description: 'Undo blocked by organization or tenant scope', schema: errorSchema },
166
+ {
167
+ status: 422,
168
+ description:
169
+ 'Undo deliberately blocked by a beforeUndo command interceptor. The interceptor chooses the status (any 4xx/5xx) and may replace the body.',
170
+ schema: errorSchema,
171
+ },
159
172
  ],
160
173
  },
161
174
  },
@@ -106,6 +106,14 @@ export async function GET(req: Request) {
106
106
  )
107
107
  const allowedWidgets = widgets.filter((w) => allowedIds.includes(w.metadata.id))
108
108
 
109
+ // An empty widget registry means the module registry has not been populated yet
110
+ // (a boot race), not that this app has no widgets. Every write below is derived
111
+ // from it, so a read request must persist nothing until it recovers — otherwise a
112
+ // restart-recoverable glitch is written into saved layouts for good (#5041).
113
+ // Note this keys off the registry, not off `allowedIds`: a user whose allowlist is
114
+ // legitimately empty on a healthy registry is still pruned and seeded as before.
115
+ const hasRegisteredWidgets = widgets.length > 0
116
+
109
117
  let layout = await loadScopeLayout(em, scope)
110
118
  let items = layout ? normalizeLayoutItems(layout.layoutJson) : []
111
119
  let hasChanged = false
@@ -120,15 +128,17 @@ export async function GET(req: Request) {
120
128
  size: widget.metadata.defaultSize ?? DEFAULT_SIZE,
121
129
  settings: widget.metadata.defaultSettings ?? undefined,
122
130
  }))
123
- layout = em.create(DashboardLayout, {
124
- userId: scope.userId,
125
- tenantId: scope.tenantId,
126
- organizationId: scope.organizationId,
127
- layoutJson: items,
128
- })
129
- em.persist(layout)
130
- hasChanged = true
131
- } else {
131
+ if (hasRegisteredWidgets) {
132
+ layout = em.create(DashboardLayout, {
133
+ userId: scope.userId,
134
+ tenantId: scope.tenantId,
135
+ organizationId: scope.organizationId,
136
+ layoutJson: items,
137
+ })
138
+ em.persist(layout)
139
+ hasChanged = true
140
+ }
141
+ } else if (hasRegisteredWidgets) {
132
142
  const existingLayout = layout
133
143
  const filtered = items.filter((item) => allowedIds.includes(item.widgetId))
134
144
  if (filtered.length !== items.length) {
@@ -252,6 +262,15 @@ export async function PUT(req: Request) {
252
262
  }
253
263
 
254
264
  const widgets = await loadAllWidgets()
265
+ // The allowlist below is derived from the registry, and this handler persists the
266
+ // filtered result unconditionally. An empty registry — the boot race behind #5041 —
267
+ // would drop every submitted item and save `[]` while answering `{ ok: true }`, so a
268
+ // stale tab reordering a widget could erase the layout it just rendered. Fail the
269
+ // write instead: the save is explicit, so the client must learn it did not happen
270
+ // and retry, rather than be told a wipe succeeded.
271
+ if (widgets.length === 0) {
272
+ return NextResponse.json({ error: 'Widget registry unavailable' }, { status: 503 })
273
+ }
255
274
  const effectiveFeatures = await rbac.getEffectiveFeatures(scope.userId, {
256
275
  tenantId: scope.tenantId,
257
276
  organizationId: scope.organizationId,
@@ -349,6 +368,7 @@ const layoutPutDoc: OpenApiMethodDoc = {
349
368
  { status: 400, description: 'Invalid layout payload', schema: dashboardsErrorSchema },
350
369
  { status: 401, description: 'Authentication required', schema: dashboardsErrorSchema },
351
370
  { status: 403, description: 'Missing dashboards.configure feature', schema: dashboardsErrorSchema },
371
+ { status: 503, description: 'Widget registry unavailable — the layout was not saved', schema: dashboardsErrorSchema },
352
372
  ],
353
373
  }
354
374
 
@@ -17,9 +17,15 @@ export function invalidateWidgetCache() {
17
17
  widgetEntriesPromise = null;
18
18
  widgetCache.clear();
19
19
  }
20
+ /**
21
+ * An empty resolution means the module registry was not populated yet — a boot
22
+ * race, not "this app has no dashboard widgets". Memoizing it would serve an
23
+ * empty registry for the lifetime of the process, so the entry is dropped and
24
+ * the next call retries. A rejected resolution is dropped for the same reason.
25
+ */
20
26
  async function loadWidgetEntries(): Promise<WidgetEntry[]> {
21
27
  if (!widgetEntriesPromise) {
22
- widgetEntriesPromise = Promise.resolve().then(() => {
28
+ const pending = Promise.resolve().then(() => {
23
29
  const list = getModules() as Module[]
24
30
  const entries = list.flatMap((mod) => {
25
31
  const moduleEntries = mod.dashboardWidgets ?? []
@@ -30,6 +36,20 @@ async function loadWidgetEntries(): Promise<WidgetEntry[]> {
30
36
  })
31
37
  return applyDashboardWidgetOverridesToEntries(entries) as WidgetEntry[]
32
38
  })
39
+ widgetEntriesPromise = pending
40
+ const forgetWhenUnusable = (entries: WidgetEntry[] | null) => {
41
+ if (widgetEntriesPromise === pending && (entries === null || entries.length === 0)) {
42
+ widgetEntriesPromise = null
43
+ }
44
+ }
45
+ try {
46
+ const entries = await pending
47
+ forgetWhenUnusable(entries)
48
+ return entries
49
+ } catch (err) {
50
+ forgetWhenUnusable(null)
51
+ throw err
52
+ }
33
53
  }
34
54
  return widgetEntriesPromise
35
55
  }
@@ -65,6 +85,14 @@ async function loadEntry(entry: WidgetEntry): Promise<LoadedWidgetModule> {
65
85
  const promise = entry.loader()
66
86
  .then((mod) => ensureValidWidgetModule(mod, entry.key, entry.moduleId))
67
87
  widgetCache.set(entry.key, promise)
88
+ // Same policy as the entries cache above: a rejected resolution is a transient
89
+ // failure (a dynamic import that lost a race), not a permanent fact about the
90
+ // widget. Memoizing it would make loadAllWidgets() reject for the lifetime of the
91
+ // process. The identity check mirrors `widgetEntriesPromise === pending`, so a
92
+ // concurrent invalidateWidgetCache() is never clobbered.
93
+ promise.catch(() => {
94
+ if (widgetCache.get(entry.key) === promise) widgetCache.delete(entry.key)
95
+ })
68
96
  }
69
97
  return widgetCache.get(entry.key)!
70
98
  }