@happyvertical/smrt-messages 0.60.14 → 0.60.15

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.
Files changed (57) hide show
  1. package/AGENTS.md +13 -0
  2. package/agents/notification-outbox.md +125 -2
  3. package/agents/profile-recipients.md +32 -0
  4. package/agents/scoped-attachment-test-matrix.md +46 -0
  5. package/dist/chunks/{AccountCollection-CI7U6MBl.js → AccountCollection-DBEG6nR7.js} +6 -7
  6. package/dist/chunks/AccountCollection-DBEG6nR7.js.map +1 -0
  7. package/dist/chunks/{Email-Bbuefk_z.js → Email-p5qIyMC5.js} +3 -3
  8. package/dist/chunks/{Email-Bbuefk_z.js.map → Email-p5qIyMC5.js.map} +1 -1
  9. package/dist/chunks/{EmailFolder-CzElqWJv.js → EmailFolder-Dk4hxikK.js} +3 -3
  10. package/dist/chunks/EmailFolder-Dk4hxikK.js.map +1 -0
  11. package/dist/chunks/{Message-BlnWWzXY.js → Message-hIwx07Kt.js} +72 -11
  12. package/dist/chunks/Message-hIwx07Kt.js.map +1 -0
  13. package/dist/chunks/{MessageCollection-C_AHAuZR.js → MessageCollection-BwnE4a_L.js} +3 -3
  14. package/dist/chunks/MessageCollection-BwnE4a_L.js.map +1 -0
  15. package/dist/chunks/__smrt-register__-D3kBjvML.js +6 -0
  16. package/dist/chunks/__smrt-register__-D3kBjvML.js.map +1 -0
  17. package/dist/chunks/protected-notification-handoff-mvaEZVp7.js +358 -0
  18. package/dist/chunks/protected-notification-handoff-mvaEZVp7.js.map +1 -0
  19. package/dist/host.browser.d.ts +18 -0
  20. package/dist/host.browser.d.ts.map +1 -0
  21. package/dist/host.browser.js +27 -0
  22. package/dist/host.browser.js.map +1 -0
  23. package/dist/host.d.ts +19 -0
  24. package/dist/host.d.ts.map +1 -0
  25. package/dist/host.js +35 -0
  26. package/dist/host.js.map +1 -0
  27. package/dist/index.d.ts +3 -1
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +589 -67
  30. package/dist/index.js.map +1 -1
  31. package/dist/manifest.json +317 -14
  32. package/dist/migrations/profileRecipients.d.ts +17 -0
  33. package/dist/migrations/profileRecipients.d.ts.map +1 -0
  34. package/dist/models/Account.d.ts.map +1 -1
  35. package/dist/models/Message.d.ts +7 -0
  36. package/dist/models/Message.d.ts.map +1 -1
  37. package/dist/models/NotificationDelivery.d.ts +20 -3
  38. package/dist/models/NotificationDelivery.d.ts.map +1 -1
  39. package/dist/notification-recipient-identity.d.ts +17 -0
  40. package/dist/notification-recipient-identity.d.ts.map +1 -0
  41. package/dist/permissions.d.ts +1 -1
  42. package/dist/permissions.d.ts.map +1 -1
  43. package/dist/protected-notification-handoff.d.ts +31 -0
  44. package/dist/protected-notification-handoff.d.ts.map +1 -0
  45. package/dist/recipes.d.ts +1 -1
  46. package/dist/senders/EmailSender.d.ts.map +1 -1
  47. package/dist/services/NotificationOutboxService.d.ts +51 -3
  48. package/dist/services/NotificationOutboxService.d.ts.map +1 -1
  49. package/dist/smrt-knowledge.json +184 -12
  50. package/dist/smrt-knowledge.okf.md +7 -2
  51. package/package.json +13 -9
  52. package/dist/chunks/AccountCollection-CI7U6MBl.js.map +0 -1
  53. package/dist/chunks/EmailFolder-CzElqWJv.js.map +0 -1
  54. package/dist/chunks/Message-BlnWWzXY.js.map +0 -1
  55. package/dist/chunks/MessageCollection-C_AHAuZR.js.map +0 -1
  56. package/dist/chunks/__smrt-register__-DFDdoQdB.js +0 -6
  57. package/dist/chunks/__smrt-register__-DFDdoQdB.js.map +0 -1
package/AGENTS.md CHANGED
@@ -151,3 +151,16 @@ reads provider-supplied paths or advances sync checkpoints. Keep this path
151
151
  provider-neutral and exclude arbitrary headers/credentials from its snapshot.
152
152
  IMAP lookup must include folder/UIDVALIDITY/UID verification; sender Message-ID
153
153
  is a lookup hint, never the durable delivery identity.
154
+
155
+ Protected notification Emails carry durable delivery provenance. Their canonical
156
+ `send`/`retrySend`, ordinary save/delete, and default EmailSender handoff are
157
+ constrained by `protected-notification-handoff.ts` (package-private, never a root
158
+ export). Only the outbox enters its exact one-use scope after current trusted
159
+ policy/byte validation. Preserve old-row/constructor identity checks, current
160
+ persisted lease checks at the actual provider boundary, copied byte buffers and
161
+ unknown-outcome marker protection. See the outbox contract and shared protected
162
+ handoff suite (SQLite and migrated PostgreSQL).
163
+
164
+ ## Protected external contacts
165
+
166
+ Profile email uses exclusive `recipientProfileId` plus `resolveProfileRecipient`, a reserved `profileNotificationPolicy` and exact current tenant-owned public Profile email. No User account is required. Before activating profiles, run normal framework schema migration and public `planNotificationProfileRecipients` / `migrateNotificationProfileRecipients`; runtime verifies physical constraints and never applies DDL. Legacy User notification and opt-out paths remain User-only. See [profile recipient contract and matrix](agents/profile-recipients.md).
@@ -27,7 +27,7 @@ Host authorization, all checked before anything is stored:
27
27
  - `resolveSenderAccountId({ tenantId })` names an active `EmailAccount` owned by
28
28
  the same tenant (reason `sender` otherwise). Configuring that account is
29
29
  deployment setup; the outbox has no mail transport of its own.
30
- - With `principal`, enqueue, `listUncertain`, and `reconcile` require
30
+ - With `principal`, enqueue, dispatch, `listUncertain`, and `reconcile` require
31
31
  `messages.send` in the tenant (reason `permission`). Omit it only for trusted
32
32
  system code that authorizes itself.
33
33
  - `isSuppressed(...)` (optional) is the opt-out hook. A suppressed enqueue stores
@@ -44,12 +44,55 @@ lead to the host's normal authenticated route. Subjects must be one line.
44
44
 
45
45
  ## Dispatch
46
46
 
47
- `dispatchDue({ tenantIds?, limit? })` (default 25, max 200) leases due rows —
47
+ `dispatchDue({ tenantIds?, deliveryIds?, limit? })` (default 25, max 200) leases due rows —
48
48
  `pending` with `nextAttemptAt <= now`, and `sending` rows whose lease lapsed —
49
49
  for the given tenants, or every tenant (discovered under `withSystemContext`)
50
50
  when `tenantIds` is omitted. Each row is processed under `withTenant(row.tenantId)`.
51
51
  Run it from a scheduled job; several workers may run it concurrently.
52
52
 
53
+ `deliveryIds` restricts both pending and expired-lease queries before their limits
54
+ and before leases; an empty array selects nothing and malformed UUIDs are
55
+ rejected. A principal defaults to its own tenant when `tenantIds` is omitted;
56
+ a principal without a tenant must select explicit tenants. Every explicit scope
57
+ is authorized before discovery, and selected rows are authorized again before
58
+ dispatch. Trusted system code without a principal retains cross-tenant discovery.
59
+
60
+ `NotificationOutboxService.capabilities` exposes `deliverySelection: true` and
61
+ `attachments: true` so hosts requiring these contracts can refuse an older
62
+ library before leasing any row. This marker does not authorize any sender.
63
+
64
+ `resolveAttachments({delivery,message,idempotencyKey})` is an optional trusted-host
65
+ hook, called before each fresh provider handoff. It must reauthorize the approved
66
+ resource, immutable version/digest and recipient and return `SendEmailAttachment[]`
67
+ using actual bytes, never untrusted file paths or URLs. Malformed results or
68
+ resolver failures reject before handoff; attachments are copied into the transport
69
+ request and the default transport forwards them to existing `Email.send()`. The
70
+ outbox does not persist bytes or invent document/recipient authority. Omission
71
+ preserves ordinary no-attachment notifications; an explicit resolver returning
72
+ `undefined` fails instead of silently dropping an expected document. Prior-handoff
73
+ reconciliation runs without requiring document bytes; an accepted or uncertain
74
+ outcome does not cause another attachment resolution/send.
75
+
76
+ Protected documents enqueue with `kind: 'protected:<policyId>'`,
77
+ `requiredDispatchPolicy: '<policyId>'` and an approved `dispatchPolicyBinding`
78
+ object (resource/version/digest/recipient identities). The trusted constructor
79
+ map `dispatchPolicies[policyId].resolveAttachments` owns current authorization
80
+ and actual-byte verification. Protected kinds require their exact policy;
81
+ enqueue rejects unknown handlers or missing bindings. A broad dispatcher without
82
+ the matching policy reports `blocked`, persists a detectable `lastError`, and
83
+ leaves provider calls and lease attempts at zero. A protected policy must return
84
+ at least one valid attachment. Existing source, policy/binding, destination,
85
+ sender and message content cannot change through an ordinary model save;
86
+ protected clones retaining their kind cannot remove the policy. Missing policy
87
+ does not authorize a resend of an uncertain prior attempt. The capability marker
88
+ includes `requiredPolicy: true`.
89
+
90
+ The two additive columns require normal consumer migration. Old rows default to
91
+ an empty policy and retain legacy ordinary-mail behavior; no historical document
92
+ consent is invented. Never run old dispatcher binaries alongside newly protected
93
+ intents: old versions cannot enforce a contract they do not implement. Rollout
94
+ and real sends require separate authorization.
95
+
53
96
  Every state change is `NotificationDelivery.transition()`: a compare-and-set on
