@cosmicdrift/kumiko-samples 0.393.0 → 0.395.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/packages/bundled-features/package.json +15 -5
- package/packages/bundled-features/src/account-security/README.md +1 -1
- package/packages/bundled-features/src/account-security/changes.json +6 -0
- package/packages/bundled-features/src/account-security/feature.ts +9 -1
- package/packages/bundled-features/src/audit/event-classification.ts +1 -0
- package/packages/bundled-features/src/auth-email-password/changes.json +6 -0
- package/packages/bundled-features/src/auth-email-password/web/auth-client.ts +10 -52
- package/packages/bundled-features/src/auth-email-password/web/auth-gate.tsx +4 -4
- package/packages/bundled-features/src/auth-email-password/web/auth-redirect.ts +3 -12
- package/packages/bundled-features/src/auth-email-password/web/index.ts +2 -0
- package/packages/bundled-features/src/auth-email-password/web/login-failure.ts +54 -0
- package/packages/bundled-features/src/auth-email-password/web/login-url.ts +19 -0
- package/packages/bundled-features/src/auth-email-password/web/static-login.ts +183 -0
- package/packages/bundled-features/src/auth-mfa/web/mfa-client.ts +7 -63
- package/packages/bundled-features/src/billing-foundation/changes.json +30 -0
- package/packages/bundled-features/src/billing-foundation/checkout-core.ts +8 -16
- package/packages/bundled-features/src/billing-foundation/events.ts +2 -0
- package/packages/bundled-features/src/billing-foundation/feature.ts +1 -1
- package/packages/bundled-features/src/billing-foundation/handlers/create-checkout-session.write.ts +9 -2
- package/packages/bundled-features/src/billing-foundation/handlers/process-payment-event.write.ts +2 -0
- package/packages/bundled-features/src/billing-foundation/index.ts +2 -0
- package/packages/bundled-features/src/billing-foundation/one-off-checkout-gate.ts +44 -0
- package/packages/bundled-features/src/billing-foundation/one-off-customer.ts +17 -0
- package/packages/bundled-features/src/billing-foundation/plan-catalog.ts +1 -0
- package/packages/bundled-features/src/billing-foundation/types.ts +26 -0
- package/packages/bundled-features/src/billing-foundation/web/billing-plans-panel.tsx +1 -0
- package/packages/bundled-features/src/billing-foundation/web/plan-switch-confirm-dialog.tsx +8 -2
- package/packages/bundled-features/src/billing-foundation/web/plan-switch-recurring.ts +23 -0
- package/packages/bundled-features/src/billing-foundation/webhook-handler.ts +1 -0
- package/packages/bundled-features/src/cap-overview/changes.json +6 -0
- package/packages/bundled-features/src/cap-overview/handlers/caps-usage.query.ts +3 -3
- package/packages/bundled-features/src/cap-overview/types.ts +2 -0
- package/packages/bundled-features/src/compliance-profiles/web/compliance-profile-catalog.tsx +10 -1
- package/packages/bundled-features/src/file-foundation/read-file-ref-content.ts +12 -3
- package/packages/bundled-features/src/files/changes.json +18 -0
- package/packages/bundled-features/src/inbound-mail-foundation/account-health.ts +146 -0
- package/packages/bundled-features/src/inbound-mail-foundation/account-poll-schedule.ts +74 -0
- package/packages/bundled-features/src/inbound-mail-foundation/account-poll.ts +238 -0
- package/packages/bundled-features/src/inbound-mail-foundation/account-record.ts +2 -0
- package/packages/bundled-features/src/inbound-mail-foundation/account-wake.ts +21 -0
- package/packages/bundled-features/src/inbound-mail-foundation/changes.json +143 -0
- package/packages/bundled-features/src/inbound-mail-foundation/connect-callback-verify.ts +65 -0
- package/packages/bundled-features/src/inbound-mail-foundation/connect-route-responses.ts +26 -0
- package/packages/bundled-features/src/inbound-mail-foundation/connect-routes.ts +93 -62
- package/packages/bundled-features/src/inbound-mail-foundation/constants.ts +66 -3
- package/packages/bundled-features/src/inbound-mail-foundation/content-refetch.ts +137 -0
- package/packages/bundled-features/src/inbound-mail-foundation/describe-error.ts +5 -0
- package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +45 -2
- package/packages/bundled-features/src/inbound-mail-foundation/events.ts +69 -2
- package/packages/bundled-features/src/inbound-mail-foundation/feature.ts +133 -118
- package/packages/bundled-features/src/inbound-mail-foundation/file-storage-failure.ts +23 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/account-address.ts +79 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/acknowledge-quarantine.write.ts +55 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/attach-message-content.write.ts +184 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/connect-account.write.ts +137 -84
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/disconnect-account.write.ts +65 -45
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/ingest-message-prepare.ts +177 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/ingest-message-schema.ts +42 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/ingest-message.write.ts +79 -160
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/list-accounts.query.ts +93 -30
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/list-messages.query.ts +46 -30
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/list-quarantine.query.ts +106 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/mark-credential-stored.write.ts +47 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/message-content.query.ts +99 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/message-content.ts +229 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/message-detail.query.ts +34 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/reactivate-account.write.ts +129 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/retry-quarantined-message.write.ts +49 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/scope-visibility.ts +48 -9
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/set-trusted-authserv-id.write.ts +66 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/thread-rollup.ts +136 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/trusted-authserv-id.ts +4 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/update-account.write.ts +82 -60
- package/packages/bundled-features/src/inbound-mail-foundation/i18n.ts +80 -2
- package/packages/bundled-features/src/inbound-mail-foundation/inbound-oauth-flow.ts +48 -0
- package/packages/bundled-features/src/inbound-mail-foundation/index.ts +93 -15
- package/packages/bundled-features/src/inbound-mail-foundation/ingest-failures.ts +137 -0
- package/packages/bundled-features/src/inbound-mail-foundation/ingest-payload.ts +46 -0
- package/packages/bundled-features/src/inbound-mail-foundation/mail-roles.ts +132 -0
- package/packages/bundled-features/src/inbound-mail-foundation/normalize-inbound-message.ts +119 -0
- package/packages/bundled-features/src/inbound-mail-foundation/oauth-access-token.ts +26 -8
- package/packages/bundled-features/src/inbound-mail-foundation/outbound-attachment-access.ts +28 -0
- package/packages/bundled-features/src/inbound-mail-foundation/outbound-attachments.ts +111 -0
- package/packages/bundled-features/src/inbound-mail-foundation/outbound-mail.ts +19 -1
- package/packages/bundled-features/src/inbound-mail-foundation/probe.ts +2 -1
- package/packages/bundled-features/src/inbound-mail-foundation/projection.ts +33 -2
- package/packages/bundled-features/src/inbound-mail-foundation/provider-errors.ts +74 -0
- package/packages/bundled-features/src/inbound-mail-foundation/quarantine-entities.ts +56 -0
- package/packages/bundled-features/src/inbound-mail-foundation/quarantine-header-import.ts +63 -0
- package/packages/bundled-features/src/inbound-mail-foundation/quarantine-retry.ts +137 -0
- package/packages/bundled-features/src/inbound-mail-foundation/quarantine-screens.ts +66 -0
- package/packages/bundled-features/src/inbound-mail-foundation/quarantine.ts +72 -0
- package/packages/bundled-features/src/inbound-mail-foundation/retention-job.ts +78 -0
- package/packages/bundled-features/src/inbound-mail-foundation/retention-sweep.ts +43 -8
- package/packages/bundled-features/src/inbound-mail-foundation/screens.ts +238 -89
- package/packages/bundled-features/src/inbound-mail-foundation/send-from-account.ts +24 -5
- package/packages/bundled-features/src/inbound-mail-foundation/sender-auth.ts +215 -0
- package/packages/bundled-features/src/inbound-mail-foundation/supervisor-ingest.ts +311 -0
- package/packages/bundled-features/src/inbound-mail-foundation/sync-account-now.ts +61 -0
- package/packages/bundled-features/src/inbound-mail-foundation/sync-cursor-store.ts +79 -0
- package/packages/bundled-features/src/inbound-mail-foundation/syncable-accounts.ts +123 -0
- package/packages/bundled-features/src/inbound-mail-foundation/tenant-destroy-hook.ts +5 -1
- package/packages/bundled-features/src/inbound-mail-foundation/types.ts +76 -105
- package/packages/bundled-features/src/inbound-mail-foundation/wake-consumer.ts +33 -0
- package/packages/bundled-features/src/inbound-mail-foundation/watch-catch-up.ts +68 -0
- package/packages/bundled-features/src/inbound-mail-foundation/watch-lease.ts +124 -0
- package/packages/bundled-features/src/inbound-mail-foundation/watch-supervisor-types.ts +87 -0
- package/packages/bundled-features/src/inbound-mail-foundation/watch-supervisor.ts +143 -433
- package/packages/bundled-features/src/inbound-mail-foundation/web/client-plugin.ts +73 -0
- package/packages/bundled-features/src/inbound-mail-foundation/web/constants.ts +7 -0
- package/packages/bundled-features/src/inbound-mail-foundation/web/index.ts +5 -0
- package/packages/bundled-features/src/inbound-provider-imap/changes.json +36 -0
- package/packages/bundled-features/src/inbound-provider-imap/connect-mailbox.ts +124 -41
- package/packages/bundled-features/src/inbound-provider-imap/connect-my-mailbox.ts +45 -0
- package/packages/bundled-features/src/inbound-provider-imap/constants.ts +2 -1
- package/packages/bundled-features/src/inbound-provider-imap/credential-document.ts +2 -1
- package/packages/bundled-features/src/inbound-provider-imap/download-batch.ts +38 -0
- package/packages/bundled-features/src/inbound-provider-imap/feature.ts +61 -136
- package/packages/bundled-features/src/inbound-provider-imap/fetch-content.ts +84 -0
- package/packages/bundled-features/src/inbound-provider-imap/i18n.ts +9 -0
- package/packages/bundled-features/src/inbound-provider-imap/imap-client.ts +35 -84
- package/packages/bundled-features/src/inbound-provider-imap/index.ts +1 -2
- package/packages/bundled-features/src/inbound-provider-imap/mime-content.ts +85 -0
- package/packages/bundled-features/src/inbound-provider-imap/parse-message.ts +149 -0
- package/packages/bundled-features/src/inbound-provider-imap/reconnect-account.ts +4 -6
- package/packages/bundled-features/src/inbound-provider-imap/reconnect-mailbox.ts +75 -45
- package/packages/bundled-features/src/inbound-provider-imap/reconnect-prefill.query.ts +19 -8
- package/packages/bundled-features/src/inbound-provider-imap/screens.ts +203 -109
- package/packages/bundled-features/src/inbound-provider-imap/send-mail.ts +11 -2
- package/packages/bundled-features/src/inbound-provider-imap/sender-auth-headers.ts +36 -0
- package/packages/bundled-features/src/inbound-provider-imap/watch-mailbox.ts +109 -0
- package/packages/bundled-features/src/inbound-provider-inmemory/feature.ts +75 -3
- package/packages/bundled-features/src/inbound-provider-inmemory/index.ts +6 -0
- package/packages/bundled-features/src/jobs/changes.json +18 -0
- package/packages/bundled-features/src/managed-pages/changes.json +7 -0
- package/packages/bundled-features/src/managed-pages/constants.ts +7 -0
- package/packages/bundled-features/src/managed-pages/feature.ts +6 -4
- package/packages/bundled-features/src/managed-pages/handlers/by-slug.query.ts +2 -0
- package/packages/bundled-features/src/managed-pages/handlers/page-body-guard.ts +61 -0
- package/packages/bundled-features/src/managed-pages/handlers/page-body-issues.ts +26 -0
- package/packages/bundled-features/src/managed-pages/handlers/page-crud.ts +17 -10
- package/packages/bundled-features/src/managed-pages/handlers/set.write.ts +15 -4
- package/packages/bundled-features/src/managed-pages/render-page-body.ts +28 -0
- package/packages/bundled-features/src/managed-pages/screens/page-screens.ts +6 -2
- package/packages/bundled-features/src/managed-pages/seeding.ts +13 -2
- package/packages/bundled-features/src/managed-pages/table.ts +6 -2
- package/packages/bundled-features/src/managed-pages/web/client-plugin.tsx +6 -4
- package/packages/bundled-features/src/managed-pages/web/constants.ts +14 -0
- package/packages/bundled-features/src/managed-pages/web/i18n.ts +14 -0
- package/packages/bundled-features/src/managed-pages/web/lossy-markdown.ts +71 -0
- package/packages/bundled-features/src/managed-pages/web/markdown-to-document.ts +27 -0
- package/packages/bundled-features/src/managed-pages/web/page-body-section.tsx +73 -0
- package/packages/bundled-features/src/subscription-paddle/changes.json +15 -0
- package/packages/bundled-features/src/subscription-paddle/checkout-config.query.ts +17 -0
- package/packages/bundled-features/src/subscription-paddle/checkout-methods.ts +107 -0
- package/packages/bundled-features/src/subscription-paddle/checkout-page.ts +154 -0
- package/packages/bundled-features/src/subscription-paddle/client.ts +78 -0
- package/packages/bundled-features/src/subscription-paddle/constants.ts +32 -0
- package/packages/bundled-features/src/subscription-paddle/feature.ts +265 -0
- package/packages/bundled-features/src/subscription-paddle/index.ts +17 -0
- package/packages/bundled-features/src/subscription-paddle/plan-switch-methods.ts +135 -0
- package/packages/bundled-features/src/subscription-paddle/price-methods.ts +148 -0
- package/packages/bundled-features/src/subscription-paddle/runtime.ts +203 -0
- package/packages/bundled-features/src/subscription-paddle/subscription-state.ts +73 -0
- package/packages/bundled-features/src/subscription-paddle/tenant-binding.ts +34 -0
- package/packages/bundled-features/src/subscription-paddle/verify-webhook.ts +61 -0
- package/packages/bundled-features/src/subscription-paddle/webhook-events.ts +172 -0
- package/packages/bundled-features/src/template-resolver/README.md +2 -2
- package/packages/bundled-features/src/template-resolver/changes.json +20 -0
- package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +16 -16
- package/packages/bundled-features/src/template-resolver/feature.ts +14 -1
- package/packages/bundled-features/src/template-resolver/handlers/collection-item.query.ts +2 -2
- package/packages/bundled-features/src/template-resolver/handlers/collection-list.query.ts +6 -2
- package/packages/bundled-features/src/template-resolver/handlers/collection-set.write.ts +24 -6
- package/packages/bundled-features/src/template-resolver/handlers/collection-shared.ts +32 -0
- package/packages/bundled-features/src/template-resolver/handlers/set.write.ts +1 -0
- package/packages/bundled-features/src/template-resolver/handlers/shared.ts +9 -3
- package/packages/bundled-features/src/template-resolver/web/client-plugin.tsx +13 -480
- package/packages/bundled-features/src/template-resolver/web/collection-entry-create-form.tsx +105 -0
- package/packages/bundled-features/src/template-resolver/web/collection-lookup.ts +33 -0
- package/packages/bundled-features/src/template-resolver/web/constants.ts +3 -0
- package/packages/bundled-features/src/template-resolver/web/content-field.tsx +61 -0
- package/packages/bundled-features/src/template-resolver/web/content-tree-provider.ts +256 -0
- package/packages/bundled-features/src/template-resolver/web/document-reference-name.ts +12 -0
- package/packages/bundled-features/src/template-resolver/web/document-schema.ts +3 -11
- package/packages/bundled-features/src/template-resolver/web/i18n.ts +9 -2
- package/packages/bundled-features/src/template-resolver/web/legacy-variable-text.ts +30 -0
- package/packages/bundled-features/src/template-resolver/web/tenant-override.ts +7 -0
- package/packages/bundled-features/src/template-resolver/web/text-block-editor.tsx +92 -0
- package/packages/bundled-features/src/template-resolver/web/use-collection-editor-context.ts +42 -0
- package/packages/bundled-features/src/template-resolver/web/use-collection-entry-create.ts +92 -0
- package/packages/bundled-features/src/template-resolver/web/use-content-write.ts +81 -0
- package/packages/bundled-features/src/template-resolver/web/use-text-block-editor.ts +127 -0
- package/packages/bundled-features/src/tier-engine/changes.json +6 -0
- package/packages/bundled-features/src/tier-engine/feature.ts +9 -1
- package/packages/bundled-features/src/user-data-rights-defaults/hooks/file-ref.userdata-hook.ts +2 -1
- package/samples/apps/use-all-bundled/e2e-billing-gallery/gallery-constants.ts +4 -0
- package/samples/apps/use-all-bundled/e2e-billing-gallery/gallery-features.ts +11 -5
- package/samples/apps/use-all-bundled/e2e-billing-gallery/server.ts +2 -2
- package/samples/apps/use-all-bundled/feature-manifest.json +89 -40
- package/samples/apps/use-all-bundled/kumiko/migrations/0056_inbound-mail-quarantine-retry.rebuild.json +4 -0
- package/samples/apps/use-all-bundled/package.json +1 -0
- package/samples/apps/use-all-bundled/playwright.billing-docs.config.ts +15 -0
- package/samples/apps/use-all-bundled/src/app/cap-overview-caps.ts +16 -2
- package/samples/apps/use-all-bundled/src/app/cap-overview-labels-feature.ts +2 -1
- package/samples/apps/use-all-bundled/src/app/client.tsx +8 -1
- package/samples/apps/use-all-bundled/src/app/screens-feature.ts +14 -2
- package/samples/apps/use-all-bundled/src/app/seed.ts +17 -2
- package/samples/apps/use-all-bundled/src/run-config.ts +19 -11
- package/samples/recipes/cross-feature-events/README.md +10 -0
- package/samples/recipes/cross-feature-events/src/feature.ts +14 -0
- package/samples/recipes/dashboard-stats/README.md +8 -0
- package/samples/recipes/dashboard-stats/src/feature.ts +91 -1
- package/samples/recipes/env-composition/README.md +2 -2
- package/samples/recipes/env-composition/src/env.ts +2 -2
- package/samples/recipes/inbound-mail-triage/README.md +8 -0
- package/samples/recipes/pdf-audit-export/src/feature.ts +71 -48
- package/packages/bundled-features/src/subscription-dodo/changes.json +0 -14
- package/packages/bundled-features/src/subscription-dodo/client.ts +0 -45
- package/packages/bundled-features/src/subscription-dodo/constants.ts +0 -24
- package/packages/bundled-features/src/subscription-dodo/feature.ts +0 -207
- package/packages/bundled-features/src/subscription-dodo/index.ts +0 -16
- package/packages/bundled-features/src/subscription-dodo/plugin-methods.ts +0 -345
- package/packages/bundled-features/src/subscription-dodo/runtime.ts +0 -126
- package/packages/bundled-features/src/subscription-dodo/verify-webhook.ts +0 -262
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
[
|
|
2
|
-
{
|
|
3
|
-
"version": "0.388.0",
|
|
4
|
-
"type": "improvement",
|
|
5
|
-
"title": "New subscription provider for Dodo Payments",
|
|
6
|
-
"detail": "createSubscriptionDodoFeature() registers the \"dodo\" subscription provider (Merchant of Record). It verifies Standard Webhooks signatures, maps Dodo events to the foundation events, creates hosted checkouts and portal sessions, and switches plans in the app through previewPlanSwitch and applyPlanSwitch. Config keys are api-key, webhook-secret, billing-live and environment. Plan switches need a Product Collection in Dodo."
|
|
7
|
-
},
|
|
8
|
-
{
|
|
9
|
-
"version": "0.388.0",
|
|
10
|
-
"type": "improvement",
|
|
11
|
-
"title": "dodoEnvSchema declares the Dodo product id slots",
|
|
12
|
-
"detail": "dodoEnvSchema({ prices: [\"PRO\"] }) adds one optional DODO_PRODUCT_PRO slot per plan next to the API key and webhook key, and checks the pdt_ prefix. It is the counterpart to stripeEnvSchema."
|
|
13
|
-
}
|
|
14
|
-
]
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
// Thin JSON-over-fetch client for the Dodo Payments REST API. All traffic goes
|
|
2
|
-
// through the injected `send`, which defaults to the SSRF-safe egress in
|
|
3
|
-
// feature.ts and is replaced by a mock in tests.
|
|
4
|
-
|
|
5
|
-
import { parseJsonOrThrow } from "@cosmicdrift/kumiko-framework/utils";
|
|
6
|
-
|
|
7
|
-
export type DodoSend = (url: string, init?: RequestInit) => Promise<Response>;
|
|
8
|
-
|
|
9
|
-
export type DodoRequest = {
|
|
10
|
-
readonly method: "GET" | "POST" | "PATCH";
|
|
11
|
-
/** Path segments interpolated into it must already be encodeURIComponent'ed. */
|
|
12
|
-
readonly path: string;
|
|
13
|
-
readonly query?: Readonly<Record<string, string>>;
|
|
14
|
-
readonly body?: unknown;
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
export type DodoTarget = { readonly baseUrl: string; readonly apiKey: string };
|
|
18
|
-
|
|
19
|
-
// Never carries the response body or the key: both can hold customer data or secrets.
|
|
20
|
-
export class DodoHttpError extends Error {
|
|
21
|
-
readonly status: number;
|
|
22
|
-
constructor(request: DodoRequest, status: number) {
|
|
23
|
-
super(`subscription-dodo: ${request.method} ${request.path} failed with status ${status}`);
|
|
24
|
-
this.name = "DodoHttpError";
|
|
25
|
-
this.status = status;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export function createDodoHttp(send: DodoSend) {
|
|
30
|
-
return async (target: DodoTarget, request: DodoRequest): Promise<unknown> => {
|
|
31
|
-
const query = request.query ? `?${new URLSearchParams(request.query).toString()}` : "";
|
|
32
|
-
const response = await send(`${target.baseUrl}${request.path}${query}`, {
|
|
33
|
-
method: request.method,
|
|
34
|
-
headers: {
|
|
35
|
-
Authorization: `Bearer ${target.apiKey}`,
|
|
36
|
-
Accept: "application/json",
|
|
37
|
-
...(request.body !== undefined && { "Content-Type": "application/json" }),
|
|
38
|
-
},
|
|
39
|
-
...(request.body !== undefined && { body: JSON.stringify(request.body) }),
|
|
40
|
-
});
|
|
41
|
-
if (!response.ok) throw new DodoHttpError(request, response.status);
|
|
42
|
-
const text = await response.text();
|
|
43
|
-
return text.length === 0 ? null : parseJsonOrThrow<unknown>(text, "subscription-dodo response");
|
|
44
|
-
};
|
|
45
|
-
}
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
export const SUBSCRIPTION_DODO_FEATURE = "subscription-dodo" as const;
|
|
2
|
-
|
|
3
|
-
// Must match the path segment in the webhook URL `/api/subscription/webhook/dodo`.
|
|
4
|
-
export const DODO_PROVIDER_NAME = "dodo" as const;
|
|
5
|
-
|
|
6
|
-
// Config-key short-names, qualified to `subscription-dodo:config:<name>` at
|
|
7
|
-
// registry-build. api-key + webhook-secret are backing:"secrets".
|
|
8
|
-
export const DODO_API_KEY_CONFIG = "api-key" as const;
|
|
9
|
-
export const DODO_WEBHOOK_SECRET_CONFIG = "webhook-secret" as const;
|
|
10
|
-
export const DODO_BILLING_LIVE_CONFIG = "billingLive" as const;
|
|
11
|
-
export const DODO_ENVIRONMENT_CONFIG = "environment" as const;
|
|
12
|
-
|
|
13
|
-
// Separate from billingLive on purpose: staging runs Dodo's test API with
|
|
14
|
-
// billingLive on, production flips both.
|
|
15
|
-
export const DodoEnvironments = {
|
|
16
|
-
test: "test",
|
|
17
|
-
live: "live",
|
|
18
|
-
} as const;
|
|
19
|
-
export type DodoEnvironment = (typeof DodoEnvironments)[keyof typeof DodoEnvironments];
|
|
20
|
-
|
|
21
|
-
export const DODO_BASE_URLS: Readonly<Record<DodoEnvironment, string>> = {
|
|
22
|
-
test: "https://test.dodopayments.com",
|
|
23
|
-
live: "https://live.dodopayments.com",
|
|
24
|
-
};
|
|
@@ -1,207 +0,0 @@
|
|
|
1
|
-
// kumiko-feature-version: 1
|
|
2
|
-
//
|
|
3
|
-
// subscription-dodo — Dodo Payments (merchant of record) plugin for the
|
|
4
|
-
// billing-foundation plugin API. Credentials, the billing-live master switch and
|
|
5
|
-
// the API environment (test | live) are config keys resolved at call time, like
|
|
6
|
-
// subscription-stripe. `apiKey` / `webhookSecret` options are env→secrets bridge
|
|
7
|
-
// fallbacks.
|
|
8
|
-
|
|
9
|
-
import type { SubscriptionProviderPlugin } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
|
|
10
|
-
import {
|
|
11
|
-
access,
|
|
12
|
-
createSystemConfig,
|
|
13
|
-
defineFeature,
|
|
14
|
-
type FeatureDefinition,
|
|
15
|
-
} from "@cosmicdrift/kumiko-framework/engine";
|
|
16
|
-
import { type FeatureWithEnvSchema, featureWithEnvSchema } from "@cosmicdrift/kumiko-framework/env";
|
|
17
|
-
import { egress } from "@cosmicdrift/kumiko-framework/http";
|
|
18
|
-
import * as z from "zod";
|
|
19
|
-
import type { DodoSend } from "./client.ts";
|
|
20
|
-
import {
|
|
21
|
-
DODO_API_KEY_CONFIG,
|
|
22
|
-
DODO_BILLING_LIVE_CONFIG,
|
|
23
|
-
DODO_ENVIRONMENT_CONFIG,
|
|
24
|
-
DODO_PROVIDER_NAME,
|
|
25
|
-
DODO_WEBHOOK_SECRET_CONFIG,
|
|
26
|
-
DodoEnvironments,
|
|
27
|
-
SUBSCRIPTION_DODO_FEATURE,
|
|
28
|
-
} from "./constants.ts";
|
|
29
|
-
import {
|
|
30
|
-
createDodoApplyPlanSwitch,
|
|
31
|
-
createDodoCancelSubscription,
|
|
32
|
-
createDodoCheckoutSession,
|
|
33
|
-
createDodoPortalSession,
|
|
34
|
-
createDodoPreviewPlanSwitch,
|
|
35
|
-
createDodoPriceCache,
|
|
36
|
-
createDodoResumeSubscription,
|
|
37
|
-
createDodoRetrievePrices,
|
|
38
|
-
createDodoRetrieveSubscription,
|
|
39
|
-
} from "./plugin-methods.ts";
|
|
40
|
-
import { createDodoRuntimes } from "./runtime.ts";
|
|
41
|
-
import { verifyAndParseDodoWebhook } from "./verify-webhook.ts";
|
|
42
|
-
|
|
43
|
-
/** Bridge contract: both fields are optional fallbacks for the secrets store. */
|
|
44
|
-
export const subscriptionDodoEnvSchema = z.object({
|
|
45
|
-
DODO_PAYMENTS_API_KEY: z
|
|
46
|
-
.string()
|
|
47
|
-
.min(1)
|
|
48
|
-
.describe("Dodo Payments API key. Bridge-fallback — prefer the secret.")
|
|
49
|
-
.meta({ kumiko: { pulumi: { secret: true } } })
|
|
50
|
-
.optional(),
|
|
51
|
-
DODO_PAYMENTS_WEBHOOK_KEY: z
|
|
52
|
-
.string()
|
|
53
|
-
.min(1)
|
|
54
|
-
.describe(
|
|
55
|
-
"Dodo Payments webhook signing key (`whsec_...`). Bridge-fallback — prefer the secret.",
|
|
56
|
-
)
|
|
57
|
-
.meta({ kumiko: { pulumi: { secret: true } } })
|
|
58
|
-
.optional(),
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
type DodoProductEnvShape<TPrice extends string> = {
|
|
62
|
-
[Key in `DODO_PRODUCT_${TPrice}`]: z.ZodOptional<z.ZodString>;
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
/** Dodo env block plus one `DODO_PRODUCT_<NAME>` slot per plan product the app
|
|
66
|
-
* maps to a tier, e.g. `dodoEnvSchema({ prices: ["PRO", "TEAM"] })`.
|
|
67
|
-
* Shares its bridge fields with `subscriptionDodoEnvSchema`, so spreading
|
|
68
|
-
* it into `composeEnvSchema({ extend })` next to the mounted feature is no
|
|
69
|
-
* key clash. */
|
|
70
|
-
export function dodoEnvSchema<const TPrice extends string>(options: {
|
|
71
|
-
readonly prices: readonly TPrice[];
|
|
72
|
-
}) {
|
|
73
|
-
const productShape = Object.fromEntries(
|
|
74
|
-
options.prices.map((price) => [
|
|
75
|
-
`DODO_PRODUCT_${price}`,
|
|
76
|
-
z
|
|
77
|
-
.string()
|
|
78
|
-
.regex(/^pdt_/, `DODO_PRODUCT_${price} must start with 'pdt_'`)
|
|
79
|
-
.optional()
|
|
80
|
-
.describe(`Dodo Payments product id (\`pdt_...\`) of the ${price} plan.`),
|
|
81
|
-
]),
|
|
82
|
-
// @cast-boundary schema-walk — Object.fromEntries widens to an index signature; the entries are exactly one optional string per listed price.
|
|
83
|
-
) as DodoProductEnvShape<TPrice>;
|
|
84
|
-
return z.object({ ...subscriptionDodoEnvSchema.shape, ...productShape });
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export type SubscriptionDodoOptions = {
|
|
88
|
-
/** Bridge-fallback API key; the `api-key` config key wins when set. */
|
|
89
|
-
readonly apiKey?: string;
|
|
90
|
-
/** Bridge-fallback webhook secret; the `webhook-secret` config key wins when set. */
|
|
91
|
-
readonly webhookSecret?: string;
|
|
92
|
-
/** Dodo product id → app tier name. Products absent here drop the event. */
|
|
93
|
-
readonly priceToTier?: Readonly<Record<string, string>>;
|
|
94
|
-
/** Product ids a mode:"payment" checkout may target; empty = one-off checkouts closed. */
|
|
95
|
-
readonly oneOffPriceIds?: readonly string[];
|
|
96
|
-
/** HTTP transport; defaults to the SSRF-safe external egress. Test seam. */
|
|
97
|
-
readonly send?: DodoSend;
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
// Validated once at feature-build time so a typo fails app startup instead of
|
|
101
|
-
// silently widening or narrowing the one-off allowlist at request time.
|
|
102
|
-
function validateOneOffPriceIds(priceIds: readonly string[]): void {
|
|
103
|
-
const seen = new Set<string>();
|
|
104
|
-
for (const priceId of priceIds) {
|
|
105
|
-
if (priceId.length === 0) {
|
|
106
|
-
throw new Error("subscription-dodo: oneOffPriceIds must not contain an empty string");
|
|
107
|
-
}
|
|
108
|
-
if (seen.has(priceId)) {
|
|
109
|
-
throw new Error(`subscription-dodo: duplicate oneOffPriceIds entry "${priceId}"`);
|
|
110
|
-
}
|
|
111
|
-
seen.add(priceId);
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
export function createSubscriptionDodoFeature(
|
|
116
|
-
options: SubscriptionDodoOptions = {},
|
|
117
|
-
): FeatureWithEnvSchema<FeatureDefinition, typeof subscriptionDodoEnvSchema.shape> {
|
|
118
|
-
validateOneOffPriceIds(options.oneOffPriceIds ?? []);
|
|
119
|
-
const feature: FeatureDefinition = defineFeature(SUBSCRIPTION_DODO_FEATURE, (r) => {
|
|
120
|
-
r.describe(
|
|
121
|
-
'Dodo Payments provider plugin for `billing-foundation`. Dodo acts as merchant of record: it sells to the customer and issues invoice and VAT, so the consumer-protection texts for this provider come from `consumerProtection.providerTexts`. Reads its API key and webhook secret from system config keys with `backing:"secrets"` (envelope-encrypted in the secrets store under the system tenant), plus a `billingLive` master switch and an `environment` key (test | live). `environment` is its own key because Dodo serves test and live mode from different API hosts and a live key must never hit the test host or the other way round; `billingLive` only decides whether checkouts are offered at all. All four are runtime config, so keys rotate and prod goes live without a redeploy, and the `mask` on each derives the sysadmin settings screen and nav. Mount via `createSubscriptionDodoFeature({ priceToTier })`; the optional `apiKey`/`webhookSecret` options are env to secrets bridge fallbacks (`DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY`). The plugin always mounts; `createCheckoutSession` throws `feature_disabled` unless `billingLive` is true. Webhooks arrive at `/api/subscription/webhook/dodo` and are verified per the Standard Webhooks spec (HMAC-SHA256 over id, timestamp and the raw body, 5 minute tolerance); events for products outside `priceToTier` or without tenant metadata are dropped. Implements hosted checkout, customer portal, cancel and resume, `retrievePrices` (10-minute TTL cache), `retrieveSubscription` for the sync job, and an in-app plan switch: `previewPlanSwitch` shows the proration before the customer confirms, `applyPlanSwitch` changes the plan without a hosted page and waits for the `plan_changed` webhook to move the tier. A plan switch in Dodo requires all plan products to belong to one Product Collection.',
|
|
122
|
-
);
|
|
123
|
-
r.uiHints({
|
|
124
|
-
displayLabel: "Billing · Dodo Payments",
|
|
125
|
-
category: "billing",
|
|
126
|
-
recommended: false,
|
|
127
|
-
});
|
|
128
|
-
r.requires({ features: ["billing-foundation"] });
|
|
129
|
-
r.requires({ features: ["config"] });
|
|
130
|
-
r.requires({ features: ["secrets"] });
|
|
131
|
-
r.envSchema(subscriptionDodoEnvSchema);
|
|
132
|
-
|
|
133
|
-
const configKeys = r.config({
|
|
134
|
-
keys: {
|
|
135
|
-
[DODO_API_KEY_CONFIG]: createSystemConfig("text", {
|
|
136
|
-
backing: "secrets",
|
|
137
|
-
write: access.systemAdmin,
|
|
138
|
-
read: access.admin,
|
|
139
|
-
mask: { title: "subscription-dodo.api-key", icon: "key", order: 1 },
|
|
140
|
-
}),
|
|
141
|
-
[DODO_WEBHOOK_SECRET_CONFIG]: createSystemConfig("text", {
|
|
142
|
-
backing: "secrets",
|
|
143
|
-
write: access.systemAdmin,
|
|
144
|
-
read: access.admin,
|
|
145
|
-
mask: { title: "subscription-dodo.webhook-secret", icon: "shield", order: 2 },
|
|
146
|
-
}),
|
|
147
|
-
[DODO_ENVIRONMENT_CONFIG]: createSystemConfig("select", {
|
|
148
|
-
default: DodoEnvironments.test,
|
|
149
|
-
options: [DodoEnvironments.test, DodoEnvironments.live],
|
|
150
|
-
write: access.systemAdmin,
|
|
151
|
-
read: access.admin,
|
|
152
|
-
mask: { title: "subscription-dodo.environment", icon: "server", order: 3 },
|
|
153
|
-
}),
|
|
154
|
-
[DODO_BILLING_LIVE_CONFIG]: createSystemConfig("boolean", {
|
|
155
|
-
default: false,
|
|
156
|
-
write: access.privileged,
|
|
157
|
-
read: access.admin,
|
|
158
|
-
mask: { title: "subscription-dodo.billing-live", icon: "rocket", order: 4 },
|
|
159
|
-
}),
|
|
160
|
-
},
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
r.translations({
|
|
164
|
-
keys: {
|
|
165
|
-
"subscription-dodo.api-key": { en: "Dodo Payments API key" },
|
|
166
|
-
"subscription-dodo.webhook-secret": { en: "Dodo Payments webhook secret" },
|
|
167
|
-
"subscription-dodo.environment": { en: "Dodo Payments environment" },
|
|
168
|
-
"subscription-dodo.billing-live": { en: "Live billing" },
|
|
169
|
-
"subscription-dodo.settings": { en: "Dodo Payments" },
|
|
170
|
-
"screen:subscription-dodo-system.title": { en: "Dodo Payments" },
|
|
171
|
-
},
|
|
172
|
-
});
|
|
173
|
-
|
|
174
|
-
const priceToTier = options.priceToTier ?? {};
|
|
175
|
-
const runtimes = createDodoRuntimes({
|
|
176
|
-
apiKeyHandle: configKeys[DODO_API_KEY_CONFIG],
|
|
177
|
-
webhookSecretHandle: configKeys[DODO_WEBHOOK_SECRET_CONFIG],
|
|
178
|
-
billingLiveHandle: configKeys[DODO_BILLING_LIVE_CONFIG],
|
|
179
|
-
environmentHandle: configKeys[DODO_ENVIRONMENT_CONFIG],
|
|
180
|
-
send: options.send ?? egress({ kind: "external" }),
|
|
181
|
-
fallback: {
|
|
182
|
-
...(options.apiKey !== undefined && { apiKey: options.apiKey }),
|
|
183
|
-
...(options.webhookSecret !== undefined && { webhookSecret: options.webhookSecret }),
|
|
184
|
-
},
|
|
185
|
-
});
|
|
186
|
-
|
|
187
|
-
const plugin: SubscriptionProviderPlugin = {
|
|
188
|
-
displayName: "Dodo Payments",
|
|
189
|
-
verifyAndParseWebhook: verifyAndParseDodoWebhook(runtimes.webhook, { priceToTier }),
|
|
190
|
-
createCheckoutSession: createDodoCheckoutSession(runtimes.ctx),
|
|
191
|
-
createPortalSession: createDodoPortalSession(runtimes.ctx),
|
|
192
|
-
cancelSubscription: createDodoCancelSubscription(runtimes.ctx),
|
|
193
|
-
resumeSubscription: createDodoResumeSubscription(runtimes.ctx),
|
|
194
|
-
priceToTier,
|
|
195
|
-
oneOffPriceIds: options.oneOffPriceIds ?? [],
|
|
196
|
-
isBillingEnabled: runtimes.ctx.isBillingEnabled,
|
|
197
|
-
retrievePrices: createDodoRetrievePrices(runtimes.ctx, createDodoPriceCache()),
|
|
198
|
-
retrieveSubscription: createDodoRetrieveSubscription(runtimes.ctx, { priceToTier }),
|
|
199
|
-
previewPlanSwitch: createDodoPreviewPlanSwitch(runtimes.ctx),
|
|
200
|
-
applyPlanSwitch: createDodoApplyPlanSwitch(runtimes.ctx),
|
|
201
|
-
};
|
|
202
|
-
r.useExtension("subscriptionProvider", DODO_PROVIDER_NAME, plugin);
|
|
203
|
-
|
|
204
|
-
return { configKeys };
|
|
205
|
-
});
|
|
206
|
-
return featureWithEnvSchema(feature, subscriptionDodoEnvSchema);
|
|
207
|
-
}
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
// Public API of the subscription-dodo bundled feature. The webhook verifier,
|
|
2
|
-
// client and plugin methods are internal to feature.ts.
|
|
3
|
-
|
|
4
|
-
export {
|
|
5
|
-
DODO_BASE_URLS,
|
|
6
|
-
DODO_PROVIDER_NAME,
|
|
7
|
-
type DodoEnvironment,
|
|
8
|
-
DodoEnvironments,
|
|
9
|
-
SUBSCRIPTION_DODO_FEATURE,
|
|
10
|
-
} from "./constants.ts";
|
|
11
|
-
export {
|
|
12
|
-
createSubscriptionDodoFeature,
|
|
13
|
-
dodoEnvSchema,
|
|
14
|
-
type SubscriptionDodoOptions,
|
|
15
|
-
subscriptionDodoEnvSchema,
|
|
16
|
-
} from "./feature.ts";
|
|
@@ -1,345 +0,0 @@
|
|
|
1
|
-
// Dodo Payments plugin methods for the post-tenant phase. Option shapes are
|
|
2
|
-
// derived from the plugin contract so a contract change fails at compile time.
|
|
3
|
-
// Every response is validated with Zod; every non-2xx throws a DodoHttpError.
|
|
4
|
-
|
|
5
|
-
import {
|
|
6
|
-
KNOWN_RECURRING_INTERVALS,
|
|
7
|
-
type PlanSwitchPreview,
|
|
8
|
-
type ProviderPrice,
|
|
9
|
-
type ProviderSubscriptionSnapshot,
|
|
10
|
-
SubscriptionCancelTimings,
|
|
11
|
-
type SubscriptionProviderPlugin,
|
|
12
|
-
} from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
|
|
13
|
-
import type { HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
|
|
14
|
-
import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
|
|
15
|
-
import * as z from "zod";
|
|
16
|
-
import { DodoHttpError } from "./client.ts";
|
|
17
|
-
import type { DodoCtxRuntime } from "./runtime.ts";
|
|
18
|
-
import { dodoSubscriptionSchema, mapDodoSubscriptionState } from "./verify-webhook.ts";
|
|
19
|
-
|
|
20
|
-
type PluginMethod<TName extends keyof SubscriptionProviderPlugin> = NonNullable<
|
|
21
|
-
SubscriptionProviderPlugin[TName]
|
|
22
|
-
>;
|
|
23
|
-
|
|
24
|
-
const NOT_FOUND = 404;
|
|
25
|
-
|
|
26
|
-
function subscriptionPath(providerSubscriptionId: string): string {
|
|
27
|
-
return `/subscriptions/${encodeURIComponent(providerSubscriptionId)}`;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function forcedLanguage(locale: string): string {
|
|
31
|
-
return (locale.split(/[-_]/)[0] ?? locale).toLowerCase();
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// =============================================================================
|
|
35
|
-
// Checkout + portal + cancel/resume
|
|
36
|
-
// =============================================================================
|
|
37
|
-
|
|
38
|
-
const checkoutResponseSchema = z.object({
|
|
39
|
-
session_id: z.string(),
|
|
40
|
-
checkout_url: z.string().nullable(),
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
export function createDodoCheckoutSession(
|
|
44
|
-
runtime: DodoCtxRuntime,
|
|
45
|
-
): PluginMethod<"createCheckoutSession"> {
|
|
46
|
-
return async (ctx, options) => {
|
|
47
|
-
// No Dodo session may be created while billing is not live.
|
|
48
|
-
await runtime.assertBillingLive(ctx);
|
|
49
|
-
const response = checkoutResponseSchema.parse(
|
|
50
|
-
await runtime.call(ctx, {
|
|
51
|
-
method: "POST",
|
|
52
|
-
path: "/checkouts",
|
|
53
|
-
body: {
|
|
54
|
-
product_cart: [{ product_id: options.priceId, quantity: 1 }],
|
|
55
|
-
...(options.providerCustomerId && {
|
|
56
|
-
customer: { customer_id: options.providerCustomerId },
|
|
57
|
-
}),
|
|
58
|
-
return_url: options.successUrl,
|
|
59
|
-
cancel_url: options.cancelUrl,
|
|
60
|
-
metadata: {
|
|
61
|
-
tenantId: options.tenantId,
|
|
62
|
-
...(options.consentId && { consentId: options.consentId }),
|
|
63
|
-
},
|
|
64
|
-
...(options.locale && {
|
|
65
|
-
customization: { force_language: forcedLanguage(options.locale) },
|
|
66
|
-
}),
|
|
67
|
-
},
|
|
68
|
-
}),
|
|
69
|
-
);
|
|
70
|
-
if (!response.checkout_url) {
|
|
71
|
-
throw new Error("subscription-dodo: checkout session was created without a checkout_url");
|
|
72
|
-
}
|
|
73
|
-
return { url: response.checkout_url };
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
const portalResponseSchema = z.object({ link: z.string() });
|
|
78
|
-
|
|
79
|
-
export function createDodoPortalSession(
|
|
80
|
-
runtime: DodoCtxRuntime,
|
|
81
|
-
): PluginMethod<"createPortalSession"> {
|
|
82
|
-
return async (ctx, options) => {
|
|
83
|
-
const response = portalResponseSchema.parse(
|
|
84
|
-
await runtime.call(ctx, {
|
|
85
|
-
method: "POST",
|
|
86
|
-
path: `/customers/${encodeURIComponent(options.providerCustomerId)}/customer-portal/session`,
|
|
87
|
-
query: { return_url: options.returnUrl },
|
|
88
|
-
}),
|
|
89
|
-
);
|
|
90
|
-
return { url: response.link };
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
export function createDodoCancelSubscription(
|
|
95
|
-
runtime: DodoCtxRuntime,
|
|
96
|
-
): PluginMethod<"cancelSubscription"> {
|
|
97
|
-
return async (ctx, options) => {
|
|
98
|
-
await runtime.call(ctx, {
|
|
99
|
-
method: "PATCH",
|
|
100
|
-
path: subscriptionPath(options.providerSubscriptionId),
|
|
101
|
-
body:
|
|
102
|
-
options.when === SubscriptionCancelTimings.periodEnd
|
|
103
|
-
? { cancel_at_next_billing_date: true }
|
|
104
|
-
: { status: "cancelled" },
|
|
105
|
-
});
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
export function createDodoResumeSubscription(
|
|
110
|
-
runtime: DodoCtxRuntime,
|
|
111
|
-
): PluginMethod<"resumeSubscription"> {
|
|
112
|
-
return async (ctx, options) => {
|
|
113
|
-
await runtime.call(ctx, {
|
|
114
|
-
method: "PATCH",
|
|
115
|
-
path: subscriptionPath(options.providerSubscriptionId),
|
|
116
|
-
body: { cancel_at_next_billing_date: false },
|
|
117
|
-
});
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// =============================================================================
|
|
122
|
-
// Prices
|
|
123
|
-
// =============================================================================
|
|
124
|
-
|
|
125
|
-
const productSchema = z.object({
|
|
126
|
-
product_id: z.string(),
|
|
127
|
-
price: z.discriminatedUnion("type", [
|
|
128
|
-
z.object({
|
|
129
|
-
type: z.literal("recurring_price"),
|
|
130
|
-
price: z.number(),
|
|
131
|
-
currency: z.string(),
|
|
132
|
-
payment_frequency_interval: z.string(),
|
|
133
|
-
payment_frequency_count: z.number(),
|
|
134
|
-
}),
|
|
135
|
-
z.object({
|
|
136
|
-
type: z.literal("one_time_price"),
|
|
137
|
-
price: z.number(),
|
|
138
|
-
currency: z.string(),
|
|
139
|
-
}),
|
|
140
|
-
z.object({ type: z.literal("usage_based_price") }),
|
|
141
|
-
]),
|
|
142
|
-
// nullish: an older product without metadata must not fail the whole price lookup.
|
|
143
|
-
metadata: z.record(z.string(), z.string()).nullish(),
|
|
144
|
-
});
|
|
145
|
-
type DodoProduct = z.infer<typeof productSchema>;
|
|
146
|
-
|
|
147
|
-
function mapDodoProduct(product: DodoProduct): ProviderPrice | null {
|
|
148
|
-
const { price } = product;
|
|
149
|
-
if (price.type === "usage_based_price") return null;
|
|
150
|
-
const base = {
|
|
151
|
-
priceId: product.product_id,
|
|
152
|
-
unitAmount: price.price,
|
|
153
|
-
currency: price.currency.toLowerCase(),
|
|
154
|
-
active: true,
|
|
155
|
-
metadata: product.metadata ?? {},
|
|
156
|
-
};
|
|
157
|
-
if (price.type === "one_time_price") return { ...base, interval: null, intervalCount: 1 };
|
|
158
|
-
const rawInterval = price.payment_frequency_interval.toLowerCase();
|
|
159
|
-
const interval = KNOWN_RECURRING_INTERVALS.find((known) => known === rawInterval) ?? null;
|
|
160
|
-
return {
|
|
161
|
-
...base,
|
|
162
|
-
interval,
|
|
163
|
-
intervalCount: interval ? price.payment_frequency_count : null,
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
export type DodoPriceCache = {
|
|
168
|
-
readonly get: (priceId: string) => ProviderPrice | null | undefined;
|
|
169
|
-
readonly set: (priceId: string, price: ProviderPrice | null) => void;
|
|
170
|
-
};
|
|
171
|
-
|
|
172
|
-
export type DodoPriceCacheOptions = {
|
|
173
|
-
readonly ttlMs?: number;
|
|
174
|
-
readonly now?: () => number;
|
|
175
|
-
};
|
|
176
|
-
|
|
177
|
-
// Keyed by product id alone: ids are unique per account and a cache hit must not
|
|
178
|
-
// trigger an audited secret read on every billing-plans render. Failed lookups
|
|
179
|
-
// are never cached. `null` is a cached "skipped" product (usage-based).
|
|
180
|
-
export function createDodoPriceCache({
|
|
181
|
-
ttlMs = 600_000,
|
|
182
|
-
now = () => Temporal.Now.instant().epochMilliseconds,
|
|
183
|
-
}: DodoPriceCacheOptions = {}): DodoPriceCache {
|
|
184
|
-
const store = new Map<
|
|
185
|
-
string,
|
|
186
|
-
{ readonly price: ProviderPrice | null; readonly expiresAt: number }
|
|
187
|
-
>();
|
|
188
|
-
return {
|
|
189
|
-
get: (priceId) => {
|
|
190
|
-
const entry = store.get(priceId);
|
|
191
|
-
if (!entry) return undefined;
|
|
192
|
-
if (entry.expiresAt <= now()) {
|
|
193
|
-
store.delete(priceId);
|
|
194
|
-
return undefined;
|
|
195
|
-
}
|
|
196
|
-
return entry.price;
|
|
197
|
-
},
|
|
198
|
-
set: (priceId, price) => {
|
|
199
|
-
store.set(priceId, { price, expiresAt: now() + ttlMs });
|
|
200
|
-
},
|
|
201
|
-
};
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
async function fillPriceCache(
|
|
205
|
-
runtime: DodoCtxRuntime,
|
|
206
|
-
cache: DodoPriceCache,
|
|
207
|
-
ctx: HandlerContext,
|
|
208
|
-
priceIds: readonly string[],
|
|
209
|
-
): Promise<void> {
|
|
210
|
-
const misses = priceIds.filter((priceId) => cache.get(priceId) === undefined);
|
|
211
|
-
const settled = await Promise.allSettled(
|
|
212
|
-
misses.map(async (priceId) => ({
|
|
213
|
-
priceId,
|
|
214
|
-
product: productSchema.parse(
|
|
215
|
-
await runtime.call(ctx, {
|
|
216
|
-
method: "GET",
|
|
217
|
-
path: `/products/${encodeURIComponent(priceId)}`,
|
|
218
|
-
}),
|
|
219
|
-
),
|
|
220
|
-
})),
|
|
221
|
-
);
|
|
222
|
-
for (const outcome of settled) {
|
|
223
|
-
if (outcome.status === "fulfilled") {
|
|
224
|
-
cache.set(outcome.value.priceId, mapDodoProduct(outcome.value.product));
|
|
225
|
-
} else {
|
|
226
|
-
const message =
|
|
227
|
-
outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
|
|
228
|
-
ctx.obs.log?.warn("subscription-dodo: product lookup failed", { message });
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
export function createDodoRetrievePrices(
|
|
234
|
-
runtime: DodoCtxRuntime,
|
|
235
|
-
cache: DodoPriceCache,
|
|
236
|
-
): PluginMethod<"retrievePrices"> {
|
|
237
|
-
return async (ctx, priceIds) => {
|
|
238
|
-
await fillPriceCache(runtime, cache, ctx, priceIds);
|
|
239
|
-
return priceIds.flatMap((priceId) => cache.get(priceId) ?? []);
|
|
240
|
-
};
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// =============================================================================
|
|
244
|
-
// Plan switch (in-app: preview + apply)
|
|
245
|
-
// =============================================================================
|
|
246
|
-
|
|
247
|
-
const previewResponseSchema = z.object({
|
|
248
|
-
immediate_charge: z.object({
|
|
249
|
-
summary: z.object({
|
|
250
|
-
total_amount: z.number(),
|
|
251
|
-
tax: z.number().nullable(),
|
|
252
|
-
currency: z.string(),
|
|
253
|
-
customer_credits: z.number(),
|
|
254
|
-
}),
|
|
255
|
-
effective_at: z.string(),
|
|
256
|
-
}),
|
|
257
|
-
});
|
|
258
|
-
|
|
259
|
-
function changePlanBody(targetPriceId: string) {
|
|
260
|
-
return {
|
|
261
|
-
product_id: targetPriceId,
|
|
262
|
-
quantity: 1,
|
|
263
|
-
proration_billing_mode: "prorated_immediately",
|
|
264
|
-
effective_at: "immediately",
|
|
265
|
-
};
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
export function createDodoPreviewPlanSwitch(
|
|
269
|
-
runtime: DodoCtxRuntime,
|
|
270
|
-
): PluginMethod<"previewPlanSwitch"> {
|
|
271
|
-
return async (ctx, options): Promise<PlanSwitchPreview> => {
|
|
272
|
-
const { immediate_charge: charge } = previewResponseSchema.parse(
|
|
273
|
-
await runtime.call(ctx, {
|
|
274
|
-
method: "POST",
|
|
275
|
-
path: `${subscriptionPath(options.providerSubscriptionId)}/change-plan/preview`,
|
|
276
|
-
body: changePlanBody(options.targetPriceId),
|
|
277
|
-
}),
|
|
278
|
-
);
|
|
279
|
-
return {
|
|
280
|
-
amountDueNow: charge.summary.total_amount,
|
|
281
|
-
tax: charge.summary.tax,
|
|
282
|
-
currency: charge.summary.currency.toLowerCase(),
|
|
283
|
-
credit: charge.summary.customer_credits,
|
|
284
|
-
effectiveAt: charge.effective_at,
|
|
285
|
-
};
|
|
286
|
-
};
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
const applyResponseSchema = z.looseObject({
|
|
290
|
-
payment_id: z.string().nullish(),
|
|
291
|
-
payment_link: z.string().nullish(),
|
|
292
|
-
});
|
|
293
|
-
|
|
294
|
-
// The switch itself arrives later as a subscription.plan_changed webhook;
|
|
295
|
-
// prevent_change keeps the old plan if the immediate charge fails.
|
|
296
|
-
export function createDodoApplyPlanSwitch(
|
|
297
|
-
runtime: DodoCtxRuntime,
|
|
298
|
-
): PluginMethod<"applyPlanSwitch"> {
|
|
299
|
-
return async (ctx, options) => {
|
|
300
|
-
applyResponseSchema.parse(
|
|
301
|
-
await runtime.call(ctx, {
|
|
302
|
-
method: "POST",
|
|
303
|
-
path: `${subscriptionPath(options.providerSubscriptionId)}/change-plan`,
|
|
304
|
-
body: {
|
|
305
|
-
...changePlanBody(options.targetPriceId),
|
|
306
|
-
on_payment_failure: "prevent_change",
|
|
307
|
-
metadata: {
|
|
308
|
-
tenantId: options.tenantId,
|
|
309
|
-
...(options.consentId && { consentId: options.consentId }),
|
|
310
|
-
},
|
|
311
|
-
},
|
|
312
|
-
}),
|
|
313
|
-
);
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
// =============================================================================
|
|
318
|
-
// retrieveSubscription
|
|
319
|
-
// =============================================================================
|
|
320
|
-
|
|
321
|
-
export function createDodoRetrieveSubscription(
|
|
322
|
-
runtime: DodoCtxRuntime,
|
|
323
|
-
options: { readonly priceToTier: Readonly<Record<string, string>> },
|
|
324
|
-
): PluginMethod<"retrieveSubscription"> {
|
|
325
|
-
return async (ctx, providerSubscriptionId): Promise<ProviderSubscriptionSnapshot | null> => {
|
|
326
|
-
let raw: unknown;
|
|
327
|
-
try {
|
|
328
|
-
raw = await runtime.call(ctx, {
|
|
329
|
-
method: "GET",
|
|
330
|
-
path: subscriptionPath(providerSubscriptionId),
|
|
331
|
-
});
|
|
332
|
-
} catch (error) {
|
|
333
|
-
if (error instanceof DodoHttpError && error.status === NOT_FOUND) return null;
|
|
334
|
-
throw error;
|
|
335
|
-
}
|
|
336
|
-
const sub = dodoSubscriptionSchema.parse(raw);
|
|
337
|
-
const state = mapDodoSubscriptionState(sub, options.priceToTier);
|
|
338
|
-
if (!state) return null;
|
|
339
|
-
return {
|
|
340
|
-
providerCustomerId: sub.customer.customer_id,
|
|
341
|
-
providerSubscriptionId: sub.subscription_id,
|
|
342
|
-
...state,
|
|
343
|
-
};
|
|
344
|
-
};
|
|
345
|
-
}
|