@happyvertical/smrt-messages 0.74.2 → 0.74.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{AttachmentCollection-CGec2YSV.js → AttachmentCollection-CyHqF9ON.js} +6 -6
- package/dist/chunks/{AttachmentCollection-CGec2YSV.js.map → AttachmentCollection-CyHqF9ON.js.map} +1 -1
- package/dist/chunks/{Email-Y-yGRo0V.js → Email-vipfIWe8.js} +6 -6
- package/dist/chunks/{Email-Y-yGRo0V.js.map → Email-vipfIWe8.js.map} +1 -1
- package/dist/chunks/{EmailAccountCollection-DcTLdiKa.js → EmailAccountCollection-kglDt9j9.js} +19 -19
- package/dist/chunks/{EmailAccountCollection-DcTLdiKa.js.map → EmailAccountCollection-kglDt9j9.js.map} +1 -1
- package/dist/chunks/{EmailCollection-5OpPUNze.js → EmailCollection-VqLlXxqw.js} +3 -3
- package/dist/chunks/{EmailCollection-5OpPUNze.js.map → EmailCollection-VqLlXxqw.js.map} +1 -1
- package/dist/chunks/{EmailFolder-BP12hy5A.js → EmailFolder-C-f8YIE4.js} +6 -6
- package/dist/chunks/{EmailFolder-BP12hy5A.js.map → EmailFolder-C-f8YIE4.js.map} +1 -1
- package/dist/chunks/{EmailFolderCollection-DcpG06kl.js → EmailFolderCollection-L8kkOwq_.js} +2 -2
- package/dist/chunks/{EmailFolderCollection-DcpG06kl.js.map → EmailFolderCollection-L8kkOwq_.js.map} +1 -1
- package/dist/chunks/{EmailSender-BvZigpW5.js → EmailSender-Dfrs3UoD.js} +2 -2
- package/dist/chunks/{EmailSender-BvZigpW5.js.map → EmailSender-Dfrs3UoD.js.map} +1 -1
- package/dist/chunks/{Message-Cp7S6fwo.js → Message-D-FgiSxn.js} +6 -6
- package/dist/chunks/{Message-Cp7S6fwo.js.map → Message-D-FgiSxn.js.map} +1 -1
- package/dist/chunks/{MessageCollection-BIh13Nyl.js → MessageCollection-iMnpnr3K.js} +2 -2
- package/dist/chunks/{MessageCollection-BIh13Nyl.js.map → MessageCollection-iMnpnr3K.js.map} +1 -1
- package/dist/chunks/{MessagingEndpointCollection-DVt9vV6U.js → MessagingEndpointCollection-VUEtqpJ9.js} +2 -2
- package/dist/chunks/{MessagingEndpointCollection-DVt9vV6U.js.map → MessagingEndpointCollection-VUEtqpJ9.js.map} +1 -1
- package/dist/connect.js +1 -1
- package/dist/index.js +16 -16
- package/dist/manifest.json +1 -1
- package/dist/smrt-knowledge.json +3 -3
- package/package.json +12 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Message-Cp7S6fwo.js","names":["result"],"sources":["../../src/models/Message.ts"],"sourcesContent":["import type {\n SmrtClassOptions,\n SmrtSaveOptions,\n} from '@happyvertical/smrt-core';\nimport {\n assertProtectedNotificationDelete,\n assertProtectedNotificationRetry,\n assertProtectedNotificationSave,\n assertProtectedSenderHandoff,\n beginProtectedNotificationSend,\n ProtectedNotificationHandoffError,\n rememberNotificationOrigin,\n} from '../protected-notification-handoff.js';\n/**\n * Message model - Base class for all message types (STI)\n *\n * Common fields shared across email, tweets, slack messages, etc.\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n crossPackageRef,\n field,\n foreignKey,\n ObjectRegistry,\n SmrtObject,\n smrt,\n toSnakeCase,\n usesEmbeddedRevisionFallback,\n withEmbeddedWriteQueue,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport {\n assertHydratedMailAccess,\n assertMailScopeOn,\n decideMailAccess,\n inMailSystemAccess,\n isMailWriteGated,\n isReceivedMail,\n learnMailAccessOptions,\n MailAccessError,\n type MailPrincipal,\n type MailScope,\n mailFlag,\n resolveMailPrincipal,\n} from '../access.js';\nimport {\n approvedDraftChanged,\n auditMailAction,\n holdAgentSend,\n stampHandledBy,\n} from '../send-approval.js';\nimport type {\n MessageOptions,\n MessageSendResult,\n SendMessageOptions,\n SendStatus,\n} from '../types';\n\n/** `metadata` key recording that the last failed send may have been accepted. */\nexport const SEND_OUTCOME_UNKNOWN_METADATA_KEY = 'sendOutcomeUnknown';\n\n/**\n * The stored metadata JSON with the outcome-unknown marker set or cleared, or\n * undefined when it needs no change (or is not a JSON object to edit).\n */\nfunction withSendOutcomeMarker(\n stored: unknown,\n outcomeUnknown: boolean,\n): string | undefined {\n let bag: Record<string, unknown> = {};\n if (typeof stored === 'string' && stored.trim()) {\n try {\n const parsed: unknown = JSON.parse(stored);\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return undefined;\n }\n bag = parsed as Record<string, unknown>;\n } catch {\n return undefined;\n }\n }\n if (Boolean(bag[SEND_OUTCOME_UNKNOWN_METADATA_KEY]) === outcomeUnknown) {\n return undefined;\n }\n if (outcomeUnknown) bag[SEND_OUTCOME_UNKNOWN_METADATA_KEY] = true;\n else delete bag[SEND_OUTCOME_UNKNOWN_METADATA_KEY];\n return JSON.stringify(bag);\n}\n\n// Only the canonical send/retry implementation can authorize its exact local\n// lifecycle save. An active provider scope never grants arbitrary public saves.\nconst lifecycleSaves = new WeakMap<Message, string>();\nfunction lifecycleSignature(message: Message): string {\n return JSON.stringify([\n message.sendStatus,\n message.retryCount,\n message.maxRetries,\n message.sendError,\n message.sentAt,\n message.scheduledSendAt,\n message.metadata,\n ]);\n}\nasync function saveSendLifecycle(message: Message): Promise<void> {\n lifecycleSaves.set(message, lifecycleSignature(message));\n try {\n await message.save();\n } finally {\n lifecycleSaves.delete(message);\n }\n}\n\n// Internal saves that already hold the `send` decision and may move a message\n// back to draft (a held send); they skip the draft-scope check.\nconst heldSaves = new WeakSet<Message>();\nasync function saveHeld(message: Message): Promise<void> {\n heldSaves.add(message);\n try {\n await message.save();\n } finally {\n heldSaves.delete(message);\n }\n}\n\n// Rows a service creates in the outgoing queue (the persona route). Only the\n// module-private helper below marks one, and only a fresh row is covered; it\n// then needs the `send` scope instead of `draft`, as the send that follows does.\nconst queuedCreates = new WeakSet<Message>();\n/** Internal: not exported from the package index. */\nexport async function saveQueuedForSend(message: Message): Promise<void> {\n queuedCreates.add(message);\n try {\n await message.save();\n } finally {\n queuedCreates.delete(message);\n }\n}\n\n/**\n * The only fields a send-path save of a draft may change: the send lifecycle,\n * the handled-by stamp and the revision. Everything else, including fields the\n * package does not know (tenant, slug, context, subclass fields), must equal\n * the stored row.\n */\nconst SEND_PATH_MAY_CHANGE = new Set([\n 'sendStatus',\n 'sentAt',\n 'sendError',\n 'retryCount',\n 'handledById',\n 'handledByKind',\n 'handledAt',\n 'updatedAt',\n // A row created in this process holds its in-memory timestamp, which the\n // stored one can differ from; the send path never reads it back.\n 'createdAt',\n 'created_at',\n]);\n\n/** Read and flagged state: not content a send transmits. */\nconst TRIAGE_MAY_CHANGE = new Set([\n 'isRead',\n 'isFlagged',\n 'updatedAt',\n 'createdAt',\n 'created_at',\n]);\n\ninterface DraftRequirements {\n /** `scope:accountId` pairs the write needs. */\n keys: Set<string>;\n /** A stored `sent` row moved out of `sent`: sent mail is a record. */\n refused: boolean;\n /** The send path's own save: a fresh row, or a stored row otherwise unchanged. */\n lifecycle: boolean;\n}\n\nconst emptyRequirements = (): DraftRequirements => ({\n keys: new Set(),\n refused: false,\n lifecycle: false,\n});\n\nconst DATE_LIKE =\n /^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$/;\n\n/** One comparable form of a field value, whether instance or stored row. */\nfunction canonValue(value: unknown): string {\n if (value === undefined || value === null) return '';\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? '' : value.toISOString();\n }\n if (typeof value === 'object') return JSON.stringify(value);\n if (typeof value === 'string') {\n if (DATE_LIKE.test(value)) {\n const time = Date.parse(value);\n if (!Number.isNaN(time)) return new Date(time).toISOString();\n }\n if (value.startsWith('[') || value.startsWith('{')) {\n try {\n return JSON.stringify(JSON.parse(value));\n } catch {\n return value;\n }\n }\n }\n return String(value);\n}\n\nconst DRAFT_CARRIED_FIELDS = new Set(['tenantId', 'metadata', 'correlationId']);\n\n/**\n * Stored fields declared by Message and Email. A derived reply/forward draft\n * starts without any of them; the registry adds subclass fields at runtime.\n */\nconst DRAFT_RESET_FIELDS = [\n 'accountId',\n 'personaId',\n 'endpointId',\n 'correlationId',\n 'threadId',\n 'subject',\n 'body',\n 'fromAddress',\n 'fromName',\n 'toAddresses',\n 'date',\n 'isRead',\n 'isFlagged',\n 'hasAttachments',\n 'size',\n 'metadata',\n 'sendStatus',\n 'sentAt',\n 'sendError',\n 'retryCount',\n 'maxRetries',\n 'scheduledSendAt',\n 'inReplyToMessageId',\n 'handledById',\n 'handledByKind',\n 'handledAt',\n 'createdAt',\n 'updatedAt',\n 'messageId',\n 'inReplyTo',\n 'providerMessageId',\n 'ccAddresses',\n 'bccAddresses',\n 'replyToAddress',\n 'replyToName',\n 'textBody',\n 'htmlBody',\n 'folderId',\n 'folderPath',\n 'labels',\n 'flags',\n 'isAnswered',\n 'isDraft',\n 'rawMessage',\n 'headers',\n];\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class Message extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n @foreignKey('Account')\n @field({\n description: 'The connected account used to receive or send this message.',\n })\n accountId = '';\n @crossPackageRef('@happyvertical/smrt-personas:AgentPersona', {\n nullable: true,\n })\n @field({\n description:\n 'The assistant identity associated with this message, when one was used.',\n })\n personaId: string | null = null;\n @foreignKey('MessagingEndpoint')\n @field({ description: 'The saved destination used to deliver this message.' })\n endpointId: string | null = null;\n @field({\n description:\n 'A tracking reference that connects this message to related activity.',\n })\n correlationId = '';\n @field({ description: 'The conversation this message belongs to.' })\n threadId = '';\n @field({ description: 'The subject shown in the message list.' })\n subject = '';\n @field({ description: 'The message content in plain text.' })\n body = ''; // Normalized plain text\n @field({ description: 'The address the message was sent from.' })\n fromAddress = '';\n @field({ description: 'The sender name shown beside their address.' })\n fromName = '';\n @field({ description: 'The people or addresses receiving this message.' })\n toAddresses = ''; // JSON array of {address, name}\n @field({ description: 'When the message was sent or received.' })\n date: Date | null = null;\n @field({ description: 'Whether this message has been marked as read.' })\n isRead = false;\n @field({ description: 'Whether this message is flagged for follow-up.' })\n isFlagged = false;\n @field({ description: 'Whether files are attached to this message.' })\n hasAttachments = false;\n @field({ description: 'The size of the message in bytes.' })\n size = 0;\n @field({\n description: 'Additional details supplied by the messaging connection.',\n })\n metadata = ''; // JSON extension bag\n\n // Send lifecycle fields\n @field({\n description:\n 'The latest sending state: draft, sending, sent, or failed. Received mail may also show draft here.',\n })\n sendStatus: SendStatus = 'draft';\n @field({ description: 'When the message was successfully sent.' })\n sentAt: Date | null = null;\n @field({ description: 'The reason the latest send attempt failed.' })\n sendError = '';\n @field({ description: 'How many times delivery has been retried.' })\n retryCount = 0;\n @field({ description: 'The maximum number of delivery retries allowed.' })\n maxRetries = 3;\n @field({ description: 'When this message is scheduled to be sent.' })\n scheduledSendAt: Date | null = null;\n @foreignKey('Message')\n @field({ description: 'The earlier message this one replies to.' })\n inReplyToMessageId = '';\n\n // Who handled this message last (a person or an agent), recorded from the\n // host-supplied acting principal by triage, drafting and sending.\n @field({\n readonly: true,\n description: 'The person or assistant who last acted on this message.',\n })\n handledById: string | null = null;\n @field({\n readonly: true,\n description: 'Whether a person or an assistant last acted on this message.',\n })\n handledByKind: string | null = null;\n @field({\n readonly: true,\n description: 'When someone last acted on this message.',\n })\n handledAt: Date | null = null;\n\n // Timestamps\n @field({ description: 'When this message was recorded.' })\n createdAt = new Date();\n @field({ description: 'When this message was last changed.' })\n updatedAt = new Date();\n\n constructor(options: MessageOptions = {}) {\n super(options);\n\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.accountId !== undefined) this.accountId = options.accountId;\n if (options.personaId !== undefined) this.personaId = options.personaId;\n if (options.endpointId !== undefined) this.endpointId = options.endpointId;\n if (options.correlationId !== undefined)\n this.correlationId = options.correlationId;\n if (options.threadId !== undefined) this.threadId = options.threadId;\n if (options.subject !== undefined) this.subject = options.subject;\n if (options.body !== undefined) this.body = options.body;\n if (options.fromAddress !== undefined)\n this.fromAddress = options.fromAddress;\n if (options.fromName !== undefined) this.fromName = options.fromName;\n if (options.toAddresses !== undefined)\n this.toAddresses = options.toAddresses;\n if (options.date !== undefined) this.date = options.date || null;\n if (options.isRead !== undefined) this.isRead = options.isRead;\n if (options.isFlagged !== undefined) this.isFlagged = options.isFlagged;\n if (options.hasAttachments !== undefined)\n this.hasAttachments = options.hasAttachments;\n if (options.size !== undefined) this.size = options.size;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n if (options.sendStatus !== undefined) this.sendStatus = options.sendStatus;\n if (options.sentAt !== undefined) this.sentAt = options.sentAt || null;\n if (options.sendError !== undefined) this.sendError = options.sendError;\n if (options.retryCount !== undefined) this.retryCount = options.retryCount;\n if (options.maxRetries !== undefined) this.maxRetries = options.maxRetries;\n if (options.scheduledSendAt !== undefined)\n this.scheduledSendAt = options.scheduledSendAt || null;\n if (options.inReplyToMessageId !== undefined)\n this.inReplyToMessageId = options.inReplyToMessageId;\n if (options.handledById !== undefined)\n this.handledById = options.handledById;\n if (options.handledByKind !== undefined)\n this.handledByKind = options.handledByKind;\n if (options.handledAt !== undefined)\n this.handledAt = options.handledAt || null;\n if (options.createdAt) this.createdAt = options.createdAt;\n if (options.updatedAt) this.updatedAt = options.updatedAt;\n rememberNotificationOrigin(this);\n }\n\n /** Ordinary saves preserve protected outbox provenance and approved content. */\n override async save(options?: SmrtSaveOptions): Promise<this> {\n const signature = lifecycleSaves.get(this);\n lifecycleSaves.delete(this);\n const authorized =\n signature !== undefined && signature === lifecycleSignature(this);\n const lifecycle = authorized || heldSaves.has(this);\n const required = await this.enforceDraftScope(lifecycle, true);\n return this.withTransaction(async () => {\n // The decision above used the stored row as it was then; inside the\n // write, the row this save replaces must still need nothing more.\n await this.assertDraftScopeStillHolds(lifecycle, true, required);\n await assertProtectedNotificationSave(this, options, authorized);\n if (signature !== undefined && signature !== lifecycleSignature(this))\n throw new Error('Message lifecycle changed during its guarded save.');\n const result = await super.save(options);\n // Core may adopt a natural-key row that appeared during save. Verify\n // its resulting durable identity before this transaction can commit.\n await assertProtectedNotificationSave(this, options, authorized);\n if (signature !== undefined && signature !== lifecycleSignature(this))\n throw new Error('Message lifecycle changed during its guarded save.');\n rememberNotificationOrigin(this);\n return result;\n });\n }\n\n /** Protected outbound evidence is retained; ordinary message deletion remains unchanged. */\n override async delete(\n options: { expectedUpdatedAt?: Date | string } = {},\n ): Promise<void> {\n const required = await this.enforceDraftScope(false, false);\n return this.withTransaction(async () => {\n await this.assertDraftScopeStillHolds(false, false, required);\n await assertProtectedNotificationDelete(this);\n return super.delete(options);\n });\n }\n\n /**\n * Creating, changing or deleting mail that a later send would transmit\n * needs the `draft` scope on an owned account, whichever route the write\n * takes ({@link isMailWriteGated}): every row that is not `sent`, received\n * mail included when it is saved, so content cannot be written without the\n * scope and then flipped into a draft. A row counts by its stored state and\n * by the state it is moved into, so it cannot be edited by first relabelling\n * it, and both accounts count when it moves. A fresh row needs the scope\n * too. Received mail (provider-tagged, unflagged, plain `draft`) is never\n * sent ({@link Message.send} refuses it), may be deleted, and a stored\n * `sent` row cannot leave `sent`. The stored row decides, whatever class\n * this instance is. Trusted system work, unowned accounts and sent mail are\n * unaffected.\n *\n * A save that changes only the triage fields (read and flagged state) of a\n * stored row needs nothing here: they are not content a send transmits.\n *\n * `lifecycle` is the send path's own save (status changes, a held send moved\n * back to draft): it needs the `send` scope instead, and passes only while\n * every field outside {@link SEND_PATH_MAY_CHANGE} still equals the stored\n * row, so it cannot carry an edit. A row the send path itself creates (an\n * unsaved message being sent), or a service-queued row saved through\n * {@link saveQueuedForSend}, needs `send` too.\n *\n * Returns the requirements it enforced (empty for system work).\n */\n private async enforceDraftScope(\n lifecycle: boolean,\n save: boolean,\n ): Promise<DraftRequirements> {\n if (inMailSystemAccess()) return emptyRequirements();\n const rootOptions = { ...this.options } as SmrtClassOptions;\n learnMailAccessOptions(rootOptions);\n const required = await this.draftScopeRequirements(lifecycle, save);\n if (required.refused) throw new MailAccessError('draft', 'denied');\n for (const key of required.keys) {\n const at = key.indexOf(':');\n await assertMailScopeOn(\n [key.slice(at + 1)],\n key.slice(0, at) as MailScope,\n rootOptions,\n // A queued row whose account was deleted is marked failed by the send\n // path; there is no owner left to protect and nothing it can send.\n {\n allowMissing:\n required.lifecycle &&\n this.sendStatus === 'failed' &&\n key.startsWith('send:'),\n },\n );\n }\n return required;\n }\n\n /**\n * The same decision re-read inside the write transaction. The policy lookups\n * (grants, account owner) use the configured database handle, which a\n * single-connection engine cannot serve while a transaction is open, so they\n * stay outside; what the write re-checks is the stored row. A row that now\n * needs more than was enforced is refused, and the caller retries.\n */\n private async assertDraftScopeStillHolds(\n lifecycle: boolean,\n save: boolean,\n enforced: DraftRequirements,\n ): Promise<void> {\n if (inMailSystemAccess()) return;\n const now = await this.draftScopeRequirements(lifecycle, save);\n if (now.refused) throw new MailAccessError('draft', 'denied');\n for (const key of now.keys) {\n if (!enforced.keys.has(key)) {\n throw new MailAccessError(\n key.slice(0, key.indexOf(':')) as MailScope,\n 'denied',\n );\n }\n }\n }\n\n /** The `scope:accountId` pairs this write needs, read through `this.db`. */\n private async draftScopeRequirements(\n lifecycle: boolean,\n save: boolean,\n ): Promise<DraftRequirements> {\n const result = emptyRequirements();\n const row = this as unknown as Record<string, unknown>;\n const write = save ? 'save' : 'delete';\n const priorAccountIds: string[] = [];\n // Accounts of stored `sent` rows this write changes, moves or deletes.\n const sentAccountIds: string[] = [];\n let storedSent = false;\n let stored: Record<string, unknown> | null = null;\n let unchanged = false;\n let triageOnly = false;\n if (this.id) {\n stored = await this.getCanonicalPersistedRow({ id: this.id });\n if (stored) {\n if (isMailWriteGated(stored, write)) {\n priorAccountIds.push(String(stored.account_id ?? ''));\n }\n storedSent = stored.send_status === 'sent';\n if (storedSent) sentAccountIds.push(String(stored.account_id ?? ''));\n if (\n save &&\n stored.send_status === 'sent' &&\n row.sendStatus !== 'sent'\n ) {\n result.refused = true;\n }\n unchanged = this.matchesStoredBeyond(\n stored,\n SEND_PATH_MAY_CHANGE,\n true,\n );\n triageOnly =\n save && this.matchesStoredBeyond(stored, TRIAGE_MAY_CHANGE, false);\n }\n }\n // A new object is written over the stored row that carries its natural\n // key (the slug it has, or the one the save derives from its id), whatever\n // its own id: that row, not the id, is what the save changes.\n let takesOver = false;\n if (!this.isPersisted) {\n const columns = ObjectRegistry.getConflictColumns(\n this.getResolvedQualifiedName(),\n );\n if (columns.includes('slug')) {\n const slug =\n typeof row.slug === 'string' && row.slug\n ? row.slug\n : await this.getSlug();\n if (typeof slug === 'string' && slug) {\n // Match on the slug alone: the tenant is filled in during the save,\n // after this check, so any narrower filter could miss the row the\n // save takes over. It can only over-match, which means an extra\n // check.\n for (const keyed of await this.getCanonicalPersistedRows({ slug })) {\n if (keyed.id === this.id) continue;\n takesOver = true;\n unchanged = false;\n triageOnly = false;\n if (keyed.send_status === 'sent' && row.sendStatus !== 'sent') {\n result.refused = true;\n }\n if (isMailWriteGated(keyed, write)) {\n priorAccountIds.push(String(keyed.account_id ?? ''));\n }\n if (keyed.send_status === 'sent') {\n sentAccountIds.push(String(keyed.account_id ?? ''));\n }\n }\n }\n }\n }\n if (result.refused) return result;\n if (triageOnly) {\n // Read and flag marks are not content, but they are triage: the stored\n // row's account decides, under the triage scope instead of draft.\n for (const id of priorAccountIds) if (id) result.keys.add(`triage:${id}`);\n if (storedSent) {\n for (const id of sentAccountIds)\n if (id) result.keys.add(`triage:${id}`);\n }\n return result;\n }\n // Sent mail is a record that replies and forwards quote. Outside the\n // triage fields, changing, moving or deleting a stored `sent` row needs\n // `send` on the account it is on and on the one it moves to.\n for (const id of sentAccountIds) if (id) result.keys.add(`send:${id}`);\n if (storedSent && save && this.accountId) {\n result.keys.add(`send:${this.accountId}`);\n }\n const fresh = !stored && !takesOver;\n const outgoingNow = isMailWriteGated(row, write);\n // A sent record comes into being through the send path or trusted sync.\n // Replies and forwards quote it, so writing a row into `sent` needs the\n // `send` scope on its account, whatever it was before.\n if (\n save &&\n row.sendStatus === 'sent' &&\n (fresh ||\n takesOver ||\n stored?.send_status !== 'sent' ||\n String(stored.account_id ?? '') !== this.accountId) &&\n this.accountId\n ) {\n result.keys.add(`send:${this.accountId}`);\n }\n if (!outgoingNow && !priorAccountIds.length) return result;\n const sanctioned =\n (lifecycle && ((stored && unchanged) || fresh)) ||\n (fresh && queuedCreates.has(this));\n const scope: MailScope = sanctioned ? 'send' : 'draft';\n result.lifecycle = Boolean(lifecycle && ((stored && unchanged) || fresh));\n for (const id of [outgoingNow ? this.accountId : '', ...priorAccountIds]) {\n if (id) result.keys.add(`${scope}:${id}`);\n }\n return result;\n }\n\n /**\n * Whether every field outside `allowed` equals `stored`. `held` lets a held\n * send raise the draft flag.\n */\n private matchesStoredBeyond(\n stored: Record<string, unknown>,\n allowed: ReadonlySet<string>,\n held: boolean,\n ): boolean {\n const row = this as unknown as Record<string, unknown>;\n const qualified = this.getResolvedQualifiedName();\n const names = new Set([\n ...this.draftFieldNames(),\n 'tenantId',\n 'slug',\n 'context',\n ]);\n let registered: ReadonlyMap<\n string,\n {\n type?: string;\n transient?: boolean;\n _meta?: { transient?: boolean };\n }\n >;\n try {\n registered = ObjectRegistry.getFields(qualified);\n } catch {\n registered = new Map();\n }\n // Fields kept in the `_meta_data` bag of an STI row.\n let storedMeta: Record<string, unknown> | null | undefined;\n const metaOf = (): Record<string, unknown> | null => {\n if (storedMeta !== undefined) return storedMeta;\n const raw = stored._meta_data;\n storedMeta = null;\n if (raw === undefined || raw === null || raw === '') {\n storedMeta = {};\n } else if (typeof raw === 'object') {\n storedMeta = raw as Record<string, unknown>;\n } else if (typeof raw === 'string') {\n try {\n const parsed: unknown = JSON.parse(raw);\n if (parsed && typeof parsed === 'object') {\n storedMeta = parsed as Record<string, unknown>;\n }\n } catch {\n // Unreadable: nothing can be compared, so the row counts as changed.\n }\n }\n return storedMeta;\n };\n // Write-through fields live on a linked record: any pending edit is a\n // change, and so is a draft the instance does not expose.\n const writeThrough: string[] = [];\n try {\n // Names come from the declaration itself, as core persists them; the\n // linked target is not resolved, so a lookup failure cannot refuse a\n // save that carries no pending edit.\n for (const link of Object.values(\n ObjectRegistry.getConfig(qualified).writeThrough ?? {},\n )) {\n writeThrough.push(\n ...link.fields,\n ...Object.keys(link.virtualFields ?? {}),\n );\n }\n } catch {\n return false;\n }\n if (writeThrough.length) {\n const pending = new Set(this.getPendingWriteThroughFields());\n for (const name of writeThrough) {\n if (allowed.has(name)) continue;\n if (pending.has(name)) return false;\n }\n }\n for (const name of names) {\n if (allowed.has(name)) continue;\n // A held send flags the message as a draft; it may raise the flag only.\n if (\n held &&\n name === 'isDraft' &&\n heldSaves.has(this) &&\n mailFlag(row[name])\n ) {\n continue;\n }\n // A class without the property cannot carry a value for it.\n if (!(name in this)) continue;\n if (writeThrough.includes(name)) continue;\n const definition = registered.get(name);\n const column = toSnakeCase(name);\n let storedValue: unknown;\n if (definition?.type === 'meta') {\n const bag = metaOf();\n if (!bag) return false;\n storedValue = bag[name];\n } else if (column in stored) {\n storedValue = stored[column];\n } else if (\n definition &&\n !definition.transient &&\n !definition._meta?.transient &&\n definition.type !== 'oneToMany' &&\n definition.type !== 'manyToMany'\n ) {\n // A registered field this comparison cannot read back counts as\n // changed: it cannot be shown to equal the stored row.\n return false;\n } else {\n continue;\n }\n const mine = row[name];\n const same =\n typeof mine === 'boolean'\n ? mine === mailFlag(storedValue)\n : canonValue(mine) === canonValue(storedValue);\n if (!same) return false;\n }\n return true;\n }\n\n private async finalizeSendLifecycle(\n result: MessageSendResult,\n actor: MailPrincipal | null = null,\n ): Promise<void> {\n if (!this.id) throw new Error('Cannot finalize an unsaved message send');\n\n const sendStatus: SendStatus = result.success ? 'sent' : 'failed';\n const sendError = result.success ? '' : (result.error ?? 'Send failed');\n const useEmbeddedFallback = usesEmbeddedRevisionFallback(this.db);\n for (let attempt = 0; attempt < 8; attempt += 1) {\n let nextRevision: Date | undefined;\n await withEmbeddedWriteQueue(this.db, useEmbeddedFallback, async () => {\n const current = await this.getCanonicalPersistedRow({ id: this.id });\n if (current?.send_status !== 'sending') return;\n const currentRevision = current.updated_at;\n const currentRevisionMs = new Date(String(currentRevision)).getTime();\n if (!Number.isFinite(currentRevisionMs)) return;\n nextRevision = new Date(Math.max(Date.now(), currentRevisionMs + 1));\n // Record durably whether a failure may still have been accepted, so a\n // later reconciliation can tell it from a definite rejection.\n const metadata = withSendOutcomeMarker(\n current.metadata,\n !result.success && result.outcomeUnknown === true,\n );\n if (actor) stampHandledBy(this, actor, nextRevision);\n const values = {\n send_status: sendStatus,\n sent_at: result.success ? result.sentAt : null,\n send_error: sendError,\n updated_at: nextRevision,\n ...(metadata === undefined ? {} : { metadata }),\n ...(actor\n ? {\n handled_by_id: this.handledById,\n handled_by_kind: this.handledByKind,\n handled_at: this.handledAt,\n }\n : {}),\n };\n if (useEmbeddedFallback) {\n await this.db.upsert(this.tableName, ['id'], {\n ...current,\n ...values,\n });\n return;\n }\n await this.db.update(\n this.tableName,\n {\n id: this.id,\n send_status: 'sending',\n updated_at:\n currentRevision instanceof Date\n ? currentRevision.toISOString()\n : currentRevision,\n },\n values,\n );\n });\n // DuckDB's generic update result reports one affected row even when the\n // predicate matched none. Verify the durable lifecycle value instead of\n // trusting adapter row-count metadata before declaring finalization.\n const verified = await this.getCanonicalPersistedRow({ id: this.id });\n if (verified?.send_status === sendStatus) {\n await this.completePersistedUpdate(verified);\n return;\n }\n }\n throw new Error('Cannot finalize: message revision kept changing');\n }\n\n /**\n * Get to addresses as parsed array\n */\n getToAddresses(): Array<{ address: string; name?: string }> {\n if (!this.toAddresses) return [];\n try {\n return JSON.parse(this.toAddresses);\n } catch {\n return [];\n }\n }\n\n /**\n * Set to addresses from array\n */\n setToAddresses(addresses: Array<{ address: string; name?: string }>): void {\n this.toAddresses = JSON.stringify(addresses);\n }\n\n /**\n * Get metadata as parsed object\n */\n getMetadata(): Record<string, unknown> {\n if (!this.metadata) return {};\n try {\n return JSON.parse(this.metadata);\n } catch {\n return {};\n }\n }\n\n /**\n * Set metadata from object\n */\n setMetadata(data: Record<string, unknown>): void {\n this.metadata = JSON.stringify(data);\n }\n\n /**\n * Mark message as read\n */\n async markRead(): Promise<void> {\n this.isRead = true;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Mark message as unread\n */\n async markUnread(): Promise<void> {\n this.isRead = false;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Toggle flagged status\n */\n async toggleFlagged(): Promise<void> {\n this.isFlagged = !this.isFlagged;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Check if message is unread\n */\n isUnread(): boolean {\n return !this.isRead;\n }\n\n /**\n * Get a short preview of the message body\n */\n getPreview(maxLength = 200): string {\n const text = this.body || '';\n if (text.length <= maxLength) return text;\n return `${text.slice(0, maxLength)}...`;\n }\n\n /**\n * Direct hydration (`new X({ id }).initialize()`, `loadRelated()`) bypasses\n * the collection read hooks, so the per-account mail policy is applied here\n * too: a row of an account closed to the principal never hydrates.\n */\n override async loadFromId() {\n await super.loadFromId();\n await assertHydratedMailAccess({\n accountId: this.accountId,\n options: this.options,\n });\n }\n\n override async loadFromSlug() {\n await super.loadFromSlug();\n await assertHydratedMailAccess({\n accountId: this.accountId,\n options: this.options,\n });\n }\n\n /**\n * Get the account for this message\n */\n async getAccount() {\n if (!this.accountId) return null;\n\n const { AccountCollection } = await import(\n '../collections/AccountCollection'\n );\n const collection = await AccountCollection.create(this.options);\n\n return await collection.get({ id: this.accountId });\n }\n\n async getEndpoint() {\n if (!this.endpointId) return null;\n const { MessagingEndpointCollection } = await import(\n '../collections/MessagingEndpointCollection.js'\n );\n const collection = await MessagingEndpointCollection.create(this.options);\n return collection.get({ id: this.endpointId });\n }\n\n /**\n * Get messages in the same thread\n */\n async getThreadMessages(): Promise<Message[]> {\n if (!this.threadId) return [this];\n\n const { MessageCollection } = await import(\n '../collections/MessageCollection'\n );\n const collection = await MessageCollection.create(this.options);\n\n return await collection.list({ where: { threadId: this.threadId } });\n }\n\n /**\n * Get attachments for this message\n */\n async getAttachments() {\n const { AttachmentCollection } = await import(\n '../collections/AttachmentCollection'\n );\n const collection = await AttachmentCollection.create(this.options);\n\n return await collection.list({ where: { messageId: this.id } });\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Send Lifecycle\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Send this message via its account's sender\n */\n async send(options?: SendMessageOptions): Promise<MessageSendResult> {\n try {\n await beginProtectedNotificationSend(this, options);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n sentAt: new Date(),\n };\n }\n // Received mail is a record of what arrived, never an outgoing message.\n // The stored row counts too: a base `Message` handle carries no\n // provider-id fields of its subclass.\n const storedRow = this.id\n ? await this.getCanonicalPersistedRow({ id: this.id })\n : null;\n if (\n isReceivedMail(this as unknown as Record<string, unknown>) ||\n (storedRow && isReceivedMail(storedRow))\n ) {\n return {\n success: false,\n error: 'Cannot send: this is received mail',\n sentAt: new Date(),\n };\n }\n // Entry guard: a message that is already in flight or delivered must not be\n // sent again. Catches same-instance double-clicks before any work happens.\n if (this.sendStatus === 'sending' || this.sendStatus === 'sent') {\n return {\n success: false,\n error: `Cannot send: message is already '${this.sendStatus}'`,\n sentAt: new Date(),\n };\n }\n\n // Resolve account\n const account = await this.getAccount();\n if (!account) {\n const result: MessageSendResult = {\n success: false,\n error: 'No account associated with this message',\n sentAt: new Date(),\n };\n this.sendStatus = 'failed';\n this.sendError = result.error ?? '';\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n return result;\n }\n\n if (!account.isActive) {\n const result: MessageSendResult = {\n success: false,\n error: 'Messaging account is inactive',\n sentAt: new Date(),\n };\n this.sendStatus = 'failed';\n this.sendError = result.error ?? '';\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n return result;\n }\n\n // Owned accounts need the `send` scope. A denial leaves the message as it\n // was: a refused principal must not mark someone else's draft failed.\n const access = await decideMailAccess(account, 'send');\n if (!access.allowed) {\n return {\n success: false,\n error: 'Mail access denied for scope send',\n sentAt: new Date(),\n };\n }\n\n // The acting principal (host-supplied). Trusted system work (sync, the\n // notification outbox) has none and is never held or stamped.\n const actor = inMailSystemAccess() ? null : await resolveMailPrincipal();\n\n // Send-as: from any mail account, everything but trusted system work\n // sends only from the account's own address. Sending as anyone else needs\n // a delegation grant, which does not exist yet, so it is refused.\n if (!inMailSystemAccess() && 'email' in account) {\n const from = (this.fromAddress || '').trim().toLowerCase();\n const own = String((account as { email?: unknown }).email ?? '')\n .trim()\n .toLowerCase();\n if (from && from !== own) {\n return {\n success: false,\n error: \"Mail can only be sent from the account's own address.\",\n sentAt: new Date(),\n };\n }\n }\n\n // Agents follow the account's send policy: by default the draft is held\n // for a person's approval and nothing leaves (smrt#5141).\n // Trusted system work is not held, except a persona (agent) message: a\n // system drain must never send an agent's message around its approval.\n const held =\n inMailSystemAccess() && !this.personaId\n ? null\n : await holdAgentSend(this, account, options, actor);\n if (held) {\n // A held message is a draft: out of any pending/scheduled outbox, and\n // decidable by a person. Content is untouched, so the binding holds.\n const toDraft =\n held.pendingApproval !== undefined && this.sendStatus !== 'draft';\n if (toDraft) this.sendStatus = 'draft';\n // A held message is a flagged draft, not a plain `draft` status (which\n // received mail carries), so it stays under the draft scope.\n const flagDraft =\n held.pendingApproval !== undefined &&\n 'isDraft' in this &&\n !mailFlag((this as unknown as { isDraft?: unknown }).isDraft);\n if (flagDraft) (this as unknown as { isDraft: boolean }).isDraft = true;\n if (held.pendingApproval?.created) stampHandledBy(this, actor);\n if (toDraft || flagDraft || held.pendingApproval?.created) {\n await saveHeld(this);\n }\n // A refused send of a queued message fails definitely (nothing left),\n // so it does not linger as `pending` for a later drain.\n if (\n held.pendingApproval === undefined &&\n (this.sendStatus === 'pending' || this.sendStatus === 'scheduled') &&\n this.isPersisted\n ) {\n this.sendStatus = 'failed';\n this.sendError = held.error ?? 'Send refused';\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n }\n return held;\n }\n // Audited before anything is claimed: an audit failure sends nothing.\n if (actor) await auditMailAction('messages.send', this);\n\n // Get sender from account\n let sender: Awaited<ReturnType<typeof account.createSender>>;\n try {\n sender = await account.createSender();\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n this.sendStatus = 'failed';\n this.sendError = errorMessage;\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n return {\n success: false,\n error: errorMessage,\n sentAt: new Date(),\n };\n }\n\n // Claim the send. For a persisted row, do a compare-and-set so only one\n // concurrent sender wins: flip send_status to 'sending' atomically, gated on\n // the status we observed. If no row matched, another sender already claimed\n // it — abort without delivering (prevents duplicate sends). For an unsaved\n // draft there is no row yet, so the in-memory transition + save() (INSERT)\n // serves as the claim.\n const claimFromStatus = this.sendStatus;\n if (this.isPersisted && this.id) {\n const loadedRevision = this.updated_at;\n if (!loadedRevision) {\n return {\n success: false,\n error: 'Cannot send: persisted message has no loaded revision',\n sentAt: new Date(),\n };\n }\n const claimedRevision = new Date(\n Math.max(Date.now(), loadedRevision.getTime() + 1),\n );\n const useEmbeddedFallback = usesEmbeddedRevisionFallback(this.db);\n let claimed = false;\n await withEmbeddedWriteQueue(this.db, useEmbeddedFallback, async () => {\n if (useEmbeddedFallback) {\n const current = await this.getCanonicalPersistedRow({ id: this.id });\n const storedRevision = current?.updated_at;\n const currentRevision =\n storedRevision instanceof Date\n ? storedRevision.getTime()\n : typeof storedRevision === 'string'\n ? Date.parse(storedRevision)\n : Number.NaN;\n if (\n !current ||\n current.send_status !== claimFromStatus ||\n !Number.isFinite(currentRevision) ||\n currentRevision !== loadedRevision.getTime()\n )\n return;\n await this.db.upsert(this.tableName, ['id'], {\n ...current,\n send_status: 'sending',\n updated_at: claimedRevision,\n });\n claimed = true;\n return;\n }\n const claim = await this.db.update(\n this.tableName,\n {\n id: this.id,\n send_status: claimFromStatus,\n updated_at: loadedRevision.toISOString(),\n },\n { send_status: 'sending', updated_at: claimedRevision },\n );\n claimed = claim?.affected === 1;\n });\n if (!claimed) {\n return {\n success: false,\n error: 'Cannot send: message is already being sent',\n sentAt: new Date(),\n };\n }\n this.sendStatus = 'sending';\n this.updated_at = claimedRevision;\n this.updatedAt = new Date();\n } else {\n this.sendStatus = 'sending';\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n }\n\n // A send an approval released must still be the approved draft now that\n // the row is claimed (attachment rows are not covered by the claim).\n if (await approvedDraftChanged(this)) {\n const changed: MessageSendResult = {\n success: false,\n error: 'The draft changed after it was approved; nothing was sent.',\n sentAt: new Date(),\n };\n await this.finalizeSendLifecycle(changed, actor);\n return changed;\n }\n\n let result: MessageSendResult;\n try {\n await assertProtectedSenderHandoff(this, options);\n result = await sender.send(this, options);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n // A sender that throws mid-send says nothing about provider acceptance.\n result = {\n success: false,\n error: errorMessage,\n ...(error instanceof ProtectedNotificationHandoffError\n ? {}\n : { outcomeUnknown: true }),\n sentAt: new Date(),\n };\n }\n await this.finalizeSendLifecycle(result, actor);\n return result;\n }\n\n /** Who last acted on this message, or null. */\n getHandledBy(): { id: string; kind: string; at: Date | null } | null {\n if (!this.handledById) return null;\n return {\n id: this.handledById,\n kind: this.handledByKind || 'agent',\n at: this.handledAt,\n };\n }\n\n /**\n * Whether the latest failed send may still have been accepted by the\n * provider (see `MessageSendResult.outcomeUnknown`).\n */\n isSendOutcomeUnknown(): boolean {\n return (\n this.sendStatus === 'failed' &&\n this.getMetadata()[SEND_OUTCOME_UNKNOWN_METADATA_KEY] === true\n );\n }\n\n /**\n * Release a send claim whose sender is gone (a crash or lost lease left the\n * row in `sending`): move it to `failed` with an unknown outcome so the\n * owner of the delivery decision can send it again. Returns false, changing\n * nothing, unless the stored row is still `sending`. Only for callers that\n * have established that no live sender holds the claim.\n */\n async abandonSendAttempt(reason: string): Promise<boolean> {\n if (!this.id) return false;\n const current = await this.getCanonicalPersistedRow({ id: this.id });\n if (current?.send_status !== 'sending') return false;\n try {\n await this.finalizeSendLifecycle({\n success: false,\n error: reason,\n outcomeUnknown: true,\n sentAt: new Date(),\n });\n } catch {\n return false;\n }\n return this.sendStatus === 'failed';\n }\n\n /**\n * Retry sending a failed message\n */\n async retrySend(options?: SendMessageOptions): Promise<MessageSendResult> {\n try {\n await assertProtectedNotificationRetry(this, options);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n sentAt: new Date(),\n };\n }\n if (this.sendStatus !== 'failed') {\n return {\n success: false,\n error: `Cannot retry: message status is '${this.sendStatus}', expected 'failed'`,\n sentAt: new Date(),\n };\n }\n\n if (this.retryCount >= this.maxRetries) {\n return {\n success: false,\n error: `Retry budget exhausted (${this.retryCount}/${this.maxRetries})`,\n sentAt: new Date(),\n };\n }\n\n this.retryCount++;\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n\n return this.send(options);\n }\n\n /**\n * Options for a derived draft (reply/forward) built from this message. Carries\n * the DB connection + tenant context from `this.options`, but strips this\n * message's own identity fields. When this message was hydrated from the DB,\n * `this.options` holds the row's `id`/`slug`/`context`/`_skipLoad`; spreading\n * those into a new draft would make `draft.save()` upsert onto the natural-key\n * conflict columns (`slug`/`context`/`_meta_type`) and overwrite the ORIGINAL\n * message instead of inserting a new row. See EmailAccount.childOptions().\n */\n protected draftOptions(): Record<string, unknown> {\n const rest = { ...(this.options as Record<string, unknown>) };\n delete rest.id;\n delete rest.slug;\n delete rest.context;\n delete rest._skipLoad;\n // `this.options` of a hydrated row carries every stored column. A derived\n // draft must not inherit any of them (htmlBody, bcc, messageId, headers,\n // send state, handled-by, ...); createReply/createForward then set back\n // only what reply/forward semantics define. Only connection and tenant\n // context survive.\n // `personaId` is dropped on purpose: a reply is authored by the replying\n // principal, so it falls under that principal's hold rules, not the\n // persona the inbound message happened to be addressed through.\n // `metadata` and `correlationId` stay: the protected-notification\n // handoff keys its provenance on them, so a derived draft of a protected\n // notification must keep failing closed. Neither is sent as mail content.\n for (const name of this.draftFieldNames()) {\n if (!DRAFT_CARRIED_FIELDS.has(name)) delete rest[name];\n }\n return rest;\n }\n\n /** Every stored field name of this message's class, including subclasses. */\n private draftFieldNames(): string[] {\n const names = new Set<string>(DRAFT_RESET_FIELDS);\n try {\n for (const key of ObjectRegistry.getFields(\n this.getResolvedQualifiedName(),\n ).keys()) {\n names.add(key);\n }\n } catch {\n // The static list above still covers every field this package declares.\n }\n return [...names];\n }\n\n /**\n * Create a reply to this message (returns unsaved draft)\n */\n createReply(_options?: { replyAll?: boolean }): Message {\n const reply = new (this.constructor as typeof Message)({\n ...this.draftOptions(),\n id: undefined,\n accountId: this.accountId,\n threadId: this.threadId || this.id || '',\n subject: this.subject.startsWith('Re:')\n ? this.subject\n : `Re: ${this.subject}`,\n toAddresses: JSON.stringify([\n { address: this.fromAddress, name: this.fromName },\n ]),\n fromAddress: '',\n fromName: '',\n body: this.buildQuotedBody(),\n inReplyToMessageId: this.id || '',\n sendStatus: 'draft',\n isRead: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n });\n\n return reply;\n }\n\n /**\n * Create a forward of this message (returns unsaved draft)\n */\n createForward(): Message {\n const forward = new (this.constructor as typeof Message)({\n ...this.draftOptions(),\n id: undefined,\n accountId: this.accountId,\n threadId: '',\n subject: this.subject.startsWith('Fwd:')\n ? this.subject\n : `Fwd: ${this.subject}`,\n toAddresses: '[]',\n fromAddress: '',\n fromName: '',\n body: this.buildQuotedBody(),\n // Attachment rows are not copied, so the draft has none.\n hasAttachments: false,\n inReplyToMessageId: '',\n sendStatus: 'draft',\n isRead: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n });\n\n return forward;\n }\n\n /**\n * Build quoted body for reply/forward\n */\n protected buildQuotedBody(): string {\n const dateStr = this.date ? this.date.toLocaleString() : 'unknown date';\n const from = this.fromName\n ? `${this.fromName} <${this.fromAddress}>`\n : this.fromAddress;\n\n const quotedLines = (this.body || '')\n .split('\\n')\n .map((line) => `> ${line}`)\n .join('\\n');\n\n return `\\n\\nOn ${dateStr}, ${from} wrote:\\n${quotedLines}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA8DO,IAAM,oCAAoC;AAMjD,SAAS,sBACP,QACA,gBACoB;CACpB,IAAI,MAA+B,CAAC;CACpC,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,GAC5C,IAAI;EACF,MAAM,SAAkB,KAAK,MAAM,MAAM;EACzC,IAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GAC/D;EAEF,MAAM;CACR,QAAQ;EACN;CACF;CAEF,IAAI,QAAQ,IAAA,qBAAsC,MAAM,gBACtD;CAEF,IAAI,gBAAgB,IAAI,qCAAqC;MACxD,OAAO,IAAI;CAChB,OAAO,KAAK,UAAU,GAAG;AAC3B;AAIA,IAAM,iCAAiB,IAAI,QAAyB;AACpD,SAAS,mBAAmB,SAA0B;CACpD,OAAO,KAAK,UAAU;EACpB,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;CACV,CAAC;AACH;AACA,eAAe,kBAAkB,SAAiC;CAChE,eAAe,IAAI,SAAS,mBAAmB,OAAO,CAAC;CACvD,IAAI;EACF,MAAM,QAAQ,KAAK;CACrB,UAAE;EACA,eAAe,OAAO,OAAO;CAC/B;AACF;AAIA,IAAM,4BAAY,IAAI,QAAiB;AACvC,eAAe,SAAS,SAAiC;CACvD,UAAU,IAAI,OAAO;CACrB,IAAI;EACF,MAAM,QAAQ,KAAK;CACrB,UAAE;EACA,UAAU,OAAO,OAAO;CAC1B;AACF;AAKA,IAAM,gCAAgB,IAAI,QAAiB;AAE3C,eAAsB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X,WAAA,eAAA,CAAA;AAKA,gBAAA,CAJC,MAAM;CACL,UAAU;CACV,aAAa;AACf,CAAC,CAAA,GAlFU,QAmFX,WAAA,iBAAA,CAAA;AAKA,gBAAA,CAJC,MAAM;CACL,UAAU;CACV,aAAa;AACf,CAAC,CAAA,GAvFU,QAwFX,WAAA,aAAA,CAAA;AAIA,gBAAA,CADC,MAAM,EAAE,aAAa,kCAAkC,CAAC,CAAA,GA3F9C,QA4FX,WAAA,aAAA,CAAA;AAEA,gBAAA,CADC,MAAM,EAAE,aAAa,sCAAsC,CAAC,CAAA,GA7FlD,QA8FX,WAAA,aAAA,CAAA;AA9FW,UAAN,gBAAA,CAPN,aAAa,EAAE,MAAM,WAAW,CAAC,GACjC,KAAK;CACJ,eAAe;CACf,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,cAAc,KAAK;AAC5B,CAAC,CAAA,GACY,OAAA"}
|
|
1
|
+
{"version":3,"file":"Message-D-FgiSxn.js","names":["result"],"sources":["../../src/models/Message.ts"],"sourcesContent":["import type {\n SmrtClassOptions,\n SmrtSaveOptions,\n} from '@happyvertical/smrt-core';\nimport {\n assertProtectedNotificationDelete,\n assertProtectedNotificationRetry,\n assertProtectedNotificationSave,\n assertProtectedSenderHandoff,\n beginProtectedNotificationSend,\n ProtectedNotificationHandoffError,\n rememberNotificationOrigin,\n} from '../protected-notification-handoff.js';\n/**\n * Message model - Base class for all message types (STI)\n *\n * Common fields shared across email, tweets, slack messages, etc.\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n crossPackageRef,\n field,\n foreignKey,\n ObjectRegistry,\n SmrtObject,\n smrt,\n toSnakeCase,\n usesEmbeddedRevisionFallback,\n withEmbeddedWriteQueue,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport {\n assertHydratedMailAccess,\n assertMailScopeOn,\n decideMailAccess,\n inMailSystemAccess,\n isMailWriteGated,\n isReceivedMail,\n learnMailAccessOptions,\n MailAccessError,\n type MailPrincipal,\n type MailScope,\n mailFlag,\n resolveMailPrincipal,\n} from '../access.js';\nimport {\n approvedDraftChanged,\n auditMailAction,\n holdAgentSend,\n stampHandledBy,\n} from '../send-approval.js';\nimport type {\n MessageOptions,\n MessageSendResult,\n SendMessageOptions,\n SendStatus,\n} from '../types';\n\n/** `metadata` key recording that the last failed send may have been accepted. */\nexport const SEND_OUTCOME_UNKNOWN_METADATA_KEY = 'sendOutcomeUnknown';\n\n/**\n * The stored metadata JSON with the outcome-unknown marker set or cleared, or\n * undefined when it needs no change (or is not a JSON object to edit).\n */\nfunction withSendOutcomeMarker(\n stored: unknown,\n outcomeUnknown: boolean,\n): string | undefined {\n let bag: Record<string, unknown> = {};\n if (typeof stored === 'string' && stored.trim()) {\n try {\n const parsed: unknown = JSON.parse(stored);\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return undefined;\n }\n bag = parsed as Record<string, unknown>;\n } catch {\n return undefined;\n }\n }\n if (Boolean(bag[SEND_OUTCOME_UNKNOWN_METADATA_KEY]) === outcomeUnknown) {\n return undefined;\n }\n if (outcomeUnknown) bag[SEND_OUTCOME_UNKNOWN_METADATA_KEY] = true;\n else delete bag[SEND_OUTCOME_UNKNOWN_METADATA_KEY];\n return JSON.stringify(bag);\n}\n\n// Only the canonical send/retry implementation can authorize its exact local\n// lifecycle save. An active provider scope never grants arbitrary public saves.\nconst lifecycleSaves = new WeakMap<Message, string>();\nfunction lifecycleSignature(message: Message): string {\n return JSON.stringify([\n message.sendStatus,\n message.retryCount,\n message.maxRetries,\n message.sendError,\n message.sentAt,\n message.scheduledSendAt,\n message.metadata,\n ]);\n}\nasync function saveSendLifecycle(message: Message): Promise<void> {\n lifecycleSaves.set(message, lifecycleSignature(message));\n try {\n await message.save();\n } finally {\n lifecycleSaves.delete(message);\n }\n}\n\n// Internal saves that already hold the `send` decision and may move a message\n// back to draft (a held send); they skip the draft-scope check.\nconst heldSaves = new WeakSet<Message>();\nasync function saveHeld(message: Message): Promise<void> {\n heldSaves.add(message);\n try {\n await message.save();\n } finally {\n heldSaves.delete(message);\n }\n}\n\n// Rows a service creates in the outgoing queue (the persona route). Only the\n// module-private helper below marks one, and only a fresh row is covered; it\n// then needs the `send` scope instead of `draft`, as the send that follows does.\nconst queuedCreates = new WeakSet<Message>();\n/** Internal: not exported from the package index. */\nexport async function saveQueuedForSend(message: Message): Promise<void> {\n queuedCreates.add(message);\n try {\n await message.save();\n } finally {\n queuedCreates.delete(message);\n }\n}\n\n/**\n * The only fields a send-path save of a draft may change: the send lifecycle,\n * the handled-by stamp and the revision. Everything else, including fields the\n * package does not know (tenant, slug, context, subclass fields), must equal\n * the stored row.\n */\nconst SEND_PATH_MAY_CHANGE = new Set([\n 'sendStatus',\n 'sentAt',\n 'sendError',\n 'retryCount',\n 'handledById',\n 'handledByKind',\n 'handledAt',\n 'updatedAt',\n // A row created in this process holds its in-memory timestamp, which the\n // stored one can differ from; the send path never reads it back.\n 'createdAt',\n 'created_at',\n]);\n\n/** Read and flagged state: not content a send transmits. */\nconst TRIAGE_MAY_CHANGE = new Set([\n 'isRead',\n 'isFlagged',\n 'updatedAt',\n 'createdAt',\n 'created_at',\n]);\n\ninterface DraftRequirements {\n /** `scope:accountId` pairs the write needs. */\n keys: Set<string>;\n /** A stored `sent` row moved out of `sent`: sent mail is a record. */\n refused: boolean;\n /** The send path's own save: a fresh row, or a stored row otherwise unchanged. */\n lifecycle: boolean;\n}\n\nconst emptyRequirements = (): DraftRequirements => ({\n keys: new Set(),\n refused: false,\n lifecycle: false,\n});\n\nconst DATE_LIKE =\n /^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$/;\n\n/** One comparable form of a field value, whether instance or stored row. */\nfunction canonValue(value: unknown): string {\n if (value === undefined || value === null) return '';\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? '' : value.toISOString();\n }\n if (typeof value === 'object') return JSON.stringify(value);\n if (typeof value === 'string') {\n if (DATE_LIKE.test(value)) {\n const time = Date.parse(value);\n if (!Number.isNaN(time)) return new Date(time).toISOString();\n }\n if (value.startsWith('[') || value.startsWith('{')) {\n try {\n return JSON.stringify(JSON.parse(value));\n } catch {\n return value;\n }\n }\n }\n return String(value);\n}\n\nconst DRAFT_CARRIED_FIELDS = new Set(['tenantId', 'metadata', 'correlationId']);\n\n/**\n * Stored fields declared by Message and Email. A derived reply/forward draft\n * starts without any of them; the registry adds subclass fields at runtime.\n */\nconst DRAFT_RESET_FIELDS = [\n 'accountId',\n 'personaId',\n 'endpointId',\n 'correlationId',\n 'threadId',\n 'subject',\n 'body',\n 'fromAddress',\n 'fromName',\n 'toAddresses',\n 'date',\n 'isRead',\n 'isFlagged',\n 'hasAttachments',\n 'size',\n 'metadata',\n 'sendStatus',\n 'sentAt',\n 'sendError',\n 'retryCount',\n 'maxRetries',\n 'scheduledSendAt',\n 'inReplyToMessageId',\n 'handledById',\n 'handledByKind',\n 'handledAt',\n 'createdAt',\n 'updatedAt',\n 'messageId',\n 'inReplyTo',\n 'providerMessageId',\n 'ccAddresses',\n 'bccAddresses',\n 'replyToAddress',\n 'replyToName',\n 'textBody',\n 'htmlBody',\n 'folderId',\n 'folderPath',\n 'labels',\n 'flags',\n 'isAnswered',\n 'isDraft',\n 'rawMessage',\n 'headers',\n];\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class Message extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n @foreignKey('Account')\n @field({\n description: 'The connected account used to receive or send this message.',\n })\n accountId = '';\n @crossPackageRef('@happyvertical/smrt-personas:AgentPersona', {\n nullable: true,\n })\n @field({\n description:\n 'The assistant identity associated with this message, when one was used.',\n })\n personaId: string | null = null;\n @foreignKey('MessagingEndpoint')\n @field({ description: 'The saved destination used to deliver this message.' })\n endpointId: string | null = null;\n @field({\n description:\n 'A tracking reference that connects this message to related activity.',\n })\n correlationId = '';\n @field({ description: 'The conversation this message belongs to.' })\n threadId = '';\n @field({ description: 'The subject shown in the message list.' })\n subject = '';\n @field({ description: 'The message content in plain text.' })\n body = ''; // Normalized plain text\n @field({ description: 'The address the message was sent from.' })\n fromAddress = '';\n @field({ description: 'The sender name shown beside their address.' })\n fromName = '';\n @field({ description: 'The people or addresses receiving this message.' })\n toAddresses = ''; // JSON array of {address, name}\n @field({ description: 'When the message was sent or received.' })\n date: Date | null = null;\n @field({ description: 'Whether this message has been marked as read.' })\n isRead = false;\n @field({ description: 'Whether this message is flagged for follow-up.' })\n isFlagged = false;\n @field({ description: 'Whether files are attached to this message.' })\n hasAttachments = false;\n @field({ description: 'The size of the message in bytes.' })\n size = 0;\n @field({\n description: 'Additional details supplied by the messaging connection.',\n })\n metadata = ''; // JSON extension bag\n\n // Send lifecycle fields\n @field({\n description:\n 'The latest sending state: draft, sending, sent, or failed. Received mail may also show draft here.',\n })\n sendStatus: SendStatus = 'draft';\n @field({ description: 'When the message was successfully sent.' })\n sentAt: Date | null = null;\n @field({ description: 'The reason the latest send attempt failed.' })\n sendError = '';\n @field({ description: 'How many times delivery has been retried.' })\n retryCount = 0;\n @field({ description: 'The maximum number of delivery retries allowed.' })\n maxRetries = 3;\n @field({ description: 'When this message is scheduled to be sent.' })\n scheduledSendAt: Date | null = null;\n @foreignKey('Message')\n @field({ description: 'The earlier message this one replies to.' })\n inReplyToMessageId = '';\n\n // Who handled this message last (a person or an agent), recorded from the\n // host-supplied acting principal by triage, drafting and sending.\n @field({\n readonly: true,\n description: 'The person or assistant who last acted on this message.',\n })\n handledById: string | null = null;\n @field({\n readonly: true,\n description: 'Whether a person or an assistant last acted on this message.',\n })\n handledByKind: string | null = null;\n @field({\n readonly: true,\n description: 'When someone last acted on this message.',\n })\n handledAt: Date | null = null;\n\n // Timestamps\n @field({ description: 'When this message was recorded.' })\n createdAt = new Date();\n @field({ description: 'When this message was last changed.' })\n updatedAt = new Date();\n\n constructor(options: MessageOptions = {}) {\n super(options);\n\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.accountId !== undefined) this.accountId = options.accountId;\n if (options.personaId !== undefined) this.personaId = options.personaId;\n if (options.endpointId !== undefined) this.endpointId = options.endpointId;\n if (options.correlationId !== undefined)\n this.correlationId = options.correlationId;\n if (options.threadId !== undefined) this.threadId = options.threadId;\n if (options.subject !== undefined) this.subject = options.subject;\n if (options.body !== undefined) this.body = options.body;\n if (options.fromAddress !== undefined)\n this.fromAddress = options.fromAddress;\n if (options.fromName !== undefined) this.fromName = options.fromName;\n if (options.toAddresses !== undefined)\n this.toAddresses = options.toAddresses;\n if (options.date !== undefined) this.date = options.date || null;\n if (options.isRead !== undefined) this.isRead = options.isRead;\n if (options.isFlagged !== undefined) this.isFlagged = options.isFlagged;\n if (options.hasAttachments !== undefined)\n this.hasAttachments = options.hasAttachments;\n if (options.size !== undefined) this.size = options.size;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n if (options.sendStatus !== undefined) this.sendStatus = options.sendStatus;\n if (options.sentAt !== undefined) this.sentAt = options.sentAt || null;\n if (options.sendError !== undefined) this.sendError = options.sendError;\n if (options.retryCount !== undefined) this.retryCount = options.retryCount;\n if (options.maxRetries !== undefined) this.maxRetries = options.maxRetries;\n if (options.scheduledSendAt !== undefined)\n this.scheduledSendAt = options.scheduledSendAt || null;\n if (options.inReplyToMessageId !== undefined)\n this.inReplyToMessageId = options.inReplyToMessageId;\n if (options.handledById !== undefined)\n this.handledById = options.handledById;\n if (options.handledByKind !== undefined)\n this.handledByKind = options.handledByKind;\n if (options.handledAt !== undefined)\n this.handledAt = options.handledAt || null;\n if (options.createdAt) this.createdAt = options.createdAt;\n if (options.updatedAt) this.updatedAt = options.updatedAt;\n rememberNotificationOrigin(this);\n }\n\n /** Ordinary saves preserve protected outbox provenance and approved content. */\n override async save(options?: SmrtSaveOptions): Promise<this> {\n const signature = lifecycleSaves.get(this);\n lifecycleSaves.delete(this);\n const authorized =\n signature !== undefined && signature === lifecycleSignature(this);\n const lifecycle = authorized || heldSaves.has(this);\n const required = await this.enforceDraftScope(lifecycle, true);\n return this.withTransaction(async () => {\n // The decision above used the stored row as it was then; inside the\n // write, the row this save replaces must still need nothing more.\n await this.assertDraftScopeStillHolds(lifecycle, true, required);\n await assertProtectedNotificationSave(this, options, authorized);\n if (signature !== undefined && signature !== lifecycleSignature(this))\n throw new Error('Message lifecycle changed during its guarded save.');\n const result = await super.save(options);\n // Core may adopt a natural-key row that appeared during save. Verify\n // its resulting durable identity before this transaction can commit.\n await assertProtectedNotificationSave(this, options, authorized);\n if (signature !== undefined && signature !== lifecycleSignature(this))\n throw new Error('Message lifecycle changed during its guarded save.');\n rememberNotificationOrigin(this);\n return result;\n });\n }\n\n /** Protected outbound evidence is retained; ordinary message deletion remains unchanged. */\n override async delete(\n options: { expectedUpdatedAt?: Date | string } = {},\n ): Promise<void> {\n const required = await this.enforceDraftScope(false, false);\n return this.withTransaction(async () => {\n await this.assertDraftScopeStillHolds(false, false, required);\n await assertProtectedNotificationDelete(this);\n return super.delete(options);\n });\n }\n\n /**\n * Creating, changing or deleting mail that a later send would transmit\n * needs the `draft` scope on an owned account, whichever route the write\n * takes ({@link isMailWriteGated}): every row that is not `sent`, received\n * mail included when it is saved, so content cannot be written without the\n * scope and then flipped into a draft. A row counts by its stored state and\n * by the state it is moved into, so it cannot be edited by first relabelling\n * it, and both accounts count when it moves. A fresh row needs the scope\n * too. Received mail (provider-tagged, unflagged, plain `draft`) is never\n * sent ({@link Message.send} refuses it), may be deleted, and a stored\n * `sent` row cannot leave `sent`. The stored row decides, whatever class\n * this instance is. Trusted system work, unowned accounts and sent mail are\n * unaffected.\n *\n * A save that changes only the triage fields (read and flagged state) of a\n * stored row needs nothing here: they are not content a send transmits.\n *\n * `lifecycle` is the send path's own save (status changes, a held send moved\n * back to draft): it needs the `send` scope instead, and passes only while\n * every field outside {@link SEND_PATH_MAY_CHANGE} still equals the stored\n * row, so it cannot carry an edit. A row the send path itself creates (an\n * unsaved message being sent), or a service-queued row saved through\n * {@link saveQueuedForSend}, needs `send` too.\n *\n * Returns the requirements it enforced (empty for system work).\n */\n private async enforceDraftScope(\n lifecycle: boolean,\n save: boolean,\n ): Promise<DraftRequirements> {\n if (inMailSystemAccess()) return emptyRequirements();\n const rootOptions = { ...this.options } as SmrtClassOptions;\n learnMailAccessOptions(rootOptions);\n const required = await this.draftScopeRequirements(lifecycle, save);\n if (required.refused) throw new MailAccessError('draft', 'denied');\n for (const key of required.keys) {\n const at = key.indexOf(':');\n await assertMailScopeOn(\n [key.slice(at + 1)],\n key.slice(0, at) as MailScope,\n rootOptions,\n // A queued row whose account was deleted is marked failed by the send\n // path; there is no owner left to protect and nothing it can send.\n {\n allowMissing:\n required.lifecycle &&\n this.sendStatus === 'failed' &&\n key.startsWith('send:'),\n },\n );\n }\n return required;\n }\n\n /**\n * The same decision re-read inside the write transaction. The policy lookups\n * (grants, account owner) use the configured database handle, which a\n * single-connection engine cannot serve while a transaction is open, so they\n * stay outside; what the write re-checks is the stored row. A row that now\n * needs more than was enforced is refused, and the caller retries.\n */\n private async assertDraftScopeStillHolds(\n lifecycle: boolean,\n save: boolean,\n enforced: DraftRequirements,\n ): Promise<void> {\n if (inMailSystemAccess()) return;\n const now = await this.draftScopeRequirements(lifecycle, save);\n if (now.refused) throw new MailAccessError('draft', 'denied');\n for (const key of now.keys) {\n if (!enforced.keys.has(key)) {\n throw new MailAccessError(\n key.slice(0, key.indexOf(':')) as MailScope,\n 'denied',\n );\n }\n }\n }\n\n /** The `scope:accountId` pairs this write needs, read through `this.db`. */\n private async draftScopeRequirements(\n lifecycle: boolean,\n save: boolean,\n ): Promise<DraftRequirements> {\n const result = emptyRequirements();\n const row = this as unknown as Record<string, unknown>;\n const write = save ? 'save' : 'delete';\n const priorAccountIds: string[] = [];\n // Accounts of stored `sent` rows this write changes, moves or deletes.\n const sentAccountIds: string[] = [];\n let storedSent = false;\n let stored: Record<string, unknown> | null = null;\n let unchanged = false;\n let triageOnly = false;\n if (this.id) {\n stored = await this.getCanonicalPersistedRow({ id: this.id });\n if (stored) {\n if (isMailWriteGated(stored, write)) {\n priorAccountIds.push(String(stored.account_id ?? ''));\n }\n storedSent = stored.send_status === 'sent';\n if (storedSent) sentAccountIds.push(String(stored.account_id ?? ''));\n if (\n save &&\n stored.send_status === 'sent' &&\n row.sendStatus !== 'sent'\n ) {\n result.refused = true;\n }\n unchanged = this.matchesStoredBeyond(\n stored,\n SEND_PATH_MAY_CHANGE,\n true,\n );\n triageOnly =\n save && this.matchesStoredBeyond(stored, TRIAGE_MAY_CHANGE, false);\n }\n }\n // A new object is written over the stored row that carries its natural\n // key (the slug it has, or the one the save derives from its id), whatever\n // its own id: that row, not the id, is what the save changes.\n let takesOver = false;\n if (!this.isPersisted) {\n const columns = ObjectRegistry.getConflictColumns(\n this.getResolvedQualifiedName(),\n );\n if (columns.includes('slug')) {\n const slug =\n typeof row.slug === 'string' && row.slug\n ? row.slug\n : await this.getSlug();\n if (typeof slug === 'string' && slug) {\n // Match on the slug alone: the tenant is filled in during the save,\n // after this check, so any narrower filter could miss the row the\n // save takes over. It can only over-match, which means an extra\n // check.\n for (const keyed of await this.getCanonicalPersistedRows({ slug })) {\n if (keyed.id === this.id) continue;\n takesOver = true;\n unchanged = false;\n triageOnly = false;\n if (keyed.send_status === 'sent' && row.sendStatus !== 'sent') {\n result.refused = true;\n }\n if (isMailWriteGated(keyed, write)) {\n priorAccountIds.push(String(keyed.account_id ?? ''));\n }\n if (keyed.send_status === 'sent') {\n sentAccountIds.push(String(keyed.account_id ?? ''));\n }\n }\n }\n }\n }\n if (result.refused) return result;\n if (triageOnly) {\n // Read and flag marks are not content, but they are triage: the stored\n // row's account decides, under the triage scope instead of draft.\n for (const id of priorAccountIds) if (id) result.keys.add(`triage:${id}`);\n if (storedSent) {\n for (const id of sentAccountIds)\n if (id) result.keys.add(`triage:${id}`);\n }\n return result;\n }\n // Sent mail is a record that replies and forwards quote. Outside the\n // triage fields, changing, moving or deleting a stored `sent` row needs\n // `send` on the account it is on and on the one it moves to.\n for (const id of sentAccountIds) if (id) result.keys.add(`send:${id}`);\n if (storedSent && save && this.accountId) {\n result.keys.add(`send:${this.accountId}`);\n }\n const fresh = !stored && !takesOver;\n const outgoingNow = isMailWriteGated(row, write);\n // A sent record comes into being through the send path or trusted sync.\n // Replies and forwards quote it, so writing a row into `sent` needs the\n // `send` scope on its account, whatever it was before.\n if (\n save &&\n row.sendStatus === 'sent' &&\n (fresh ||\n takesOver ||\n stored?.send_status !== 'sent' ||\n String(stored.account_id ?? '') !== this.accountId) &&\n this.accountId\n ) {\n result.keys.add(`send:${this.accountId}`);\n }\n if (!outgoingNow && !priorAccountIds.length) return result;\n const sanctioned =\n (lifecycle && ((stored && unchanged) || fresh)) ||\n (fresh && queuedCreates.has(this));\n const scope: MailScope = sanctioned ? 'send' : 'draft';\n result.lifecycle = Boolean(lifecycle && ((stored && unchanged) || fresh));\n for (const id of [outgoingNow ? this.accountId : '', ...priorAccountIds]) {\n if (id) result.keys.add(`${scope}:${id}`);\n }\n return result;\n }\n\n /**\n * Whether every field outside `allowed` equals `stored`. `held` lets a held\n * send raise the draft flag.\n */\n private matchesStoredBeyond(\n stored: Record<string, unknown>,\n allowed: ReadonlySet<string>,\n held: boolean,\n ): boolean {\n const row = this as unknown as Record<string, unknown>;\n const qualified = this.getResolvedQualifiedName();\n const names = new Set([\n ...this.draftFieldNames(),\n 'tenantId',\n 'slug',\n 'context',\n ]);\n let registered: ReadonlyMap<\n string,\n {\n type?: string;\n transient?: boolean;\n _meta?: { transient?: boolean };\n }\n >;\n try {\n registered = ObjectRegistry.getFields(qualified);\n } catch {\n registered = new Map();\n }\n // Fields kept in the `_meta_data` bag of an STI row.\n let storedMeta: Record<string, unknown> | null | undefined;\n const metaOf = (): Record<string, unknown> | null => {\n if (storedMeta !== undefined) return storedMeta;\n const raw = stored._meta_data;\n storedMeta = null;\n if (raw === undefined || raw === null || raw === '') {\n storedMeta = {};\n } else if (typeof raw === 'object') {\n storedMeta = raw as Record<string, unknown>;\n } else if (typeof raw === 'string') {\n try {\n const parsed: unknown = JSON.parse(raw);\n if (parsed && typeof parsed === 'object') {\n storedMeta = parsed as Record<string, unknown>;\n }\n } catch {\n // Unreadable: nothing can be compared, so the row counts as changed.\n }\n }\n return storedMeta;\n };\n // Write-through fields live on a linked record: any pending edit is a\n // change, and so is a draft the instance does not expose.\n const writeThrough: string[] = [];\n try {\n // Names come from the declaration itself, as core persists them; the\n // linked target is not resolved, so a lookup failure cannot refuse a\n // save that carries no pending edit.\n for (const link of Object.values(\n ObjectRegistry.getConfig(qualified).writeThrough ?? {},\n )) {\n writeThrough.push(\n ...link.fields,\n ...Object.keys(link.virtualFields ?? {}),\n );\n }\n } catch {\n return false;\n }\n if (writeThrough.length) {\n const pending = new Set(this.getPendingWriteThroughFields());\n for (const name of writeThrough) {\n if (allowed.has(name)) continue;\n if (pending.has(name)) return false;\n }\n }\n for (const name of names) {\n if (allowed.has(name)) continue;\n // A held send flags the message as a draft; it may raise the flag only.\n if (\n held &&\n name === 'isDraft' &&\n heldSaves.has(this) &&\n mailFlag(row[name])\n ) {\n continue;\n }\n // A class without the property cannot carry a value for it.\n if (!(name in this)) continue;\n if (writeThrough.includes(name)) continue;\n const definition = registered.get(name);\n const column = toSnakeCase(name);\n let storedValue: unknown;\n if (definition?.type === 'meta') {\n const bag = metaOf();\n if (!bag) return false;\n storedValue = bag[name];\n } else if (column in stored) {\n storedValue = stored[column];\n } else if (\n definition &&\n !definition.transient &&\n !definition._meta?.transient &&\n definition.type !== 'oneToMany' &&\n definition.type !== 'manyToMany'\n ) {\n // A registered field this comparison cannot read back counts as\n // changed: it cannot be shown to equal the stored row.\n return false;\n } else {\n continue;\n }\n const mine = row[name];\n const same =\n typeof mine === 'boolean'\n ? mine === mailFlag(storedValue)\n : canonValue(mine) === canonValue(storedValue);\n if (!same) return false;\n }\n return true;\n }\n\n private async finalizeSendLifecycle(\n result: MessageSendResult,\n actor: MailPrincipal | null = null,\n ): Promise<void> {\n if (!this.id) throw new Error('Cannot finalize an unsaved message send');\n\n const sendStatus: SendStatus = result.success ? 'sent' : 'failed';\n const sendError = result.success ? '' : (result.error ?? 'Send failed');\n const useEmbeddedFallback = usesEmbeddedRevisionFallback(this.db);\n for (let attempt = 0; attempt < 8; attempt += 1) {\n let nextRevision: Date | undefined;\n await withEmbeddedWriteQueue(this.db, useEmbeddedFallback, async () => {\n const current = await this.getCanonicalPersistedRow({ id: this.id });\n if (current?.send_status !== 'sending') return;\n const currentRevision = current.updated_at;\n const currentRevisionMs = new Date(String(currentRevision)).getTime();\n if (!Number.isFinite(currentRevisionMs)) return;\n nextRevision = new Date(Math.max(Date.now(), currentRevisionMs + 1));\n // Record durably whether a failure may still have been accepted, so a\n // later reconciliation can tell it from a definite rejection.\n const metadata = withSendOutcomeMarker(\n current.metadata,\n !result.success && result.outcomeUnknown === true,\n );\n if (actor) stampHandledBy(this, actor, nextRevision);\n const values = {\n send_status: sendStatus,\n sent_at: result.success ? result.sentAt : null,\n send_error: sendError,\n updated_at: nextRevision,\n ...(metadata === undefined ? {} : { metadata }),\n ...(actor\n ? {\n handled_by_id: this.handledById,\n handled_by_kind: this.handledByKind,\n handled_at: this.handledAt,\n }\n : {}),\n };\n if (useEmbeddedFallback) {\n await this.db.upsert(this.tableName, ['id'], {\n ...current,\n ...values,\n });\n return;\n }\n await this.db.update(\n this.tableName,\n {\n id: this.id,\n send_status: 'sending',\n updated_at:\n currentRevision instanceof Date\n ? currentRevision.toISOString()\n : currentRevision,\n },\n values,\n );\n });\n // DuckDB's generic update result reports one affected row even when the\n // predicate matched none. Verify the durable lifecycle value instead of\n // trusting adapter row-count metadata before declaring finalization.\n const verified = await this.getCanonicalPersistedRow({ id: this.id });\n if (verified?.send_status === sendStatus) {\n await this.completePersistedUpdate(verified);\n return;\n }\n }\n throw new Error('Cannot finalize: message revision kept changing');\n }\n\n /**\n * Get to addresses as parsed array\n */\n getToAddresses(): Array<{ address: string; name?: string }> {\n if (!this.toAddresses) return [];\n try {\n return JSON.parse(this.toAddresses);\n } catch {\n return [];\n }\n }\n\n /**\n * Set to addresses from array\n */\n setToAddresses(addresses: Array<{ address: string; name?: string }>): void {\n this.toAddresses = JSON.stringify(addresses);\n }\n\n /**\n * Get metadata as parsed object\n */\n getMetadata(): Record<string, unknown> {\n if (!this.metadata) return {};\n try {\n return JSON.parse(this.metadata);\n } catch {\n return {};\n }\n }\n\n /**\n * Set metadata from object\n */\n setMetadata(data: Record<string, unknown>): void {\n this.metadata = JSON.stringify(data);\n }\n\n /**\n * Mark message as read\n */\n async markRead(): Promise<void> {\n this.isRead = true;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Mark message as unread\n */\n async markUnread(): Promise<void> {\n this.isRead = false;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Toggle flagged status\n */\n async toggleFlagged(): Promise<void> {\n this.isFlagged = !this.isFlagged;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Check if message is unread\n */\n isUnread(): boolean {\n return !this.isRead;\n }\n\n /**\n * Get a short preview of the message body\n */\n getPreview(maxLength = 200): string {\n const text = this.body || '';\n if (text.length <= maxLength) return text;\n return `${text.slice(0, maxLength)}...`;\n }\n\n /**\n * Direct hydration (`new X({ id }).initialize()`, `loadRelated()`) bypasses\n * the collection read hooks, so the per-account mail policy is applied here\n * too: a row of an account closed to the principal never hydrates.\n */\n override async loadFromId() {\n await super.loadFromId();\n await assertHydratedMailAccess({\n accountId: this.accountId,\n options: this.options,\n });\n }\n\n override async loadFromSlug() {\n await super.loadFromSlug();\n await assertHydratedMailAccess({\n accountId: this.accountId,\n options: this.options,\n });\n }\n\n /**\n * Get the account for this message\n */\n async getAccount() {\n if (!this.accountId) return null;\n\n const { AccountCollection } = await import(\n '../collections/AccountCollection'\n );\n const collection = await AccountCollection.create(this.options);\n\n return await collection.get({ id: this.accountId });\n }\n\n async getEndpoint() {\n if (!this.endpointId) return null;\n const { MessagingEndpointCollection } = await import(\n '../collections/MessagingEndpointCollection.js'\n );\n const collection = await MessagingEndpointCollection.create(this.options);\n return collection.get({ id: this.endpointId });\n }\n\n /**\n * Get messages in the same thread\n */\n async getThreadMessages(): Promise<Message[]> {\n if (!this.threadId) return [this];\n\n const { MessageCollection } = await import(\n '../collections/MessageCollection'\n );\n const collection = await MessageCollection.create(this.options);\n\n return await collection.list({ where: { threadId: this.threadId } });\n }\n\n /**\n * Get attachments for this message\n */\n async getAttachments() {\n const { AttachmentCollection } = await import(\n '../collections/AttachmentCollection'\n );\n const collection = await AttachmentCollection.create(this.options);\n\n return await collection.list({ where: { messageId: this.id } });\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Send Lifecycle\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Send this message via its account's sender\n */\n async send(options?: SendMessageOptions): Promise<MessageSendResult> {\n try {\n await beginProtectedNotificationSend(this, options);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n sentAt: new Date(),\n };\n }\n // Received mail is a record of what arrived, never an outgoing message.\n // The stored row counts too: a base `Message` handle carries no\n // provider-id fields of its subclass.\n const storedRow = this.id\n ? await this.getCanonicalPersistedRow({ id: this.id })\n : null;\n if (\n isReceivedMail(this as unknown as Record<string, unknown>) ||\n (storedRow && isReceivedMail(storedRow))\n ) {\n return {\n success: false,\n error: 'Cannot send: this is received mail',\n sentAt: new Date(),\n };\n }\n // Entry guard: a message that is already in flight or delivered must not be\n // sent again. Catches same-instance double-clicks before any work happens.\n if (this.sendStatus === 'sending' || this.sendStatus === 'sent') {\n return {\n success: false,\n error: `Cannot send: message is already '${this.sendStatus}'`,\n sentAt: new Date(),\n };\n }\n\n // Resolve account\n const account = await this.getAccount();\n if (!account) {\n const result: MessageSendResult = {\n success: false,\n error: 'No account associated with this message',\n sentAt: new Date(),\n };\n this.sendStatus = 'failed';\n this.sendError = result.error ?? '';\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n return result;\n }\n\n if (!account.isActive) {\n const result: MessageSendResult = {\n success: false,\n error: 'Messaging account is inactive',\n sentAt: new Date(),\n };\n this.sendStatus = 'failed';\n this.sendError = result.error ?? '';\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n return result;\n }\n\n // Owned accounts need the `send` scope. A denial leaves the message as it\n // was: a refused principal must not mark someone else's draft failed.\n const access = await decideMailAccess(account, 'send');\n if (!access.allowed) {\n return {\n success: false,\n error: 'Mail access denied for scope send',\n sentAt: new Date(),\n };\n }\n\n // The acting principal (host-supplied). Trusted system work (sync, the\n // notification outbox) has none and is never held or stamped.\n const actor = inMailSystemAccess() ? null : await resolveMailPrincipal();\n\n // Send-as: from any mail account, everything but trusted system work\n // sends only from the account's own address. Sending as anyone else needs\n // a delegation grant, which does not exist yet, so it is refused.\n if (!inMailSystemAccess() && 'email' in account) {\n const from = (this.fromAddress || '').trim().toLowerCase();\n const own = String((account as { email?: unknown }).email ?? '')\n .trim()\n .toLowerCase();\n if (from && from !== own) {\n return {\n success: false,\n error: \"Mail can only be sent from the account's own address.\",\n sentAt: new Date(),\n };\n }\n }\n\n // Agents follow the account's send policy: by default the draft is held\n // for a person's approval and nothing leaves (smrt#5141).\n // Trusted system work is not held, except a persona (agent) message: a\n // system drain must never send an agent's message around its approval.\n const held =\n inMailSystemAccess() && !this.personaId\n ? null\n : await holdAgentSend(this, account, options, actor);\n if (held) {\n // A held message is a draft: out of any pending/scheduled outbox, and\n // decidable by a person. Content is untouched, so the binding holds.\n const toDraft =\n held.pendingApproval !== undefined && this.sendStatus !== 'draft';\n if (toDraft) this.sendStatus = 'draft';\n // A held message is a flagged draft, not a plain `draft` status (which\n // received mail carries), so it stays under the draft scope.\n const flagDraft =\n held.pendingApproval !== undefined &&\n 'isDraft' in this &&\n !mailFlag((this as unknown as { isDraft?: unknown }).isDraft);\n if (flagDraft) (this as unknown as { isDraft: boolean }).isDraft = true;\n if (held.pendingApproval?.created) stampHandledBy(this, actor);\n if (toDraft || flagDraft || held.pendingApproval?.created) {\n await saveHeld(this);\n }\n // A refused send of a queued message fails definitely (nothing left),\n // so it does not linger as `pending` for a later drain.\n if (\n held.pendingApproval === undefined &&\n (this.sendStatus === 'pending' || this.sendStatus === 'scheduled') &&\n this.isPersisted\n ) {\n this.sendStatus = 'failed';\n this.sendError = held.error ?? 'Send refused';\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n }\n return held;\n }\n // Audited before anything is claimed: an audit failure sends nothing.\n if (actor) await auditMailAction('messages.send', this);\n\n // Get sender from account\n let sender: Awaited<ReturnType<typeof account.createSender>>;\n try {\n sender = await account.createSender();\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n this.sendStatus = 'failed';\n this.sendError = errorMessage;\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n return {\n success: false,\n error: errorMessage,\n sentAt: new Date(),\n };\n }\n\n // Claim the send. For a persisted row, do a compare-and-set so only one\n // concurrent sender wins: flip send_status to 'sending' atomically, gated on\n // the status we observed. If no row matched, another sender already claimed\n // it — abort without delivering (prevents duplicate sends). For an unsaved\n // draft there is no row yet, so the in-memory transition + save() (INSERT)\n // serves as the claim.\n const claimFromStatus = this.sendStatus;\n if (this.isPersisted && this.id) {\n const loadedRevision = this.updated_at;\n if (!loadedRevision) {\n return {\n success: false,\n error: 'Cannot send: persisted message has no loaded revision',\n sentAt: new Date(),\n };\n }\n const claimedRevision = new Date(\n Math.max(Date.now(), loadedRevision.getTime() + 1),\n );\n const useEmbeddedFallback = usesEmbeddedRevisionFallback(this.db);\n let claimed = false;\n await withEmbeddedWriteQueue(this.db, useEmbeddedFallback, async () => {\n if (useEmbeddedFallback) {\n const current = await this.getCanonicalPersistedRow({ id: this.id });\n const storedRevision = current?.updated_at;\n const currentRevision =\n storedRevision instanceof Date\n ? storedRevision.getTime()\n : typeof storedRevision === 'string'\n ? Date.parse(storedRevision)\n : Number.NaN;\n if (\n !current ||\n current.send_status !== claimFromStatus ||\n !Number.isFinite(currentRevision) ||\n currentRevision !== loadedRevision.getTime()\n )\n return;\n await this.db.upsert(this.tableName, ['id'], {\n ...current,\n send_status: 'sending',\n updated_at: claimedRevision,\n });\n claimed = true;\n return;\n }\n const claim = await this.db.update(\n this.tableName,\n {\n id: this.id,\n send_status: claimFromStatus,\n updated_at: loadedRevision.toISOString(),\n },\n { send_status: 'sending', updated_at: claimedRevision },\n );\n claimed = claim?.affected === 1;\n });\n if (!claimed) {\n return {\n success: false,\n error: 'Cannot send: message is already being sent',\n sentAt: new Date(),\n };\n }\n this.sendStatus = 'sending';\n this.updated_at = claimedRevision;\n this.updatedAt = new Date();\n } else {\n this.sendStatus = 'sending';\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n }\n\n // A send an approval released must still be the approved draft now that\n // the row is claimed (attachment rows are not covered by the claim).\n if (await approvedDraftChanged(this)) {\n const changed: MessageSendResult = {\n success: false,\n error: 'The draft changed after it was approved; nothing was sent.',\n sentAt: new Date(),\n };\n await this.finalizeSendLifecycle(changed, actor);\n return changed;\n }\n\n let result: MessageSendResult;\n try {\n await assertProtectedSenderHandoff(this, options);\n result = await sender.send(this, options);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n // A sender that throws mid-send says nothing about provider acceptance.\n result = {\n success: false,\n error: errorMessage,\n ...(error instanceof ProtectedNotificationHandoffError\n ? {}\n : { outcomeUnknown: true }),\n sentAt: new Date(),\n };\n }\n await this.finalizeSendLifecycle(result, actor);\n return result;\n }\n\n /** Who last acted on this message, or null. */\n getHandledBy(): { id: string; kind: string; at: Date | null } | null {\n if (!this.handledById) return null;\n return {\n id: this.handledById,\n kind: this.handledByKind || 'agent',\n at: this.handledAt,\n };\n }\n\n /**\n * Whether the latest failed send may still have been accepted by the\n * provider (see `MessageSendResult.outcomeUnknown`).\n */\n isSendOutcomeUnknown(): boolean {\n return (\n this.sendStatus === 'failed' &&\n this.getMetadata()[SEND_OUTCOME_UNKNOWN_METADATA_KEY] === true\n );\n }\n\n /**\n * Release a send claim whose sender is gone (a crash or lost lease left the\n * row in `sending`): move it to `failed` with an unknown outcome so the\n * owner of the delivery decision can send it again. Returns false, changing\n * nothing, unless the stored row is still `sending`. Only for callers that\n * have established that no live sender holds the claim.\n */\n async abandonSendAttempt(reason: string): Promise<boolean> {\n if (!this.id) return false;\n const current = await this.getCanonicalPersistedRow({ id: this.id });\n if (current?.send_status !== 'sending') return false;\n try {\n await this.finalizeSendLifecycle({\n success: false,\n error: reason,\n outcomeUnknown: true,\n sentAt: new Date(),\n });\n } catch {\n return false;\n }\n return this.sendStatus === 'failed';\n }\n\n /**\n * Retry sending a failed message\n */\n async retrySend(options?: SendMessageOptions): Promise<MessageSendResult> {\n try {\n await assertProtectedNotificationRetry(this, options);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n sentAt: new Date(),\n };\n }\n if (this.sendStatus !== 'failed') {\n return {\n success: false,\n error: `Cannot retry: message status is '${this.sendStatus}', expected 'failed'`,\n sentAt: new Date(),\n };\n }\n\n if (this.retryCount >= this.maxRetries) {\n return {\n success: false,\n error: `Retry budget exhausted (${this.retryCount}/${this.maxRetries})`,\n sentAt: new Date(),\n };\n }\n\n this.retryCount++;\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n\n return this.send(options);\n }\n\n /**\n * Options for a derived draft (reply/forward) built from this message. Carries\n * the DB connection + tenant context from `this.options`, but strips this\n * message's own identity fields. When this message was hydrated from the DB,\n * `this.options` holds the row's `id`/`slug`/`context`/`_skipLoad`; spreading\n * those into a new draft would make `draft.save()` upsert onto the natural-key\n * conflict columns (`slug`/`context`/`_meta_type`) and overwrite the ORIGINAL\n * message instead of inserting a new row. See EmailAccount.childOptions().\n */\n protected draftOptions(): Record<string, unknown> {\n const rest = { ...(this.options as Record<string, unknown>) };\n delete rest.id;\n delete rest.slug;\n delete rest.context;\n delete rest._skipLoad;\n // `this.options` of a hydrated row carries every stored column. A derived\n // draft must not inherit any of them (htmlBody, bcc, messageId, headers,\n // send state, handled-by, ...); createReply/createForward then set back\n // only what reply/forward semantics define. Only connection and tenant\n // context survive.\n // `personaId` is dropped on purpose: a reply is authored by the replying\n // principal, so it falls under that principal's hold rules, not the\n // persona the inbound message happened to be addressed through.\n // `metadata` and `correlationId` stay: the protected-notification\n // handoff keys its provenance on them, so a derived draft of a protected\n // notification must keep failing closed. Neither is sent as mail content.\n for (const name of this.draftFieldNames()) {\n if (!DRAFT_CARRIED_FIELDS.has(name)) delete rest[name];\n }\n return rest;\n }\n\n /** Every stored field name of this message's class, including subclasses. */\n private draftFieldNames(): string[] {\n const names = new Set<string>(DRAFT_RESET_FIELDS);\n try {\n for (const key of ObjectRegistry.getFields(\n this.getResolvedQualifiedName(),\n ).keys()) {\n names.add(key);\n }\n } catch {\n // The static list above still covers every field this package declares.\n }\n return [...names];\n }\n\n /**\n * Create a reply to this message (returns unsaved draft)\n */\n createReply(_options?: { replyAll?: boolean }): Message {\n const reply = new (this.constructor as typeof Message)({\n ...this.draftOptions(),\n id: undefined,\n accountId: this.accountId,\n threadId: this.threadId || this.id || '',\n subject: this.subject.startsWith('Re:')\n ? this.subject\n : `Re: ${this.subject}`,\n toAddresses: JSON.stringify([\n { address: this.fromAddress, name: this.fromName },\n ]),\n fromAddress: '',\n fromName: '',\n body: this.buildQuotedBody(),\n inReplyToMessageId: this.id || '',\n sendStatus: 'draft',\n isRead: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n });\n\n return reply;\n }\n\n /**\n * Create a forward of this message (returns unsaved draft)\n */\n createForward(): Message {\n const forward = new (this.constructor as typeof Message)({\n ...this.draftOptions(),\n id: undefined,\n accountId: this.accountId,\n threadId: '',\n subject: this.subject.startsWith('Fwd:')\n ? this.subject\n : `Fwd: ${this.subject}`,\n toAddresses: '[]',\n fromAddress: '',\n fromName: '',\n body: this.buildQuotedBody(),\n // Attachment rows are not copied, so the draft has none.\n hasAttachments: false,\n inReplyToMessageId: '',\n sendStatus: 'draft',\n isRead: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n });\n\n return forward;\n }\n\n /**\n * Build quoted body for reply/forward\n */\n protected buildQuotedBody(): string {\n const dateStr = this.date ? this.date.toLocaleString() : 'unknown date';\n const from = this.fromName\n ? `${this.fromName} <${this.fromAddress}>`\n : this.fromAddress;\n\n const quotedLines = (this.body || '')\n .split('\\n')\n .map((line) => `> ${line}`)\n .join('\\n');\n\n return `\\n\\nOn ${dateStr}, ${from} wrote:\\n${quotedLines}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA8DO,IAAM,oCAAoC;AAMjD,SAAS,sBACP,QACA,gBACoB;CACpB,IAAI,MAA+B,CAAC;CACpC,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,GAC5C,IAAI;EACF,MAAM,SAAkB,KAAK,MAAM,MAAM;EACzC,IAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GAC/D;EAEF,MAAM;CACR,QAAQ;EACN;CACF;CAEF,IAAI,QAAQ,IAAA,qBAAsC,MAAM,gBACtD;CAEF,IAAI,gBAAgB,IAAI,qCAAqC;MACxD,OAAO,IAAI;CAChB,OAAO,KAAK,UAAU,GAAG;AAC3B;AAIA,IAAM,iCAAiB,IAAI,QAAyB;AACpD,SAAS,mBAAmB,SAA0B;CACpD,OAAO,KAAK,UAAU;EACpB,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;CACV,CAAC;AACH;AACA,eAAe,kBAAkB,SAAiC;CAChE,eAAe,IAAI,SAAS,mBAAmB,OAAO,CAAC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,WAAA,cAAA,CAAA;AAEA,gBAAA,CADC,MAAM,EAAE,aAAa,6CAA6C,CAAC,CAAA,GAlEzD,QAmEX,WAAA,mBAAA,CAAA;AAGA,gBAAA,CAFC,WAAW,SAAS,GACpB,MAAM,EAAE,aAAa,2CAA2C,CAAC,CAAA,GArEvD,QAsEX,WAAA,sBAAA,CAAA;AAQA,gBAAA,CAJC,MAAM;CACL,UAAU;CACV,aAAa;AACf,CAAC,CAAA,GA7EU,QA8EX,WAAA,eAAA,CAAA;AAKA,gBAAA,CAJC,MAAM;CACL,UAAU;CACV,aAAa;AACf,CAAC,CAAA,GAlFU,QAmFX,WAAA,iBAAA,CAAA;AAKA,gBAAA,CAJC,MAAM;CACL,UAAU;CACV,aAAa;AACf,CAAC,CAAA,GAvFU,QAwFX,WAAA,aAAA,CAAA;AAIA,gBAAA,CADC,MAAM,EAAE,aAAa,kCAAkC,CAAC,CAAA,GA3F9C,QA4FX,WAAA,aAAA,CAAA;AAEA,gBAAA,CADC,MAAM,EAAE,aAAa,sCAAsC,CAAC,CAAA,GA7FlD,QA8FX,WAAA,aAAA,CAAA;AA9FW,UAAN,gBAAA,CAPN,aAAa,EAAE,MAAM,WAAW,CAAC,GACjC,KAAK;CACJ,eAAe;CACf,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,cAAc,KAAK;AAC5B,CAAC,CAAA,GACY,OAAA"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
2
|
import { queryGlobal, queryWithGlobals } from "../host.js";
|
|
3
|
-
import { t as Message } from "./Message-
|
|
3
|
+
import { t as Message } from "./Message-D-FgiSxn.js";
|
|
4
4
|
import { SmrtCollection } from "@happyvertical/smrt-core";
|
|
5
5
|
//#region src/collections/MessageCollection.ts
|
|
6
6
|
var MessageCollection_exports = /* @__PURE__ */ __exportAll({ MessageCollection: () => MessageCollection });
|
|
@@ -170,4 +170,4 @@ var MessageCollection = class extends SmrtCollection {
|
|
|
170
170
|
//#endregion
|
|
171
171
|
export { MessageCollection_exports as n, MessageCollection as t };
|
|
172
172
|
|
|
173
|
-
//# sourceMappingURL=MessageCollection-
|
|
173
|
+
//# sourceMappingURL=MessageCollection-iMnpnr3K.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MessageCollection-BIh13Nyl.js","names":[],"sources":["../../src/collections/MessageCollection.ts"],"sourcesContent":["/**\n * MessageCollection - Unified collection for polymorphic message queries\n *\n * Queries the messages table with STI, returning correct subclass instances.\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { queryGlobal, queryWithGlobals } from '../host.js';\nimport { Message } from '../models/Message';\nimport type { MessageSearchFilters } from '../types';\n\nexport class MessageCollection extends SmrtCollection<Message> {\n static readonly _itemClass = Message;\n\n /**\n * Search messages with filters\n */\n async search(\n query: string,\n filters?: MessageSearchFilters,\n ): Promise<Message[]> {\n let messages = await this.list({});\n\n // Filter by query\n if (query) {\n const lowerQuery = query.toLowerCase();\n messages = messages.filter(\n (m) =>\n m.subject?.toLowerCase().includes(lowerQuery) ||\n m.body?.toLowerCase().includes(lowerQuery) ||\n m.fromAddress?.toLowerCase().includes(lowerQuery) ||\n m.fromName?.toLowerCase().includes(lowerQuery),\n );\n }\n\n // Apply filters\n if (filters) {\n if (filters.accountIds && filters.accountIds.length > 0) {\n messages = messages.filter((m) =>\n filters.accountIds?.includes(m.accountId),\n );\n }\n if (filters.messageType) {\n messages = messages.filter((m) => {\n const metaType = (m as { _meta_type?: string })._meta_type || '';\n return metaType.includes(filters.messageType as string);\n });\n }\n if (filters.from) {\n const fromLower = filters.from.toLowerCase();\n messages = messages.filter(\n (m) =>\n m.fromAddress?.toLowerCase().includes(fromLower) ||\n m.fromName?.toLowerCase().includes(fromLower),\n );\n }\n if (filters.to) {\n const toLower = filters.to.toLowerCase();\n messages = messages.filter((m) =>\n m.toAddresses?.toLowerCase().includes(toLower),\n );\n }\n if (filters.isRead !== undefined) {\n messages = messages.filter((m) => m.isRead === filters.isRead);\n }\n if (filters.isFlagged !== undefined) {\n messages = messages.filter((m) => m.isFlagged === filters.isFlagged);\n }\n if (filters.sinceDate) {\n messages = messages.filter(\n (m) => m.date && m.date >= (filters.sinceDate as Date),\n );\n }\n if (filters.beforeDate) {\n messages = messages.filter(\n (m) => m.date && m.date < (filters.beforeDate as Date),\n );\n }\n if (filters.query) {\n const q = filters.query.toLowerCase();\n messages = messages.filter(\n (m) =>\n m.subject?.toLowerCase().includes(q) ||\n m.body?.toLowerCase().includes(q),\n );\n }\n }\n\n return messages;\n }\n\n /**\n * Get messages by multiple accounts\n */\n async getByAccounts(accountIds: string[]): Promise<Message[]> {\n const allMessages = await this.list({});\n return allMessages.filter((m) => accountIds.includes(m.accountId));\n }\n\n /**\n * Get messages by STI type.\n *\n * Accepts either the full discriminator (e.g. \"@happyvertical/smrt-messages:Email\")\n * or the short type name (e.g. \"Email\").\n */\n async getByType(messageType: string): Promise<Message[]> {\n if (messageType.includes(':') || messageType.startsWith('@')) {\n return await this.list({ where: { _meta_type: messageType } });\n }\n const allMessages = await this.list({});\n return allMessages.filter((m) => {\n const metaType = (m as { _meta_type?: string })._meta_type || '';\n return metaType.endsWith(`:${messageType}`);\n });\n }\n\n /**\n * Get unread messages\n */\n async getUnread(accountId?: string): Promise<Message[]> {\n const where: Record<string, unknown> = { isRead: false };\n if (accountId) {\n where.accountId = accountId;\n }\n return await this.list({ where });\n }\n\n /**\n * Get flagged messages\n */\n async getFlagged(accountId?: string): Promise<Message[]> {\n const where: Record<string, unknown> = { isFlagged: true };\n if (accountId) {\n where.accountId = accountId;\n }\n return await this.list({ where });\n }\n\n /**\n * Get recent messages\n */\n async getRecent(limit = 20, accountId?: string): Promise<Message[]> {\n const allMessages = await this.list({\n where: accountId ? { accountId } : undefined,\n });\n\n return allMessages\n .sort((a, b) => {\n const dateA = a.date?.getTime() || 0;\n const dateB = b.date?.getTime() || 0;\n return dateB - dateA;\n })\n .slice(0, limit);\n }\n\n /**\n * Get messages by thread\n */\n async getByThread(threadId: string): Promise<Message[]> {\n return await this.list({ where: { threadId } });\n }\n\n /**\n * Mark multiple messages as read\n */\n async markAllRead(messageIds: string[]): Promise<void> {\n // One refused or failed row does not stop the rest; the first error is\n // raised once every row has been tried.\n let failure: unknown;\n for (const id of messageIds) {\n try {\n const message = await this.get({ id });\n if (message) {\n await message.markRead();\n }\n } catch (error) {\n failure ??= error;\n }\n }\n if (failure) throw failure;\n }\n\n /**\n * Get message statistics for an account\n */\n async getAccountStats(accountId: string): Promise<{\n total: number;\n unread: number;\n flagged: number;\n byType: Record<string, number>;\n }> {\n const messages = await this.list({ where: { accountId } });\n const byType: Record<string, number> = {};\n\n for (const msg of messages) {\n const metaType = (msg as { _meta_type?: string })._meta_type || 'Unknown';\n const shortType = metaType.split(':').pop() || metaType;\n byType[shortType] = (byType[shortType] || 0) + 1;\n }\n\n return {\n total: messages.length,\n unread: messages.filter((m) => !m.isRead).length,\n flagged: messages.filter((m) => m.isFlagged).length,\n byType,\n };\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Send / Draft Queries\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Get draft messages\n */\n async getDrafts(accountId?: string): Promise<Message[]> {\n const where: Record<string, unknown> = { sendStatus: 'draft' };\n if (accountId) where.accountId = accountId;\n return await this.list({ where });\n }\n\n /**\n * Get sent messages\n */\n async getSent(accountId?: string): Promise<Message[]> {\n const where: Record<string, unknown> = { sendStatus: 'sent' };\n if (accountId) where.accountId = accountId;\n return await this.list({ where });\n }\n\n /**\n * Get scheduled messages\n */\n async getScheduled(accountId?: string): Promise<Message[]> {\n const where: Record<string, unknown> = { sendStatus: 'scheduled' };\n if (accountId) where.accountId = accountId;\n return await this.list({ where });\n }\n\n /**\n * Get messages that failed to send\n */\n async getFailedSends(accountId?: string): Promise<Message[]> {\n const where: Record<string, unknown> = { sendStatus: 'failed' };\n if (accountId) where.accountId = accountId;\n return await this.list({ where });\n }\n\n /**\n * Get outbox (pending + sending + scheduled)\n */\n async getOutbox(accountId?: string): Promise<Message[]> {\n const allMessages = await this.list({\n where: accountId ? { accountId } : undefined,\n });\n return allMessages.filter(\n (m) =>\n m.sendStatus === 'pending' ||\n m.sendStatus === 'sending' ||\n m.sendStatus === 'scheduled',\n );\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n async findByTenant(tenantId: string): Promise<Message[]> {\n return this.list({ where: { tenantId } });\n }\n\n // Message is the @TenantScoped STI base, so an explicit `tenant_id IS NULL`\n // filter via list() throws and unflagged raw SQL is blocked under an active\n // tenant context (#1596). Route through the raw helpers — no `_meta_type`\n // scope so the base collection still returns ALL message subtypes.\n async findGlobal(): Promise<Message[]> {\n return queryGlobal<Message>(this);\n }\n\n async findWithGlobals(tenantId: string): Promise<Message[]> {\n return queryWithGlobals<Message>(this, tenantId, 'Message.findWithGlobals');\n }\n}\n"],"mappings":";;;;;;AAWO,IAAM,oBAAN,cAAgC,eAAwB;CAC7D,OAAgB,aAAa;;;;CAK7B,MAAM,OACJ,OACA,SACoB;EACpB,IAAI,WAAW,MAAM,KAAK,KAAK,CAAC,CAAC;EAGjC,IAAI,OAAO;GACT,MAAM,aAAa,MAAM,YAAY;GACrC,WAAW,SAAS,QACjB,MACC,EAAE,SAAS,YAAY,CAAA,CAAE,SAAS,UAAU,KAC5C,EAAE,MAAM,YAAY,CAAA,CAAE,SAAS,UAAU,KACzC,EAAE,aAAa,YAAY,CAAA,CAAE,SAAS,UAAU,KAChD,EAAE,UAAU,YAAY,CAAA,CAAE,SAAS,UAAU,CACjD;EACF;EAGA,IAAI,SAAS;GACX,IAAI,QAAQ,cAAc,QAAQ,WAAW,SAAS,GACpD,WAAW,SAAS,QAAQ,MAC1B,QAAQ,YAAY,SAAS,EAAE,SAA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AO,KAAK,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;CAC1C;CAMA,MAAM,aAAiC;EACrC,OAAO,YAAqB,IAAI;CAClC;CAEA,MAAM,gBAAgB,UAAsC;EAC1D,OAAO,iBAA0B,MAAM,UAAU,yBAAyB;CAC5E;AACF"}
|
|
1
|
+
{"version":3,"file":"MessageCollection-iMnpnr3K.js","names":[],"sources":["../../src/collections/MessageCollection.ts"],"sourcesContent":["/**\n * MessageCollection - Unified collection for polymorphic message queries\n *\n * Queries the messages table with STI, returning correct subclass instances.\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { queryGlobal, queryWithGlobals } from '../host.js';\nimport { Message } from '../models/Message';\nimport type { MessageSearchFilters } from '../types';\n\nexport class MessageCollection extends SmrtCollection<Message> {\n static readonly _itemClass = Message;\n\n /**\n * Search messages with filters\n */\n async search(\n query: string,\n filters?: MessageSearchFilters,\n ): Promise<Message[]> {\n let messages = await this.list({});\n\n // Filter by query\n if (query) {\n const lowerQuery = query.toLowerCase();\n messages = messages.filter(\n (m) =>\n m.subject?.toLowerCase().includes(lowerQuery) ||\n m.body?.toLowerCase().includes(lowerQuery) ||\n m.fromAddress?.toLowerCase().includes(lowerQuery) ||\n m.fromName?.toLowerCase().includes(lowerQuery),\n );\n }\n\n // Apply filters\n if (filters) {\n if (filters.accountIds && filters.accountIds.length > 0) {\n messages = messages.filter((m) =>\n filters.accountIds?.includes(m.accountId),\n );\n }\n if (filters.messageType) {\n messages = messages.filter((m) => {\n const metaType = (m as { _meta_type?: string })._meta_type || '';\n return metaType.includes(filters.messageType as string);\n });\n }\n if (filters.from) {\n const fromLower = filters.from.toLowerCase();\n messages = messages.filter(\n (m) =>\n m.fromAddress?.toLowerCase().includes(fromLower) ||\n m.fromName?.toLowerCase().includes(fromLower),\n );\n }\n if (filters.to) {\n const toLower = filters.to.toLowerCase();\n messages = messages.filter((m) =>\n m.toAddresses?.toLowerCase().includes(toLower),\n );\n }\n if (filters.isRead !== undefined) {\n messages = messages.filter((m) => m.isRead === filters.isRead);\n }\n if (filters.isFlagged !== undefined) {\n messages = messages.filter((m) => m.isFlagged === filters.isFlagged);\n }\n if (filters.sinceDate) {\n messages = messages.filter(\n (m) => m.date && m.date >= (filters.sinceDate as Date),\n );\n }\n if (filters.beforeDate) {\n messages = messages.filter(\n (m) => m.date && m.date < (filters.beforeDate as Date),\n );\n }\n if (filters.query) {\n const q = filters.query.toLowerCase();\n messages = messages.filter(\n (m) =>\n m.subject?.toLowerCase().includes(q) ||\n m.body?.toLowerCase().includes(q),\n );\n }\n }\n\n return messages;\n }\n\n /**\n * Get messages by multiple accounts\n */\n async getByAccounts(accountIds: string[]): Promise<Message[]> {\n const allMessages = await this.list({});\n return allMessages.filter((m) => accountIds.includes(m.accountId));\n }\n\n /**\n * Get messages by STI type.\n *\n * Accepts either the full discriminator (e.g. \"@happyvertical/smrt-messages:Email\")\n * or the short type name (e.g. \"Email\").\n */\n async getByType(messageType: string): Promise<Message[]> {\n if (messageType.includes(':') || messageType.startsWith('@')) {\n return await this.list({ where: { _meta_type: messageType } });\n }\n const allMessages = await this.list({});\n return allMessages.filter((m) => {\n const metaType = (m as { _meta_type?: string })._meta_type || '';\n return metaType.endsWith(`:${messageType}`);\n });\n }\n\n /**\n * Get unread messages\n */\n async getUnread(accountId?: string): Promise<Message[]> {\n const where: Record<string, unknown> = { isRead: false };\n if (accountId) {\n where.accountId = accountId;\n }\n return await this.list({ where });\n }\n\n /**\n * Get flagged messages\n */\n async getFlagged(accountId?: string): Promise<Message[]> {\n const where: Record<string, unknown> = { isFlagged: true };\n if (accountId) {\n where.accountId = accountId;\n }\n return await this.list({ where });\n }\n\n /**\n * Get recent messages\n */\n async getRecent(limit = 20, accountId?: string): Promise<Message[]> {\n const allMessages = await this.list({\n where: accountId ? { accountId } : undefined,\n });\n\n return allMessages\n .sort((a, b) => {\n const dateA = a.date?.getTime() || 0;\n const dateB = b.date?.getTime() || 0;\n return dateB - dateA;\n })\n .slice(0, limit);\n }\n\n /**\n * Get messages by thread\n */\n async getByThread(threadId: string): Promise<Message[]> {\n return await this.list({ where: { threadId } });\n }\n\n /**\n * Mark multiple messages as read\n */\n async markAllRead(messageIds: string[]): Promise<void> {\n // One refused or failed row does not stop the rest; the first error is\n // raised once every row has been tried.\n let failure: unknown;\n for (const id of messageIds) {\n try {\n const message = await this.get({ id });\n if (message) {\n await message.markRead();\n }\n } catch (error) {\n failure ??= error;\n }\n }\n if (failure) throw failure;\n }\n\n /**\n * Get message statistics for an account\n */\n async getAccountStats(accountId: string): Promise<{\n total: number;\n unread: number;\n flagged: number;\n byType: Record<string, number>;\n }> {\n const messages = await this.list({ where: { accountId } });\n const byType: Record<string, number> = {};\n\n for (const msg of messages) {\n const metaType = (msg as { _meta_type?: string })._meta_type || 'Unknown';\n const shortType = metaType.split(':').pop() || metaType;\n byType[shortType] = (byType[shortType] || 0) + 1;\n }\n\n return {\n total: messages.length,\n unread: messages.filter((m) => !m.isRead).length,\n flagged: messages.filter((m) => m.isFlagged).length,\n byType,\n };\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Send / Draft Queries\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Get draft messages\n */\n async getDrafts(accountId?: string): Promise<Message[]> {\n const where: Record<string, unknown> = { sendStatus: 'draft' };\n if (accountId) where.accountId = accountId;\n return await this.list({ where });\n }\n\n /**\n * Get sent messages\n */\n async getSent(accountId?: string): Promise<Message[]> {\n const where: Record<string, unknown> = { sendStatus: 'sent' };\n if (accountId) where.accountId = accountId;\n return await this.list({ where });\n }\n\n /**\n * Get scheduled messages\n */\n async getScheduled(accountId?: string): Promise<Message[]> {\n const where: Record<string, unknown> = { sendStatus: 'scheduled' };\n if (accountId) where.accountId = accountId;\n return await this.list({ where });\n }\n\n /**\n * Get messages that failed to send\n */\n async getFailedSends(accountId?: string): Promise<Message[]> {\n const where: Record<string, unknown> = { sendStatus: 'failed' };\n if (accountId) where.accountId = accountId;\n return await this.list({ where });\n }\n\n /**\n * Get outbox (pending + sending + scheduled)\n */\n async getOutbox(accountId?: string): Promise<Message[]> {\n const allMessages = await this.list({\n where: accountId ? { accountId } : undefined,\n });\n return allMessages.filter(\n (m) =>\n m.sendStatus === 'pending' ||\n m.sendStatus === 'sending' ||\n m.sendStatus === 'scheduled',\n );\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n async findByTenant(tenantId: string): Promise<Message[]> {\n return this.list({ where: { tenantId } });\n }\n\n // Message is the @TenantScoped STI base, so an explicit `tenant_id IS NULL`\n // filter via list() throws and unflagged raw SQL is blocked under an active\n // tenant context (#1596). Route through the raw helpers — no `_meta_type`\n // scope so the base collection still returns ALL message subtypes.\n async findGlobal(): Promise<Message[]> {\n return queryGlobal<Message>(this);\n }\n\n async findWithGlobals(tenantId: string): Promise<Message[]> {\n return queryWithGlobals<Message>(this, tenantId, 'Message.findWithGlobals');\n }\n}\n"],"mappings":";;;;;;AAWO,IAAM,oBAAN,cAAgC,eAAwB;CAC7D,OAAgB,aAAa;;;;CAK7B,MAAM,OACJ,OACA,SACoB;EACpB,IAAI,WAAW,MAAM,KAAK,KAAK,CAAC,CAAC;EAGjC,IAAI,OAAO;GACT,MAAM,aAAa,MAAM,YAAY;GACrC,WAAW,SAAS,QACjB,MACC,EAAE,SAAS,YAAY,CAAA,CAAE,SAAS,UAAU,KAC5C,EAAE,MAAM,YAAY,CAAA,CAAE,SAAS,UAAU,KACzC,EAAE,aAAa,YAAY,CAAA,CAAE,SAAS,UAAU,KAChD,EAAE,UAAU,YAAY,CAAA,CAAE,SAAS,UAAU,CACjD;EACF;EAGA,IAAI,SAAS;GACX,IAAI,QAAQ,cAAc,QAAQ,WAAW,SAAS,GACpD,WAAW,SAAS,QAAQ,MAC1B,QAAQ,YAAY,SAAS,EAAE,SAAS,CAC1C;GAEF,IAAI,QAAQ,aACV,WAAW,SAAS,QAAQ,MAAM;IAEhC,QADkB,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AAiC;EACrC,OAAO,YAAqB,IAAI;CAClC;CAEA,MAAM,gBAAgB,UAAsC;EAC1D,OAAO,iBAA0B,MAAM,UAAU,yBAAyB;CAC5E;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
|
-
import "./EmailAccountCollection-
|
|
2
|
+
import "./EmailAccountCollection-kglDt9j9.js";
|
|
3
3
|
import { SmrtCollection, SmrtObject, crossPackageRef, field, smrt } from "@happyvertical/smrt-core";
|
|
4
4
|
import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy/decorators";
|
|
5
5
|
//#region src/models/MessagingEndpoint.ts
|
|
@@ -94,4 +94,4 @@ var MessagingEndpointCollection = class extends SmrtCollection {
|
|
|
94
94
|
//#endregion
|
|
95
95
|
export { MessagingEndpointCollection_exports as n, MessagingEndpoint as r, MessagingEndpointCollection as t };
|
|
96
96
|
|
|
97
|
-
//# sourceMappingURL=MessagingEndpointCollection-
|
|
97
|
+
//# sourceMappingURL=MessagingEndpointCollection-VUEtqpJ9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MessagingEndpointCollection-
|
|
1
|
+
{"version":3,"file":"MessagingEndpointCollection-VUEtqpJ9.js","names":[],"sources":["../../src/models/MessagingEndpoint.ts","../../src/collections/MessagingEndpointCollection.ts"],"sourcesContent":["import type { SmrtObjectOptions } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n crossPackageRef,\n field,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport type { MessagingChannel, MessagingEndpointOptions } from '../types.js';\n\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'messaging_endpoints',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n conflictColumns: ['tenant_id', 'channel', 'label'],\n})\nexport class MessagingEndpoint extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId()\n tenantId = '';\n\n @crossPackageRef('@happyvertical/smrt-profiles:Profile', { nullable: true })\n profileId: string | null = null;\n\n @field({ required: true, requiredFor: 'identity' })\n label = '';\n\n @field({ required: true })\n channel: MessagingChannel = 'email';\n\n /** Provider-specific destination JSON. Hidden from generated read surfaces. */\n @field({ required: true, sensitive: true })\n address = '{}';\n\n isActive = true;\n verifiedAt: Date | null = null;\n createdAt = new Date();\n updatedAt = new Date();\n\n constructor(options: MessagingEndpointOptions = {}) {\n super(options as SmrtObjectOptions);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.profileId !== undefined) this.profileId = options.profileId;\n if (options.label !== undefined) this.label = options.label;\n if (options.channel !== undefined) this.channel = options.channel;\n if (options.address !== undefined) this.address = options.address;\n if (options.isActive !== undefined) this.isActive = options.isActive;\n if (options.verifiedAt !== undefined) this.verifiedAt = options.verifiedAt;\n if (options.createdAt !== undefined) this.createdAt = options.createdAt;\n if (options.updatedAt !== undefined) this.updatedAt = options.updatedAt;\n }\n\n getAddress<T extends Record<string, unknown> = Record<string, unknown>>(): T {\n try {\n return JSON.parse(this.address) as T;\n } catch {\n return {} as T;\n }\n }\n\n setAddress(address: Record<string, unknown>): void {\n this.address = JSON.stringify(address);\n }\n\n getMaskedAddress(): string {\n const address = this.getAddress();\n const visible =\n address.email ??\n address.chatId ??\n address.to ??\n address.stream ??\n address.phoneNumber;\n if (typeof visible !== 'string' && typeof visible !== 'number')\n return '••••';\n const value = String(visible);\n if (value.includes('@')) {\n const [name, domain] = value.split('@');\n return `${name.slice(0, 2)}•••@${domain}`;\n }\n return value.length <= 4 ? '••••' : `••••${value.slice(-4)}`;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { MessagingEndpoint } from '../models/MessagingEndpoint.js';\n\nexport class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AAM,SAAS,GAAG,GAAG;GACvB,MAAM,CAAC,MAAM,UAAU,MAAM,MAAM,GAAG;GACtC,OAAO,GAAG,KAAK,MAAM,GAAG,CAAC,EAAC,qBAAO;EACnC;EACA,OAAO,MAAM,UAAU,IAAI,SAAS,2BAAO,MAAM,MAAM,EAAE;CAC3D;AACF;AAhEoD,cAAvC,mBAA8C,mBAAkB,8BAAA;AAE3E,gBAAA,CADC,SAAS,CAAA,GADC,kBAEX,WAAA,YAAA,CAAA;AAGA,gBAAA,CADC,gBAAgB,wCAAwC,EAAE,UAAU,KAAK,CAAC,CAAA,GAJhE,kBAKX,WAAA,aAAA,CAAA;AAGA,gBAAA,CADC,MAAM;CAAE,UAAU;CAAM,aAAa;AAAW,CAAC,CAAA,GAPvC,kBAQX,WAAA,SAAA,CAAA;AAGA,gBAAA,CADC,MAAM,EAAE,UAAU,KAAK,CAAC,CAAA,GAVd,kBAWX,WAAA,WAAA,CAAA;AAIA,gBAAA,CADC,MAAM;CAAE,UAAU;CAAM,WAAW;AAAK,CAAC,CAAA,GAd/B,kBAeX,WAAA,WAAA,CAAA;AAfW,oBAAN,gBAAA,CARN,aAAa,EAAE,MAAM,WAAW,CAAC,GACjC,KAAK;CACJ,WAAW;CACX,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,iBAAiB;EAAC;EAAa;EAAW;CAAO;AACnD,CAAC,CAAA,GACY,iBAAA;;;;AClBN,IAAM,8BAAN,cAA0C,eAAkC;CACjF,OAAgB,aAAa;AAC/B"}
|
package/dist/connect.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as EmailAccount, t as EmailAccountCollection } from "./chunks/EmailAccountCollection-
|
|
1
|
+
import { r as EmailAccount, t as EmailAccountCollection } from "./chunks/EmailAccountCollection-kglDt9j9.js";
|
|
2
2
|
import { withTenant } from "./host.js";
|
|
3
3
|
import { ObjectRegistry } from "@happyvertical/smrt-core";
|
|
4
4
|
import { ConnectError, ConnectStateCollection, beginConnect, buildOAuth2AuthorizeUrl, consumeConnect, discoverOidcEndpoints, exchangeOAuth2Code, fetchOidcUserInfo } from "@happyvertical/smrt-secrets/connect";
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import { $ as MANAGE_MESSAGE_CREDENTIALS_PERMISSION, A as MailAccessService, B as getMailAccessConfig, D as MAIL_ACCOUNT_RESOURCE_TYPE, E as Account, F as canAccessMailAccount, H as isMailScope, I as configureMailAccess, J as mailScopePermission, K as learnMailAccessOptions, L as decideMailAccess, M as assertMailAccess, O as MAIL_SCOPES, Q as withoutListBounds, R as deniedMailAccountIds, V as inMailSystemAccess, W as isPersonMailPrincipal, X as resolveMailPrincipal, Y as resetMailAccess, Z as runWithMailSystemAccess, _ as resetMailSendApprovals, at as ensureMessagingPermissionsRegistered, b as AttachmentStorageError, c as HeldSendError, et as MANAGE_MESSAGE_ROUTES_PERMISSION, f as auditMailAction, g as mailSendBindingHash, i as AccountCollection, it as assertMessagingPermission, j as assertHydratedMailAccess, k as MailAccessError, l as MailSendApprovalService, m as effectiveAgentSendPolicy, nt as MESSAGING_PERMISSION_DEFINITIONS, o as MailWriteBackUnsupportedError, ot as messagingPrincipalFromPermissions, p as configureMailSendApprovals, r as EmailAccount, rt as SEND_MESSAGES_PERMISSION, s as APPROVE_HELD_SEND_PERMISSION, st as seedMessagesRolePermissions, t as EmailAccountCollection, tt as MESSAGES_ROLE_PERMISSION_MATRIX, v as stampHandledBy, w as resetAttachmentStorage, x as configureAttachmentStorage, y as threadHandledBy, z as getEffectiveMailAccessConfigs } from "./chunks/EmailAccountCollection-
|
|
1
|
+
import { $ as MANAGE_MESSAGE_CREDENTIALS_PERMISSION, A as MailAccessService, B as getMailAccessConfig, D as MAIL_ACCOUNT_RESOURCE_TYPE, E as Account, F as canAccessMailAccount, H as isMailScope, I as configureMailAccess, J as mailScopePermission, K as learnMailAccessOptions, L as decideMailAccess, M as assertMailAccess, O as MAIL_SCOPES, Q as withoutListBounds, R as deniedMailAccountIds, V as inMailSystemAccess, W as isPersonMailPrincipal, X as resolveMailPrincipal, Y as resetMailAccess, Z as runWithMailSystemAccess, _ as resetMailSendApprovals, at as ensureMessagingPermissionsRegistered, b as AttachmentStorageError, c as HeldSendError, et as MANAGE_MESSAGE_ROUTES_PERMISSION, f as auditMailAction, g as mailSendBindingHash, i as AccountCollection, it as assertMessagingPermission, j as assertHydratedMailAccess, k as MailAccessError, l as MailSendApprovalService, m as effectiveAgentSendPolicy, nt as MESSAGING_PERMISSION_DEFINITIONS, o as MailWriteBackUnsupportedError, ot as messagingPrincipalFromPermissions, p as configureMailSendApprovals, r as EmailAccount, rt as SEND_MESSAGES_PERMISSION, s as APPROVE_HELD_SEND_PERMISSION, st as seedMessagesRolePermissions, t as EmailAccountCollection, tt as MESSAGES_ROLE_PERMISSION_MATRIX, v as stampHandledBy, w as resetAttachmentStorage, x as configureAttachmentStorage, y as threadHandledBy, z as getEffectiveMailAccessConfigs } from "./chunks/EmailAccountCollection-kglDt9j9.js";
|
|
2
2
|
import { buildSqliteRebuildStatements, isDeepStrictEqual, normalizeIdentityEmail, queryGlobal, queryWithGlobals, readNotificationProfile, withSystemContext, withTenant } from "./host.js";
|
|
3
|
-
import { r as Attachment, t as AttachmentCollection } from "./chunks/AttachmentCollection-
|
|
4
|
-
import { t as EmailFolder } from "./chunks/EmailFolder-
|
|
3
|
+
import { r as Attachment, t as AttachmentCollection } from "./chunks/AttachmentCollection-CyHqF9ON.js";
|
|
4
|
+
import { t as EmailFolder } from "./chunks/EmailFolder-C-f8YIE4.js";
|
|
5
5
|
import { d as withProtectedNotificationHandoff, f as PROFILE_NOTIFICATION_POLICY_PREFIX, l as protectedNotificationMetadata, m as profileNotificationPolicy, p as assertNotificationRecipientIdentity, t as ProtectedNotificationHandoffError } from "./chunks/protected-notification-handoff-mvaEZVp7.js";
|
|
6
|
-
import { n as saveQueuedForSend, t as Message } from "./chunks/Message-
|
|
6
|
+
import { n as saveQueuedForSend, t as Message } from "./chunks/Message-D-FgiSxn.js";
|
|
7
7
|
import { a as registerMessagingProvider, n as getMessagingProvider, o as ZulipSender, r as listMessagingProviders, s as TelegramSender, t as ensureBuiltinMessagingProvidersRegistered } from "./chunks/providers-Bz_F_ywF.js";
|
|
8
|
-
import { t as MessageCollection } from "./chunks/MessageCollection-
|
|
9
|
-
import { r as MessagingEndpoint, t as MessagingEndpointCollection } from "./chunks/MessagingEndpointCollection-
|
|
10
|
-
import { t as Email } from "./chunks/Email-
|
|
11
|
-
import { t as EmailCollection } from "./chunks/EmailCollection-
|
|
12
|
-
import { t as EmailFolderCollection } from "./chunks/EmailFolderCollection-
|
|
13
|
-
import { t as EmailSender } from "./chunks/EmailSender-
|
|
8
|
+
import { t as MessageCollection } from "./chunks/MessageCollection-iMnpnr3K.js";
|
|
9
|
+
import { r as MessagingEndpoint, t as MessagingEndpointCollection } from "./chunks/MessagingEndpointCollection-VUEtqpJ9.js";
|
|
10
|
+
import { t as Email } from "./chunks/Email-vipfIWe8.js";
|
|
11
|
+
import { t as EmailCollection } from "./chunks/EmailCollection-VqLlXxqw.js";
|
|
12
|
+
import { t as EmailFolderCollection } from "./chunks/EmailFolderCollection-L8kkOwq_.js";
|
|
13
|
+
import { t as EmailSender } from "./chunks/EmailSender-Dfrs3UoD.js";
|
|
14
14
|
import { t as SlackSender } from "./chunks/SlackSender-CetlSe6D.js";
|
|
15
15
|
import { t as TweetSender } from "./chunks/TweetSender-Dw-TDxIB.js";
|
|
16
16
|
import { GlobalInterceptors, ObjectRegistry, SmrtCollection, SmrtObject, SmrtRecipe, crossPackageRef, detectEngine, field, foreignKey, isUniqueViolationError, smrt, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue } from "@happyvertical/smrt-core";
|
|
@@ -98,7 +98,7 @@ function createMailAccessInterceptor() {
|
|
|
98
98
|
const row = instance;
|
|
99
99
|
row.accountId = null;
|
|
100
100
|
if (!row.messageId || !row.options) return;
|
|
101
|
-
const { MessageCollection } = await import("./chunks/MessageCollection-
|
|
101
|
+
const { MessageCollection } = await import("./chunks/MessageCollection-iMnpnr3K.js").then((n) => n.n);
|
|
102
102
|
row.accountId = (await runWithMailSystemAccess(async () => (await MessageCollection.create(row.options)).get({ id: row.messageId })))?.accountId || null;
|
|
103
103
|
},
|
|
104
104
|
async afterList(className, results, context) {
|
|
@@ -172,13 +172,13 @@ var MailDraftService = class {
|
|
|
172
172
|
}
|
|
173
173
|
options;
|
|
174
174
|
async account(accountId) {
|
|
175
|
-
const { EmailAccountCollection } = await import("./chunks/EmailAccountCollection-
|
|
175
|
+
const { EmailAccountCollection } = await import("./chunks/EmailAccountCollection-kglDt9j9.js").then((n) => n.n);
|
|
176
176
|
const account = await runWithMailSystemAccess(async () => (await EmailAccountCollection.create(withoutListBounds(this.options))).get({ id: accountId }));
|
|
177
177
|
if (!account?.id) throw new MailDraftError("Mail account not found.", 404);
|
|
178
178
|
return account;
|
|
179
179
|
}
|
|
180
180
|
async stored(id) {
|
|
181
|
-
const { EmailCollection } = await import("./chunks/EmailCollection-
|
|
181
|
+
const { EmailCollection } = await import("./chunks/EmailCollection-VqLlXxqw.js").then((n) => n.n);
|
|
182
182
|
return await runWithMailSystemAccess(async () => (await EmailCollection.create(this.options)).get({ id }));
|
|
183
183
|
}
|
|
184
184
|
/** Create or update a draft. Returns the saved draft. */
|
|
@@ -203,7 +203,7 @@ var MailDraftService = class {
|
|
|
203
203
|
draft = original.createReply({ replyAll: input.replyAll === true });
|
|
204
204
|
await draft.initialize();
|
|
205
205
|
} else {
|
|
206
|
-
const { Email: EmailClass } = await import("./chunks/Email-
|
|
206
|
+
const { Email: EmailClass } = await import("./chunks/Email-vipfIWe8.js").then((n) => n.n);
|
|
207
207
|
draft = new (ObjectRegistry.resolveEffectiveConstructor(EmailClass))({
|
|
208
208
|
...this.options,
|
|
209
209
|
tenantId: account.tenantId,
|
|
@@ -983,7 +983,7 @@ var EmailAttachment = class extends Attachment {
|
|
|
983
983
|
*/
|
|
984
984
|
async getEmail() {
|
|
985
985
|
if (!this.messageId) return null;
|
|
986
|
-
const { EmailCollection } = await import("./chunks/EmailCollection-
|
|
986
|
+
const { EmailCollection } = await import("./chunks/EmailCollection-VqLlXxqw.js").then((n) => n.n);
|
|
987
987
|
return await (await EmailCollection.create(this.options)).get({ id: this.messageId });
|
|
988
988
|
}
|
|
989
989
|
};
|
|
@@ -2689,7 +2689,7 @@ var CorrespondentService = class {
|
|
|
2689
2689
|
return result;
|
|
2690
2690
|
}
|
|
2691
2691
|
async ownAddresses(accountIds) {
|
|
2692
|
-
const { EmailAccountCollection } = await import("./chunks/EmailAccountCollection-
|
|
2692
|
+
const { EmailAccountCollection } = await import("./chunks/EmailAccountCollection-kglDt9j9.js").then((n) => n.n);
|
|
2693
2693
|
const accounts = await EmailAccountCollection.create({ db: this.options.db });
|
|
2694
2694
|
const out = [];
|
|
2695
2695
|
for (const id of accountIds) {
|
package/dist/manifest.json
CHANGED