54
97
  `stateVersion` (and the lease token for a lease holder) that writes a unique
55
98
  `transitionId` and re-reads the row to prove the write won. PostgreSQL and
@@ -160,3 +203,83 @@ New tables `notification_opt_outs` (same rules) and `notification_deliveries` (t
160
203
  off): consumers run `db:migrate`. `recipient_user_id` is a cross-package uuid
161
204
  ref to `smrt-users:User`; `account_id`/`message_id` are FKs to `accounts` and
162
205
  `messages`.
206
+
207
+ ## Protected canonical Message handoff
208
+
209
+ `capabilities.protectedCanonicalSend` advertises the canonical-send guard in
210
+ addition to `requiredPolicy`. A protected delivery's single canonical Email has
211
+ a durable `metadata.__smrtProtectedOutbox` marker, backed by the delivery's
212
+ `messageId`. The marker is not authorization. Protected rows cannot clear or
213
+ change their marker, correlation, original identity, body, sender/recipients,
214
+ cc/bcc, HTML, raw content or headers through ordinary saves. Constructor-captured
215
+ original identity plus persisted old-row inspection also protect a loaded object
216
+ whose public id/correlation/metadata fields were changed and clones retaining
217
+ protected provenance. Ordinary model/collection deletion retains that evidence.
218
+ An existing protected canonical row receives the marker before dispatch; this is
219
+ non-authorizing migration of metadata, not permission to send.
220
+
221
+ Direct `Message.send`, `retrySend`, and default `EmailSender.send` refuse protected
222
+ mail without the outbox's private, exact, one-use handoff scope. The scope is
223
+ created only after the trusted named policy resolves/authorizes actual bytes.
224
+ It binds tenant, delivery, canonical message, lease, attempt/state version,
225
+ approved content/destinations and attachment names/types/IDs/dispositions/digests.
226
+ No capability mint is exported from the package root. Custom trusted transports
227
+ receive bytes only after a fresh durable lease check. The canonical sender and
228
+ actual default EmailClient boundary repeat that check after attachment I/O;
229
+ effective account-default sender and all destinations/body parts must match.
230
+ Send-time attachment buffers are privately copied before the SDK receives them.
231
+
232
+ Concurrent/reentrant second calls and detached tasks using an inherited async
233
+ context fail closed: scope state is deactivated when its transport callback
234
+ returns. A local guard denial is a definite pre-provider refusal, not an unknown
235
+ acceptance. Protected lifecycle/unknown-outcome metadata cannot be rewritten by
236
+ ordinary saves to make reconciliation mistake a prior uncertain handoff for a
237
+ safe retry. Existing unknown outcomes retain the normal reconciliation barrier.
238
+ Ordinary unprotected messages, including unsaved direct-sender drafts, retain
239
+ their existing contract.
240
+
241
+ The trusted-provider boundary is explicit: these guards constrain public package
242
+ Message/EmailSender and outbox paths. Arbitrary trusted server code calling a
243
+ provider SDK outside this package, or a custom transport deliberately sending
244
+ through its own SDK, remains responsible for that code's authority and behavior.
245
+
246
+ ## Typed external contacts
247
+
248
+ Protected email also accepts exactly one `recipientProfileId` instead of a User. See [profile recipients](profile-recipients.md) for reserved profile policy identity, current Profile/host relationship checks, explicit schema plan/apply prerequisites and compatibility evidence. No auth account is fabricated.
249
+
250
+ ## Browser/server boundary (#4747)
251
+
252
+ Protected notifications add no Node-only imports to the browser graph. Existing
253
+ package/dependency browser-capability declarations still apply. Protected canonical
254
+ handoff and schema maintenance require the server host: private SHA-256, strict
255
+ binding comparison, async-local scope, Core migration rebuild operations and
256
+ public Profile lookup/normalization live behind stable package
257
+ `host.js` / `host.browser.js` entries, following Core's
258
+ existing browser-map pattern. The browser counterpart never mints or inherits
259
+ handoff authority and throws before protected operations or maintenance; it does
260
+ not install a global context, skip durable guards or approximate hashing. Public
261
+ server APIs and canonical persisted association/lease/one-use checks are unchanged.
262
+ The owning dist browser bundle gate must remain green without a ratchet waiver.
263
+
264
+ ## Blocked-prefix liveness and final-write protection
265
+
266
+ The dispatch limit bounds acquired leases, rather than blocked diagnostics.
267
+ Discovery walks bounded pages ordered by physical due/lease timestamp and UUID,
268
+ recovering expired leases before pending rows. Its cursor captures timestamp text
269
+ in the database before hydration, preserving PostgreSQL microseconds. A blocked
270
+ policy or Profile cannot repeatedly fill the first page and starve eligible mail
271
+ in its own tenant or another authorized scope. Explicit delivery selectors and
272
+ pre-discovery tenant authorization apply to every page. Repeated identical
273
+ blocked errors do not rewrite the row; no backoff, cancellation or lease is added,
274
+ so a currently authorized configured host can deliver immediately.
275
+
276
+ Public delivery saves bind their checked snapshot through Core's mandatory
277
+ `CollectionInterceptor.writeGuard` at the final persistence operation. An ordinary
278
+ save cannot adopt a protected natural identity inserted after its initial lookup.
279
+ Protected saves bind tenant, typed recipient, source, policy/binding, content and
280
+ lifecycle version/transition; a concurrent transition wins without being undone.
281
+ The private per-instance snapshot exists only during the save, and concurrent
282
+ saves of one instance are refused. Existing revision/sync options, ordinary
283
+ natural-key upsert and identical protected clones keep their normal contracts.
284
+ SQLite uses Core's existing serialized compare/write; PostgreSQL places the
285
+ mandatory predicate on its final UPDATE. No runtime schema or provider changes.
@@ -0,0 +1,32 @@
1
+ # Protected external-contact email recipients
2
+
3
+ `enqueueEmail` accepts exactly one of the existing `recipientUserId` or new `recipientProfileId`. Profile recipients are **email only** and reference a real tenant-owned public `smrt-profiles:Profile`; they do not need an auth User. No address, sentinel User, inferred tenant membership or recipient array is accepted. The one public `Profile.email` scalar is normalized by public `normalizeIdentityEmail`; the host's `resolveProfileRecipient` must authorize and return exactly that same current address. Multiple alternative emails are never selected implicitly.
4
+
5
+ Use `profileNotificationPolicy('your.host-policy.v1')` as `requiredDispatchPolicy` and `kind = 'protected:' + policyId`. Register that exact trusted handler in `dispatchPolicies`, with immutable document/recipient binding. The reserved `profile:` policy namespace and `protected:profile:` kind force profile identity in saves, enqueue, leasing and canonical send. Changing/clearing kind, either identity, address or policy on an existing protected row or natural-key clone is denied. A trusted application inventing a completely separate ordinary event has a distinct identity and is outside the clone threat model.
6
+
7
+ The host must check the real resource relationship (for example issued Invoice → Customer.profileId and current Project → Client.contactProfileId), current actor/privacy/field grants and contact authority at preview, approval and every policy handoff. Generic tenancy alone cannot grant that relationship. The service also re-resolves the tenant-owned profile and host callback before leasing and immediately before provider transport, denying changed/deleted/foreign/unrelated contacts. Broad dispatch without the matching protected handler stays blocked with no attempt or provider call. Existing Message/EmailSender protected canonical checks cover profile sends too. Unknown outcomes remain uncertain until reconciliation; this API adds no resend shortcut.
8
+
9
+ Legacy User inputs and `resolveRecipient` are unchanged. `NotificationSuppressionRequest` and existing `optOutSuppression` retain their required User ID and exact legacy TypeScript contract. Profiles use the separate optional `isProfileSuppressed(NotificationProfileSuppressionRequest)` hook, checked at enqueue and dispatch. It receives a real Profile ID and no User ID; a host supplies its current contact opt-out/resource policy. User opt-out preferences are never inferred onto unrelated external contacts. No global User opt-out row is fabricated.
10
+
11
+ ## Explicit schema maintenance
12
+
13
+ Inspect `planNotificationProfileRecipients(db, 'postgres' | 'sqlite')` first. It is read-only, returning SQL, unexpected invalid/duplicate row IDs and obsolete index inventory. On an existing PostgreSQL database, apply this explicit maintenance **before** the normal PostgreSQL-safe manifest migration: the expanded NULL-equal conflict key requires an atomic writer window and cannot be created by concurrent-index DDL. Then run normal manifest migration and verify the helper's empty replay. On a fresh database, create the normal manifest schema first, then apply this helper to install the physical typed CHECK.
14
+
15
+ `migrateNotificationProfileRecipients` runs a fresh plan inside one transaction; PostgreSQL takes an exclusive table lock. It never performs runtime auto-DDL. The caller must use a root migration handle in an authorized writer maintenance window. The same public helper supports the legacy-table-first path; do not disable PostgreSQL-safe mode globally to get past its maintenance refusal.
16
+
17
+ The migration preserves all legacy row IDs, User references, message/provider IDs, outcome/history and existing data. Legacy rows become `recipientKind='user'` with actual NULL profile reference; profile rows require actual NULL User reference. User/profile unique indexes preserve logical idempotency independently. The expanded natural key `(tenant, kind, User, Profile, channel, sourceRef)` retains public raw-save/upsert semantics. PostgreSQL's obsolete four-column User-only `NULLS NOT DISTINCT` index is the **only** old index removed; otherwise it would collapse distinct profiles with the same source. Unexpected named index or CHECK drift and invalid/duplicate old identities require explicit reconciliation, never guessed repair.
18
+
19
+ SQLite uses public core `buildSqliteRebuildStatements` to preserve the live DDL, indexes, triggers, rowids and data while relaxing the unused User column, adding profile fields and a real table CHECK. It refuses incoming-FK rebuild shapes and never disables foreign keys. Unsupported/ambiguous schema shapes fail closed for an explicit maintenance path. A failed DDL step rolls back old schema/indexes/history; replay after success is empty.
20
+
21
+ Profile enqueue/dispatch verifies actual physical nullability, the complete CHECK predicate, required unique indexes and absence of the old four-column NND index. A migration ledger/version flag alone never opens this gate. Ordinary User use is not gated on the extra profile CHECK/index maintenance **after normal framework additive schema migration** has supplied the typed columns/defaults. A zero-new-column old database still needs that normal schema phase; this is not a claim that new ORM code writes old physical columns unchanged. The explicit helper also plans/applies from a legacy table directly during maintenance, preserving old rows. Mixed old binaries must be drained before migration/activation; old binaries cannot honor typed protected contracts. Follow released-package/schema adoption before enabling any real host.
22
+
23
+ ## Risk-based evidence matrix
24
+
25
+ | Invariant | Reachable positive | Negative/failure | Actor/context | Executor/transaction | Runtime/dialect | External edge | Level |
26
+ | --- | --- | --- | --- | --- | --- | --- | --- |
27
+ | Typed contact identity | real Profile/no User, exact normalized email, actual attachment capture | both/neither/empty/wrong kind/channel/namespace, foreign/deleted/unrelated/revoked/changed contact | current explicit tenant/principal plus host resource policy | all source reads current; no caller address | Node26 SQLite worker, PG18 coordinator | public Profile + host callbacks | shared service suite |
28
+ | Legacy logical identity | repeated/concurrent User enqueue and raw saves; profile same-key replay | profile/user collision, different profiles collapsing, wrong-tenant dispatch | explicit tenant dispatch/permission | DB unique indexes/null-aware upsert | SQLite/PG | no provider writes | source suites |
29
+ | Protected lifecycle | approved bytes through registered handler only | new-ID natural-key clone changes binding/address/lifecycle; namespace downgrade; generic/direct send | trusted resource-aware policy, current actor | lease CAS + canonical one-use handoff | SQLite/PG | capture transport only | existing guard + profile suite |
30
+ | Schema evolution | read-only plan, legacy data/FK/history preservation, atomic apply/replay | obsolete NND collapse, named index/CHECK drift, invalid duplicate old rows, partial DDL failure | maintenance owner only | exclusive PG lock or safe SQLite live-DDL rebuild, rollback | SQLite worker/PG18 coordinator | N/A: database-only maintenance | migration suites |
31
+
32
+ Worker evidence is narrow in-process only. PostgreSQL migration/rollback, native app no-User PDF browser proof, full validation, canonical knowledge build and release adoption belong to integration. No customer/provider sends are authorized by this documentation.
@@ -0,0 +1,46 @@
1
+ # Scoped outbox and attachment evidence (#4747)
2
+
3
+ High risk: tenant authority and confidential attachment disclosure. Host code
4
+ owns immutable document/recipient consent; this service accepts trusted byte
5
+ resolvers, never arbitrary URLs or file paths. All other outbox behavior stays
6
+ on the existing public lease/transition/provider contract.
7
+
8
+ | Invariant | Trigger | Positive | Negative/failure | Actor/context | Executor/transaction | Runtime/dialect | External edge | Level/command |
9
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- |
10
+ | Selection precedes loading/limit/claim | dispatchDue(deliveryIds) | exact requested pending/expired row found despite older unrelated rows | empty/malformed IDs never widen; foreign ID cannot cross tenant; unrelated rows untouched | principal exact tenant, or explicitly trusted system | same supplied db and existing CAS lease | Node26, SQLite and PostgreSQL; DuckDB where package supports | optional additive selector; legacy omission preserved | notification-outbox.test.ts plus PostgreSQL lane |
11
+ | Dispatch authorization | explicit or omitted tenantIds | permitted principal dispatches own tenant | foreign scope or absent messages.send denied before query/lease; unscoped principal must choose tenants | validated MessagingPrincipal; per-row check before dispatch | existing public collection; no new schema | Node26/SQLite + PG | no-principal legacy trusted system preserved | regression base failure/head pass |
12
+ | Real attachment bytes | pre-handoff resolver | bytes reach capture and existing Email.send options | malformed/missing return or resolver failure reaches no provider | host resolver reauthorizes current approved artifact; tenant context | existing delivery/message, resolver before handedOffAt | Node26/SQLite + PG | SendEmailAttachment, no provider import | narrow byte/resolver/default-transport tests |
13
+ | Retry safety | rejected send/recovery | resolver reruns before each fresh handoff | unknown outcome uncertain; no byte resolver/send on accepted reconciliation | current dispatch principal and host policy per attempt | existing durable state machine and lease | Node26/SQLite + PG | provider rejection/lost response | focused retry/recovery tests plus existing suite |
14
+
15
+ | Required policy admission | protected enqueue/batch/default dispatch | recognized policy + immutable artifact/destination binding yields bytes | unknown/missing policy blocks before lease, zero provider calls; new protected clone cannot clear policy | trusted server policy map, live host resource authority | public delivery save + CAS transitions | Node26/SQLite + PostgreSQL | old dispatcher binaries excluded from protected rollout | three baseline failures; current tests plus migrated PG proof |
16
+
17
+ Full touched-package tests/type checks/root documented validation remain release
18
+ gates. No UI change: browser N/A (package has no maintained browser harness).
19
+ Two additive policy columns require normal migration; legacy rows retain empty
20
+ policy defaults. PostgreSQL proof exercises native UUID/JSONB protection and
21
+ blocked default dispatch. Current-head evidence receipts
22
+ are recorded outside the worktree by the coordinator.
23
+
24
+ ## Canonical Message handoff guard (#4747)
25
+
26
+ Named high-risk trigger: confidential attachment disclosure through an alternate
27
+ public send/retry/provider path. Source baseline regressions run before edits.
28
+
29
+ | Invariant / trigger | Positive | Negative/failure | Actor/context | Executor / durable state | Runtime/dialect | Contract edge / command |
30
+ | --- | --- | --- | --- | --- | --- | --- |
31
+ | Durable association | protected canonical message reload/save retains delivery | direct send/retry, cleared correlation/metadata, spoofed id, clone retaining protection cannot escape | trusted outbox policy vs arbitrary public caller | persisted delivery.messageId + protected message marker + original loaded identity; same supplied db | Node26 SQLite; PG integration | public Message/Email APIs; notification-outbox guard suite |
32
+ | Exact capability | approved bytes reach default EmailSender once | omitted/changed bytes, recipient/body/cc/bcc/from/headers changes deny | private one-use scope only after trusted current policy | exact tenant/delivery/message/lease/attempt/body/destination/byte digests | Node26 SQLite + PG | no public mint or arbitrary method dispatch |
33
+ | Actual provider boundary | current sending lease/attempt permits one handoff | lease loss/expiry after validation, reentrant/concurrent second call, detached async context expiry deny | same exact instance/canonical identity | re-read current persisted delivery immediately at handoff; one-use flags | Node26 SQLite + PG | default sender + capture provider |
34
+ | Retry and uncertainty | definite rejection permits new policy validation on fresh attempt | unknown remains uncertain; direct retry cannot resend | current authority per outbox attempt | existing outbox reconciliation/state machine | Node26 SQLite + PG | existing protected/default transport suite |
35
+ | Compatibility | ordinary unprotected messages still send/retry | forged protected marker never grants authority | current ordinary account semantics | existing Message CAS | Node26 SQLite + PG | provider-neutral root, no SDK import |
36
+
37
+ Trust boundary: package guards cannot prevent arbitrary trusted server code from
38
+ calling a provider SDK outside the messaging package. The private helper is not a
39
+ package-root export and never accepts a client-selected authorization callback.
40
+
41
+ Natural-key protection checks both stored old identity and the resulting adopted
42
+ identity inside a caller-affine transaction; a row appearing during a save cannot
43
+ be adopted to erase protection. Public saves inside an active provider scope gain
44
+ no lifecycle authority: only private canonical send/retry code can authorize its
45
+ exact one-use lifecycle save. Unknown-outcome marker rewrites fail. The shared
46
+ suite exercises these paths under SQLite and is wired into the migrated PG lane.
@@ -1,7 +1,8 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import "./__smrt-register__-DFDdoQdB.js";
2
+ import "./__smrt-register__-D3kBjvML.js";
3
+ import { createAccountSecretService, getCurrentTenant, queryGlobal, queryWithGlobals, withTenant } from "../host.js";
3
4
  import { SmrtCollection, SmrtObject, field, smrt } from "@happyvertical/smrt-core";
