@arbidocs/react 0.5.149 → 0.5.151

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/notifications/server-notifications.ts"],
4
- "sourcesContent": ["/**\n * What a server-persisted notification (`NotificationResponse`) says and where it leads \u2014 the one\n * type\u2192presentation mapping every surface reads (the arrival toast, the bell entry, the\n * notification centre), so wording cannot drift between them or between hosts.\n *\n * Titles derive from `type`, the sender and plaintext routing metadata only: the E2E-encrypted\n * content is never needed. Where an entry leads is data ({@link NotificationTarget}); the host\n * owns navigation and turns a target into its own route.\n */\n\nimport type { components } from '@arbidocs/client'\nimport { mailDraftIdFromContent } from '../mail/client'\nimport type { NotifyVariant } from './notify-store'\n\ntype NotificationResponse = components['schemas']['NotificationResponse']\ntype NotificationUser = NotificationResponse['sender']\n\n/** Where a notification leads. The host maps each kind onto its routes. */\nexport type NotificationTarget =\n /** A workspace's own page (a membership change). */\n | { kind: 'workspace'; workspaceId: string }\n /** A thread, scrolled to a message when given. */\n | { kind: 'conversation'; workspaceId?: string; conversationId: string; messageId?: string }\n /** A document: at a version, on a comment, or on a viewer tab when given. */\n | {\n kind: 'document'\n workspaceId?: string\n documentId: string\n version?: number\n commentId?: string\n tab?: 'pdf'\n }\n /** The mailbox, on a draft when given. */\n | { kind: 'mail'; draftId?: string }\n /** A database, open at a row when given (an approval's request). */\n | { kind: 'database'; workspaceId?: string; databaseId: string; rowId?: string }\n /** The workflows page, on a workflow (in its workspace) when given. */\n | { kind: 'workflows'; workflowId?: string; workspaceId?: string }\n /** Projects and their AI usage. */\n | { kind: 'projects' }\n | { kind: 'support'; ticketId: number }\n /** Storage settings. */\n | { kind: 'storage' }\n /** Where seats are added (the Box's licence page). */\n | { kind: 'seats' }\n /** Review a workspace access request (choose a workspace and a role). */\n | { kind: 'access-request'; notification: NotificationResponse }\n /** Call the sender back. */\n | { kind: 'call-back'; user: NotificationUser }\n /** An external page, opened in a new tab. */\n | { kind: 'url'; url: string }\n /** The calendar, on an event when given; `join`: join the event's online meeting. */\n | { kind: 'calendar'; eventId?: string; recurrenceId?: string | null; join?: boolean }\n\n/** A server notification's presentation: its sentence, severity, and where it leads. */\nexport interface ServerNotificationDescription {\n title: string\n variant: NotifyVariant\n /** The label of the action that opens {@link target} (\"Review and sign\"); default \"View\". */\n actionLabel?: string\n target?: NotificationTarget\n}\n\nexport interface DescribeServerNotificationOptions {\n /** The sender's display name; default their given and family name, else their email. */\n senderName?: string\n /** The name of a document the notification is about, when the host knows it (names are\n * encrypted, so a notification carries only the id). */\n documentName?: (workspaceId: string | null | undefined, documentId: string) => string | undefined\n /** The portal origins a deployment-user notice may link to. */\n portalOrigins?: readonly string[]\n}\n\n/** A person's display name: given and family name, else their email. */\nexport function notificationUserName(user: NotificationUser): string {\n return [user.given_name, user.family_name].filter(Boolean).join(' ') || user.email\n}\n\nconst CONVERSATION_ID = /^con-[a-zA-Z0-9]+$/\nconst WORKFLOW_ID = /^wfl-[a-zA-Z0-9]+$/\nconst DOCUMENT_ID = /^doc-[a-zA-Z0-9]+$/\n\nfunction parse(content: string | null | undefined): Record<string, unknown> | null {\n try {\n const value = JSON.parse(content || '{}') as unknown\n return value && typeof value === 'object' ? (value as Record<string, unknown>) : null\n } catch {\n return null\n }\n}\n\n/**\n * The plaintext totals of an `upload_set_complete` notification (one upload action finished: every\n * document of it is processed or failed). Counts and opaque ids only; never a file name.\n */\nexport function uploadSetMeta(content: string | null | undefined): {\n total: number\n completed: number\n failed: number\n failedDocumentIds: string[]\n refused: number\n notUploaded: number\n} {\n const meta = parse(content) ?? {}\n const count = (key: string) => {\n const value = meta[key]\n return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : 0\n }\n const ids = Array.isArray(meta.failed_doc_ext_ids) ? meta.failed_doc_ext_ids : []\n return {\n total: count('total'),\n completed: count('completed'),\n failed: count('failed'),\n failedDocumentIds: ids.filter(\n (id): id is string => typeof id === 'string' && DOCUMENT_ID.test(id)\n ),\n refused: count('refused'),\n notUploaded: count('not_uploaded'),\n }\n}\n\nconst documents = (n: number) => `${n} document${n === 1 ? '' : 's'}`\n\n/** \"250 documents indexed\", or \"247 of 250 documents indexed \u00B7 3 failed \u00B7 1 skipped\". */\nexport function uploadSetTitle(content: string | null | undefined): string {\n const { total, completed, failed, refused, notUploaded } = uploadSetMeta(content)\n const parts = [\n completed === total || total === 0\n ? `${documents(completed)} indexed`\n : `${completed} of ${documents(total)} indexed`,\n ]\n if (failed) parts.push(`${failed} failed`)\n if (refused) parts.push(`${refused} skipped`)\n if (notUploaded) parts.push(`${notUploaded} not uploaded`)\n return parts.join(' \u00B7 ')\n}\n\n/** Deadline metadata is intentionally plaintext; the confidential question stays in the thread. */\nexport function inputRequestTitle(content: string | null | undefined): string {\n const metadata = parse(content)\n if (!metadata) return 'ARBI needs your input \u2014 open the thread to reply'\n const timeout = typeof metadata.timeout_seconds === 'number' ? metadata.timeout_seconds : 300\n const minutes = Math.ceil(timeout / 60)\n const deadline = typeof metadata.expires_at === 'string' ? new Date(metadata.expires_at) : null\n if (deadline && Number.isFinite(deadline.getTime())) {\n return `ARBI needs your input \u2014 ${minutes} min to reply (until ${deadline.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })})`\n }\n return `ARBI needs your input \u2014 ${minutes} min to reply`\n}\n\n/**\n * The plaintext routing content of a `document_activity` notification: `{doc_ext_id, event,\n * reason, version}`. Opaque ids and a closed vocabulary only; never the file name.\n */\nexport function documentActivityMeta(content: string | null | undefined): {\n documentId?: string\n reason?: string\n version?: number\n} {\n const meta = parse(content)\n if (!meta) return {}\n const documentId =\n typeof meta.doc_ext_id === 'string' && DOCUMENT_ID.test(meta.doc_ext_id)\n ? meta.doc_ext_id\n : undefined\n const version =\n typeof meta.version === 'number' && Number.isInteger(meta.version) && meta.version > 0\n ? meta.version\n : undefined\n const reason = typeof meta.reason === 'string' ? meta.reason : undefined\n return { documentId, reason, version }\n}\n\n/** What a `document_activity` says after its sender: \"signed a document\", \"saved version 3 of a document\". */\nexport function documentActivityPhrase(content: string | null | undefined): string {\n const { reason, version } = documentActivityMeta(content)\n if (reason === 'signed') return 'signed a document'\n return version ? `saved version ${version} of a document` : 'saved a new version of a document'\n}\n\n/** The document and comment a `docx_mention` points at (routing ids only). */\nexport function docxMentionMeta(content: string | null | undefined): {\n documentId?: string\n commentId?: string\n} {\n const meta = parse(content)\n if (!meta || typeof meta.document_id !== 'string' || !DOCUMENT_ID.test(meta.document_id))\n return {}\n return {\n documentId: meta.document_id,\n commentId: typeof meta.comment_id === 'string' && meta.comment_id ? meta.comment_id : undefined,\n }\n}\n\n/**\n * The plaintext routing content of a signature-request notification: `{request_id, document_id,\n * signed_version?}`. Opaque ids only: the document's name is encrypted, so it is never in a\n * notification.\n */\nexport function signatureRequestMeta(content: string | null | undefined): {\n documentId?: string\n version?: number\n} {\n const meta = parse(content)\n if (!meta) return {}\n const documentId =\n typeof meta.document_id === 'string' && DOCUMENT_ID.test(meta.document_id)\n ? meta.document_id\n : undefined\n const version =\n typeof meta.signed_version === 'number' && Number.isInteger(meta.signed_version)\n ? meta.signed_version\n : undefined\n return { documentId, version }\n}\n\n/** The notification types of a signature request. */\nexport const SIGNATURE_NOTIFICATION_TYPES = [\n 'signature_requested',\n 'signature_completed',\n 'signature_declined',\n] as const\nexport type SignatureNotificationType = (typeof SIGNATURE_NOTIFICATION_TYPES)[number]\n\nexport function isSignatureNotificationType(\n type: string | null | undefined\n): type is SignatureNotificationType {\n return (SIGNATURE_NOTIFICATION_TYPES as readonly string[]).includes(type ?? '')\n}\n\n/**\n * What a signature notification says, around the person's name and the document's:\n * `{lead} [person] {verb} [document]{tail}`. The recipient reads it about the sender\n * (\"Priya Shah asked you to sign NDA.pdf\"); the sender, in their own activity, about what they did\n * (\"You asked Sam Lee to sign NDA.pdf\"), with the person left out when the sentence needs none.\n */\nexport function signatureNotificationPhrase(\n type: SignatureNotificationType,\n incoming: boolean\n): { lead: string; showPerson: boolean; verb: string; tail: string } {\n if (incoming) {\n switch (type) {\n case 'signature_requested':\n return { lead: '', showPerson: true, verb: 'asked you to sign', tail: '' }\n case 'signature_completed':\n return { lead: '', showPerson: true, verb: 'signed', tail: ' \u2014 everyone has now signed' }\n case 'signature_declined':\n return { lead: '', showPerson: true, verb: 'declined to sign', tail: '' }\n }\n }\n switch (type) {\n case 'signature_requested':\n return { lead: 'You asked', showPerson: true, verb: 'to sign', tail: '' }\n case 'signature_completed':\n return { lead: 'You signed', showPerson: false, verb: '', tail: ' \u2014 everyone has now signed' }\n case 'signature_declined':\n return { lead: 'You declined to sign', showPerson: false, verb: '', tail: '' }\n }\n}\n\n/**\n * Plaintext routing metadata on call notifications (`call_missed`): `{call_ext_id}`. Never a\n * title \u2014 titles are encrypted under the call's key.\n */\nexport function callNotificationMeta(content: string | null | undefined): { callExtId?: string } {\n const meta = parse(content)\n return {\n callExtId:\n typeof meta?.call_ext_id === 'string' && /^call-[a-zA-Z0-9]{8}$/.test(meta.call_ext_id)\n ? meta.call_ext_id\n : undefined,\n }\n}\n\n/** A Box had no seat for a new internal user: the inviter's invitation was not sent. Central\n * emails the inviter and the Box admins; this is the inviter's own notice. */\nexport const BOX_SEAT_REFUSED = 'box_seat_refused'\nexport const BOX_SEAT_REFUSED_TITLE =\n 'Invitation not sent: your Box has no seat left. Your Box admins have been notified and can add users in the ARBI portal.'\nexport const BOX_SEAT_REFUSED_ACTION = 'Open the ARBI portal'\n\n/** A deployment admin's notice about the Box's users (`deployment_user_invited` / `_registered`):\n * an invitation sent (sender = the inviter) or an account created (sender = the new user). */\nexport function isDeploymentUserNotification(type: string | null | undefined): boolean {\n return type === 'deployment_user_invited' || type === 'deployment_user_registered'\n}\n\n/** The portal origins a \"Manage users\" link may open by default. Anything else gets no button. */\nexport const ALLOWED_PORTAL_ORIGINS: readonly string[] = ['https://portal.arbicity.com']\n\n/** The portal link, only when it is https on an allowed portal origin. */\nexport function safePortalUrl(\n value: unknown,\n origins: readonly string[] = ALLOWED_PORTAL_ORIGINS\n): string | undefined {\n if (typeof value !== 'string') return undefined\n try {\n const url = new URL(value)\n if (url.protocol !== 'https:' || !origins.includes(url.origin)) return undefined\n return url.href\n } catch {\n return undefined\n }\n}\n\n/** Plaintext content of a deployment-user notification: `{email, user_type, portal_url}`. */\nexport function deploymentUserMeta(\n content: string | null | undefined,\n origins: readonly string[] = ALLOWED_PORTAL_ORIGINS\n): { email?: string; external: boolean; portalUrl?: string } {\n const meta = parse(content)\n if (!meta) return { external: false }\n const email = typeof meta.email === 'string' && meta.email.trim() ? meta.email.trim() : undefined\n return {\n email,\n external: meta.user_type === 'external',\n portalUrl: safePortalUrl(meta.portal_url, origins),\n }\n}\n\n/** A document's display name, as a document list shows it (its title, else its file name). */\nexport function documentDisplayName(\n doc:\n | { file_name?: string | null; doc_metadata?: { title?: string | null } | null }\n | null\n | undefined\n): string | undefined {\n return doc?.doc_metadata?.title || doc?.file_name || undefined\n}\n\n/** What the work notifications say in a list, where the sender has a column of their own. */\nexport const WORK_NOTIFICATION_LABELS: Readonly<Record<string, string>> = {\n conversation_ready: 'A task is ready',\n conversation_done: 'A task was marked done',\n conversation_notified: 'You were notified in a thread',\n workflow_failed: 'A workflow failed to run',\n}\n\nfunction conversationTarget(n: NotificationResponse): NotificationTarget | undefined {\n if (!n.conversation_ext_id || !CONVERSATION_ID.test(n.conversation_ext_id)) return undefined\n return {\n kind: 'conversation',\n workspaceId: n.workspace_ext_id ?? undefined,\n conversationId: n.conversation_ext_id,\n ...(n.message_ext_id ? { messageId: n.message_ext_id } : {}),\n }\n}\n\n/** The workflows page on the notification's workflow (`{workflow_ext_id}` in its content). */\nfunction workflowTarget(n: NotificationResponse): NotificationTarget {\n const workflowId = parse(n.content)?.workflow_ext_id\n return {\n kind: 'workflows',\n ...(typeof workflowId === 'string' && WORKFLOW_ID.test(workflowId) ? { workflowId } : {}),\n ...(n.workspace_ext_id ? { workspaceId: n.workspace_ext_id } : {}),\n }\n}\n\nfunction signatureTitle(\n n: NotificationResponse,\n senderName: string,\n documentName: DescribeServerNotificationOptions['documentName']\n): string {\n const type = n.type as SignatureNotificationType\n const { documentId } = signatureRequestMeta(n.content)\n const name = documentId ? documentName?.(n.workspace_ext_id, documentId) : undefined\n const fallback = type === 'signature_requested' ? 'a document' : 'your document'\n const { verb, tail } = signatureNotificationPhrase(type, true)\n return `${senderName} ${verb} ${name ?? fallback}${tail}`\n}\n\nconst DATABASE_ID = /^dbs-[a-zA-Z0-9]{8}$/\nconst ROW_ID = /^dbr-[a-zA-Z0-9]{8}$/\n\n/** A request row to open (`{database_id, row_id}` in a notification's content), when well formed. */\nfunction databaseTarget(\n n: NotificationResponse,\n meta: Record<string, unknown> | null\n): Extract<NotificationTarget, { kind: 'database' }> | undefined {\n const databaseId = meta?.database_id\n const rowId = meta?.row_id\n if (typeof databaseId !== 'string' || !DATABASE_ID.test(databaseId)) return undefined\n return {\n kind: 'database',\n databaseId,\n ...(typeof rowId === 'string' && ROW_ID.test(rowId) ? { rowId } : {}),\n ...(n.workspace_ext_id ? { workspaceId: n.workspace_ext_id } : {}),\n }\n}\n\n/** The run a workflow notification is about, from the recipient's side: \"your\" or \"Sam Lee\u2019s\". */\nfunction runOwner(n: NotificationResponse, senderName: string): string {\n return n.sender.external_id === n.recipient?.external_id ? 'your' : `${senderName}\u2019s`\n}\n\n/**\n * What a `step_ready` says: a step of a workflow run needs the recipient. Its content is\n * `{conversation_ext_id, step, workflow_ext_id, reason}` (`reason`: ready, sent_back, reminder,\n * finished); the step's title is encrypted in the run, so the sentence names the run's owner only.\n * An approval step adds its request (`database_id`, `row_id`), which it opens directly.\n */\nexport function stepReadyTitle(n: NotificationResponse, senderName: string): string {\n const meta = parse(n.content)\n const run = `${runOwner(n, senderName)} workflow`\n const reason = meta?.reason\n if (meta?.action === 'approval' && reason !== 'sent_back' && reason !== 'finished')\n return reason === 'reminder'\n ? `A request in ${run} is still waiting for your decision`\n : `A request in ${run} needs your decision`\n switch (reason) {\n case 'sent_back':\n return `A step in ${run} was sent back to you`\n case 'reminder':\n return `A step in ${run} is still waiting for you`\n case 'finished':\n return `A step assigned to you in ${run} finished`\n default:\n return `A step in ${run} is ready for you`\n }\n}\n\nfunction quotaPercent(type: string): number | null {\n if (type === 'quota_threshold_100') return 100\n if (type === 'quota_threshold_90') return 90\n if (type === 'quota_threshold_50') return 50\n return null\n}\n\n/**\n * One server notification \u2192 what it says to its recipient and where it leads, or null for\n * types without a sentence here (calendar events, sync completions: they have their own\n * surfaces).\n */\nexport function describeServerNotification(\n n: NotificationResponse,\n options: DescribeServerNotificationOptions = {}\n): ServerNotificationDescription | null {\n const senderName = options.senderName ?? notificationUserName(n.sender)\n const workspace: NotificationTarget | undefined = n.workspace_ext_id\n ? { kind: 'workspace', workspaceId: n.workspace_ext_id }\n : undefined\n const type = n.type as string\n\n if (type === BOX_SEAT_REFUSED) {\n return {\n title: BOX_SEAT_REFUSED_TITLE,\n variant: 'warning',\n actionLabel: BOX_SEAT_REFUSED_ACTION,\n target: { kind: 'seats' },\n }\n }\n const pct = quotaPercent(type)\n if (pct !== null) {\n return {\n title: `You have used ${pct}% of your daily AI limit for this project.`,\n variant: pct === 100 ? 'error' : pct === 90 ? 'warning' : 'info',\n target: { kind: 'projects' },\n }\n }\n\n switch (type) {\n case 'support_ticket_received':\n case 'support_ticket_reviewed':\n case 'support_ticket_resolved': {\n const ticketId = parse(n.content)?.ticket_id\n if (typeof ticketId !== 'number' || !Number.isSafeInteger(ticketId) || ticketId < 1)\n return null\n const suppliedReference = parse(n.content)?.ticket_reference\n const reference =\n typeof suppliedReference === 'string' &&\n /^[a-z0-9-]+-[0-9]+$/.test(suppliedReference) &&\n suppliedReference.endsWith(`-${ticketId}`)\n ? suppliedReference\n : `#${ticketId}`\n return {\n title:\n type === 'support_ticket_received'\n ? `We received support request ${reference}`\n : type === 'support_ticket_reviewed'\n ? `We have reviewed support request ${reference}`\n : `Support request ${reference} is resolved`,\n variant: 'success',\n actionLabel: type === 'support_ticket_resolved' ? 'View outcome' : 'View request',\n target: { kind: 'support', ticketId },\n }\n }\n // A request waiting for this approver's decision, or a decision on the recipient's request: ids only\n // (`{database_id, row_id, column_id}`); the row opens in its database.\n case 'database_row_submitted':\n case 'database_row_decided': {\n const target = databaseTarget(n, parse(n.content))\n if (!target) return null\n const submitted = type === 'database_row_submitted'\n return {\n title: submitted\n ? `${senderName} submitted a request for your decision`\n : `${senderName} decided your request`,\n variant: 'info',\n actionLabel: submitted ? 'Review' : 'Open',\n target,\n }\n }\n // A workflow step needs the recipient. An approval opens its request; any other step the run's\n // thread, where the step is.\n case 'step_ready': {\n const meta = parse(n.content)\n const request = meta?.action === 'approval' ? databaseTarget(n, meta) : undefined\n const reminder = meta?.reason === 'reminder'\n return {\n title: stepReadyTitle(n, senderName),\n variant: reminder ? 'warning' : 'info',\n ...(request\n ? { actionLabel: 'Review', target: request }\n : { target: conversationTarget(n) ?? workflowTarget(n) }),\n }\n }\n // A step of the recipient's own run raised a named signal (a config name, not content).\n case 'workflow_signal': {\n const signal = parse(n.content)?.signal\n return {\n title:\n typeof signal === 'string' && signal\n ? `A workflow step raised the \u201C${signal}\u201D signal`\n : 'A workflow step raised a signal',\n variant: 'info',\n target: conversationTarget(n) ?? workflowTarget(n),\n }\n }\n case 'file_shared': {\n const meta = parse(n.content)\n const id = meta?.file_share_id\n if (typeof id !== 'string' || !/^fsh-[0-9a-f]{32}$/.test(id)) return null\n return {\n title: meta?.declined\n ? `${senderName} declined to sign a file`\n : meta?.completed\n ? 'Everyone has signed. Your PDF is ready.'\n : meta?.signature\n ? `${senderName} asked you to sign a file`\n : `${senderName} shared a file with you`,\n variant: meta?.declined ? 'warning' : meta?.completed ? 'success' : 'info',\n actionLabel: meta?.signature && !meta?.completed ? 'Review and sign' : 'Open file',\n target: { kind: 'url', url: `/shared-files/${id}` },\n }\n }\n // One upload action finished (however many batches it was sent and processed in). A failed\n // document is where it leads when there is one; otherwise the workspace.\n case 'upload_set_complete': {\n const meta = uploadSetMeta(n.content)\n const problems = meta.failed + meta.notUploaded\n const failed = meta.failedDocumentIds\n return {\n title: uploadSetTitle(n.content),\n variant: problems ? 'warning' : 'success',\n ...(failed.length === 1\n ? {\n actionLabel: 'Open failed document',\n target: {\n kind: 'document' as const,\n workspaceId: n.workspace_ext_id ?? undefined,\n documentId: failed[0],\n },\n }\n : { target: workspace }),\n }\n }\n case 'call_missed':\n return {\n title: `Missed call from ${senderName}`,\n variant: 'warning',\n actionLabel: 'Call back',\n target: { kind: 'call-back', user: n.sender },\n }\n case 'native_mail_received':\n return {\n title: 'New email in your encrypted inbox',\n variant: 'info',\n target: { kind: 'mail' },\n }\n case 'mail_draft_ready': {\n const draftId = mailDraftIdFromContent(n.content)\n return {\n title: `${senderName} left a draft email for you to review`,\n variant: 'info',\n target: { kind: 'mail', ...(draftId ? { draftId } : {}) },\n }\n }\n case 'workspaceuser_added_owner':\n return { title: `${senderName} added you as owner`, variant: 'info', target: workspace }\n case 'workspaceuser_added_collaborator':\n return {\n title: `${senderName} added you as collaborator`,\n variant: 'info',\n target: workspace,\n }\n case 'workspaceuser_added_guest':\n return { title: `${senderName} added you as a viewer`, variant: 'info', target: workspace }\n case 'workspaceuser_removed':\n return { title: `${senderName} removed you from a workspace`, variant: 'warning' }\n case 'workspaceuser_updated_owner':\n return {\n title: `${senderName} changed your role to owner`,\n variant: 'info',\n target: workspace,\n }\n case 'workspaceuser_updated_collaborator':\n return {\n title: `${senderName} changed your role to collaborator`,\n variant: 'info',\n target: workspace,\n }\n case 'workspaceuser_updated_guest':\n return {\n title: `${senderName} changed your role to viewer`,\n variant: 'info',\n target: workspace,\n }\n case 'signature_requested':\n case 'signature_completed':\n case 'signature_declined': {\n const { documentId, version } = signatureRequestMeta(n.content)\n return {\n title: signatureTitle(n, senderName, options.documentName),\n variant:\n type === 'signature_completed'\n ? 'success'\n : type === 'signature_declined'\n ? 'warning'\n : 'info',\n actionLabel: type === 'signature_requested' ? 'Review and sign' : 'Open',\n // A request opens the current version on its PDF, where the banner offers \"Review and\n // sign\"; a completed request opens the signed copy.\n target: documentId\n ? {\n kind: 'document',\n workspaceId: n.workspace_ext_id ?? undefined,\n documentId,\n ...(version ? { version } : {}),\n tab: 'pdf',\n }\n : undefined,\n }\n }\n case 'docx_mention': {\n const { documentId, commentId } = docxMentionMeta(n.content)\n return {\n title: `${senderName} mentioned you in a document comment`,\n variant: 'info',\n target: documentId\n ? {\n kind: 'document',\n workspaceId: n.workspace_ext_id ?? undefined,\n documentId,\n ...(commentId ? { commentId } : {}),\n }\n : undefined,\n }\n }\n case 'agent_input_requested':\n return { title: inputRequestTitle(n.content), variant: 'info', target: conversationTarget(n) }\n case 'mention':\n return {\n title: `${senderName} mentioned you in a conversation`,\n variant: 'info',\n target: conversationTarget(n),\n }\n case 'thread_reply':\n return {\n title: `${senderName} replied in a thread`,\n variant: 'info',\n target: conversationTarget(n),\n }\n case 'document_activity': {\n const { documentId, version } = documentActivityMeta(n.content)\n return {\n title: `${senderName} ${documentActivityPhrase(n.content)}`,\n variant: 'info',\n target: documentId\n ? {\n kind: 'document',\n workspaceId: n.workspace_ext_id ?? undefined,\n documentId,\n ...(version ? { version } : {}),\n }\n : undefined,\n }\n }\n // Each of these opens the thread, so the person it is for finds it. One about your own thread\n // (you started the work) says so.\n case 'conversation_ready':\n return {\n title:\n n.sender.external_id === n.recipient.external_id\n ? 'Your thread is ready'\n : `${senderName}\u2019s thread is ready`,\n variant: 'info',\n target: conversationTarget(n),\n }\n case 'conversation_notified':\n return {\n title: `${senderName} notified you in a thread`,\n variant: 'info',\n target: conversationTarget(n),\n }\n case 'conversation_done':\n return {\n title: `${senderName} marked a thread done`,\n variant: 'success',\n target: conversationTarget(n),\n }\n case 'workflow_completed':\n return { title: 'A workflow completed', variant: 'success', target: workflowTarget(n) }\n // The failed run's thread when it has one (its error is there), else the workflow.\n case 'workflow_failed':\n return {\n title: 'A workflow failed to start',\n variant: 'error',\n target: conversationTarget(n) ?? workflowTarget(n),\n }\n case 'deployment_user_invited':\n case 'deployment_user_registered': {\n const { email, external, portalUrl } = deploymentUserMeta(n.content, options.portalOrigins)\n const suffix = external ? ' \u00B7 External' : ''\n return {\n title:\n type === 'deployment_user_invited'\n ? `${senderName} invited ${email ?? 'a new user'}${suffix}`\n : `${email ?? senderName} joined${suffix}`,\n variant: 'info',\n ...(portalUrl && {\n actionLabel: 'Manage users',\n target: { kind: 'url' as const, url: portalUrl },\n }),\n }\n }\n // Someone shared a document into a workspace the recipient owns or follows (e.g. a skill\n // published to the marketplace): its owner may review it.\n case 'doc_shared':\n return {\n title: `${senderName} shared a document into a workspace`,\n variant: 'info',\n target: workspace,\n }\n case 'contact_accepted':\n return { title: `${senderName} joined the platform`, variant: 'success', target: workspace }\n case 'workspace_access_request':\n return {\n title: `${senderName} asked for workspace access`,\n variant: 'info',\n // Straight into the review \u2014 granting needs a workspace choice and a role, so a bare\n // \"grant\" action could never be right here.\n target: { kind: 'access-request', notification: n },\n }\n case 'project_quota_warning': {\n let resource = 'usage'\n let percentage: number | null = null\n let upgrade = ''\n let impending = false\n try {\n const data = JSON.parse(n.content ?? '{}')\n resource = data.resource === 'storage_gb' ? 'storage' : 'AI credits'\n if (data.limit > 0) percentage = Math.round((data.used / data.limit) * 100)\n if (data.stage === 'before_upgrade') {\n impending = true\n const charge = new Intl.NumberFormat('en-GB', {\n style: 'currency',\n currency: data.currency || 'GBP',\n }).format(data.charge_ex_vat_pence / 100)\n upgrade = `An automatic ${resource} upgrade will now be attempted: ${charge} ex VAT.`\n } else if (data.automatic_upgrade === true) {\n upgrade =\n ' An automatic upgrade is available within your limit and will be attempted when needed, subject to payment.'\n } else if (data.automatic_upgrade === false) {\n upgrade =\n data.upgrade_reason === 'limit'\n ? ' No automatic upgrade fits your remaining limit. Increase it or add allowances to keep working.'\n : data.upgrade_reason === 'payment'\n ? ' Automatic upgrades are paused. Resolve your payment issue to keep working.'\n : ' Automatic upgrades are unavailable. Upgrade your plan or reduce usage to keep working.'\n }\n } catch {\n /* An old or malformed notice still opens project usage. */\n }\n return {\n title: impending\n ? upgrade\n : `Your project is approaching its ${resource} limit${percentage != null ? ` (${percentage}% used)` : ''}.${upgrade}`,\n variant: 'warning',\n target: { kind: 'projects' },\n }\n }\n case 'project_retention': {\n let deadline = ''\n try {\n const data = JSON.parse(n.content ?? '{}')\n if (data.deletion_at) deadline = new Date(data.deletion_at).toLocaleDateString('en-GB')\n } catch {\n /* display the recovery notice without a date */\n }\n return {\n title: `Your project subscription has ended. Export or resubscribe${deadline ? ` before ${deadline}` : ''} to keep its data.`,\n variant: 'warning',\n target: { kind: 'projects' },\n }\n }\n case 'storage_quota_exceeded':\n return {\n title:\n 'Your storage is full. Mail still arrives, but new uploads and attachments are paused until you free space or add storage.',\n variant: 'error',\n target: { kind: 'storage' },\n }\n case 'signup_reward':\n return {\n title: n.content ? `\uD83C\uDF89 Signup bonus \u2014 ${n.content}` : '\uD83C\uDF89 You earned a signup bonus!',\n variant: 'success',\n target: { kind: 'projects' },\n }\n case 'referral_reward':\n return {\n title: n.content ? `\uD83C\uDF81 Reward \u2014 ${n.content}` : '\uD83C\uDF81 You earned a reward!',\n variant: 'success',\n target: { kind: 'projects' },\n }\n default:\n return null\n }\n}\n"],
5
- "mappings": "AAWA,SAAS,8BAA8B;AA+DhC,SAAS,qBAAqB,MAAgC;AACnE,SAAO,CAAC,KAAK,YAAY,KAAK,WAAW,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG,KAAK,KAAK;AAC/E;AAEA,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,cAAc;AAEpB,SAAS,MAAM,SAAoE;AACjF,MAAI;AACF,UAAM,QAAQ,KAAK,MAAM,WAAW,IAAI;AACxC,WAAO,SAAS,OAAO,UAAU,WAAY,QAAoC;AAAA,EACnF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAc,SAO5B;AACA,QAAM,OAAO,MAAM,OAAO,KAAK,C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,UAAU;AAAA,MAC5B;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,OAAO,EAAE,UAAU,iCAAqB,EAAE,OAAO,KAAK;AAAA,QACtD,SAAS;AAAA,QACT,QAAQ,EAAE,MAAM,WAAW;AAAA,MAC7B;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,OAAO,EAAE,UAAU,2BAAe,EAAE,OAAO,KAAK;AAAA,QAChD,SAAS;AAAA,QACT,QAAQ,EAAE,MAAM,WAAW;AAAA,MAC7B;AAAA,IACF;AACE,aAAO;AAAA,EACX;AACF;",
4
+ "sourcesContent": ["/**\n * What a server-persisted notification (`NotificationResponse`) says and where it leads \u2014 the one\n * type\u2192presentation mapping every surface reads (the arrival toast, the bell entry, the\n * notification centre), so wording cannot drift between them or between hosts.\n *\n * Titles derive from `type`, the sender and plaintext routing metadata only: the E2E-encrypted\n * content is never needed. Where an entry leads is data ({@link NotificationTarget}); the host\n * owns navigation and turns a target into its own route.\n */\n\nimport type { components } from '@arbidocs/client'\nimport { mailDraftIdFromContent } from '../mail/client'\nimport type { NotifyVariant } from './notify-store'\n\ntype NotificationResponse = components['schemas']['NotificationResponse']\ntype NotificationUser = NotificationResponse['sender']\n\n/** Where a notification leads. The host maps each kind onto its routes. */\nexport type NotificationTarget =\n /** A workspace's own page (a membership change). */\n | { kind: 'workspace'; workspaceId: string }\n /** A thread, scrolled to a message when given. */\n | { kind: 'conversation'; workspaceId?: string; conversationId: string; messageId?: string }\n /** A document: at a version, on a comment, or on a viewer tab when given. */\n | {\n kind: 'document'\n workspaceId?: string\n documentId: string\n version?: number\n commentId?: string\n tab?: 'pdf'\n }\n /** The mailbox, on a draft when given. */\n | { kind: 'mail'; draftId?: string }\n /** A database, open at a row when given (an approval's request). */\n | { kind: 'database'; workspaceId?: string; databaseId: string; rowId?: string }\n /** The workflows page, on a workflow (in its workspace) when given. */\n | { kind: 'workflows'; workflowId?: string; workspaceId?: string }\n /** Projects and their AI usage. */\n | { kind: 'projects' }\n | { kind: 'support'; ticketId: number }\n /** Storage settings. */\n | { kind: 'storage' }\n /** Where seats are added (the Box's licence page). */\n | { kind: 'seats' }\n /** Review a workspace access request (choose a workspace and a role). */\n | { kind: 'access-request'; notification: NotificationResponse }\n /** Call the sender back. */\n | { kind: 'call-back'; user: NotificationUser }\n /** An external page, opened in a new tab. */\n | { kind: 'url'; url: string }\n /** A shared file, shown in the direct chat between the notification's two people (the one who\n * is not me); a host without direct chats opens the file's own page. */\n | { kind: 'file-share'; shareId: string; senderId: string; recipientId: string }\n /** The calendar, on an event when given; `join`: join the event's online meeting. */\n | { kind: 'calendar'; eventId?: string; recurrenceId?: string | null; join?: boolean }\n\n/** A server notification's presentation: its sentence, severity, and where it leads. */\nexport interface ServerNotificationDescription {\n title: string\n variant: NotifyVariant\n /** The label of the action that opens {@link target} (\"Review and sign\"); default \"View\". */\n actionLabel?: string\n target?: NotificationTarget\n}\n\nexport interface DescribeServerNotificationOptions {\n /** The sender's display name; default their given and family name, else their email. */\n senderName?: string\n /** The name of a document the notification is about, when the host knows it (names are\n * encrypted, so a notification carries only the id). */\n documentName?: (workspaceId: string | null | undefined, documentId: string) => string | undefined\n /** The portal origins a deployment-user notice may link to. */\n portalOrigins?: readonly string[]\n}\n\n/** A person's display name: given and family name, else their email. */\nexport function notificationUserName(user: NotificationUser): string {\n return [user.given_name, user.family_name].filter(Boolean).join(' ') || user.email\n}\n\nconst CONVERSATION_ID = /^con-[a-zA-Z0-9]+$/\nconst WORKFLOW_ID = /^wfl-[a-zA-Z0-9]+$/\nconst DOCUMENT_ID = /^doc-[a-zA-Z0-9]+$/\nconst FILE_SHARE_ID = /^fsh-[0-9a-f]{32}$/\n\nfunction parse(content: string | null | undefined): Record<string, unknown> | null {\n try {\n const value = JSON.parse(content || '{}') as unknown\n return value && typeof value === 'object' ? (value as Record<string, unknown>) : null\n } catch {\n return null\n }\n}\n\n/**\n * What happened to a shared file: shared to view, a signature asked for, one signer signed (others\n * still pending), everyone signed, or a signer declined.\n */\nexport type FileShareEvent = 'shared' | 'signature-requested' | 'signed' | 'completed' | 'declined'\n\n/**\n * The plaintext of a `file_shared` notification: the share's id and what happened. Ids and flags\n * only, never the file name (the share itself has it). Null when the id is malformed.\n */\nexport function fileShareNotificationMeta(\n content: string | null | undefined\n): { shareId: string; event: FileShareEvent } | null {\n const meta = parse(content)\n const shareId = meta?.file_share_id\n if (typeof shareId !== 'string' || !FILE_SHARE_ID.test(shareId)) return null\n const event: FileShareEvent =\n meta?.declined === true\n ? 'declined'\n : meta?.completed === true\n ? 'completed'\n : meta?.signed === true\n ? 'signed'\n : meta?.signature === true\n ? 'signature-requested'\n : 'shared'\n return { shareId, event }\n}\n\nconst FILE_SHARE_TITLES: Record<FileShareEvent, (sender: string) => string> = {\n shared: (sender) => `${sender} shared a file with you`,\n 'signature-requested': (sender) => `${sender} asked you to sign a file`,\n signed: (sender) => `${sender} signed a file`,\n completed: () => 'Everyone has signed. Your PDF is ready.',\n declined: (sender) => `${sender} declined to sign a file`,\n}\n\n/**\n * The plaintext totals of an `upload_set_complete` notification (one upload action finished: every\n * document of it is processed or failed). Counts and opaque ids only; never a file name.\n */\nexport function uploadSetMeta(content: string | null | undefined): {\n total: number\n completed: number\n failed: number\n failedDocumentIds: string[]\n refused: number\n notUploaded: number\n} {\n const meta = parse(content) ?? {}\n const count = (key: string) => {\n const value = meta[key]\n return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : 0\n }\n const ids = Array.isArray(meta.failed_doc_ext_ids) ? meta.failed_doc_ext_ids : []\n return {\n total: count('total'),\n completed: count('completed'),\n failed: count('failed'),\n failedDocumentIds: ids.filter(\n (id): id is string => typeof id === 'string' && DOCUMENT_ID.test(id)\n ),\n refused: count('refused'),\n notUploaded: count('not_uploaded'),\n }\n}\n\nconst documents = (n: number) => `${n} document${n === 1 ? '' : 's'}`\n\n/** \"250 documents indexed\", or \"247 of 250 documents indexed \u00B7 3 failed \u00B7 1 skipped\". */\nexport function uploadSetTitle(content: string | null | undefined): string {\n const { total, completed, failed, refused, notUploaded } = uploadSetMeta(content)\n const parts = [\n completed === total || total === 0\n ? `${documents(completed)} indexed`\n : `${completed} of ${documents(total)} indexed`,\n ]\n if (failed) parts.push(`${failed} failed`)\n if (refused) parts.push(`${refused} skipped`)\n if (notUploaded) parts.push(`${notUploaded} not uploaded`)\n return parts.join(' \u00B7 ')\n}\n\n/** Deadline metadata is intentionally plaintext; the confidential question stays in the thread. */\nexport function inputRequestTitle(content: string | null | undefined): string {\n const metadata = parse(content)\n if (!metadata) return 'ARBI needs your input \u2014 open the thread to reply'\n const timeout = typeof metadata.timeout_seconds === 'number' ? metadata.timeout_seconds : 300\n const minutes = Math.ceil(timeout / 60)\n const deadline = typeof metadata.expires_at === 'string' ? new Date(metadata.expires_at) : null\n if (deadline && Number.isFinite(deadline.getTime())) {\n return `ARBI needs your input \u2014 ${minutes} min to reply (until ${deadline.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })})`\n }\n return `ARBI needs your input \u2014 ${minutes} min to reply`\n}\n\n/**\n * The plaintext routing content of a `document_activity` notification: `{doc_ext_id, event,\n * reason, version}`. Opaque ids and a closed vocabulary only; never the file name.\n */\nexport function documentActivityMeta(content: string | null | undefined): {\n documentId?: string\n reason?: string\n version?: number\n} {\n const meta = parse(content)\n if (!meta) return {}\n const documentId =\n typeof meta.doc_ext_id === 'string' && DOCUMENT_ID.test(meta.doc_ext_id)\n ? meta.doc_ext_id\n : undefined\n const version =\n typeof meta.version === 'number' && Number.isInteger(meta.version) && meta.version > 0\n ? meta.version\n : undefined\n const reason = typeof meta.reason === 'string' ? meta.reason : undefined\n return { documentId, reason, version }\n}\n\n/** What a `document_activity` says after its sender: \"signed a document\", \"saved version 3 of a document\". */\nexport function documentActivityPhrase(content: string | null | undefined): string {\n const { reason, version } = documentActivityMeta(content)\n if (reason === 'signed') return 'signed a document'\n return version ? `saved version ${version} of a document` : 'saved a new version of a document'\n}\n\n/** The document and comment a `docx_mention` points at (routing ids only). */\nexport function docxMentionMeta(content: string | null | undefined): {\n documentId?: string\n commentId?: string\n} {\n const meta = parse(content)\n if (!meta || typeof meta.document_id !== 'string' || !DOCUMENT_ID.test(meta.document_id))\n return {}\n return {\n documentId: meta.document_id,\n commentId: typeof meta.comment_id === 'string' && meta.comment_id ? meta.comment_id : undefined,\n }\n}\n\n/**\n * The plaintext routing content of a signature-request notification: `{request_id, document_id,\n * signed_version?}`. Opaque ids only: the document's name is encrypted, so it is never in a\n * notification.\n */\nexport function signatureRequestMeta(content: string | null | undefined): {\n documentId?: string\n version?: number\n} {\n const meta = parse(content)\n if (!meta) return {}\n const documentId =\n typeof meta.document_id === 'string' && DOCUMENT_ID.test(meta.document_id)\n ? meta.document_id\n : undefined\n const version =\n typeof meta.signed_version === 'number' && Number.isInteger(meta.signed_version)\n ? meta.signed_version\n : undefined\n return { documentId, version }\n}\n\n/** The notification types of a signature request. */\nexport const SIGNATURE_NOTIFICATION_TYPES = [\n 'signature_requested',\n 'signature_completed',\n 'signature_declined',\n] as const\nexport type SignatureNotificationType = (typeof SIGNATURE_NOTIFICATION_TYPES)[number]\n\nexport function isSignatureNotificationType(\n type: string | null | undefined\n): type is SignatureNotificationType {\n return (SIGNATURE_NOTIFICATION_TYPES as readonly string[]).includes(type ?? '')\n}\n\n/**\n * What a signature notification says, around the person's name and the document's:\n * `{lead} [person] {verb} [document]{tail}`. The recipient reads it about the sender\n * (\"Priya Shah asked you to sign NDA.pdf\"); the sender, in their own activity, about what they did\n * (\"You asked Sam Lee to sign NDA.pdf\"), with the person left out when the sentence needs none.\n */\nexport function signatureNotificationPhrase(\n type: SignatureNotificationType,\n incoming: boolean\n): { lead: string; showPerson: boolean; verb: string; tail: string } {\n if (incoming) {\n switch (type) {\n case 'signature_requested':\n return { lead: '', showPerson: true, verb: 'asked you to sign', tail: '' }\n case 'signature_completed':\n return { lead: '', showPerson: true, verb: 'signed', tail: ' \u2014 everyone has now signed' }\n case 'signature_declined':\n return { lead: '', showPerson: true, verb: 'declined to sign', tail: '' }\n }\n }\n switch (type) {\n case 'signature_requested':\n return { lead: 'You asked', showPerson: true, verb: 'to sign', tail: '' }\n case 'signature_completed':\n return { lead: 'You signed', showPerson: false, verb: '', tail: ' \u2014 everyone has now signed' }\n case 'signature_declined':\n return { lead: 'You declined to sign', showPerson: false, verb: '', tail: '' }\n }\n}\n\n/**\n * Plaintext routing metadata on call notifications (`call_missed`): `{call_ext_id}`. Never a\n * title \u2014 titles are encrypted under the call's key.\n */\nexport function callNotificationMeta(content: string | null | undefined): { callExtId?: string } {\n const meta = parse(content)\n return {\n callExtId:\n typeof meta?.call_ext_id === 'string' && /^call-[a-zA-Z0-9]{8}$/.test(meta.call_ext_id)\n ? meta.call_ext_id\n : undefined,\n }\n}\n\n/** A Box had no seat for a new internal user: the inviter's invitation was not sent. Central\n * emails the inviter and the Box admins; this is the inviter's own notice. */\nexport const BOX_SEAT_REFUSED = 'box_seat_refused'\nexport const BOX_SEAT_REFUSED_TITLE =\n 'Invitation not sent: your Box has no seat left. Your Box admins have been notified and can add users in the ARBI portal.'\nexport const BOX_SEAT_REFUSED_ACTION = 'Open the ARBI portal'\n\n/** A deployment admin's notice about the Box's users (`deployment_user_invited` / `_registered`):\n * an invitation sent (sender = the inviter) or an account created (sender = the new user). */\nexport function isDeploymentUserNotification(type: string | null | undefined): boolean {\n return type === 'deployment_user_invited' || type === 'deployment_user_registered'\n}\n\n/** The portal origins a \"Manage users\" link may open by default. Anything else gets no button. */\nexport const ALLOWED_PORTAL_ORIGINS: readonly string[] = ['https://portal.arbicity.com']\n\n/** The portal link, only when it is https on an allowed portal origin. */\nexport function safePortalUrl(\n value: unknown,\n origins: readonly string[] = ALLOWED_PORTAL_ORIGINS\n): string | undefined {\n if (typeof value !== 'string') return undefined\n try {\n const url = new URL(value)\n if (url.protocol !== 'https:' || !origins.includes(url.origin)) return undefined\n return url.href\n } catch {\n return undefined\n }\n}\n\n/** Plaintext content of a deployment-user notification: `{email, user_type, portal_url}`. */\nexport function deploymentUserMeta(\n content: string | null | undefined,\n origins: readonly string[] = ALLOWED_PORTAL_ORIGINS\n): { email?: string; external: boolean; portalUrl?: string } {\n const meta = parse(content)\n if (!meta) return { external: false }\n const email = typeof meta.email === 'string' && meta.email.trim() ? meta.email.trim() : undefined\n return {\n email,\n external: meta.user_type === 'external',\n portalUrl: safePortalUrl(meta.portal_url, origins),\n }\n}\n\n/** A document's display name, as a document list shows it (its title, else its file name). */\nexport function documentDisplayName(\n doc:\n | { file_name?: string | null; doc_metadata?: { title?: string | null } | null }\n | null\n | undefined\n): string | undefined {\n return doc?.doc_metadata?.title || doc?.file_name || undefined\n}\n\n/** What the work notifications say in a list, where the sender has a column of their own. */\nexport const WORK_NOTIFICATION_LABELS: Readonly<Record<string, string>> = {\n conversation_ready: 'A task is ready',\n conversation_done: 'A task was marked done',\n conversation_notified: 'You were notified in a thread',\n workflow_failed: 'A workflow failed to run',\n}\n\nfunction conversationTarget(n: NotificationResponse): NotificationTarget | undefined {\n if (!n.conversation_ext_id || !CONVERSATION_ID.test(n.conversation_ext_id)) return undefined\n return {\n kind: 'conversation',\n workspaceId: n.workspace_ext_id ?? undefined,\n conversationId: n.conversation_ext_id,\n ...(n.message_ext_id ? { messageId: n.message_ext_id } : {}),\n }\n}\n\n/** The workflows page on the notification's workflow (`{workflow_ext_id}` in its content). */\nfunction workflowTarget(n: NotificationResponse): NotificationTarget {\n const workflowId = parse(n.content)?.workflow_ext_id\n return {\n kind: 'workflows',\n ...(typeof workflowId === 'string' && WORKFLOW_ID.test(workflowId) ? { workflowId } : {}),\n ...(n.workspace_ext_id ? { workspaceId: n.workspace_ext_id } : {}),\n }\n}\n\nfunction signatureTitle(\n n: NotificationResponse,\n senderName: string,\n documentName: DescribeServerNotificationOptions['documentName']\n): string {\n const type = n.type as SignatureNotificationType\n const { documentId } = signatureRequestMeta(n.content)\n const name = documentId ? documentName?.(n.workspace_ext_id, documentId) : undefined\n const fallback = type === 'signature_requested' ? 'a document' : 'your document'\n const { verb, tail } = signatureNotificationPhrase(type, true)\n return `${senderName} ${verb} ${name ?? fallback}${tail}`\n}\n\nconst DATABASE_ID = /^dbs-[a-zA-Z0-9]{8}$/\nconst ROW_ID = /^dbr-[a-zA-Z0-9]{8}$/\n\n/** A request row to open (`{database_id, row_id}` in a notification's content), when well formed. */\nfunction databaseTarget(\n n: NotificationResponse,\n meta: Record<string, unknown> | null\n): Extract<NotificationTarget, { kind: 'database' }> | undefined {\n const databaseId = meta?.database_id\n const rowId = meta?.row_id\n if (typeof databaseId !== 'string' || !DATABASE_ID.test(databaseId)) return undefined\n return {\n kind: 'database',\n databaseId,\n ...(typeof rowId === 'string' && ROW_ID.test(rowId) ? { rowId } : {}),\n ...(n.workspace_ext_id ? { workspaceId: n.workspace_ext_id } : {}),\n }\n}\n\n/** The run a workflow notification is about, from the recipient's side: \"your\" or \"Sam Lee\u2019s\". */\nfunction runOwner(n: NotificationResponse, senderName: string): string {\n return n.sender.external_id === n.recipient?.external_id ? 'your' : `${senderName}\u2019s`\n}\n\n/**\n * What a `step_ready` says: a step of a workflow run needs the recipient. Its content is\n * `{conversation_ext_id, step, workflow_ext_id, reason}` (`reason`: ready, sent_back, reminder,\n * finished); the step's title is encrypted in the run, so the sentence names the run's owner only.\n * An approval step adds its request (`database_id`, `row_id`), which it opens directly.\n */\nexport function stepReadyTitle(n: NotificationResponse, senderName: string): string {\n const meta = parse(n.content)\n const run = `${runOwner(n, senderName)} workflow`\n const reason = meta?.reason\n if (meta?.action === 'approval' && reason !== 'sent_back' && reason !== 'finished')\n return reason === 'reminder'\n ? `A request in ${run} is still waiting for your decision`\n : `A request in ${run} needs your decision`\n switch (reason) {\n case 'sent_back':\n return `A step in ${run} was sent back to you`\n case 'reminder':\n return `A step in ${run} is still waiting for you`\n case 'finished':\n return `A step assigned to you in ${run} finished`\n default:\n return `A step in ${run} is ready for you`\n }\n}\n\nfunction quotaPercent(type: string): number | null {\n if (type === 'quota_threshold_100') return 100\n if (type === 'quota_threshold_90') return 90\n if (type === 'quota_threshold_50') return 50\n return null\n}\n\n/**\n * One server notification \u2192 what it says to its recipient and where it leads, or null for\n * types without a sentence here (calendar events, sync completions: they have their own\n * surfaces).\n */\nexport function describeServerNotification(\n n: NotificationResponse,\n options: DescribeServerNotificationOptions = {}\n): ServerNotificationDescription | null {\n const senderName = options.senderName ?? notificationUserName(n.sender)\n const workspace: NotificationTarget | undefined = n.workspace_ext_id\n ? { kind: 'workspace', workspaceId: n.workspace_ext_id }\n : undefined\n const type = n.type as string\n\n if (type === BOX_SEAT_REFUSED) {\n return {\n title: BOX_SEAT_REFUSED_TITLE,\n variant: 'warning',\n actionLabel: BOX_SEAT_REFUSED_ACTION,\n target: { kind: 'seats' },\n }\n }\n const pct = quotaPercent(type)\n if (pct !== null) {\n return {\n title: `You have used ${pct}% of your daily AI limit for this project.`,\n variant: pct === 100 ? 'error' : pct === 90 ? 'warning' : 'info',\n target: { kind: 'projects' },\n }\n }\n\n switch (type) {\n case 'support_ticket_received':\n case 'support_ticket_reviewed':\n case 'support_ticket_resolved': {\n const ticketId = parse(n.content)?.ticket_id\n if (typeof ticketId !== 'number' || !Number.isSafeInteger(ticketId) || ticketId < 1)\n return null\n const suppliedReference = parse(n.content)?.ticket_reference\n const reference =\n typeof suppliedReference === 'string' &&\n /^[a-z0-9-]+-[0-9]+$/.test(suppliedReference) &&\n suppliedReference.endsWith(`-${ticketId}`)\n ? suppliedReference\n : `#${ticketId}`\n return {\n title:\n type === 'support_ticket_received'\n ? `We received support request ${reference}`\n : type === 'support_ticket_reviewed'\n ? `We have reviewed support request ${reference}`\n : `Support request ${reference} is resolved`,\n variant: 'success',\n actionLabel: type === 'support_ticket_resolved' ? 'View outcome' : 'View request',\n target: { kind: 'support', ticketId },\n }\n }\n // A request waiting for this approver's decision, or a decision on the recipient's request: ids only\n // (`{database_id, row_id, column_id}`); the row opens in its database.\n case 'database_row_submitted':\n case 'database_row_decided': {\n const target = databaseTarget(n, parse(n.content))\n if (!target) return null\n const submitted = type === 'database_row_submitted'\n return {\n title: submitted\n ? `${senderName} submitted a request for your decision`\n : `${senderName} decided your request`,\n variant: 'info',\n actionLabel: submitted ? 'Review' : 'Open',\n target,\n }\n }\n // A workflow step needs the recipient. An approval opens its request; any other step the run's\n // thread, where the step is.\n case 'step_ready': {\n const meta = parse(n.content)\n const request = meta?.action === 'approval' ? databaseTarget(n, meta) : undefined\n const reminder = meta?.reason === 'reminder'\n return {\n title: stepReadyTitle(n, senderName),\n variant: reminder ? 'warning' : 'info',\n ...(request\n ? { actionLabel: 'Review', target: request }\n : { target: conversationTarget(n) ?? workflowTarget(n) }),\n }\n }\n // A step of the recipient's own run raised a named signal (a config name, not content).\n case 'workflow_signal': {\n const signal = parse(n.content)?.signal\n return {\n title:\n typeof signal === 'string' && signal\n ? `A workflow step raised the \u201C${signal}\u201D signal`\n : 'A workflow step raised a signal',\n variant: 'info',\n target: conversationTarget(n) ?? workflowTarget(n),\n }\n }\n // A shared file opens in the direct chat with the person on the other side.\n case 'file_shared': {\n const meta = fileShareNotificationMeta(n.content)\n if (!meta) return null\n const { event } = meta\n return {\n title: FILE_SHARE_TITLES[event](senderName),\n variant:\n event === 'declined'\n ? 'warning'\n : event === 'completed' || event === 'signed'\n ? 'success'\n : 'info',\n actionLabel: event === 'signature-requested' ? 'Review and sign' : 'Open file',\n target: {\n kind: 'file-share',\n shareId: meta.shareId,\n senderId: n.sender.external_id,\n recipientId: n.recipient.external_id,\n },\n }\n }\n // One upload action finished (however many batches it was sent and processed in). A failed\n // document is where it leads when there is one; otherwise the workspace.\n case 'upload_set_complete': {\n const meta = uploadSetMeta(n.content)\n const problems = meta.failed + meta.notUploaded\n const failed = meta.failedDocumentIds\n return {\n title: uploadSetTitle(n.content),\n variant: problems ? 'warning' : 'success',\n ...(failed.length === 1\n ? {\n actionLabel: 'Open failed document',\n target: {\n kind: 'document' as const,\n workspaceId: n.workspace_ext_id ?? undefined,\n documentId: failed[0],\n },\n }\n : { target: workspace }),\n }\n }\n case 'call_missed':\n return {\n title: `Missed call from ${senderName}`,\n variant: 'warning',\n actionLabel: 'Call back',\n target: { kind: 'call-back', user: n.sender },\n }\n case 'native_mail_received':\n return {\n title: 'New email in your encrypted inbox',\n variant: 'info',\n target: { kind: 'mail' },\n }\n case 'mail_draft_ready': {\n const draftId = mailDraftIdFromContent(n.content)\n return {\n title: `${senderName} left a draft email for you to review`,\n variant: 'info',\n target: { kind: 'mail', ...(draftId ? { draftId } : {}) },\n }\n }\n case 'workspaceuser_added_owner':\n return { title: `${senderName} added you as owner`, variant: 'info', target: workspace }\n case 'workspaceuser_added_collaborator':\n return {\n title: `${senderName} added you as collaborator`,\n variant: 'info',\n target: workspace,\n }\n case 'workspaceuser_added_guest':\n return { title: `${senderName} added you as a viewer`, variant: 'info', target: workspace }\n case 'workspaceuser_removed':\n return { title: `${senderName} removed you from a workspace`, variant: 'warning' }\n case 'workspaceuser_updated_owner':\n return {\n title: `${senderName} changed your role to owner`,\n variant: 'info',\n target: workspace,\n }\n case 'workspaceuser_updated_collaborator':\n return {\n title: `${senderName} changed your role to collaborator`,\n variant: 'info',\n target: workspace,\n }\n case 'workspaceuser_updated_guest':\n return {\n title: `${senderName} changed your role to viewer`,\n variant: 'info',\n target: workspace,\n }\n case 'signature_requested':\n case 'signature_completed':\n case 'signature_declined': {\n const { documentId, version } = signatureRequestMeta(n.content)\n return {\n title: signatureTitle(n, senderName, options.documentName),\n variant:\n type === 'signature_completed'\n ? 'success'\n : type === 'signature_declined'\n ? 'warning'\n : 'info',\n actionLabel: type === 'signature_requested' ? 'Review and sign' : 'Open',\n // A request opens the current version on its PDF, where the banner offers \"Review and\n // sign\"; a completed request opens the signed copy.\n target: documentId\n ? {\n kind: 'document',\n workspaceId: n.workspace_ext_id ?? undefined,\n documentId,\n ...(version ? { version } : {}),\n tab: 'pdf',\n }\n : undefined,\n }\n }\n case 'docx_mention': {\n const { documentId, commentId } = docxMentionMeta(n.content)\n return {\n title: `${senderName} mentioned you in a document comment`,\n variant: 'info',\n target: documentId\n ? {\n kind: 'document',\n workspaceId: n.workspace_ext_id ?? undefined,\n documentId,\n ...(commentId ? { commentId } : {}),\n }\n : undefined,\n }\n }\n case 'agent_input_requested':\n return { title: inputRequestTitle(n.content), variant: 'info', target: conversationTarget(n) }\n case 'mention':\n return {\n title: `${senderName} mentioned you in a conversation`,\n variant: 'info',\n target: conversationTarget(n),\n }\n case 'thread_reply':\n return {\n title: `${senderName} replied in a thread`,\n variant: 'info',\n target: conversationTarget(n),\n }\n case 'document_activity': {\n const { documentId, version } = documentActivityMeta(n.content)\n return {\n title: `${senderName} ${documentActivityPhrase(n.content)}`,\n variant: 'info',\n target: documentId\n ? {\n kind: 'document',\n workspaceId: n.workspace_ext_id ?? undefined,\n documentId,\n ...(version ? { version } : {}),\n }\n : undefined,\n }\n }\n // Each of these opens the thread, so the person it is for finds it. One about your own thread\n // (you started the work) says so.\n case 'conversation_ready':\n return {\n title:\n n.sender.external_id === n.recipient.external_id\n ? 'Your thread is ready'\n : `${senderName}\u2019s thread is ready`,\n variant: 'info',\n target: conversationTarget(n),\n }\n case 'conversation_notified':\n return {\n title: `${senderName} notified you in a thread`,\n variant: 'info',\n target: conversationTarget(n),\n }\n case 'conversation_done':\n return {\n title: `${senderName} marked a thread done`,\n variant: 'success',\n target: conversationTarget(n),\n }\n case 'workflow_completed':\n return { title: 'A workflow completed', variant: 'success', target: workflowTarget(n) }\n // The failed run's thread when it has one (its error is there), else the workflow.\n case 'workflow_failed':\n return {\n title: 'A workflow failed to start',\n variant: 'error',\n target: conversationTarget(n) ?? workflowTarget(n),\n }\n case 'deployment_user_invited':\n case 'deployment_user_registered': {\n const { email, external, portalUrl } = deploymentUserMeta(n.content, options.portalOrigins)\n const suffix = external ? ' \u00B7 External' : ''\n return {\n title:\n type === 'deployment_user_invited'\n ? `${senderName} invited ${email ?? 'a new user'}${suffix}`\n : `${email ?? senderName} joined${suffix}`,\n variant: 'info',\n ...(portalUrl && {\n actionLabel: 'Manage users',\n target: { kind: 'url' as const, url: portalUrl },\n }),\n }\n }\n // Someone shared a document into a workspace the recipient owns or follows (e.g. a skill\n // published to the marketplace): its owner may review it.\n case 'doc_shared':\n return {\n title: `${senderName} shared a document into a workspace`,\n variant: 'info',\n target: workspace,\n }\n case 'contact_accepted':\n return { title: `${senderName} joined the platform`, variant: 'success', target: workspace }\n case 'workspace_access_request':\n return {\n title: `${senderName} asked for workspace access`,\n variant: 'info',\n // Straight into the review \u2014 granting needs a workspace choice and a role, so a bare\n // \"grant\" action could never be right here.\n target: { kind: 'access-request', notification: n },\n }\n case 'project_quota_warning': {\n let resource = 'usage'\n let percentage: number | null = null\n let upgrade = ''\n let impending = false\n try {\n const data = JSON.parse(n.content ?? '{}')\n resource = data.resource === 'storage_gb' ? 'storage' : 'AI credits'\n if (data.limit > 0) percentage = Math.round((data.used / data.limit) * 100)\n if (data.stage === 'before_upgrade') {\n impending = true\n const charge = new Intl.NumberFormat('en-GB', {\n style: 'currency',\n currency: data.currency || 'GBP',\n }).format(data.charge_ex_vat_pence / 100)\n upgrade = `An automatic ${resource} upgrade will now be attempted: ${charge} ex VAT.`\n } else if (data.automatic_upgrade === true) {\n upgrade =\n ' An automatic upgrade is available within your limit and will be attempted when needed, subject to payment.'\n } else if (data.automatic_upgrade === false) {\n upgrade =\n data.upgrade_reason === 'limit'\n ? ' No automatic upgrade fits your remaining limit. Increase it or add allowances to keep working.'\n : data.upgrade_reason === 'payment'\n ? ' Automatic upgrades are paused. Resolve your payment issue to keep working.'\n : ' Automatic upgrades are unavailable. Upgrade your plan or reduce usage to keep working.'\n }\n } catch {\n /* An old or malformed notice still opens project usage. */\n }\n return {\n title: impending\n ? upgrade\n : `Your project is approaching its ${resource} limit${percentage != null ? ` (${percentage}% used)` : ''}.${upgrade}`,\n variant: 'warning',\n target: { kind: 'projects' },\n }\n }\n case 'project_retention': {\n let deadline = ''\n try {\n const data = JSON.parse(n.content ?? '{}')\n if (data.deletion_at) deadline = new Date(data.deletion_at).toLocaleDateString('en-GB')\n } catch {\n /* display the recovery notice without a date */\n }\n return {\n title: `Your project subscription has ended. Export or resubscribe${deadline ? ` before ${deadline}` : ''} to keep its data.`,\n variant: 'warning',\n target: { kind: 'projects' },\n }\n }\n case 'storage_quota_exceeded':\n return {\n title:\n 'Your storage is full. Mail still arrives, but new uploads and attachments are paused until you free space or add storage.',\n variant: 'error',\n target: { kind: 'storage' },\n }\n case 'signup_reward':\n return {\n title: n.content ? `\uD83C\uDF89 Signup bonus \u2014 ${n.content}` : '\uD83C\uDF89 You earned a signup bonus!',\n variant: 'success',\n target: { kind: 'projects' },\n }\n case 'referral_reward':\n return {\n title: n.content ? `\uD83C\uDF81 Reward \u2014 ${n.content}` : '\uD83C\uDF81 You earned a reward!',\n variant: 'success',\n target: { kind: 'projects' },\n }\n default:\n return null\n }\n}\n"],
5
+ "mappings": "AAWA,SAAS,8BAA8B;AAkEhC,SAAS,qBAAqB,MAAgC;AACnE,SAAO,CAAC,KAAK,YAAY,KAAK,WAAW,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG,KAAK,KAAK;AAC/E;AAEA,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,cAAc;AACpB,MAAM,gBAAgB;AAEtB,SAAS,MAAM,SAAoE;AACjF,MAAI;AACF,UAAM,QAAQ,KAAK,MAAM,WAAW,IAAI;AACxC,WAAO,SAAS,OAAO,UAAU,WAAY,QAAoC;AAAA,EACnF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAYO,SAAS,0BACd,SACmD;AACnD,QAAM,OAAO,MAAM,OAAO;AAC1B,QAAM,UAAU,MAAM;AACtB,MAAI,OAAO,YAAY,YAAY,CAAC,cAAc,KAAK,OAAO,EAAG,QAAO;AACxE,QAAM,QACJ,MAAM,aAAa,OACf,aACA,MAAM,cAAc,OAClB,cACA,MAAM,WAAW,OACf,WACA,MAAM,cAAc,OAClB,wBACA;AACZ,SAAO,EAAE,SAAS,MAAM;AAC1B;AAEA,MAAM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AQ;AAAA,MAER;AACA,aAAO;AAAA,QACL,OAAO,6DAA6D,WAAW,WAAW,QAAQ,KAAK,EAAE;AAAA,QACzG,SAAS;AAAA,QACT,QAAQ,EAAE,MAAM,WAAW;AAAA,MAC7B;AAAA,IACF;AAAA,IACA,KAAK;AACH,aAAO;AAAA,QACL,OACE;AAAA,QACF,SAAS;AAAA,QACT,QAAQ,EAAE,MAAM,UAAU;AAAA,MAC5B;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,OAAO,EAAE,UAAU,iCAAqB,EAAE,OAAO,KAAK;AAAA,QACtD,SAAS;AAAA,QACT,QAAQ,EAAE,MAAM,WAAW;AAAA,MAC7B;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,OAAO,EAAE,UAAU,2BAAe,EAAE,OAAO,KAAK;AAAA,QAChD,SAAS;AAAA,QACT,QAAQ,EAAE,MAAM,WAAW;AAAA,MAC7B;AAAA,IACF;AACE,aAAO;AAAA,EACX;AACF;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arbidocs/react",
3
- "version": "0.5.149",
3
+ "version": "0.5.151",
4
4
  "description": "React hooks and provider for the ARBI SDK",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -117,8 +117,8 @@
