create-ailk 0.1.0 → 0.2.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/README.md +124 -3
- package/component-catalog.md +456 -0
- package/dist/cli.js +92 -16
- package/dist/component-catalog.d.ts +11 -0
- package/dist/component-catalog.js +39 -0
- package/dist/copy.d.ts +7 -0
- package/dist/copy.js +24 -0
- package/dist/derive-architecture.d.ts +13 -0
- package/dist/derive-architecture.js +238 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +19 -2
- package/dist/lib/extract-module-bundle.d.ts +16 -0
- package/dist/lib/extract-module-bundle.js +184 -0
- package/dist/lib/fetch-module.d.ts +55 -0
- package/dist/lib/fetch-module.js +125 -0
- package/dist/lib/module-license-gate.d.ts +48 -0
- package/dist/lib/module-license-gate.js +67 -0
- package/dist/lib/module-tier.d.ts +35 -0
- package/dist/lib/module-tier.js +37 -0
- package/dist/module-architecture.d.ts +175 -0
- package/dist/module-architecture.js +663 -0
- package/dist/parse-args.d.ts +47 -1
- package/dist/parse-args.js +143 -2
- package/dist/programmatic.d.ts +160 -3
- package/dist/programmatic.js +196 -7
- package/dist/surfaces.d.ts +211 -0
- package/dist/surfaces.js +532 -0
- package/dist/sync-routes.d.ts +92 -0
- package/dist/sync-routes.js +350 -0
- package/package.json +12 -5
- package/templates/.claude/rules/architecture.md +6 -2
- package/templates/.claude/skills/README.md +9 -9
- package/templates/.claude/skills/add-schema/SKILL.md +14 -7
- package/templates/.claude/skills/add-schema/references/schema-types.md +109 -6
- package/templates/.claude/skills/provision-config/SKILL.md +1 -1
- package/templates/.claude/skills/scaffold-commerce/SKILL.md +498 -1
- package/templates/.claude/skills/scaffold-commerce/templates/checkout-route.template.ts +370 -0
- package/templates/.claude/skills/scaffold-commerce/templates/invoice-route.template.ts +376 -0
- package/templates/.claude/skills/scaffold-commerce/templates/payment-link-route.template.ts +471 -0
- package/templates/.claude/skills/scaffold-commerce/templates/portal-route.template.ts +365 -0
- package/templates/.claude/skills/scaffold-commerce/templates/stripe-config.template.ts +60 -0
- package/templates/.claude/skills/scaffold-commerce/templates/subscription-route.template.ts +446 -0
- package/templates/.claude/skills/suggest-site-pages/references/categories.md +4 -4
- package/templates/.env.example +126 -2
- package/templates/CLAUDE.md +11 -5
- package/templates/README.md +1 -1
- package/templates/apps/api/.env.example +38 -0
- package/templates/apps/api/CLAUDE.md +78 -1
- package/templates/apps/api/LICENSE +201 -0
- package/templates/apps/api/api/index.ts +6 -141
- package/templates/apps/api/jest.config.cjs +16 -0
- package/templates/apps/api/package.json +22 -6
- package/templates/apps/api/src/__tests__/module-exclusion.test.ts +141 -0
- package/templates/apps/api/src/__tests__/server.test.ts +46 -0
- package/templates/apps/api/src/__tests__/vercel-handler.test.ts +211 -0
- package/templates/apps/api/src/bin/abandon-sweep.ts +42 -0
- package/templates/apps/api/src/bin/deliverable-resend.ts +144 -0
- package/templates/apps/api/src/bin/deliverable-upload.ts +114 -0
- package/templates/apps/api/src/bin/followup-sweep.ts +44 -0
- package/templates/apps/api/src/bin/listing-csv-sweep.ts +46 -0
- package/templates/apps/api/src/bin/seed-presets.ts +58 -0
- package/templates/apps/api/src/bin/seed-waitlist-experiments.ts +104 -0
- package/templates/apps/api/src/bin/session-retention-sweep.ts +46 -0
- package/templates/apps/api/src/cli.ts +5 -11
- package/templates/apps/api/src/config/index.ts +35 -0
- package/templates/apps/api/src/config/modules.ts +43 -0
- package/templates/apps/api/src/lib/__mocks__/prisma-client.js +11 -0
- package/templates/apps/api/src/lib/__mocks__/prisma.ts +241 -0
- package/templates/apps/api/src/lib/__tests__/lead-capture-store.test.ts +2 -2
- package/templates/apps/api/src/lib/site.ts +16 -0
- package/templates/apps/api/src/lib/stripe.ts +22 -0
- package/templates/apps/api/src/lib/tenant-db.ts +225 -0
- package/templates/apps/api/src/lib/ws-token.ts +91 -0
- package/templates/apps/api/src/middleware/__tests__/adversarial/session-fixation.test.ts +7 -1
- package/templates/apps/api/src/middleware/__tests__/auth.cookie-path.test.ts +7 -1
- package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +91 -4
- package/templates/apps/api/src/middleware/auth.ts +43 -8
- package/templates/apps/api/src/middleware/rate-limit.ts +78 -3
- package/templates/apps/api/src/middleware/tenant.ts +99 -0
- package/templates/apps/api/src/openapi/__tests__/openapi.test.ts +92 -0
- package/templates/apps/api/src/openapi/spec.ts +312 -3
- package/templates/apps/api/src/routes/aeo/__tests__/index.test.ts +175 -0
- package/templates/apps/api/src/routes/aeo/index.ts +107 -0
- package/templates/apps/api/src/routes/auth/__tests__/auth-tokens.functional.test.ts +5 -2
- package/templates/apps/api/src/routes/auth/__tests__/tokens.test.ts +22 -3
- package/templates/apps/api/src/routes/auth/tokens.ts +13 -1
- package/templates/apps/api/src/routes/billing/__tests__/portal.test.ts +450 -0
- package/templates/apps/api/src/routes/billing/__tests__/read.test.ts +262 -0
- package/templates/apps/api/src/routes/billing/__tests__/usage.test.ts +436 -0
- package/templates/apps/api/src/routes/billing/index.ts +36 -0
- package/templates/apps/api/src/routes/billing/portal.ts +182 -0
- package/templates/apps/api/src/routes/billing/read.ts +75 -0
- package/templates/apps/api/src/routes/billing/usage.ts +153 -0
- package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +99 -0
- package/templates/apps/api/src/routes/checkout/sessions.ts +20 -8
- package/templates/apps/api/src/routes/content/create.ts +1 -0
- package/templates/apps/api/src/routes/content/delete.ts +1 -0
- package/templates/apps/api/src/routes/content/index.ts +42 -6
- package/templates/apps/api/src/routes/content/update.ts +1 -0
- package/templates/apps/api/src/routes/deliverables/__tests__/index.test.ts +393 -0
- package/templates/apps/api/src/routes/deliverables/index.ts +200 -0
- package/templates/apps/api/src/routes/flow-checkouts/__tests__/index.test.ts +443 -0
- package/templates/apps/api/src/routes/flow-checkouts/index.ts +82 -0
- package/templates/apps/api/src/routes/flows/README.md +147 -0
- package/templates/apps/api/src/routes/flows/__tests__/index.test.ts +752 -0
- package/templates/apps/api/src/routes/flows/__tests__/recommender.test.ts +671 -0
- package/templates/apps/api/src/routes/flows/index.ts +202 -0
- package/templates/apps/api/src/routes/flows/recommender.ts +443 -0
- package/templates/apps/api/src/routes/leads/__tests__/index.test.ts +438 -31
- package/templates/apps/api/src/routes/leads/__tests__/track.test.ts +10 -10
- package/templates/apps/api/src/routes/leads/index.ts +43 -9
- package/templates/apps/api/src/routes/project-listings/__tests__/configured-application.test.ts +558 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/copy-edit.test.ts +815 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +869 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/me-route-precedence.test.ts +221 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/me.test.ts +468 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/public.test.ts +424 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/site-answers.test.ts +707 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/site-key.test.ts +375 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/structured-address.test.ts +467 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/tenant-isolation.test.ts +566 -0
- package/templates/apps/api/src/routes/project-listings/get.ts +70 -0
- package/templates/apps/api/src/routes/project-listings/index.ts +120 -0
- package/templates/apps/api/src/routes/project-listings/list.ts +47 -0
- package/templates/apps/api/src/routes/project-listings/me.ts +76 -0
- package/templates/apps/api/src/routes/project-listings/patch-copy.ts +222 -0
- package/templates/apps/api/src/routes/project-listings/patch-draft.ts +97 -0
- package/templates/apps/api/src/routes/project-listings/patch.ts +136 -0
- package/templates/apps/api/src/routes/project-listings/public.ts +52 -0
- package/templates/apps/api/src/routes/project-listings/respond.ts +37 -0
- package/templates/apps/api/src/routes/project-listings/resume-token.ts +22 -0
- package/templates/apps/api/src/routes/project-listings/start.ts +106 -0
- package/templates/apps/api/src/routes/project-listings/submit.ts +122 -0
- package/templates/apps/api/src/routes/schedule/__tests__/index.test.ts +490 -0
- package/templates/apps/api/src/routes/schedule/index.ts +249 -0
- package/templates/apps/api/src/routes/slack/__tests__/actions.test.ts +385 -0
- package/templates/apps/api/src/routes/slack/actions.ts +177 -0
- package/templates/apps/api/src/routes/slack/index.ts +38 -0
- package/templates/apps/api/src/routes/test/auth/__tests__/session.test.ts +16 -6
- package/templates/apps/api/src/routes/test/auth/session.ts +8 -6
- package/templates/apps/api/src/routes/waitlist-experiments/__tests__/tenant-isolation.test.ts +577 -0
- package/templates/apps/api/src/routes/waitlist-experiments/comparison.ts +78 -0
- package/templates/apps/api/src/routes/waitlist-experiments/index.ts +41 -0
- package/templates/apps/api/src/routes/waitlist-experiments/list.ts +64 -0
- package/templates/apps/api/src/routes/waitlist-experiments/respond.ts +42 -0
- package/templates/apps/api/src/routes/waitlist-experiments/signup.ts +84 -0
- package/templates/apps/api/src/routes/waitlist-experiments/signups.ts +119 -0
- package/templates/apps/api/src/routes/waitlist-signups/__tests__/index.test.ts +238 -0
- package/templates/apps/api/src/routes/waitlist-signups/index.ts +101 -0
- package/templates/apps/api/src/routes/webhooks/README.md +35 -12
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +315 -0
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +270 -0
- package/templates/apps/api/src/routes/webhooks/stripe.ts +248 -20
- package/templates/apps/api/src/routes/workspaces/__tests__/config-tenant-isolation.test.ts +356 -0
- package/templates/apps/api/src/routes/workspaces/__tests__/tenant-isolation.test.ts +671 -0
- package/templates/apps/api/src/routes/workspaces/config.ts +125 -0
- package/templates/apps/api/src/routes/workspaces/index.ts +194 -0
- package/templates/apps/api/src/routes/workspaces/sessions.ts +218 -0
- package/templates/apps/api/src/server.ts +307 -7
- package/templates/apps/api/src/services/__tests__/abandon-email.test.ts +489 -0
- package/templates/apps/api/src/services/__tests__/aeo-score.test.ts +475 -0
- package/templates/apps/api/src/services/__tests__/answer-distributions.test.ts +132 -0
- package/templates/apps/api/src/services/__tests__/consent-migration.test.ts +65 -0
- package/templates/apps/api/src/services/__tests__/consent.test.ts +282 -0
- package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +523 -0
- package/templates/apps/api/src/services/__tests__/deliverable-resend.test.ts +359 -0
- package/templates/apps/api/src/services/__tests__/entitlements.test.ts +142 -0
- package/templates/apps/api/src/services/__tests__/flow-aggregate.test.ts +425 -0
- package/templates/apps/api/src/services/__tests__/flow-engine.test.ts +2840 -0
- package/templates/apps/api/src/services/__tests__/lead-promotion.test.ts +393 -0
- package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +8 -8
- package/templates/apps/api/src/services/__tests__/listing-csv-sweep.test.ts +560 -0
- package/templates/apps/api/src/services/__tests__/listing-promotion.test.ts +684 -0
- package/templates/apps/api/src/services/__tests__/playbook-compile.test.ts +406 -0
- package/templates/apps/api/src/services/__tests__/playbook-render.test.ts +290 -0
- package/templates/apps/api/src/services/__tests__/project-listing-decision.test.ts +736 -0
- package/templates/apps/api/src/services/__tests__/project-listing-flow.test.ts +475 -0
- package/templates/apps/api/src/services/__tests__/project-listing-issue.test.ts +340 -0
- package/templates/apps/api/src/services/__tests__/recommender-capture.test.ts +983 -0
- package/templates/apps/api/src/services/__tests__/slack-notify.test.ts +278 -0
- package/templates/apps/api/src/services/__tests__/tenant-context-cascade.test.ts +71 -0
- package/templates/apps/api/src/services/__tests__/tenant-context.test.ts +379 -0
- package/templates/apps/api/src/services/__tests__/usage-aggregation.test.ts +941 -0
- package/templates/apps/api/src/services/__tests__/usage-credits.test.ts +588 -0
- package/templates/apps/api/src/services/__tests__/usage-metering.test.ts +768 -0
- package/templates/apps/api/src/services/__tests__/waitlist-dashboard.test.ts +1314 -0
- package/templates/apps/api/src/services/__tests__/waitlist-experiments.test.ts +341 -0
- package/templates/apps/api/src/services/__tests__/waitlist-followup.test.ts +567 -0
- package/templates/apps/api/src/services/__tests__/waitlist-scoring.test.ts +474 -0
- package/templates/apps/api/src/services/__tests__/waitlist-signups.test.ts +354 -0
- package/templates/apps/api/src/services/abandon-email.ts +307 -0
- package/templates/apps/api/src/services/aeo-score.ts +288 -0
- package/templates/apps/api/src/services/answer-distributions.ts +138 -0
- package/templates/apps/api/src/services/consent.ts +236 -0
- package/templates/apps/api/src/services/deliverable-fulfillment.ts +523 -0
- package/templates/apps/api/src/services/entitlements.ts +102 -0
- package/templates/apps/api/src/services/flow-aggregate.ts +232 -0
- package/templates/apps/api/src/services/flow-checkouts.ts +123 -0
- package/templates/apps/api/src/services/flow-engine.ts +1296 -0
- package/templates/apps/api/src/services/lead-promotion.ts +176 -0
- package/templates/apps/api/src/services/lead-routing.ts +3 -3
- package/templates/apps/api/src/services/listing-config.ts +102 -0
- package/templates/apps/api/src/services/listing-csv-sweep.ts +455 -0
- package/templates/apps/api/src/services/listing-promotion.ts +342 -0
- package/templates/apps/api/src/services/playbook-compile.ts +398 -0
- package/templates/apps/api/src/services/playbook-render.ts +263 -0
- package/templates/apps/api/src/services/project-listing-decision.ts +510 -0
- package/templates/apps/api/src/services/project-listing-flow.ts +426 -0
- package/templates/apps/api/src/services/project-listing-issue.ts +251 -0
- package/templates/apps/api/src/services/project-listings.ts +1472 -0
- package/templates/apps/api/src/services/recommender-capture.ts +835 -0
- package/templates/apps/api/src/services/scheduling/cal-provider.ts +392 -0
- package/templates/apps/api/src/services/scheduling/index.ts +63 -0
- package/templates/apps/api/src/services/scheduling/types.ts +88 -0
- package/templates/apps/api/src/services/slack-notify.ts +240 -0
- package/templates/apps/api/src/services/tenant-context.ts +451 -0
- package/templates/apps/api/src/services/usage-aggregation.ts +516 -0
- package/templates/apps/api/src/services/usage-credits.ts +340 -0
- package/templates/apps/api/src/services/usage-metering.ts +699 -0
- package/templates/apps/api/src/services/waitlist-dashboard.ts +947 -0
- package/templates/apps/api/src/services/waitlist-experiments.ts +213 -0
- package/templates/apps/api/src/services/waitlist-followup.ts +486 -0
- package/templates/apps/api/src/services/waitlist-scoring.ts +166 -0
- package/templates/apps/api/src/services/waitlist-signups.ts +165 -0
- package/templates/apps/api/src/vercel-handler.ts +165 -0
- package/templates/apps/api/tsconfig.json +0 -12
- package/templates/apps/mcp/CLAUDE.md +19 -9
- package/templates/apps/mcp/LICENSE +201 -0
- package/templates/apps/mcp/__tests__/create_page.test.ts +1 -0
- package/templates/apps/mcp/__tests__/delete_page.test.ts +1 -0
- package/templates/apps/mcp/__tests__/module-exclusion.test.ts +105 -0
- package/templates/apps/mcp/__tests__/parity.test.ts +70 -6
- package/templates/apps/mcp/__tests__/request_callback.test.ts +4 -4
- package/templates/apps/mcp/__tests__/schedule_tools.test.ts +242 -0
- package/templates/apps/mcp/__tests__/submit_lead.test.ts +4 -4
- package/templates/apps/mcp/__tests__/subscribe_newsletter.test.ts +4 -4
- package/templates/apps/mcp/__tests__/tools/purchase.test.ts +47 -0
- package/templates/apps/mcp/__tests__/update_page.test.ts +1 -0
- package/templates/apps/mcp/package.json +6 -4
- package/templates/apps/mcp/src/config/modules.ts +37 -0
- package/templates/apps/mcp/src/server.ts +109 -18
- package/templates/apps/mcp/src/tools/capture_lead.ts +1 -1
- package/templates/apps/mcp/src/tools/create_booking.ts +58 -0
- package/templates/apps/mcp/src/tools/create_page.ts +1 -0
- package/templates/apps/mcp/src/tools/delete_page.ts +1 -0
- package/templates/apps/mcp/src/tools/get_event_meta.ts +55 -0
- package/templates/apps/mcp/src/tools/get_flow.ts +61 -0
- package/templates/apps/mcp/src/tools/index.ts +25 -0
- package/templates/apps/mcp/src/tools/list_availability.ts +67 -0
- package/templates/apps/mcp/src/tools/purchase.ts +3 -0
- package/templates/apps/mcp/src/tools/submit_flow_step.ts +83 -0
- package/templates/apps/mcp/src/tools/update_page.ts +1 -0
- package/templates/apps/mcp/tsconfig.json +1 -9
- package/templates/apps/web/.env.example +44 -0
- package/templates/apps/web/CLAUDE.md +28 -0
- package/templates/apps/web/LICENSE +201 -0
- package/templates/apps/web/__tests__/__mocks__/code-highlight.jest-stub.ts +24 -0
- package/templates/apps/web/__tests__/__mocks__/next-intl-server.ts +33 -0
- package/templates/apps/web/__tests__/__mocks__/next-intl.ts +18 -0
- package/templates/apps/web/__tests__/__mocks__/server-only.ts +13 -0
- package/templates/apps/web/__tests__/__mocks__/style-mock.js +4 -0
- package/templates/apps/web/__tests__/__mocks__/vercel-analytics-server.ts +9 -0
- package/templates/apps/web/__tests__/jest-support/import-meta-transformer.cjs +90 -0
- package/templates/apps/web/__tests__/setup.ts +22 -32
- package/templates/apps/web/app/.well-known/ai-plugin.json/route.ts +6 -3
- package/templates/apps/web/app/.well-known/mcp.json/build-manifest.ts +8 -2
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +260 -0
- package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +263 -0
- package/templates/apps/web/app/[locale]/(authed)/account/sign-out-button.tsx +39 -0
- package/templates/apps/web/app/[locale]/(authed)/layout.tsx +54 -0
- package/templates/apps/web/app/[locale]/(authed)/sign-in-gate.tsx +96 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/[experimentId]/page.tsx +309 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/[experimentId]/signups/[leadId]/page.tsx +149 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/comparison.test.tsx +273 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/gate.test.tsx +172 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/list.test.tsx +171 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/signup.test.tsx +179 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/ExperimentsTable.tsx +116 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/ForbiddenState.tsx +24 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/OfferFunnelTable.tsx +66 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/RollupTicker.tsx +61 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/ScoreTrace.tsx +114 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/SignupsTable.tsx +139 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/WaitlistComparisonTabs.tsx +85 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/components/status-badges.tsx +67 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/format.ts +111 -0
- package/templates/apps/web/app/[locale]/(authed)/waitlist/page.tsx +179 -0
- package/templates/apps/web/app/[locale]/about/page.tsx +10 -1
- package/templates/apps/web/app/[locale]/blog/[[...slug]]/page.tsx +6 -1
- package/templates/apps/web/app/[locale]/careers/[slug]/page.tsx +9 -0
- package/templates/apps/web/app/[locale]/careers/__tests__/page-renderer-migration.test.tsx +3 -3
- package/templates/apps/web/app/[locale]/careers/page.tsx +9 -1
- package/templates/apps/web/app/[locale]/case-studies/[slug]/page.tsx +9 -0
- package/templates/apps/web/app/[locale]/case-studies/__tests__/page-renderer-migration.test.tsx +3 -3
- package/templates/apps/web/app/[locale]/case-studies/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/clients/__tests__/page-renderer-migration.test.tsx +11 -1
- package/templates/apps/web/app/[locale]/clients/page.tsx +9 -1
- package/templates/apps/web/app/[locale]/contact/ContactForm.tsx +21 -1
- package/templates/apps/web/app/[locale]/contact/ConversationalIntakeWrapper.tsx +188 -0
- package/templates/apps/web/app/[locale]/contact/__tests__/ConversationalIntakeWrapper.test.tsx +242 -0
- package/templates/apps/web/app/[locale]/contact/__tests__/contact.actions.test.ts +29 -0
- package/templates/apps/web/app/[locale]/contact/__tests__/intake-analytics.test.ts +51 -0
- package/templates/apps/web/app/[locale]/contact/__tests__/page-renderer-migration.test.tsx +39 -15
- package/templates/apps/web/app/[locale]/contact/contact.actions.ts +21 -3
- package/templates/apps/web/app/[locale]/contact/intake-analytics.ts +49 -0
- package/templates/apps/web/app/[locale]/contact/intake-script.ts +66 -0
- package/templates/apps/web/app/[locale]/contact/page.tsx +14 -4
- package/templates/apps/web/app/[locale]/courses/[slug]/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/courses/__tests__/page-renderer-migration.test.tsx +3 -3
- package/templates/apps/web/app/[locale]/courses/page.tsx +9 -1
- package/templates/apps/web/app/[locale]/docs/[[...slug]]/page.tsx +1 -0
- package/templates/apps/web/app/[locale]/downloads/__tests__/page-renderer-migration.test.tsx +11 -1
- package/templates/apps/web/app/[locale]/downloads/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/events/[slug]/page.tsx +9 -0
- package/templates/apps/web/app/[locale]/events/__tests__/page-renderer-migration.test.tsx +12 -2
- package/templates/apps/web/app/[locale]/events/page.tsx +9 -1
- package/templates/apps/web/app/[locale]/faq/page.tsx +10 -1
- package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +265 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.permalink.test.tsx +445 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.test.tsx +341 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/checkout.actions.test.ts +287 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/flow.actions.test.ts +302 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/two-route-tool.test.tsx +128 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/checkout.actions.ts +254 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/flow.actions.ts +144 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/page.tsx +108 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +532 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsEmailStep.tsx +121 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.checkout.test.tsx +457 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/page.test.tsx +396 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/page.tsx +114 -0
- package/templates/apps/web/app/[locale]/flows/[slug]/start/page.tsx +52 -0
- package/templates/apps/web/app/[locale]/how-to/[slug]/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/how-to/__tests__/page-renderer-migration.test.tsx +1 -1
- package/templates/apps/web/app/[locale]/integrations/[slug]/page.tsx +9 -0
- package/templates/apps/web/app/[locale]/integrations/__tests__/page-renderer-migration.test.tsx +3 -3
- package/templates/apps/web/app/[locale]/integrations/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/launch-service/page.tsx +14 -1
- package/templates/apps/web/app/[locale]/layout.tsx +127 -16
- package/templates/apps/web/app/[locale]/page.tsx +10 -1
- package/templates/apps/web/app/[locale]/partners/[slug]/page.tsx +9 -0
- package/templates/apps/web/app/[locale]/partners/__tests__/page-renderer-migration.test.tsx +3 -3
- package/templates/apps/web/app/[locale]/partners/page.tsx +9 -1
- package/templates/apps/web/app/[locale]/products/[slug]/page.tsx +9 -0
- package/templates/apps/web/app/[locale]/products/__tests__/page-renderer-migration.test.tsx +3 -3
- package/templates/apps/web/app/[locale]/products/page.tsx +9 -1
- package/templates/apps/web/app/[locale]/projects/[slug]/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/projects/__tests__/page-renderer-migration.test.tsx +10 -0
- package/templates/apps/web/app/[locale]/projects/apply/ListingApplicationClient.tsx +110 -0
- package/templates/apps/web/app/[locale]/projects/apply/__tests__/ListingApplicationClient.test.tsx +96 -0
- package/templates/apps/web/app/[locale]/projects/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/resources/[slug]/page.tsx +9 -0
- package/templates/apps/web/app/[locale]/resources/__tests__/page-renderer-migration.test.tsx +12 -2
- package/templates/apps/web/app/[locale]/resources/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/schedule/__tests__/page.test.tsx +117 -0
- package/templates/apps/web/app/[locale]/schedule/confirmed/__tests__/page.test.tsx +96 -0
- package/templates/apps/web/app/[locale]/schedule/confirmed/page.tsx +92 -0
- package/templates/apps/web/app/[locale]/schedule/page.tsx +82 -0
- package/templates/apps/web/app/[locale]/services/[slug]/page.tsx +9 -0
- package/templates/apps/web/app/[locale]/services/__tests__/page-renderer-migration.test.tsx +3 -3
- package/templates/apps/web/app/[locale]/services/page.tsx +9 -1
- package/templates/apps/web/app/[locale]/sign-in/__tests__/next-path.test.ts +31 -0
- package/templates/apps/web/app/[locale]/sign-in/__tests__/page.test.tsx +152 -0
- package/templates/apps/web/app/[locale]/sign-in/next-path.ts +0 -0
- package/templates/apps/web/app/[locale]/sign-in/page.tsx +83 -0
- package/templates/apps/web/app/[locale]/sign-in/sign-in-card.tsx +123 -0
- package/templates/apps/web/app/[locale]/software/[slug]/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/software/__tests__/page-renderer-migration.test.tsx +1 -1
- package/templates/apps/web/app/[locale]/tech-articles/[slug]/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/tech-articles/__tests__/page-renderer-migration.test.tsx +1 -1
- package/templates/apps/web/app/[locale]/testimonials/__tests__/page-renderer-migration.test.tsx +11 -1
- package/templates/apps/web/app/[locale]/testimonials/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/thanks/[slug]/__tests__/page.test.tsx +93 -0
- package/templates/apps/web/app/[locale]/thanks/[slug]/page.tsx +48 -0
- package/templates/apps/web/app/[locale]/use-cases/__tests__/page-renderer-migration.test.tsx +11 -1
- package/templates/apps/web/app/[locale]/use-cases/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/whitepapers/[slug]/page.tsx +13 -1
- package/templates/apps/web/app/[locale]/whitepapers/__tests__/page-renderer-migration.test.tsx +1 -1
- package/templates/apps/web/app/globals.css +35 -0
- package/templates/apps/web/app/llms.txt/route.ts +2 -1
- package/templates/apps/web/app/og/route.tsx +10 -2
- package/templates/apps/web/auth.ts +8 -0
- package/templates/apps/web/components/sign-out-trigger.tsx +42 -0
- package/templates/apps/web/content/en/blog/README.txt +25 -0
- package/templates/apps/web/content/en/docs/index.mdx +28 -0
- package/templates/apps/web/jest.config.cjs +90 -27
- package/templates/apps/web/lib/__tests__/site-brand.test.ts +119 -0
- package/templates/apps/web/lib/__tests__/site-theme.test.ts +112 -0
- package/templates/apps/web/lib/__tests__/structured-data.test.tsx +499 -0
- package/templates/apps/web/lib/account-config.ts +13 -0
- package/templates/apps/web/lib/server-api.ts +85 -0
- package/templates/apps/web/lib/site-brand.tsx +121 -0
- package/templates/apps/web/lib/site-theme.ts +74 -0
- package/templates/apps/web/messages/en.json +275 -7
- package/templates/apps/web/middleware.ts +11 -3
- package/templates/apps/web/next.config.mjs +8 -2
- package/templates/apps/web/package.json +17 -7
- package/templates/apps/web/postcss.config.mjs +23 -0
- package/templates/apps/web/public/.well-known/security.txt +3 -3
- package/templates/apps/web/src/lib/routes.ts +15 -2
- package/templates/apps/web/tsconfig.json +1 -16
- package/templates/content/_site.mdx +36 -25
- package/templates/content/en/AboutPage/about.mdx +24 -14
- package/templates/content/en/ContactPage/contact.mdx +23 -14
- package/templates/content/en/FAQPage/faq.mdx +10 -392
- package/templates/content/en/HomePage/home.mdx +14 -285
- package/templates/database/CHANGELOG.md +443 -0
- package/templates/database/LICENSE +201 -0
- package/templates/database/README.md +3 -1
- package/templates/database/__tests__/flows-listing-diagnostic.test.ts +392 -0
- package/templates/database/__tests__/flows-presets.test.ts +173 -0
- package/templates/database/__tests__/prefixed-ids.db.test.ts +146 -0
- package/templates/database/__tests__/seed.test.ts +88 -0
- package/templates/database/__tests__/user-cascade.test.ts +19 -4
- package/templates/database/auth/schema.prisma +521 -0
- package/templates/database/config/schema.prisma +234 -0
- package/templates/database/content/schema.prisma +263 -0
- package/templates/database/flows/listing-diagnostic.ts +182 -0
- package/templates/database/flows/presets.ts +315 -0
- package/templates/database/inbox/__tests__/schema.test.ts +4 -0
- package/templates/database/inbox/schema.prisma +574 -3
- package/templates/database/jest.config.cjs +8 -0
- package/templates/database/migrations/20260712215647_add_multi_tenant_tenancy/migration.sql +201 -0
- package/templates/database/migrations/20260713143320_reanchor_site_config_to_workspace/migration.sql +67 -0
- package/templates/database/migrations/20260713174000_add_audit_logs/migration.sql +46 -0
- package/templates/database/migrations/20260713190000_drop_telemetry_records/migration.sql +25 -0
- package/templates/database/migrations/20260713192000_add_uuidv7_function/migration.sql +49 -0
- package/templates/database/migrations/20260713192429_prefixed_uuid_entity_ids/migration.sql +197 -0
- package/templates/database/migrations/20260713200000_add_org_billing/migration.sql +32 -0
- package/templates/database/migrations/20260714000000_add_lead_promotion_fields/migration.sql +22 -0
- package/templates/database/migrations/20260714010000_add_usage_billing_content_models/migration.sql +151 -0
- package/templates/database/migrations/20260714020000_add_usage_billing_auth_config_models/migration.sql +223 -0
- package/templates/database/migrations/20260714030000_credit_balance_non_negative/migration.sql +22 -0
- package/templates/database/migrations/20260714030000_widen_usage_billing_report_aggregates/migration.sql +32 -0
- package/templates/database/migrations/20260810233516_add_flow_engine_models/migration.sql +40 -0
- package/templates/database/migrations/20260811020000_add_flow_session_abandon_email_columns/migration.sql +4 -0
- package/templates/database/migrations/20260811030000_add_flow_session_abandon_email_index/migration.sql +2 -0
- package/templates/database/migrations/20260811040000_add_flow_session_segment/migration.sql +2 -0
- package/templates/database/migrations/20260811050000_add_deliverable_models/migration.sql +29 -0
- package/templates/database/migrations/20260812000000_add_deliverable_grant_send_columns/migration.sql +6 -0
- package/templates/database/migrations/20260902222948_add_waitlist_experiment_models/migration.sql +39 -0
- package/templates/database/migrations/20260902224500_add_waitlist_id_format_checks/migration.sql +24 -0
- package/templates/database/migrations/20260903004112_add_flow_session_flags_aeo_score/migration.sql +3 -0
- package/templates/database/migrations/20260903010000_add_playbook_instance/migration.sql +33 -0
- package/templates/database/migrations/20260904000000_add_waitlist_followup_send/migration.sql +30 -0
- package/templates/database/migrations/20260905230000_add_flow_checkout/migration.sql +47 -0
- package/templates/database/migrations/20260906000000_add_flow_checkout_idempotency/migration.sql +16 -0
- package/templates/database/migrations/20260907120000_add_project_listing/migration.sql +47 -0
- package/templates/database/migrations/20260907130000_add_project_listing_slack_columns/migration.sql +10 -0
- package/templates/database/migrations/20260907180000_add_listing_csv_send/migration.sql +26 -0
- package/templates/database/migrations/20260909120000_project_listings_platform/migration.sql +90 -0
- package/templates/database/migrations/20260909180000_listing_draft_and_fields/migration.sql +174 -0
- package/templates/database/migrations/20260910120000_listing_public_site_key/migration.sql +14 -0
- package/templates/database/migrations/20260911120000_listing_copy_edit_audit/migration.sql +25 -0
- package/templates/database/migrations/20260911140000_listing_structured_address/migration.sql +32 -0
- package/templates/database/migrations/20260911180000_consent_grants/migration.sql +71 -0
- package/templates/database/migrations/20260911200000_listing_site_answers/migration.sql +30 -0
- package/templates/database/migrations/20260912120000_listing_owner_link/migration.sql +49 -0
- package/templates/database/ops/schema.prisma +27 -0
- package/templates/database/package.json +42 -4
- package/templates/database/prisma.config.ts +1 -1
- package/templates/database/schema.prisma +19 -435
- package/templates/database/seed-test.ts +14 -4
- package/templates/database/seed.ts +148 -0
- package/templates/database/tenancy.ts +45 -0
- package/templates/database/tsconfig.flows.json +15 -0
- package/templates/database/tsconfig.json +7 -1
- package/templates/database/tsconfig.tenancy.json +14 -0
- package/templates/package.json +30 -55
- package/templates/pnpm-workspace.yaml +0 -3
- package/templates/project.yaml +1 -1
- package/templates/tsconfig.json +1 -37
- package/templates/apps/web/__tests__/auth/adversarial/cookie-attributes.test.ts +0 -94
- package/templates/apps/web/__tests__/auth/adversarial/oauth-state-parameter.test.ts +0 -75
- package/templates/apps/web/__tests__/auth/adversarial/redirect-uri-allowlist.test.ts +0 -82
- package/templates/apps/web/__tests__/auth/env-helpers.test.ts +0 -168
- package/templates/apps/web/__tests__/authority-list-routes.test.tsx +0 -208
- package/templates/apps/web/__tests__/better-stack.test.ts +0 -66
- package/templates/apps/web/__tests__/blog-dir-resolution.test.ts +0 -87
- package/templates/apps/web/__tests__/blog-source-populated.test.ts +0 -130
- package/templates/apps/web/__tests__/data-testid-coverage.test.tsx +0 -60
- package/templates/apps/web/__tests__/google-analytics.test.tsx +0 -104
- package/templates/apps/web/__tests__/i18n/middleware.test.ts +0 -119
- package/templates/apps/web/__tests__/i18n/routing.test.ts +0 -114
- package/templates/apps/web/__tests__/i18n/translations.test.ts +0 -191
- package/templates/apps/web/__tests__/json-ld.test.ts +0 -98
- package/templates/apps/web/__tests__/knowledge-events-routes.test.tsx +0 -580
- package/templates/apps/web/__tests__/layout-stealth.test.ts +0 -39
- package/templates/apps/web/__tests__/lighthouse-fixtures/improvement-image-shrink.tsx +0 -103
- package/templates/apps/web/__tests__/lighthouse-fixtures/override-fixture.md +0 -114
- package/templates/apps/web/__tests__/lighthouse-fixtures/regression-bloat.tsx +0 -94
- package/templates/apps/web/__tests__/page.test.tsx +0 -230
- package/templates/apps/web/__tests__/products-services-phase1.test.tsx +0 -321
- package/templates/apps/web/__tests__/projects-routes.test.tsx +0 -392
- package/templates/apps/web/__tests__/resources-downloads-integrations-phase2.test.tsx +0 -475
- package/templates/apps/web/__tests__/routes/ai-plugin-json.test.ts +0 -53
- package/templates/apps/web/__tests__/routes/blog-route.test.tsx +0 -191
- package/templates/apps/web/__tests__/routes/llms-txt.test.ts +0 -123
- package/templates/apps/web/__tests__/routes/robots-txt.test.ts +0 -52
- package/templates/apps/web/__tests__/routes/sitemap-xml.test.ts +0 -78
- package/templates/apps/web/__tests__/routes/well-known-mcp.test.ts +0 -203
- package/templates/apps/web/__tests__/section-routes.test.tsx +0 -693
- package/templates/apps/web/__tests__/security-headers.test.ts +0 -201
- package/templates/apps/web/__tests__/sentry-config.test.ts +0 -116
- package/templates/apps/web/__tests__/sitemap-locales.test.ts +0 -415
- package/templates/apps/web/__tests__/standalone-informational-routes.test.tsx +0 -844
- package/templates/apps/web/app/[locale]/__tests__/layout.test.tsx +0 -120
- package/templates/apps/web/app/[locale]/__tests__/page-renderer-migration.test.tsx +0 -202
- package/templates/apps/web/app/__tests__/error-boundaries.test.tsx +0 -152
- package/templates/apps/web/content/en/blog/index.mdx +0 -15
- package/templates/apps/web/content/en/blog/launching-ailk.mdx +0 -20
- package/templates/apps/web/content/en/docs/getting-started.mdx +0 -30
- package/templates/content/.gitkeep +0 -0
- package/templates/content/CLAUDE.md +0 -85
- package/templates/content/ar/HomePage/home.mdx +0 -123
- package/templates/content/ar/_site.mdx +0 -35
- package/templates/content/de/_site.mdx +0 -29
- package/templates/content/en/.gitkeep +0 -0
- package/templates/content/en/AboutPage/about.schema.json +0 -82
- package/templates/content/en/BookCall/book-call.mdx +0 -19
- package/templates/content/en/BookCall/book-call.schema.json +0 -121
- package/templates/content/en/BreadcrumbList/site-breadcrumbs.mdx +0 -20
- package/templates/content/en/CareersList/careers.mdx +0 -24
- package/templates/content/en/CaseStudiesList/case-studies.mdx +0 -22
- package/templates/content/en/CaseStudiesList/showcase.mdx +0 -8
- package/templates/content/en/CaseStudy/ailk-aeo-rollout.mdx +0 -32
- package/templates/content/en/CaseStudy/schema-builder-migration.mdx +0 -41
- package/templates/content/en/ClientsList/clients.mdx +0 -38
- package/templates/content/en/ContactPage/contact.schema.json +0 -100
- package/templates/content/en/ContactPoint/primary.mdx +0 -14
- package/templates/content/en/Course/aeo-fundamentals.mdx +0 -37
- package/templates/content/en/Course/schema-builder-workshop.mdx +0 -62
- package/templates/content/en/CoursesList/courses.mdx +0 -22
- package/templates/content/en/DownloadsList/downloads.mdx +0 -22
- package/templates/content/en/Event/aeo-office-hours-may-2026.mdx +0 -39
- package/templates/content/en/Event/ailk-launch-day-2026.mdx +0 -35
- package/templates/content/en/EventsList/events.mdx +0 -26
- package/templates/content/en/FAQPage/faq.schema.json +0 -231
- package/templates/content/en/GlossaryList/glossary.mdx +0 -19
- package/templates/content/en/GlossaryList/glossary.schema.json +0 -300
- package/templates/content/en/HomePage/home.schema.json +0 -88
- package/templates/content/en/HomePage/launch-service.mdx +0 -475
- package/templates/content/en/HomePage/launch-service.schema.json +0 -138
- package/templates/content/en/HowTo/add-mdx-content.mdx +0 -38
- package/templates/content/en/HowTo/configure-aeo-scoring.mdx +0 -35
- package/templates/content/en/HowTo/set-up-json-ld.mdx +0 -36
- package/templates/content/en/Integration/github-actions.mdx +0 -31
- package/templates/content/en/Integration/openai-api.mdx +0 -26
- package/templates/content/en/Integration/vercel.mdx +0 -32
- package/templates/content/en/IntegrationsList/integrations.mdx +0 -22
- package/templates/content/en/JobPosting/content-strategist.mdx +0 -46
- package/templates/content/en/JobPosting/developer-advocate.mdx +0 -47
- package/templates/content/en/JobPosting/senior-fullstack-engineer.mdx +0 -57
- package/templates/content/en/LandingPage/aeo-audit.mdx +0 -19
- package/templates/content/en/LandingPage/aeo-audit.schema.json +0 -92
- package/templates/content/en/LandingPage/agency-waitlist.mdx +0 -340
- package/templates/content/en/LandingPage/agency-waitlist.schema.json +0 -152
- package/templates/content/en/LandingPage/developers.mdx +0 -19
- package/templates/content/en/LandingPage/developers.schema.json +0 -109
- package/templates/content/en/LandingPage/for-agencies.mdx +0 -390
- package/templates/content/en/LandingPage/for-agencies.schema.json +0 -107
- package/templates/content/en/LandingPage/for-ai-search-agencies.mdx +0 -417
- package/templates/content/en/LandingPage/for-ai-search-agencies.schema.json +0 -105
- package/templates/content/en/LandingPage/for-businesses.mdx +0 -19
- package/templates/content/en/LandingPage/for-businesses.schema.json +0 -96
- package/templates/content/en/LandingPage/platform.mdx +0 -369
- package/templates/content/en/LandingPage/platform.schema.json +0 -166
- package/templates/content/en/LandingPage/vs-ai-website-builders.mdx +0 -19
- package/templates/content/en/LandingPage/vs-ai-website-builders.schema.json +0 -102
- package/templates/content/en/LandingPage/vs-wordpress.mdx +0 -19
- package/templates/content/en/LandingPage/vs-wordpress.schema.json +0 -53
- package/templates/content/en/NewsletterSignup/newsletter.mdx +0 -236
- package/templates/content/en/NewsletterSignup/newsletter.schema.json +0 -91
- package/templates/content/en/Organization/site-owner.mdx +0 -16
- package/templates/content/en/Partner/prisma.mdx +0 -31
- package/templates/content/en/Partner/supabase.mdx +0 -30
- package/templates/content/en/Partner/vercel.mdx +0 -28
- package/templates/content/en/PartnersList/partners.mdx +0 -22
- package/templates/content/en/Person/founder.mdx +0 -18
- package/templates/content/en/Pricing/pricing.mdx +0 -538
- package/templates/content/en/Pricing/pricing.schema.json +0 -209
- package/templates/content/en/PrivacyPage/privacy.mdx +0 -165
- package/templates/content/en/PrivacyPage/privacy.schema.json +0 -64
- package/templates/content/en/Product/ailk.mdx +0 -19
- package/templates/content/en/Product/ailk.schema.json +0 -94
- package/templates/content/en/Product/api-launch-kit.mdx +0 -26
- package/templates/content/en/Product/launch-kit.mdx +0 -28
- package/templates/content/en/ProductsList/products.mdx +0 -26
- package/templates/content/en/Project/ailk-phase-2.mdx +0 -54
- package/templates/content/en/ProjectsList/projects.mdx +0 -25
- package/templates/content/en/ResourceDetail/aeo-scoring-guide.mdx +0 -27
- package/templates/content/en/ResourceDetail/content-model-whitepaper.mdx +0 -28
- package/templates/content/en/ResourceDetail/schema-org-quick-reference.mdx +0 -39
- package/templates/content/en/ResourcesHub/resources.mdx +0 -22
- package/templates/content/en/Service/consulting.mdx +0 -22
- package/templates/content/en/Service/implementation.mdx +0 -30
- package/templates/content/en/Service/launch-service.mdx +0 -232
- package/templates/content/en/Service/launch.mdx +0 -228
- package/templates/content/en/ServicesList/services.mdx +0 -84
- package/templates/content/en/SoftwareProduct/ailk-aeo.mdx +0 -44
- package/templates/content/en/SoftwareProduct/ailk-content-adapters.mdx +0 -47
- package/templates/content/en/SoftwareProduct/ailk-schema.mdx +0 -49
- package/templates/content/en/TeamList/team.mdx +0 -63
- package/templates/content/en/TeamMember/founder.mdx +0 -72
- package/templates/content/en/TermsPage/terms.mdx +0 -19
- package/templates/content/en/TermsPage/terms.schema.json +0 -99
- package/templates/content/en/TestimonialsList/testimonials.mdx +0 -44
- package/templates/content/en/UseCasesList/use-cases.mdx +0 -30
- package/templates/content/en/Whitepaper/ax-first-product-development.mdx +0 -27
- package/templates/content/en/Whitepaper/open-core-commercial-strategy.mdx +0 -27
- package/templates/content/en/Whitepaper/structured-data-for-answer-engines.mdx +0 -31
- package/templates/content/en-XA/AboutPage/about.mdx +0 -8
- package/templates/content/en-XA/FAQPage/faq.mdx +0 -8
- package/templates/content/en-XA/HomePage/home.mdx +0 -8
- package/templates/content/es/_site.mdx +0 -30
- package/templates/content/fr/_site.mdx +0 -30
- package/templates/content/ja/_site.mdx +0 -30
- package/templates/content/pt-BR/AboutPage/about.mdx +0 -8
- package/templates/content/pt-BR/FAQPage/faq.mdx +0 -8
- package/templates/content/pt-BR/HomePage/home.mdx +0 -23
|
@@ -0,0 +1,941 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file usage-aggregation.test.ts
|
|
3
|
+
* @description Unit tests for the usage-aggregation service (ADR 0009 D3
|
|
4
|
+
* service-layer pattern; spec
|
|
5
|
+
* docs/specs/3705-s2-usage-aggregation-service-spec.md §5).
|
|
6
|
+
*
|
|
7
|
+
* External dependency boundary mocked:
|
|
8
|
+
* - apps/api/src/lib/prisma — the repo-standard `__mocks__/prisma.ts`
|
|
9
|
+
* manual mock (`jest.mock("../../lib/prisma.js")`), extended with
|
|
10
|
+
* `usageEvent.aggregate` + `usageBillingReport.upsert` (#3714, FEAT-047
|
|
11
|
+
* P2.S2 — not yet in the generated Prisma client this package compiles
|
|
12
|
+
* against; `aggregate` since #3739 M2, was `findMany`). `usage-aggregation.ts`
|
|
13
|
+
* casts `prisma` to a local structural delegate type
|
|
14
|
+
* (`UsageAggregationPrismaDelegates`); this test does the same so the
|
|
15
|
+
* mock's `jest.fn()` methods type-check the same way the service's calls
|
|
16
|
+
* do.
|
|
17
|
+
*
|
|
18
|
+
* `usageEvent.aggregate` is given a REALISTIC `_sum`/`_count` implementation
|
|
19
|
+
* over an in-memory fixture "table" (mirroring `usage-metering.test.ts`'s
|
|
20
|
+
* `seedMarkupTable` pattern) so the org-isolation (AC-4/AC-UB-10) and
|
|
21
|
+
* period-window tests exercise the actual query-boundary filtering the
|
|
22
|
+
* service relies on, not just a static per-call stub — the fixture applies
|
|
23
|
+
* the SAME `where` filter a real Postgres aggregate would, then sums the
|
|
24
|
+
* matching rows itself (standing in for the DB's SUM).
|
|
25
|
+
*
|
|
26
|
+
* `usageBillingReport.upsert` is given REALISTIC upsert semantics over an
|
|
27
|
+
* in-memory table keyed by the compound `(organizationId, periodStart,
|
|
28
|
+
* periodEnd)` unique constraint, so the idempotency test (AC-2) proves no
|
|
29
|
+
* duplicate row is ever created on re-run — not merely that `upsert` was
|
|
30
|
+
* called twice.
|
|
31
|
+
*
|
|
32
|
+
* COLUMN-WIDTH ENFORCEMENT (#3738 H2 — load-bearing). The upsert fixture parses
|
|
33
|
+
* the REAL `database/content/schema.prisma` at test time, derives each persisted
|
|
34
|
+
* column's representable range from its declared type (`@db.Decimal(p,s)` /
|
|
35
|
+
* `Int` / `BigInt`), and THROWS the same errors Postgres would on overflow
|
|
36
|
+
* (`numeric field overflow`, `integer out of range`).
|
|
37
|
+
*
|
|
38
|
+
* This is what makes the $10k-month / 2.15B-token tests real rather than
|
|
39
|
+
* decorative. With a plain `jest.fn()` upsert an overflow is INVISIBLE — the
|
|
40
|
+
* mock happily accepts any JS number — so the H2 defect (aggregate columns
|
|
41
|
+
* sized for a single event: `Decimal(10,6)` = max $9,999.999999, `Int` = max
|
|
42
|
+
* 2.15B tokens) would sail through a mocked suite untouched, which is exactly
|
|
43
|
+
* how it reached `main`. By grounding the fixture in the actual schema file,
|
|
44
|
+
* the overflow tests FAIL against the pre-fix columns and pass only once the
|
|
45
|
+
* migration widens them — and they can never drift from the schema, because
|
|
46
|
+
* they read it.
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
// eslint-disable-next-line no-restricted-syntax -- lib/prisma.ts wraps the external DB boundary (PrismaClient requires a live connection); __mocks__/prisma.ts is the repo-standard test double for this boundary.
|
|
50
|
+
jest.mock("../../lib/prisma.js");
|
|
51
|
+
|
|
52
|
+
import { readFileSync } from "node:fs";
|
|
53
|
+
import { resolve } from "node:path";
|
|
54
|
+
|
|
55
|
+
import { prisma } from "../../lib/prisma.js";
|
|
56
|
+
import {
|
|
57
|
+
aggregateUsagePeriod,
|
|
58
|
+
type AggregateResult,
|
|
59
|
+
type UsageAggregationPrismaDelegates,
|
|
60
|
+
} from "../usage-aggregation";
|
|
61
|
+
|
|
62
|
+
// The generated Prisma client doesn't carry the FEAT-047 P1 models yet
|
|
63
|
+
// (#3709/#3710) — see the file docblock. Same structural cast the service
|
|
64
|
+
// source uses.
|
|
65
|
+
// eslint-disable-next-line no-restricted-syntax -- prisma's TS type resolves to the real (not-yet-augmented) PrismaClient; the FEAT-047 content-namespace delegates (usageEvent/usageBillingReport, #3709) don't exist on it yet, so the intermediate `unknown` widening is required, not gratuitous — mirrors the identical cast in usage-aggregation.ts.
|
|
66
|
+
const db = prisma as unknown as UsageAggregationPrismaDelegates;
|
|
67
|
+
|
|
68
|
+
/** The delegate methods are typed as plain functions; the mock behind them is a jest.Mock. */
|
|
69
|
+
const mockOf = (fn: unknown): jest.Mock => fn as jest.Mock;
|
|
70
|
+
|
|
71
|
+
const ORG_A = "org_00000000-0000-7000-8000-0000000000a1";
|
|
72
|
+
const ORG_B = "org_00000000-0000-7000-8000-0000000000b2";
|
|
73
|
+
|
|
74
|
+
/** March 2026 (UTC) — the test period. */
|
|
75
|
+
const PERIOD_START = new Date(Date.UTC(2026, 2, 1));
|
|
76
|
+
const PERIOD_END = new Date(Date.UTC(2026, 3, 1)); // April 1, UTC — exclusive upper bound
|
|
77
|
+
/** Any timestamp within the period; the service normalizes to the month start. */
|
|
78
|
+
const MID_PERIOD_DATE = new Date(Date.UTC(2026, 2, 1));
|
|
79
|
+
|
|
80
|
+
// ── Schema-grounded column limits (#3738 H2) ─────────────────────────────────
|
|
81
|
+
// Parsed from the REAL schema so the fixture's overflow behaviour can never
|
|
82
|
+
// drift from the migration. See the file docblock for why this is load-bearing.
|
|
83
|
+
|
|
84
|
+
const SCHEMA_PATH = resolve(
|
|
85
|
+
__dirname,
|
|
86
|
+
"../../../../../database/content/schema.prisma",
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
/** The `UsageBillingReport` model block, verbatim from database/content/schema.prisma. */
|
|
90
|
+
function readReportModelBlock(): string {
|
|
91
|
+
const schema = readFileSync(SCHEMA_PATH, "utf8");
|
|
92
|
+
const match = schema.match(/model\s+UsageBillingReport\s*\{([\s\S]*?)\n\}/);
|
|
93
|
+
if (!match?.[1]) {
|
|
94
|
+
throw new Error(
|
|
95
|
+
`Could not locate the UsageBillingReport model in ${SCHEMA_PATH}`,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
return match[1];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Max value a Postgres `numeric(p, s)` column can hold: 10^(p-s) - 10^-s. */
|
|
102
|
+
function decimalMax(precision: number, scale: number): number {
|
|
103
|
+
return 10 ** (precision - scale) - 10 ** -scale;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const INT4_MAX = 2_147_483_647;
|
|
107
|
+
const INT8_MAX = 9_223_372_036_854_775_807n;
|
|
108
|
+
|
|
109
|
+
type ColumnLimit =
|
|
110
|
+
| { kind: "decimal"; max: number }
|
|
111
|
+
| { kind: "int4"; max: number }
|
|
112
|
+
| { kind: "int8"; max: bigint };
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Derives the representable range of a `UsageBillingReport` field from the
|
|
116
|
+
* live schema — `@db.Decimal(p,s)` -> numeric bounds; bare `Int` -> int4;
|
|
117
|
+
* `BigInt` -> int8.
|
|
118
|
+
*/
|
|
119
|
+
function columnLimit(field: string): ColumnLimit {
|
|
120
|
+
const block = readReportModelBlock();
|
|
121
|
+
const line = block
|
|
122
|
+
.split("\n")
|
|
123
|
+
.find((l) => new RegExp(`^\\s*${field}\\s+\\w`).test(l));
|
|
124
|
+
if (!line) {
|
|
125
|
+
throw new Error(`Field ${field} not found on UsageBillingReport`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const dec = line.match(/@db\.Decimal\((\d+)\s*,\s*(\d+)\)/);
|
|
129
|
+
if (dec) {
|
|
130
|
+
return { kind: "decimal", max: decimalMax(Number(dec[1]), Number(dec[2])) };
|
|
131
|
+
}
|
|
132
|
+
if (/^\s*\w+\s+BigInt\b/.test(line)) return { kind: "int8", max: INT8_MAX };
|
|
133
|
+
if (/^\s*\w+\s+Int\b/.test(line)) return { kind: "int4", max: INT4_MAX };
|
|
134
|
+
throw new Error(`Unrecognised column type for ${field}: ${line.trim()}`);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The persisted columns the service writes, with their schema-derived limits. */
|
|
138
|
+
const PERSISTED_COLUMNS = [
|
|
139
|
+
"totalProviderCost",
|
|
140
|
+
"totalMarkupAmount",
|
|
141
|
+
"totalBilledAmount",
|
|
142
|
+
"totalTokens",
|
|
143
|
+
"eventCount",
|
|
144
|
+
] as const;
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Throws exactly as Postgres would when a written value exceeds its column.
|
|
148
|
+
* This is the check a `jest.fn()` upsert silently skips — and the reason the
|
|
149
|
+
* H2 overflow reached `main`.
|
|
150
|
+
*/
|
|
151
|
+
function assertFitsColumns(data: Record<string, unknown>): void {
|
|
152
|
+
for (const field of PERSISTED_COLUMNS) {
|
|
153
|
+
if (!(field in data)) continue;
|
|
154
|
+
const raw = data[field];
|
|
155
|
+
if (raw === undefined || raw === null) continue;
|
|
156
|
+
|
|
157
|
+
const limit = columnLimit(field);
|
|
158
|
+
const value = typeof raw === "bigint" ? raw : Number(raw);
|
|
159
|
+
|
|
160
|
+
if (limit.kind === "decimal") {
|
|
161
|
+
if (Math.abs(Number(value)) > limit.max) {
|
|
162
|
+
throw new Error(
|
|
163
|
+
`numeric field overflow: a field with precision limit ${limit.max} ` +
|
|
164
|
+
`cannot hold ${String(value)} (column ${field})`,
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
} else if (limit.kind === "int4") {
|
|
168
|
+
if (Math.abs(Number(value)) > limit.max) {
|
|
169
|
+
throw new Error(`integer out of range (column ${field})`);
|
|
170
|
+
}
|
|
171
|
+
} else {
|
|
172
|
+
const asBig =
|
|
173
|
+
typeof value === "bigint" ? value : BigInt(Math.trunc(Number(value)));
|
|
174
|
+
if (asBig > limit.max || asBig < -limit.max) {
|
|
175
|
+
throw new Error(`bigint out of range (column ${field})`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
type FixtureEvent = {
|
|
182
|
+
organizationId: string;
|
|
183
|
+
completionStatus: string;
|
|
184
|
+
createdAt: Date;
|
|
185
|
+
providerCostUsd: unknown;
|
|
186
|
+
billedCostUsd: unknown;
|
|
187
|
+
totalTokens: unknown;
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
/** The in-memory "usage_events" fixture table `aggregate` sums over. */
|
|
191
|
+
let eventTable: FixtureEvent[];
|
|
192
|
+
/** The in-memory "usage_billing_reports" table, keyed by the compound unique constraint. */
|
|
193
|
+
let reportTable: Map<string, Record<string, unknown> & { id: string }>;
|
|
194
|
+
let reportIdCounter: number;
|
|
195
|
+
|
|
196
|
+
function reportKey(organizationId: string, periodStart: Date, periodEnd: Date): string {
|
|
197
|
+
return `${organizationId}|${periodStart.toISOString()}|${periodEnd.toISOString()}`;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Coerces a fixture row's value the same way a real Postgres NOT NULL
|
|
202
|
+
* Decimal/Int column would have to (the fixture's inputs are already
|
|
203
|
+
* numeric or Decimal-shaped by construction — `seedEvent`'s type only
|
|
204
|
+
* accepts those) — mirrors the service's own `toNumber` for Decimal-like
|
|
205
|
+
* `{ toNumber() }` fixture rows (#3738 M1's coercion tests).
|
|
206
|
+
*/
|
|
207
|
+
function fixtureToNumber(value: unknown): number {
|
|
208
|
+
if (typeof value === "number") return value;
|
|
209
|
+
if (
|
|
210
|
+
value !== null &&
|
|
211
|
+
typeof value === "object" &&
|
|
212
|
+
"toNumber" in value &&
|
|
213
|
+
typeof (value as { toNumber: unknown }).toNumber === "function"
|
|
214
|
+
) {
|
|
215
|
+
return (value as { toNumber(): number }).toNumber();
|
|
216
|
+
}
|
|
217
|
+
return Number.NaN;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Installs realistic aggregate() _sum/_count filtering + realistic upsert (insert-or-update, no duplicates). */
|
|
221
|
+
function installFixtureDb() {
|
|
222
|
+
// #3739 M2 — stands in for Postgres's SUM: filters the in-memory table by
|
|
223
|
+
// the same `where` clause a real aggregate query would apply, then sums
|
|
224
|
+
// the matching rows' three columns and reports the count. Returns `null`
|
|
225
|
+
// per `_sum` field when zero rows match (Prisma's own convention), so
|
|
226
|
+
// callers exercise the same null-coalescing path production hits.
|
|
227
|
+
mockOf(db.usageEvent.aggregate).mockImplementation(
|
|
228
|
+
async (args: {
|
|
229
|
+
where: {
|
|
230
|
+
organizationId: string;
|
|
231
|
+
completionStatus: string;
|
|
232
|
+
createdAt: { gte: Date; lt: Date };
|
|
233
|
+
};
|
|
234
|
+
}) => {
|
|
235
|
+
const { organizationId, completionStatus, createdAt } = args.where;
|
|
236
|
+
const matching = eventTable.filter(
|
|
237
|
+
(e) =>
|
|
238
|
+
e.organizationId === organizationId &&
|
|
239
|
+
e.completionStatus === completionStatus &&
|
|
240
|
+
e.createdAt.getTime() >= createdAt.gte.getTime() &&
|
|
241
|
+
e.createdAt.getTime() < createdAt.lt.getTime(),
|
|
242
|
+
);
|
|
243
|
+
if (matching.length === 0) {
|
|
244
|
+
return {
|
|
245
|
+
_sum: { providerCostUsd: null, billedCostUsd: null, totalTokens: null },
|
|
246
|
+
_count: 0,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
let providerCostUsd = 0;
|
|
250
|
+
let billedCostUsd = 0;
|
|
251
|
+
let totalTokens = 0;
|
|
252
|
+
for (const row of matching) {
|
|
253
|
+
providerCostUsd += fixtureToNumber(row.providerCostUsd);
|
|
254
|
+
billedCostUsd += fixtureToNumber(row.billedCostUsd);
|
|
255
|
+
totalTokens += fixtureToNumber(row.totalTokens);
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
_sum: { providerCostUsd, billedCostUsd, totalTokens },
|
|
259
|
+
_count: matching.length,
|
|
260
|
+
};
|
|
261
|
+
},
|
|
262
|
+
);
|
|
263
|
+
|
|
264
|
+
mockOf(db.usageBillingReport.upsert).mockImplementation(
|
|
265
|
+
async (args: {
|
|
266
|
+
where: {
|
|
267
|
+
organizationId_periodStart_periodEnd: {
|
|
268
|
+
organizationId: string;
|
|
269
|
+
periodStart: Date;
|
|
270
|
+
periodEnd: Date;
|
|
271
|
+
};
|
|
272
|
+
};
|
|
273
|
+
create: Record<string, unknown>;
|
|
274
|
+
update: Record<string, unknown>;
|
|
275
|
+
}) => {
|
|
276
|
+
const { organizationId, periodStart, periodEnd } =
|
|
277
|
+
args.where.organizationId_periodStart_periodEnd;
|
|
278
|
+
const key = reportKey(organizationId, periodStart, periodEnd);
|
|
279
|
+
const existing = reportTable.get(key);
|
|
280
|
+
if (existing) {
|
|
281
|
+
// Postgres validates the written values against the column types —
|
|
282
|
+
// so does this fixture (#3738 H2).
|
|
283
|
+
assertFitsColumns(args.update);
|
|
284
|
+
const updated = { ...existing, ...args.update };
|
|
285
|
+
reportTable.set(key, updated);
|
|
286
|
+
return { id: existing.id };
|
|
287
|
+
}
|
|
288
|
+
assertFitsColumns(args.create);
|
|
289
|
+
reportIdCounter += 1;
|
|
290
|
+
const id = `rpt_${reportIdCounter}`;
|
|
291
|
+
const created = { id, ...args.create };
|
|
292
|
+
reportTable.set(key, created);
|
|
293
|
+
return { id };
|
|
294
|
+
},
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** The system-default markup usage-metering falls back to (20%). */
|
|
299
|
+
const DEFAULT_MARKUP = 1.2;
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Seeds one UsageEvent. When `billedCostUsd` is not pinned explicitly it is
|
|
303
|
+
* DERIVED from `providerCostUsd` at the default markup, so the fixture always
|
|
304
|
+
* produces a COHERENT event (billed >= provider), exactly as `recordUsageEvent`
|
|
305
|
+
* writes it.
|
|
306
|
+
*
|
|
307
|
+
* Previously the default was a flat `billedCostUsd: 1.2`, which — paired with
|
|
308
|
+
* an explicit `providerCostUsd: 3` / `999` — silently produced INVERTED events
|
|
309
|
+
* (billed < provider: billing below cost). Those are impossible in production
|
|
310
|
+
* and are now correctly rejected by the money invariants (#3738 M1), so the
|
|
311
|
+
* fixture must model a real event rather than an impossible one. A test that
|
|
312
|
+
* WANTS an inverted row still pins `billedCostUsd` explicitly.
|
|
313
|
+
*/
|
|
314
|
+
function seedEvent(overrides: Partial<FixtureEvent>): void {
|
|
315
|
+
const merged = {
|
|
316
|
+
organizationId: ORG_A,
|
|
317
|
+
completionStatus: "success",
|
|
318
|
+
createdAt: MID_PERIOD_DATE,
|
|
319
|
+
providerCostUsd: 1,
|
|
320
|
+
totalTokens: 1_000,
|
|
321
|
+
...overrides,
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
const billedCostUsd =
|
|
325
|
+
"billedCostUsd" in overrides
|
|
326
|
+
? overrides.billedCostUsd
|
|
327
|
+
: typeof merged.providerCostUsd === "number"
|
|
328
|
+
? merged.providerCostUsd * DEFAULT_MARKUP
|
|
329
|
+
: DEFAULT_MARKUP;
|
|
330
|
+
|
|
331
|
+
eventTable.push({ ...merged, billedCostUsd });
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function expectInvalidInput(result: AggregateResult) {
|
|
335
|
+
expect(result.ok).toBe(false);
|
|
336
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
337
|
+
expect(err.error.kind).toBe("invalid_input");
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
describe("aggregateUsagePeriod", () => {
|
|
341
|
+
beforeEach(() => {
|
|
342
|
+
jest.clearAllMocks();
|
|
343
|
+
jest.spyOn(console, "warn").mockImplementation(() => undefined);
|
|
344
|
+
jest.spyOn(console, "error").mockImplementation(() => undefined);
|
|
345
|
+
eventTable = [];
|
|
346
|
+
reportTable = new Map();
|
|
347
|
+
reportIdCounter = 0;
|
|
348
|
+
installFixtureDb();
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
afterEach(() => {
|
|
352
|
+
jest.restoreAllMocks();
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
// ── AC-1: SUM successful UsageEvents into the totals ──────────────────────
|
|
356
|
+
it("AC-1: SUMs successful UsageEvents into provider/markup/billed/tokens/eventCount", async () => {
|
|
357
|
+
seedEvent({ providerCostUsd: 3, billedCostUsd: 3.6, totalTokens: 1_000_000 });
|
|
358
|
+
seedEvent({ providerCostUsd: 2, billedCostUsd: 2.4, totalTokens: 500_000 });
|
|
359
|
+
|
|
360
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
361
|
+
|
|
362
|
+
expect(result.ok).toBe(true);
|
|
363
|
+
const ok = result as Extract<AggregateResult, { ok: true }>;
|
|
364
|
+
expect(ok.totals).toEqual({
|
|
365
|
+
totalProviderCost: 5,
|
|
366
|
+
totalMarkupAmount: 1,
|
|
367
|
+
totalBilledAmount: 6,
|
|
368
|
+
totalTokens: 1_500_000,
|
|
369
|
+
eventCount: 2,
|
|
370
|
+
includedCents: 0,
|
|
371
|
+
creditBalanceCents: 0,
|
|
372
|
+
onDemandCents: 0,
|
|
373
|
+
});
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
it("AC-1: filters out non-success completionStatus (D2) — an error/pricing_missing event is excluded", async () => {
|
|
377
|
+
seedEvent({ providerCostUsd: 3, billedCostUsd: 3.6, totalTokens: 1_000 });
|
|
378
|
+
seedEvent({
|
|
379
|
+
completionStatus: "error",
|
|
380
|
+
providerCostUsd: 100,
|
|
381
|
+
billedCostUsd: 120,
|
|
382
|
+
totalTokens: 999_999,
|
|
383
|
+
});
|
|
384
|
+
seedEvent({
|
|
385
|
+
completionStatus: "pricing_missing:success",
|
|
386
|
+
providerCostUsd: 0,
|
|
387
|
+
billedCostUsd: 0,
|
|
388
|
+
totalTokens: 999_999,
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
const result = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
|
|
392
|
+
AggregateResult,
|
|
393
|
+
{ ok: true }
|
|
394
|
+
>;
|
|
395
|
+
|
|
396
|
+
expect(result.totals.eventCount).toBe(1);
|
|
397
|
+
expect(result.totals.totalProviderCost).toBe(3);
|
|
398
|
+
expect(result.totals.totalTokens).toBe(1_000);
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
it("AC-1: excludes events outside the period window (before periodStart / at-or-after periodEnd)", async () => {
|
|
402
|
+
seedEvent({
|
|
403
|
+
createdAt: new Date(PERIOD_START.getTime() - 1),
|
|
404
|
+
providerCostUsd: 10,
|
|
405
|
+
}); // just before the window
|
|
406
|
+
seedEvent({ createdAt: PERIOD_START, providerCostUsd: 1 }); // inclusive lower bound
|
|
407
|
+
seedEvent({ createdAt: PERIOD_END, providerCostUsd: 10 }); // exclusive upper bound — excluded
|
|
408
|
+
seedEvent({
|
|
409
|
+
createdAt: new Date(PERIOD_END.getTime() - 1),
|
|
410
|
+
providerCostUsd: 1,
|
|
411
|
+
}); // just inside the window
|
|
412
|
+
|
|
413
|
+
const result = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
|
|
414
|
+
AggregateResult,
|
|
415
|
+
{ ok: true }
|
|
416
|
+
>;
|
|
417
|
+
|
|
418
|
+
expect(result.totals.eventCount).toBe(2);
|
|
419
|
+
expect(result.totals.totalProviderCost).toBe(2);
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
it("a periodStart mid-month normalizes to the calendar-month window", async () => {
|
|
423
|
+
seedEvent({ createdAt: MID_PERIOD_DATE, providerCostUsd: 5 });
|
|
424
|
+
|
|
425
|
+
const midMonth = new Date(Date.UTC(2026, 2, 17, 8, 30));
|
|
426
|
+
const result = (await aggregateUsagePeriod(ORG_A, midMonth)) as Extract<
|
|
427
|
+
AggregateResult,
|
|
428
|
+
{ ok: true }
|
|
429
|
+
>;
|
|
430
|
+
|
|
431
|
+
expect(result.totals.eventCount).toBe(1);
|
|
432
|
+
expect(result.totals.totalProviderCost).toBe(5);
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
// ── AC-2: idempotent getOrCreateReport ─────────────────────────────────────
|
|
436
|
+
describe("AC-2: idempotency", () => {
|
|
437
|
+
it("a second invocation for the same (org, period) UPDATES the same report — no duplicate", async () => {
|
|
438
|
+
seedEvent({ providerCostUsd: 1, billedCostUsd: 1.2, totalTokens: 100 });
|
|
439
|
+
|
|
440
|
+
const first = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
|
|
441
|
+
AggregateResult,
|
|
442
|
+
{ ok: true }
|
|
443
|
+
>;
|
|
444
|
+
|
|
445
|
+
// A second event lands before the re-run — the re-run must reflect it.
|
|
446
|
+
seedEvent({ providerCostUsd: 2, billedCostUsd: 2.4, totalTokens: 200 });
|
|
447
|
+
const second = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
|
|
448
|
+
AggregateResult,
|
|
449
|
+
{ ok: true }
|
|
450
|
+
>;
|
|
451
|
+
|
|
452
|
+
expect(second.reportId).toBe(first.reportId);
|
|
453
|
+
expect(reportTable.size).toBe(1); // no duplicate row
|
|
454
|
+
expect(second.totals.eventCount).toBe(2);
|
|
455
|
+
expect(second.totals.totalProviderCost).toBe(3);
|
|
456
|
+
expect(db.usageBillingReport.upsert).toHaveBeenCalledTimes(2);
|
|
457
|
+
});
|
|
458
|
+
|
|
459
|
+
it("status stays PENDING across a re-run (P2 never advances it)", async () => {
|
|
460
|
+
seedEvent({ providerCostUsd: 1, billedCostUsd: 1.2, totalTokens: 100 });
|
|
461
|
+
await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
462
|
+
await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
463
|
+
|
|
464
|
+
const [record] = Array.from(reportTable.values());
|
|
465
|
+
// The service never writes `status` — the DB default (PENDING) stands,
|
|
466
|
+
// and a re-run's `update` payload must not carry the key either.
|
|
467
|
+
const updateCall = mockOf(db.usageBillingReport.upsert).mock.calls[1]?.[0] as {
|
|
468
|
+
update: Record<string, unknown>;
|
|
469
|
+
};
|
|
470
|
+
expect(updateCall.update).not.toHaveProperty("status");
|
|
471
|
+
expect(record).not.toHaveProperty("status");
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
it("a re-run does not clobber attribution cents a later phase (P3/P4) may have set", async () => {
|
|
475
|
+
seedEvent({ providerCostUsd: 1, billedCostUsd: 1.2, totalTokens: 100 });
|
|
476
|
+
await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
477
|
+
|
|
478
|
+
// Simulate P3/P4 having since applied attribution to the persisted row.
|
|
479
|
+
const [key] = Array.from(reportTable.keys());
|
|
480
|
+
const existing = reportTable.get(key!)!;
|
|
481
|
+
reportTable.set(key!, { ...existing, includedCents: 500 });
|
|
482
|
+
|
|
483
|
+
await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
484
|
+
|
|
485
|
+
const updated = reportTable.get(key!)!;
|
|
486
|
+
expect(updated.includedCents).toBe(500);
|
|
487
|
+
});
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
// ── AC-3 (AC-UB-03a): reconciliation over a full test period ───────────────
|
|
491
|
+
describe("AC-3: reconciliation (AC-UB-03a)", () => {
|
|
492
|
+
it("report totals equal the SUM of source events, and totalBilled == totalProvider * (1 + markup) within tolerance", async () => {
|
|
493
|
+
const MARKUP = 0.2; // 20% — matches the system-default markup usage-metering falls back to
|
|
494
|
+
const events = [
|
|
495
|
+
{ providerCostUsd: 3, tokens: 1_000_000 },
|
|
496
|
+
{ providerCostUsd: 2, tokens: 500_000 },
|
|
497
|
+
{ providerCostUsd: 7.5, tokens: 2_250_000 },
|
|
498
|
+
{ providerCostUsd: 0.333333, tokens: 10_000 },
|
|
499
|
+
];
|
|
500
|
+
let expectedProvider = 0;
|
|
501
|
+
let expectedBilled = 0;
|
|
502
|
+
let expectedTokens = 0;
|
|
503
|
+
for (const e of events) {
|
|
504
|
+
const billed = e.providerCostUsd * (1 + MARKUP);
|
|
505
|
+
seedEvent({
|
|
506
|
+
providerCostUsd: e.providerCostUsd,
|
|
507
|
+
billedCostUsd: billed,
|
|
508
|
+
totalTokens: e.tokens,
|
|
509
|
+
});
|
|
510
|
+
expectedProvider += e.providerCostUsd;
|
|
511
|
+
expectedBilled += billed;
|
|
512
|
+
expectedTokens += e.tokens;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
const result = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
|
|
516
|
+
AggregateResult,
|
|
517
|
+
{ ok: true }
|
|
518
|
+
>;
|
|
519
|
+
|
|
520
|
+
expect(result.totals.totalProviderCost).toBeCloseTo(expectedProvider, 6);
|
|
521
|
+
expect(result.totals.totalBilledAmount).toBeCloseTo(expectedBilled, 6);
|
|
522
|
+
expect(result.totals.totalTokens).toBe(expectedTokens);
|
|
523
|
+
expect(result.totals.eventCount).toBe(events.length);
|
|
524
|
+
|
|
525
|
+
// AC-UB-03a — the reconciliation identity, within tolerance.
|
|
526
|
+
expect(result.totals.totalBilledAmount).toBeCloseTo(
|
|
527
|
+
result.totals.totalProviderCost * (1 + MARKUP),
|
|
528
|
+
6,
|
|
529
|
+
);
|
|
530
|
+
// totalBilled == totalProvider + totalMarkup holds exactly by construction.
|
|
531
|
+
expect(
|
|
532
|
+
result.totals.totalProviderCost + result.totals.totalMarkupAmount,
|
|
533
|
+
).toBeCloseTo(result.totals.totalBilledAmount, 10);
|
|
534
|
+
});
|
|
535
|
+
|
|
536
|
+
it("an empty period reconciles to all-zero totals, not a missing/undefined report", async () => {
|
|
537
|
+
const result = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
|
|
538
|
+
AggregateResult,
|
|
539
|
+
{ ok: true }
|
|
540
|
+
>;
|
|
541
|
+
|
|
542
|
+
expect(result.totals).toEqual({
|
|
543
|
+
totalProviderCost: 0,
|
|
544
|
+
totalMarkupAmount: 0,
|
|
545
|
+
totalBilledAmount: 0,
|
|
546
|
+
totalTokens: 0,
|
|
547
|
+
eventCount: 0,
|
|
548
|
+
includedCents: 0,
|
|
549
|
+
creditBalanceCents: 0,
|
|
550
|
+
onDemandCents: 0,
|
|
551
|
+
});
|
|
552
|
+
});
|
|
553
|
+
});
|
|
554
|
+
|
|
555
|
+
// ── AC-4 (AC-UB-10): org isolation ─────────────────────────────────────────
|
|
556
|
+
describe("AC-4: org isolation (AC-UB-10)", () => {
|
|
557
|
+
it("org A's aggregation never includes org B's events", async () => {
|
|
558
|
+
seedEvent({ organizationId: ORG_A, providerCostUsd: 3, totalTokens: 100 });
|
|
559
|
+
seedEvent({ organizationId: ORG_B, providerCostUsd: 999, totalTokens: 999_999 });
|
|
560
|
+
|
|
561
|
+
const resultA = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
|
|
562
|
+
AggregateResult,
|
|
563
|
+
{ ok: true }
|
|
564
|
+
>;
|
|
565
|
+
|
|
566
|
+
expect(resultA.totals.eventCount).toBe(1);
|
|
567
|
+
expect(resultA.totals.totalProviderCost).toBe(3);
|
|
568
|
+
expect(resultA.totals.totalTokens).toBe(100);
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
it("the query is organizationId-scoped at the boundary, not filtered client-side", async () => {
|
|
572
|
+
seedEvent({ organizationId: ORG_A });
|
|
573
|
+
|
|
574
|
+
await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
575
|
+
|
|
576
|
+
expect(db.usageEvent.aggregate).toHaveBeenCalledWith(
|
|
577
|
+
expect.objectContaining({
|
|
578
|
+
where: expect.objectContaining({ organizationId: ORG_A }),
|
|
579
|
+
}),
|
|
580
|
+
);
|
|
581
|
+
});
|
|
582
|
+
|
|
583
|
+
it("org A and org B get separate reports for the same period", async () => {
|
|
584
|
+
seedEvent({ organizationId: ORG_A, providerCostUsd: 1 });
|
|
585
|
+
seedEvent({ organizationId: ORG_B, providerCostUsd: 2 });
|
|
586
|
+
|
|
587
|
+
const resultA = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
|
|
588
|
+
AggregateResult,
|
|
589
|
+
{ ok: true }
|
|
590
|
+
>;
|
|
591
|
+
const resultB = (await aggregateUsagePeriod(ORG_B, PERIOD_START)) as Extract<
|
|
592
|
+
AggregateResult,
|
|
593
|
+
{ ok: true }
|
|
594
|
+
>;
|
|
595
|
+
|
|
596
|
+
expect(resultA.reportId).not.toBe(resultB.reportId);
|
|
597
|
+
expect(reportTable.size).toBe(2);
|
|
598
|
+
});
|
|
599
|
+
});
|
|
600
|
+
|
|
601
|
+
// ── AC-5: discriminated result, PII-safe logging, invalid-input handling ──
|
|
602
|
+
describe("AC-5: boundary validation + result shape", () => {
|
|
603
|
+
it("rejects a malformed organizationId", async () => {
|
|
604
|
+
const result = await aggregateUsagePeriod("not-an-org-id", PERIOD_START);
|
|
605
|
+
|
|
606
|
+
expectInvalidInput(result);
|
|
607
|
+
expect(db.usageEvent.aggregate).not.toHaveBeenCalled();
|
|
608
|
+
expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
it("rejects an invalid Date", async () => {
|
|
612
|
+
const result = await aggregateUsagePeriod(ORG_A, new Date(NaN));
|
|
613
|
+
|
|
614
|
+
expectInvalidInput(result);
|
|
615
|
+
expect(db.usageEvent.aggregate).not.toHaveBeenCalled();
|
|
616
|
+
});
|
|
617
|
+
|
|
618
|
+
it("the error names the offending field", async () => {
|
|
619
|
+
const result = await aggregateUsagePeriod("not-an-org-id", PERIOD_START);
|
|
620
|
+
|
|
621
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
622
|
+
expect(err.error.message).toContain("organizationId");
|
|
623
|
+
});
|
|
624
|
+
|
|
625
|
+
it("PII/content non-leak — the ok result carries only ids/counts/computed totals", async () => {
|
|
626
|
+
seedEvent({});
|
|
627
|
+
|
|
628
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
629
|
+
|
|
630
|
+
expect(Object.keys(result)).toEqual(
|
|
631
|
+
expect.arrayContaining(["ok", "reportId", "totals"]),
|
|
632
|
+
);
|
|
633
|
+
const ok = result as Extract<AggregateResult, { ok: true }>;
|
|
634
|
+
expect(Object.keys(ok.totals).sort()).toEqual(
|
|
635
|
+
[
|
|
636
|
+
"creditBalanceCents",
|
|
637
|
+
"eventCount",
|
|
638
|
+
"includedCents",
|
|
639
|
+
"onDemandCents",
|
|
640
|
+
"totalBilledAmount",
|
|
641
|
+
"totalMarkupAmount",
|
|
642
|
+
"totalProviderCost",
|
|
643
|
+
"totalTokens",
|
|
644
|
+
].sort(),
|
|
645
|
+
);
|
|
646
|
+
});
|
|
647
|
+
});
|
|
648
|
+
|
|
649
|
+
// ── Non-finite guard — a corrupt row must never poison the persisted report ─
|
|
650
|
+
describe("non-finite guard (fails closed, never persists a poisoned total)", () => {
|
|
651
|
+
it("a NaN-valued stored event fails the aggregation rather than writing NaN", async () => {
|
|
652
|
+
seedEvent({ providerCostUsd: Number.NaN, billedCostUsd: 1, totalTokens: 1 });
|
|
653
|
+
|
|
654
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
655
|
+
|
|
656
|
+
expect(result.ok).toBe(false);
|
|
657
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
658
|
+
expect(err.error.kind).toBe("aggregation_failed");
|
|
659
|
+
expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
|
|
660
|
+
});
|
|
661
|
+
|
|
662
|
+
it("a corrupt Decimal-shaped row (unparseable) fails the aggregation, never persists", async () => {
|
|
663
|
+
seedEvent({ providerCostUsd: "not-a-number", billedCostUsd: 1, totalTokens: 1 });
|
|
664
|
+
|
|
665
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
666
|
+
|
|
667
|
+
expect(result.ok).toBe(false);
|
|
668
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
669
|
+
expect(err.error.kind).toBe("aggregation_failed");
|
|
670
|
+
expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
|
|
671
|
+
});
|
|
672
|
+
|
|
673
|
+
it("a Prisma-Decimal-like row (object with toNumber()) coerces correctly on the happy path", async () => {
|
|
674
|
+
seedEvent({
|
|
675
|
+
providerCostUsd: { toNumber: () => 4 },
|
|
676
|
+
billedCostUsd: { toNumber: () => 4.8 },
|
|
677
|
+
totalTokens: 1_000,
|
|
678
|
+
});
|
|
679
|
+
|
|
680
|
+
const result = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
|
|
681
|
+
AggregateResult,
|
|
682
|
+
{ ok: true }
|
|
683
|
+
>;
|
|
684
|
+
|
|
685
|
+
expect(result.ok).toBe(true);
|
|
686
|
+
expect(result.totals.totalProviderCost).toBe(4);
|
|
687
|
+
expect(result.totals.totalBilledAmount).toBe(4.8);
|
|
688
|
+
});
|
|
689
|
+
});
|
|
690
|
+
|
|
691
|
+
// ── write_failed — the report write itself throws ─────────────────────────
|
|
692
|
+
describe("write_failed", () => {
|
|
693
|
+
it("a report-write failure returns write_failed and does not leak the raw error", async () => {
|
|
694
|
+
seedEvent({ providerCostUsd: 1, billedCostUsd: 1.2, totalTokens: 1 });
|
|
695
|
+
const leaky = new Error(
|
|
696
|
+
`Invalid \`prisma.usageBillingReport.upsert()\` invocation: { organizationId: "${ORG_A}" }`,
|
|
697
|
+
);
|
|
698
|
+
mockOf(db.usageBillingReport.upsert).mockRejectedValueOnce(leaky);
|
|
699
|
+
|
|
700
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
701
|
+
|
|
702
|
+
expect(result.ok).toBe(false);
|
|
703
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
704
|
+
expect(err.error.kind).toBe("write_failed");
|
|
705
|
+
expect(err.error.message).not.toContain(ORG_A);
|
|
706
|
+
expect(err.error.message).not.toContain("prisma");
|
|
707
|
+
expect(console.error).toHaveBeenCalled();
|
|
708
|
+
});
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
// ── H1 (#3738): the READ path is inside the error guard ───────────────────
|
|
712
|
+
// Before the fix, the read (findMany, then aggregate since #3739 M2) sat
|
|
713
|
+
// OUTSIDE the try/catch, so a DB read error rejected the promise instead of
|
|
714
|
+
// returning the discriminated union the docblock promises ("Never
|
|
715
|
+
// throws"). #3717's route will trust that union.
|
|
716
|
+
describe("H1: read-path error guard (the union contract holds on a read failure)", () => {
|
|
717
|
+
it("a DB read failure returns a discriminated result rather than throwing", async () => {
|
|
718
|
+
mockOf(db.usageEvent.aggregate).mockRejectedValueOnce(
|
|
719
|
+
new Error("connection pool timeout"),
|
|
720
|
+
);
|
|
721
|
+
|
|
722
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
723
|
+
|
|
724
|
+
expect(result.ok).toBe(false);
|
|
725
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
726
|
+
expect(err.error.kind).toBe("read_failed");
|
|
727
|
+
// Fails closed — a failed read must never write a (zeroed) report.
|
|
728
|
+
expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
|
|
729
|
+
});
|
|
730
|
+
|
|
731
|
+
it("a read failure does not leak the tenant id or the raw Prisma error", async () => {
|
|
732
|
+
// Prisma read errors embed the `where` clause — which carries the org id.
|
|
733
|
+
const leaky = new Error(
|
|
734
|
+
`Invalid \`prisma.usageEvent.aggregate()\` invocation: { where: { organizationId: "${ORG_A}" } }`,
|
|
735
|
+
);
|
|
736
|
+
mockOf(db.usageEvent.aggregate).mockRejectedValueOnce(leaky);
|
|
737
|
+
|
|
738
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
739
|
+
|
|
740
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
741
|
+
expect(err.error.message).not.toContain(ORG_A);
|
|
742
|
+
expect(err.error.message).not.toContain("prisma");
|
|
743
|
+
// The detail is logged server-side only.
|
|
744
|
+
expect(console.error).toHaveBeenCalled();
|
|
745
|
+
});
|
|
746
|
+
});
|
|
747
|
+
|
|
748
|
+
// ── H2a (#3738): the aggregate columns can represent a real month ─────────
|
|
749
|
+
// These are the load-bearing tests. The upsert fixture enforces the REAL
|
|
750
|
+
// schema's column widths (see the file docblock), so both cases FAIL against
|
|
751
|
+
// the pre-fix `Decimal(10,6)` / `Int` columns — the exact defect that stalls
|
|
752
|
+
// billing forever for the largest tenants.
|
|
753
|
+
describe("H2a: aggregate columns hold a large month (schema-grounded)", () => {
|
|
754
|
+
it("a $10,000+ provider-cost month aggregates and persists", async () => {
|
|
755
|
+
// 3 × $4,000 = $12,000 provider — past the old Decimal(10,6) ceiling
|
|
756
|
+
// ($9,999.999999), which made the upsert throw and permanently stall the
|
|
757
|
+
// report for this org.
|
|
758
|
+
for (let i = 0; i < 3; i += 1) {
|
|
759
|
+
seedEvent({
|
|
760
|
+
providerCostUsd: 4_000,
|
|
761
|
+
billedCostUsd: 4_800,
|
|
762
|
+
totalTokens: 1_000,
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
767
|
+
|
|
768
|
+
expect(result.ok).toBe(true);
|
|
769
|
+
const ok = result as Extract<AggregateResult, { ok: true }>;
|
|
770
|
+
expect(ok.totals.totalProviderCost).toBe(12_000);
|
|
771
|
+
expect(ok.totals.totalBilledAmount).toBe(14_400);
|
|
772
|
+
expect(ok.totals.totalMarkupAmount).toBe(2_400);
|
|
773
|
+
// The report row actually exists — billing did not stall.
|
|
774
|
+
expect(reportTable.size).toBe(1);
|
|
775
|
+
});
|
|
776
|
+
|
|
777
|
+
it("a >2.15B-token month aggregates and persists", async () => {
|
|
778
|
+
// 3 × 800M = 2.4B tokens — past the old int4 ceiling (2,147,483,647).
|
|
779
|
+
// ~700k requests at 3k tokens: one busy tenant.
|
|
780
|
+
for (let i = 0; i < 3; i += 1) {
|
|
781
|
+
seedEvent({
|
|
782
|
+
providerCostUsd: 1,
|
|
783
|
+
billedCostUsd: 1.2,
|
|
784
|
+
totalTokens: 800_000_000,
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
789
|
+
|
|
790
|
+
expect(result.ok).toBe(true);
|
|
791
|
+
const ok = result as Extract<AggregateResult, { ok: true }>;
|
|
792
|
+
expect(ok.totals.totalTokens).toBe(2_400_000_000);
|
|
793
|
+
expect(reportTable.size).toBe(1);
|
|
794
|
+
});
|
|
795
|
+
|
|
796
|
+
it("totalTokens is written as a BigInt (the widened int8 column)", async () => {
|
|
797
|
+
seedEvent({ totalTokens: 3_000_000_000 });
|
|
798
|
+
|
|
799
|
+
await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
800
|
+
|
|
801
|
+
const createCall = mockOf(db.usageBillingReport.upsert).mock
|
|
802
|
+
.calls[0]?.[0] as { create: Record<string, unknown> };
|
|
803
|
+
expect(typeof createCall.create.totalTokens).toBe("bigint");
|
|
804
|
+
expect(createCall.create.totalTokens).toBe(3_000_000_000n);
|
|
805
|
+
});
|
|
806
|
+
|
|
807
|
+
it("the schema itself declares aggregate-sized columns (guards against a schema regression)", () => {
|
|
808
|
+
// Asserted directly against database/content/schema.prisma so a future
|
|
809
|
+
// narrowing of these columns fails here, not in production billing.
|
|
810
|
+
const provider = columnLimit("totalProviderCost");
|
|
811
|
+
const billed = columnLimit("totalBilledAmount");
|
|
812
|
+
const markup = columnLimit("totalMarkupAmount");
|
|
813
|
+
const tokens = columnLimit("totalTokens");
|
|
814
|
+
|
|
815
|
+
// Must comfortably clear a $10k month (the old ceiling).
|
|
816
|
+
for (const usd of [provider, billed, markup]) {
|
|
817
|
+
expect(usd.kind).toBe("decimal");
|
|
818
|
+
expect(usd.max as number).toBeGreaterThan(1_000_000);
|
|
819
|
+
}
|
|
820
|
+
// Must be int8 — int4 tops out at 2.15B tokens.
|
|
821
|
+
expect(tokens.kind).toBe("int8");
|
|
822
|
+
});
|
|
823
|
+
});
|
|
824
|
+
|
|
825
|
+
// ── H2b (#3738): a pre-write bounds assertion, LOUD and alertable ─────────
|
|
826
|
+
// Fail-closed is right, but the failure must be DISTINGUISHABLE — a generic
|
|
827
|
+
// `write_failed` + a bare console.error is how silent, permanent,
|
|
828
|
+
// largest-customer revenue loss goes unnoticed.
|
|
829
|
+
describe("H2b: bounds assertion fails closed with a distinct, alertable kind", () => {
|
|
830
|
+
it("a total beyond the representable range returns aggregate_overflow, not write_failed", async () => {
|
|
831
|
+
// Past the service's own MAX_TOTAL_USD cap. Reached here via two large
|
|
832
|
+
// rows; in production, via a corrupt row or an org past the cap. Either
|
|
833
|
+
// way the guard protects the TOTAL, however it is arrived at.
|
|
834
|
+
seedEvent({ providerCostUsd: 6e8, billedCostUsd: 7e8, totalTokens: 1 });
|
|
835
|
+
seedEvent({ providerCostUsd: 6e8, billedCostUsd: 7e8, totalTokens: 1 });
|
|
836
|
+
|
|
837
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
838
|
+
|
|
839
|
+
expect(result.ok).toBe(false);
|
|
840
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
841
|
+
expect(err.error.kind).toBe("aggregate_overflow");
|
|
842
|
+
// Distinct from the generic write failure — this is the alertable signal.
|
|
843
|
+
expect(err.error.kind).not.toBe("write_failed");
|
|
844
|
+
// Never persists a truncated/overflowed total.
|
|
845
|
+
expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
|
|
846
|
+
});
|
|
847
|
+
|
|
848
|
+
it("a token total beyond MAX_SAFE_INTEGER returns aggregate_overflow", async () => {
|
|
849
|
+
seedEvent({ totalTokens: 9e15 });
|
|
850
|
+
seedEvent({ totalTokens: 9e15 });
|
|
851
|
+
|
|
852
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
853
|
+
|
|
854
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
855
|
+
expect(err.error.kind).toBe("aggregate_overflow");
|
|
856
|
+
expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
|
|
857
|
+
});
|
|
858
|
+
|
|
859
|
+
it("the overflow is logged as an alertable event, not a bare generic error", async () => {
|
|
860
|
+
seedEvent({ providerCostUsd: 6e8, billedCostUsd: 7e8 });
|
|
861
|
+
seedEvent({ providerCostUsd: 6e8, billedCostUsd: 7e8 });
|
|
862
|
+
|
|
863
|
+
await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
864
|
+
|
|
865
|
+
// The log line must name the overflow so it can be alerted on.
|
|
866
|
+
const logged = mockOf(console.error).mock.calls.flat().map(String).join(" ");
|
|
867
|
+
expect(logged).toMatch(/overflow/i);
|
|
868
|
+
});
|
|
869
|
+
|
|
870
|
+
it("the assertion fires BEFORE the column limit, so Postgres never overflows", async () => {
|
|
871
|
+
// The service's cap ($1B) sits far below the column capacity
|
|
872
|
+
// (Decimal(20,6) ≈ $1e14), so the loud assertion is always the gate —
|
|
873
|
+
// the DB's silent numeric overflow is unreachable.
|
|
874
|
+
const cap = columnLimit("totalProviderCost");
|
|
875
|
+
expect(cap.kind).toBe("decimal");
|
|
876
|
+
expect(cap.max as number).toBeGreaterThan(1e9);
|
|
877
|
+
});
|
|
878
|
+
});
|
|
879
|
+
|
|
880
|
+
// ── M1 (#3738): the money guard checks non-negative, not just finite ──────
|
|
881
|
+
// A negative total is FINITE — it sails through a finite-only guard and
|
|
882
|
+
// persists as a credit. This is the class that produced the sibling's bug.
|
|
883
|
+
describe("M1: non-negative + reconciliation guard", () => {
|
|
884
|
+
it("a negative provider cost fails closed rather than persisting a credit", async () => {
|
|
885
|
+
seedEvent({ providerCostUsd: -5, billedCostUsd: 1, totalTokens: 1 });
|
|
886
|
+
|
|
887
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
888
|
+
|
|
889
|
+
expect(result.ok).toBe(false);
|
|
890
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
891
|
+
expect(err.error.kind).toBe("aggregation_failed");
|
|
892
|
+
expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
|
|
893
|
+
});
|
|
894
|
+
|
|
895
|
+
it("a billed total below the provider total (negative markup) fails closed", async () => {
|
|
896
|
+
seedEvent({ providerCostUsd: 10, billedCostUsd: 5, totalTokens: 1 });
|
|
897
|
+
|
|
898
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
899
|
+
|
|
900
|
+
expect(result.ok).toBe(false);
|
|
901
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
902
|
+
expect(err.error.kind).toBe("aggregation_failed");
|
|
903
|
+
expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
|
|
904
|
+
});
|
|
905
|
+
|
|
906
|
+
it("a negative token count fails closed", async () => {
|
|
907
|
+
seedEvent({ totalTokens: -100 });
|
|
908
|
+
|
|
909
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
910
|
+
|
|
911
|
+
expect(result.ok).toBe(false);
|
|
912
|
+
expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
|
|
913
|
+
});
|
|
914
|
+
});
|
|
915
|
+
|
|
916
|
+
// ── L1 (#3738): toNumber must not coerce an unusable value to a silent 0 ──
|
|
917
|
+
describe("L1: unusable column values fail closed, never coerce to a silent zero", () => {
|
|
918
|
+
it("a null money column fails the aggregation rather than underbilling as 0", async () => {
|
|
919
|
+
// `Number(null) === 0` — the old coercion silently DROPPED the row's cost
|
|
920
|
+
// (an underbill) instead of the NaN the docblock claimed it produced.
|
|
921
|
+
seedEvent({ providerCostUsd: null, billedCostUsd: 1, totalTokens: 1 });
|
|
922
|
+
|
|
923
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
924
|
+
|
|
925
|
+
expect(result.ok).toBe(false);
|
|
926
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
927
|
+
expect(err.error.kind).toBe("aggregation_failed");
|
|
928
|
+
expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
|
|
929
|
+
});
|
|
930
|
+
|
|
931
|
+
it("an empty-string money column fails the aggregation (Number('') === 0)", async () => {
|
|
932
|
+
seedEvent({ providerCostUsd: "", billedCostUsd: 1, totalTokens: 1 });
|
|
933
|
+
|
|
934
|
+
const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
|
|
935
|
+
|
|
936
|
+
const err = result as Extract<AggregateResult, { ok: false }>;
|
|
937
|
+
expect(err.error.kind).toBe("aggregation_failed");
|
|
938
|
+
expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
|
|
939
|
+
});
|
|
940
|
+
});
|
|
941
|
+
});
|