4
- import { TenantScoped, getCurrentTenant, queryGlobal, queryWithGlobals, tenantId, withTenant } from "@happyvertical/smrt-tenancy";
5
+ import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy/decorators";
5
6
  //#region src/models/Account.ts
6
7
  var __defProp = Object.defineProperty;
7
8
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -95,8 +96,7 @@ var Account = class extends SmrtObject {
95
96
  */
96
97
  async setCredentials(credentials, options = {}) {
97
98
  if (!this.id) throw new Error("Account must be persisted before storing credentials.");
98
- const { SecretService } = await import("@happyvertical/smrt-secrets");
99
- const secretService = await SecretService.create({ db: this.db });
99
+ const secretService = await createAccountSecretService(this.db);
100
100
  const secretName = `${this.channelType || "messaging"}-account-${this.id}`;
101
101
  const secretValue = JSON.stringify(credentials);
102
102
  const tenantId2 = this.requireCredentialTenantId("store credentials");
@@ -124,8 +124,7 @@ var Account = class extends SmrtObject {
124
124
  async getCredentials() {
125
125
  if (!this.credentialSecretId) return this.getSettings();
126
126
  const tenantId2 = this.requireCredentialTenantId("retrieve credentials");
127
- const { SecretService } = await import("@happyvertical/smrt-secrets");
128
- const secretService = await SecretService.create({ db: this.db });
127
+ const secretService = await createAccountSecretService(this.db);
129
128
  try {
130
129
  const secret = await secretService.retrieveForTenant(tenantId2, this.credentialSecretId);
131
130
  return JSON.parse(secret.value);
@@ -255,4 +254,4 @@ var AccountCollection = class extends SmrtCollection {
255
254
  //#endregion
256
255
  export { AccountCollection_exports as n, Account as r, AccountCollection as t };
257
256
 
258
- //# sourceMappingURL=AccountCollection-CI7U6MBl.js.map
257
+ //# sourceMappingURL=AccountCollection-DBEG6nR7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AccountCollection-DBEG6nR7.js","names":["tenantId"],"sources":["../../src/models/Account.ts","../../src/collections/AccountCollection.ts"],"sourcesContent":["/**\n * Account model - Base class for all messaging account types (STI)\n *\n * Common fields shared across email, Slack, Twitter accounts, 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 { field, SmrtObject, smrt } from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport {\n createAccountSecretService,\n getCurrentTenant,\n withTenant,\n} from '../host.js';\nimport type { AccountOptions, MessageSenderInterface } from '../types';\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n})\nexport class Account extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n @field({\n description: 'The display name for this connected messaging account.',\n })\n name = '';\n @field({\n description: 'The service that connects this account to your application.',\n })\n providerType = '';\n @field({\n description:\n 'The kind of messaging this account supports, such as email or chat.',\n })\n channelType = '';\n // credentialSecretId stores the Secret's NAME (keyed by name + tenant\n // context in smrt-secrets), NOT its primary-key id — see setCredentials()/\n // getCredentials() which call tenant-bound SecretService operations by name.\n // So it is deliberately NOT a @crossPackageRef id FK.\n @field({ sensitive: true, readonly: true })\n credentialSecretId: string | null = null;\n @field({ description: 'Whether this account is enabled for messaging.' })\n isActive = true;\n @field({ description: 'When this account last checked for new messages.' })\n lastSyncAt: Date | null = null;\n // JSON. Sensitive (#1540): may hold a plaintext credential fallback, so it is\n // excluded from generated API/MCP responses and rejected as a `where` filter\n // key.\n @field({ sensitive: true, readonly: true })\n settings = ''; // JSON\n /** Non-secret provider configuration such as a Zulip site URL. */\n @field({\n description:\n 'The public connection settings for this account; credentials are stored separately.',\n })\n configuration = '{}';\n\n // Timestamps\n @field({ description: 'When this account was added.' })\n createdAt = new Date();\n @field({ description: 'When this account was last changed.' })\n updatedAt = new Date();\n\n constructor(options: AccountOptions = {}) {\n super(options);\n\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.name !== undefined) this.name = options.name;\n if (options.providerType !== undefined)\n this.providerType = options.providerType;\n if (options.channelType !== undefined)\n this.channelType = options.channelType;\n if (options.credentialSecretId !== undefined)\n this.credentialSecretId = options.credentialSecretId || null;\n if (options.isActive !== undefined) this.isActive = options.isActive;\n if (options.lastSyncAt !== undefined)\n this.lastSyncAt = options.lastSyncAt || null;\n if (options.settings !== undefined) this.settings = options.settings;\n if (options.configuration !== undefined)\n this.configuration = options.configuration;\n if (options.createdAt) this.createdAt = options.createdAt;\n if (options.updatedAt) this.updatedAt = options.updatedAt;\n }\n\n /**\n * Get settings as parsed object\n */\n getSettings(): Record<string, unknown> {\n if (!this.settings) return {};\n try {\n return JSON.parse(this.settings);\n } catch {\n return {};\n }\n }\n\n /**\n * Set settings from object\n */\n setSettings(settings: Record<string, unknown>): void {\n this.settings = JSON.stringify(settings);\n }\n\n getConfiguration(): Record<string, unknown> {\n try {\n return JSON.parse(this.configuration || '{}');\n } catch {\n return {};\n }\n }\n\n setConfiguration(configuration: Record<string, unknown>): void {\n this.configuration = JSON.stringify(configuration);\n }\n\n get hasCredentials(): boolean {\n return Boolean(this.credentialSecretId || this.settings);\n }\n\n /**\n * Activate account\n */\n async activate(): Promise<void> {\n this.isActive = true;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Deactivate account\n */\n async deactivate(): Promise<void> {\n this.isActive = false;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Store credentials securely using smrt-secrets\n */\n async setCredentials(\n credentials: Record<string, unknown>,\n options: {\n description?: string;\n category?: string;\n } = {},\n ): Promise<void> {\n if (!this.id) {\n throw new Error('Account must be persisted before storing credentials.');\n }\n const secretService = await createAccountSecretService(this.db);\n\n const secretName = `${this.channelType || 'messaging'}-account-${this.id}`;\n const secretValue = JSON.stringify(credentials);\n const tenantId = this.requireCredentialTenantId('store credentials');\n\n await secretService.storeForTenant(\n tenantId,\n this.credentialSecretId || secretName,\n secretValue,\n {\n description: options.description || `Credentials for ${this.name}`,\n category: options.category || 'messaging',\n },\n );\n\n this.credentialSecretId ||= secretName;\n this.updatedAt = new Date();\n await this.withCredentialTenantContext(() => this.save());\n }\n\n /**\n * Create a sender for this account.\n * Subclasses must override to return a concrete sender.\n */\n async createSender(): Promise<MessageSenderInterface> {\n const { getMessagingProvider } = await import('../providers.js');\n const provider = getMessagingProvider(this.providerType);\n if (!provider?.createSender) {\n throw new Error(\n `createSender() not implemented for account type '${this.providerType}'`,\n );\n }\n return provider.createSender(this);\n }\n\n /**\n * Retrieve stored credentials\n */\n async getCredentials(): Promise<Record<string, unknown> | null> {\n if (!this.credentialSecretId) {\n return this.getSettings();\n }\n\n const tenantId = this.requireCredentialTenantId('retrieve credentials');\n const secretService = await createAccountSecretService(this.db);\n\n try {\n const secret = await secretService.retrieveForTenant(\n tenantId,\n this.credentialSecretId,\n );\n return JSON.parse(secret.value);\n } catch {\n return null;\n }\n }\n\n private getCredentialTenantId(): string | null {\n return this.tenantId || getCurrentTenant()?.tenantId || null;\n }\n\n private requireCredentialTenantId(action: string): string {\n const tenantId = this.getCredentialTenantId();\n if (!tenantId) {\n throw new Error(`Tenant context required to ${action}.`);\n }\n return tenantId;\n }\n\n private async withCredentialTenantContext<T>(\n fn: () => Promise<T>,\n ): Promise<T> {\n const tenantId = this.getCredentialTenantId();\n if (!tenantId || getCurrentTenant()?.tenantId === tenantId) return fn();\n return withTenant({ tenantId }, fn);\n }\n}\n","/**\n * AccountCollection - Unified collection for polymorphic account queries\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { queryGlobal, queryWithGlobals } from '../host.js';\nimport { Account } from '../models/Account';\nimport type { AccountSearchFilters } from '../types';\n\nexport class AccountCollection extends SmrtCollection<Account> {\n static readonly _itemClass = Account;\n\n /**\n * Get active accounts\n */\n async getActive(): Promise<Account[]> {\n return await this.list({ where: { isActive: true } });\n }\n\n /**\n * Get inactive accounts\n */\n async getInactive(): Promise<Account[]> {\n return await this.list({ where: { isActive: false } });\n }\n\n /**\n * Get accounts by provider type\n */\n async getByProviderType(providerType: string): Promise<Account[]> {\n return await this.list({ where: { providerType } });\n }\n\n /**\n * Get accounts by STI type.\n *\n * Accepts either the full discriminator (e.g. \"@happyvertical/smrt-messages:EmailAccount\")\n * or the short type name (e.g. \"EmailAccount\").\n */\n async getByType(accountType: string): Promise<Account[]> {\n if (accountType.includes(':') || accountType.startsWith('@')) {\n return await this.list({ where: { _meta_type: accountType } });\n }\n const allAccounts = await this.list({});\n return allAccounts.filter((a) => {\n const metaType = (a as { _meta_type?: string })._meta_type || '';\n return metaType.endsWith(`:${accountType}`);\n });\n }\n\n /**\n * Search accounts with filters\n */\n async search(\n query: string,\n filters?: AccountSearchFilters,\n ): Promise<Account[]> {\n let accounts = await this.list({});\n\n if (query) {\n const lowerQuery = query.toLowerCase();\n accounts = accounts.filter((a) =>\n a.name?.toLowerCase().includes(lowerQuery),\n );\n }\n\n if (filters) {\n if (filters.providerType) {\n accounts = accounts.filter(\n (a) => a.providerType === filters.providerType,\n );\n }\n if (filters.isActive !== undefined) {\n accounts = accounts.filter((a) => a.isActive === filters.isActive);\n }\n if (filters.accountType) {\n accounts = accounts.filter((a) => {\n const metaType = (a as { _meta_type?: string })._meta_type || '';\n return metaType.includes(filters.accountType as string);\n });\n }\n }\n\n return accounts;\n }\n\n /**\n * Get account statistics\n */\n async getStats(): Promise<{\n total: number;\n active: number;\n inactive: number;\n byType: Record<string, number>;\n }> {\n const accounts = await this.list({});\n const byType: Record<string, number> = {};\n\n for (const account of accounts) {\n const metaType =\n (account 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: accounts.length,\n active: accounts.filter((a) => a.isActive).length,\n inactive: accounts.filter((a) => !a.isActive).length,\n byType,\n };\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n async findByTenant(tenantId: string): Promise<Account[]> {\n return this.list({ where: { tenantId } });\n }\n\n // Account is the @TenantScoped STI base — see MessageCollection. Route through\n // the raw helpers; no `_meta_type` so the base returns ALL account subtypes.\n async findGlobal(): Promise<Account[]> {\n return queryGlobal<Account>(this);\n }\n\n async findWithGlobals(tenantId: string): Promise<Account[]> {\n return queryWithGlobals<Account>(this, tenantId, 'Account.findWithGlobals');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyBO,IAAM,UAAN,cAAsB,WAAW;CAEtC,WAA0B;CAK1B,OAAO;CAIP,eAAe;CAKf,cAAc;CAMd,qBAAoC;CAEpC,WAAW;CAEX,aAA0B;CAK1B,WAAW;CAMX,gBAAgB;CAIhB,4BAAY,IAAI,KAAK;CAErB,4BAAY,IAAI,KAAK;CAErB,YAAY,UAA0B,CAAC,GAAG;EACxC,MAAM,OAAO;EAEb,IAAI,QAAQ,aAAa,KAAA,GAAW,KAAK,WAAW,QAAQ;EAC5D,IAAI,QAAQ,SAAS,KAAA,GAAW,KAAK,OAAO,QAAQ;EACpD,IAAI,QAAQ,iBAAiB,KAAA,GAC3B,KAAK,eAAe,QAAQ;EAC9B,IAAI,QAAQ,gB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AQ,QAAQ;GAEnE,IAAI,QAAQ,aACV,WAAW,SAAS,QAAQ,MAAM;IAEhC,QADkB,EAA8B,cAAc,GAAA,CAC9C,SAAS,QAAQ,WAAqB;GACxD,CAAC;EAEL;EAEA,OAAO;CACT;;;;CAKA,MAAM,WAKH;EACD,MAAM,WAAW,MAAM,KAAK,KAAK,CAAC,CAAC;EACnC,MAAM,SAAiC,CAAC;EAExC,KAAA,MAAW,WAAW,UAAU;GAC9B,MAAM,WACH,QAAoC,cAAc;GACrD,MAAM,YAAY,SAAS,MAAM,GAAG,CAAA,CAAE,IAAI,KAAK;GAC/C,OAAO,cAAc,OAAO,cAAc,KAAK;EACjD;EAEA,OAAO;GACL,OAAO,SAAS;GAChB,QAAQ,SAAS,QAAQ,MAAM,EAAE,QAAQ,CAAA,CAAE;GAC3C,UAAU,SAAS,QAAQ,MAAM,CAAC,EAAE,QAAQ,CAAA,CAAE;GAC9C;EACF;CACF;CAMA,MAAM,aAAa,UAAsC;EACvD,OAAO,KAAK,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;CAC1C;CAIA,MAAM,aAAiC;EACrC,OAAO,YAAqB,IAAI;CAClC;CAEA,MAAM,gBAAgB,UAAsC;EAC1D,OAAO,iBAA0B,MAAM,UAAU,yBAAyB;CAC5E;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import "./__smrt-register__-DFDdoQdB.js";
3
- import { t as Message } from "./Message-BlnWWzXY.js";
2
+ import "./__smrt-register__-D3kBjvML.js";
3
+ import { t as Message } from "./Message-hIwx07Kt.js";
4
4
  import { field, smrt } from "@happyvertical/smrt-core";
5
5
  //#region src/models/Email.ts
6
6
  var Email_exports = /* @__PURE__ */ __exportAll({ Email: () => Email });
@@ -334,4 +334,4 @@ Email = __decorateClass([smrt({
334
334
  //#endregion
335
335
  export { Email_exports as n, Email as t };
336
336
 
337
- //# sourceMappingURL=Email-Bbuefk_z.js.map
337
+ //# sourceMappingURL=Email-p5qIyMC5.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Email-Bbuefk_z.js","names":[],"sources":["../../src/models/Email.ts"],"sourcesContent":["/**\n * Email model - Email message extending the Message STI base\n *\n * Retains all email-specific fields (RFC 822 compliance, folders, etc.)\n * while inheriting common message fields from Message.\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 { field, smrt } from '@happyvertical/smrt-core';\nimport type {\n EmailOptions,\n MessageSendResult,\n SendEmailOptions,\n} from '../types';\nimport { Message } from './Message';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get', 'create', 'update', 'delete'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n // Message is read-only over REST; this provider type is writable there.\n widenParentExposure: { api: ['create', 'update', 'delete'] },\n})\nexport class Email extends Message { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n // RFC 822 fields\n @field({\n description:\n 'The email reference assigned by the sender for tracking replies.',\n })\n messageId = ''; // RFC 822 Message-ID header\n @field({\n description: 'The sender-assigned reference of the email being replied to.',\n })\n inReplyTo = '';\n\n // Additional recipients\n @field({ description: 'Recipients receiving a visible copy of this email.' })\n ccAddresses = '';\n @field({\n description:\n 'Recipients receiving a copy without appearing in the visible recipient list.',\n })\n bccAddresses = '';\n @field({ description: 'The address replies should be sent to.' })\n replyToAddress = '';\n @field({ description: 'The name associated with the reply address.' })\n replyToName = '';\n\n // Email-specific content\n @field({ description: 'The plain-text version of the email.' })\n textBody = '';\n @field({ description: 'The formatted version of the email.' })\n htmlBody = '';\n\n // Location\n @field({\n description:\n 'The mailbox folder reference supplied by the email connection.',\n })\n folderId = '';\n @field({\n description: 'The location of this email within the mailbox folders.',\n })\n folderPath = '';\n @field({\n description: 'Labels applied to this email by the mailbox provider.',\n })\n labels = ''; // JSON array (Gmail)\n @field({ description: 'Mailbox markers such as read, answered, or flagged.' })\n flags = ''; // JSON array (IMAP)\n\n // Email-specific status flags\n @field({ description: 'Whether this email has been replied to.' })\n isAnswered = false;\n @field({ description: 'Whether this email is saved as an unfinished draft.' })\n isDraft = false;\n\n // Raw data\n @field({\n description: 'The original email content as received from the mail server.',\n })\n rawMessage = '';\n @field({\n description: 'Delivery and routing details included with the email.',\n })\n headers = ''; // JSON object\n\n constructor(options: EmailOptions = {}) {\n super(options);\n\n if (options.messageId !== undefined) this.messageId = options.messageId;\n if (options.inReplyTo !== undefined) this.inReplyTo = options.inReplyTo;\n if (options.ccAddresses !== undefined)\n this.ccAddresses = options.ccAddresses;\n if (options.bccAddresses !== undefined)\n this.bccAddresses = options.bccAddresses;\n if (options.replyToAddress !== undefined)\n this.replyToAddress = options.replyToAddress;\n if (options.replyToName !== undefined)\n this.replyToName = options.replyToName;\n if (options.textBody !== undefined) this.textBody = options.textBody;\n if (options.htmlBody !== undefined) this.htmlBody = options.htmlBody;\n if (options.folderId !== undefined) this.folderId = options.folderId;\n if (options.folderPath !== undefined) this.folderPath = options.folderPath;\n if (options.labels !== undefined) this.labels = options.labels;\n if (options.flags !== undefined) this.flags = options.flags;\n if (options.isAnswered !== undefined) this.isAnswered = options.isAnswered;\n if (options.isDraft !== undefined) this.isDraft = options.isDraft;\n if (options.rawMessage !== undefined) this.rawMessage = options.rawMessage;\n if (options.headers !== undefined) this.headers = options.headers;\n\n // Populate base body from textBody for unified access\n if (options.textBody && !options.body) {\n this.body = options.textBody;\n }\n }\n\n /**\n * Get CC addresses as parsed array\n */\n getCcAddresses(): Array<{ address: string; name?: string }> {\n if (!this.ccAddresses) return [];\n try {\n return JSON.parse(this.ccAddresses);\n } catch {\n return [];\n }\n }\n\n /**\n * Get BCC addresses as parsed array\n */\n getBccAddresses(): Array<{ address: string; name?: string }> {\n if (!this.bccAddresses) return [];\n try {\n return JSON.parse(this.bccAddresses);\n } catch {\n return [];\n }\n }\n\n /**\n * Get labels as parsed array\n */\n getLabels(): string[] {\n if (!this.labels) return [];\n try {\n return JSON.parse(this.labels);\n } catch {\n return [];\n }\n }\n\n /**\n * Set labels from array\n */\n setLabels(labels: string[]): void {\n this.labels = JSON.stringify(labels);\n }\n\n /**\n * Get flags as parsed array\n */\n getFlags(): string[] {\n if (!this.flags) return [];\n try {\n return JSON.parse(this.flags);\n } catch {\n return [];\n }\n }\n\n /**\n * Set flags from array\n */\n setFlags(flags: string[]): void {\n this.flags = JSON.stringify(flags);\n }\n\n /**\n * Get headers as parsed object\n */\n getHeaders(): Record<string, string | string[]> {\n if (!this.headers) return {};\n try {\n return JSON.parse(this.headers);\n } catch {\n return {};\n }\n }\n\n /**\n * Set headers from object\n */\n setHeaders(headers: Record<string, string | string[]>): void {\n this.headers = JSON.stringify(headers);\n }\n\n /**\n * Get the email account (typed as EmailAccount)\n */\n override async getAccount() {\n if (!this.accountId) return null;\n\n const { EmailAccountCollection } = await import(\n '../collections/EmailAccountCollection'\n );\n const collection = await EmailAccountCollection.create(this.options);\n\n return await collection.get({ id: this.accountId });\n }\n\n /**\n * Get the folder\n */\n async getFolder() {\n if (!this.folderId) return null;\n\n const { EmailFolderCollection } = await import(\n '../collections/EmailFolderCollection'\n );\n const collection = await EmailFolderCollection.create(this.options);\n\n return await collection.get({ id: this.folderId });\n }\n\n /**\n * Get emails in the same thread\n */\n async getThreadEmails(): Promise<Email[]> {\n if (!this.threadId) return [this];\n\n const { EmailCollection } = await import('../collections/EmailCollection');\n const collection = await EmailCollection.create(this.options);\n\n return await collection.getByThread(this.threadId);\n }\n\n /**\n * Get a short preview of the email body\n */\n override getPreview(maxLength = 200): string {\n const body = this.textBody || this.htmlBody?.replace(/<[^>]*>/g, '') || '';\n if (body.length <= maxLength) return body;\n return `${body.slice(0, maxLength)}...`;\n }\n\n /**\n * Get References header values as array\n */\n getReferences(): string[] {\n const headers = this.getHeaders();\n const refs = headers.references;\n if (!refs) return [];\n if (Array.isArray(refs)) return refs;\n return refs.split(/\\s+/).filter(Boolean);\n }\n\n /**\n * Create a reply to this email with RFC 822 threading\n */\n override createReply(options?: { replyAll?: boolean }): Email {\n const reply = new Email({\n ...this.draftOptions(),\n id: undefined,\n accountId: this.accountId,\n threadId: this.threadId || this.id || undefined,\n subject: this.subject.startsWith('Re:')\n ? this.subject\n : `Re: ${this.subject}`,\n fromAddress: '',\n fromName: '',\n inReplyToMessageId: this.id || undefined,\n sendStatus: 'draft',\n isRead: true,\n isDraft: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n\n // RFC 822 threading\n inReplyTo: this.messageId,\n\n // To: original sender\n toAddresses: JSON.stringify([\n { address: this.fromAddress, name: this.fromName },\n ]),\n });\n\n // RFC 822 References: original references + original Message-ID\n const refs = [...this.getReferences()];\n if (this.messageId && !refs.includes(this.messageId)) {\n refs.push(this.messageId);\n }\n reply.setHeaders({ references: refs.join(' ') });\n\n // Reply-All: add original To/CC as CC (excluding self)\n if (options?.replyAll) {\n const allRecipients = [\n ...this.getToAddresses(),\n ...this.getCcAddresses(),\n ];\n // Remove original sender (already in To:) and any duplicates\n const seen = new Set([this.fromAddress.toLowerCase()]);\n const ccAddresses = allRecipients.filter((r) => {\n const addr = r.address.toLowerCase();\n if (seen.has(addr)) return false;\n seen.add(addr);\n return true;\n });\n reply.ccAddresses = JSON.stringify(ccAddresses);\n }\n\n reply.body = this.buildQuotedBody();\n reply.textBody = reply.body;\n\n return reply;\n }\n\n /**\n * Create a forward of this email\n */\n override createForward(): Email {\n const forwardBody = this.buildForwardBody();\n\n const forward = new Email({\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 ccAddresses: '[]',\n bccAddresses: '[]',\n fromAddress: '',\n fromName: '',\n body: forwardBody,\n textBody: forwardBody,\n hasAttachments: this.hasAttachments,\n inReplyToMessageId: '',\n inReplyTo: '',\n sendStatus: 'draft',\n isDraft: true,\n isRead: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n });\n\n return forward;\n }\n\n /**\n * Build email-specific quoted body for replies\n */\n protected override 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 bodyText = this.textBody || this.body || '';\n const quotedLines = bodyText\n .split('\\n')\n .map((line) => `> ${line}`)\n .join('\\n');\n\n return `\\n\\nOn ${dateStr}, ${from} wrote:\\n${quotedLines}`;\n }\n\n /**\n * Build forwarded message body\n */\n private buildForwardBody(): 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 toStr = this.getToAddresses()\n .map((r) => (r.name ? `${r.name} <${r.address}>` : r.address))\n .join(', ');\n\n const bodyText = this.textBody || this.body || '';\n\n return [\n '',\n '',\n '---------- Forwarded message ----------',\n `From: ${from}`,\n `Date: ${dateStr}`,\n `Subject: ${this.subject}`,\n `To: ${toStr}`,\n '',\n bodyText,\n ].join('\\n');\n }\n\n /**\n * Send this email. Accepts {@link SendEmailOptions}, including send-time\n * `attachments`, which `EmailSender` merges with the stored rows (#3808).\n */\n override async send(options?: SendEmailOptions): Promise<MessageSendResult> {\n const result = await super.send(options);\n await this.markHasAttachments(options, result);\n return result;\n }\n\n /** Retry a failed send; takes the same options as {@link Email.send}. */\n override async retrySend(\n options?: SendEmailOptions,\n ): Promise<MessageSendResult> {\n const result = await super.retrySend(options);\n await this.markHasAttachments(options, result);\n return result;\n }\n\n /**\n * Record `hasAttachments` once send-time bytes were actually delivered, so a\n * rejected or failed send never claims attachments that did not go out.\n */\n private async markHasAttachments(\n options: SendEmailOptions | undefined,\n result: MessageSendResult,\n ): Promise<void> {\n if (!result.success || !options?.attachments?.length) return;\n if (this.hasAttachments) return;\n this.hasAttachments = true;\n if (this.isPersisted) await this.save();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0BO,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,GAzDU,MA0DX,WAAA,cAAA,CAAA;AAIA,gBAAA,CAHC,MAAM,EACL,aAAa,wDACf,CAAC,CAAA,GA7DU,MA8DX,WAAA,WAAA,CAAA;AA9DW,QAAN,gBAAA,CARN,KAAK;CACJ,eAAe;CACf,KAAK,EAAE,SAAS;EAAC;EAAQ;EAAO;EAAU;EAAU;CAAQ,EAAE;CAC9D,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,cAAc,KAAK;CAE1B,qBAAqB,EAAE,KAAK;EAAC;EAAU;EAAU;CAAQ,EAAE;AAC7D,CAAC,CAAA,GACY,KAAA"}
1
+ {"version":3,"file":"Email-p5qIyMC5.js","names":[],"sources":["../../src/models/Email.ts"],"sourcesContent":["/**\n * Email model - Email message extending the Message STI base\n *\n * Retains all email-specific fields (RFC 822 compliance, folders, etc.)\n * while inheriting common message fields from Message.\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 { field, smrt } from '@happyvertical/smrt-core';\nimport type {\n EmailOptions,\n MessageSendResult,\n SendEmailOptions,\n} from '../types';\nimport { Message } from './Message';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get', 'create', 'update', 'delete'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n // Message is read-only over REST; this provider type is writable there.\n widenParentExposure: { api: ['create', 'update', 'delete'] },\n})\nexport class Email extends Message { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n // RFC 822 fields\n @field({\n description:\n 'The email reference assigned by the sender for tracking replies.',\n })\n messageId = ''; // RFC 822 Message-ID header\n @field({\n description: 'The sender-assigned reference of the email being replied to.',\n })\n inReplyTo = '';\n\n // Additional recipients\n @field({ description: 'Recipients receiving a visible copy of this email.' })\n ccAddresses = '';\n @field({\n description:\n 'Recipients receiving a copy without appearing in the visible recipient list.',\n })\n bccAddresses = '';\n @field({ description: 'The address replies should be sent to.' })\n replyToAddress = '';\n @field({ description: 'The name associated with the reply address.' })\n replyToName = '';\n\n // Email-specific content\n @field({ description: 'The plain-text version of the email.' })\n textBody = '';\n @field({ description: 'The formatted version of the email.' })\n htmlBody = '';\n\n // Location\n @field({\n description:\n 'The mailbox folder reference supplied by the email connection.',\n })\n folderId = '';\n @field({\n description: 'The location of this email within the mailbox folders.',\n })\n folderPath = '';\n @field({\n description: 'Labels applied to this email by the mailbox provider.',\n })\n labels = ''; // JSON array (Gmail)\n @field({ description: 'Mailbox markers such as read, answered, or flagged.' })\n flags = ''; // JSON array (IMAP)\n\n // Email-specific status flags\n @field({ description: 'Whether this email has been replied to.' })\n isAnswered = false;\n @field({ description: 'Whether this email is saved as an unfinished draft.' })\n isDraft = false;\n\n // Raw data\n @field({\n description: 'The original email content as received from the mail server.',\n })\n rawMessage = '';\n @field({\n description: 'Delivery and routing details included with the email.',\n })\n headers = ''; // JSON object\n\n constructor(options: EmailOptions = {}) {\n super(options);\n\n if (options.messageId !== undefined) this.messageId = options.messageId;\n if (options.inReplyTo !== undefined) this.inReplyTo = options.inReplyTo;\n if (options.ccAddresses !== undefined)\n this.ccAddresses = options.ccAddresses;\n if (options.bccAddresses !== undefined)\n this.bccAddresses = options.bccAddresses;\n if (options.replyToAddress !== undefined)\n this.replyToAddress = options.replyToAddress;\n if (options.replyToName !== undefined)\n this.replyToName = options.replyToName;\n if (options.textBody !== undefined) this.textBody = options.textBody;\n if (options.htmlBody !== undefined) this.htmlBody = options.htmlBody;\n if (options.folderId !== undefined) this.folderId = options.folderId;\n if (options.folderPath !== undefined) this.folderPath = options.folderPath;\n if (options.labels !== undefined) this.labels = options.labels;\n if (options.flags !== undefined) this.flags = options.flags;\n if (options.isAnswered !== undefined) this.isAnswered = options.isAnswered;\n if (options.isDraft !== undefined) this.isDraft = options.isDraft;\n if (options.rawMessage !== undefined) this.rawMessage = options.rawMessage;\n if (options.headers !== undefined) this.headers = options.headers;\n\n // Populate base body from textBody for unified access\n if (options.textBody && !options.body) {\n this.body = options.textBody;\n }\n }\n\n /**\n * Get CC addresses as parsed array\n */\n getCcAddresses(): Array<{ address: string; name?: string }> {\n if (!this.ccAddresses) return [];\n try {\n return JSON.parse(this.ccAddresses);\n } catch {\n return [];\n }\n }\n\n /**\n * Get BCC addresses as parsed array\n */\n getBccAddresses(): Array<{ address: string; name?: string }> {\n if (!this.bccAddresses) return [];\n try {\n return JSON.parse(this.bccAddresses);\n } catch {\n return [];\n }\n }\n\n /**\n * Get labels as parsed array\n */\n getLabels(): string[] {\n if (!this.labels) return [];\n try {\n return JSON.parse(this.labels);\n } catch {\n return [];\n }\n }\n\n /**\n * Set labels from array\n */\n setLabels(labels: string[]): void {\n this.labels = JSON.stringify(labels);\n }\n\n /**\n * Get flags as parsed array\n */\n getFlags(): string[] {\n if (!this.flags) return [];\n try {\n return JSON.parse(this.flags);\n } catch {\n return [];\n }\n }\n\n /**\n * Set flags from array\n */\n setFlags(flags: string[]): void {\n this.flags = JSON.stringify(flags);\n }\n\n /**\n * Get headers as parsed object\n */\n getHeaders(): Record<string, string | string[]> {\n if (!this.headers) return {};\n try {\n return JSON.parse(this.headers);\n } catch {\n return {};\n }\n }\n\n /**\n * Set headers from object\n */\n setHeaders(headers: Record<string, string | string[]>): void {\n this.headers = JSON.stringify(headers);\n }\n\n /**\n * Get the email account (typed as EmailAccount)\n */\n override async getAccount() {\n if (!this.accountId) return null;\n\n const { EmailAccountCollection } = await import(\n '../collections/EmailAccountCollection'\n );\n const collection = await EmailAccountCollection.create(this.options);\n\n return await collection.get({ id: this.accountId });\n }\n\n /**\n * Get the folder\n */\n async getFolder() {\n if (!this.folderId) return null;\n\n const { EmailFolderCollection } = await import(\n '../collections/EmailFolderCollection'\n );\n const collection = await EmailFolderCollection.create(this.options);\n\n return await collection.get({ id: this.folderId });\n }\n\n /**\n * Get emails in the same thread\n */\n async getThreadEmails(): Promise<Email[]> {\n if (!this.threadId) return [this];\n\n const { EmailCollection } = await import('../collections/EmailCollection');\n const collection = await EmailCollection.create(this.options);\n\n return await collection.getByThread(this.threadId);\n }\n\n /**\n * Get a short preview of the email body\n */\n override getPreview(maxLength = 200): string {\n const body = this.textBody || this.htmlBody?.replace(/<[^>]*>/g, '') || '';\n if (body.length <= maxLength) return body;\n return `${body.slice(0, maxLength)}...`;\n }\n\n /**\n * Get References header values as array\n */\n getReferences(): string[] {\n const headers = this.getHeaders();\n const refs = headers.references;\n if (!refs) return [];\n if (Array.isArray(refs)) return refs;\n return refs.split(/\\s+/).filter(Boolean);\n }\n\n /**\n * Create a reply to this email with RFC 822 threading\n */\n override createReply(options?: { replyAll?: boolean }): Email {\n const reply = new Email({\n ...this.draftOptions(),\n id: undefined,\n accountId: this.accountId,\n threadId: this.threadId || this.id || undefined,\n subject: this.subject.startsWith('Re:')\n ? this.subject\n : `Re: ${this.subject}`,\n fromAddress: '',\n fromName: '',\n inReplyToMessageId: this.id || undefined,\n sendStatus: 'draft',\n isRead: true,\n isDraft: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n\n // RFC 822 threading\n inReplyTo: this.messageId,\n\n // To: original sender\n toAddresses: JSON.stringify([\n { address: this.fromAddress, name: this.fromName },\n ]),\n });\n\n // RFC 822 References: original references + original Message-ID\n const refs = [...this.getReferences()];\n if (this.messageId && !refs.includes(this.messageId)) {\n refs.push(this.messageId);\n }\n reply.setHeaders({ references: refs.join(' ') });\n\n // Reply-All: add original To/CC as CC (excluding self)\n if (options?.replyAll) {\n const allRecipients = [\n ...this.getToAddresses(),\n ...this.getCcAddresses(),\n ];\n // Remove original sender (already in To:) and any duplicates\n const seen = new Set([this.fromAddress.toLowerCase()]);\n const ccAddresses = allRecipients.filter((r) => {\n const addr = r.address.toLowerCase();\n if (seen.has(addr)) return false;\n seen.add(addr);\n return true;\n });\n reply.ccAddresses = JSON.stringify(ccAddresses);\n }\n\n reply.body = this.buildQuotedBody();\n reply.textBody = reply.body;\n\n return reply;\n }\n\n /**\n * Create a forward of this email\n */\n override createForward(): Email {\n const forwardBody = this.buildForwardBody();\n\n const forward = new Email({\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 ccAddresses: '[]',\n bccAddresses: '[]',\n fromAddress: '',\n fromName: '',\n body: forwardBody,\n textBody: forwardBody,\n hasAttachments: this.hasAttachments,\n inReplyToMessageId: '',\n inReplyTo: '',\n sendStatus: 'draft',\n isDraft: true,\n isRead: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n });\n\n return forward;\n }\n\n /**\n * Build email-specific quoted body for replies\n */\n protected override 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 bodyText = this.textBody || this.body || '';\n const quotedLines = bodyText\n .split('\\n')\n .map((line) => `> ${line}`)\n .join('\\n');\n\n return `\\n\\nOn ${dateStr}, ${from} wrote:\\n${quotedLines}`;\n }\n\n /**\n * Build forwarded message body\n */\n private buildForwardBody(): 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 toStr = this.getToAddresses()\n .map((r) => (r.name ? `${r.name} <${r.address}>` : r.address))\n .join(', ');\n\n const bodyText = this.textBody || this.body || '';\n\n return [\n '',\n '',\n '---------- Forwarded message ----------',\n `From: ${from}`,\n `Date: ${dateStr}`,\n `Subject: ${this.subject}`,\n `To: ${toStr}`,\n '',\n bodyText,\n ].join('\\n');\n }\n\n /**\n * Send this email. Accepts {@link SendEmailOptions}, including send-time\n * `attachments`, which `EmailSender` merges with the stored rows (#3808).\n */\n override async send(options?: SendEmailOptions): Promise<MessageSendResult> {\n const result = await super.send(options);\n await this.markHasAttachments(options, result);\n return result;\n }\n\n /** Retry a failed send; takes the same options as {@link Email.send}. */\n override async retrySend(\n options?: SendEmailOptions,\n ): Promise<MessageSendResult> {\n const result = await super.retrySend(options);\n await this.markHasAttachments(options, result);\n return result;\n }\n\n /**\n * Record `hasAttachments` once send-time bytes were actually delivered, so a\n * rejected or failed send never claims attachments that did not go out.\n */\n private async markHasAttachments(\n options: SendEmailOptions | undefined,\n result: MessageSendResult,\n ): Promise<void> {\n if (!result.success || !options?.attachments?.length) return;\n if (this.hasAttachments) return;\n this.hasAttachments = true;\n if (this.isPersisted) await this.save();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0BO,IAAM,QAAN,cAAoB,QAAQ;CAMjC,YAAY;CAIZ,YAAY;CAIZ,cAAc;CAKd,eAAe;CAEf,iBAAiB;CAEjB,cAAc;CAId,WAAW;CAEX,WAAW;CAOX,WAAW;CAIX,aAAa;CAIb,SAAS;CAET,QAAQ;CAIR,aAAa;CAEb,UAAU;CAMV,aAAa;CAIb,UAAU;CAEV,YAAY,UAAwB,CAAC,GAAG;EACtC,MAAM,OAAO;EAEb,IAAI,QAAQ,cAAc,KAAA,GAAW,KAAK,YAAY,QAAQ;EAC9D,IAAI,QAAQ,cAAc,KAAA,GAAW,KAAK,YAAY,QAAQ;EAC9D,IAAI,QAAQ,gBAAgB,KAAA,GAC1B,KAAK,cAAc,QAAQ;EAC7B,IAAI,QAAQ,iBAAiB,KAAA,GAC3B,KAAK,eAAe,QAAQ;EAC9B,IAAI,QAAQ,mBAAmB,KAAA,GAC7B,KAAK,iBAAiB,QAAQ;EAChC,IAAI,QAAQ,gBAAgB,KAAA,GAC1B,KAAK,cAAc,QAAQ;EAC7B,IAAI,QAAQ,aAAa,KAAA,GAAW,KAAK,WAAW,QAAQ;EAC5D,IAAI,QAAQ,aAAa,KAAA,GAAW,KAAK,WAAW,QAAQ;EAC5D,IAAI,QAAQ,aAAa,KAAA,GAAW,KAAK,WAAW,QAAQ;EAC5D,IAAI,QAAQ,eAAe,KAAA,GAAW,KAAK,aAAa,QAAQ;EAChE,IAAI,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3CU,MA4CX,WAAA,UAAA,CAAA;AAEA,gBAAA,CADC,MAAM,EAAE,aAAa,sDAAsD,CAAC,CAAA,GA7ClE,MA8CX,WAAA,SAAA,CAAA;AAIA,gBAAA,CADC,MAAM,EAAE,aAAa,0CAA0C,CAAC,CAAA,GAjDtD,MAkDX,WAAA,cAAA,CAAA;AAEA,gBAAA,CADC,MAAM,EAAE,aAAa,sDAAsD,CAAC,CAAA,GAnDlE,MAoDX,WAAA,WAAA,CAAA;AAMA,gBAAA,CAHC,MAAM,EACL,aAAa,+DACf,CAAC,CAAA,GAzDU,MA0DX,WAAA,cAAA,CAAA;AAIA,gBAAA,CAHC,MAAM,EACL,aAAa,wDACf,CAAC,CAAA,GA7DU,MA8DX,WAAA,WAAA,CAAA;AA9DW,QAAN,gBAAA,CARN,KAAK;CACJ,eAAe;CACf,KAAK,EAAE,SAAS;EAAC;EAAQ;EAAO;EAAU;EAAU;CAAQ,EAAE;CAC9D,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,cAAc,KAAK;CAE1B,qBAAqB,EAAE,KAAK;EAAC;EAAU;EAAU;CAAQ,EAAE;AAC7D,CAAC,CAAA,GACY,KAAA"}
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import "./__smrt-register__-DFDdoQdB.js";
2
+ import "./__smrt-register__-D3kBjvML.js";
3
3
  import { SmrtObject, foreignKey, smrt } from "@happyvertical/smrt-core";
4
- import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy";
4
+ import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy/decorators";
5
5
  //#region src/models/EmailFolder.ts
6
6
  var EmailFolder_exports = /* @__PURE__ */ __exportAll({ EmailFolder: () => EmailFolder });
7
7
  var __defProp = Object.defineProperty;
@@ -159,4 +159,4 @@ EmailFolder = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
159
159
  //#endregion
160
160
  export { EmailFolder_exports as n, EmailFolder as t };
161
161
 
162
- //# sourceMappingURL=EmailFolder-CzElqWJv.js.map
162
+ //# sourceMappingURL=EmailFolder-Dk4hxikK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EmailFolder-Dk4hxikK.js","names":[],"sources":["../../src/models/EmailFolder.ts"],"sourcesContent":["/**\n * EmailFolder model - Folder/label tracking\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 { foreignKey, SmrtObject, smrt } from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport type { EmailFolderOptions } from '../types';\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n api: { include: ['list', 'get', 'create', 'update', 'delete'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class EmailFolder extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n @foreignKey('Account')\n accountId = '';\n name = '';\n path = '';\n delimiter = '/';\n specialUse = ''; // '\\\\Inbox', '\\\\Sent', '\\\\Drafts', etc.\n messageCount = 0;\n unreadCount = 0;\n subscribed = true;\n\n // Timestamps\n createdAt = new Date();\n updatedAt = new Date();\n\n constructor(options: EmailFolderOptions = {}) {\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.name !== undefined) this.name = options.name;\n if (options.path !== undefined) this.path = options.path;\n if (options.delimiter !== undefined) this.delimiter = options.delimiter;\n if (options.specialUse !== undefined) this.specialUse = options.specialUse;\n if (options.messageCount !== undefined)\n this.messageCount = options.messageCount;\n if (options.unreadCount !== undefined)\n this.unreadCount = options.unreadCount;\n if (options.subscribed !== undefined) this.subscribed = options.subscribed;\n if (options.createdAt) this.createdAt = options.createdAt;\n if (options.updatedAt) this.updatedAt = options.updatedAt;\n }\n\n /**\n * Get the email account\n */\n async getAccount() {\n if (!this.accountId) return null;\n\n const { EmailAccountCollection } = await import(\n '../collections/EmailAccountCollection'\n );\n const collection = await EmailAccountCollection.create(this.options);\n\n return await collection.get({ id: this.accountId });\n }\n\n /**\n * Get all emails in this folder\n */\n async getEmails(limit?: number) {\n const { EmailCollection } = await import('../collections/EmailCollection');\n const collection = await EmailCollection.create(this.options);\n\n const options: { where: Record<string, unknown>; limit?: number } = {\n where: { folderId: this.id },\n };\n if (limit) {\n options.limit = limit;\n }\n\n return await collection.list(options);\n }\n\n /**\n * Get unread emails in this folder\n */\n async getUnreadEmails(limit?: number) {\n const { EmailCollection } = await import('../collections/EmailCollection');\n const collection = await EmailCollection.create(this.options);\n\n const options: { where: Record<string, unknown>; limit?: number } = {\n where: { folderId: this.id, isRead: false },\n };\n if (limit) {\n options.limit = limit;\n }\n\n return await collection.list(options);\n }\n\n /**\n * Update message counts from database\n */\n async refreshCounts(): Promise<void> {\n if (!this.id) {\n throw new Error(\n 'EmailFolder.refreshCounts requires a persisted folder (missing id)',\n );\n }\n const folderId = this.id;\n const { EmailCollection } = await import('../collections/EmailCollection');\n const collection = await EmailCollection.create(this.options);\n\n this.messageCount = await collection.countByFolder(folderId);\n this.unreadCount = await collection.countUnreadByFolder(folderId);\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Check if this is the inbox folder\n */\n isInbox(): boolean {\n return this.specialUse === '\\\\Inbox' || this.path.toLowerCase() === 'inbox';\n }\n\n /**\n * Check if this is the sent folder\n */\n isSent(): boolean {\n return this.specialUse === '\\\\Sent' || this.path.toLowerCase() === 'sent';\n }\n\n /**\n * Check if this is the drafts folder\n */\n isDrafts(): boolean {\n return (\n this.specialUse === '\\\\Drafts' || this.path.toLowerCase() === 'drafts'\n );\n }\n\n /**\n * Check if this is the trash folder\n */\n isTrash(): boolean {\n return this.specialUse === '\\\\Trash' || this.path.toLowerCase() === 'trash';\n }\n\n /**\n * Check if this is the spam/junk folder\n */\n isSpam(): boolean {\n return (\n this.specialUse === '\\\\Junk' ||\n this.path.toLowerCase() === 'spam' ||\n this.path.toLowerCase() === 'junk'\n );\n }\n\n /**\n * Check if this is a system folder\n */\n isSystemFolder(): boolean {\n return !!this.specialUse;\n }\n\n /**\n * Subscribe to folder\n */\n async subscribe(): Promise<void> {\n this.subscribed = true;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Unsubscribe from folder\n */\n async unsubscribe(): Promise<void> {\n this.subscribed = false;\n this.updatedAt = new Date();\n await this.save();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiBO,IAAM,cAAN,cAA0B,WAAW;CAE1C,WAA0B;CAG1B,YAAY;CACZ,OAAO;CACP,OAAO;CACP,YAAY;CACZ,aAAa;CACb,eAAe;CACf,cAAc;CACd,aAAa;CAGb,4BAAY,IAAI,KAAK;CACrB,4BAAY,IAAI,KAAK;CAErB,YAAY,UAA8B,CAAC,GAAG;EAC5C,MAAM,OAAO;EAEb,IAAI,QAAQ,aAAa,KAAA,GAAW,KAAK,WAAW,QAAQ;EAC5D,IAAI,QAAQ,cAAc,KAAA,GAAW,KAAK,YAAY,QAAQ;EAC9D,IAAI,QAAQ,SAAS,KAAA,GAAW,KAAK,OAAO,QAAQ;EACpD,IAAI,QAAQ,SAAS,KAAA,GAAW,KAAK,OAAO,QAAQ;EACpD,IAAI,QAAQ,cAAc,KAAA,GAAW,KAAK,YAAY,QAAQ;EAC9D,IAAI,QAAQ,eAAe,KAAA,GAAW,KAAK,aAAa,QAAQ;EAChE,IAAI,QAAQ,iBAAiB,KAAA,GAC3B,KAAK,eAAe,QAAQ;EAC9B,IAAI,QAAQ,gBAAgB,KAAA,GAC1B,KAAK,cAAc,QAAQ;EAC7B,IAAI,QAAQ,eAAe,KAAA,GAAW,KAAK,aAAa,QAAQ;EAChE,IAAI,QAAQ,WAAW,KAAK,YAAY,QAAQ;EAChD,IAAI,QAAQ,WAAW,KAAK,YAAY,QAAQ;CAClD;;;;CA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