117
117
  "build-storybook": "storybook build"
118
118
  },
119
119
  "dependencies": {
120
- "@arbidocs/client": "0.5.149",
121
- "@arbidocs/sdk": "0.5.149",
120
+ "@arbidocs/client": "0.5.151",
121
+ "@arbidocs/sdk": "0.5.151",
122
122
  "@didit-protocol/sdk-web": "0.4.0",
123
123
  "@livekit/components-react": "2.9.24",
124
124
  "@radix-ui/react-avatar": "^1.2.0",
@@ -1,264 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkP2DPOZBS_cjs = require('./chunk-P2DPOZBS.cjs');
4
- var chunkKULS4YWP_cjs = require('./chunk-KULS4YWP.cjs');
5
- var react = require('react');
6
- var jsxRuntime = require('react/jsx-runtime');
7
-
8
- function uploadQueryString(query) {
9
- const params = new URLSearchParams();
10
- for (const [key, value] of Object.entries(query)) {
11
- if (value === null || value === void 0) continue;
12
- for (const item of Array.isArray(value) ? value : [value]) params.append(key, String(item));
13
- }
14
- return params.toString();
15
- }
16
- function downloadBlob(blob, fileName) {
17
- const url = URL.createObjectURL(blob);
18
- const a = document.createElement("a");
19
- a.href = url;
20
- a.download = fileName;
21
- document.body.appendChild(a);
22
- a.click();
23
- a.remove();
24
- setTimeout(() => URL.revokeObjectURL(url), 6e4);
25
- }
26
- function clientUpload(client) {
27
- return async ({ file, query }) => {
28
- const formData = new FormData();
29
- formData.append("files", file);
30
- const { data, response } = await client.POST("/v1/document/upload", {
31
- params: { query },
32
- // The schema types the multipart body as `{ files: string[] }`; the FormData is sent as is.
33
- body: formData,
34
- bodySerializer: () => formData
35
- });
36
- if (!response.ok) throw new Error(`Upload failed with status ${response.status}`);
37
- return data;
38
- };
39
- }
40
- function defaultCertificateUrl(reference) {
41
- const origin = typeof location === "undefined" ? "" : location.origin;
42
- return `${origin}/verify/${encodeURIComponent(reference)}`;
43
- }
44
- function certificateLink(signature, certificateUrl) {
45
- if (certificateUrl) return certificateUrl(signature.reference);
46
- return signature.certificate_url || defaultCertificateUrl(signature.reference);
47
- }
48
- var DocumentToolsContext = react.createContext(null);
49
- function DocumentToolsProvider({ children, ...env }) {
50
- const arbiDeploymentDomain = chunkP2DPOZBS_cjs.useDeploymentDomain();
51
- const guards = react.useRef(/* @__PURE__ */ new Map());
52
- const pendingFlushes = react.useRef(/* @__PURE__ */ new Map());
53
- const registerBeforeFileShare = react.useCallback((id, flush) => {
54
- guards.current.set(id, flush);
55
- return () => {
56
- if (guards.current.get(id) !== flush) return;
57
- guards.current.delete(id);
58
- const pending = flush();
59
- pendingFlushes.current.set(id, pending);
60
- void pending.then(
61
- () => {
62
- if (pendingFlushes.current.get(id) === pending) pendingFlushes.current.delete(id);
63
- },
64
- () => {
65
- }
66
- );
67
- };
68
- }, []);
69
- const prepareFileShare = react.useCallback(async (id) => {
70
- const guard = guards.current.get(id);
71
- if (guard) {
72
- await guard();
73
- pendingFlushes.current.delete(id);
74
- } else await pendingFlushes.current.get(id);
75
- }, []);
76
- const {
77
- client,
78
- deploymentDomain,
79
- user,
80
- notify,
81
- openDocument,
82
- onDocumentsChanged,
83
- uploadDocument,
84
- saveFile,
85
- emailDocument,
86
- certificateUrl
87
- } = env;
88
- const value = react.useMemo(
89
- () => ({
90
- client,
91
- prepareFileShare,
92
- registerBeforeFileShare,
93
- deploymentDomain: deploymentDomain ?? arbiDeploymentDomain,
94
- user,
95
- openDocument,
96
- onDocumentsChanged,
97
- emailDocument,
98
- notify: notify ?? (() => {
99
- }),
100
- saveFile: saveFile ?? downloadBlob,
101
- uploadDocument: uploadDocument ?? clientUpload(client),
102
- certificateUrl
103
- }),
104
- [
105
- client,
106
- prepareFileShare,
107
- registerBeforeFileShare,
108
- deploymentDomain,
109
- arbiDeploymentDomain,
110
- user,
111
- notify,
112
- openDocument,
113
- onDocumentsChanged,
114
- uploadDocument,
115
- saveFile,
116
- emailDocument,
117
- certificateUrl
118
- ]
119
- );
120
- return /* @__PURE__ */ jsxRuntime.jsx(DocumentToolsContext.Provider, { value, children });
121
- }
122
- function useOptionalDocumentTools() {
123
- return react.useContext(DocumentToolsContext);
124
- }
125
- function useDocumentTools() {
126
- const env = react.useContext(DocumentToolsContext);
127
- if (!env) throw new Error("The document tools must be used within a <DocumentToolsProvider>");
128
- return env;
129
- }
130
-
131
- // src/document-tools/document-pdf.ts
132
- var DocumentFetchError = class extends Error {
133
- status;
134
- constructor(message, status) {
135
- super(message);
136
- this.name = "DocumentFetchError";
137
- this.status = status;
138
- }
139
- };
140
- async function fetchDocumentBytes(client, endpoint, documentRef, options, headers, what) {
141
- const ref = chunkKULS4YWP_cjs.parseVersionRef(documentRef);
142
- const version = options.version ?? ref.version;
143
- const { data, response } = await client.GET(endpoint, {
144
- params: {
145
- path: { document_ext_id: ref.docId },
146
- query: {
147
- ...version ? { version } : {},
148
- ...options.workspaceExtId ? { workspace_ext_id: options.workspaceExtId } : {}
149
- }
150
- },
151
- headers,
152
- parseAs: "blob",
153
- signal: options.signal
154
- });
155
- if (!response.ok || !(data instanceof Blob)) {
156
- throw new DocumentFetchError(
157
- `${what} could not be loaded (${response.status})`,
158
- response.status
159
- );
160
- }
161
- return { blob: data, response };
162
- }
163
- function contentDispositionFileName(header) {
164
- if (!header) return void 0;
165
- const extended = /filename\*\s*=\s*(?:[\w-]+)?'[^']*'([^;]+)/i.exec(header);
166
- if (extended) {
167
- try {
168
- return decodeURIComponent(extended[1].trim().replace(/^"|"$/g, "")) || void 0;
169
- } catch {
170
- }
171
- }
172
- const plain = /filename\s*=\s*("((?:[^"\\]|\\.)*)"|[^;]+)/i.exec(header);
173
- if (!plain) return void 0;
174
- const name = plain[2] !== void 0 ? plain[2].replace(/\\(.)/g, "$1") : plain[1].trim();
175
- return name || void 0;
176
- }
177
- async function fetchDocumentPdf(client, documentRef, options = {}) {
178
- const { blob } = await fetchDocumentBytes(
179
- client,
180
- "/v1/document/{document_ext_id}/view",
181
- documentRef,
182
- options,
183
- { Accept: "application/pdf" },
184
- "The PDF"
185
- );
186
- return blob;
187
- }
188
- async function fetchDocumentFile(client, documentRef, options = {}) {
189
- const { blob, response } = await fetchDocumentBytes(
190
- client,
191
- "/v1/document/{document_ext_id}/download",
192
- documentRef,
193
- options,
194
- {},
195
- "The file"
196
- );
197
- const name = contentDispositionFileName(response.headers.get("Content-Disposition"));
198
- return name ? new File([blob], name, { type: blob.type }) : blob;
199
- }
200
-
201
- // src/document-tools/markup-download.ts
202
- var SIGNED_LOCKED_REASON = "Signed documents can't be changed \u2014 download the signed file instead";
203
- function isSignedVersion(doc, version) {
204
- const n = version ?? doc.current_version ?? 1;
205
- return (doc.versions ?? []).some((v) => v.n === n && v.reason === "signed");
206
- }
207
- var MarkupDownloadError = class extends Error {
208
- constructor(message, status) {
209
- super(message);
210
- this.status = status;
211
- this.name = "MarkupDownloadError";
212
- }
213
- status;
214
- };
215
- function currentHasMarkup(doc) {
216
- const n = doc.current_version ?? 1;
217
- return (doc.versions ?? []).some((v) => v.n === n && (v.markup_count ?? 0) > 0);
218
- }
219
- async function fetchMarkupPdf(client, documentId, version, workspaceExtId) {
220
- const { data, response } = await client.GET("/v1/document/{document_ext_id}/markup/pdf", {
221
- params: {
222
- path: { document_ext_id: documentId },
223
- query: {
224
- ...version ? { version } : {},
225
- ...workspaceExtId ? { workspace_ext_id: workspaceExtId } : {}
226
- }
227
- },
228
- parseAs: "blob"
229
- });
230
- if (!response.ok || !data) {
231
- throw new MarkupDownloadError(
232
- response.status === 404 ? "This document has no markup yet" : (
233
- // The server refuses a signed version: its PDF takes no more changes.
234
- response.status === 409 ? SIGNED_LOCKED_REASON : "The markup could not be downloaded"
235
- ),
236
- response.status
237
- );
238
- }
239
- const disposition = response.headers.get("content-disposition") ?? "";
240
- const utf8 = /filename\*=UTF-8''([^;]+)/i.exec(disposition)?.[1];
241
- const plain = /filename="([^"]+)"/i.exec(disposition)?.[1];
242
- const fileName = utf8 ? decodeURIComponent(utf8) : plain ?? "markup.pdf";
243
- return { blob: data, fileName };
244
- }
245
-
246
- exports.DocumentFetchError = DocumentFetchError;
247
- exports.DocumentToolsProvider = DocumentToolsProvider;
248
- exports.MarkupDownloadError = MarkupDownloadError;
249
- exports.SIGNED_LOCKED_REASON = SIGNED_LOCKED_REASON;
250
- exports.certificateLink = certificateLink;
251
- exports.clientUpload = clientUpload;
252
- exports.contentDispositionFileName = contentDispositionFileName;
253
- exports.currentHasMarkup = currentHasMarkup;
254
- exports.defaultCertificateUrl = defaultCertificateUrl;
255
- exports.downloadBlob = downloadBlob;
256
- exports.fetchDocumentFile = fetchDocumentFile;
257
- exports.fetchDocumentPdf = fetchDocumentPdf;
258
- exports.fetchMarkupPdf = fetchMarkupPdf;
259
- exports.isSignedVersion = isSignedVersion;
260
- exports.uploadQueryString = uploadQueryString;
261
- exports.useDocumentTools = useDocumentTools;
262
- exports.useOptionalDocumentTools = useOptionalDocumentTools;
263
- //# sourceMappingURL=chunk-ASL7H2TF.cjs.map
264
- //# sourceMappingURL=chunk-ASL7H2TF.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/document-tools/environment.tsx","../src/document-tools/document-pdf.ts","../src/document-tools/markup-download.ts"],"names":["createContext","useDeploymentDomain","useRef","useCallback","useMemo","jsx","useContext","parseVersionRef"],"mappings":";;;;;;;AAmEO,SAAS,kBAAkB,KAAA,EAAoC;AACpE,EAAA,MAAM,MAAA,GAAS,IAAI,eAAA,EAAgB;AACnC,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAChD,IAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,MAAA,EAAW;AAC3C,IAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,CAAM,OAAA,CAAQ,KAAK,IAAI,KAAA,GAAQ,CAAC,KAAK,CAAA,EAAG,MAAA,CAAO,MAAA,CAAO,GAAA,EAAK,MAAA,CAAO,IAAI,CAAC,CAAA;AAAA,EAC5F;AACA,EAAA,OAAO,OAAO,QAAA,EAAS;AACzB;AAqDO,SAAS,YAAA,CAAa,MAAY,QAAA,EAAwB;AAC/D,EAAA,MAAM,GAAA,GAAM,GAAA,CAAI,eAAA,CAAgB,IAAI,CAAA;AACpC,EAAA,MAAM,CAAA,GAAI,QAAA,CAAS,aAAA,CAAc,GAAG,CAAA;AACpC,EAAA,CAAA,CAAE,IAAA,GAAO,GAAA;AACT,EAAA,CAAA,CAAE,QAAA,GAAW,QAAA;AACb,EAAA,QAAA,CAAS,IAAA,CAAK,YAAY,CAAC,CAAA;AAC3B,EAAA,CAAA,CAAE,KAAA,EAAM;AACR,EAAA,CAAA,CAAE,MAAA,EAAO;AACT,EAAA,UAAA,CAAW,MAAM,GAAA,CAAI,eAAA,CAAgB,GAAG,GAAG,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A,QACL,GAAI,OAAA,GAAU,EAAE,OAAA,KAAY,EAAC;AAAA,QAC7B,GAAI,cAAA,GAAiB,EAAE,gBAAA,EAAkB,cAAA,KAAmB;AAAC;AAC/D,KACF;AAAA,IACA,OAAA,EAAS;AAAA,GACV,CAAA;AACD,EAAA,IAAI,CAAC,QAAA,CAAS,EAAA,IAAM,CAAC,IAAA,EAAM;AACzB,IAAA,MAAM,IAAI,mBAAA;AAAA,MACR,QAAA,CAAS,WAAW,GAAA,GAChB,iCAAA;AAAA;AAAA,QAEA,QAAA,CAAS,MAAA,KAAW,GAAA,GAClB,oBAAA,GACA;AAAA,OAAA;AAAA,MACN,QAAA,CAAS;AAAA,KACX;AAAA,EACF;AACA,EAAA,MAAM,WAAA,GAAc,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,qBAAqB,CAAA,IAAK,EAAA;AACnE,EAAA,MAAM,IAAA,GAAO,4BAAA,CAA6B,IAAA,CAAK,WAAW,IAAI,CAAC,CAAA;AAC/D,EAAA,MAAM,KAAA,GAAQ,qBAAA,CAAsB,IAAA,CAAK,WAAW,IAAI,CAAC,CAAA;AACzD,EAAA,MAAM,QAAA,GAAW,IAAA,GAAO,kBAAA,CAAmB,IAAI,IAAK,KAAA,IAAS,YAAA;AAC7D,EAAA,OAAO,EAAE,IAAA,EAAM,IAAA,EAAc,QAAA,EAAS;AACxC","file":"chunk-ASL7H2TF.cjs","sourcesContent":["/**\n * The host app's side of the document tools (markup, freeze, e-signing, versions): the one place\n * the tools reach the app. They never import a store, a router, a toast library or app API code;\n * the host passes what it has to `<DocumentToolsProvider>` and every optional field has a default.\n *\n * `client` is an openapi-fetch client for the ARBI API (`ArbiClient['fetch']` from\n * `@arbidocs/client`, or `arbi.getClient().fetch` from an `@arbidocs/sdk` `Arbi`), signed in with the\n * user's session; it carries the auth.\n */\n\nimport { createContext, useCallback, useContext, useMemo, useRef, type ReactNode } from 'react'\nimport type { ArbiClient, operations } from '@arbidocs/client'\nimport { useDeploymentDomain } from '../useArbi'\n\nexport type DocumentToolsClient = ArbiClient['fetch']\n\nexport type DocumentToolsNoticeKind = 'success' | 'error' | 'info' | 'warning'\n\nexport interface DocumentToolsNoticeOptions {\n /** A second line under the message. */\n description?: string\n /** One action button on the notice (\"Email it\"). */\n action?: { label: string; onClick: () => void }\n}\n\nexport type DocumentToolsNotify = (\n message: string,\n kind: DocumentToolsNoticeKind,\n options?: DocumentToolsNoticeOptions\n) => void\n\nexport interface DocumentToolsUser {\n /** The name marks are authored as and the signer's name is prefilled with. */\n name: string\n /** The sign-in email: signing re-derives the user's key from it and the password. */\n email?: string | null\n /** The user's id (usr-*): which fields of a signature request are theirs. */\n externalId?: string | null\n}\n\n/** What changed about a document, so the host can refresh its own lists and caches. */\nexport type DocumentChange =\n /** A version's markup got its first mark or lost its last one. */\n | 'markup'\n /** A signature was added: the document has a new current version. */\n | 'signed'\n /** A new document was made from it (a frozen copy). The ids are the NEW documents. */\n | 'copy'\n /** A new version was saved (the Word editor's Save version): the document's current version. */\n | 'version'\n\n/**\n * The `/v1/document/upload` query, typed from the API schema: `derived_from` is a list (a\n * production set is derived from every document in it), `shared` a boolean.\n */\nexport type DocumentUploadQuery = NonNullable<operations['upload_documents']['parameters']['query']>\n\nexport interface DocumentUploadRequest {\n file: File\n /** `/v1/document/upload` query: `derived_from`, `derived_role`, `shared`, `folder`. */\n query: DocumentUploadQuery\n}\n\n/**\n * The upload query as a URL query string, for a host that posts the upload itself (an XHR with\n * progress): a list repeats its key (`derived_from=a&derived_from=b`), empty values are left out.\n */\nexport function uploadQueryString(query: DocumentUploadQuery): string {\n const params = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (value === null || value === undefined) continue\n for (const item of Array.isArray(value) ? value : [value]) params.append(key, String(item))\n }\n return params.toString()\n}\n\nexport interface DocumentToolsEnvironment {\n client: DocumentToolsClient\n /**\n * The deployment domain the user's keys are derived for. Needed for signing. Default: the one\n * the host's `Arbi` computes (`arbi.getDeploymentDomain()`), if any.\n */\n deploymentDomain?: string\n /** The signed-in user; marks are authored as \"You\" without one, and signing is unavailable. */\n user?: DocumentToolsUser | null\n /** Surface a transient message. Default: none (errors still show inline where they can). */\n notify?: DocumentToolsNotify\n /** Open a document or a version reference (`doc-…@v2`): the copy just made, the signed copy. */\n openDocument?: (documentRef: string) => void\n /**\n * Documents changed on the server (see {@link DocumentChange}); refresh the host's lists. The\n * tools wait for it before opening the document, so a copy is listed when it opens.\n */\n onDocumentsChanged?: (documentIds: string[], change: DocumentChange) => void | Promise<void>\n /** Upload a derived copy. Default: `POST /v1/document/upload` through `client`. */\n uploadDocument?: (\n request: DocumentUploadRequest\n ) => Promise<{ doc_ext_ids?: string[] } | undefined>\n /** Save a file to the user's computer. Default: a temporary download link. */\n saveFile?: (blob: Blob, fileName: string) => void\n /** Email a document (offered once it is signed). Omitted: no \"Email it\". */\n emailDocument?: (documentRef: string) => void\n /**\n * The public page that checks a signature (the certificate) in this app. When given, \"View\n * certificate\" opens it in preference to the backend's `certificate_url` (which is on the\n * deployment domain, like the link embedded in the signed PDF). Without it: the backend's\n * `certificate_url`, else `/verify/{reference}` on this origin.\n */\n certificateUrl?: (reference: string) => string\n}\n\n/** The environment with every default filled in. */\nexport interface ResolvedDocumentToolsEnvironment extends DocumentToolsEnvironment {\n prepareFileShare: (documentId: string) => Promise<void>\n registerBeforeFileShare: (documentId: string, flush: () => Promise<void>) => () => void\n notify: DocumentToolsNotify\n saveFile: (blob: Blob, fileName: string) => void\n uploadDocument: (\n request: DocumentUploadRequest\n ) => Promise<{ doc_ext_ids?: string[] } | undefined>\n}\n\n/**\n * Save a blob through a temporary `<a download>`. The object URL is revoked a minute later, not at\n * once: revoking straight after `click()` can cancel the download (Safari, and large files\n * elsewhere) before the browser has read the blob.\n */\nexport function downloadBlob(blob: Blob, fileName: string): void {\n const url = URL.createObjectURL(blob)\n const a = document.createElement('a')\n a.href = url\n a.download = fileName\n document.body.appendChild(a)\n a.click()\n a.remove()\n setTimeout(() => URL.revokeObjectURL(url), 60_000)\n}\n\n/** The default upload: multipart `files` to `/v1/document/upload` through the API client. */\nexport function clientUpload(client: DocumentToolsClient) {\n return async ({ file, query }: DocumentUploadRequest) => {\n const formData = new FormData()\n formData.append('files', file)\n const { data, response } = await client.POST('/v1/document/upload', {\n params: { query },\n // The schema types the multipart body as `{ files: string[] }`; the FormData is sent as is.\n body: formData as unknown as { files: string[] },\n bodySerializer: () => formData,\n })\n if (!response.ok) throw new Error(`Upload failed with status ${response.status}`)\n return data\n }\n}\n\nexport function defaultCertificateUrl(reference: string): string {\n const origin = typeof location === 'undefined' ? '' : location.origin\n return `${origin}/verify/${encodeURIComponent(reference)}`\n}\n\n/**\n * Where \"View certificate\" goes for a signature: the host's `certificateUrl(reference)` when it\n * gives one, else the `certificate_url` the backend returned, else `/verify/{reference}` here.\n */\nexport function certificateLink(\n signature: { reference: string; certificate_url?: string | null },\n certificateUrl?: (reference: string) => string\n): string {\n if (certificateUrl) return certificateUrl(signature.reference)\n return signature.certificate_url || defaultCertificateUrl(signature.reference)\n}\n\nconst DocumentToolsContext = createContext<ResolvedDocumentToolsEnvironment | null>(null)\n\nexport interface DocumentToolsProviderProps extends DocumentToolsEnvironment {\n children: ReactNode\n}\n\nexport function DocumentToolsProvider({ children, ...env }: DocumentToolsProviderProps) {\n const arbiDeploymentDomain = useDeploymentDomain()\n const guards = useRef(new Map<string, () => Promise<void>>())\n const pendingFlushes = useRef(new Map<string, Promise<void>>())\n const registerBeforeFileShare = useCallback((id: string, flush: () => Promise<void>) => {\n guards.current.set(id, flush)\n return () => {\n if (guards.current.get(id) !== flush) return\n guards.current.delete(id)\n const pending = flush()\n pendingFlushes.current.set(id, pending)\n void pending.then(\n () => {\n if (pendingFlushes.current.get(id) === pending) pendingFlushes.current.delete(id)\n },\n () => {}\n )\n }\n }, [])\n const prepareFileShare = useCallback(async (id: string) => {\n const guard = guards.current.get(id)\n if (guard) {\n await guard()\n pendingFlushes.current.delete(id)\n } else await pendingFlushes.current.get(id)\n }, [])\n const {\n client,\n deploymentDomain,\n user,\n notify,\n openDocument,\n onDocumentsChanged,\n uploadDocument,\n saveFile,\n emailDocument,\n certificateUrl,\n } = env\n const value = useMemo<ResolvedDocumentToolsEnvironment>(\n () => ({\n client,\n prepareFileShare,\n registerBeforeFileShare,\n deploymentDomain: deploymentDomain ?? arbiDeploymentDomain,\n user,\n openDocument,\n onDocumentsChanged,\n emailDocument,\n notify: notify ?? (() => {}),\n saveFile: saveFile ?? downloadBlob,\n uploadDocument: uploadDocument ?? clientUpload(client),\n certificateUrl,\n }),\n [\n client,\n prepareFileShare,\n registerBeforeFileShare,\n deploymentDomain,\n arbiDeploymentDomain,\n user,\n notify,\n openDocument,\n onDocumentsChanged,\n uploadDocument,\n saveFile,\n emailDocument,\n certificateUrl,\n ]\n )\n return <DocumentToolsContext.Provider value={value}>{children}</DocumentToolsContext.Provider>\n}\n\n/** The host's environment, or `null` outside a `<DocumentToolsProvider>`. */\nexport function useOptionalDocumentTools(): ResolvedDocumentToolsEnvironment | null {\n return useContext(DocumentToolsContext)\n}\n\n/** The host's environment; throws outside a `<DocumentToolsProvider>`. */\nexport function useDocumentTools(): ResolvedDocumentToolsEnvironment {\n const env = useContext(DocumentToolsContext)\n if (!env) throw new Error('The document tools must be used within a <DocumentToolsProvider>')\n return env\n}\n","/**\n * A document's bytes, through the host's API client: the PDF the viewer and the tools draw on\n * (`/view`: the file itself for a PDF, its PDF rendering for a Word or text file) and the stored\n * file (`/download`). Either takes a document id or a version reference `doc-…@v{n}`.\n */\n\nimport { parseVersionRef } from '../artifacts/versions'\nimport type { DocumentToolsClient } from './environment'\n\nexport interface DocumentFetchOptions {\n /** The version to fetch. Default: the one `documentRef` names, else the current version. */\n version?: number | null\n workspaceExtId?: string\n signal?: AbortSignal\n}\n\n/** A document's bytes could not be fetched; `status` is the HTTP status. */\nexport class DocumentFetchError extends Error {\n readonly status: number\n constructor(message: string, status: number) {\n super(message)\n this.name = 'DocumentFetchError'\n this.status = status\n }\n}\n\nasync function fetchDocumentBytes(\n client: DocumentToolsClient,\n endpoint: '/v1/document/{document_ext_id}/view' | '/v1/document/{document_ext_id}/download',\n documentRef: string,\n options: DocumentFetchOptions,\n headers: Record<string, string>,\n what: string\n): Promise<{ blob: Blob; response: Response }> {\n const ref = parseVersionRef(documentRef)\n const version = options.version ?? ref.version\n const { data, response } = await client.GET(endpoint, {\n params: {\n path: { document_ext_id: ref.docId },\n query: {\n ...(version ? { version } : {}),\n ...(options.workspaceExtId ? { workspace_ext_id: options.workspaceExtId } : {}),\n },\n },\n headers,\n parseAs: 'blob',\n signal: options.signal,\n })\n if (!response.ok || !(data instanceof Blob)) {\n throw new DocumentFetchError(\n `${what} could not be loaded (${response.status})`,\n response.status\n )\n }\n return { blob: data, response }\n}\n\n/**\n * The file name a `Content-Disposition` header gives, or `undefined`. Prefers the RFC 5987\n * `filename*=UTF-8''…` form (percent-encoded, any script) over the plain `filename=`.\n */\nexport function contentDispositionFileName(header: string | null | undefined): string | undefined {\n if (!header) return undefined\n const extended = /filename\\*\\s*=\\s*(?:[\\w-]+)?'[^']*'([^;]+)/i.exec(header)\n if (extended) {\n try {\n return decodeURIComponent(extended[1].trim().replace(/^\"|\"$/g, '')) || undefined\n } catch {\n // A malformed escape: fall back to the plain parameter.\n }\n }\n const plain = /filename\\s*=\\s*(\"((?:[^\"\\\\]|\\\\.)*)\"|[^;]+)/i.exec(header)\n if (!plain) return undefined\n const name = plain[2] !== undefined ? plain[2].replace(/\\\\(.)/g, '$1') : plain[1].trim()\n return name || undefined\n}\n\n/**\n * The PDF of a document version: `GET /v1/document/{id}/view?version=` with\n * `Accept: application/pdf`. Throws a {@link DocumentFetchError} when there is none (yet).\n */\nexport async function fetchDocumentPdf(\n client: DocumentToolsClient,\n documentRef: string,\n options: DocumentFetchOptions = {}\n): Promise<Blob> {\n const { blob } = await fetchDocumentBytes(\n client,\n '/v1/document/{document_ext_id}/view',\n documentRef,\n options,\n { Accept: 'application/pdf' },\n 'The PDF'\n )\n return blob\n}\n\n/**\n * The stored file of a document version, as uploaded: `GET /v1/document/{id}/download`. When the\n * server names the file (`Content-Disposition`), the result is a `File` carrying that name.\n */\nexport async function fetchDocumentFile(\n client: DocumentToolsClient,\n documentRef: string,\n options: DocumentFetchOptions = {}\n): Promise<Blob | File> {\n const { blob, response } = await fetchDocumentBytes(\n client,\n '/v1/document/{document_ext_id}/download',\n documentRef,\n options,\n {},\n 'The file'\n )\n const name = contentDispositionFileName(response.headers.get('Content-Disposition'))\n return name ? new File([blob], name, { type: blob.type }) : blob\n}\n","/**\n * \"Download with markup\": a document version's markup PDF, the PDF with its annotations as native\n * PDF annotations (comments, highlights, stamps, unapplied redactions), which Acrobat and Preview\n * show. The plain Download serves the original. Kept apart from the annotation layer code so a\n * documents list can offer it without loading the annotation tools.\n *\n * A SIGNED version is locked: nothing but a further signature changes it. Its markup stays in the\n * separate markup layer (a title beside the signature, say) and is never written into its PDF, so\n * it has no \"Download with markup\"; the plain Download is the signed file as it is.\n */\n\nimport type { DocumentToolsClient } from './environment'\n\ninterface DocumentVersions {\n current_version?: number | null\n versions?: Array<{ n: number; markup_count?: number | null; reason?: string | null }> | null\n}\n\n/** Why \"Download with markup\" is off for a signed version. */\nexport const SIGNED_LOCKED_REASON =\n \"Signed documents can't be changed — download the signed file instead\"\n\n/** Whether a version (default: the current one) is a signed copy, per its version entry. */\nexport function isSignedVersion(doc: DocumentVersions, version?: number): boolean {\n const n = version ?? doc.current_version ?? 1\n return (doc.versions ?? []).some((v) => v.n === n && v.reason === 'signed')\n}\n\nexport class MarkupDownloadError extends Error {\n constructor(\n message: string,\n readonly status?: number\n ) {\n super(message)\n this.name = 'MarkupDownloadError'\n }\n}\n\n/** Whether a document's current version has markup (per its version entries). */\nexport function currentHasMarkup(doc: DocumentVersions): boolean {\n const n = doc.current_version ?? 1\n return (doc.versions ?? []).some((v) => v.n === n && (v.markup_count ?? 0) > 0)\n}\n\n/** Fetch a version's markup PDF (default: the current version's). */\nexport async function fetchMarkupPdf(\n client: DocumentToolsClient,\n documentId: string,\n version?: number,\n workspaceExtId?: string\n): Promise<{ blob: Blob; fileName: string }> {\n const { data, response } = await client.GET('/v1/document/{document_ext_id}/markup/pdf', {\n params: {\n path: { document_ext_id: documentId },\n query: {\n ...(version ? { version } : {}),\n ...(workspaceExtId ? { workspace_ext_id: workspaceExtId } : {}),\n },\n },\n parseAs: 'blob',\n })\n if (!response.ok || !data) {\n throw new MarkupDownloadError(\n response.status === 404\n ? 'This document has no markup yet'\n : // The server refuses a signed version: its PDF takes no more changes.\n response.status === 409\n ? SIGNED_LOCKED_REASON\n : 'The markup could not be downloaded',\n response.status\n )\n }\n const disposition = response.headers.get('content-disposition') ?? ''\n const utf8 = /filename\\*=UTF-8''([^;]+)/i.exec(disposition)?.[1]\n const plain = /filename=\"([^\"]+)\"/i.exec(disposition)?.[1]\n const fileName = utf8 ? decodeURIComponent(utf8) : (plain ?? 'markup.pdf')\n return { blob: data as Blob, fileName }\n}\n"]}