@jini-ai/user-management 0.7.3-next.1 → 0.7.3-next.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/CHANGELOG.md +6 -0
- package/README.md +55 -2
- package/dist/admin/adapters/memory.js +4 -4
- package/dist/admin-http/auth/auth-request.d.ts +112 -0
- package/dist/admin-http/auth/auth-request.js +32 -0
- package/dist/admin-http/auth/boot-redemption.d.ts +9 -0
- package/dist/admin-http/auth/boot-redemption.js +17 -0
- package/dist/admin-http/auth/boot-session.d.ts +30 -0
- package/dist/admin-http/auth/boot-session.js +40 -0
- package/dist/admin-http/auth/current-user.d.ts +28 -0
- package/dist/admin-http/auth/current-user.js +34 -0
- package/dist/admin-http/auth/index.d.ts +17 -0
- package/dist/admin-http/auth/index.js +9 -0
- package/dist/admin-http/auth/local-boot-session.d.ts +9 -0
- package/dist/admin-http/auth/local-boot-session.js +30 -0
- package/dist/admin-http/auth/logout.d.ts +10 -0
- package/dist/admin-http/auth/logout.js +17 -0
- package/dist/admin-http/auth/mfa-login.d.ts +30 -0
- package/dist/admin-http/auth/mfa-login.js +43 -0
- package/dist/admin-http/auth/password-login.d.ts +35 -0
- package/dist/admin-http/auth/password-login.js +52 -0
- package/dist/admin-http/auth/password-status.d.ts +34 -0
- package/dist/admin-http/auth/password-status.js +42 -0
- package/dist/admin-http/http/api-keys.d.ts +45 -0
- package/dist/admin-http/http/api-keys.js +28 -0
- package/dist/admin-http/http/users.d.ts +71 -0
- package/dist/admin-http/http/users.js +42 -0
- package/dist/admin-http/owner/mfa-deps.d.ts +41 -0
- package/dist/admin-http/owner/mfa-deps.js +26 -0
- package/dist/admin-http/owner/mfa-routes.d.ts +72 -0
- package/dist/admin-http/owner/mfa-routes.js +105 -0
- package/dist/admin-http/owner/passkey-admission.d.ts +46 -0
- package/dist/admin-http/owner/passkey-admission.js +23 -0
- package/dist/admin-http/owner/passkey-route-deps.d.ts +53 -0
- package/dist/admin-http/owner/passkey-route-deps.js +33 -0
- package/dist/admin-http/owner/passkey-routes.d.ts +146 -0
- package/dist/admin-http/owner/passkey-routes.js +98 -0
- package/dist/admin-http/owner/recovery-routes.d.ts +71 -0
- package/dist/admin-http/owner/recovery-routes.js +112 -0
- package/dist/admin-http/routes/api-keys/create-principal.d.ts +26 -0
- package/dist/admin-http/routes/api-keys/create-principal.js +37 -0
- package/dist/admin-http/routes/api-keys/issue.d.ts +32 -0
- package/dist/admin-http/routes/api-keys/issue.js +38 -0
- package/dist/admin-http/routes/api-keys/revoke.d.ts +26 -0
- package/dist/admin-http/routes/api-keys/revoke.js +31 -0
- package/dist/admin-http/routes/api-keys/shared.d.ts +46 -0
- package/dist/admin-http/routes/api-keys/shared.js +38 -0
- package/dist/admin-http/routes/users/access-shared.d.ts +103 -0
- package/dist/admin-http/routes/users/access-shared.js +85 -0
- package/dist/admin-http/routes/users/assign-role.d.ts +24 -0
- package/dist/admin-http/routes/users/assign-role.js +30 -0
- package/dist/admin-http/routes/users/attach-policy.d.ts +25 -0
- package/dist/admin-http/routes/users/attach-policy.js +31 -0
- package/dist/admin-http/routes/users/create-policy.d.ts +19 -0
- package/dist/admin-http/routes/users/create-policy.js +28 -0
- package/dist/admin-http/routes/users/create-role.d.ts +15 -0
- package/dist/admin-http/routes/users/create-role.js +21 -0
- package/dist/admin-http/routes/users/create.d.ts +32 -0
- package/dist/admin-http/routes/users/create.js +67 -0
- package/dist/admin-http/routes/users/delete-policy.d.ts +16 -0
- package/dist/admin-http/routes/users/delete-policy.js +24 -0
- package/dist/admin-http/routes/users/delete-role.d.ts +16 -0
- package/dist/admin-http/routes/users/delete-role.js +24 -0
- package/dist/admin-http/routes/users/delete.d.ts +35 -0
- package/dist/admin-http/routes/users/delete.js +35 -0
- package/dist/admin-http/routes/users/disable.d.ts +31 -0
- package/dist/admin-http/routes/users/disable.js +38 -0
- package/dist/admin-http/routes/users/enable.d.ts +32 -0
- package/dist/admin-http/routes/users/enable.js +45 -0
- package/dist/admin-http/routes/users/list-policies.d.ts +18 -0
- package/dist/admin-http/routes/users/list-policies.js +20 -0
- package/dist/admin-http/routes/users/list-policy-permissions.d.ts +28 -0
- package/dist/admin-http/routes/users/list-policy-permissions.js +30 -0
- package/dist/admin-http/routes/users/list-roles.d.ts +18 -0
- package/dist/admin-http/routes/users/list-roles.js +20 -0
- package/dist/admin-http/routes/users/list.d.ts +40 -0
- package/dist/admin-http/routes/users/list.js +82 -0
- package/dist/admin-http/routes/users/remove-policy-permission.d.ts +48 -0
- package/dist/admin-http/routes/users/remove-policy-permission.js +62 -0
- package/dist/admin-http/routes/users/reset-password.d.ts +33 -0
- package/dist/admin-http/routes/users/reset-password.js +52 -0
- package/dist/admin-http/routes/users/shared.d.ts +124 -0
- package/dist/admin-http/routes/users/shared.js +93 -0
- package/dist/admin-http/routes/users/update-policy.d.ts +25 -0
- package/dist/admin-http/routes/users/update-policy.js +30 -0
- package/dist/admin-http/routes/users/update-role.d.ts +23 -0
- package/dist/admin-http/routes/users/update-role.js +29 -0
- package/dist/admin-http/routes/users/update.d.ts +35 -0
- package/dist/admin-http/routes/users/update.js +78 -0
- package/dist/admin-http/routes/users/write-policy-permission.d.ts +31 -0
- package/dist/admin-http/routes/users/write-policy-permission.js +45 -0
- package/dist/core/ports.d.ts +22 -3
- package/dist/core/types.d.ts +17 -5
- package/dist/core/types.js +12 -0
- package/dist/identity/api-key-secret.d.ts +68 -0
- package/dist/identity/api-key-secret.js +229 -0
- package/dist/identity/api-key-service.d.ts +144 -0
- package/dist/identity/api-key-service.js +389 -0
- package/dist/identity/api-key-types.d.ts +79 -0
- package/dist/identity/api-key-types.js +2 -0
- package/dist/identity/boot-session-token.d.ts +18 -0
- package/dist/identity/boot-session-token.js +92 -0
- package/dist/identity/builtin-role-grants.d.ts +120 -0
- package/dist/identity/builtin-role-grants.js +88 -0
- package/dist/identity/delete-user-service.d.ts +195 -0
- package/dist/identity/delete-user-service.js +275 -0
- package/dist/identity/owner-reset-env.d.ts +37 -0
- package/dist/identity/owner-reset-env.js +38 -0
- package/dist/identity/permission-grants.d.ts +31 -0
- package/dist/identity/permission-grants.js +12 -0
- package/dist/identity/permission-list-tool.d.ts +35 -0
- package/dist/identity/permission-list-tool.js +47 -0
- package/dist/identity/repo.authentication.d.ts +57 -0
- package/dist/identity/repo.authentication.js +153 -0
- package/dist/identity/repo.authorization.d.ts +82 -0
- package/dist/identity/repo.authorization.js +203 -0
- package/dist/identity/repo.d.ts +87 -0
- package/dist/identity/repo.js +167 -0
- package/dist/identity/repo.memory.d.ts +31 -0
- package/dist/identity/repo.memory.js +37 -0
- package/dist/identity/role-manage-permission.d.ts +34 -0
- package/dist/identity/role-manage-permission.js +39 -0
- package/dist/identity/site-key-permission.d.ts +66 -0
- package/dist/identity/site-key-permission.js +92 -0
- package/dist/identity/sql/kernel-user-purge.d.ts +19 -0
- package/dist/identity/sql/kernel-user-purge.js +34 -0
- package/dist/identity/sql/kernel-user-trash-store.d.ts +15 -0
- package/dist/identity/sql/kernel-user-trash-store.js +41 -0
- package/dist/identity/sql/user-trash-adapter.d.ts +87 -0
- package/dist/identity/sql/user-trash-adapter.js +124 -0
- package/dist/identity/tool-registrations.d.ts +100 -0
- package/dist/identity/tool-registrations.js +257 -0
- package/dist/identity/user-manage-permission.d.ts +8 -0
- package/dist/identity/user-manage-permission.js +8 -0
- package/dist/identity/user-purge-types.d.ts +85 -0
- package/dist/identity/user-purge-types.js +17 -0
- package/dist/identity/user-purge.d.ts +69 -0
- package/dist/identity/user-purge.js +46 -0
- package/dist/identity/username-change-ports.d.ts +15 -0
- package/dist/identity/username-change-ports.js +22 -0
- package/dist/mail/site/capture-clear.d.ts +58 -0
- package/dist/mail/site/capture-clear.js +21 -0
- package/dist/mail/status/agent-tools.d.ts +65 -0
- package/dist/mail/status/agent-tools.js +22 -0
- package/dist/mail/status/delivery-agent-tools.d.ts +206 -0
- package/dist/mail/status/delivery-agent-tools.js +63 -0
- package/dist/mail/status/delivery-tool-registrations.d.ts +216 -0
- package/dist/mail/status/delivery-tool-registrations.js +110 -0
- package/dist/mail/status/domain-deps.d.ts +25 -0
- package/dist/mail/status/domain-deps.js +23 -0
- package/dist/mail/status/permissions.d.ts +43 -0
- package/dist/mail/status/permissions.js +45 -0
- package/dist/mail/status/provider-agent-tools.d.ts +38 -0
- package/dist/mail/status/provider-agent-tools.js +17 -0
- package/dist/mail/status/provider-operations.d.ts +166 -0
- package/dist/mail/status/provider-operations.js +121 -0
- package/dist/mail/status/provider-tool-registrations.d.ts +65 -0
- package/dist/mail/status/provider-tool-registrations.js +106 -0
- package/dist/mail/status/tool-registrations.d.ts +152 -0
- package/dist/mail/status/tool-registrations.js +112 -0
- package/dist/member-login/credentials.d.ts +40 -0
- package/dist/member-login/credentials.js +26 -0
- package/dist/member-login/link-service.d.ts +66 -0
- package/dist/member-login/link-service.js +141 -0
- package/dist/member-login/oidc-login.d.ts +132 -0
- package/dist/member-login/oidc-login.js +206 -0
- package/dist/member-login/oidc-request.d.ts +80 -0
- package/dist/member-login/oidc-request.js +86 -0
- package/dist/member-login/providers.d.ts +79 -0
- package/dist/member-login/providers.js +41 -0
- package/dist/member-login/ready-providers.d.ts +17 -0
- package/dist/member-login/ready-providers.js +11 -0
- package/dist/member-login/unlink-identity.d.ts +26 -0
- package/dist/member-login/unlink-identity.js +59 -0
- package/dist/members/access-resolver.d.ts +107 -0
- package/dist/members/access-resolver.js +231 -0
- package/dist/members/agent-tools.d.ts +14 -0
- package/dist/members/agent-tools.js +139 -0
- package/dist/members/auth-mail.d.ts +27 -0
- package/dist/members/auth-mail.js +21 -0
- package/dist/members/capability-card.d.ts +18 -0
- package/dist/members/capability-card.js +27 -0
- package/dist/members/consent-service.d.ts +115 -0
- package/dist/members/consent-service.js +179 -0
- package/dist/members/member-admin-writes.d.ts +73 -0
- package/dist/members/member-admin-writes.js +149 -0
- package/dist/members/member-challenge-request.d.ts +59 -0
- package/dist/members/member-challenge-request.js +145 -0
- package/dist/members/member-challenge.d.ts +37 -0
- package/dist/members/member-challenge.js +84 -0
- package/dist/members/member-credentials.d.ts +35 -0
- package/dist/members/member-credentials.js +57 -0
- package/dist/members/member-sign-in.d.ts +44 -0
- package/dist/members/member-sign-in.js +130 -0
- package/dist/members/member-validation.d.ts +5 -0
- package/dist/members/member-validation.js +13 -0
- package/dist/members/password-auth.d.ts +55 -0
- package/dist/members/password-auth.js +177 -0
- package/dist/members/ports.d.ts +455 -0
- package/dist/members/ports.js +21 -0
- package/dist/members/public-member-auth-response.d.ts +68 -0
- package/dist/members/public-member-auth-response.js +45 -0
- package/dist/members/public-member-response.d.ts +25 -0
- package/dist/members/public-member-response.js +15 -0
- package/dist/members/repo.d.ts +199 -0
- package/dist/members/repo.js +324 -0
- package/dist/members/repo.memory.d.ts +276 -0
- package/dist/members/repo.memory.js +395 -0
- package/dist/members/repo.rows.d.ts +153 -0
- package/dist/members/repo.rows.js +250 -0
- package/dist/members/repo.sessions.d.ts +80 -0
- package/dist/members/repo.sessions.js +166 -0
- package/dist/members/repo.sql.d.ts +9 -0
- package/dist/members/repo.sql.js +11 -0
- package/dist/members/subscriber-directory.d.ts +85 -0
- package/dist/members/subscriber-directory.js +70 -0
- package/dist/members/tool-registrations.d.ts +143 -0
- package/dist/members/tool-registrations.js +247 -0
- package/dist/members/trash-member.d.ts +24 -0
- package/dist/members/trash-member.js +24 -0
- package/dist/members/types.d.ts +321 -0
- package/dist/members/types.js +34 -0
- package/dist/members/write-service.d.ts +17 -0
- package/dist/members/write-service.js +15 -0
- package/dist/newsletter/agent-tools.d.ts +20 -0
- package/dist/newsletter/agent-tools.js +236 -0
- package/dist/newsletter/campaign-write-service.d.ts +92 -0
- package/dist/newsletter/campaign-write-service.js +190 -0
- package/dist/newsletter/campaign.d.ts +53 -0
- package/dist/newsletter/campaign.js +95 -0
- package/dist/newsletter/confirmation.d.ts +75 -0
- package/dist/newsletter/confirmation.js +142 -0
- package/dist/newsletter/data-module-manifest.d.ts +68 -0
- package/dist/newsletter/data-module-manifest.js +126 -0
- package/dist/newsletter/delivery/tool-registrations.d.ts +67 -0
- package/dist/newsletter/delivery/tool-registrations.js +229 -0
- package/dist/newsletter/errors.d.ts +93 -0
- package/dist/newsletter/errors.js +93 -0
- package/dist/newsletter/hooks.d.ts +59 -0
- package/dist/newsletter/hooks.js +49 -0
- package/dist/newsletter/http-error-responses.d.ts +17 -0
- package/dist/newsletter/http-error-responses.js +96 -0
- package/dist/newsletter/launch-gate.d.ts +62 -0
- package/dist/newsletter/launch-gate.js +29 -0
- package/dist/newsletter/lists.d.ts +60 -0
- package/dist/newsletter/lists.js +83 -0
- package/dist/newsletter/ports.d.ts +278 -0
- package/dist/newsletter/ports.js +2 -0
- package/dist/newsletter/repo-sends.d.ts +82 -0
- package/dist/newsletter/repo-sends.js +178 -0
- package/dist/newsletter/repo-subscribers.d.ts +82 -0
- package/dist/newsletter/repo-subscribers.js +193 -0
- package/dist/newsletter/repo.d.ts +61 -0
- package/dist/newsletter/repo.js +147 -0
- package/dist/newsletter/repo.memory.d.ts +201 -0
- package/dist/newsletter/repo.memory.js +250 -0
- package/dist/newsletter/repo.rows.d.ts +221 -0
- package/dist/newsletter/repo.rows.js +260 -0
- package/dist/newsletter/send-pipeline.d.ts +236 -0
- package/dist/newsletter/send-pipeline.js +514 -0
- package/dist/newsletter/subscriptions.d.ts +87 -0
- package/dist/newsletter/subscriptions.js +119 -0
- package/dist/newsletter/tool-registrations.d.ts +89 -0
- package/dist/newsletter/tool-registrations.deps.d.ts +9 -0
- package/dist/newsletter/tool-registrations.deps.js +9 -0
- package/dist/newsletter/tool-registrations.js +133 -0
- package/dist/newsletter/tool-registrations.read.d.ts +76 -0
- package/dist/newsletter/tool-registrations.read.js +140 -0
- package/dist/newsletter/tool-registrations.write.d.ts +54 -0
- package/dist/newsletter/tool-registrations.write.js +229 -0
- package/dist/newsletter/types.d.ts +279 -0
- package/dist/newsletter/types.js +23 -0
- package/dist/newsletter/unsubscribe.d.ts +41 -0
- package/dist/newsletter/unsubscribe.js +100 -0
- package/dist/project-keys/attached-vault.d.ts +23 -0
- package/dist/project-keys/attached-vault.js +65 -0
- package/dist/project-keys/create-vault.d.ts +17 -0
- package/dist/project-keys/create-vault.js +29 -0
- package/dist/project-keys/service.d.ts +133 -0
- package/dist/project-keys/service.js +128 -0
- package/dist/project-keys/site-references.d.ts +30 -0
- package/dist/project-keys/site-references.js +63 -0
- package/dist/project-keys/site-sealer.d.ts +28 -0
- package/dist/project-keys/site-sealer.js +64 -0
- package/dist/project-keys/sql/attachments.d.ts +33 -0
- package/dist/project-keys/sql/attachments.js +55 -0
- package/dist/project-keys/tools.d.ts +86 -0
- package/dist/project-keys/tools.js +66 -0
- package/dist/public-http/routes/mail/feedback.d.ts +44 -0
- package/dist/public-http/routes/mail/feedback.js +17 -0
- package/dist/public-http/routes/newsletter/confirm.d.ts +38 -0
- package/dist/public-http/routes/newsletter/confirm.js +33 -0
- package/dist/public-http/routes/newsletter/page.d.ts +29 -0
- package/dist/public-http/routes/newsletter/page.js +34 -0
- package/dist/public-http/routes/newsletter/unsubscribe.d.ts +33 -0
- package/dist/public-http/routes/newsletter/unsubscribe.js +35 -0
- package/dist/react/auth/Passkeys.d.ts +2 -34
- package/dist/react/auth/RecoveryCodesCard.d.ts +27 -0
- package/dist/react/auth/RecoveryCodesCard.hooks.d.ts +67 -0
- package/dist/react/auth/RecoveryCodesCard.hooks.js +38 -0
- package/dist/react/auth/RecoveryCodesCard.js +56 -0
- package/dist/react/auth/TotpSettings.d.ts +2 -23
- package/dist/react/auth/local-owner-signin.d.ts +40 -0
- package/dist/react/auth/local-owner-signin.js +25 -0
- package/dist/react/auth/owner-mfa-api.d.ts +10 -0
- package/dist/react/auth/owner-mfa-api.js +17 -0
- package/dist/react/auth/owner-passkey-api.d.ts +11 -0
- package/dist/react/auth/owner-passkey-api.js +17 -0
- package/dist/react/auth/owner-recovery-api.d.ts +51 -0
- package/dist/react/auth/owner-recovery-api.js +29 -0
- package/dist/react/auth/owner-request.d.ts +7 -0
- package/dist/react/auth/owner-request.js +2 -0
- package/dist/react/index.d.ts +10 -0
- package/dist/react/index.js +6 -0
- package/dist/react/mail/Email.d.ts +20 -0
- package/dist/react/mail/Email.js +143 -0
- package/dist/react/mail/EmailProviderTab.d.ts +34 -0
- package/dist/react/mail/EmailProviderTab.js +132 -0
- package/dist/react/mail/EmailSegments.d.ts +24 -0
- package/dist/react/mail/EmailSegments.js +15 -0
- package/dist/react/mail/EmailTemplateEditor.d.ts +146 -0
- package/dist/react/mail/EmailTemplateEditor.js +116 -0
- package/dist/react/mail/email-view.types.d.ts +236 -0
- package/dist/react/mail/email-view.types.js +2 -0
- package/dist/react/members/Members.d.ts +5 -3
- package/dist/react/members/Members.js +3 -3
- package/dist/react/members/api/members-api.d.ts +37 -0
- package/dist/react/members/api/members-api.js +16 -0
- package/dist/react/members/hooks/use-members.hooks.js +2 -1
- package/dist/react/members/members-i18n.d.ts +23 -0
- package/dist/react/members/members-i18n.js +25 -0
- package/dist/react/members/members-i18n.locales-a.d.ts +4 -0
- package/dist/react/members/members-i18n.locales-a.js +294 -0
- package/dist/react/members/members-i18n.locales-b.d.ts +4 -0
- package/dist/react/members/members-i18n.locales-b.js +265 -0
- package/dist/react/models.d.ts +1 -49
- package/dist/react/ports.d.ts +3 -143
- package/dist/react/roles/api/roles-api.d.ts +74 -0
- package/dist/react/roles/api/roles-api.js +22 -0
- package/dist/react/testing.js +18 -9
- package/dist/react/users/UsersPanel.d.ts +30 -0
- package/dist/react/users/UsersPanel.hooks.d.ts +8 -0
- package/dist/react/users/UsersPanel.hooks.js +9 -0
- package/dist/react/users/UsersPanel.js +9 -0
- package/dist/react/users/api/users-api.d.ts +65 -0
- package/dist/react/users/api/users-api.js +46 -0
- package/dist/react/users/hooks/use-localized-users.hooks.d.ts +43 -0
- package/dist/react/users/hooks/use-localized-users.hooks.js +15 -0
- package/dist/react/users/hooks/use-users-state.hooks.d.ts +18 -18
- package/dist/react/users/password-reset-notice.d.ts +8 -0
- package/dist/react/users/password-reset-notice.js +36 -0
- package/dist/server/admin-crud-service.d.ts +4 -10
- package/dist/server/admin-crud-service.js +20 -6
- package/dist/server/agent-tool-registrations.js +20 -5
- package/dist/server/agent-tools.js +16 -3
- package/dist/server/auth-challenge.d.ts +1 -1
- package/dist/server/auth-service.js +2 -1
- package/dist/server/grant-service.d.ts +1 -0
- package/dist/server/grant-service.js +7 -4
- package/dist/server/mfa/passkey-service.d.ts +2 -2
- package/dist/server/mfa/passkey-service.js +1 -1
- package/dist/server/mfa/service.js +6 -4
- package/dist/server/repo.memory.d.ts +30 -2
- package/dist/server/repo.memory.js +58 -4
- package/dist/server/seed.js +3 -3
- package/dist/server/sql/assignments.d.ts +90 -0
- package/dist/server/sql/assignments.js +128 -0
- package/dist/server/sql/index.d.ts +6 -0
- package/dist/server/sql/index.js +5 -0
- package/dist/server/sql/kernel.d.ts +9 -0
- package/dist/server/sql/kernel.js +2 -0
- package/dist/server/sql/mfa.d.ts +36 -0
- package/dist/server/sql/mfa.js +51 -0
- package/dist/server/sql/passkeys.d.ts +25 -0
- package/dist/server/sql/passkeys.js +33 -0
- package/dist/server/sql/recovery-codes.d.ts +22 -0
- package/dist/server/sql/recovery-codes.js +32 -0
- package/package.json +910 -12
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
import { transitionCampaignStatus } from "./campaign.js";
|
|
2
|
+
import { NewsletterCampaignNotEditableError, NewsletterCampaignNotFoundError, NewsletterLaunchGateBlockedError, NewsletterValidationError, } from "./errors.js";
|
|
3
|
+
import { evaluateLaunchGate } from "./launch-gate.js";
|
|
4
|
+
import { buildUnsubscribeLink } from "./unsubscribe.js";
|
|
5
|
+
const TEST_SEND_MIN = 1;
|
|
6
|
+
const TEST_SEND_MAX = 10;
|
|
7
|
+
export const SEND_BATCH_CLAIMED_EVENT = "newsletter.send.batch.claimed";
|
|
8
|
+
/**
|
|
9
|
+
* How long one run holds a send row while it dispatches it (2026-09-16). Must outlast one row's hooks + `mailer.send`
|
|
10
|
+
* + `recordResult` (the hosted mail adapter caps a call at 10s). A run that throws after leasing a row keeps the lease, so
|
|
11
|
+
* the lease must also expire before the batch event's LAST attempt, whichever attempt took it. The tightest case is a
|
|
12
|
+
* lease taken on attempt `MAX_OUTBOX_ATTEMPTS - 1`: the last attempt can follow after only
|
|
13
|
+
* computeOutboxBackoffMs({ attempts: MAX_OUTBOX_ATTEMPTS - 1 }, { random: () => 0 }) = 240s. A lease still live then fails that attempt, the
|
|
14
|
+
* outbox seals the event "failed", and the row stays "pending" forever. Hence 2 minutes, not the first draft's 5
|
|
15
|
+
* (review fix, 2026-09-16). `send-pipeline.test.ts` pins both bounds.
|
|
16
|
+
*/
|
|
17
|
+
export const NEWSLETTER_SEND_ROW_LEASE_MS = 2 * 60 * 1000;
|
|
18
|
+
/**
|
|
19
|
+
* Quota waits (2026-10-21, review email#4). A rate limit is back-pressure, not a failure, so it must never spend the
|
|
20
|
+
* outbox's failure budget: a batch of 20 against a provider's small (e.g. 2/s, burst-2) bucket defers on almost every other row, which
|
|
21
|
+
* used to fail the batch each time and exhaust `MAX_OUTBOX_ATTEMPTS` with recipients still pending. A short hint is
|
|
22
|
+
* waited out inline (each wait at most 2s, at most 20s per run: far inside the 60s outbox delivery timeout and the 2
|
|
23
|
+
* minute row lease); a longer one reschedules the deferred row and the rest as a fresh event, due no earlier than the
|
|
24
|
+
* hint and the deferred row's lease.
|
|
25
|
+
*/
|
|
26
|
+
export const NEWSLETTER_INLINE_DEFER_MAX_MS = 2_000;
|
|
27
|
+
export const NEWSLETTER_INLINE_DEFER_BUDGET_MS = 20_000;
|
|
28
|
+
/** Wait used when a rate-limited result carries no `retryAfterMs` hint. */
|
|
29
|
+
const DEFAULT_DEFER_MS = 1_000;
|
|
30
|
+
/** REQ-19/25 — only the pipeline (`authorizeSend`) may start a real send; compose/schedule-tier actors cannot (AC-25). */
|
|
31
|
+
export async function authorizeSend(required, _optional = {}) {
|
|
32
|
+
const { deps, input } = required;
|
|
33
|
+
return deps.campaignRepo.transaction({ fn: async () => {
|
|
34
|
+
const campaign = await deps.campaignRepo.findById({ workspaceId: input.workspaceId, id: input.campaignId });
|
|
35
|
+
if (!campaign)
|
|
36
|
+
throw new NewsletterCampaignNotFoundError(`campaign ${input.campaignId} was not found`);
|
|
37
|
+
// evaluateLaunchGate (T018) called EXACTLY ONCE, inside this transaction (INV-05).
|
|
38
|
+
const launchGateSnapshot = await evaluateLaunchGate({ deps: deps.launchGateDeps, workspaceId: input.workspaceId, isTestSend: false });
|
|
39
|
+
if (!launchGateSnapshot.met) {
|
|
40
|
+
throw new NewsletterLaunchGateBlockedError({ message: "the Launch Readiness Gate is not satisfied", unmetPreconditions: launchGateSnapshot.unmetPreconditions });
|
|
41
|
+
}
|
|
42
|
+
const decision = transitionCampaignStatus({ from: campaign.status, to: "sending", actorTier: "pipeline" });
|
|
43
|
+
if (!decision.allowed) {
|
|
44
|
+
throw new NewsletterCampaignNotEditableError({ message: decision.reason, currentStatus: campaign.status, attemptedAction: "send" });
|
|
45
|
+
}
|
|
46
|
+
const now = deps.clock.nowIso();
|
|
47
|
+
const updated = { ...campaign, status: "sending", sendStartedAt: now, updatedAt: now };
|
|
48
|
+
await deps.campaignRepo.saveCampaignRow(updated);
|
|
49
|
+
const revisions = await deps.campaignRepo.listRevisions({ workspaceId: input.workspaceId, campaignId: input.campaignId });
|
|
50
|
+
const seq = revisions.length > 0 ? Math.max(...revisions.map((r) => r.seq)) + 1 : 1;
|
|
51
|
+
await deps.campaignRepo.appendRevision({ campaignId: updated.id, workspaceId: updated.workspaceId, seq, state: updated, actorId: "system:send-pipeline", recordedAt: now });
|
|
52
|
+
return { campaign: updated, launchGateSnapshot };
|
|
53
|
+
} });
|
|
54
|
+
}
|
|
55
|
+
async function materializeAudience({ deps, input }) {
|
|
56
|
+
const subscribed = await deps.subscriptionRepo.listSubscribed({ workspaceId: input.workspaceId, listId: input.listId });
|
|
57
|
+
const contacts = await deps.subscriberDirectory.getContacts({
|
|
58
|
+
workspaceId: input.workspaceId,
|
|
59
|
+
subscriberIds: subscribed.map((s) => s.subscriberId),
|
|
60
|
+
});
|
|
61
|
+
const contactBySubscriberId = new Map(contacts.map((c) => [c.subscriberId, c]));
|
|
62
|
+
const now = deps.clock.nowIso();
|
|
63
|
+
const snapshotId = deps.ids.newId();
|
|
64
|
+
const snapshot = {
|
|
65
|
+
id: snapshotId,
|
|
66
|
+
workspaceId: input.workspaceId,
|
|
67
|
+
campaignId: input.campaignId,
|
|
68
|
+
listId: input.listId,
|
|
69
|
+
recipientCount: 0,
|
|
70
|
+
createdAt: now,
|
|
71
|
+
};
|
|
72
|
+
const sendRows = [];
|
|
73
|
+
for (const subscription of subscribed) {
|
|
74
|
+
const contact = contactBySubscriberId.get(subscription.subscriberId);
|
|
75
|
+
if (!contact || !contact.emailDeliverable)
|
|
76
|
+
continue; // Missing or undeliverable contacts are excluded.
|
|
77
|
+
sendRows.push({
|
|
78
|
+
id: deps.ids.newId(),
|
|
79
|
+
workspaceId: input.workspaceId,
|
|
80
|
+
campaignId: input.campaignId,
|
|
81
|
+
audienceSnapshotId: snapshotId,
|
|
82
|
+
subscriberId: subscription.subscriberId,
|
|
83
|
+
recipientEmail: contact.email,
|
|
84
|
+
status: "pending",
|
|
85
|
+
attempts: 0,
|
|
86
|
+
idempotencyKey: `newsletter:${input.campaignId}:${subscription.subscriberId}:${snapshotId}`,
|
|
87
|
+
providerMessageId: null,
|
|
88
|
+
lastError: null,
|
|
89
|
+
nextAttemptAt: null,
|
|
90
|
+
createdAt: now,
|
|
91
|
+
updatedAt: now,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
return { now, snapshotId, snapshot, sendRows };
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* REQ-16 — materialize `subscribed` subscriptions into 1 snapshot + N send rows. Idempotent by
|
|
98
|
+
* presence-check (INV-06/orchestrator.spec §6): a retry for a campaign that already has
|
|
99
|
+
* `audienceSnapshotId` set is a no-op returning the existing snapshot, never a second snapshot.
|
|
100
|
+
* Unresolvable subscribers are silently excluded (AC-22, EC-07) — never an error.
|
|
101
|
+
*/
|
|
102
|
+
export async function freezeAudience(required, _optional = {}) {
|
|
103
|
+
const { deps, input } = required;
|
|
104
|
+
const campaign = await deps.campaignRepo.findById({ workspaceId: input.workspaceId, id: input.campaignId });
|
|
105
|
+
if (!campaign)
|
|
106
|
+
throw new NewsletterCampaignNotFoundError(`campaign ${input.campaignId} was not found`);
|
|
107
|
+
if (campaign.audienceSnapshotId) {
|
|
108
|
+
const existing = await deps.audienceSnapshotRepo.findById({ workspaceId: input.workspaceId, id: campaign.audienceSnapshotId });
|
|
109
|
+
if (existing) {
|
|
110
|
+
// Paged by id so no audience size is silently cut off.
|
|
111
|
+
const sendIds = [];
|
|
112
|
+
for (let afterId;;) {
|
|
113
|
+
const rows = await deps.sendRepo.listByCampaign({ workspaceId: input.workspaceId, campaignId: input.campaignId, ...(afterId === undefined ? {} : { afterId }), limit: 10000 });
|
|
114
|
+
sendIds.push(...rows.map((r) => r.id));
|
|
115
|
+
const last = rows.at(-1);
|
|
116
|
+
if (rows.length < 10000 || last === undefined)
|
|
117
|
+
return { snapshot: existing, sendIds };
|
|
118
|
+
afterId = last.id;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const { now, snapshotId, snapshot, sendRows } = await materializeAudience({ deps, input });
|
|
123
|
+
const finalSnapshot = { ...snapshot, recipientCount: sendRows.length };
|
|
124
|
+
await deps.audienceSnapshotRepo.save(finalSnapshot);
|
|
125
|
+
if (sendRows.length > 0)
|
|
126
|
+
await deps.sendRepo.saveBatch({ rows: sendRows });
|
|
127
|
+
// Contact lookup can overlap a human pause. Attach the snapshot to the current row without
|
|
128
|
+
// restoring an earlier status; paused batches remain pending until an approved resume.
|
|
129
|
+
const updatedCampaign = await deps.campaignRepo.transaction({ fn: async () => {
|
|
130
|
+
const current = await deps.campaignRepo.findById({ workspaceId: input.workspaceId, id: input.campaignId });
|
|
131
|
+
if (!current)
|
|
132
|
+
throw new NewsletterCampaignNotFoundError(`campaign ${input.campaignId} was not found`);
|
|
133
|
+
const updated = { ...current, audienceSnapshotId: snapshotId, updatedAt: now };
|
|
134
|
+
await deps.campaignRepo.saveCampaignRow(updated);
|
|
135
|
+
return updated;
|
|
136
|
+
} });
|
|
137
|
+
const sendIds = sendRows.map((row) => row.id);
|
|
138
|
+
await enqueueSendBatches({ deps, campaign: updatedCampaign, audienceSnapshotId: snapshotId, sendIds });
|
|
139
|
+
return { snapshot: finalSnapshot, sendIds };
|
|
140
|
+
}
|
|
141
|
+
/** Queues existing ledger ids in the same bounded outbox batches for initial launch and resume.
|
|
142
|
+
* @complexity O(n) ids and O(n/20) outbox writes; no addresses are embedded in events. */
|
|
143
|
+
async function enqueueSendBatches(required) {
|
|
144
|
+
const { deps, campaign, audienceSnapshotId, sendIds } = required;
|
|
145
|
+
for (let i = 0; i < sendIds.length; i += 20) {
|
|
146
|
+
const job = { workspaceId: campaign.workspaceId, campaignId: campaign.id, audienceSnapshotId, sendIds: sendIds.slice(i, i + 20) };
|
|
147
|
+
const event = { id: deps.ids.newId(), name: SEND_BATCH_CLAIMED_EVENT, occurredAt: deps.clock.nowIso(), workspaceId: campaign.workspaceId, payload: job };
|
|
148
|
+
await deps.outbox.enqueue(event);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** `claimBatch` — delegates to the EXISTING generic `processOutbox` primitive, unmodified (W-003). */
|
|
152
|
+
export function claimBatch(required, optional = {}) {
|
|
153
|
+
const { deps } = required;
|
|
154
|
+
const { batchSize = 20 } = optional;
|
|
155
|
+
return deps.processOutbox({ outbox: deps.outbox, bus: deps.bus, clock: { nowMs: () => Date.parse(deps.clock.nowIso()) } }, { batchSize });
|
|
156
|
+
}
|
|
157
|
+
/** The `runHookChain` input for one row: both hook contexts plus the base message (REQ-17). @complexity O(1). */
|
|
158
|
+
function hookChainInput(required) {
|
|
159
|
+
const { row } = required;
|
|
160
|
+
return {
|
|
161
|
+
recipientFilterContext: {
|
|
162
|
+
workspaceId: row.workspaceId,
|
|
163
|
+
campaignId: required.campaignId,
|
|
164
|
+
listId: required.listId,
|
|
165
|
+
subscriberId: row.subscriberId,
|
|
166
|
+
recipientEmail: row.recipientEmail,
|
|
167
|
+
status: required.status,
|
|
168
|
+
},
|
|
169
|
+
beforeSendContext: { workspaceId: row.workspaceId, campaignId: required.campaignId, sendId: row.id, subscriberId: row.subscriberId },
|
|
170
|
+
message: {
|
|
171
|
+
workspaceId: row.workspaceId,
|
|
172
|
+
to: { email: row.recipientEmail },
|
|
173
|
+
from: { email: required.message.fromEmail, name: required.message.fromName },
|
|
174
|
+
replyTo: { email: required.message.replyTo },
|
|
175
|
+
subject: required.message.subject,
|
|
176
|
+
// Keys stay present even when undefined: in-process hooks can tell a missing key from an undefined one.
|
|
177
|
+
text: required.message.text,
|
|
178
|
+
html: required.message.html,
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* REQ-17/22/23 — recipient.filter -> beforeSend -> `MailerPort.send()`, in that fixed order
|
|
184
|
+
* (`hooks.ts`'s `runHookChain`). Never constructs/imports a concrete `MailerPort` (INV-08) — always
|
|
185
|
+
* receives `deps.mailer` as a call-time dependency.
|
|
186
|
+
*/
|
|
187
|
+
export async function dispatchRow(required, _optional = {}) {
|
|
188
|
+
const { deps, row } = required;
|
|
189
|
+
// REQ-10: crash-recovery / redelivery idempotency (INV-10, EC-04) — a row already terminal is
|
|
190
|
+
// never re-dispatched (the outbox's own redelivery must not double-send). Defense in depth
|
|
191
|
+
// (2026-09-16): `handleSendBatchClaimed` leases the row (`claimForDispatch`) before calling this,
|
|
192
|
+
// which is what actually stops overlapping runs.
|
|
193
|
+
if (row.status !== "pending") {
|
|
194
|
+
return { outcome: row.status === "delivered" || row.status === "sent" ? "sent" : "failed", providerMessageId: row.providerMessageId, error: row.lastError };
|
|
195
|
+
}
|
|
196
|
+
const hookResult = await deps.hooks.runHookChain(hookChainInput(required));
|
|
197
|
+
if (!hookResult.keep) {
|
|
198
|
+
return { outcome: "suppressed", providerMessageId: null, error: hookResult.reason };
|
|
199
|
+
}
|
|
200
|
+
const headers = await unsubscribeHeaders({ deps, row, listId: required.listId, campaignId: required.campaignId, consentRevisionId: required.consentRevisionId ?? null });
|
|
201
|
+
const result = await deps.mailer.send({ ...hookResult.message, headers: { ...hookResult.message.headers, ...headers } }, {
|
|
202
|
+
idempotencyKey: row.idempotencyKey,
|
|
203
|
+
workspaceId: row.workspaceId,
|
|
204
|
+
sourceContext: { module: "newsletter", ref: row.id },
|
|
205
|
+
// The bulk lane: suppression honours complaints, the provider's reserved transactional capacity
|
|
206
|
+
// is never consumed, and the policy refuses a message without the unsubscribe headers above.
|
|
207
|
+
purpose: "bulk",
|
|
208
|
+
});
|
|
209
|
+
if (result.ok) {
|
|
210
|
+
return { outcome: "sent", providerMessageId: result.providerMessageId, error: null };
|
|
211
|
+
}
|
|
212
|
+
// A rate limit is back-pressure, not a failure: the row stays pending for the retried batch. The
|
|
213
|
+
// shared code covers the local token bucket AND provider throttling (adapters normalize a 429 to it).
|
|
214
|
+
if (deps.isMailRateLimited({ result }))
|
|
215
|
+
return { outcome: "deferred", providerMessageId: null, error: result.message, retryAfterMs: result.retryAfterMs ?? DEFAULT_DEFER_MS };
|
|
216
|
+
return { outcome: "failed", providerMessageId: null, error: result.message };
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* RFC 8058 one-click headers for one recipient: the signed, origin-anchored link from
|
|
220
|
+
* `buildUnsubscribeLink` (REQ-30/INV-09), answered by the public `POST /newsletter/unsubscribe`.
|
|
221
|
+
* @complexity One key derivation and one origin read.
|
|
222
|
+
*/
|
|
223
|
+
async function unsubscribeHeaders(required) {
|
|
224
|
+
const { deps, row } = required;
|
|
225
|
+
if (!deps.unsubscribe)
|
|
226
|
+
return {};
|
|
227
|
+
const url = await buildUnsubscribeLink({ deps: deps.unsubscribe, claims: {
|
|
228
|
+
workspaceId: row.workspaceId, subscriberId: row.subscriberId, listId: required.listId, campaignId: required.campaignId, consentRevisionId: required.consentRevisionId,
|
|
229
|
+
} });
|
|
230
|
+
return { "List-Unsubscribe": `<${url}>`, "List-Unsubscribe-Post": "List-Unsubscribe=One-Click" };
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* REQ-24/INV-02 — records one send row's outcome with the atomic `recordOutcome` (2026-09-16; it was a read-then-write
|
|
234
|
+
* that let two concurrent results for the SAME row both pass the pending check and both count, H4), then counts it with
|
|
235
|
+
* the atomic `incrementCounter` (it was a read-modify-write of the campaign row, which lost concurrent counts and could
|
|
236
|
+
* write back a stale status over a pause). Still two writes, not one transaction: a crash between them leaves the row
|
|
237
|
+
* terminal and uncounted; counters stay rebuildable from the sends ledger.
|
|
238
|
+
*/
|
|
239
|
+
export async function recordResult(required, _optional = {}) {
|
|
240
|
+
const { deps, input } = required;
|
|
241
|
+
const now = deps.clock.nowIso();
|
|
242
|
+
const status = input.outcome === "sent" ? "delivered" : "failed";
|
|
243
|
+
const recorded = await deps.sendRepo.recordOutcome({
|
|
244
|
+
workspaceId: input.workspaceId,
|
|
245
|
+
id: input.sendId,
|
|
246
|
+
status,
|
|
247
|
+
providerMessageId: input.providerMessageId,
|
|
248
|
+
lastError: input.error,
|
|
249
|
+
updatedAt: now,
|
|
250
|
+
});
|
|
251
|
+
if (!recorded) {
|
|
252
|
+
// Missing, or another run already recorded it: never re-written or counted twice.
|
|
253
|
+
const row = await deps.sendRepo.findById({ workspaceId: input.workspaceId, id: input.sendId });
|
|
254
|
+
if (!row)
|
|
255
|
+
throw new Error(`send row ${input.sendId} was not found`);
|
|
256
|
+
return { sendRow: row };
|
|
257
|
+
}
|
|
258
|
+
await deps.campaignRepo.incrementCounter({ workspaceId: input.workspaceId, id: input.campaignId, counter: status, updatedAt: now });
|
|
259
|
+
return { sendRow: recorded };
|
|
260
|
+
}
|
|
261
|
+
/** REQ-18 — flips to `sent` when 0 pending remain. Naturally idempotent — safe to call redundantly. */
|
|
262
|
+
export async function completeIfDrained(required, _optional = {}) {
|
|
263
|
+
const { deps, input } = required;
|
|
264
|
+
const campaign = await deps.campaignRepo.findById({ workspaceId: input.workspaceId, id: input.campaignId });
|
|
265
|
+
if (!campaign)
|
|
266
|
+
return { campaign: null };
|
|
267
|
+
// The state machine is the single guard: for the pipeline tier, `-> sent` is allowed only from
|
|
268
|
+
// `sending`, so a draft/paused/already-sent campaign returns null here before any ledger read.
|
|
269
|
+
const decision = transitionCampaignStatus({ from: campaign.status, to: "sent", actorTier: "pipeline" });
|
|
270
|
+
if (!decision.allowed)
|
|
271
|
+
return { campaign: null };
|
|
272
|
+
const pending = await deps.sendRepo.countPendingByCampaign({ workspaceId: input.workspaceId, campaignId: input.campaignId });
|
|
273
|
+
if (pending > 0)
|
|
274
|
+
return { campaign: null };
|
|
275
|
+
const now = deps.clock.nowIso();
|
|
276
|
+
const updated = { ...campaign, status: "sent", updatedAt: now };
|
|
277
|
+
await deps.campaignRepo.saveCampaignRow(updated);
|
|
278
|
+
return { campaign: updated };
|
|
279
|
+
}
|
|
280
|
+
/** REQ-19 — admin-triggered pause/resume (`admin.newsletter.campaign.send` tier). `claimBatch` no-ops while paused (checked by the caller before invoking `claimBatch`). */
|
|
281
|
+
export async function pauseCampaign(required, _optional = {}) {
|
|
282
|
+
return transitionAndSave({ deps: required.deps, input: required.input, to: "paused" });
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Commits paused -> sending, then requeues only pending rows of the frozen audience.
|
|
286
|
+
* @returns The resumed campaign; requeueFailed means the transition succeeded but fan-out needs attention.
|
|
287
|
+
* @throws NewsletterCampaignNotFoundError or NewsletterCampaignNotEditableError before any transition.
|
|
288
|
+
* @complexity O(n) ledger reads and O(n/20) outbox writes, O(1000) auxiliary space.
|
|
289
|
+
*/
|
|
290
|
+
export async function resumeCampaign(required, _optional = {}) {
|
|
291
|
+
const result = await transitionAndSave({ deps: required.deps, input: required.input, to: "sending" });
|
|
292
|
+
// A paused batch may already have been acknowledged. Requeue its remaining ledger rows;
|
|
293
|
+
// the existing per-row leases and idempotency keys make overlapping/redelivered jobs safe.
|
|
294
|
+
if (!result.campaign.audienceSnapshotId)
|
|
295
|
+
return result;
|
|
296
|
+
try {
|
|
297
|
+
await requeuePendingSends({ deps: required.deps, campaign: result.campaign, audienceSnapshotId: result.campaign.audienceSnapshotId });
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
// Do not expose repository/provider diagnostics or turn an already-committed resume into a refusal.
|
|
301
|
+
required.deps.reportError({ message: "[newsletter] pending delivery requeue failed after resume; inspect the send log before retrying", error });
|
|
302
|
+
return { ...result, requeueFailed: true };
|
|
303
|
+
}
|
|
304
|
+
return result;
|
|
305
|
+
}
|
|
306
|
+
/** Requeues the current snapshot's pending rows in bounded pages. @complexity O(n) time, O(1000) space. */
|
|
307
|
+
async function requeuePendingSends(required) {
|
|
308
|
+
const { deps, campaign, audienceSnapshotId } = required;
|
|
309
|
+
let afterId;
|
|
310
|
+
for (;;) {
|
|
311
|
+
const rows = await deps.sendRepo.listByCampaign({ workspaceId: campaign.workspaceId, campaignId: campaign.id, ...(afterId === undefined ? {} : { afterId }), limit: 1000 });
|
|
312
|
+
const pendingIds = rows.filter((row) => row.status === "pending" && row.audienceSnapshotId === audienceSnapshotId).map((row) => row.id);
|
|
313
|
+
await enqueueSendBatches({ deps, campaign, audienceSnapshotId, sendIds: pendingIds });
|
|
314
|
+
const last = rows.at(-1);
|
|
315
|
+
if (rows.length < 1000 || last === undefined)
|
|
316
|
+
return;
|
|
317
|
+
afterId = last.id;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
async function transitionAndSave({ deps, input, to }, _options = {}) {
|
|
321
|
+
return deps.campaignRepo.transaction({ fn: async () => {
|
|
322
|
+
const campaign = await deps.campaignRepo.findById({ workspaceId: input.workspaceId, id: input.campaignId });
|
|
323
|
+
if (!campaign)
|
|
324
|
+
throw new NewsletterCampaignNotFoundError(`campaign ${input.campaignId} was not found`);
|
|
325
|
+
const decision = transitionCampaignStatus({ from: campaign.status, to, actorTier: "send" });
|
|
326
|
+
if (!decision.allowed)
|
|
327
|
+
throw new NewsletterCampaignNotEditableError({ message: decision.reason, currentStatus: campaign.status, attemptedAction: to });
|
|
328
|
+
const now = deps.clock.nowIso();
|
|
329
|
+
const updated = { ...campaign, status: to, updatedAt: now };
|
|
330
|
+
await deps.campaignRepo.saveCampaignRow(updated);
|
|
331
|
+
return { campaign: updated };
|
|
332
|
+
} });
|
|
333
|
+
}
|
|
334
|
+
/** SEND_TEST_CAMPAIGN — hits only the 1-10 given addresses, no snapshot/send-ledger rows created (AC-26). */
|
|
335
|
+
export async function sendTestCampaign(required) {
|
|
336
|
+
const { deps, input } = required;
|
|
337
|
+
if (input.testAddresses.length < TEST_SEND_MIN || input.testAddresses.length > TEST_SEND_MAX) {
|
|
338
|
+
throw new NewsletterValidationError({ message: `test-send address count must be between ${TEST_SEND_MIN} and ${TEST_SEND_MAX}`, field: "testAddresses", reason: "length" });
|
|
339
|
+
}
|
|
340
|
+
const campaign = await deps.campaignRepo.findById({ workspaceId: input.workspaceId, id: input.campaignId });
|
|
341
|
+
if (!campaign)
|
|
342
|
+
throw new NewsletterCampaignNotFoundError(`campaign ${input.campaignId} was not found`);
|
|
343
|
+
const launchGateSnapshot = await evaluateLaunchGate({ deps: deps.launchGateDeps, workspaceId: input.workspaceId, isTestSend: true });
|
|
344
|
+
if (!launchGateSnapshot.met) {
|
|
345
|
+
throw new NewsletterLaunchGateBlockedError({ message: "the Launch Readiness Gate is not satisfied for a test send", unmetPreconditions: launchGateSnapshot.unmetPreconditions });
|
|
346
|
+
}
|
|
347
|
+
const results = [];
|
|
348
|
+
for (const email of input.testAddresses) {
|
|
349
|
+
const result = await deps.mailer.send({
|
|
350
|
+
workspaceId: input.workspaceId,
|
|
351
|
+
to: { email },
|
|
352
|
+
from: { email: campaign.fromEmail, name: campaign.fromName },
|
|
353
|
+
replyTo: { email: campaign.replyTo },
|
|
354
|
+
subject: `[TEST] ${campaign.subject}`,
|
|
355
|
+
...(campaign.preheader == null ? {} : { text: campaign.preheader }),
|
|
356
|
+
}, { idempotencyKey: `newsletter:test:${campaign.id}:${email}:${deps.clock.nowIso()}`, workspaceId: input.workspaceId, sourceContext: { module: "newsletter", ref: campaign.id } });
|
|
357
|
+
results.push(result.ok ? { email, outcome: "sent", error: null } : { email, outcome: "failed", error: result.message, errorCode: result.errorCode });
|
|
358
|
+
}
|
|
359
|
+
return { results };
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Leases one send row for this run through `NewsletterSendRepoPort.claimForDispatch` (2026-09-16):
|
|
363
|
+
* the leased row, `"leased-elsewhere"` when another live run already holds its lease, or `null` when
|
|
364
|
+
* it is missing or already terminal (nothing left to dispatch).
|
|
365
|
+
*
|
|
366
|
+
* @complexity O(1) beyond the two repo calls it may make.
|
|
367
|
+
*/
|
|
368
|
+
async function claimSendRow(required) {
|
|
369
|
+
const { deps, workspaceId, sendId } = required;
|
|
370
|
+
const nowIso = deps.clock.nowIso();
|
|
371
|
+
const leaseUntilIso = new Date(Date.parse(nowIso) + NEWSLETTER_SEND_ROW_LEASE_MS).toISOString();
|
|
372
|
+
const leased = await deps.sendRepo.claimForDispatch({ workspaceId, id: sendId, nowIso, leaseUntilIso });
|
|
373
|
+
if (leased)
|
|
374
|
+
return leased;
|
|
375
|
+
const current = await deps.sendRepo.findById({ workspaceId, id: sendId });
|
|
376
|
+
return current?.status === "pending" ? "leased-elsewhere" : null;
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Dispatches one already-leased row through the fixed `recipient.filter` -> `beforeSend` -> `send()`
|
|
380
|
+
* -> `recordResult` chain. Extracted from `handleSendBatchClaimed` (2026-09-16) to keep that
|
|
381
|
+
* function's branching under the repo's complexity ceiling.
|
|
382
|
+
*
|
|
383
|
+
* @complexity O(1) beyond the hook chain, the mailer call, and `recordResult`.
|
|
384
|
+
*/
|
|
385
|
+
async function dispatchAndRecord(required) {
|
|
386
|
+
const { deps, job, campaign, row } = required;
|
|
387
|
+
const subscription = await deps.subscriptionRepo.findBySubscriberAndList({
|
|
388
|
+
workspaceId: job.workspaceId,
|
|
389
|
+
listId: campaign.listId,
|
|
390
|
+
subscriberId: row.subscriberId,
|
|
391
|
+
});
|
|
392
|
+
const status = subscription?.status ?? "unsubscribed";
|
|
393
|
+
const dispatchResult = await dispatchRow({
|
|
394
|
+
deps,
|
|
395
|
+
row,
|
|
396
|
+
campaignId: job.campaignId,
|
|
397
|
+
listId: campaign.listId,
|
|
398
|
+
status,
|
|
399
|
+
message: { subject: campaign.subject, ...(campaign.preheader == null ? {} : { text: campaign.preheader }), fromName: campaign.fromName, fromEmail: campaign.fromEmail, replyTo: campaign.replyTo },
|
|
400
|
+
consentRevisionId: subscription?.consentRevisionIdAtSubscribe ?? null,
|
|
401
|
+
});
|
|
402
|
+
// Rate limited: leave the row pending (its lease expires) so the retried batch sends it later.
|
|
403
|
+
if (dispatchResult.outcome === "deferred")
|
|
404
|
+
return { kind: "deferred", retryAfterMs: dispatchResult.retryAfterMs ?? DEFAULT_DEFER_MS };
|
|
405
|
+
// BUG FIX: `recordResult` is the ONLY place a send row's status ever leaves "pending" --
|
|
406
|
+
// `dispatchRow` above never writes. Previously this call was skipped for a "suppressed"
|
|
407
|
+
// outcome, which left the row at "pending" forever: `countPendingByCampaign` could never reach
|
|
408
|
+
// 0 for that campaign, so `completeIfDrained` (below) could never fire once any recipient was
|
|
409
|
+
// suppressed. `recordResult` already maps any non-"sent" outcome (including "suppressed") to a
|
|
410
|
+
// terminal "failed" status, so calling it unconditionally is sufficient -- no new status value
|
|
411
|
+
// is needed.
|
|
412
|
+
await recordResult({
|
|
413
|
+
deps,
|
|
414
|
+
input: {
|
|
415
|
+
workspaceId: job.workspaceId,
|
|
416
|
+
sendId: row.id,
|
|
417
|
+
campaignId: job.campaignId,
|
|
418
|
+
outcome: dispatchResult.outcome,
|
|
419
|
+
providerMessageId: dispatchResult.providerMessageId,
|
|
420
|
+
error: dispatchResult.error,
|
|
421
|
+
},
|
|
422
|
+
});
|
|
423
|
+
return { kind: "recorded" };
|
|
424
|
+
}
|
|
425
|
+
/** Whether the campaign is still `sending`; re-read because a pause can land during any provider call or wait. */
|
|
426
|
+
async function stillSending(required) {
|
|
427
|
+
const current = await required.deps.campaignRepo.findById({ workspaceId: required.job.workspaceId, id: required.job.campaignId });
|
|
428
|
+
return current?.status === "sending";
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Dispatches one leased row, waiting out short quota hints inline while this run's wait budget allows.
|
|
432
|
+
* @complexity O(waits) dispatch attempts, each bounded by {@link NEWSLETTER_INLINE_DEFER_BUDGET_MS} in total.
|
|
433
|
+
*/
|
|
434
|
+
async function dispatchWithinBudget(required) {
|
|
435
|
+
const { deps, budget } = required;
|
|
436
|
+
for (;;) {
|
|
437
|
+
const outcome = await dispatchAndRecord(required);
|
|
438
|
+
if (outcome.kind === "recorded")
|
|
439
|
+
return { kind: "next" };
|
|
440
|
+
const wait = outcome.retryAfterMs;
|
|
441
|
+
const fits = wait <= NEWSLETTER_INLINE_DEFER_MAX_MS && budget.waitedMs + wait <= NEWSLETTER_INLINE_DEFER_BUDGET_MS;
|
|
442
|
+
if (!deps.sleep || !fits)
|
|
443
|
+
return { kind: "deferred", retryAfterMs: wait, leaseUntilIso: required.row.nextAttemptAt ?? deps.clock.nowIso() };
|
|
444
|
+
budget.waitedMs += wait;
|
|
445
|
+
await deps.sleep({ ms: wait });
|
|
446
|
+
if (!(await stillSending(required)))
|
|
447
|
+
return { kind: "stopped" };
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
/** One recipient of a batch: pause check, lease, dispatch. @complexity O(1) repo calls beyond the dispatch. */
|
|
451
|
+
async function runBatchRow(required) {
|
|
452
|
+
const { deps, job, sendId } = required;
|
|
453
|
+
// Re-read before each recipient: pause can arrive while the prior provider request is in flight.
|
|
454
|
+
// Resume requeues pending rows, so acknowledging this stopped batch does not strand them.
|
|
455
|
+
if (!(await stillSending({ deps, job })))
|
|
456
|
+
return { kind: "stopped" };
|
|
457
|
+
const row = await claimSendRow({ deps, workspaceId: job.workspaceId, sendId });
|
|
458
|
+
if (row === "leased-elsewhere")
|
|
459
|
+
return { kind: "leased-elsewhere" };
|
|
460
|
+
if (!row)
|
|
461
|
+
return { kind: "next" };
|
|
462
|
+
return dispatchWithinBudget({ ...required, row });
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Reschedules the deferred row and every row after it as a fresh batch event, so a quota wait spends
|
|
466
|
+
* no outbox attempt. Both outbox adapters take an event's `occurredAt` as its first due time, so the
|
|
467
|
+
* continuation's `occurredAt` is when it may run: the later of the provider's hint and the deferred
|
|
468
|
+
* row's own lease (an earlier run would find that row leased and fail the batch).
|
|
469
|
+
*/
|
|
470
|
+
async function continueLater(required) {
|
|
471
|
+
const { deps, job, step } = required;
|
|
472
|
+
const hinted = new Date(Date.parse(deps.clock.nowIso()) + step.retryAfterMs).toISOString();
|
|
473
|
+
const dueIso = hinted > step.leaseUntilIso ? hinted : step.leaseUntilIso;
|
|
474
|
+
const event = { id: deps.ids.newId(), name: SEND_BATCH_CLAIMED_EVENT, occurredAt: dueIso, workspaceId: job.workspaceId, payload: { ...job, sendIds: required.sendIds } };
|
|
475
|
+
await deps.outbox.enqueue(event);
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* The bus-subscriber handler the host's composition root wires onto `newsletter.send.batch.claimed` (T040).
|
|
479
|
+
* Per-row fixed order: `recipient.filter` -> `beforeSend` -> `send()` -> `recordResult`; one row's
|
|
480
|
+
* failure never aborts sibling rows in the same batch.
|
|
481
|
+
*
|
|
482
|
+
* Each row is leased (`claimSendRow`) before any hook or send (2026-09-16), so overlapping runs of
|
|
483
|
+
* the same batch never send one row twice. A terminal or missing row is skipped without
|
|
484
|
+
* re-recording. A row leased by another live run is skipped here, and once every row in the job has
|
|
485
|
+
* been attempted, the whole batch fails so the outbox retries it after backoff — that is what lets a
|
|
486
|
+
* run that died mid-batch (holding a lease) release its rows once the lease expires, instead of
|
|
487
|
+
* stranding them.
|
|
488
|
+
*/
|
|
489
|
+
export async function handleSendBatchClaimed(required, _optional = {}) {
|
|
490
|
+
const { deps, job } = required;
|
|
491
|
+
const campaign = await deps.campaignRepo.findById({ workspaceId: job.workspaceId, id: job.campaignId });
|
|
492
|
+
if (!campaign)
|
|
493
|
+
return;
|
|
494
|
+
let leasedElsewhere = 0;
|
|
495
|
+
const budget = { waitedMs: 0 };
|
|
496
|
+
for (const [index, sendId] of job.sendIds.entries()) {
|
|
497
|
+
const step = await runBatchRow({ deps, job, campaign, sendId, budget });
|
|
498
|
+
if (step.kind === "stopped")
|
|
499
|
+
return;
|
|
500
|
+
if (step.kind === "leased-elsewhere")
|
|
501
|
+
leasedElsewhere += 1;
|
|
502
|
+
if (step.kind === "deferred") {
|
|
503
|
+
// The provider's bucket is empty: further rows would only be deferred too. Reschedule them
|
|
504
|
+
// (a quota wait, not a failure) instead of marking anyone failed or spending an outbox attempt.
|
|
505
|
+
await continueLater({ deps, job, sendIds: job.sendIds.slice(index), step });
|
|
506
|
+
break;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
await completeIfDrained({ deps, input: { workspaceId: job.workspaceId, campaignId: job.campaignId } });
|
|
510
|
+
if (leasedElsewhere > 0) {
|
|
511
|
+
throw new Error(`${leasedElsewhere} send row(s) of campaign ${job.campaignId} are leased by another run; the batch will be retried`);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
//# sourceMappingURL=send-pipeline.js.map
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file `subscriptions.ts` — subscription add/import chokepoint (ADR-PIPE-011 C-013, REQ-10/31).
|
|
3
|
+
*
|
|
4
|
+
* `importSubscriptions` MUST call the exact same per-row path `saveSubscription` uses — any
|
|
5
|
+
* divergence breaks REQ-31's "no separate unvalidated import path" guarantee (aggregate-risk note,
|
|
6
|
+
* ADR-PIPE-011 Contract Map). Never creates a new Members identity (REQ-10) — resolves via
|
|
7
|
+
* `SubscriberDirectoryPort`, read-only.
|
|
8
|
+
*/
|
|
9
|
+
import type { UUID } from "@jini-ai/core/primitives";
|
|
10
|
+
import { type ConfirmationDeps } from "./confirmation.js";
|
|
11
|
+
import type { MembersConsentCapability, NewsletterListRepoPort, NewsletterSubscriptionRepoPort, SubscriberDirectoryPort } from "./ports.js";
|
|
12
|
+
import type { SubscriptionRow } from "./types.js";
|
|
13
|
+
export interface SubscriptionsDeps {
|
|
14
|
+
subscriptionRepo: NewsletterSubscriptionRepoPort;
|
|
15
|
+
/** api.spec.md §6: `CREATE_SUBSCRIPTION`/`IMPORT_SUBSCRIPTIONS` -> `404 NEWSLETTER_LIST_NOT_FOUND` for an unknown `listId`. */
|
|
16
|
+
listRepo: NewsletterListRepoPort;
|
|
17
|
+
subscriberDirectory: SubscriberDirectoryPort;
|
|
18
|
+
confirmationDeps: ConfirmationDeps;
|
|
19
|
+
clock: {
|
|
20
|
+
nowIso(): string;
|
|
21
|
+
};
|
|
22
|
+
ids: {
|
|
23
|
+
newId(): string;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/** C-013 — resolve `subscriberId` via `SubscriberDirectoryPort`, create a `pending` subscription, trigger confirmation (AC-12/13). */
|
|
27
|
+
export declare function saveSubscription(required: {
|
|
28
|
+
deps: SubscriptionsDeps;
|
|
29
|
+
input: {
|
|
30
|
+
workspaceId: UUID;
|
|
31
|
+
listId: UUID;
|
|
32
|
+
subscriberId: UUID;
|
|
33
|
+
source: SubscriptionRow["source"];
|
|
34
|
+
};
|
|
35
|
+
}, _optional?: Record<string, never>): Promise<{
|
|
36
|
+
subscription: SubscriptionRow;
|
|
37
|
+
}>;
|
|
38
|
+
export interface UnsubscribeSubscriptionDeps {
|
|
39
|
+
subscriptionRepo: NewsletterSubscriptionRepoPort;
|
|
40
|
+
/** `null` = unbound — see `launch-gate.ts`'s file header on why this must never be stubbed to succeed. */
|
|
41
|
+
consentCapability: MembersConsentCapability | null;
|
|
42
|
+
clock: {
|
|
43
|
+
nowIso(): string;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* C-013 (admin-triggered removal half) — `REMOVE_SUBSCRIPTION` (api.spec.md §1/§5): flips a
|
|
48
|
+
* subscription to `unsubscribed` directly, by primary key, no signed token involved (unlike
|
|
49
|
+
* `unsubscribe.ts`'s `processUnsubscribe`, which verifies a `KeyringPort`-derived token and is the
|
|
50
|
+
* self-service, no-login public path). Same terminal shape and the same conditional
|
|
51
|
+
* `MembersConsentCapability.revoke()` side effect `processUnsubscribe` performs — an admin removing
|
|
52
|
+
* a subscription must revoke real consent state exactly as a self-service unsubscribe would, once a
|
|
53
|
+
* real binding exists. Idempotent: removing an already-`unsubscribed` subscription is a no-op
|
|
54
|
+
* success, not an error (mirrors `processUnsubscribe`'s EC-03 carve-out).
|
|
55
|
+
*/
|
|
56
|
+
export declare function unsubscribeSubscription(required: {
|
|
57
|
+
deps: UnsubscribeSubscriptionDeps;
|
|
58
|
+
input: {
|
|
59
|
+
workspaceId: UUID;
|
|
60
|
+
id: UUID;
|
|
61
|
+
};
|
|
62
|
+
}, _optional?: Record<string, never>): Promise<{
|
|
63
|
+
subscription: SubscriptionRow;
|
|
64
|
+
}>;
|
|
65
|
+
/**
|
|
66
|
+
* C-013 — import a batch (1-500) of subscriber ids, routing EVERY row through the identical
|
|
67
|
+
* `saveSubscription` path (AC-40/EC-08): a batch with one invalid id still creates the valid rows.
|
|
68
|
+
*/
|
|
69
|
+
export declare function importSubscriptions(required: {
|
|
70
|
+
deps: SubscriptionsDeps;
|
|
71
|
+
input: {
|
|
72
|
+
workspaceId: UUID;
|
|
73
|
+
listId: UUID;
|
|
74
|
+
subscribers: readonly {
|
|
75
|
+
subscriberId: UUID;
|
|
76
|
+
source: SubscriptionRow["source"];
|
|
77
|
+
}[];
|
|
78
|
+
};
|
|
79
|
+
}, _optional?: Record<string, never>): Promise<{
|
|
80
|
+
created: SubscriptionRow[];
|
|
81
|
+
failed: {
|
|
82
|
+
index: number;
|
|
83
|
+
code: string;
|
|
84
|
+
message: string;
|
|
85
|
+
}[];
|
|
86
|
+
}>;
|
|
87
|
+
//# sourceMappingURL=subscriptions.d.ts.map
|