@open-mercato/documents 0.9.1-develop.7574.1.837288eec1 → 0.10.0
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/dist/contentSecurityPolicy.js +23 -0
- package/dist/contentSecurityPolicy.js.map +7 -0
- package/dist/modules/documents/api/[id]/comments/access-check/route.js +13 -6
- package/dist/modules/documents/api/[id]/comments/access-check/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/comments/route.js +2 -0
- package/dist/modules/documents/api/[id]/comments/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/content/route.js +2 -0
- package/dist/modules/documents/api/[id]/content/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/route.js +3 -0
- package/dist/modules/documents/api/[id]/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/shares/route.js +2 -0
- package/dist/modules/documents/api/[id]/shares/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/versions/route.js +2 -0
- package/dist/modules/documents/api/[id]/versions/route.js.map +2 -2
- package/dist/modules/documents/api/_shared.js +10 -27
- package/dist/modules/documents/api/_shared.js.map +3 -3
- package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js +3 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js +1 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js +15 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js +15 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js +20 -8
- package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js +3 -0
- package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/editorTypes.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js +46 -0
- package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js.map +7 -0
- package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js +14 -6
- package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js +3 -0
- package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js.map +2 -2
- package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js +3 -0
- package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js.map +2 -2
- package/dist/modules/documents/backend/documents/components/TemplatePreview.js +3 -0
- package/dist/modules/documents/backend/documents/components/TemplatePreview.js.map +2 -2
- package/dist/modules/documents/commands/comments.js +2 -2
- package/dist/modules/documents/commands/comments.js.map +2 -2
- package/dist/modules/documents/commands/folders.js +1 -0
- package/dist/modules/documents/commands/folders.js.map +2 -2
- package/dist/modules/documents/commands/interceptors.js +11 -0
- package/dist/modules/documents/commands/interceptors.js.map +2 -2
- package/dist/modules/documents/data/attachment-access.js +84 -0
- package/dist/modules/documents/data/attachment-access.js.map +7 -0
- package/dist/modules/documents/data/validators.js +11 -0
- package/dist/modules/documents/data/validators.js.map +2 -2
- package/dist/modules/documents/lib/actor.js +32 -0
- package/dist/modules/documents/lib/actor.js.map +7 -0
- package/dist/modules/documents/lib/collabMaterializer.js +52 -9
- package/dist/modules/documents/lib/collabMaterializer.js.map +2 -2
- package/dist/modules/documents/lib/collabPersistence.js +13 -0
- package/dist/modules/documents/lib/collabPersistence.js.map +7 -0
- package/dist/modules/documents/lib/permissions.js +35 -2
- package/dist/modules/documents/lib/permissions.js.map +2 -2
- package/dist/modules/documents/widgets/injection/related-documents/widget.client.js +3 -2
- package/dist/modules/documents/widgets/injection/related-documents/widget.client.js.map +2 -2
- package/dist/modules/documents/widgets/injection-table.js +12 -3
- package/dist/modules/documents/widgets/injection-table.js.map +2 -2
- package/dist/server/documents-collab-server.js +74 -1
- package/dist/server/documents-collab-server.js.map +2 -2
- package/jest.config.cjs +1 -1
- package/package.json +37 -37
- package/server/documents-collab-server.ts +79 -0
- package/src/contentSecurityPolicy.ts +21 -0
- package/src/modules/documents/api/[id]/comments/access-check/route.ts +13 -6
- package/src/modules/documents/api/[id]/comments/route.ts +2 -0
- package/src/modules/documents/api/[id]/content/route.ts +2 -0
- package/src/modules/documents/api/[id]/route.ts +3 -0
- package/src/modules/documents/api/[id]/shares/route.ts +2 -0
- package/src/modules/documents/api/[id]/versions/route.ts +2 -0
- package/src/modules/documents/api/_shared.ts +10 -36
- package/src/modules/documents/backend/documents/[id]/DocumentCanvas.tsx +3 -1
- package/src/modules/documents/backend/documents/[id]/DocumentEditorIsland.tsx +4 -1
- package/src/modules/documents/backend/documents/[id]/DocumentEditorSurface.tsx +19 -1
- package/src/modules/documents/backend/documents/[id]/DocumentPageClient.tsx +14 -0
- package/src/modules/documents/backend/documents/[id]/VersionHistoryPanel.tsx +23 -8
- package/src/modules/documents/backend/documents/[id]/VersionPreviewDialog.tsx +3 -0
- package/src/modules/documents/backend/documents/[id]/editorTypes.ts +1 -0
- package/src/modules/documents/backend/documents/[id]/saveCollaborativeContent.ts +43 -0
- package/src/modules/documents/backend/documents/[id]/useDocumentComments.ts +17 -7
- package/src/modules/documents/backend/documents/[id]/useDocumentEditor.ts +3 -0
- package/src/modules/documents/backend/documents/components/TemplateBodyEditor.tsx +3 -0
- package/src/modules/documents/backend/documents/components/TemplatePreview.tsx +3 -0
- package/src/modules/documents/commands/comments.ts +2 -2
- package/src/modules/documents/commands/folders.ts +1 -3
- package/src/modules/documents/commands/interceptors.ts +11 -0
- package/src/modules/documents/data/attachment-access.ts +83 -0
- package/src/modules/documents/data/validators.ts +12 -0
- package/src/modules/documents/lib/actor.ts +39 -0
- package/src/modules/documents/lib/collabMaterializer.ts +62 -11
- package/src/modules/documents/lib/collabPersistence.ts +10 -0
- package/src/modules/documents/lib/permissions.ts +52 -0
- package/src/modules/documents/widgets/injection/related-documents/widget.client.tsx +3 -2
- package/src/modules/documents/widgets/injection-table.ts +17 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/documents/api/%5Bid%5D/versions/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { randomUUID } from 'node:crypto'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findAndCountWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { DocumentVersion } from '../../../data/entities'\nimport { DOCUMENTS_ENTITY_IDS } from '../../../lib/constants'\nimport { DOCUMENTS_VERSION_LIST_PAGE_SIZE } from '../../../lib/historyLimits'\nimport { assertTier } from '../../../lib/permissions'\nimport { resolveUserLabels } from '../../../lib/userLabels'\nimport {\n assertDocumentNotArchived,\n handleDocumentsRouteError,\n readBody,\n resolveDocumentsContext,\n routeErrorSchema,\n runMutationGuardAfterSuccess,\n validateMutationGuard,\n withDocumentsContextErrors,\n} from '../../_shared'\nimport {\n attachDocumentsOperationMetadata,\n buildDocumentsCommandRuntimeContext,\n resolveDocumentsCommandBus,\n} from '../../_commands'\nimport type { CreateVersionCommandInput } from '../../../commands/versions'\nimport { documentVersionLabelSchema } from '../../../data/validators'\nimport { sanitizeDocumentVersionLabel } from '../../../lib/versionLabels'\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nexport const versionCreateSchema = z.object({\n label: documentVersionLabelSchema,\n})\n\nexport const versionListQuerySchema = z.object({\n page: z.coerce.number().int().min(1).max(10_000).default(1),\n pageSize: z.coerce.number().int().min(1).max(DOCUMENTS_VERSION_LIST_PAGE_SIZE)\n .default(DOCUMENTS_VERSION_LIST_PAGE_SIZE),\n})\n\nconst versionListItemSchema = z.object({\n id: z.string().uuid(),\n label: z.string().nullable(),\n createdByUserId: z.string().uuid(),\n createdByLabel: z.string().nullable(),\n createdAt: z.string(),\n})\n\nconst versionListResponseSchema = z.object({\n items: z.array(versionListItemSchema),\n page: z.number().int().positive(),\n pageSize: z.number().int().positive(),\n total: z.number().int().nonnegative(),\n totalPages: z.number().int().positive(),\n})\n\nconst versionCreateResponseSchema = z.object({\n id: z.string().uuid(),\n label: z.string().nullable(),\n createdByUserId: z.string().uuid(),\n createdAt: z.string(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['documents.view'] },\n POST: { requireAuth: true, requireFeatures: ['documents.edit'] },\n}\n\nasync function resolveId(context: RouteContext): Promise<string> {\n const params = await context.params\n return params.id\n}\n\nfunction serializeVersion(version: DocumentVersion): z.infer<typeof versionCreateResponseSchema> {\n return {\n id: version.id,\n label: sanitizeDocumentVersionLabel(version.label),\n createdByUserId: version.createdByUserId,\n createdAt: version.createdAt.toISOString(),\n }\n}\n\nexport async function GET(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n await assertTier(ctx.em, documentId, ctx.auth, 'viewer')\n const url = new URL(request.url)\n const query = versionListQuerySchema.parse(Object.fromEntries(url.searchParams.entries()))\n const [versions, total] = await findAndCountWithDecryption(\n ctx.em,\n DocumentVersion,\n {\n documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n },\n {\n fields: ['id', 'label', 'createdByUserId', 'createdAt'],\n orderBy: { createdAt: 'DESC', id: 'ASC' },\n limit: query.pageSize,\n offset: (query.page - 1) * query.pageSize,\n },\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n )\n const labels = await resolveUserLabels(\n ctx.container,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n versions.map((version) => version.createdByUserId),\n )\n\n return NextResponse.json({\n items: versions.map((version) => ({\n ...serializeVersion(version),\n createdByLabel: labels.get(version.createdByUserId)?.label ?? null,\n })),\n page: query.page,\n pageSize: query.pageSize,\n total,\n totalPages: Math.max(1, Math.ceil(total / query.pageSize)),\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.versions.list')\n }\n}\n\nexport async function POST(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.edit'])\n await assertTier(ctx.em, documentId, ctx.auth, 'editor')\n await assertDocumentNotArchived(ctx, documentId)\n const input = versionCreateSchema.parse(await readBody(request))\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentVersion,\n resourceId: documentId,\n operation: 'create',\n mutationPayload: input,\n mutationPayloadSchema: versionCreateSchema,\n })\n const commandInput: CreateVersionCommandInput = {\n ...input,\n documentId,\n versionId: randomUUID(),\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n }\n const { result, logEntry } = await resolveDocumentsCommandBus(ctx).execute<\n CreateVersionCommandInput,\n z.infer<typeof versionCreateResponseSchema>\n >('documents.version.create', {\n input: commandInput,\n ctx: buildDocumentsCommandRuntimeContext(ctx),\n })\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentVersion,\n resourceId: documentId,\n operation: 'create',\n })\n\n const response = NextResponse.json({\n id: result.id,\n label: sanitizeDocumentVersionLabel(result.label),\n createdByUserId: result.createdByUserId,\n createdAt: result.createdAt,\n }, { status: 201 })\n return attachDocumentsOperationMetadata(response, logEntry, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentVersion,\n resourceId: result.id,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.versions.create')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Document versions',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: {\n summary: 'List document versions',\n query: versionListQuerySchema,\n responses: [{ status: 200, description: 'Document version metadata', schema: versionListResponseSchema }],\n errors: [\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n ],\n },\n POST: {\n summary: 'Create document version snapshot',\n requestBody: { contentType: 'application/json', schema: versionCreateSchema },\n responses: [{ status: 201, description: 'Version snapshot created', schema: versionCreateResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 413, description: 'Request body, document content, or version history exceeds its safe storage bound', schema: routeErrorSchema },\n ],\n },\n },\n})\n\nexport default { GET, POST }\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAE3B,SAAS,kCAAkC;AAC3C,SAAS,uBAAuB;AAChC,SAAS,4BAA4B;AACrC,SAAS,wCAAwC;AACjD,SAAS,kBAAkB;AAC3B,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,kCAAkC;AAC3C,SAAS,oCAAoC;AAMtC,MAAM,sBAAsB,EAAE,OAAO;AAAA,EAC1C,OAAO;AACT,CAAC;AAEM,MAAM,yBAAyB,EAAE,OAAO;AAAA,EAC7C,MAAM,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAM,EAAE,QAAQ,CAAC;AAAA,EAC1D,UAAU,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,gCAAgC,EAC1E,QAAQ,gCAAgC;AAC7C,CAAC;AAED,MAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,IAAI,EAAE,OA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O,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,EAC9C,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,OAAO;AAAA,MACP,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,6BAA6B,QAAQ,0BAA0B,CAAC;AAAA,MACxG,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,iBAAiB;AAAA,QACrE,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,iBAAiB;AAAA,MACpE;AAAA,IACF;AAAA,IACA,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa,EAAE,aAAa,oBAAoB,QAAQ,oBAAoB;AAAA,MAC5E,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,4BAA4B,CAAC;AAAA,MACzG,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,iBAAiB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,iBAAiB;AAAA,QACrE,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,iBAAiB;AAAA,QAClE,EAAE,QAAQ,KAAK,aAAa,qFAAqF,QAAQ,iBAAiB;AAAA,MAC5I;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAED,IAAO,gBAAQ,EAAE,KAAK,KAAK;",
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { randomUUID } from 'node:crypto'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findAndCountWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { DocumentVersion } from '../../../data/entities'\nimport { DOCUMENTS_ENTITY_IDS } from '../../../lib/constants'\nimport { DOCUMENTS_VERSION_LIST_PAGE_SIZE } from '../../../lib/historyLimits'\nimport { assertTier } from '../../../lib/permissions'\nimport { resolveUserLabels } from '../../../lib/userLabels'\nimport {\n assertDocumentId,\n assertDocumentNotArchived,\n handleDocumentsRouteError,\n readBody,\n resolveDocumentsContext,\n routeErrorSchema,\n runMutationGuardAfterSuccess,\n validateMutationGuard,\n withDocumentsContextErrors,\n} from '../../_shared'\nimport {\n attachDocumentsOperationMetadata,\n buildDocumentsCommandRuntimeContext,\n resolveDocumentsCommandBus,\n} from '../../_commands'\nimport type { CreateVersionCommandInput } from '../../../commands/versions'\nimport { documentVersionLabelSchema } from '../../../data/validators'\nimport { sanitizeDocumentVersionLabel } from '../../../lib/versionLabels'\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nexport const versionCreateSchema = z.object({\n label: documentVersionLabelSchema,\n})\n\nexport const versionListQuerySchema = z.object({\n page: z.coerce.number().int().min(1).max(10_000).default(1),\n pageSize: z.coerce.number().int().min(1).max(DOCUMENTS_VERSION_LIST_PAGE_SIZE)\n .default(DOCUMENTS_VERSION_LIST_PAGE_SIZE),\n})\n\nconst versionListItemSchema = z.object({\n id: z.string().uuid(),\n label: z.string().nullable(),\n createdByUserId: z.string().uuid(),\n createdByLabel: z.string().nullable(),\n createdAt: z.string(),\n})\n\nconst versionListResponseSchema = z.object({\n items: z.array(versionListItemSchema),\n page: z.number().int().positive(),\n pageSize: z.number().int().positive(),\n total: z.number().int().nonnegative(),\n totalPages: z.number().int().positive(),\n})\n\nconst versionCreateResponseSchema = z.object({\n id: z.string().uuid(),\n label: z.string().nullable(),\n createdByUserId: z.string().uuid(),\n createdAt: z.string(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['documents.view'] },\n POST: { requireAuth: true, requireFeatures: ['documents.edit'] },\n}\n\nasync function resolveId(context: RouteContext): Promise<string> {\n const params = await context.params\n return params.id\n}\n\nfunction serializeVersion(version: DocumentVersion): z.infer<typeof versionCreateResponseSchema> {\n return {\n id: version.id,\n label: sanitizeDocumentVersionLabel(version.label),\n createdByUserId: version.createdByUserId,\n createdAt: version.createdAt.toISOString(),\n }\n}\n\nexport async function GET(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n assertDocumentId(documentId)\n await assertTier(ctx.em, documentId, ctx.auth, 'viewer')\n const url = new URL(request.url)\n const query = versionListQuerySchema.parse(Object.fromEntries(url.searchParams.entries()))\n const [versions, total] = await findAndCountWithDecryption(\n ctx.em,\n DocumentVersion,\n {\n documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n },\n {\n fields: ['id', 'label', 'createdByUserId', 'createdAt'],\n orderBy: { createdAt: 'DESC', id: 'ASC' },\n limit: query.pageSize,\n offset: (query.page - 1) * query.pageSize,\n },\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n )\n const labels = await resolveUserLabels(\n ctx.container,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n versions.map((version) => version.createdByUserId),\n )\n\n return NextResponse.json({\n items: versions.map((version) => ({\n ...serializeVersion(version),\n createdByLabel: labels.get(version.createdByUserId)?.label ?? null,\n })),\n page: query.page,\n pageSize: query.pageSize,\n total,\n totalPages: Math.max(1, Math.ceil(total / query.pageSize)),\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.versions.list')\n }\n}\n\nexport async function POST(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.edit'])\n await assertTier(ctx.em, documentId, ctx.auth, 'editor')\n await assertDocumentNotArchived(ctx, documentId)\n const input = versionCreateSchema.parse(await readBody(request))\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentVersion,\n resourceId: documentId,\n operation: 'create',\n mutationPayload: input,\n mutationPayloadSchema: versionCreateSchema,\n })\n const commandInput: CreateVersionCommandInput = {\n ...input,\n documentId,\n versionId: randomUUID(),\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n }\n const { result, logEntry } = await resolveDocumentsCommandBus(ctx).execute<\n CreateVersionCommandInput,\n z.infer<typeof versionCreateResponseSchema>\n >('documents.version.create', {\n input: commandInput,\n ctx: buildDocumentsCommandRuntimeContext(ctx),\n })\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentVersion,\n resourceId: documentId,\n operation: 'create',\n })\n\n const response = NextResponse.json({\n id: result.id,\n label: sanitizeDocumentVersionLabel(result.label),\n createdByUserId: result.createdByUserId,\n createdAt: result.createdAt,\n }, { status: 201 })\n return attachDocumentsOperationMetadata(response, logEntry, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentVersion,\n resourceId: result.id,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.versions.create')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Document versions',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: {\n summary: 'List document versions',\n query: versionListQuerySchema,\n responses: [{ status: 200, description: 'Document version metadata', schema: versionListResponseSchema }],\n errors: [\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n ],\n },\n POST: {\n summary: 'Create document version snapshot',\n requestBody: { contentType: 'application/json', schema: versionCreateSchema },\n responses: [{ status: 201, description: 'Version snapshot created', schema: versionCreateResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 413, description: 'Request body, document content, or version history exceeds its safe storage bound', schema: routeErrorSchema },\n ],\n },\n },\n})\n\nexport default { GET, POST }\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAE3B,SAAS,kCAAkC;AAC3C,SAAS,uBAAuB;AAChC,SAAS,4BAA4B;AACrC,SAAS,wCAAwC;A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,qBAAqB,QAAQ,iBAAiB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,iBAAiB;AAAA,QACrE,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,iBAAiB;AAAA,QAClE,EAAE,QAAQ,KAAK,aAAa,qFAAqF,QAAQ,iBAAiB;AAAA,MAC5I;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAED,IAAO,gBAAQ,EAAE,KAAK,KAAK;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { resolveActorUserId } from "../lib/actor.js";
|
|
2
|
+
import { resolveActorUserId as resolveActorUserId2 } from "../lib/actor.js";
|
|
1
3
|
import { NextResponse } from "next/server";
|
|
2
4
|
import { z } from "zod";
|
|
3
5
|
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
|
|
@@ -54,7 +56,6 @@ function withDocumentsContextErrors(doc) {
|
|
|
54
56
|
}
|
|
55
57
|
return { ...doc, methods };
|
|
56
58
|
}
|
|
57
|
-
const actorUuidSchema = z.string().uuid();
|
|
58
59
|
const ROUTE_ERROR_TRANSLATIONS = {
|
|
59
60
|
Unauthorized: { key: "api.errors.unauthorized", fallback: "Unauthorized" },
|
|
60
61
|
Forbidden: { key: "api.errors.forbidden", fallback: "Forbidden" },
|
|
@@ -174,14 +175,6 @@ function readAuthScopeId(auth, key) {
|
|
|
174
175
|
if (typeof value === "string" && value.trim().length > 0) return value.trim();
|
|
175
176
|
return null;
|
|
176
177
|
}
|
|
177
|
-
function normalizeActorUuid(value) {
|
|
178
|
-
if (typeof value !== "string") return null;
|
|
179
|
-
const normalized = value.trim();
|
|
180
|
-
return actorUuidSchema.safeParse(normalized).success ? normalized : null;
|
|
181
|
-
}
|
|
182
|
-
function isApiKeyAuth(auth) {
|
|
183
|
-
return auth.isApiKey === true || auth.sub.trim().startsWith("api_key:");
|
|
184
|
-
}
|
|
185
178
|
function hasDocumentsFeature(auth, feature) {
|
|
186
179
|
if (auth.isSuperAdmin === true) return true;
|
|
187
180
|
return hasAllFeatures([feature], auth.features);
|
|
@@ -310,23 +303,6 @@ async function resolveDocumentsContext(request, requiredFeatures) {
|
|
|
310
303
|
request
|
|
311
304
|
};
|
|
312
305
|
}
|
|
313
|
-
function resolveActorUserId(auth) {
|
|
314
|
-
const subject = auth.sub.trim();
|
|
315
|
-
if (isApiKeyAuth(auth)) {
|
|
316
|
-
const keyId = normalizeActorUuid(auth.keyId);
|
|
317
|
-
if (!keyId || subject !== `api_key:${keyId}`) {
|
|
318
|
-
throw new CrudHttpError(403, { error: "api.errors.forbidden" });
|
|
319
|
-
}
|
|
320
|
-
if (auth.userId === void 0 || auth.userId === null) return keyId;
|
|
321
|
-
const backingUserId = normalizeActorUuid(auth.userId);
|
|
322
|
-
if (backingUserId) return backingUserId;
|
|
323
|
-
throw new CrudHttpError(403, { error: "api.errors.forbidden" });
|
|
324
|
-
}
|
|
325
|
-
const actorUserId = normalizeActorUuid(subject);
|
|
326
|
-
const claimedUserId = auth.userId === void 0 || auth.userId === null ? actorUserId : normalizeActorUuid(auth.userId);
|
|
327
|
-
if (actorUserId && claimedUserId === actorUserId) return actorUserId;
|
|
328
|
-
throw new CrudHttpError(403, { error: "api.errors.forbidden" });
|
|
329
|
-
}
|
|
330
306
|
async function readBody(request, maxBytes = DOCUMENTS_JSON_BODY_LIMITS.standard) {
|
|
331
307
|
return await readBoundedJsonBody(request, maxBytes, {}) ?? {};
|
|
332
308
|
}
|
|
@@ -374,6 +350,12 @@ async function handleDocumentsRouteError(error, label) {
|
|
|
374
350
|
{ status: 500 }
|
|
375
351
|
);
|
|
376
352
|
}
|
|
353
|
+
const documentIdSchema = z.string().uuid();
|
|
354
|
+
function assertDocumentId(id) {
|
|
355
|
+
if (!documentIdSchema.safeParse(id).success) {
|
|
356
|
+
throw new CrudHttpError(404, { error: "documents.documents.notFound" });
|
|
357
|
+
}
|
|
358
|
+
}
|
|
377
359
|
async function loadScopedDocument(ctx, id) {
|
|
378
360
|
const document = await findOneWithDecryption(ctx.em, Document, {
|
|
379
361
|
id,
|
|
@@ -482,6 +464,7 @@ export {
|
|
|
482
464
|
ORGANIZATION_SELECTION_INVALID_DESCRIPTION,
|
|
483
465
|
ORGANIZATION_SELECTION_INVALID_ERROR_CODE,
|
|
484
466
|
ROUTE_ERROR_TRANSLATIONS,
|
|
467
|
+
assertDocumentId,
|
|
485
468
|
assertDocumentNotArchived,
|
|
486
469
|
deriveCapabilitiesForContext,
|
|
487
470
|
handleDocumentsRouteError,
|
|
@@ -492,7 +475,7 @@ export {
|
|
|
492
475
|
loadScopedDocument,
|
|
493
476
|
loadScopedShare,
|
|
494
477
|
readBody,
|
|
495
|
-
resolveActorUserId,
|
|
478
|
+
resolveActorUserId2 as resolveActorUserId,
|
|
496
479
|
resolveDocumentCapabilityProjection,
|
|
497
480
|
resolveDocumentsContext,
|
|
498
481
|
routeErrorSchema,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/documents/api/_shared.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { z } from 'zod'\nimport { getAuthFromRequest, type AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'\nimport {\n ORGANIZATION_SCOPE_REQUIRED_ERROR_CODE,\n resolveActiveOrganizationId,\n} from '@open-mercato/shared/lib/auth/organizationScope'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport {\n runRouteMutationGuards,\n type RouteMutationGuardPassed,\n} from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { OpenApiHttpMethod, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n Document,\n DocumentContent,\n DocumentFolder,\n DocumentShare,\n} from '../data/entities'\nimport {\n deriveDocumentCapabilities,\n type DocumentCapabilities,\n} from '../lib/capabilities'\nimport {\n resolveActiveSubjectRoleIds,\n resolvePermission,\n type DocumentTier,\n} from '../lib/permissions'\nimport { hasResolvedDocumentsOrganizationAccess } from '../lib/organizationAccess'\nimport { containsCanonicalUuid } from '../lib/displayLabels'\nimport {\n DOCUMENTS_JSON_BODY_LIMITS,\n readBoundedJsonBody,\n} from '../lib/requestBody'\nimport { resolveOrganizationScopeService } from '../lib/platformServices'\n\nconst logger = createLogger('documents').child({ component: 'api' })\n\nexport type DocumentsAuthContext = NonNullable<AuthContext> & {\n features: string[]\n roleIds: string[]\n resolvedRoleIds: string[]\n organizationId: string\n}\n\nexport type DocumentsRouteContext = {\n container: AwilixContainer\n em: EntityManager\n auth: DocumentsAuthContext\n tenantId: string\n organizationId: string\n request: Request\n}\n\ntype RbacServiceLike = {\n loadAcl: (\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<{\n isSuperAdmin: boolean\n features: string[]\n organizations: string[] | null\n }>\n}\n\nexport type MutationGuardResult = RouteMutationGuardPassed\n\nexport type DocumentCapabilityProjection = {\n relationshipTier: DocumentTier | null\n capabilities: DocumentCapabilities\n}\n\n/**\n * Every documents error body carries a translated `error` message. Some also\n * carry a machine-readable `code` discriminator: without it a client cannot\n * tell an unresolved organization scope (recoverable \u2014 pick an organization)\n * apart from an ordinary validation rejection, since both are a 400.\n */\nexport const routeErrorSchema = z.object({ error: z.string(), code: z.string().optional() })\n\nexport const ORGANIZATION_SCOPE_REQUIRED_DESCRIPTION =\n `Organization scope could not be resolved (\\`code: ${ORGANIZATION_SCOPE_REQUIRED_ERROR_CODE}\\`)`\n\nexport const ORGANIZATION_SELECTION_INVALID_ERROR_CODE = 'organization_selection_invalid'\n\nexport const ORGANIZATION_SELECTION_INVALID_DESCRIPTION =\n `The selected organization no longer resolves (\\`code: ${ORGANIZATION_SELECTION_INVALID_ERROR_CODE}\\`)`\n\n/**\n * `resolveDocumentsContext` answers 400 with the\n * `organization_scope_required` discriminator whenever an unrestricted caller\n * (a super-admin viewing a foreign tenant with \"all organizations\" selected)\n * has no resolvable organization. Every route that resolves a documents\n * context can therefore return it, including methods whose own contract\n * declares no 400 at all \u2014 so the contract has to say so, or generated clients\n * and the API reference cannot model the recovery path.\n *\n * Responses are keyed by status when the document is built, so a route that\n * already documents a 400 must merge rather than append a second entry.\n */\nexport function withDocumentsContextErrors(doc: OpenApiRouteDoc): OpenApiRouteDoc {\n const methods: OpenApiRouteDoc['methods'] = {}\n for (const method of Object.keys(doc.methods) as OpenApiHttpMethod[]) {\n const methodDoc = doc.methods[method]\n if (!methodDoc) continue\n const merge = (\n errors: NonNullable<typeof methodDoc.errors>,\n status: number,\n description: string,\n ): NonNullable<typeof methodDoc.errors> => (\n errors.some((error) => error.status === status)\n ? errors.map((error) => (error.status === status\n ? {\n ...error,\n description: error.description\n ? `${error.description}, or ${description}`\n : description,\n schema: error.schema ?? routeErrorSchema,\n }\n : error))\n : [...errors, { status, description, schema: routeErrorSchema }]\n )\n // `resolveDocumentsContext` answers 400 `organization_scope_required` and\n // 422 `organization_selection_invalid` from the same call, so both ride on\n // every route that resolves a documents context.\n let errors = merge(methodDoc.errors ?? [], 400, ORGANIZATION_SCOPE_REQUIRED_DESCRIPTION)\n errors = merge(errors, 422, ORGANIZATION_SELECTION_INVALID_DESCRIPTION)\n methods[method] = { ...methodDoc, errors }\n }\n return { ...doc, methods }\n}\n\nconst actorUuidSchema = z.string().uuid()\n\nexport const ROUTE_ERROR_TRANSLATIONS: Record<string, { key: string; fallback: string }> = {\n Unauthorized: { key: 'api.errors.unauthorized', fallback: 'Unauthorized' },\n Forbidden: { key: 'api.errors.forbidden', fallback: 'Forbidden' },\n 'Organization context is required': {\n key: 'documents.errors.organizationRequired',\n fallback: 'Organization context is required',\n },\n 'Validation failed': { key: 'api.errors.invalidPayload', fallback: 'Invalid payload.' },\n 'Internal server error': { key: 'api.errors.internal', fallback: 'Internal server error' },\n 'Record changed by another user': {\n key: 'documents.errors.recordChanged',\n fallback: 'Record changed by another user',\n },\n 'Document not found': { key: 'documents.documents.notFound', fallback: 'Document not found.' },\n 'documents.content.notFound': {\n key: 'documents.content.notFound',\n fallback: 'Document content not found.',\n },\n 'documents.versions.notFound': {\n key: 'documents.versions.notFound',\n fallback: 'Version not found.',\n },\n 'documents.folders.error.invalidPlacement': {\n key: 'documents.folders.error.invalidPlacement',\n fallback: 'This folder cannot be placed there.',\n },\n 'Folder not found': { key: 'documents.folders.notFound', fallback: 'Folder not found.' },\n 'Share not found': { key: 'documents.share.notFound', fallback: 'Share not found.' },\n 'Comment not found': { key: 'documents.comments.notFound', fallback: 'Comment not found.' },\n 'Document comment limit reached': {\n key: 'documents.comments.limitExceeded',\n fallback: 'This document has reached its comment limit.',\n },\n 'Document version history storage limit exceeded': {\n key: 'documents.versions.quotaExceeded',\n fallback: 'Version history could not retain this snapshot within the document storage limit.',\n },\n 'documents.errors.requestBodyTooLarge': {\n key: 'documents.errors.requestBodyTooLarge',\n fallback: 'Request body is too large.',\n },\n 'Share principal not found in this organization': {\n key: 'documents.share.principalNotFound',\n fallback: 'Share principal not found in this organization',\n },\n 'Private attachment partition is not configured': {\n key: 'documents.attachments.partitionUnavailable',\n fallback: 'Private attachment partition is not configured',\n },\n 'Expected multipart/form-data': {\n key: 'documents.attachments.multipartRequired',\n fallback: 'Expected multipart/form-data',\n },\n 'File is required': { key: 'documents.attachments.fileRequired', fallback: 'File is required' },\n 'Attachment exceeds the maximum upload size.': {\n key: 'documents.attachments.tooLarge',\n fallback: 'Attachment exceeds the maximum upload size.',\n },\n 'Executable file types are not allowed as attachments.': {\n key: 'documents.attachments.executableBlocked',\n fallback: 'Executable file types are not allowed as attachments.',\n },\n 'Active content uploads are not allowed.': {\n key: 'documents.attachments.activeContentBlocked',\n fallback: 'Active content uploads are not allowed.',\n },\n 'Attachment storage quota exceeded for this tenant.': {\n key: 'documents.attachments.quotaExceeded',\n fallback: 'Attachment storage quota exceeded for this tenant.',\n },\n 'Attachment not found': { key: 'documents.attachments.notFound', fallback: 'Attachment not found' },\n 'Partition misconfigured': {\n key: 'documents.attachments.partitionMisconfigured',\n fallback: 'Attachment partition is misconfigured',\n },\n 'File not available': {\n key: 'documents.attachments.fileUnavailable',\n fallback: 'File not available',\n },\n 'Unsupported format': { key: 'documents.export.unsupportedFormat', fallback: 'Unsupported format' },\n 'documents.export.runtimeUnavailable': {\n key: 'documents.export.runtimeUnavailable',\n fallback: 'PDF export is temporarily unavailable.',\n },\n 'documents.errors.organizationSelectionInvalid': {\n key: 'documents.errors.organizationSelectionInvalid',\n fallback: 'Your selected organization is no longer available. Please re-select an organization and try again.',\n },\n}\n\nconst ROUTE_ERROR_KEY_FALLBACKS = Object.fromEntries(\n Object.values(ROUTE_ERROR_TRANSLATIONS).map(({ key, fallback }) => [key, fallback]),\n) as Record<string, string>\n\nfunction normalizeStrings(values: unknown): string[] {\n if (!Array.isArray(values)) return []\n return Array.from(\n new Set(\n values\n .map((value) => (typeof value === 'string' ? value.trim() : ''))\n .filter((value) => value.length > 0),\n ),\n )\n}\n\nfunction resolveSelectedOrganization(\n auth: NonNullable<AuthContext>,\n scope: { selectedId?: string | null; filterIds?: string[] | null; allowedIds?: string[] | null; tenantId?: string | null } | null,\n): string | null {\n // Every document row carries one organization, so there is no \"all\n // organizations\" view of this module. When the super-admin switcher clears\n // `auth.orgId`, keep the operator on their own organization (the shared\n // helper refuses the fallback once the tenant override moved them elsewhere)\n // instead of failing every request.\n const activeOrganizationId = resolveActiveOrganizationId(auth)\n const allowed = scope?.filterIds ?? scope?.allowedIds ?? (activeOrganizationId ? [activeOrganizationId] : null)\n const candidates = [\n scope?.selectedId ?? null,\n activeOrganizationId,\n Array.isArray(allowed) && allowed.length > 0 ? allowed[0] : null,\n ]\n for (const candidate of candidates) {\n if (!candidate) continue\n if (!Array.isArray(allowed) || allowed.includes(candidate)) return candidate\n }\n return null\n}\n\nfunction readAuthScopeId(auth: NonNullable<AuthContext>, key: 'actorTenantId' | 'actorOrgId'): string | null {\n const value = auth[key]\n if (typeof value === 'string' && value.trim().length > 0) return value.trim()\n return null\n}\n\nfunction normalizeActorUuid(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const normalized = value.trim()\n return actorUuidSchema.safeParse(normalized).success ? normalized : null\n}\n\nfunction isApiKeyAuth(auth: NonNullable<AuthContext>): boolean {\n return auth.isApiKey === true || auth.sub.trim().startsWith('api_key:')\n}\n\nexport function hasDocumentsFeature(auth: DocumentsAuthContext, feature: string): boolean {\n if (auth.isSuperAdmin === true) return true\n return hasAllFeatures([feature], auth.features)\n}\n\nexport function hasAnyDocumentsFeature(auth: DocumentsAuthContext, features: string[]): boolean {\n if (auth.isSuperAdmin === true) return true\n return features.some((feature) => hasAllFeatures([feature], auth.features))\n}\n\nexport function deriveCapabilitiesForContext(\n ctx: DocumentsRouteContext,\n relationshipTier: DocumentTier | null,\n options: { archived?: boolean } = {},\n): DocumentCapabilities {\n return deriveDocumentCapabilities({\n relationshipTier,\n managerOverride: hasDocumentsFeature(ctx.auth, 'documents.manage'),\n archived: options.archived === true,\n userFeatures: ctx.auth.features,\n })\n}\n\nexport async function resolveDocumentCapabilityProjection(\n ctx: DocumentsRouteContext,\n documentId: string,\n options: { archived?: boolean } = {},\n): Promise<DocumentCapabilityProjection> {\n const relationshipTier = await resolvePermission(ctx.em, documentId, ctx.auth)\n return {\n relationshipTier,\n capabilities: deriveCapabilitiesForContext(ctx, relationshipTier, options),\n }\n}\n\nexport async function loadDocumentArchivedState(\n ctx: DocumentsRouteContext,\n documentId: string,\n): Promise<{ archivedAt: Date | null }> {\n const document = await findOneWithDecryption(\n ctx.em,\n Document,\n {\n id: documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: null,\n },\n { fields: ['id', 'archivedAt'] },\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n )\n if (!document) throw new CrudHttpError(404, { error: 'documents.documents.notFound' })\n return { archivedAt: document.archivedAt ?? null }\n}\n\nexport async function assertDocumentNotArchived(\n ctx: DocumentsRouteContext,\n documentId: string,\n): Promise<void> {\n const state = await loadDocumentArchivedState(ctx, documentId)\n if (state.archivedAt !== null) {\n throw new CrudHttpError(403, { error: 'documents.errors.documentArchived' })\n }\n}\n\nexport async function resolveDocumentsContext(\n request: Request,\n requiredFeatures: string[],\n): Promise<DocumentsRouteContext> {\n const container = await createRequestContainer()\n const em = container.resolve('em') as EntityManager\n const auth = await getAuthFromRequest(request)\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: 'api.errors.unauthorized' })\n }\n\n const authenticatedActorUserId = resolveActorUserId(auth)\n const actorTenantId = readAuthScopeId(auth, 'actorTenantId') ?? auth.tenantId\n const actorOrganizationId = readAuthScopeId(auth, 'actorOrgId') ?? auth.orgId\n const rbacService = container.resolve('rbacService') as RbacServiceLike\n const actorAcl = await rbacService.loadAcl(auth.sub, {\n tenantId: actorTenantId,\n organizationId: actorOrganizationId,\n })\n // Organization scope resolution historically accepts the authenticated\n // superadmin bit to support tenant/org switching. Replace that potentially\n // stale token bit with the live RBAC decision before asking the shared scope\n // resolver to expand parent grants into descendant organizations.\n const scopeAuth = {\n ...auth,\n // API-key authentication validates both keyId and any backing user. Keep\n // the prefixed subject for ACL while projecting its UUID domain actor for\n // ownership/share/audit helpers. An unbound key uses its own key UUID.\n userId: authenticatedActorUserId,\n isSuperAdmin: actorAcl.isSuperAdmin === true,\n }\n const organizationScopeService = resolveOrganizationScopeService(container)\n if (!organizationScopeService) {\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n const scope = await organizationScopeService.resolveForRequest({ auth: scopeAuth, request })\n // The caller explicitly selected an organization that no longer resolves to a\n // real, accessible org (stale selected-org cookie after a delete or an access\n // loss). The scope resolver falls back to another allowed org, so continuing\n // would silently read and write against an organization the caller never\n // chose. Fail loud on every documents operation instead \u2014 the same contract\n // `makeCrudRoute` enforces via `rejectInvalidOrgSelection` (#3936).\n if (scope?.selectionRejected) {\n throw new CrudHttpError(422, {\n error: 'documents.errors.organizationSelectionInvalid',\n code: ORGANIZATION_SELECTION_INVALID_ERROR_CODE,\n })\n }\n const tenantId = scope?.tenantId ?? auth.tenantId\n const organizationId = resolveSelectedOrganization(scopeAuth, scope)\n if (!tenantId) {\n throw new CrudHttpError(400, { error: 'documents.errors.organizationRequired' })\n }\n if (!organizationId) {\n // An unrestricted caller with no resolvable organization (a super-admin\n // viewing a foreign tenant with \"all organizations\" selected) is a 400, not\n // a 401 (which `apiFetch` would turn into a refresh loop) and not a 403 (the\n // caller is allowed in; they only need to pick an organization). A caller\n // whose grants expand to no organization at all stays a 403.\n const unrestricted = (scope?.filterIds ?? scope?.allowedIds ?? null) === null\n if (unrestricted) {\n throw new CrudHttpError(400, {\n error: 'documents.errors.organizationRequired',\n code: ORGANIZATION_SCOPE_REQUIRED_ERROR_CODE,\n })\n }\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n\n const acl = await rbacService.loadAcl(auth.sub, { tenantId, organizationId })\n if (!hasResolvedDocumentsOrganizationAccess(acl, organizationId, scope)) {\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n const roleIds = await resolveActiveSubjectRoleIds(\n container,\n { tenantId, organizationId },\n auth.sub,\n )\n const documentsAuth: DocumentsAuthContext = {\n ...scopeAuth,\n tenantId,\n orgId: organizationId,\n organizationId,\n roleIds,\n resolvedRoleIds: roleIds,\n // JWT/trusted-request claims are only authentication hints. The current\n // RBAC projection is authoritative for features and superadmin status so\n // a revoked grant cannot survive in a long-lived token.\n features: acl.isSuperAdmin === true ? ['*'] : normalizeStrings(acl.features),\n isSuperAdmin: acl.isSuperAdmin === true,\n }\n\n if (!hasAnyDocumentsFeature(documentsAuth, requiredFeatures)) {\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n\n return {\n container,\n em,\n auth: documentsAuth,\n tenantId,\n organizationId,\n request,\n }\n}\n\nexport function resolveActorUserId(auth: NonNullable<AuthContext>): string {\n const subject = auth.sub.trim()\n if (isApiKeyAuth(auth)) {\n // `keyId` is populated only by successful API-key authentication. Do not\n // recover an actor by parsing an arbitrary prefixed subject when that\n // validated field is absent, malformed, or disagrees with the subject.\n const keyId = normalizeActorUuid(auth.keyId)\n if (!keyId || subject !== `api_key:${keyId}`) {\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n if (auth.userId === undefined || auth.userId === null) return keyId\n const backingUserId = normalizeActorUuid(auth.userId)\n if (backingUserId) return backingUserId\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n\n const actorUserId = normalizeActorUuid(subject)\n const claimedUserId = auth.userId === undefined || auth.userId === null\n ? actorUserId\n : normalizeActorUuid(auth.userId)\n if (actorUserId && claimedUserId === actorUserId) return actorUserId\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n}\n\nexport async function readBody(\n request: Request,\n maxBytes = DOCUMENTS_JSON_BODY_LIMITS.standard,\n): Promise<Record<string, unknown>> {\n return (await readBoundedJsonBody<Record<string, unknown>>(request, maxBytes, {})) ?? {}\n}\n\nasync function localizeRouteErrorBody(body: Record<string, unknown>): Promise<Record<string, unknown>> {\n const rawError = typeof body.error === 'string' ? body.error : null\n if (!rawError) return body\n\n if (containsCanonicalUuid(rawError)) {\n const { key, fallback } = ROUTE_ERROR_TRANSLATIONS['Internal server error']!\n try {\n const { translate } = await resolveTranslations()\n return { ...body, error: translate(key, fallback) }\n } catch {\n return { ...body, error: fallback }\n }\n }\n\n const literal = ROUTE_ERROR_TRANSLATIONS[rawError]\n const key = literal?.key ?? rawError\n const fallback = literal?.fallback ?? ROUTE_ERROR_KEY_FALLBACKS[key]\n // Attachment failures reach these routes as the attachments module's own\n // catalogued keys. The locale dictionary is merged across modules, so they\n // resolve here; without this prefix the raw key would reach the client.\n if (\n !key.startsWith('documents.')\n && !key.startsWith('api.')\n && !key.startsWith('attachments.')\n ) return body\n\n try {\n const { translate } = await resolveTranslations()\n return { ...body, error: translate(key, fallback) }\n } catch {\n return { ...body, error: fallback ?? key }\n }\n}\n\nexport async function handleDocumentsRouteError(error: unknown, label: string): Promise<Response> {\n if (isCrudHttpError(error)) {\n const body = error.body && typeof error.body === 'object' && !Array.isArray(error.body)\n ? error.body as Record<string, unknown>\n : { error: 'api.errors.internal' }\n return NextResponse.json(await localizeRouteErrorBody(body), { status: error.status })\n }\n const interceptorRejection = getCommandInterceptorHttpRejection(error)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n if (error instanceof z.ZodError) {\n return NextResponse.json(\n await localizeRouteErrorBody({ error: 'api.errors.invalidPayload', details: error.issues }),\n { status: 400 },\n )\n }\n logger.error(`${label} failed`, { err: error })\n return NextResponse.json(\n await localizeRouteErrorBody({ error: 'api.errors.internal' }),\n { status: 500 },\n )\n}\n\nexport async function loadScopedDocument(ctx: DocumentsRouteContext, id: string): Promise<Document> {\n const document = await findOneWithDecryption(ctx.em, Document, {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: null,\n }, undefined, { tenantId: ctx.tenantId, organizationId: ctx.organizationId })\n if (!document) throw new CrudHttpError(404, { error: 'documents.documents.notFound' })\n return document\n}\n\n/**\n * Only the owner (or a documents manager) may learn that a document was\n * removed, e.g. after undoing its creation; everyone else keeps the\n * existence-hiding 403 so deleted ids stay indistinguishable from foreign ones.\n */\nexport async function isRemovedDocumentVisibleToActor(ctx: DocumentsRouteContext, id: string): Promise<boolean> {\n const document = await findOneWithDecryption(ctx.em, Document, {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: { $ne: null },\n }, { fields: ['id', 'ownerUserId'] }, { tenantId: ctx.tenantId, organizationId: ctx.organizationId })\n if (!document) return false\n if (hasDocumentsFeature(ctx.auth, 'documents.manage')) return true\n return document.ownerUserId === resolveActorUserId(ctx.auth)\n}\n\nexport async function loadScopedShare(\n ctx: DocumentsRouteContext,\n documentId: string,\n shareId: string,\n): Promise<DocumentShare> {\n const share = await findOneWithDecryption(ctx.em, DocumentShare, {\n id: shareId,\n documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: null,\n }, undefined, { tenantId: ctx.tenantId, organizationId: ctx.organizationId })\n if (!share) throw new CrudHttpError(404, { error: 'documents.share.notFound' })\n return share\n}\n\nexport function serializeDocument(document: Document): Record<string, unknown> {\n return {\n id: document.id,\n title: document.title,\n folderId: document.folderId ?? null,\n ownerUserId: document.ownerUserId,\n createdByUserId: document.createdByUserId,\n isActive: document.isActive,\n createdAt: document.createdAt.toISOString(),\n updatedAt: document.updatedAt.toISOString(),\n }\n}\n\nexport function serializeContent(content: DocumentContent | null): Record<string, unknown> {\n return {\n contentHtml: content?.contentHtml ?? '',\n contentText: content?.contentText ?? '',\n updatedAt: content?.updatedAt ? content.updatedAt.toISOString() : null,\n }\n}\n\nexport function serializeFolder(folder: DocumentFolder): Record<string, unknown> {\n return {\n id: folder.id,\n name: folder.name,\n parentFolderId: folder.parentFolderId ?? null,\n ownerUserId: folder.ownerUserId,\n createdAt: folder.createdAt.toISOString(),\n updatedAt: folder.updatedAt.toISOString(),\n }\n}\n\nexport function serializeShare(share: DocumentShare): Record<string, unknown> {\n return {\n id: share.id,\n documentId: share.documentId,\n principalType: share.principalType,\n principalId: share.principalId,\n permission: share.permission,\n createdByUserId: share.createdByUserId,\n createdAt: share.createdAt.toISOString(),\n updatedAt: share.updatedAt.toISOString(),\n }\n}\n\nexport async function validateMutationGuard(\n ctx: DocumentsRouteContext,\n input: {\n resourceKind: string\n resourceId: string\n operation: 'create' | 'update' | 'delete' | 'custom'\n mutationPayload?: Record<string, unknown> | null\n /**\n * Re-parses a guard's `modifiedPayload` before it reaches the command. A\n * registry guard may rewrite the payload, and the route's own schema is the\n * only thing that still guarantees the command receives a shape it can trust.\n */\n mutationPayloadSchema?: { parse: (value: unknown) => Record<string, unknown> }\n },\n): Promise<MutationGuardResult> {\n // `runRouteMutationGuards` runs EVERY registered guard plus the bridged legacy\n // DI service. The deprecated `validateCrudMutationGuard` /\n // `runCrudMutationGuardAfterSuccess` pair used here before resolved only the\n // single DI-registered guard service, so every guard a module contributed\n // through the registry \u2014 along with its payload transformation and its\n // after-success callback \u2014 was silently skipped on Documents writes.\n const guardResult = await runRouteMutationGuards({\n container: ctx.container,\n req: ctx.request,\n auth: {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: resolveActorUserId(ctx.auth),\n userFeatures: ctx.auth.features,\n },\n input: {\n resourceKind: input.resourceKind,\n resourceId: input.resourceId,\n operation: input.operation,\n mutationPayload: input.mutationPayload ?? null,\n },\n })\n if (!guardResult.ok) {\n throw new CrudHttpError(guardResult.errorStatus, guardResult.errorBody)\n }\n if (guardResult.modifiedPayload && input.mutationPayload) {\n const transformed = input.mutationPayloadSchema\n ? input.mutationPayloadSchema.parse(guardResult.modifiedPayload)\n : guardResult.modifiedPayload\n // Routes read the object they handed in, so the transformation has to land\n // there rather than only on the guard result.\n for (const key of Object.keys(input.mutationPayload)) delete input.mutationPayload[key]\n Object.assign(input.mutationPayload, transformed)\n }\n return guardResult\n}\n\nexport async function runMutationGuardAfterSuccess(\n _ctx: DocumentsRouteContext,\n guardResult: MutationGuardResult,\n _input: {\n resourceKind: string\n resourceId: string\n operation: 'create' | 'update' | 'delete' | 'custom'\n },\n): Promise<void> {\n await guardResult.runAfterSuccess()\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAG7B,SAAS,SAAS;AAClB,SAAS,0BAA4C;AACrD,SAAS,8BAA8B;AACvC,SAAS,sBAAsB;AA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,eAAe,MAAM;AAAA,IACrB,aAAa,MAAM;AAAA,IACnB,YAAY,MAAM;AAAA,IAClB,iBAAiB,MAAM;AAAA,IACvB,WAAW,MAAM,UAAU,YAAY;AAAA,IACvC,WAAW,MAAM,UAAU,YAAY;AAAA,EACzC;AACF;AAEA,eAAsB,sBACpB,KACA,OAY8B;AAO9B,QAAM,cAAc,MAAM,uBAAuB;AAAA,IAC/C,WAAW,IAAI;AAAA,IACf,KAAK,IAAI;AAAA,IACT,MAAM;AAAA,MACJ,UAAU,IAAI;AAAA,MACd,gBAAgB,IAAI;AAAA,MACpB,QAAQ,mBAAmB,IAAI,IAAI;AAAA,MACnC,cAAc,IAAI,KAAK;AAAA,IACzB;AAAA,IACA,OAAO;AAAA,MACL,cAAc,MAAM;AAAA,MACpB,YAAY,MAAM;AAAA,MAClB,WAAW,MAAM;AAAA,MACjB,iBAAiB,MAAM,mBAAmB;AAAA,IAC5C;AAAA,EACF,CAAC;AACD,MAAI,CAAC,YAAY,IAAI;AACnB,UAAM,IAAI,cAAc,YAAY,aAAa,YAAY,SAAS;AAAA,EACxE;AACA,MAAI,YAAY,mBAAmB,MAAM,iBAAiB;AACxD,UAAM,cAAc,MAAM,wBACtB,MAAM,sBAAsB,MAAM,YAAY,eAAe,IAC7D,YAAY;AAGhB,eAAW,OAAO,OAAO,KAAK,MAAM,eAAe,EAAG,QAAO,MAAM,gBAAgB,GAAG;AACtF,WAAO,OAAO,MAAM,iBAAiB,WAAW;AAAA,EAClD;AACA,SAAO;AACT;AAEA,eAAsB,6BACpB,MACA,aACA,QAKe;AACf,QAAM,YAAY,gBAAgB;AACpC;",
|
|
6
|
-
"names": ["errors", "key", "fallback"]
|
|
4
|
+
"sourcesContent": ["import { resolveActorUserId } from '../lib/actor'\nexport { resolveActorUserId } from '../lib/actor'\nimport { NextResponse } from 'next/server'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { z } from 'zod'\nimport { getAuthFromRequest, type AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'\nimport {\n ORGANIZATION_SCOPE_REQUIRED_ERROR_CODE,\n resolveActiveOrganizationId,\n} from '@open-mercato/shared/lib/auth/organizationScope'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport {\n runRouteMutationGuards,\n type RouteMutationGuardPassed,\n} from '@open-mercato/shared/lib/crud/route-mutation-guard'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { OpenApiHttpMethod, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n Document,\n DocumentContent,\n DocumentFolder,\n DocumentShare,\n} from '../data/entities'\nimport {\n deriveDocumentCapabilities,\n type DocumentCapabilities,\n} from '../lib/capabilities'\nimport {\n resolveActiveSubjectRoleIds,\n resolvePermission,\n type DocumentTier,\n} from '../lib/permissions'\nimport { hasResolvedDocumentsOrganizationAccess } from '../lib/organizationAccess'\nimport { containsCanonicalUuid } from '../lib/displayLabels'\nimport {\n DOCUMENTS_JSON_BODY_LIMITS,\n readBoundedJsonBody,\n} from '../lib/requestBody'\nimport { resolveOrganizationScopeService } from '../lib/platformServices'\n\nconst logger = createLogger('documents').child({ component: 'api' })\n\nexport type DocumentsAuthContext = NonNullable<AuthContext> & {\n features: string[]\n roleIds: string[]\n resolvedRoleIds: string[]\n organizationId: string\n}\n\nexport type DocumentsRouteContext = {\n container: AwilixContainer\n em: EntityManager\n auth: DocumentsAuthContext\n tenantId: string\n organizationId: string\n request: Request\n}\n\ntype RbacServiceLike = {\n loadAcl: (\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<{\n isSuperAdmin: boolean\n features: string[]\n organizations: string[] | null\n }>\n}\n\nexport type MutationGuardResult = RouteMutationGuardPassed\n\nexport type DocumentCapabilityProjection = {\n relationshipTier: DocumentTier | null\n capabilities: DocumentCapabilities\n}\n\n/**\n * Every documents error body carries a translated `error` message. Some also\n * carry a machine-readable `code` discriminator: without it a client cannot\n * tell an unresolved organization scope (recoverable \u2014 pick an organization)\n * apart from an ordinary validation rejection, since both are a 400.\n */\nexport const routeErrorSchema = z.object({ error: z.string(), code: z.string().optional() })\n\nexport const ORGANIZATION_SCOPE_REQUIRED_DESCRIPTION =\n `Organization scope could not be resolved (\\`code: ${ORGANIZATION_SCOPE_REQUIRED_ERROR_CODE}\\`)`\n\nexport const ORGANIZATION_SELECTION_INVALID_ERROR_CODE = 'organization_selection_invalid'\n\nexport const ORGANIZATION_SELECTION_INVALID_DESCRIPTION =\n `The selected organization no longer resolves (\\`code: ${ORGANIZATION_SELECTION_INVALID_ERROR_CODE}\\`)`\n\n/**\n * `resolveDocumentsContext` answers 400 with the\n * `organization_scope_required` discriminator whenever an unrestricted caller\n * (a super-admin viewing a foreign tenant with \"all organizations\" selected)\n * has no resolvable organization. Every route that resolves a documents\n * context can therefore return it, including methods whose own contract\n * declares no 400 at all \u2014 so the contract has to say so, or generated clients\n * and the API reference cannot model the recovery path.\n *\n * Responses are keyed by status when the document is built, so a route that\n * already documents a 400 must merge rather than append a second entry.\n */\nexport function withDocumentsContextErrors(doc: OpenApiRouteDoc): OpenApiRouteDoc {\n const methods: OpenApiRouteDoc['methods'] = {}\n for (const method of Object.keys(doc.methods) as OpenApiHttpMethod[]) {\n const methodDoc = doc.methods[method]\n if (!methodDoc) continue\n const merge = (\n errors: NonNullable<typeof methodDoc.errors>,\n status: number,\n description: string,\n ): NonNullable<typeof methodDoc.errors> => (\n errors.some((error) => error.status === status)\n ? errors.map((error) => (error.status === status\n ? {\n ...error,\n description: error.description\n ? `${error.description}, or ${description}`\n : description,\n schema: error.schema ?? routeErrorSchema,\n }\n : error))\n : [...errors, { status, description, schema: routeErrorSchema }]\n )\n // `resolveDocumentsContext` answers 400 `organization_scope_required` and\n // 422 `organization_selection_invalid` from the same call, so both ride on\n // every route that resolves a documents context.\n let errors = merge(methodDoc.errors ?? [], 400, ORGANIZATION_SCOPE_REQUIRED_DESCRIPTION)\n errors = merge(errors, 422, ORGANIZATION_SELECTION_INVALID_DESCRIPTION)\n methods[method] = { ...methodDoc, errors }\n }\n return { ...doc, methods }\n}\n\nexport const ROUTE_ERROR_TRANSLATIONS: Record<string, { key: string; fallback: string }> = {\n Unauthorized: { key: 'api.errors.unauthorized', fallback: 'Unauthorized' },\n Forbidden: { key: 'api.errors.forbidden', fallback: 'Forbidden' },\n 'Organization context is required': {\n key: 'documents.errors.organizationRequired',\n fallback: 'Organization context is required',\n },\n 'Validation failed': { key: 'api.errors.invalidPayload', fallback: 'Invalid payload.' },\n 'Internal server error': { key: 'api.errors.internal', fallback: 'Internal server error' },\n 'Record changed by another user': {\n key: 'documents.errors.recordChanged',\n fallback: 'Record changed by another user',\n },\n 'Document not found': { key: 'documents.documents.notFound', fallback: 'Document not found.' },\n 'documents.content.notFound': {\n key: 'documents.content.notFound',\n fallback: 'Document content not found.',\n },\n 'documents.versions.notFound': {\n key: 'documents.versions.notFound',\n fallback: 'Version not found.',\n },\n 'documents.folders.error.invalidPlacement': {\n key: 'documents.folders.error.invalidPlacement',\n fallback: 'This folder cannot be placed there.',\n },\n 'Folder not found': { key: 'documents.folders.notFound', fallback: 'Folder not found.' },\n 'Share not found': { key: 'documents.share.notFound', fallback: 'Share not found.' },\n 'Comment not found': { key: 'documents.comments.notFound', fallback: 'Comment not found.' },\n 'Document comment limit reached': {\n key: 'documents.comments.limitExceeded',\n fallback: 'This document has reached its comment limit.',\n },\n 'Document version history storage limit exceeded': {\n key: 'documents.versions.quotaExceeded',\n fallback: 'Version history could not retain this snapshot within the document storage limit.',\n },\n 'documents.errors.requestBodyTooLarge': {\n key: 'documents.errors.requestBodyTooLarge',\n fallback: 'Request body is too large.',\n },\n 'Share principal not found in this organization': {\n key: 'documents.share.principalNotFound',\n fallback: 'Share principal not found in this organization',\n },\n 'Private attachment partition is not configured': {\n key: 'documents.attachments.partitionUnavailable',\n fallback: 'Private attachment partition is not configured',\n },\n 'Expected multipart/form-data': {\n key: 'documents.attachments.multipartRequired',\n fallback: 'Expected multipart/form-data',\n },\n 'File is required': { key: 'documents.attachments.fileRequired', fallback: 'File is required' },\n 'Attachment exceeds the maximum upload size.': {\n key: 'documents.attachments.tooLarge',\n fallback: 'Attachment exceeds the maximum upload size.',\n },\n 'Executable file types are not allowed as attachments.': {\n key: 'documents.attachments.executableBlocked',\n fallback: 'Executable file types are not allowed as attachments.',\n },\n 'Active content uploads are not allowed.': {\n key: 'documents.attachments.activeContentBlocked',\n fallback: 'Active content uploads are not allowed.',\n },\n 'Attachment storage quota exceeded for this tenant.': {\n key: 'documents.attachments.quotaExceeded',\n fallback: 'Attachment storage quota exceeded for this tenant.',\n },\n 'Attachment not found': { key: 'documents.attachments.notFound', fallback: 'Attachment not found' },\n 'Partition misconfigured': {\n key: 'documents.attachments.partitionMisconfigured',\n fallback: 'Attachment partition is misconfigured',\n },\n 'File not available': {\n key: 'documents.attachments.fileUnavailable',\n fallback: 'File not available',\n },\n 'Unsupported format': { key: 'documents.export.unsupportedFormat', fallback: 'Unsupported format' },\n 'documents.export.runtimeUnavailable': {\n key: 'documents.export.runtimeUnavailable',\n fallback: 'PDF export is temporarily unavailable.',\n },\n 'documents.errors.organizationSelectionInvalid': {\n key: 'documents.errors.organizationSelectionInvalid',\n fallback: 'Your selected organization is no longer available. Please re-select an organization and try again.',\n },\n}\n\nconst ROUTE_ERROR_KEY_FALLBACKS = Object.fromEntries(\n Object.values(ROUTE_ERROR_TRANSLATIONS).map(({ key, fallback }) => [key, fallback]),\n) as Record<string, string>\n\nfunction normalizeStrings(values: unknown): string[] {\n if (!Array.isArray(values)) return []\n return Array.from(\n new Set(\n values\n .map((value) => (typeof value === 'string' ? value.trim() : ''))\n .filter((value) => value.length > 0),\n ),\n )\n}\n\nfunction resolveSelectedOrganization(\n auth: NonNullable<AuthContext>,\n scope: { selectedId?: string | null; filterIds?: string[] | null; allowedIds?: string[] | null; tenantId?: string | null } | null,\n): string | null {\n // Every document row carries one organization, so there is no \"all\n // organizations\" view of this module. When the super-admin switcher clears\n // `auth.orgId`, keep the operator on their own organization (the shared\n // helper refuses the fallback once the tenant override moved them elsewhere)\n // instead of failing every request.\n const activeOrganizationId = resolveActiveOrganizationId(auth)\n const allowed = scope?.filterIds ?? scope?.allowedIds ?? (activeOrganizationId ? [activeOrganizationId] : null)\n const candidates = [\n scope?.selectedId ?? null,\n activeOrganizationId,\n Array.isArray(allowed) && allowed.length > 0 ? allowed[0] : null,\n ]\n for (const candidate of candidates) {\n if (!candidate) continue\n if (!Array.isArray(allowed) || allowed.includes(candidate)) return candidate\n }\n return null\n}\n\nfunction readAuthScopeId(auth: NonNullable<AuthContext>, key: 'actorTenantId' | 'actorOrgId'): string | null {\n const value = auth[key]\n if (typeof value === 'string' && value.trim().length > 0) return value.trim()\n return null\n}\n\nexport function hasDocumentsFeature(auth: DocumentsAuthContext, feature: string): boolean {\n if (auth.isSuperAdmin === true) return true\n return hasAllFeatures([feature], auth.features)\n}\n\nexport function hasAnyDocumentsFeature(auth: DocumentsAuthContext, features: string[]): boolean {\n if (auth.isSuperAdmin === true) return true\n return features.some((feature) => hasAllFeatures([feature], auth.features))\n}\n\nexport function deriveCapabilitiesForContext(\n ctx: DocumentsRouteContext,\n relationshipTier: DocumentTier | null,\n options: { archived?: boolean } = {},\n): DocumentCapabilities {\n return deriveDocumentCapabilities({\n relationshipTier,\n managerOverride: hasDocumentsFeature(ctx.auth, 'documents.manage'),\n archived: options.archived === true,\n userFeatures: ctx.auth.features,\n })\n}\n\nexport async function resolveDocumentCapabilityProjection(\n ctx: DocumentsRouteContext,\n documentId: string,\n options: { archived?: boolean } = {},\n): Promise<DocumentCapabilityProjection> {\n const relationshipTier = await resolvePermission(ctx.em, documentId, ctx.auth)\n return {\n relationshipTier,\n capabilities: deriveCapabilitiesForContext(ctx, relationshipTier, options),\n }\n}\n\nexport async function loadDocumentArchivedState(\n ctx: DocumentsRouteContext,\n documentId: string,\n): Promise<{ archivedAt: Date | null }> {\n const document = await findOneWithDecryption(\n ctx.em,\n Document,\n {\n id: documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: null,\n },\n { fields: ['id', 'archivedAt'] },\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n )\n if (!document) throw new CrudHttpError(404, { error: 'documents.documents.notFound' })\n return { archivedAt: document.archivedAt ?? null }\n}\n\nexport async function assertDocumentNotArchived(\n ctx: DocumentsRouteContext,\n documentId: string,\n): Promise<void> {\n const state = await loadDocumentArchivedState(ctx, documentId)\n if (state.archivedAt !== null) {\n throw new CrudHttpError(403, { error: 'documents.errors.documentArchived' })\n }\n}\n\nexport async function resolveDocumentsContext(\n request: Request,\n requiredFeatures: string[],\n): Promise<DocumentsRouteContext> {\n const container = await createRequestContainer()\n const em = container.resolve('em') as EntityManager\n const auth = await getAuthFromRequest(request)\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: 'api.errors.unauthorized' })\n }\n\n const authenticatedActorUserId = resolveActorUserId(auth)\n const actorTenantId = readAuthScopeId(auth, 'actorTenantId') ?? auth.tenantId\n const actorOrganizationId = readAuthScopeId(auth, 'actorOrgId') ?? auth.orgId\n const rbacService = container.resolve('rbacService') as RbacServiceLike\n const actorAcl = await rbacService.loadAcl(auth.sub, {\n tenantId: actorTenantId,\n organizationId: actorOrganizationId,\n })\n // Organization scope resolution historically accepts the authenticated\n // superadmin bit to support tenant/org switching. Replace that potentially\n // stale token bit with the live RBAC decision before asking the shared scope\n // resolver to expand parent grants into descendant organizations.\n const scopeAuth = {\n ...auth,\n // API-key authentication validates both keyId and any backing user. Keep\n // the prefixed subject for ACL while projecting its UUID domain actor for\n // ownership/share/audit helpers. An unbound key uses its own key UUID.\n userId: authenticatedActorUserId,\n isSuperAdmin: actorAcl.isSuperAdmin === true,\n }\n const organizationScopeService = resolveOrganizationScopeService(container)\n if (!organizationScopeService) {\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n const scope = await organizationScopeService.resolveForRequest({ auth: scopeAuth, request })\n // The caller explicitly selected an organization that no longer resolves to a\n // real, accessible org (stale selected-org cookie after a delete or an access\n // loss). The scope resolver falls back to another allowed org, so continuing\n // would silently read and write against an organization the caller never\n // chose. Fail loud on every documents operation instead \u2014 the same contract\n // `makeCrudRoute` enforces via `rejectInvalidOrgSelection` (#3936).\n if (scope?.selectionRejected) {\n throw new CrudHttpError(422, {\n error: 'documents.errors.organizationSelectionInvalid',\n code: ORGANIZATION_SELECTION_INVALID_ERROR_CODE,\n })\n }\n const tenantId = scope?.tenantId ?? auth.tenantId\n const organizationId = resolveSelectedOrganization(scopeAuth, scope)\n if (!tenantId) {\n throw new CrudHttpError(400, { error: 'documents.errors.organizationRequired' })\n }\n if (!organizationId) {\n // An unrestricted caller with no resolvable organization (a super-admin\n // viewing a foreign tenant with \"all organizations\" selected) is a 400, not\n // a 401 (which `apiFetch` would turn into a refresh loop) and not a 403 (the\n // caller is allowed in; they only need to pick an organization). A caller\n // whose grants expand to no organization at all stays a 403.\n const unrestricted = (scope?.filterIds ?? scope?.allowedIds ?? null) === null\n if (unrestricted) {\n throw new CrudHttpError(400, {\n error: 'documents.errors.organizationRequired',\n code: ORGANIZATION_SCOPE_REQUIRED_ERROR_CODE,\n })\n }\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n\n const acl = await rbacService.loadAcl(auth.sub, { tenantId, organizationId })\n if (!hasResolvedDocumentsOrganizationAccess(acl, organizationId, scope)) {\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n const roleIds = await resolveActiveSubjectRoleIds(\n container,\n { tenantId, organizationId },\n auth.sub,\n )\n const documentsAuth: DocumentsAuthContext = {\n ...scopeAuth,\n tenantId,\n orgId: organizationId,\n organizationId,\n roleIds,\n resolvedRoleIds: roleIds,\n // JWT/trusted-request claims are only authentication hints. The current\n // RBAC projection is authoritative for features and superadmin status so\n // a revoked grant cannot survive in a long-lived token.\n features: acl.isSuperAdmin === true ? ['*'] : normalizeStrings(acl.features),\n isSuperAdmin: acl.isSuperAdmin === true,\n }\n\n if (!hasAnyDocumentsFeature(documentsAuth, requiredFeatures)) {\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n\n return {\n container,\n em,\n auth: documentsAuth,\n tenantId,\n organizationId,\n request,\n }\n}\n\nexport async function readBody(\n request: Request,\n maxBytes = DOCUMENTS_JSON_BODY_LIMITS.standard,\n): Promise<Record<string, unknown>> {\n return (await readBoundedJsonBody<Record<string, unknown>>(request, maxBytes, {})) ?? {}\n}\n\nasync function localizeRouteErrorBody(body: Record<string, unknown>): Promise<Record<string, unknown>> {\n const rawError = typeof body.error === 'string' ? body.error : null\n if (!rawError) return body\n\n if (containsCanonicalUuid(rawError)) {\n const { key, fallback } = ROUTE_ERROR_TRANSLATIONS['Internal server error']!\n try {\n const { translate } = await resolveTranslations()\n return { ...body, error: translate(key, fallback) }\n } catch {\n return { ...body, error: fallback }\n }\n }\n\n const literal = ROUTE_ERROR_TRANSLATIONS[rawError]\n const key = literal?.key ?? rawError\n const fallback = literal?.fallback ?? ROUTE_ERROR_KEY_FALLBACKS[key]\n // Attachment failures reach these routes as the attachments module's own\n // catalogued keys. The locale dictionary is merged across modules, so they\n // resolve here; without this prefix the raw key would reach the client.\n if (\n !key.startsWith('documents.')\n && !key.startsWith('api.')\n && !key.startsWith('attachments.')\n ) return body\n\n try {\n const { translate } = await resolveTranslations()\n return { ...body, error: translate(key, fallback) }\n } catch {\n return { ...body, error: fallback ?? key }\n }\n}\n\nexport async function handleDocumentsRouteError(error: unknown, label: string): Promise<Response> {\n if (isCrudHttpError(error)) {\n const body = error.body && typeof error.body === 'object' && !Array.isArray(error.body)\n ? error.body as Record<string, unknown>\n : { error: 'api.errors.internal' }\n return NextResponse.json(await localizeRouteErrorBody(body), { status: error.status })\n }\n const interceptorRejection = getCommandInterceptorHttpRejection(error)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n if (error instanceof z.ZodError) {\n return NextResponse.json(\n await localizeRouteErrorBody({ error: 'api.errors.invalidPayload', details: error.issues }),\n { status: 400 },\n )\n }\n logger.error(`${label} failed`, { err: error })\n return NextResponse.json(\n await localizeRouteErrorBody({ error: 'api.errors.internal' }),\n { status: 500 },\n )\n}\n\nconst documentIdSchema = z.string().uuid()\n\nexport function assertDocumentId(id: string): void {\n if (!documentIdSchema.safeParse(id).success) {\n throw new CrudHttpError(404, { error: 'documents.documents.notFound' })\n }\n}\n\nexport async function loadScopedDocument(ctx: DocumentsRouteContext, id: string): Promise<Document> {\n const document = await findOneWithDecryption(ctx.em, Document, {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: null,\n }, undefined, { tenantId: ctx.tenantId, organizationId: ctx.organizationId })\n if (!document) throw new CrudHttpError(404, { error: 'documents.documents.notFound' })\n return document\n}\n\n/**\n * Only the owner (or a documents manager) may learn that a document was\n * removed, e.g. after undoing its creation; everyone else keeps the\n * existence-hiding 403 so deleted ids stay indistinguishable from foreign ones.\n */\nexport async function isRemovedDocumentVisibleToActor(ctx: DocumentsRouteContext, id: string): Promise<boolean> {\n const document = await findOneWithDecryption(ctx.em, Document, {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: { $ne: null },\n }, { fields: ['id', 'ownerUserId'] }, { tenantId: ctx.tenantId, organizationId: ctx.organizationId })\n if (!document) return false\n if (hasDocumentsFeature(ctx.auth, 'documents.manage')) return true\n return document.ownerUserId === resolveActorUserId(ctx.auth)\n}\n\nexport async function loadScopedShare(\n ctx: DocumentsRouteContext,\n documentId: string,\n shareId: string,\n): Promise<DocumentShare> {\n const share = await findOneWithDecryption(ctx.em, DocumentShare, {\n id: shareId,\n documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: null,\n }, undefined, { tenantId: ctx.tenantId, organizationId: ctx.organizationId })\n if (!share) throw new CrudHttpError(404, { error: 'documents.share.notFound' })\n return share\n}\n\nexport function serializeDocument(document: Document): Record<string, unknown> {\n return {\n id: document.id,\n title: document.title,\n folderId: document.folderId ?? null,\n ownerUserId: document.ownerUserId,\n createdByUserId: document.createdByUserId,\n isActive: document.isActive,\n createdAt: document.createdAt.toISOString(),\n updatedAt: document.updatedAt.toISOString(),\n }\n}\n\nexport function serializeContent(content: DocumentContent | null): Record<string, unknown> {\n return {\n contentHtml: content?.contentHtml ?? '',\n contentText: content?.contentText ?? '',\n updatedAt: content?.updatedAt ? content.updatedAt.toISOString() : null,\n }\n}\n\nexport function serializeFolder(folder: DocumentFolder): Record<string, unknown> {\n return {\n id: folder.id,\n name: folder.name,\n parentFolderId: folder.parentFolderId ?? null,\n ownerUserId: folder.ownerUserId,\n createdAt: folder.createdAt.toISOString(),\n updatedAt: folder.updatedAt.toISOString(),\n }\n}\n\nexport function serializeShare(share: DocumentShare): Record<string, unknown> {\n return {\n id: share.id,\n documentId: share.documentId,\n principalType: share.principalType,\n principalId: share.principalId,\n permission: share.permission,\n createdByUserId: share.createdByUserId,\n createdAt: share.createdAt.toISOString(),\n updatedAt: share.updatedAt.toISOString(),\n }\n}\n\nexport async function validateMutationGuard(\n ctx: DocumentsRouteContext,\n input: {\n resourceKind: string\n resourceId: string\n operation: 'create' | 'update' | 'delete' | 'custom'\n mutationPayload?: Record<string, unknown> | null\n /**\n * Re-parses a guard's `modifiedPayload` before it reaches the command. A\n * registry guard may rewrite the payload, and the route's own schema is the\n * only thing that still guarantees the command receives a shape it can trust.\n */\n mutationPayloadSchema?: { parse: (value: unknown) => Record<string, unknown> }\n },\n): Promise<MutationGuardResult> {\n // `runRouteMutationGuards` runs EVERY registered guard plus the bridged legacy\n // DI service. The deprecated `validateCrudMutationGuard` /\n // `runCrudMutationGuardAfterSuccess` pair used here before resolved only the\n // single DI-registered guard service, so every guard a module contributed\n // through the registry \u2014 along with its payload transformation and its\n // after-success callback \u2014 was silently skipped on Documents writes.\n const guardResult = await runRouteMutationGuards({\n container: ctx.container,\n req: ctx.request,\n auth: {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: resolveActorUserId(ctx.auth),\n userFeatures: ctx.auth.features,\n },\n input: {\n resourceKind: input.resourceKind,\n resourceId: input.resourceId,\n operation: input.operation,\n mutationPayload: input.mutationPayload ?? null,\n },\n })\n if (!guardResult.ok) {\n throw new CrudHttpError(guardResult.errorStatus, guardResult.errorBody)\n }\n if (guardResult.modifiedPayload && input.mutationPayload) {\n const transformed = input.mutationPayloadSchema\n ? input.mutationPayloadSchema.parse(guardResult.modifiedPayload)\n : guardResult.modifiedPayload\n // Routes read the object they handed in, so the transformation has to land\n // there rather than only on the guard result.\n for (const key of Object.keys(input.mutationPayload)) delete input.mutationPayload[key]\n Object.assign(input.mutationPayload, transformed)\n }\n return guardResult\n}\n\nexport async function runMutationGuardAfterSuccess(\n _ctx: DocumentsRouteContext,\n guardResult: MutationGuardResult,\n _input: {\n resourceKind: string\n resourceId: string\n operation: 'create' | 'update' | 'delete' | 'custom'\n },\n): Promise<void> {\n await guardResult.runAfterSuccess()\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,0BAA0B;AACnC,SAAS,sBAAAA,2BAA0B;AACnC,SAAS,oBAAoB;AAG7B,SAAS,SAAS;AAClB,SAAS,0BAA4C;AACrD,SAAS,8BAA8B;AACvC,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe,uBAAuB;AAC/C,SAAS,0CAA0C;AACnD;AAAA,EACE;AAAA,OAEK;AACP,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAE7B;AAAA,EACE;AAAA,EAGA;AAAA,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QAKe;AACf,QAAM,YAAY,gBAAgB;AACpC;",
|
|
6
|
+
"names": ["resolveActorUserId", "errors", "key", "fallback"]
|
|
7
7
|
}
|
|
@@ -14,6 +14,7 @@ import { OutlinePane } from "./OutlinePane.js";
|
|
|
14
14
|
import { captureCommentAnchor } from "./CommentAnchorNavigation.js";
|
|
15
15
|
import { DOCUMENT_EDITOR_CONTENT_CLASS } from "./editorTypes.js";
|
|
16
16
|
import { DOCUMENT_PAGINATION_STYLES } from "./documentPagination.js";
|
|
17
|
+
import { useContentSecurityPolicyNonce } from "@open-mercato/ui/theme/ContentSecurityPolicyProvider";
|
|
17
18
|
const EMPTY_BUBBLE_MENU_STATE = {
|
|
18
19
|
bold: false,
|
|
19
20
|
italic: false,
|
|
@@ -30,6 +31,7 @@ function DocumentCanvas({
|
|
|
30
31
|
onComment
|
|
31
32
|
}) {
|
|
32
33
|
const t = useT();
|
|
34
|
+
const nonce = useContentSecurityPolicyNonce();
|
|
33
35
|
const editorState = useEditorState({
|
|
34
36
|
editor,
|
|
35
37
|
selector: ({ editor: current }) => current ? {
|
|
@@ -50,7 +52,7 @@ function DocumentCanvas({
|
|
|
50
52
|
[onComment, readOnly]
|
|
51
53
|
);
|
|
52
54
|
return /* @__PURE__ */ jsxs("div", { className: "om-doc-canvas max-h-[calc(100dvh-var(--topbar-height,0px)-12rem)] min-h-96 overflow-auto bg-muted p-0 sm:px-4 sm:py-8 md:px-8 md:py-10", children: [
|
|
53
|
-
/* @__PURE__ */ jsx("style", { children: DOCUMENT_PAGINATION_STYLES }),
|
|
55
|
+
/* @__PURE__ */ jsx("style", { nonce, children: DOCUMENT_PAGINATION_STYLES }),
|
|
54
56
|
notice ? /* @__PURE__ */ jsx(Alert, { status: "information", style: "lighter", className: "mx-auto mb-4 max-w-3xl", children: /* @__PURE__ */ jsx(AlertDescription, { children: notice }) }) : null,
|
|
55
57
|
/* @__PURE__ */ jsxs("div", { className: "mx-auto flex w-fit min-w-full flex-col gap-4 lg:flex-row lg:items-start", children: [
|
|
56
58
|
outlineOpen ? /* @__PURE__ */ jsx(OutlinePane, { editor }) : null,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/documents/backend/documents/%5Bid%5D/DocumentCanvas.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport type { Editor } from '@tiptap/core'\nimport { EditorContent, useEditorState } from '@tiptap/react'\nimport { BubbleMenu } from '@tiptap/react/menus'\nimport { Bold, Italic, Link2, MessageSquare, Underline } from 'lucide-react'\nimport { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { OutlinePane } from './OutlinePane'\nimport { captureCommentAnchor, type CommentAnchor } from './CommentAnchorNavigation'\nimport { DOCUMENT_EDITOR_CONTENT_CLASS } from './editorTypes'\nimport { DOCUMENT_PAGINATION_STYLES } from './documentPagination'\n\ntype TitleModel = {\n value: string\n setValue: (value: string) => void\n saving: boolean\n commit: () => Promise<void>\n onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void\n}\n\nconst EMPTY_BUBBLE_MENU_STATE = {\n bold: false,\n italic: false,\n underline: false,\n link: false,\n}\n\nexport function DocumentCanvas({\n editor,\n title,\n readOnly,\n outlineOpen,\n notice,\n onOpenLink,\n onComment,\n}: {\n editor: Editor | null\n title: TitleModel\n readOnly: boolean\n outlineOpen: boolean\n notice: string | null\n onOpenLink: () => void\n onComment?: (anchor: CommentAnchor) => void\n}) {\n const t = useT()\n const editorState = useEditorState({\n editor,\n selector: ({ editor: current }) => current ? {\n bold: current.isActive('bold'),\n italic: current.isActive('italic'),\n underline: current.isActive('underline'),\n link: current.isActive('link'),\n } : EMPTY_BUBBLE_MENU_STATE,\n }) ?? EMPTY_BUBBLE_MENU_STATE\n const keepSelection = React.useCallback((event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault(), [])\n const comment = React.useCallback(() => {\n if (!editor || !onComment) return\n const anchor = captureCommentAnchor(editor)\n if (anchor) onComment(anchor)\n }, [editor, onComment])\n const shouldShow = React.useCallback(\n ({ from, to }: { from: number; to: number }) => from !== to && (!readOnly || Boolean(onComment)),\n [onComment, readOnly],\n )\n\n return (\n <div className=\"om-doc-canvas max-h-[calc(100dvh-var(--topbar-height,0px)-12rem)] min-h-96 overflow-auto bg-muted p-0 sm:px-4 sm:py-8 md:px-8 md:py-10\">\n <style>{DOCUMENT_PAGINATION_STYLES}</style>\n {notice ? <Alert status=\"information\" style=\"lighter\" className=\"mx-auto mb-4 max-w-3xl\"><AlertDescription>{notice}</AlertDescription></Alert> : null}\n <div className=\"mx-auto flex w-fit min-w-full flex-col gap-4 lg:flex-row lg:items-start\">\n {outlineOpen ? <OutlinePane editor={editor} /> : null}\n <article className=\"om-doc-paper mx-auto flex-none bg-card sm:rounded-sm sm:shadow-lg\">\n {readOnly ? (\n <h1 className=\"mb-6 text-xl font-semibold leading-tight text-foreground sm:mb-8 sm:text-3xl\">{title.value}</h1>\n ) : (\n <Input\n value={title.value}\n onChange={(event) => title.setValue(event.target.value)}\n onBlur={() => void title.commit()}\n onKeyDown={title.onKeyDown}\n maxLength={512}\n disabled={title.saving}\n aria-label={t('documents.editor.title.ariaLabel')}\n className=\"mb-6 h-auto border-0 bg-transparent px-0 py-0 text-xl font-semibold leading-tight text-foreground shadow-none focus-visible:shadow-focus sm:mb-8 sm:text-3xl\"\n />\n )}\n {editor ? (\n <BubbleMenu editor={editor} shouldShow={shouldShow} className=\"z-popover flex items-center gap-1 rounded-md border border-border bg-card p-1 shadow-md\">\n {!readOnly ? (\n <>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.bold ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.bold')} aria-pressed={editorState.bold} onMouseDown={keepSelection} onClick={() => editor.chain().focus().toggleBold().run()}><Bold /></IconButton>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.italic ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.italic')} aria-pressed={editorState.italic} onMouseDown={keepSelection} onClick={() => editor.chain().focus().toggleItalic().run()}><Italic /></IconButton>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.underline ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.underline')} aria-pressed={editorState.underline} onMouseDown={keepSelection} onClick={() => editor.chain().focus().toggleMark('underline').run()}><Underline /></IconButton>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.link ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.link')} aria-pressed={editorState.link} onMouseDown={keepSelection} onClick={onOpenLink}><Link2 /></IconButton>\n </>\n ) : null}\n {onComment ? <Button type=\"button\" size=\"sm\" variant=\"ghost\" onMouseDown={keepSelection} onClick={comment}><MessageSquare />{t('documents.editor.toolbar.comment')}</Button> : null}\n </BubbleMenu>\n ) : null}\n <EditorContent className={cn(DOCUMENT_EDITOR_CONTENT_CLASS, readOnly && 'select-text')} editor={editor} />\n </article>\n </div>\n </div>\n )\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport type { Editor } from '@tiptap/core'\nimport { EditorContent, useEditorState } from '@tiptap/react'\nimport { BubbleMenu } from '@tiptap/react/menus'\nimport { Bold, Italic, Link2, MessageSquare, Underline } from 'lucide-react'\nimport { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { OutlinePane } from './OutlinePane'\nimport { captureCommentAnchor, type CommentAnchor } from './CommentAnchorNavigation'\nimport { DOCUMENT_EDITOR_CONTENT_CLASS } from './editorTypes'\nimport { DOCUMENT_PAGINATION_STYLES } from './documentPagination'\nimport { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'\n\ntype TitleModel = {\n value: string\n setValue: (value: string) => void\n saving: boolean\n commit: () => Promise<void>\n onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void\n}\n\nconst EMPTY_BUBBLE_MENU_STATE = {\n bold: false,\n italic: false,\n underline: false,\n link: false,\n}\n\nexport function DocumentCanvas({\n editor,\n title,\n readOnly,\n outlineOpen,\n notice,\n onOpenLink,\n onComment,\n}: {\n editor: Editor | null\n title: TitleModel\n readOnly: boolean\n outlineOpen: boolean\n notice: string | null\n onOpenLink: () => void\n onComment?: (anchor: CommentAnchor) => void\n}) {\n const t = useT()\n const nonce = useContentSecurityPolicyNonce()\n const editorState = useEditorState({\n editor,\n selector: ({ editor: current }) => current ? {\n bold: current.isActive('bold'),\n italic: current.isActive('italic'),\n underline: current.isActive('underline'),\n link: current.isActive('link'),\n } : EMPTY_BUBBLE_MENU_STATE,\n }) ?? EMPTY_BUBBLE_MENU_STATE\n const keepSelection = React.useCallback((event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault(), [])\n const comment = React.useCallback(() => {\n if (!editor || !onComment) return\n const anchor = captureCommentAnchor(editor)\n if (anchor) onComment(anchor)\n }, [editor, onComment])\n const shouldShow = React.useCallback(\n ({ from, to }: { from: number; to: number }) => from !== to && (!readOnly || Boolean(onComment)),\n [onComment, readOnly],\n )\n\n return (\n <div className=\"om-doc-canvas max-h-[calc(100dvh-var(--topbar-height,0px)-12rem)] min-h-96 overflow-auto bg-muted p-0 sm:px-4 sm:py-8 md:px-8 md:py-10\">\n <style nonce={nonce}>{DOCUMENT_PAGINATION_STYLES}</style>\n {notice ? <Alert status=\"information\" style=\"lighter\" className=\"mx-auto mb-4 max-w-3xl\"><AlertDescription>{notice}</AlertDescription></Alert> : null}\n <div className=\"mx-auto flex w-fit min-w-full flex-col gap-4 lg:flex-row lg:items-start\">\n {outlineOpen ? <OutlinePane editor={editor} /> : null}\n <article className=\"om-doc-paper mx-auto flex-none bg-card sm:rounded-sm sm:shadow-lg\">\n {readOnly ? (\n <h1 className=\"mb-6 text-xl font-semibold leading-tight text-foreground sm:mb-8 sm:text-3xl\">{title.value}</h1>\n ) : (\n <Input\n value={title.value}\n onChange={(event) => title.setValue(event.target.value)}\n onBlur={() => void title.commit()}\n onKeyDown={title.onKeyDown}\n maxLength={512}\n disabled={title.saving}\n aria-label={t('documents.editor.title.ariaLabel')}\n className=\"mb-6 h-auto border-0 bg-transparent px-0 py-0 text-xl font-semibold leading-tight text-foreground shadow-none focus-visible:shadow-focus sm:mb-8 sm:text-3xl\"\n />\n )}\n {editor ? (\n <BubbleMenu editor={editor} shouldShow={shouldShow} className=\"z-popover flex items-center gap-1 rounded-md border border-border bg-card p-1 shadow-md\">\n {!readOnly ? (\n <>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.bold ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.bold')} aria-pressed={editorState.bold} onMouseDown={keepSelection} onClick={() => editor.chain().focus().toggleBold().run()}><Bold /></IconButton>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.italic ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.italic')} aria-pressed={editorState.italic} onMouseDown={keepSelection} onClick={() => editor.chain().focus().toggleItalic().run()}><Italic /></IconButton>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.underline ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.underline')} aria-pressed={editorState.underline} onMouseDown={keepSelection} onClick={() => editor.chain().focus().toggleMark('underline').run()}><Underline /></IconButton>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.link ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.link')} aria-pressed={editorState.link} onMouseDown={keepSelection} onClick={onOpenLink}><Link2 /></IconButton>\n </>\n ) : null}\n {onComment ? <Button type=\"button\" size=\"sm\" variant=\"ghost\" onMouseDown={keepSelection} onClick={comment}><MessageSquare />{t('documents.editor.toolbar.comment')}</Button> : null}\n </BubbleMenu>\n ) : null}\n <EditorContent className={cn(DOCUMENT_EDITOR_CONTENT_CLASS, readOnly && 'select-text')} editor={editor} />\n </article>\n </div>\n </div>\n )\n}\n"],
|
|
5
|
+
"mappings": ";AA2EM,SAsBU,UAtBV,KAsBU,YAtBV;AAzEN,YAAY,WAAW;AAEvB,SAAS,eAAe,sBAAsB;AAC9C,SAAS,kBAAkB;AAC3B,SAAS,MAAM,QAAQ,OAAO,eAAe,iBAAiB;AAC9D,SAAS,OAAO,wBAAwB;AACxC,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB,SAAS,UAAU;AACnB,SAAS,mBAAmB;AAC5B,SAAS,4BAAgD;AACzD,SAAS,qCAAqC;AAC9C,SAAS,kCAAkC;AAC3C,SAAS,qCAAqC;AAU9C,MAAM,0BAA0B;AAAA,EAC9B,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,MAAM;AACR;AAEO,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAQG;AACD,QAAM,IAAI,KAAK;AACf,QAAM,QAAQ,8BAA8B;AAC5C,QAAM,cAAc,eAAe;AAAA,IACjC;AAAA,IACA,UAAU,CAAC,EAAE,QAAQ,QAAQ,MAAM,UAAU;AAAA,MAC3C,MAAM,QAAQ,SAAS,MAAM;AAAA,MAC7B,QAAQ,QAAQ,SAAS,QAAQ;AAAA,MACjC,WAAW,QAAQ,SAAS,WAAW;AAAA,MACvC,MAAM,QAAQ,SAAS,MAAM;AAAA,IAC/B,IAAI;AAAA,EACN,CAAC,KAAK;AACN,QAAM,gBAAgB,MAAM,YAAY,CA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O,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,GAAG,8BAAC,QAAK,GAAE;AAAA,YACnQ,oBAAC,cAAW,MAAK,UAAS,MAAK,MAAK,SAAS,YAAY,SAAS,YAAY,SAAS,cAAY,EAAE,iCAAiC,GAAG,gBAAc,YAAY,QAAQ,aAAa,eAAe,SAAS,MAAM,OAAO,MAAM,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAG,8BAAC,UAAO,GAAE;AAAA,YAC7Q,oBAAC,cAAW,MAAK,UAAS,MAAK,MAAK,SAAS,YAAY,YAAY,YAAY,SAAS,cAAY,EAAE,oCAAoC,GAAG,gBAAc,YAAY,WAAW,aAAa,eAAe,SAAS,MAAM,OAAO,MAAM,EAAE,MAAM,EAAE,WAAW,WAAW,EAAE,IAAI,GAAG,8BAAC,aAAU,GAAE;AAAA,YAClS,oBAAC,cAAW,MAAK,UAAS,MAAK,MAAK,SAAS,YAAY,OAAO,YAAY,SAAS,cAAY,EAAE,+BAA+B,GAAG,gBAAc,YAAY,MAAM,aAAa,eAAe,SAAS,YAAY,8BAAC,SAAM,GAAE;AAAA,aACjO,IACE;AAAA,UACH,YAAY,qBAAC,UAAO,MAAK,UAAS,MAAK,MAAK,SAAQ,SAAQ,aAAa,eAAe,SAAS,SAAS;AAAA,gCAAC,iBAAc;AAAA,YAAG,EAAE,kCAAkC;AAAA,aAAE,IAAY;AAAA,WACjL,IACE;AAAA,QACJ,oBAAC,iBAAc,WAAW,GAAG,+BAA+B,YAAY,aAAa,GAAG,QAAgB;AAAA,SAC1G;AAAA,OACF;AAAA,KACF;AAEJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -25,7 +25,7 @@ function DocumentEditorIsland(props) {
|
|
|
25
25
|
const query = next.toString();
|
|
26
26
|
router.replace(query ? `?${query}` : "?", { scroll: false });
|
|
27
27
|
}, [forcedReadOnly, router, searchParams]);
|
|
28
|
-
if (collaboration.mode === "connecting") return /* @__PURE__ */ jsx(LoadingMessage, { label: t("documents.editor.loading") });
|
|
28
|
+
if (collaboration.mode === "connecting" || collaboration.mode === "collab" && collaboration.connectionStatus === "connecting") return /* @__PURE__ */ jsx(LoadingMessage, { label: t("documents.editor.loading") });
|
|
29
29
|
if (collaboration.mode === "fallback") {
|
|
30
30
|
return /* @__PURE__ */ createElement(DocumentEditorSurface, { ...props, readOnly: forcedReadOnly, key: `fallback:${props.documentId}`, transport: "fallback", connectionStatus: "offline", presenceUsers: [], mode, onModeChange: changeMode });
|
|
31
31
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/documents/backend/documents/%5Bid%5D/DocumentEditorIsland.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useRouter, useSearchParams } from 'next/navigation'\nimport { LoadingMessage } from '@open-mercato/ui/backend/detail'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { DocumentEditorSurface } from './DocumentEditorSurface'\nimport { resolveEditorMode, type DocumentEditorIslandProps, type EditorMode } from './editorTypes'\nimport { useDocumentCollaboration } from './useDocumentCollaboration'\n\nexport default function DocumentEditorIsland(props: DocumentEditorIslandProps) {\n const t = useT()\n const router = useRouter()\n const searchParams = useSearchParams()\n const collaboration = useDocumentCollaboration(props.documentId)\n const requestedMode: EditorMode = searchParams.get('mode') === 'preview' ? 'preview' : 'edit'\n const serverReadOnly = collaboration.mode === 'collab'\n ? collaboration.serverReadOnly\n : collaboration.mode === 'fallback'\n ? collaboration.readOnly\n : false\n const forcedReadOnly = props.readOnly || serverReadOnly\n const mode = resolveEditorMode(props.readOnly, serverReadOnly, requestedMode)\n const changeMode = React.useCallback((nextMode: EditorMode) => {\n if (forcedReadOnly) return\n const next = new URLSearchParams(searchParams.toString())\n if (nextMode === 'preview') next.set('mode', 'preview')\n else next.delete('mode')\n const query = next.toString()\n router.replace(query ? `?${query}` : '?', { scroll: false })\n }, [forcedReadOnly, router, searchParams])\n\n if (collaboration.mode === 'connecting') return <LoadingMessage label={t('documents.editor.loading')} />\n if (collaboration.mode === 'fallback') {\n return <DocumentEditorSurface {...props} readOnly={forcedReadOnly} key={`fallback:${props.documentId}`} transport=\"fallback\" connectionStatus=\"offline\" presenceUsers={[]} mode={mode} onModeChange={changeMode} />\n }\n return (\n <DocumentEditorSurface\n {...props}\n readOnly={forcedReadOnly}\n key={`collab:${props.documentId}`}\n transport=\"collab\"\n collabResources={collaboration.resources}\n connectionStatus={collaboration.connectionStatus}\n presenceUsers={collaboration.presenceUsers}\n mode={mode}\n onModeChange={changeMode}\n />\n )\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useRouter, useSearchParams } from 'next/navigation'\nimport { LoadingMessage } from '@open-mercato/ui/backend/detail'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { DocumentEditorSurface } from './DocumentEditorSurface'\nimport { resolveEditorMode, type DocumentEditorIslandProps, type EditorMode } from './editorTypes'\nimport { useDocumentCollaboration } from './useDocumentCollaboration'\n\nexport default function DocumentEditorIsland(props: DocumentEditorIslandProps) {\n const t = useT()\n const router = useRouter()\n const searchParams = useSearchParams()\n const collaboration = useDocumentCollaboration(props.documentId)\n const requestedMode: EditorMode = searchParams.get('mode') === 'preview' ? 'preview' : 'edit'\n const serverReadOnly = collaboration.mode === 'collab'\n ? collaboration.serverReadOnly\n : collaboration.mode === 'fallback'\n ? collaboration.readOnly\n : false\n const forcedReadOnly = props.readOnly || serverReadOnly\n const mode = resolveEditorMode(props.readOnly, serverReadOnly, requestedMode)\n const changeMode = React.useCallback((nextMode: EditorMode) => {\n if (forcedReadOnly) return\n const next = new URLSearchParams(searchParams.toString())\n if (nextMode === 'preview') next.set('mode', 'preview')\n else next.delete('mode')\n const query = next.toString()\n router.replace(query ? `?${query}` : '?', { scroll: false })\n }, [forcedReadOnly, router, searchParams])\n\n if (\n collaboration.mode === 'connecting'\n || (collaboration.mode === 'collab' && collaboration.connectionStatus === 'connecting')\n ) return <LoadingMessage label={t('documents.editor.loading')} />\n if (collaboration.mode === 'fallback') {\n return <DocumentEditorSurface {...props} readOnly={forcedReadOnly} key={`fallback:${props.documentId}`} transport=\"fallback\" connectionStatus=\"offline\" presenceUsers={[]} mode={mode} onModeChange={changeMode} />\n }\n return (\n <DocumentEditorSurface\n {...props}\n readOnly={forcedReadOnly}\n key={`collab:${props.documentId}`}\n transport=\"collab\"\n collabResources={collaboration.resources}\n connectionStatus={collaboration.connectionStatus}\n presenceUsers={collaboration.presenceUsers}\n mode={mode}\n onModeChange={changeMode}\n />\n )\n}\n"],
|
|
5
|
+
"mappings": ";AAmCW;AAEA;AAnCX,YAAY,WAAW;AACvB,SAAS,WAAW,uBAAuB;AAC3C,SAAS,sBAAsB;AAC/B,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC,SAAS,yBAA0E;AACnF,SAAS,gCAAgC;AAE1B,SAAR,qBAAsC,OAAkC;AAC7E,QAAM,IAAI,KAAK;AACf,QAAM,SAAS,UAAU;AACzB,QAAM,eAAe,gBAAgB;AACrC,QAAM,gBAAgB,yBAAyB,MAAM,UAAU;AAC/D,QAAM,gBAA4B,aAAa,IAAI,MAAM,MAAM,YAAY,YAAY;AACvF,QAAM,iBAAiB,cAAc,SAAS,WAC1C,cAAc,iBACd,cAAc,SAAS,aACrB,cAAc,WACd;AACN,QAAM,iBAAiB,MAAM,YAAY;AACzC,QAAM,OAAO,kBAAkB,MAAM,UAAU,gBAAgB,aAAa;AAC5E,QAAM,aAAa,MAAM,YAAY,CAAC,aAAyB;AAC7D,QAAI,eAAgB;AACpB,UAAM,OAAO,IAAI,gBAAgB,aAAa,SAAS,CAAC;AACxD,QAAI,aAAa,UAAW,MAAK,IAAI,QAAQ,SAAS;AAAA,QACjD,MAAK,OAAO,MAAM;AACvB,UAAM,QAAQ,KAAK,SAAS;AAC5B,WAAO,QAAQ,QAAQ,IAAI,KAAK,KAAK,KAAK,EAAE,QAAQ,MAAM,CAAC;AAAA,EAC7D,GAAG,CAAC,gBAAgB,QAAQ,YAAY,CAAC;AAEzC,MACE,cAAc,SAAS,gBACnB,cAAc,SAAS,YAAY,cAAc,qBAAqB,aAC1E,QAAO,oBAAC,kBAAe,OAAO,EAAE,0BAA0B,GAAG;AAC/D,MAAI,cAAc,SAAS,YAAY;AACrC,WAAO,8BAAC,yBAAuB,GAAG,OAAO,UAAU,gBAAgB,KAAK,YAAY,MAAM,UAAU,IAAI,WAAU,YAAW,kBAAiB,WAAU,eAAe,CAAC,GAAG,MAAY,cAAc,YAAY;AAAA,EACnN;AACA,SACE;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,UAAU;AAAA,MACV,KAAK,UAAU,MAAM,UAAU;AAAA,MAC/B,WAAU;AAAA,MACV,iBAAiB,cAAc;AAAA,MAC/B,kBAAkB,cAAc;AAAA,MAChC,eAAe,cAAc;AAAA,MAC7B;AAAA,MACA,cAAc;AAAA;AAAA,EAChB;AAEJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
3
3
|
import * as React from "react";
|
|
4
|
+
import { useContentSecurityPolicyNonce } from "@open-mercato/ui/theme/ContentSecurityPolicyProvider";
|
|
4
5
|
import { Link2, Unlink } from "lucide-react";
|
|
5
6
|
import { Button } from "@open-mercato/ui/primitives/button";
|
|
6
7
|
import { Input } from "@open-mercato/ui/primitives/input";
|
|
@@ -18,8 +19,10 @@ import { useDocumentEditor } from "./useDocumentEditor.js";
|
|
|
18
19
|
import { useFallbackContentPersistence } from "./useFallbackContentPersistence.js";
|
|
19
20
|
import { useDocumentTitle } from "./useDocumentTitle.js";
|
|
20
21
|
import { useEditorInsertions } from "./useEditorInsertions.js";
|
|
22
|
+
import { saveCollaborativeContent } from "./saveCollaborativeContent.js";
|
|
21
23
|
function DocumentEditorSurface(input) {
|
|
22
24
|
const t = useT();
|
|
25
|
+
const nonce = useContentSecurityPolicyNonce();
|
|
23
26
|
const [outlineOpen, setOutlineOpen] = React.useState(false);
|
|
24
27
|
const [suggestionRange, setSuggestionRange] = React.useState(null);
|
|
25
28
|
const modeChangeInFlightRef = React.useRef(false);
|
|
@@ -50,6 +53,17 @@ function DocumentEditorSurface(input) {
|
|
|
50
53
|
readOnly: effectiveReadOnly,
|
|
51
54
|
onTitleChange: input.onTitleChange
|
|
52
55
|
});
|
|
56
|
+
React.useEffect(() => {
|
|
57
|
+
const controller = new AbortController();
|
|
58
|
+
input.onSaveReady?.(async () => {
|
|
59
|
+
if (controller.signal.aborted || input.readOnly || !editorModel.editorRef.current) return false;
|
|
60
|
+
return input.transport === "fallback" ? fallbackPersistence.saveNow() : input.collabResources ? saveCollaborativeContent(input.collabResources, controller.signal) : false;
|
|
61
|
+
});
|
|
62
|
+
return () => {
|
|
63
|
+
controller.abort();
|
|
64
|
+
input.onSaveReady?.(null);
|
|
65
|
+
};
|
|
66
|
+
}, [editorModel.editorRef, fallbackPersistence.saveNow, input.collabResources, input.onSaveReady, input.readOnly, input.transport]);
|
|
53
67
|
const insertions = useEditorInsertions({
|
|
54
68
|
documentId: input.documentId,
|
|
55
69
|
editorRef: editorModel.editorRef,
|
|
@@ -82,7 +96,7 @@ function DocumentEditorSurface(input) {
|
|
|
82
96
|
}
|
|
83
97
|
}, [fallbackPersistence.saveNow, input.mode, input.onModeChange, input.transport]);
|
|
84
98
|
return /* @__PURE__ */ jsxs("div", { className: cn("space-y-3", input.transport === "collab" && "om-doc-collab", input.mode === "preview" && "om-doc-preview"), children: [
|
|
85
|
-
/* @__PURE__ */ jsx("style", { children: EDITOR_PRESENCE_STYLES }),
|
|
99
|
+
/* @__PURE__ */ jsx("style", { nonce, children: EDITOR_PRESENCE_STYLES }),
|
|
86
100
|
/* @__PURE__ */ jsxs("div", { className: "overflow-hidden rounded-lg border border-border bg-muted shadow-sm", children: [
|
|
87
101
|
/* @__PURE__ */ jsxs("div", { className: "sticky top-0 z-sticky border-b border-border bg-card/95", children: [
|
|
88
102
|
/* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center justify-between gap-2 px-3 py-2", children: /* @__PURE__ */ jsx(
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/documents/backend/documents/%5Bid%5D/DocumentEditorSurface.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { Link2, Unlink } from 'lucide-react'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { EntityPicker } from '../components/EntityPicker'\nimport { DocumentCanvas } from './DocumentCanvas'\nimport { EditorStatusPresence } from './EditorStatusPresence'\nimport { EditorToolbar } from './EditorToolbar'\nimport { RecordFieldsDialog } from './RecordFieldsDialog'\nimport { EDITOR_PRESENCE_STYLES } from './editorPresenceStyles'\nimport { canCreateSelectionComment, type CollabResources, type ConnectionStatus, type DocumentEditorIslandProps, type EditorMode, type PresenceUser } from './editorTypes'\nimport { useDocumentEditor } from './useDocumentEditor'\nimport { useFallbackContentPersistence } from './useFallbackContentPersistence'\nimport { useDocumentTitle } from './useDocumentTitle'\nimport { useEditorInsertions } from './useEditorInsertions'\n\ntype Props = DocumentEditorIslandProps & {\n transport: 'collab' | 'fallback'\n collabResources?: CollabResources\n connectionStatus: ConnectionStatus\n presenceUsers: PresenceUser[]\n mode: EditorMode\n onModeChange: (mode: EditorMode) => void\n}\n\nexport function DocumentEditorSurface(input: Props) {\n const t = useT()\n const [outlineOpen, setOutlineOpen] = React.useState(false)\n const [suggestionRange, setSuggestionRange] = React.useState<{ from: number; to: number } | null>(null)\n const modeChangeInFlightRef = React.useRef(false)\n const effectiveReadOnly = input.readOnly || input.mode === 'preview'\n const openSuggestion = React.useCallback((range: { from: number; to: number }) => setSuggestionRange(range), [])\n const closeSuggestion = React.useCallback(() => setSuggestionRange(null), [])\n const fallbackPersistence = useFallbackContentPersistence({\n documentId: input.documentId,\n initialUpdatedAt: input.contentUpdatedAt ?? null,\n enabled: input.transport === 'fallback' && !input.readOnly,\n onConflictRefresh: input.onContentConflict,\n })\n const editorModel = useDocumentEditor({\n documentId: input.documentId,\n initialContentHtml: input.initialContentHtml,\n editorMode: input.transport,\n collabResources: input.collabResources,\n readOnly: effectiveReadOnly,\n onEditorReady: input.onEditorReady,\n onUpdate: fallbackPersistence.onEditorUpdate,\n onEntitySuggestion: openSuggestion,\n onSuggestionClose: closeSuggestion,\n })\n const title = useDocumentTitle({\n documentId: input.documentId,\n title: input.title,\n updatedAt: input.documentUpdatedAt ?? null,\n readOnly: effectiveReadOnly,\n onTitleChange: input.onTitleChange,\n })\n const insertions = useEditorInsertions({\n documentId: input.documentId,\n editorRef: editorModel.editorRef,\n disabled: effectiveReadOnly,\n suggestionRange,\n setSuggestionRange,\n })\n React.useEffect(() => {\n if (suggestionRange && !effectiveReadOnly) insertions.setPickerOpen(true)\n }, [effectiveReadOnly, insertions.setPickerOpen, suggestionRange])\n\n const status = input.transport === 'fallback' ? 'offline' : input.connectionStatus\n const notice = input.transport === 'fallback'\n ? t(input.readOnly ? 'documents.editor.realtime.readOnlyFallback' : 'documents.editor.realtime.singleUserFallback')\n : input.readOnly\n ? t('documents.editor.readOnly')\n : input.mode === 'preview'\n ? t('documents.editor.mode.previewNotice')\n : null\n const selectionCommentHandler = canCreateSelectionComment({\n permissionReadOnly: input.readOnly,\n mode: input.mode,\n transport: input.transport,\n hasCommentHandler: Boolean(input.onComment),\n }) ? input.onComment : undefined\n const handleModeChange = React.useCallback(async (nextMode: EditorMode) => {\n if (nextMode === input.mode || modeChangeInFlightRef.current) return\n if (input.transport !== 'fallback' || nextMode !== 'preview') {\n input.onModeChange(nextMode)\n return\n }\n\n modeChangeInFlightRef.current = true\n try {\n if (await fallbackPersistence.saveNow()) input.onModeChange(nextMode)\n } finally {\n modeChangeInFlightRef.current = false\n }\n }, [fallbackPersistence.saveNow, input.mode, input.onModeChange, input.transport])\n\n return (\n <div className={cn('space-y-3', input.transport === 'collab' && 'om-doc-collab', input.mode === 'preview' && 'om-doc-preview')}>\n <style>{EDITOR_PRESENCE_STYLES}</style>\n <div className=\"overflow-hidden rounded-lg border border-border bg-muted shadow-sm\">\n <div className=\"sticky top-0 z-sticky border-b border-border bg-card/95\">\n <div className=\"flex flex-wrap items-center justify-between gap-2 px-3 py-2\">\n <EditorStatusPresence\n status={status}\n users={input.presenceUsers}\n counts={editorModel.counts}\n mode={input.mode}\n canEdit={!input.readOnly}\n onModeChange={(nextMode) => { void handleModeChange(nextMode) }}\n fallbackSave={input.transport === 'fallback' && !input.readOnly ? {\n status: fallbackPersistence.status,\n onSave: fallbackPersistence.saveNow,\n } : undefined}\n />\n </div>\n {input.mode === 'edit' ? (\n <EditorToolbar\n editor={editorModel.editor}\n disabled={effectiveReadOnly || !editorModel.editor}\n outlineOpen={outlineOpen}\n uploading={insertions.uploading}\n onToggleOutline={() => setOutlineOpen((value) => !value)}\n onOpenEntityPicker={insertions.openEntityPicker}\n onOpenLink={insertions.openLink}\n onImage={() => insertions.fileInputRef.current?.click()}\n />\n ) : null}\n {insertions.linkOpen && !effectiveReadOnly ? (\n <div className=\"flex flex-col gap-3 border-t border-border bg-muted/30 p-3 md:flex-row md:items-end\" onKeyDown={(event) => {\n if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') { event.preventDefault(); insertions.applyLink() }\n if (event.key === 'Escape') { event.preventDefault(); insertions.setLinkOpen(false) }\n }}>\n <div className=\"min-w-0 flex-1 space-y-2\">\n <Label htmlFor={`document-link-${input.documentId}`}>{t('documents.editor.link.url')}</Label>\n <Input id={`document-link-${input.documentId}`} type=\"url\" value={insertions.linkHref} onChange={(event) => insertions.setLinkHref(event.target.value)} placeholder={t('documents.editor.link.placeholder')} />\n </div>\n <Button type=\"button\" onClick={insertions.applyLink}><Link2 />{t('documents.editor.link.apply')}</Button>\n <Button type=\"button\" variant=\"outline\" onClick={insertions.removeLink}><Unlink />{t('documents.editor.link.remove')}</Button>\n <Button type=\"button\" variant=\"ghost\" onClick={() => insertions.setLinkOpen(false)}>{t('documents.actions.cancel')}</Button>\n </div>\n ) : null}\n </div>\n <DocumentCanvas editor={editorModel.editor} title={title} readOnly={effectiveReadOnly} outlineOpen={outlineOpen} notice={notice} onOpenLink={insertions.openLink} onComment={selectionCommentHandler} />\n </div>\n <EntityPicker open={insertions.entityPickerOpen} onOpenChange={insertions.setPickerOpen} onPick={(pick) => { void insertions.handleEntityPick(pick) }} />\n <RecordFieldsDialog\n documentId={input.documentId}\n linkId={insertions.recordFieldsLinkId}\n editor={editorModel.editor}\n canInsert={!effectiveReadOnly && Boolean(editorModel.editor)}\n onOpenChange={(open) => { if (!open) insertions.closeRecordFields() }}\n />\n <input ref={insertions.fileInputRef} type=\"file\" accept=\"image/*\" className=\"hidden\" aria-label={t('documents.editor.imageInput')} onChange={(event) => { void insertions.handleFiles(event.target.files) }} />\n </div>\n )\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'\nimport { Link2, Unlink } from 'lucide-react'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { EntityPicker } from '../components/EntityPicker'\nimport { DocumentCanvas } from './DocumentCanvas'\nimport { EditorStatusPresence } from './EditorStatusPresence'\nimport { EditorToolbar } from './EditorToolbar'\nimport { RecordFieldsDialog } from './RecordFieldsDialog'\nimport { EDITOR_PRESENCE_STYLES } from './editorPresenceStyles'\nimport { canCreateSelectionComment, type CollabResources, type ConnectionStatus, type DocumentEditorIslandProps, type EditorMode, type PresenceUser } from './editorTypes'\nimport { useDocumentEditor } from './useDocumentEditor'\nimport { useFallbackContentPersistence } from './useFallbackContentPersistence'\nimport { useDocumentTitle } from './useDocumentTitle'\nimport { useEditorInsertions } from './useEditorInsertions'\nimport { saveCollaborativeContent } from './saveCollaborativeContent'\n\ntype Props = DocumentEditorIslandProps & {\n transport: 'collab' | 'fallback'\n collabResources?: CollabResources\n connectionStatus: ConnectionStatus\n presenceUsers: PresenceUser[]\n mode: EditorMode\n onModeChange: (mode: EditorMode) => void\n}\n\nexport function DocumentEditorSurface(input: Props) {\n const t = useT()\n const nonce = useContentSecurityPolicyNonce()\n const [outlineOpen, setOutlineOpen] = React.useState(false)\n const [suggestionRange, setSuggestionRange] = React.useState<{ from: number; to: number } | null>(null)\n const modeChangeInFlightRef = React.useRef(false)\n const effectiveReadOnly = input.readOnly || input.mode === 'preview'\n const openSuggestion = React.useCallback((range: { from: number; to: number }) => setSuggestionRange(range), [])\n const closeSuggestion = React.useCallback(() => setSuggestionRange(null), [])\n const fallbackPersistence = useFallbackContentPersistence({\n documentId: input.documentId,\n initialUpdatedAt: input.contentUpdatedAt ?? null,\n enabled: input.transport === 'fallback' && !input.readOnly,\n onConflictRefresh: input.onContentConflict,\n })\n const editorModel = useDocumentEditor({\n documentId: input.documentId,\n initialContentHtml: input.initialContentHtml,\n editorMode: input.transport,\n collabResources: input.collabResources,\n readOnly: effectiveReadOnly,\n onEditorReady: input.onEditorReady,\n onUpdate: fallbackPersistence.onEditorUpdate,\n onEntitySuggestion: openSuggestion,\n onSuggestionClose: closeSuggestion,\n })\n const title = useDocumentTitle({\n documentId: input.documentId,\n title: input.title,\n updatedAt: input.documentUpdatedAt ?? null,\n readOnly: effectiveReadOnly,\n onTitleChange: input.onTitleChange,\n })\n React.useEffect(() => {\n const controller = new AbortController()\n input.onSaveReady?.(async () => {\n if (controller.signal.aborted || input.readOnly || !editorModel.editorRef.current) return false\n return input.transport === 'fallback'\n ? fallbackPersistence.saveNow()\n : input.collabResources\n ? saveCollaborativeContent(input.collabResources, controller.signal)\n : false\n })\n return () => {\n controller.abort()\n input.onSaveReady?.(null)\n }\n }, [editorModel.editorRef, fallbackPersistence.saveNow, input.collabResources, input.onSaveReady, input.readOnly, input.transport])\n const insertions = useEditorInsertions({\n documentId: input.documentId,\n editorRef: editorModel.editorRef,\n disabled: effectiveReadOnly,\n suggestionRange,\n setSuggestionRange,\n })\n React.useEffect(() => {\n if (suggestionRange && !effectiveReadOnly) insertions.setPickerOpen(true)\n }, [effectiveReadOnly, insertions.setPickerOpen, suggestionRange])\n\n const status = input.transport === 'fallback' ? 'offline' : input.connectionStatus\n const notice = input.transport === 'fallback'\n ? t(input.readOnly ? 'documents.editor.realtime.readOnlyFallback' : 'documents.editor.realtime.singleUserFallback')\n : input.readOnly\n ? t('documents.editor.readOnly')\n : input.mode === 'preview'\n ? t('documents.editor.mode.previewNotice')\n : null\n const selectionCommentHandler = canCreateSelectionComment({\n permissionReadOnly: input.readOnly,\n mode: input.mode,\n transport: input.transport,\n hasCommentHandler: Boolean(input.onComment),\n }) ? input.onComment : undefined\n const handleModeChange = React.useCallback(async (nextMode: EditorMode) => {\n if (nextMode === input.mode || modeChangeInFlightRef.current) return\n if (input.transport !== 'fallback' || nextMode !== 'preview') {\n input.onModeChange(nextMode)\n return\n }\n\n modeChangeInFlightRef.current = true\n try {\n if (await fallbackPersistence.saveNow()) input.onModeChange(nextMode)\n } finally {\n modeChangeInFlightRef.current = false\n }\n }, [fallbackPersistence.saveNow, input.mode, input.onModeChange, input.transport])\n\n return (\n <div className={cn('space-y-3', input.transport === 'collab' && 'om-doc-collab', input.mode === 'preview' && 'om-doc-preview')}>\n <style nonce={nonce}>{EDITOR_PRESENCE_STYLES}</style>\n <div className=\"overflow-hidden rounded-lg border border-border bg-muted shadow-sm\">\n <div className=\"sticky top-0 z-sticky border-b border-border bg-card/95\">\n <div className=\"flex flex-wrap items-center justify-between gap-2 px-3 py-2\">\n <EditorStatusPresence\n status={status}\n users={input.presenceUsers}\n counts={editorModel.counts}\n mode={input.mode}\n canEdit={!input.readOnly}\n onModeChange={(nextMode) => { void handleModeChange(nextMode) }}\n fallbackSave={input.transport === 'fallback' && !input.readOnly ? {\n status: fallbackPersistence.status,\n onSave: fallbackPersistence.saveNow,\n } : undefined}\n />\n </div>\n {input.mode === 'edit' ? (\n <EditorToolbar\n editor={editorModel.editor}\n disabled={effectiveReadOnly || !editorModel.editor}\n outlineOpen={outlineOpen}\n uploading={insertions.uploading}\n onToggleOutline={() => setOutlineOpen((value) => !value)}\n onOpenEntityPicker={insertions.openEntityPicker}\n onOpenLink={insertions.openLink}\n onImage={() => insertions.fileInputRef.current?.click()}\n />\n ) : null}\n {insertions.linkOpen && !effectiveReadOnly ? (\n <div className=\"flex flex-col gap-3 border-t border-border bg-muted/30 p-3 md:flex-row md:items-end\" onKeyDown={(event) => {\n if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') { event.preventDefault(); insertions.applyLink() }\n if (event.key === 'Escape') { event.preventDefault(); insertions.setLinkOpen(false) }\n }}>\n <div className=\"min-w-0 flex-1 space-y-2\">\n <Label htmlFor={`document-link-${input.documentId}`}>{t('documents.editor.link.url')}</Label>\n <Input id={`document-link-${input.documentId}`} type=\"url\" value={insertions.linkHref} onChange={(event) => insertions.setLinkHref(event.target.value)} placeholder={t('documents.editor.link.placeholder')} />\n </div>\n <Button type=\"button\" onClick={insertions.applyLink}><Link2 />{t('documents.editor.link.apply')}</Button>\n <Button type=\"button\" variant=\"outline\" onClick={insertions.removeLink}><Unlink />{t('documents.editor.link.remove')}</Button>\n <Button type=\"button\" variant=\"ghost\" onClick={() => insertions.setLinkOpen(false)}>{t('documents.actions.cancel')}</Button>\n </div>\n ) : null}\n </div>\n <DocumentCanvas editor={editorModel.editor} title={title} readOnly={effectiveReadOnly} outlineOpen={outlineOpen} notice={notice} onOpenLink={insertions.openLink} onComment={selectionCommentHandler} />\n </div>\n <EntityPicker open={insertions.entityPickerOpen} onOpenChange={insertions.setPickerOpen} onPick={(pick) => { void insertions.handleEntityPick(pick) }} />\n <RecordFieldsDialog\n documentId={input.documentId}\n linkId={insertions.recordFieldsLinkId}\n editor={editorModel.editor}\n canInsert={!effectiveReadOnly && Boolean(editorModel.editor)}\n onOpenChange={(open) => { if (!open) insertions.closeRecordFields() }}\n />\n <input ref={insertions.fileInputRef} type=\"file\" accept=\"image/*\" className=\"hidden\" aria-label={t('documents.editor.imageInput')} onChange={(event) => { void insertions.handleFiles(event.target.files) }} />\n </div>\n )\n}\n"],
|
|
5
|
+
"mappings": ";AA0HM,cAkCQ,YAlCR;AAxHN,YAAY,WAAW;AACvB,SAAS,qCAAqC;AAC9C,SAAS,OAAO,cAAc;AAC9B,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB,SAAS,UAAU;AACnB,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAAS,qBAAqB;AAC9B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,iCAAkJ;AAC3J,SAAS,yBAAyB;AAClC,SAAS,qCAAqC;AAC9C,SAAS,wBAAwB;AACjC,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;AAWlC,SAAS,sBAAsB,OAAc;AAClD,QAAM,IAAI,KAAK;AACf,QAAM,QAAQ,8BAA8B;AAC5C,QAAM,CAAC,aAAa,cAAc,IAAI,MAAM,SAAS,KAAK;AAC1D,QAAM,CAAC,iBAAiB,kBAAkB,IAAI,MAAM,SAA8C,IAAI;AACtG,QAAM,wBAAwB,MAAM,OAAO,KAAK;AAChD,QAAM,oBAAoB,MAAM,YAAY,MAAM,SAAS;AAC3D,QAAM,iBAAiB,MAAM,YAA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