@happyvertical/smrt-subscriptions 0.60.15 → 0.60.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/AGENTS.md +78 -0
  2. package/README.md +195 -0
  3. package/dist/billing/apply.d.ts +52 -0
  4. package/dist/billing/apply.d.ts.map +1 -0
  5. package/dist/billing/checkout-sessions.d.ts +99 -0
  6. package/dist/billing/checkout-sessions.d.ts.map +1 -0
  7. package/dist/billing/config.d.ts +64 -0
  8. package/dist/billing/config.d.ts.map +1 -0
  9. package/dist/billing/events.d.ts +49 -0
  10. package/dist/billing/events.d.ts.map +1 -0
  11. package/dist/billing/host.d.ts +3 -0
  12. package/dist/billing/host.d.ts.map +1 -0
  13. package/dist/billing/index.d.ts +4 -0
  14. package/dist/billing/index.d.ts.map +1 -0
  15. package/dist/billing/plans.d.ts +45 -0
  16. package/dist/billing/plans.d.ts.map +1 -0
  17. package/dist/billing/signing.d.ts +24 -0
  18. package/dist/billing/signing.d.ts.map +1 -0
  19. package/dist/billing/types.d.ts +265 -0
  20. package/dist/billing/types.d.ts.map +1 -0
  21. package/dist/index.d.ts +3 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1648 -26
  24. package/dist/index.js.map +1 -1
  25. package/dist/manifest.json +313 -4
  26. package/dist/models/BillingCheckoutSession.d.ts +39 -0
  27. package/dist/models/BillingCheckoutSession.d.ts.map +1 -0
  28. package/dist/models/index.d.ts +1 -0
  29. package/dist/models/index.d.ts.map +1 -1
  30. package/dist/recipes.d.ts +1 -1
  31. package/dist/smrt-knowledge.json +101 -8
  32. package/dist/smrt-knowledge.okf.md +5 -2
  33. package/dist/svelte/CommercialOverview.svelte +37 -11
  34. package/dist/svelte/PlanPicker.svelte +18 -17
  35. package/dist/svelte/SubscriptionSummary.svelte +13 -11
  36. package/dist/svelte/UsageThresholds.svelte +21 -17
  37. package/dist/vault-account/actions.d.ts +24 -0
  38. package/dist/vault-account/actions.d.ts.map +1 -0
  39. package/dist/vault-account/errors.d.ts +20 -0
  40. package/dist/vault-account/errors.d.ts.map +1 -0
  41. package/dist/vault-account/index.d.ts +5 -0
  42. package/dist/vault-account/index.d.ts.map +1 -0
  43. package/dist/vault-account/relay-admin-client.d.ts +10 -0
  44. package/dist/vault-account/relay-admin-client.d.ts.map +1 -0
  45. package/dist/vault-account/types.d.ts +115 -0
  46. package/dist/vault-account/types.d.ts.map +1 -0
  47. package/package.json +9 -7
package/dist/index.js CHANGED
@@ -3,28 +3,117 @@ import { _ as subscriberToColumns, a as samePlanTerms, c as deterministicUuid, d
3
3
  import { r as SubscriptionPlan, t as SubscriptionPlanCollection } from "./chunks/SubscriptionPlanCollection-Dmkorx_Q.js";
4
4
  import { r as SubscriptionPlanVersion, t as SubscriptionPlanVersionCollection } from "./chunks/SubscriptionPlanVersionCollection-yTE_Y-2z.js";
5
5
  import { r as snapshotLegacyPlanVersion, t as pinSubscriptionPlanVersion } from "./chunks/plan-versioning-ChDyHPvn.js";
6
- import { ObjectRegistry, SmrtCollection, SmrtObject, SmrtRecipe, classifyDatabaseError, crossPackageRef, field, foreignKey, isDatabaseInterface, isEmbeddedDatabase, isPostgresDatabase, smrt, usesPostgresDialect, withEmbeddedWriteTransaction } from "@happyvertical/smrt-core";
7
- import { TenantIsolationError, TenantScoped, getTenantId, isSuperAdminBypass, isSystemContext, tenantId, withSystemContext } from "@happyvertical/smrt-tenancy";
6
+ import { ObjectRegistry, RUN_ONCE_CLAIMS_TABLE, RunOnceClaimError, SmrtCollection, SmrtObject, SmrtRecipe, classifyDatabaseError, crossPackageRef, deriveRunOnceClaimKey, digestRunOnceContent, field, foreignKey, isDatabaseInterface, isEmbeddedDatabase, isPostgresDatabase, runOnce, smrt, usesPostgresDialect, withEmbeddedWriteTransaction } from "@happyvertical/smrt-core";
7
+ import { TenantIsolationError, TenantScoped, getTenantId, isSuperAdminBypass, isSystemContext, tenantId, withSystemContext, withTenant } from "@happyvertical/smrt-tenancy";
8
8
  import { preflightMinorUnitsRescale, rescaleMoneyColumnsToMinorUnits } from "@happyvertical/smrt-core/migrations";
9
+ import { DEFAULT_STEP_UP_MAX_AGE_SECONDS, StepUpRequiredError, isTenantOwnerSession, requireRecentAuthentication } from "@happyvertical/smrt-users/step-up";
9
10
  //#region src/__smrt-register__.ts
10
- ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-subscriptions","packageVersion":"0.60.15","objects":{"@happyvertical/smrt-subscriptions:SubscriptionPlanCollection":{"name":"subscriptionplancollection","className":"SubscriptionPlanCollection","qualifiedName":"@happyvertical/smrt-subscriptions:SubscriptionPlanCollection","collection":"subscriptionplans","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/collections/SubscriptionPlanCollection.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{"findByPlanKey":{"name":"findByPlanKey","async":true,"parameters":[{"name":"tenantId","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]},{"name":"planKey","type":"string","optional":false}],"returnType":"Promise<SubscriptionPlan | null>","isStatic":false,"isPublic":true},"findActive":{"name":"findActive","async":true,"parameters":[],"returnType":"Promise<SubscriptionPlan[]>","isStatic":false,"isPublic":true},"findByProviderPriceId":{"name":"findByProviderPriceId","async":true,"parameters":[{"name":"providerPriceId","type":"string","optional":false}],"returnType":"Promise<SubscriptionPlan | null>","isStatic":false,"isPublic":true},"findByStripePriceId":{"name":"findByStripePriceId","async":true,"parameters":[{"name":"stripePriceId","type":"string","optional":false}],"returnType":"Promise<SubscriptionPlan | null>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_subscription_plans","api":{"include":["list","get","create","update"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"SubscriptionPlan","exportName":"SubscriptionPlanCollection","collectionExportName":"SubscriptionPlanCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:SubscriptionPlan","inheritedExposure":["api","mcp"],"schema":{"tableName":"_smrt_subscription_plans","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_subscription_plans\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"plan_key\\" TEXT DEFAULT '',\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT '',\\n \\"status\\" TEXT DEFAULT 'active',\\n \\"sort_order\\" INTEGER DEFAULT 0,\\n \\"price_amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"billing_interval\\" TEXT DEFAULT 'month',\\n \\"pricing_mode\\" TEXT DEFAULT 'fixed',\\n \\"minimum_amount\\" INTEGER DEFAULT 0,\\n \\"suggested_amount\\" INTEGER DEFAULT 0,\\n \\"external_provider\\" TEXT,\\n \\"provider_product_id\\" TEXT,\\n \\"provider_price_id\\" TEXT,\\n \\"stripe_product_id\\" TEXT,\\n \\"stripe_price_id\\" TEXT,\\n \\"features\\" TEXT DEFAULT '[]',\\n \\"thresholds\\" TEXT DEFAULT '[]',\\n \\"metadata\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"plan_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"active"},"sort_order":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"price_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"billing_interval":{"type":"TEXT","notNull":false,"unique":false,"default":"month"},"pricing_mode":{"type":"TEXT","notNull":false,"unique":false,"default":"fixed"},"minimum_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"suggested_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"external_provider":{"type":"TEXT","notNull":false,"unique":false},"provider_product_id":{"type":"TEXT","notNull":false,"unique":false},"provider_price_id":{"type":"TEXT","notNull":false,"unique":false},"stripe_product_id":{"type":"TEXT","notNull":false,"unique":false},"stripe_price_id":{"type":"TEXT","notNull":false,"unique":false},"features":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"thresholds":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_subscription_plans_tenant_id_plan_key_idx","columns":["tenant_id","plan_key"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_subscription_plans_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_subscription_plans_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"458e59be"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:SubscriptionPlanVersionCollection":{"name":"subscriptionplanversioncollection","className":"SubscriptionPlanVersionCollection","qualifiedName":"@happyvertical/smrt-subscriptions:SubscriptionPlanVersionCollection","collection":"subscriptionplanversions","description":"Effective-dated plan versions (#4032).","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/collections/SubscriptionPlanVersionCollection.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{"findVisibleById":{"name":"findVisibleById","async":true,"parameters":[{"name":"id","type":"string","optional":false}],"returnType":"Promise<SubscriptionPlanVersion | null>","isStatic":false,"isPublic":true},"listForPlan":{"name":"listForPlan","async":true,"parameters":[{"name":"planId","type":"string","optional":false}],"returnType":"Promise<SubscriptionPlanVersion[]>","isStatic":false,"isPublic":true},"findLatest":{"name":"findLatest","async":true,"parameters":[{"name":"planId","type":"string","optional":false},{"name":"tenantId","type":"string | null","optional":true,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<SubscriptionPlanVersion | null>","isStatic":false,"isPublic":true},"findInForce":{"name":"findInForce","async":true,"parameters":[{"name":"planId","type":"string","optional":false},{"name":"at","type":"Date","optional":false}],"returnType":"Promise<SubscriptionPlanVersion | null>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_subscription_plan_versions","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"SubscriptionPlanVersion","exportName":"SubscriptionPlanVersionCollection","collectionExportName":"SubscriptionPlanVersionCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:SubscriptionPlanVersion","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_subscription_plan_versions","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_subscription_plan_versions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"plan_id\\" UUID,\\n \\"plan_key\\" TEXT DEFAULT '',\\n \\"version\\" INTEGER DEFAULT 0,\\n \\"effective_from\\" TIMESTAMP,\\n \\"name\\" TEXT DEFAULT '',\\n \\"status\\" TEXT DEFAULT 'active',\\n \\"price_amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"billing_interval\\" TEXT DEFAULT 'month',\\n \\"pricing_mode\\" TEXT DEFAULT 'fixed',\\n \\"minimum_amount\\" INTEGER DEFAULT 0,\\n \\"suggested_amount\\" INTEGER DEFAULT 0,\\n \\"features\\" TEXT DEFAULT '[]',\\n \\"thresholds\\" TEXT DEFAULT '[]'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"plan_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_subscription_plans","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"plan_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"version":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"effective_from":{"type":"TIMESTAMP","notNull":false,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"active"},"price_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"billing_interval":{"type":"TEXT","notNull":false,"unique":false,"default":"month"},"pricing_mode":{"type":"TEXT","notNull":false,"unique":false,"default":"fixed"},"minimum_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"suggested_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"features":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"thresholds":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"}},"indexes":[{"name":"_smrt_subscription_plan_versions_plan_id_version_idx","columns":["plan_id","version"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_subscription_plan_versions_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_subscription_plan_versions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"f42156f9"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:TenantSubscriptionCollection":{"name":"tenantsubscriptioncollection","className":"TenantSubscriptionCollection","qualifiedName":"@happyvertical/smrt-subscriptions:TenantSubscriptionCollection","collection":"tenantsubscriptions","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/collections/TenantSubscriptionCollection.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{"findByTenant":{"name":"findByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<TenantSubscription[]>","isStatic":false,"isPublic":true},"findCurrentForTenant":{"name":"findCurrentForTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"now","type":"any","optional":true}],"returnType":"Promise<TenantSubscription | null>","isStatic":false,"isPublic":true},"findCurrentForSubscriber":{"name":"findCurrentForSubscriber","async":true,"parameters":[{"name":"subscriber","type":"Subscriber","optional":false},{"name":"now","type":"any","optional":true}],"returnType":"Promise<TenantSubscription | null>","isStatic":false,"isPublic":true},"findByStripeSubscriptionId":{"name":"findByStripeSubscriptionId","async":true,"parameters":[{"name":"stripeSubscriptionId","type":"string","optional":false}],"returnType":"Promise<TenantSubscription | null>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_tenant_subscriptions","api":{"include":["list","get","create","update"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"TenantSubscription","exportName":"TenantSubscriptionCollection","collectionExportName":"TenantSubscriptionCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:TenantSubscription","inheritedExposure":["api","mcp"],"schema":{"tableName":"_smrt_tenant_subscriptions","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_tenant_subscriptions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"plan_id\\" UUID,\\n \\"status\\" TEXT DEFAULT 'incomplete',\\n \\"started_at\\" TIMESTAMP,\\n \\"current_period_start\\" TIMESTAMP,\\n \\"current_period_end\\" TIMESTAMP,\\n \\"trial_ends_at\\" TIMESTAMP,\\n \\"cancel_at_period_end\\" BOOLEAN DEFAULT FALSE,\\n \\"canceled_at\\" TIMESTAMP,\\n \\"agreed_amount\\" INTEGER,\\n \\"plan_version_id\\" UUID,\\n \\"plan_version_pinned_at\\" TIMESTAMP,\\n \\"plan_version_pin_reason\\" TEXT,\\n \\"plan_version_pin_note\\" TEXT DEFAULT '',\\n \\"retains_paid_period\\" BOOLEAN DEFAULT FALSE,\\n \\"external_provider\\" TEXT,\\n \\"stripe_customer_id\\" TEXT DEFAULT '',\\n \\"stripe_subscription_id\\" TEXT DEFAULT '',\\n \\"stripe_checkout_session_id\\" TEXT DEFAULT '',\\n \\"metadata\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"plan_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_subscription_plans","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"incomplete"},"started_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"current_period_start":{"type":"TIMESTAMP","notNull":false,"unique":false},"current_period_end":{"type":"TIMESTAMP","notNull":false,"unique":false},"trial_ends_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"cancel_at_period_end":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"canceled_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"agreed_amount":{"type":"INTEGER","notNull":false,"unique":false},"plan_version_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_subscription_plan_versions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"plan_version_pinned_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"plan_version_pin_reason":{"type":"TEXT","notNull":false,"unique":false},"plan_version_pin_note":{"type":"TEXT","notNull":false,"unique":false,"default":""},"retains_paid_period":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"external_provider":{"type":"TEXT","notNull":false,"unique":false},"stripe_customer_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"stripe_subscription_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"stripe_checkout_session_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_tenant_subscriptions_tenant_id_subscriber_kind_idx","columns":["tenant_id","subscriber_kind","subscriber_external_id"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_tenant_subscriptions_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_tenant_subscriptions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_tenant_subscriptions_plan_id_idx","columns":["plan_id"]},{"name":"_smrt_tenant_subscriptions_plan_version_id_idx","columns":["plan_version_id"]}],"version":"c281741d"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:TenantUsageMetricCollection":{"name":"tenantusagemetriccollection","className":"TenantUsageMetricCollection","qualifiedName":"@happyvertical/smrt-subscriptions:TenantUsageMetricCollection","collection":"tenantusagemetrics","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/collections/TenantUsageMetricCollection.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{"recordUsage":{"name":"recordUsage","async":true,"parameters":[{"name":"options","type":"RecordUsageOptions","optional":false}],"returnType":"Promise<TenantUsageMetric>","isStatic":false,"isPublic":true},"findByTenantAndMetric":{"name":"findByTenantAndMetric","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"metricKey","type":"string","optional":false}],"returnType":"Promise<TenantUsageMetric[]>","isStatic":false,"isPublic":true},"summarizeUsage":{"name":"summarizeUsage","async":true,"parameters":[{"name":"options","type":"SummarizeUsageOptions","optional":false}],"returnType":"Promise<UsageSummary>","isStatic":false,"isPublic":true},"summarizeUsageBatch":{"name":"summarizeUsageBatch","async":true,"parameters":[{"name":"options","type":"SummarizeUsageBatchOptions","optional":false}],"returnType":"Promise<UsageSummary[]>","isStatic":false,"isPublic":true},"summarizeTenantAiUsage":{"name":"summarizeTenantAiUsage","async":true,"parameters":[{"name":"options","type":"SummarizeAiUsageOptions","optional":false}],"returnType":"Promise<AiUsageSummary>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_tenant_usage_metrics","api":{"include":["list","get","create"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get","create"]}},"extends":"SmrtCollection","extendsTypeArg":"TenantUsageMetric","exportName":"TenantUsageMetricCollection","collectionExportName":"TenantUsageMetricCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:TenantUsageMetric","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_tenant_usage_metrics","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_tenant_usage_metrics\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"quantity\\" REAL DEFAULT 0,\\n \\"window_start\\" TIMESTAMP,\\n \\"window_end\\" TIMESTAMP,\\n \\"source\\" TEXT DEFAULT '',\\n \\"source_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"work_ref_type\\" TEXT DEFAULT '',\\n \\"work_ref_id\\" TEXT DEFAULT '',\\n \\"provider\\" TEXT DEFAULT '',\\n \\"dimensions\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"quantity":{"type":"REAL","notNull":false,"unique":false,"default":0},"window_start":{"type":"TIMESTAMP","notNull":false,"unique":false},"window_end":{"type":"TIMESTAMP","notNull":false,"unique":false},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_type":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":""},"dimensions":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_tenant_usage_metrics_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_tenant_usage_metrics_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"4884a70d"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:SubscriptionPlan":{"name":"subscriptionplan","className":"SubscriptionPlan","qualifiedName":"@happyvertical/smrt-subscriptions:SubscriptionPlan","collection":"subscriptionplans","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/SubscriptionPlan.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"planKey":{"type":"text","required":false,"default":"","description":"A short code that identifies the plan, such as starter or pro.","_meta":{"description":"A short code that identifies the plan, such as starter or pro."}},"name":{"type":"text","required":false,"default":"","description":"What the plan is called, as customers see it.","_meta":{"description":"What the plan is called, as customers see it."}},"description":{"type":"text","required":false,"default":"","description":"A sentence or two about what the plan offers.","_meta":{"description":"A sentence or two about what the plan offers."}},"status":{"type":"text","required":false,"default":"active","description":"Whether the plan is a draft, on sale (active) or archived.","_meta":{"description":"Whether the plan is a draft, on sale (active) or archived."},"enum":["active","archived","draft"]},"sortOrder":{"type":"integer","required":false,"default":0,"description":"Where the plan sits when plans are listed; lower numbers come first.","_meta":{"description":"Where the plan sits when plans are listed; lower numbers come first."}},"priceAmount":{"type":"integer","required":false,"default":0,"description":"What the plan costs each billing period, in cents, as a whole number.","_meta":{"description":"What the plan costs each billing period, in cents, as a whole number."}},"currency":{"type":"text","required":false,"default":"USD","description":"The currency the price is in, such as USD.","_meta":{"description":"The currency the price is in, such as USD."}},"billingInterval":{"type":"text","required":false,"default":"month","description":"How often the subscriber is billed: every day, week, month or year.","_meta":{"description":"How often the subscriber is billed: every day, week, month or year."},"enum":["day","week","month","year"]},"pricingMode":{"type":"text","required":false,"default":"fixed","description":"Whether the plan is free, has a fixed price, or lets the subscriber choose what to pay. It cannot change once the plan is saved.","_meta":{"description":"Whether the plan is free, has a fixed price, or lets the subscriber choose what to pay. It cannot change once the plan is saved."},"enum":["free","fixed","pay_what_you_can"]},"minimumAmount":{"type":"integer","required":false,"default":0,"description":"For a pay-what-you-can plan, the least a subscriber may pay, in cents.","_meta":{"description":"For a pay-what-you-can plan, the least a subscriber may pay, in cents."}},"suggestedAmount":{"type":"integer","required":false,"default":0,"description":"For a pay-what-you-can plan, the amount suggested to the subscriber, in cents.","_meta":{"description":"For a pay-what-you-can plan, the amount suggested to the subscriber, in cents."}},"externalProvider":{"type":"text","required":false},"providerProductId":{"type":"text","required":false},"providerPriceId":{"type":"text","required":false},"stripeProductId":{"type":"text","required":false},"stripePriceId":{"type":"text","required":false},"features":{"type":"text","required":false,"default":"[]"},"thresholds":{"type":"text","required":false,"default":"[]"},"metadata":{"type":"text","required":false,"default":"{}"}},"methods":{"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"getTerms":{"name":"getTerms","async":false,"parameters":[],"returnType":"PlanTerms","isStatic":false,"isPublic":true},"save":{"name":"save","async":true,"parameters":[{"name":"options","type":"SmrtSaveOptions","optional":true}],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"publishTerms":{"name":"publishTerms","async":true,"parameters":[{"name":"options","type":"object","optional":true,"memberTypes":["Date"]}],"returnType":"Promise<SubscriptionPlanVersion>","isStatic":false,"isPublic":true},"getVersionInForce":{"name":"getVersionInForce","async":true,"parameters":[{"name":"at","type":"any","optional":true}],"returnType":"Promise<SubscriptionPlanVersion | null>","isStatic":false,"isPublic":true},"getFeatureGrants":{"name":"getFeatureGrants","async":false,"parameters":[],"returnType":"PlanFeatureGrant[]","isStatic":false,"isPublic":true},"setFeatureGrants":{"name":"setFeatureGrants","async":false,"parameters":[{"name":"grants","type":"Array<string | PlanFeatureGrant>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getFeatureKeys":{"name":"getFeatureKeys","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"getThresholds":{"name":"getThresholds","async":false,"parameters":[],"returnType":"PlanThreshold[]","isStatic":false,"isPublic":true},"setThresholds":{"name":"setThresholds","async":false,"parameters":[{"name":"thresholds","type":"PlanThreshold[]","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"JsonObject","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"metadata","type":"JsonObject","optional":false}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_subscription_plans","api":{"include":["list","get","create","update"]},"cli":{"skipApiCheck":true},"mcp":{"include":["list","get"]},"conflictColumns":["tenant_id","plan_key"],"tenantScoped":{"mode":"optional"}},"extends":"SmrtObject","exportName":"SubscriptionPlan","collectionExportName":"SubscriptionPlanCollection","displayLabelField":"name","schema":{"tableName":"_smrt_subscription_plans","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_subscription_plans\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"plan_key\\" TEXT DEFAULT '',\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT '',\\n \\"status\\" TEXT DEFAULT 'active',\\n \\"sort_order\\" INTEGER DEFAULT 0,\\n \\"price_amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"billing_interval\\" TEXT DEFAULT 'month',\\n \\"pricing_mode\\" TEXT DEFAULT 'fixed',\\n \\"minimum_amount\\" INTEGER DEFAULT 0,\\n \\"suggested_amount\\" INTEGER DEFAULT 0,\\n \\"external_provider\\" TEXT,\\n \\"provider_product_id\\" TEXT,\\n \\"provider_price_id\\" TEXT,\\n \\"stripe_product_id\\" TEXT,\\n \\"stripe_price_id\\" TEXT,\\n \\"features\\" TEXT DEFAULT '[]',\\n \\"thresholds\\" TEXT DEFAULT '[]',\\n \\"metadata\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"plan_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"active"},"sort_order":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"price_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"billing_interval":{"type":"TEXT","notNull":false,"unique":false,"default":"month"},"pricing_mode":{"type":"TEXT","notNull":false,"unique":false,"default":"fixed"},"minimum_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"suggested_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"external_provider":{"type":"TEXT","notNull":false,"unique":false},"provider_product_id":{"type":"TEXT","notNull":false,"unique":false},"provider_price_id":{"type":"TEXT","notNull":false,"unique":false},"stripe_product_id":{"type":"TEXT","notNull":false,"unique":false},"stripe_price_id":{"type":"TEXT","notNull":false,"unique":false},"features":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"thresholds":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_subscription_plans_tenant_id_plan_key_idx","columns":["tenant_id","plan_key"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_subscription_plans_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_subscription_plans_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"458e59be"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:SubscriptionPlanVersion":{"name":"subscriptionplanversion","className":"SubscriptionPlanVersion","qualifiedName":"@happyvertical/smrt-subscriptions:SubscriptionPlanVersion","collection":"subscriptionplanversions","description":"An immutable, effective-dated snapshot of a plan's terms (#4032).","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/SubscriptionPlanVersion.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"planId":{"type":"foreignKey","required":false,"related":"SubscriptionPlan","description":"The plan this version belongs to.","_meta":{"description":"The plan this version belongs to."}},"planKey":{"type":"text","required":false,"default":"","description":"The plan code at the time this version was published.","_meta":{"description":"The plan code at the time this version was published."}},"version":{"type":"integer","required":false,"default":0,"description":"Which version of the plan this is, counting from 1.","_meta":{"description":"Which version of the plan this is, counting from 1."}},"effectiveFrom":{"type":"datetime","required":false,"description":"The date and time from which these terms apply.","_meta":{"description":"The date and time from which these terms apply."}},"name":{"type":"text","required":false,"default":"","description":"What the plan was called when this version was published.","_meta":{"description":"What the plan was called when this version was published."}},"status":{"type":"text","required":false,"default":"active","description":"Whether the plan was a draft, on sale (active) or archived under this version.","_meta":{"description":"Whether the plan was a draft, on sale (active) or archived under this version."},"enum":["active","archived","draft"]},"priceAmount":{"type":"integer","required":false,"default":0,"description":"What the plan cost each billing period under this version, in cents.","_meta":{"description":"What the plan cost each billing period under this version, in cents."}},"currency":{"type":"text","required":false,"default":"USD","description":"The currency the price is in, such as USD.","_meta":{"description":"The currency the price is in, such as USD."}},"billingInterval":{"type":"text","required":false,"default":"month","description":"How often the subscriber was billed: every day, week, month or year.","_meta":{"description":"How often the subscriber was billed: every day, week, month or year."},"enum":["day","week","month","year"]},"pricingMode":{"type":"text","required":false,"default":"fixed","description":"Whether the plan was free, had a fixed price, or let the subscriber choose what to pay.","_meta":{"description":"Whether the plan was free, had a fixed price, or let the subscriber choose what to pay."},"enum":["free","fixed","pay_what_you_can"]},"minimumAmount":{"type":"integer","required":false,"default":0,"description":"For a pay-what-you-can plan, the least a subscriber could pay, in cents.","_meta":{"description":"For a pay-what-you-can plan, the least a subscriber could pay, in cents."}},"suggestedAmount":{"type":"integer","required":false,"default":0,"description":"For a pay-what-you-can plan, the amount suggested to the subscriber, in cents.","_meta":{"description":"For a pay-what-you-can plan, the amount suggested to the subscriber, in cents."}},"features":{"type":"text","required":false,"default":"[]"},"thresholds":{"type":"text","required":false,"default":"[]"}},"methods":{"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"getTerms":{"name":"getTerms","async":false,"parameters":[],"returnType":"PlanTerms","isStatic":false,"isPublic":true},"getFeatureGrants":{"name":"getFeatureGrants","async":false,"parameters":[],"returnType":"PlanFeatureGrant[]","isStatic":false,"isPublic":true},"getFeatureKeys":{"name":"getFeatureKeys","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"getThresholds":{"name":"getThresholds","async":false,"parameters":[],"returnType":"PlanThreshold[]","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_subscription_plan_versions","api":{"include":["list","get"]},"cli":{"include":["list","get"]},"mcp":{"include":["list","get"]},"conflictColumns":["plan_id","version"],"hooks":{"beforeDelete":"refuseDelete"},"tenantScoped":{"mode":"optional"}},"extends":"SmrtObject","exportName":"SubscriptionPlanVersion","collectionExportName":"SubscriptionPlanVersionCollection","displayLabelField":"name","schema":{"tableName":"_smrt_subscription_plan_versions","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_subscription_plan_versions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"plan_id\\" UUID,\\n \\"plan_key\\" TEXT DEFAULT '',\\n \\"version\\" INTEGER DEFAULT 0,\\n \\"effective_from\\" TIMESTAMP,\\n \\"name\\" TEXT DEFAULT '',\\n \\"status\\" TEXT DEFAULT 'active',\\n \\"price_amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"billing_interval\\" TEXT DEFAULT 'month',\\n \\"pricing_mode\\" TEXT DEFAULT 'fixed',\\n \\"minimum_amount\\" INTEGER DEFAULT 0,\\n \\"suggested_amount\\" INTEGER DEFAULT 0,\\n \\"features\\" TEXT DEFAULT '[]',\\n \\"thresholds\\" TEXT DEFAULT '[]'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"plan_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_subscription_plans","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"plan_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"version":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"effective_from":{"type":"TIMESTAMP","notNull":false,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"active"},"price_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"billing_interval":{"type":"TEXT","notNull":false,"unique":false,"default":"month"},"pricing_mode":{"type":"TEXT","notNull":false,"unique":false,"default":"fixed"},"minimum_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"suggested_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"features":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"thresholds":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"}},"indexes":[{"name":"_smrt_subscription_plan_versions_plan_id_version_idx","columns":["plan_id","version"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_subscription_plan_versions_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_subscription_plan_versions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"f42156f9"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:TenantSubscription":{"name":"tenantsubscription","className":"TenantSubscription","qualifiedName":"@happyvertical/smrt-subscriptions:TenantSubscription","collection":"tenantsubscriptions","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/TenantSubscription.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"subscriberKind":{"type":"text","required":false,"default":"tenant","description":"Whether the subscriber is your own workspace (tenant) or an outside customer (external).","_meta":{"description":"Whether the subscriber is your own workspace (tenant) or an outside customer (external)."},"enum":["tenant","external"]},"subscriberExternalId":{"type":"text","required":false,"default":"","description":"Who the outside subscriber is, when the subscriber type is external.","_meta":{"description":"Who the outside subscriber is, when the subscriber type is external."}},"planId":{"type":"foreignKey","required":false,"related":"SubscriptionPlan","description":"The plan this subscription is for.","_meta":{"description":"The plan this subscription is for."}},"status":{"type":"text","required":false,"default":"incomplete","description":"Where the subscription stands: incomplete, trialing, active, past due, unpaid or cancelled.","_meta":{"description":"Where the subscription stands: incomplete, trialing, active, past due, unpaid or cancelled."},"enum":["active","canceled","incomplete","past_due","trialing","unpaid"]},"startedAt":{"type":"datetime","required":false,"description":"The day the subscription began.","_meta":{"description":"The day the subscription began."}},"currentPeriodStart":{"type":"datetime","required":false,"description":"When the current billing period began.","_meta":{"description":"When the current billing period began."}},"currentPeriodEnd":{"type":"datetime","required":false,"description":"When the current billing period ends and the next one is due.","_meta":{"description":"When the current billing period ends and the next one is due."}},"trialEndsAt":{"type":"datetime","required":false,"description":"When the free trial ends, if there is one.","_meta":{"description":"When the free trial ends, if there is one."}},"cancelAtPeriodEnd":{"type":"boolean","required":false,"default":false,"description":"Tick to let the subscription run out at the end of the current period instead of renewing.","_meta":{"description":"Tick to let the subscription run out at the end of the current period instead of renewing."}},"canceledAt":{"type":"datetime","required":false,"description":"When the subscription was cancelled.","_meta":{"description":"When the subscription was cancelled."}},"agreedAmount":{"type":"integer","required":false,"description":"For a pay-what-you-can plan, the amount the subscriber chose to pay, in cents.","_meta":{"description":"For a pay-what-you-can plan, the amount the subscriber chose to pay, in cents."}},"planVersionId":{"type":"foreignKey","required":false,"related":"SubscriptionPlanVersion","description":"The version of the plan terms this subscription is held to for the current period. It is kept up to date automatically.","_meta":{"description":"The version of the plan terms this subscription is held to for the current period. It is kept up to date automatically."}},"planVersionPinnedAt":{"type":"datetime","required":false},"planVersionPinReason":{"type":"text","required":false,"enum":["period_start","renewal","upgrade","authorized","migration"]},"planVersionPinNote":{"type":"text","required":false,"default":""},"retainsPaidPeriod":{"type":"boolean","required":false,"default":false},"externalProvider":{"type":"text","required":false},"stripeCustomerId":{"type":"text","required":false,"default":""},"stripeSubscriptionId":{"type":"text","required":false,"default":""},"stripeCheckoutSessionId":{"type":"text","required":false,"default":""},"metadata":{"type":"text","required":false,"default":"{}"}},"methods":{"replacePlanVersion":{"name":"replacePlanVersion","async":true,"parameters":[{"name":"options","type":"any","optional":false,"typeUnresolved":true}],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"isEntitled":{"name":"isEntitled","async":false,"parameters":[{"name":"now","type":"any","optional":true}],"returnType":"boolean","isStatic":false,"isPublic":true},"getSubscriber":{"name":"getSubscriber","async":false,"parameters":[],"returnType":"Subscriber | null","isStatic":false,"isPublic":true},"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"JsonObject","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"metadata","type":"JsonObject","optional":false}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_tenant_subscriptions","api":{"include":["list","get","create","update"]},"cli":{"skipApiCheck":true},"mcp":{"include":["list","get"]},"conflictColumns":["tenant_id","subscriber_kind","subscriber_external_id"],"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"TenantSubscription","collectionExportName":"TenantSubscriptionCollection","validationRules":[],"schema":{"tableName":"_smrt_tenant_subscriptions","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_tenant_subscriptions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"plan_id\\" UUID,\\n \\"status\\" TEXT DEFAULT 'incomplete',\\n \\"started_at\\" TIMESTAMP,\\n \\"current_period_start\\" TIMESTAMP,\\n \\"current_period_end\\" TIMESTAMP,\\n \\"trial_ends_at\\" TIMESTAMP,\\n \\"cancel_at_period_end\\" BOOLEAN DEFAULT FALSE,\\n \\"canceled_at\\" TIMESTAMP,\\n \\"agreed_amount\\" INTEGER,\\n \\"plan_version_id\\" UUID,\\n \\"plan_version_pinned_at\\" TIMESTAMP,\\n \\"plan_version_pin_reason\\" TEXT,\\n \\"plan_version_pin_note\\" TEXT DEFAULT '',\\n \\"retains_paid_period\\" BOOLEAN DEFAULT FALSE,\\n \\"external_provider\\" TEXT,\\n \\"stripe_customer_id\\" TEXT DEFAULT '',\\n \\"stripe_subscription_id\\" TEXT DEFAULT '',\\n \\"stripe_checkout_session_id\\" TEXT DEFAULT '',\\n \\"metadata\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"plan_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_subscription_plans","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"incomplete"},"started_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"current_period_start":{"type":"TIMESTAMP","notNull":false,"unique":false},"current_period_end":{"type":"TIMESTAMP","notNull":false,"unique":false},"trial_ends_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"cancel_at_period_end":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"canceled_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"agreed_amount":{"type":"INTEGER","notNull":false,"unique":false},"plan_version_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_subscription_plan_versions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"plan_version_pinned_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"plan_version_pin_reason":{"type":"TEXT","notNull":false,"unique":false},"plan_version_pin_note":{"type":"TEXT","notNull":false,"unique":false,"default":""},"retains_paid_period":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"external_provider":{"type":"TEXT","notNull":false,"unique":false},"stripe_customer_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"stripe_subscription_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"stripe_checkout_session_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_tenant_subscriptions_tenant_id_subscriber_kind_idx","columns":["tenant_id","subscriber_kind","subscriber_external_id"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_tenant_subscriptions_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_tenant_subscriptions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_tenant_subscriptions_plan_id_idx","columns":["plan_id"]},{"name":"_smrt_tenant_subscriptions_plan_version_id_idx","columns":["plan_version_id"]}],"version":"c281741d"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:TenantUsageMetric":{"name":"tenantusagemetric","className":"TenantUsageMetric","qualifiedName":"@happyvertical/smrt-subscriptions:TenantUsageMetric","collection":"tenantusagemetrics","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/TenantUsageMetric.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"subscriberKind":{"type":"text","required":false,"default":"tenant","enum":["tenant","external"]},"subscriberExternalId":{"type":"text","required":false,"default":""},"metricKey":{"type":"text","required":false,"default":""},"quantity":{"type":"decimal","required":false,"default":0},"windowStart":{"type":"datetime","required":false},"windowEnd":{"type":"datetime","required":false},"source":{"type":"text","required":false,"default":""},"sourceId":{"type":"text","required":false,"default":""},"projectId":{"type":"text","required":false,"default":""},"workRefType":{"type":"text","required":false,"default":""},"workRefId":{"type":"text","required":false,"default":""},"provider":{"type":"text","required":false,"default":""},"dimensions":{"type":"text","required":false,"default":"{}"}},"methods":{"getSubscriber":{"name":"getSubscriber","async":false,"parameters":[],"returnType":"Subscriber | null","isStatic":false,"isPublic":true},"getDimensions":{"name":"getDimensions","async":false,"parameters":[],"returnType":"JsonObject","isStatic":false,"isPublic":true},"setDimensions":{"name":"setDimensions","async":false,"parameters":[{"name":"dimensions","type":"JsonObject","optional":false}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_tenant_usage_metrics","api":{"include":["list","get","create"]},"cli":{"include":["list","get","create"]},"mcp":{"include":["list","get"]},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"TenantUsageMetric","collectionExportName":"TenantUsageMetricCollection","validationRules":[],"schema":{"tableName":"_smrt_tenant_usage_metrics","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_tenant_usage_metrics\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"quantity\\" REAL DEFAULT 0,\\n \\"window_start\\" TIMESTAMP,\\n \\"window_end\\" TIMESTAMP,\\n \\"source\\" TEXT DEFAULT '',\\n \\"source_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"work_ref_type\\" TEXT DEFAULT '',\\n \\"work_ref_id\\" TEXT DEFAULT '',\\n \\"provider\\" TEXT DEFAULT '',\\n \\"dimensions\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"quantity":{"type":"REAL","notNull":false,"unique":false,"default":0},"window_start":{"type":"TIMESTAMP","notNull":false,"unique":false},"window_end":{"type":"TIMESTAMP","notNull":false,"unique":false},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_type":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":""},"dimensions":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_tenant_usage_metrics_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_tenant_usage_metrics_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"4884a70d"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:PricingRule":{"name":"pricingrule","className":"PricingRule","qualifiedName":"@happyvertical/smrt-subscriptions:PricingRule","collection":"pricingrules","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"ruleKey":{"type":"text","required":false,"default":""},"metricKey":{"type":"text","required":false,"default":""},"serviceKey":{"type":"text","required":false,"default":""},"strategy":{"type":"text","required":false,"default":"fixed_unit","enum":["fixed_unit","cost_plus","multiplier","tiered","included_overage","flat","custom"]},"currency":{"type":"text","required":false,"default":"USD"},"effectiveFrom":{"type":"datetime","required":false},"effectiveTo":{"type":"datetime","required":false},"priority":{"type":"integer","required":false,"default":0},"terms":{"type":"text","required":false,"default":"{}"},"active":{"type":"boolean","required":false,"default":true},"priceBookId":{"type":"foreignKey","required":false,"related":"PriceBook"}},"methods":{"getTerms":{"name":"getTerms","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true},"setTerms":{"name":"setTerms","async":false,"parameters":[{"name":"value","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_pricing_rules","api":true,"cli":true,"mcp":true,"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"PricingRule","collectionExportName":"PricingRuleCollection","validationRules":[],"schema":{"tableName":"_smrt_pricing_rules","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_pricing_rules\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"rule_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"strategy\\" TEXT DEFAULT 'fixed_unit',\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"effective_from\\" TIMESTAMP,\\n \\"effective_to\\" TIMESTAMP,\\n \\"priority\\" INTEGER DEFAULT 0,\\n \\"terms\\" TEXT DEFAULT '{}',\\n \\"active\\" BOOLEAN DEFAULT TRUE,\\n \\"price_book_id\\" UUID\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"rule_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"strategy":{"type":"TEXT","notNull":false,"unique":false,"default":"fixed_unit"},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"effective_from":{"type":"TIMESTAMP","notNull":false,"unique":false},"effective_to":{"type":"TIMESTAMP","notNull":false,"unique":false},"priority":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"terms":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true},"price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}}},"indexes":[{"name":"_smrt_pricing_rules_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_pricing_rules_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_pricing_rules_price_book_id_idx","columns":["price_book_id"]}],"version":"37fd6ea9"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:ClientCharge":{"name":"clientcharge","className":"ClientCharge","qualifiedName":"@happyvertical/smrt-subscriptions:ClientCharge","collection":"clientcharges","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"usageEventId":{"type":"foreignKey","required":false,"related":"TenantUsageMetric"},"usageTenantId":{"type":"crossPackageRef","required":false,"related":"@happyvertical/smrt-users:Tenant"},"subscriberKind":{"type":"text","required":false,"default":"tenant"},"subscriberExternalId":{"type":"text","required":false,"default":""},"projectId":{"type":"text","required":false,"default":""},"workRefType":{"type":"text","required":false,"default":""},"workRefId":{"type":"text","required":false,"default":""},"provider":{"type":"text","required":false,"default":"","description":"Who supplied the service that was used.","_meta":{"description":"Who supplied the service that was used."}},"serviceKey":{"type":"text","required":false,"default":"","description":"The service that was used.","_meta":{"description":"The service that was used."}},"metricKey":{"type":"text","required":false,"default":"","description":"What was used, such as messages sent or minutes of audio.","_meta":{"description":"What was used, such as messages sent or minutes of audio."}},"quantity":{"type":"decimal","required":false,"default":0,"description":"How much of it was used.","_meta":{"description":"How much of it was used."}},"amount":{"type":"integer","required":false,"default":0,"description":"What it cost, in cents.","_meta":{"description":"What it cost, in cents."}},"currency":{"type":"text","required":false,"default":"USD","description":"The currency the amount is in, such as USD.","_meta":{"description":"The currency the amount is in, such as USD."}},"pricingRuleId":{"type":"foreignKey","required":false,"related":"PricingRule"},"priceBookId":{"type":"foreignKey","required":false,"related":"PriceBook"},"pricingSnapshot":{"type":"text","required":false,"default":"{}"},"status":{"type":"text","required":false,"default":"draft","description":"Where the charge stands: draft, approved or adjusted.","_meta":{"description":"Where the charge stands: draft, approved or adjusted."},"enum":["draft","approved","adjusted"]},"approvedAt":{"type":"datetime","required":false,"description":"When the charge was approved.","_meta":{"description":"When the charge was approved."}}},"methods":{"getPricingSnapshot":{"name":"getPricingSnapshot","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_client_charges","api":{"include":["list","get"]},"cli":{"include":["list","get"]},"mcp":{"include":["list","get"]},"conflictColumns":["usage_event_id"],"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"ClientCharge","collectionExportName":"ClientChargeCollection","validationRules":[],"schema":{"tableName":"_smrt_client_charges","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_client_charges\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"usage_event_id\\" UUID,\\n \\"usage_tenant_id\\" UUID,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"work_ref_type\\" TEXT DEFAULT '',\\n \\"work_ref_id\\" TEXT DEFAULT '',\\n \\"provider\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"quantity\\" REAL DEFAULT 0,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"pricing_rule_id\\" UUID,\\n \\"price_book_id\\" UUID,\\n \\"pricing_snapshot\\" TEXT DEFAULT '{}',\\n \\"status\\" TEXT DEFAULT 'draft',\\n \\"approved_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"usage_event_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_tenant_usage_metrics","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"usage_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_type":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"quantity":{"type":"REAL","notNull":false,"unique":false,"default":0},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"pricing_rule_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_pricing_rules","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pricing_snapshot":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"draft"},"approved_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_client_charges_usage_event_id_idx","columns":["usage_event_id"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_client_charges_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_client_charges_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_client_charges_usage_tenant_id_idx","columns":["usage_tenant_id"]},{"name":"_smrt_client_charges_pricing_rule_id_idx","columns":["pricing_rule_id"]},{"name":"_smrt_client_charges_price_book_id_idx","columns":["price_book_id"]}],"version":"92fb8003"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:BillingAdjustment":{"name":"billingadjustment","className":"BillingAdjustment","qualifiedName":"@happyvertical/smrt-subscriptions:BillingAdjustment","collection":"billingadjustments","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"clientChargeId":{"type":"foreignKey","required":false,"related":"ClientCharge"},"amount":{"type":"integer","required":false,"default":0},"currency":{"type":"text","required":false,"default":"USD"},"reason":{"type":"text","required":false,"default":""},"source":{"type":"text","required":false,"default":""},"sourceId":{"type":"text","required":false,"default":""},"createdBy":{"type":"text","required":false,"default":""}},"methods":{},"decoratorConfig":{"tableName":"_smrt_billing_adjustments","api":{"include":["list","get"]},"cli":{"include":["list","get"]},"mcp":{"include":["list","get"]},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"BillingAdjustment","collectionExportName":"BillingAdjustmentCollection","validationRules":[],"schema":{"tableName":"_smrt_billing_adjustments","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_billing_adjustments\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"client_charge_id\\" UUID,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"reason\\" TEXT DEFAULT '',\\n \\"source\\" TEXT DEFAULT '',\\n \\"source_id\\" TEXT DEFAULT '',\\n \\"created_by\\" TEXT DEFAULT ''\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"client_charge_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_client_charges","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"reason":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"created_by":{"type":"TEXT","notNull":false,"unique":false,"default":""}},"indexes":[{"name":"_smrt_billing_adjustments_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_billing_adjustments_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_billing_adjustments_client_charge_id_idx","columns":["client_charge_id"]}],"version":"cfbd2832"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:SpendingPolicy":{"name":"spendingpolicy","className":"SpendingPolicy","qualifiedName":"@happyvertical/smrt-subscriptions:SpendingPolicy","collection":"spendingpolicies","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"name":{"type":"text","required":false,"default":""},"subscriberKind":{"type":"text","required":false,"default":""},"subscriberExternalId":{"type":"text","required":false,"default":""},"projectId":{"type":"text","required":false,"default":""},"serviceKey":{"type":"text","required":false,"default":""},"metricKey":{"type":"text","required":false,"default":""},"period":{"type":"text","required":false,"default":"month","enum":["day","week","month","year","rolling","balance"]},"rollingSeconds":{"type":"integer","required":false,"default":0},"limitAmount":{"type":"integer","required":false,"default":0},"currency":{"type":"text","required":false,"default":"USD"},"behavior":{"type":"text","required":false,"default":"observe","enum":["observe","warn","block","approval_required"]},"priority":{"type":"integer","required":false,"default":0},"active":{"type":"boolean","required":false,"default":true},"basis":{"type":"text","required":false,"default":"billed","enum":["billed","retail","wholesale"]},"setByTenantId":{"type":"crossPackageRef","required":false,"related":"@happyvertical/smrt-users:Tenant"},"balanceFrom":{"type":"datetime","required":false}},"methods":{},"decoratorConfig":{"tableName":"_smrt_spending_policies","conflictColumns":["tenant_id","subscriber_kind","subscriber_external_id","project_id","service_key","metric_key","period","name"],"api":true,"cli":true,"mcp":true,"hooks":{"beforeDelete":"assertDelegationAuthority"},"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"SpendingPolicy","collectionExportName":"SpendingPolicyCollection","displayLabelField":"name","validationRules":[],"schema":{"tableName":"_smrt_spending_policies","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_spending_policies\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"name\\" TEXT DEFAULT '',\\n \\"subscriber_kind\\" TEXT DEFAULT '',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"period\\" TEXT DEFAULT 'month',\\n \\"rolling_seconds\\" INTEGER DEFAULT 0,\\n \\"limit_amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"behavior\\" TEXT DEFAULT 'observe',\\n \\"priority\\" INTEGER DEFAULT 0,\\n \\"active\\" BOOLEAN DEFAULT TRUE,\\n \\"basis\\" TEXT DEFAULT 'billed',\\n \\"set_by_tenant_id\\" UUID,\\n \\"balance_from\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":""},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"period":{"type":"TEXT","notNull":false,"unique":false,"default":"month"},"rolling_seconds":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"limit_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"behavior":{"type":"TEXT","notNull":false,"unique":false,"default":"observe"},"priority":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true},"basis":{"type":"TEXT","notNull":false,"unique":false,"default":"billed"},"set_by_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"balance_from":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_spending_policies_tenant_id_subscriber_kind_idx","columns":["tenant_id","subscriber_kind","subscriber_external_id","project_id","service_key","metric_key","period","name"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_spending_policies_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_spending_policies_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_spending_policies_set_by_tenant_id_idx","columns":["set_by_tenant_id"]}],"version":"21fbbb20"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:PricingRuleCollection":{"name":"pricingrulecollection","className":"PricingRuleCollection","qualifiedName":"@happyvertical/smrt-subscriptions:PricingRuleCollection","collection":"pricingrules","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_pricing_rules"},"extends":"SmrtCollection","extendsTypeArg":"PricingRule","exportName":"PricingRuleCollection","collectionExportName":"PricingRuleCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:PricingRule","schema":{"tableName":"_smrt_pricing_rules","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_pricing_rules\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"rule_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"strategy\\" TEXT DEFAULT 'fixed_unit',\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"effective_from\\" TIMESTAMP,\\n \\"effective_to\\" TIMESTAMP,\\n \\"priority\\" INTEGER DEFAULT 0,\\n \\"terms\\" TEXT DEFAULT '{}',\\n \\"active\\" BOOLEAN DEFAULT TRUE,\\n \\"price_book_id\\" UUID\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"rule_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"strategy":{"type":"TEXT","notNull":false,"unique":false,"default":"fixed_unit"},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"effective_from":{"type":"TIMESTAMP","notNull":false,"unique":false},"effective_to":{"type":"TIMESTAMP","notNull":false,"unique":false},"priority":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"terms":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true},"price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}}},"indexes":[{"name":"_smrt_pricing_rules_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_pricing_rules_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_pricing_rules_price_book_id_idx","columns":["price_book_id"]}],"version":"37fd6ea9"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:ClientChargeCollection":{"name":"clientchargecollection","className":"ClientChargeCollection","qualifiedName":"@happyvertical/smrt-subscriptions:ClientChargeCollection","collection":"clientcharges","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_client_charges","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"ClientCharge","exportName":"ClientChargeCollection","collectionExportName":"ClientChargeCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:ClientCharge","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_client_charges","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_client_charges\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"usage_event_id\\" UUID,\\n \\"usage_tenant_id\\" UUID,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"work_ref_type\\" TEXT DEFAULT '',\\n \\"work_ref_id\\" TEXT DEFAULT '',\\n \\"provider\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"quantity\\" REAL DEFAULT 0,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"pricing_rule_id\\" UUID,\\n \\"price_book_id\\" UUID,\\n \\"pricing_snapshot\\" TEXT DEFAULT '{}',\\n \\"status\\" TEXT DEFAULT 'draft',\\n \\"approved_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"usage_event_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_tenant_usage_metrics","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"usage_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_type":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"quantity":{"type":"REAL","notNull":false,"unique":false,"default":0},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"pricing_rule_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_pricing_rules","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pricing_snapshot":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"draft"},"approved_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_client_charges_usage_event_id_idx","columns":["usage_event_id"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_client_charges_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_client_charges_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_client_charges_usage_tenant_id_idx","columns":["usage_tenant_id"]},{"name":"_smrt_client_charges_pricing_rule_id_idx","columns":["pricing_rule_id"]},{"name":"_smrt_client_charges_price_book_id_idx","columns":["price_book_id"]}],"version":"92fb8003"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:BillingAdjustmentCollection":{"name":"billingadjustmentcollection","className":"BillingAdjustmentCollection","qualifiedName":"@happyvertical/smrt-subscriptions:BillingAdjustmentCollection","collection":"billingadjustments","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_billing_adjustments","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"BillingAdjustment","exportName":"BillingAdjustmentCollection","collectionExportName":"BillingAdjustmentCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:BillingAdjustment","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_billing_adjustments","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_billing_adjustments\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"client_charge_id\\" UUID,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"reason\\" TEXT DEFAULT '',\\n \\"source\\" TEXT DEFAULT '',\\n \\"source_id\\" TEXT DEFAULT '',\\n \\"created_by\\" TEXT DEFAULT ''\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"client_charge_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_client_charges","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"reason":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"created_by":{"type":"TEXT","notNull":false,"unique":false,"default":""}},"indexes":[{"name":"_smrt_billing_adjustments_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_billing_adjustments_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_billing_adjustments_client_charge_id_idx","columns":["client_charge_id"]}],"version":"cfbd2832"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:SpendingPolicyCollection":{"name":"spendingpolicycollection","className":"SpendingPolicyCollection","qualifiedName":"@happyvertical/smrt-subscriptions:SpendingPolicyCollection","collection":"spendingpolicies","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_spending_policies"},"extends":"SmrtCollection","extendsTypeArg":"SpendingPolicy","exportName":"SpendingPolicyCollection","collectionExportName":"SpendingPolicyCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:SpendingPolicy","schema":{"tableName":"_smrt_spending_policies","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_spending_policies\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"name\\" TEXT DEFAULT '',\\n \\"subscriber_kind\\" TEXT DEFAULT '',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"period\\" TEXT DEFAULT 'month',\\n \\"rolling_seconds\\" INTEGER DEFAULT 0,\\n \\"limit_amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"behavior\\" TEXT DEFAULT 'observe',\\n \\"priority\\" INTEGER DEFAULT 0,\\n \\"active\\" BOOLEAN DEFAULT TRUE,\\n \\"basis\\" TEXT DEFAULT 'billed',\\n \\"set_by_tenant_id\\" UUID,\\n \\"balance_from\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":""},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"period":{"type":"TEXT","notNull":false,"unique":false,"default":"month"},"rolling_seconds":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"limit_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"behavior":{"type":"TEXT","notNull":false,"unique":false,"default":"observe"},"priority":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true},"basis":{"type":"TEXT","notNull":false,"unique":false,"default":"billed"},"set_by_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"balance_from":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_spending_policies_tenant_id_subscriber_kind_idx","columns":["tenant_id","subscriber_kind","subscriber_external_id","project_id","service_key","metric_key","period","name"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_spending_policies_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_spending_policies_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_spending_policies_set_by_tenant_id_idx","columns":["set_by_tenant_id"]}],"version":"21fbbb20"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:PriceBook":{"name":"pricebook","className":"PriceBook","qualifiedName":"@happyvertical/smrt-subscriptions:PriceBook","collection":"pricebooks","description":"A named set of prices published by one seller tenant. Its prices are ordinary PricingRule rows that carry this book's id and the same tenant; one rule per currency gives a price in several currencies.","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"bookKey":{"type":"text","required":false,"default":""},"name":{"type":"text","required":false,"default":""},"kind":{"type":"text","required":false,"default":"retail","enum":["wholesale","retail"]},"active":{"type":"boolean","required":false,"default":true}},"methods":{},"decoratorConfig":{"tableName":"_smrt_price_books","conflictColumns":["tenant_id","book_key"],"api":false,"cli":false,"mcp":false,"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"PriceBook","collectionExportName":"PriceBookCollection","displayLabelField":"name","validationRules":[],"schema":{"tableName":"_smrt_price_books","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_price_books\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"book_key\\" TEXT DEFAULT '',\\n \\"name\\" TEXT DEFAULT '',\\n \\"kind\\" TEXT DEFAULT 'retail',\\n \\"active\\" BOOLEAN DEFAULT TRUE\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"book_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"kind":{"type":"TEXT","notNull":false,"unique":false,"default":"retail"},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true}},"indexes":[{"name":"_smrt_price_books_tenant_id_book_key_idx","columns":["tenant_id","book_key"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_price_books_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_price_books_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"56296d2f"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:PriceBookAssignment":{"name":"pricebookassignment","className":"PriceBookAssignment","qualifiedName":"@happyvertical/smrt-subscriptions:PriceBookAssignment","collection":"pricebookassignments","description":"Which price books rate one child tenant's usage, keyed like the tenancy billing relationship it belongs to (one row per child).","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"childTenantId":{"type":"crossPackageRef","required":true,"related":"@happyvertical/smrt-users:Tenant","_meta":{"required":true}},"resellerTenantId":{"type":"crossPackageRef","required":true,"related":"@happyvertical/smrt-users:Tenant","_meta":{"required":true}},"wholesalePriceBookId":{"type":"foreignKey","required":false,"related":"PriceBook"},"wholesaleCurrency":{"type":"text","required":false,"default":""},"retailPriceBookId":{"type":"foreignKey","required":false,"related":"PriceBook"},"retailCurrency":{"type":"text","required":false,"default":""}},"methods":{},"decoratorConfig":{"tableName":"_smrt_price_book_assignments","conflictColumns":["child_tenant_id"],"api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"PriceBookAssignment","collectionExportName":"PriceBookAssignmentCollection","validationRules":[{"field":"childTenantId","rule":"required","fieldType":"crossPackageRef"},{"field":"resellerTenantId","rule":"required","fieldType":"crossPackageRef"}],"schema":{"tableName":"_smrt_price_book_assignments","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_price_book_assignments\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"child_tenant_id\\" UUID NOT NULL,\\n \\"reseller_tenant_id\\" UUID NOT NULL,\\n \\"wholesale_price_book_id\\" UUID,\\n \\"wholesale_currency\\" TEXT DEFAULT '',\\n \\"retail_price_book_id\\" UUID,\\n \\"retail_currency\\" TEXT DEFAULT ''\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"child_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"reseller_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"wholesale_price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"wholesale_currency":{"type":"TEXT","notNull":false,"unique":false,"default":""},"retail_price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"retail_currency":{"type":"TEXT","notNull":false,"unique":false,"default":""}},"indexes":[{"name":"_smrt_price_book_assignments_child_tenant_id_idx","columns":["child_tenant_id"],"unique":true},{"name":"_smrt_price_book_assignments_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_price_book_assignments_created_at_idx","columns":["created_at"]},{"name":"_smrt_price_book_assignments_reseller_tenant_id_idx","columns":["reseller_tenant_id"]},{"name":"_smrt_price_book_assignments_wholesale_price_book_id_idx","columns":["wholesale_price_book_id"]},{"name":"_smrt_price_book_assignments_retail_price_book_id_idx","columns":["retail_price_book_id"]}],"version":"990da9b7"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:RetailCharge":{"name":"retailcharge","className":"RetailCharge","qualifiedName":"@happyvertical/smrt-subscriptions:RetailCharge","collection":"retailcharges","description":"What a reseller charges one child for one usage event, priced from the reseller's retail book.","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"resellerTenantId":{"type":"crossPackageRef","required":false,"related":"@happyvertical/smrt-users:Tenant"},"usageEventId":{"type":"foreignKey","required":false,"related":"TenantUsageMetric"},"clientChargeId":{"type":"foreignKey","required":false,"related":"ClientCharge"},"subscriberKind":{"type":"text","required":false,"default":"tenant"},"subscriberExternalId":{"type":"text","required":false,"default":""},"projectId":{"type":"text","required":false,"default":""},"workRefType":{"type":"text","required":false,"default":""},"workRefId":{"type":"text","required":false,"default":""},"provider":{"type":"text","required":false,"default":""},"serviceKey":{"type":"text","required":false,"default":""},"metricKey":{"type":"text","required":false,"default":""},"quantity":{"type":"decimal","required":false,"default":0},"amount":{"type":"integer","required":false,"default":0},"currency":{"type":"text","required":false,"default":"USD"},"priceBookId":{"type":"foreignKey","required":false,"related":"PriceBook"},"pricingRuleId":{"type":"foreignKey","required":false,"related":"PricingRule"},"pricingSnapshot":{"type":"text","required":false,"default":"{}"},"status":{"type":"text","required":false,"default":"draft","enum":["draft","approved"]},"approvedAt":{"type":"datetime","required":false}},"methods":{"getPricingSnapshot":{"name":"getPricingSnapshot","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_retail_charges","api":{"include":["list","get"]},"cli":{"include":["list","get"]},"mcp":{"include":["list","get"]},"conflictColumns":["usage_event_id"],"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"RetailCharge","collectionExportName":"RetailChargeCollection","validationRules":[],"schema":{"tableName":"_smrt_retail_charges","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_retail_charges\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"reseller_tenant_id\\" UUID,\\n \\"usage_event_id\\" UUID,\\n \\"client_charge_id\\" UUID,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"work_ref_type\\" TEXT DEFAULT '',\\n \\"work_ref_id\\" TEXT DEFAULT '',\\n \\"provider\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"quantity\\" REAL DEFAULT 0,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"price_book_id\\" UUID,\\n \\"pricing_rule_id\\" UUID,\\n \\"pricing_snapshot\\" TEXT DEFAULT '{}',\\n \\"status\\" TEXT DEFAULT 'draft',\\n \\"approved_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"reseller_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"usage_event_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_tenant_usage_metrics","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"client_charge_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_client_charges","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_type":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"quantity":{"type":"REAL","notNull":false,"unique":false,"default":0},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pricing_rule_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_pricing_rules","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pricing_snapshot":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"draft"},"approved_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_retail_charges_usage_event_id_idx","columns":["usage_event_id"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_retail_charges_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_retail_charges_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_retail_charges_reseller_tenant_id_idx","columns":["reseller_tenant_id"]},{"name":"_smrt_retail_charges_client_charge_id_idx","columns":["client_charge_id"]},{"name":"_smrt_retail_charges_price_book_id_idx","columns":["price_book_id"]},{"name":"_smrt_retail_charges_pricing_rule_id_idx","columns":["pricing_rule_id"]}],"version":"ad6930a8"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:CreditGrant":{"name":"creditgrant","className":"CreditGrant","qualifiedName":"@happyvertical/smrt-subscriptions:CreditGrant","collection":"creditgrants","description":"An append-only credit on a prepaid (period: 'balance') spending policy. Positive amounts add credit; a negative amount reverses an earlier grant.","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"spendingPolicyId":{"type":"foreignKey","required":false,"related":"SpendingPolicy"},"amount":{"type":"integer","required":false,"default":0},"currency":{"type":"text","required":false,"default":"USD"},"reason":{"type":"text","required":false,"default":""},"source":{"type":"text","required":false,"default":""},"sourceId":{"type":"text","required":false,"default":""},"grantedByTenantId":{"type":"crossPackageRef","required":false,"related":"@happyvertical/smrt-users:Tenant"}},"methods":{},"decoratorConfig":{"tableName":"_smrt_credit_grants","api":{"include":["list","get"]},"cli":{"include":["list","get"]},"mcp":{"include":["list","get"]},"hooks":{"beforeDelete":"refuseDelete"},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"CreditGrant","collectionExportName":"CreditGrantCollection","validationRules":[],"schema":{"tableName":"_smrt_credit_grants","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_credit_grants\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"spending_policy_id\\" UUID,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"reason\\" TEXT DEFAULT '',\\n \\"source\\" TEXT DEFAULT '',\\n \\"source_id\\" TEXT DEFAULT '',\\n \\"granted_by_tenant_id\\" UUID\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"spending_policy_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_spending_policies","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"reason":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"granted_by_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_credit_grants_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_credit_grants_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_credit_grants_spending_policy_id_idx","columns":["spending_policy_id"]},{"name":"_smrt_credit_grants_granted_by_tenant_id_idx","columns":["granted_by_tenant_id"]}],"version":"e11305fc"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:PriceBookCollection":{"name":"pricebookcollection","className":"PriceBookCollection","qualifiedName":"@happyvertical/smrt-subscriptions:PriceBookCollection","collection":"pricebooks","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_price_books","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"PriceBook","exportName":"PriceBookCollection","collectionExportName":"PriceBookCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:PriceBook","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_price_books","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_price_books\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"book_key\\" TEXT DEFAULT '',\\n \\"name\\" TEXT DEFAULT '',\\n \\"kind\\" TEXT DEFAULT 'retail',\\n \\"active\\" BOOLEAN DEFAULT TRUE\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"book_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"kind":{"type":"TEXT","notNull":false,"unique":false,"default":"retail"},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true}},"indexes":[{"name":"_smrt_price_books_tenant_id_book_key_idx","columns":["tenant_id","book_key"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_price_books_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_price_books_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"56296d2f"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:PriceBookAssignmentCollection":{"name":"pricebookassignmentcollection","className":"PriceBookAssignmentCollection","qualifiedName":"@happyvertical/smrt-subscriptions:PriceBookAssignmentCollection","collection":"pricebookassignments","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_price_book_assignments","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"PriceBookAssignment","exportName":"PriceBookAssignmentCollection","collectionExportName":"PriceBookAssignmentCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:PriceBookAssignment","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_price_book_assignments","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_price_book_assignments\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"child_tenant_id\\" UUID NOT NULL,\\n \\"reseller_tenant_id\\" UUID NOT NULL,\\n \\"wholesale_price_book_id\\" UUID,\\n \\"wholesale_currency\\" TEXT DEFAULT '',\\n \\"retail_price_book_id\\" UUID,\\n \\"retail_currency\\" TEXT DEFAULT ''\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"child_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"reseller_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"wholesale_price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"wholesale_currency":{"type":"TEXT","notNull":false,"unique":false,"default":""},"retail_price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"retail_currency":{"type":"TEXT","notNull":false,"unique":false,"default":""}},"indexes":[{"name":"_smrt_price_book_assignments_child_tenant_id_idx","columns":["child_tenant_id"],"unique":true},{"name":"_smrt_price_book_assignments_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_price_book_assignments_created_at_idx","columns":["created_at"]},{"name":"_smrt_price_book_assignments_reseller_tenant_id_idx","columns":["reseller_tenant_id"]},{"name":"_smrt_price_book_assignments_wholesale_price_book_id_idx","columns":["wholesale_price_book_id"]},{"name":"_smrt_price_book_assignments_retail_price_book_id_idx","columns":["retail_price_book_id"]}],"version":"990da9b7"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:RetailChargeCollection":{"name":"retailchargecollection","className":"RetailChargeCollection","qualifiedName":"@happyvertical/smrt-subscriptions:RetailChargeCollection","collection":"retailcharges","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_retail_charges","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"RetailCharge","exportName":"RetailChargeCollection","collectionExportName":"RetailChargeCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:RetailCharge","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_retail_charges","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_retail_charges\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"reseller_tenant_id\\" UUID,\\n \\"usage_event_id\\" UUID,\\n \\"client_charge_id\\" UUID,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"work_ref_type\\" TEXT DEFAULT '',\\n \\"work_ref_id\\" TEXT DEFAULT '',\\n \\"provider\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"quantity\\" REAL DEFAULT 0,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"price_book_id\\" UUID,\\n \\"pricing_rule_id\\" UUID,\\n \\"pricing_snapshot\\" TEXT DEFAULT '{}',\\n \\"status\\" TEXT DEFAULT 'draft',\\n \\"approved_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"reseller_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"usage_event_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_tenant_usage_metrics","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"client_charge_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_client_charges","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_type":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"quantity":{"type":"REAL","notNull":false,"unique":false,"default":0},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pricing_rule_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_pricing_rules","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pricing_snapshot":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"draft"},"approved_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_retail_charges_usage_event_id_idx","columns":["usage_event_id"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_retail_charges_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_retail_charges_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_retail_charges_reseller_tenant_id_idx","columns":["reseller_tenant_id"]},{"name":"_smrt_retail_charges_client_charge_id_idx","columns":["client_charge_id"]},{"name":"_smrt_retail_charges_price_book_id_idx","columns":["price_book_id"]},{"name":"_smrt_retail_charges_pricing_rule_id_idx","columns":["pricing_rule_id"]}],"version":"ad6930a8"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:CreditGrantCollection":{"name":"creditgrantcollection","className":"CreditGrantCollection","qualifiedName":"@happyvertical/smrt-subscriptions:CreditGrantCollection","collection":"creditgrants","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_credit_grants","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"CreditGrant","exportName":"CreditGrantCollection","collectionExportName":"CreditGrantCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:CreditGrant","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_credit_grants","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_credit_grants\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"spending_policy_id\\" UUID,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"reason\\" TEXT DEFAULT '',\\n \\"source\\" TEXT DEFAULT '',\\n \\"source_id\\" TEXT DEFAULT '',\\n \\"granted_by_tenant_id\\" UUID\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"spending_policy_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_spending_policies","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"reason":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"granted_by_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_credit_grants_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_credit_grants_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_credit_grants_spending_policy_id_idx","columns":["spending_policy_id"]},{"name":"_smrt_credit_grants_granted_by_tenant_id_idx","columns":["granted_by_tenant_id"]}],"version":"e11305fc"},"importPath":"@happyvertical/smrt-subscriptions"}},"moduleType":"smrt","recipes":[{"id":"subscriptions.plans","className":"SubscriptionPlansRecipe","label":"Subscriptions","summary":"Sell plans that renew, see who is subscribed to which, and what their usage cost.","synonyms":["subscriptions","subscription plans","plans","memberships","recurring billing","pricing tiers"],"models":["@happyvertical/smrt-subscriptions:SubscriptionPlan","@happyvertical/smrt-subscriptions:SubscriptionPlanVersion","@happyvertical/smrt-subscriptions:TenantSubscription","@happyvertical/smrt-subscriptions:ClientCharge"],"nav":[{"label":"Plans","model":"@happyvertical/smrt-subscriptions:SubscriptionPlan","icon":"tag","description":"The plans you sell, with their price and how often they bill.","noun":"plan"},{"label":"Subscriptions","model":"@happyvertical/smrt-subscriptions:TenantSubscription","icon":"repeat","description":"Who is subscribed to which plan, and where each one stands.","noun":"subscription"},{"label":"Plan versions","model":"@happyvertical/smrt-subscriptions:SubscriptionPlanVersion","icon":"fileText","description":"Every set of terms a plan has had, and from when each applied.","noun":"plan version"},{"label":"Charges","model":"@happyvertical/smrt-subscriptions:ClientCharge","icon":"receipt","description":"What each subscriber used and what it cost them.","noun":"charge"}],"requires":[],"section":{"id":"sales","label":"Sales","icon":"shoppingBag","description":"Customers, orders and quotes: everything you sell."},"options":{"@happyvertical/smrt-subscriptions:SubscriptionPlan":{"fields":{"name":{"order":1},"planKey":{"label":"Plan code","order":2},"description":{"order":3},"status":{"order":4},"priceAmount":{"label":"Price (in cents)","order":5},"currency":{"order":6},"billingInterval":{"label":"Billed every","order":7},"pricingMode":{"label":"How it is priced","order":8},"minimumAmount":{"label":"Minimum (in cents)","visibility":"advanced"},"suggestedAmount":{"label":"Suggested (in cents)","visibility":"advanced"},"sortOrder":{"label":"Position in list","visibility":"advanced"},"tenantId":{"visibility":"hidden"},"features":{"visibility":"hidden"},"thresholds":{"visibility":"hidden"},"externalProvider":{"visibility":"hidden"},"providerProductId":{"visibility":"hidden"},"providerPriceId":{"visibility":"hidden"},"stripeProductId":{"visibility":"hidden"},"stripePriceId":{"visibility":"hidden"},"metadata":{"visibility":"hidden"}}},"@happyvertical/smrt-subscriptions:SubscriptionPlanVersion":{"fields":{"planId":{"label":"Plan","order":1},"version":{"label":"Version number","order":2},"effectiveFrom":{"label":"In force from","order":3},"name":{"order":4},"status":{"order":5},"priceAmount":{"label":"Price (in cents)","order":6},"currency":{"order":7},"billingInterval":{"label":"Billed every","order":8},"planKey":{"label":"Plan code","visibility":"advanced"},"pricingMode":{"label":"How it is priced","visibility":"advanced"},"minimumAmount":{"label":"Minimum (in cents)","visibility":"advanced"},"suggestedAmount":{"label":"Suggested (in cents)","visibility":"advanced"},"tenantId":{"visibility":"hidden"},"features":{"visibility":"hidden"},"thresholds":{"visibility":"hidden"}}},"@happyvertical/smrt-subscriptions:TenantSubscription":{"fields":{"planId":{"label":"Plan","order":1},"status":{"order":2},"startedAt":{"label":"Started on","order":3},"currentPeriodStart":{"label":"Current period starts","order":4},"currentPeriodEnd":{"label":"Current period ends","order":5},"trialEndsAt":{"label":"Trial ends","order":6},"cancelAtPeriodEnd":{"label":"Cancel at end of period","order":7},"canceledAt":{"label":"Cancelled on","visibility":"advanced"},"agreedAmount":{"label":"Agreed amount (in cents)","visibility":"advanced"},"subscriberKind":{"label":"Subscriber type","visibility":"advanced"},"subscriberExternalId":{"label":"Outside subscriber","visibility":"advanced"},"planVersionId":{"label":"Plan version","visibility":"advanced","locked":true},"tenantId":{"visibility":"hidden"},"planVersionPinnedAt":{"visibility":"hidden"},"planVersionPinReason":{"visibility":"hidden"},"planVersionPinNote":{"visibility":"hidden"},"retainsPaidPeriod":{"visibility":"hidden"},"externalProvider":{"visibility":"hidden"},"stripeCustomerId":{"visibility":"hidden"},"stripeSubscriptionId":{"visibility":"hidden"},"stripeCheckoutSessionId":{"visibility":"hidden"},"metadata":{"visibility":"hidden"}}},"@happyvertical/smrt-subscriptions:ClientCharge":{"fields":{"metricKey":{"label":"What was used","order":1},"quantity":{"label":"How much","order":2},"amount":{"label":"Amount (in cents)","order":3},"currency":{"order":4},"status":{"order":5},"approvedAt":{"label":"Approved on","order":6},"serviceKey":{"label":"Service","visibility":"advanced"},"provider":{"visibility":"advanced"},"tenantId":{"visibility":"hidden"},"usageEventId":{"visibility":"hidden"},"usageTenantId":{"visibility":"hidden"},"subscriberKind":{"visibility":"hidden"},"subscriberExternalId":{"visibility":"hidden"},"projectId":{"visibility":"hidden"},"workRefType":{"visibility":"hidden"},"workRefId":{"visibility":"hidden"},"pricingRuleId":{"visibility":"hidden"},"priceBookId":{"visibility":"hidden"},"pricingSnapshot":{"visibility":"hidden"}}}},"help":{"markdown":"## Overview\\n\\nSubscriptions is where you sell plans that renew. A plan says what it costs,\\nhow often it bills and whether it is free, a fixed price or pay what you can.\\nA subscription joins a subscriber to a plan and shows where it stands, from\\ntrial to active to cancelled. Every time you change a plan's terms, the\\nearlier terms are kept as a plan version, so a subscriber who already paid for\\na period keeps what they paid for until it renews. Charges show what each\\nsubscriber used and what it cost them.\\n\\nAll amounts are whole numbers of cents, with no decimal point.\\n\\n## Tasks\\n\\n### Set up a plan\\n\\n1. Open the plans and choose **New**.\\n2. Type the **{field:SubscriptionPlan.name}** customers will see and a short **{field:SubscriptionPlan.planKey}** such as \\"starter\\".\\n3. Choose **{field:SubscriptionPlan.pricingMode}**: free, a fixed price, or pay what you can. This cannot change once the plan is saved; make a new plan instead.\\n4. For a fixed price, enter the **{field:SubscriptionPlan.priceAmount}** in cents and the **{field:SubscriptionPlan.currency}**.\\n5. Set how often it bills in **{field:SubscriptionPlan.billingInterval}**.\\n6. Set the **{field:SubscriptionPlan.status}** to active when it is ready to sell.\\n7. Save.\\n\\n### Change a plan's price or terms\\n\\n1. Open the plan and edit the **{field:SubscriptionPlan.priceAmount}**, **{field:SubscriptionPlan.billingInterval}** or **{field:SubscriptionPlan.status}**.\\n2. Save. The new terms apply to new subscribers and to existing ones from their next renewal; a period already paid for keeps its old terms.\\n\\n### Retire a plan\\n\\n1. Open the plan and set its **{field:SubscriptionPlan.status}** to archived.\\n2. Save. No one new can subscribe to it; existing subscribers keep going until they cancel.\\n\\n### Subscribe someone to a plan\\n\\n1. Open the subscriptions and choose **New**.\\n2. Pick the **{field:TenantSubscription.planId}**.\\n3. Enter the day it **{field:TenantSubscription.startedAt}** and, if there is a free trial, when the **{field:TenantSubscription.trialEndsAt}**.\\n4. Save. The **{field:TenantSubscription.status}** shows where the subscription stands once it has been paid for.\\n\\n### See where a subscription stands\\n\\n1. Open the subscriptions and find the one you want.\\n2. The **{field:TenantSubscription.status}** shows whether it is still incomplete, on trial, active, past due, unpaid or cancelled.\\n3. **{field:TenantSubscription.currentPeriodStart}** and **{field:TenantSubscription.currentPeriodEnd}** show the period that has been paid for.\\n\\n### Cancel a subscription\\n\\n1. Open the subscription.\\n2. Tick **{field:TenantSubscription.cancelAtPeriodEnd}** so it runs out when the current period ends instead of renewing.\\n3. Save.\\n\\n### Look up the terms a subscriber was sold\\n\\nPlan versions are written automatically whenever a plan is saved with changed\\nterms; you cannot add or edit them here.\\n\\n1. Open the plan versions and find the **{field:SubscriptionPlanVersion.planId}** you are interested in.\\n2. Each row shows the **{field:SubscriptionPlanVersion.version}** and the date it was **{field:SubscriptionPlanVersion.effectiveFrom}**.\\n3. Read the **{field:SubscriptionPlanVersion.priceAmount}**, **{field:SubscriptionPlanVersion.currency}** and **{field:SubscriptionPlanVersion.billingInterval}** that applied under it.\\n\\n### See what a subscriber was charged\\n\\nCharges are created by the usage and billing service as usage is recorded;\\nyou cannot add or edit them here.\\n\\n1. Open the charges.\\n2. Each row shows **{field:ClientCharge.metricKey}**, **{field:ClientCharge.quantity}** and the **{field:ClientCharge.amount}** in cents.\\n3. The **{field:ClientCharge.status}** shows whether the charge is still a draft, approved or adjusted.\\n","fieldRefs":["ClientCharge.amount","ClientCharge.metricKey","ClientCharge.quantity","ClientCharge.status","SubscriptionPlan.billingInterval","SubscriptionPlan.currency","SubscriptionPlan.name","SubscriptionPlan.planKey","SubscriptionPlan.priceAmount","SubscriptionPlan.pricingMode","SubscriptionPlan.status","SubscriptionPlanVersion.billingInterval","SubscriptionPlanVersion.currency","SubscriptionPlanVersion.effectiveFrom","SubscriptionPlanVersion.planId","SubscriptionPlanVersion.priceAmount","SubscriptionPlanVersion.version","TenantSubscription.cancelAtPeriodEnd","TenantSubscription.currentPeriodEnd","TenantSubscription.currentPeriodStart","TenantSubscription.planId","TenantSubscription.startedAt","TenantSubscription.status","TenantSubscription.trialEndsAt"]},"demo":{"mode":"server","reasons":["Needs a server because its package does not build for a browser: core migrations (node:crypto, node:os); and its package depends on @happyvertical/smrt-tenancy, which do not build for a browser (#3624, #3626)."]}}],"smrtDependencies":["@happyvertical/smrt-core","@happyvertical/smrt-features","@happyvertical/smrt-tenancy"],"browser":{"status":"server-only","issues":["#3624","#3626"],"reason":"core migrations (node:crypto, node:os)","via":["@happyvertical/smrt-tenancy"]},"stampsConstructors":true}`));
11
+ ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-subscriptions","packageVersion":"0.60.17","objects":{"@happyvertical/smrt-subscriptions:SubscriptionPlanCollection":{"name":"subscriptionplancollection","className":"SubscriptionPlanCollection","qualifiedName":"@happyvertical/smrt-subscriptions:SubscriptionPlanCollection","collection":"subscriptionplans","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/collections/SubscriptionPlanCollection.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{"findByPlanKey":{"name":"findByPlanKey","async":true,"parameters":[{"name":"tenantId","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]},{"name":"planKey","type":"string","optional":false}],"returnType":"Promise<SubscriptionPlan | null>","isStatic":false,"isPublic":true},"findActive":{"name":"findActive","async":true,"parameters":[],"returnType":"Promise<SubscriptionPlan[]>","isStatic":false,"isPublic":true},"findByProviderPriceId":{"name":"findByProviderPriceId","async":true,"parameters":[{"name":"providerPriceId","type":"string","optional":false}],"returnType":"Promise<SubscriptionPlan | null>","isStatic":false,"isPublic":true},"findByStripePriceId":{"name":"findByStripePriceId","async":true,"parameters":[{"name":"stripePriceId","type":"string","optional":false}],"returnType":"Promise<SubscriptionPlan | null>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_subscription_plans","api":{"include":["list","get","create","update"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"SubscriptionPlan","exportName":"SubscriptionPlanCollection","collectionExportName":"SubscriptionPlanCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:SubscriptionPlan","inheritedExposure":["api","mcp"],"schema":{"tableName":"_smrt_subscription_plans","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_subscription_plans\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"plan_key\\" TEXT DEFAULT '',\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT '',\\n \\"status\\" TEXT DEFAULT 'active',\\n \\"sort_order\\" INTEGER DEFAULT 0,\\n \\"price_amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"billing_interval\\" TEXT DEFAULT 'month',\\n \\"pricing_mode\\" TEXT DEFAULT 'fixed',\\n \\"minimum_amount\\" INTEGER DEFAULT 0,\\n \\"suggested_amount\\" INTEGER DEFAULT 0,\\n \\"external_provider\\" TEXT,\\n \\"provider_product_id\\" TEXT,\\n \\"provider_price_id\\" TEXT,\\n \\"stripe_product_id\\" TEXT,\\n \\"stripe_price_id\\" TEXT,\\n \\"features\\" TEXT DEFAULT '[]',\\n \\"thresholds\\" TEXT DEFAULT '[]',\\n \\"metadata\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"plan_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"active"},"sort_order":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"price_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"billing_interval":{"type":"TEXT","notNull":false,"unique":false,"default":"month"},"pricing_mode":{"type":"TEXT","notNull":false,"unique":false,"default":"fixed"},"minimum_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"suggested_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"external_provider":{"type":"TEXT","notNull":false,"unique":false},"provider_product_id":{"type":"TEXT","notNull":false,"unique":false},"provider_price_id":{"type":"TEXT","notNull":false,"unique":false},"stripe_product_id":{"type":"TEXT","notNull":false,"unique":false},"stripe_price_id":{"type":"TEXT","notNull":false,"unique":false},"features":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"thresholds":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_subscription_plans_tenant_id_plan_key_idx","columns":["tenant_id","plan_key"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_subscription_plans_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_subscription_plans_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"458e59be"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:SubscriptionPlanVersionCollection":{"name":"subscriptionplanversioncollection","className":"SubscriptionPlanVersionCollection","qualifiedName":"@happyvertical/smrt-subscriptions:SubscriptionPlanVersionCollection","collection":"subscriptionplanversions","description":"Effective-dated plan versions (#4032).","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/collections/SubscriptionPlanVersionCollection.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{"findVisibleById":{"name":"findVisibleById","async":true,"parameters":[{"name":"id","type":"string","optional":false}],"returnType":"Promise<SubscriptionPlanVersion | null>","isStatic":false,"isPublic":true},"listForPlan":{"name":"listForPlan","async":true,"parameters":[{"name":"planId","type":"string","optional":false}],"returnType":"Promise<SubscriptionPlanVersion[]>","isStatic":false,"isPublic":true},"findLatest":{"name":"findLatest","async":true,"parameters":[{"name":"planId","type":"string","optional":false},{"name":"tenantId","type":"string | null","optional":true,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<SubscriptionPlanVersion | null>","isStatic":false,"isPublic":true},"findInForce":{"name":"findInForce","async":true,"parameters":[{"name":"planId","type":"string","optional":false},{"name":"at","type":"Date","optional":false}],"returnType":"Promise<SubscriptionPlanVersion | null>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_subscription_plan_versions","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"SubscriptionPlanVersion","exportName":"SubscriptionPlanVersionCollection","collectionExportName":"SubscriptionPlanVersionCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:SubscriptionPlanVersion","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_subscription_plan_versions","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_subscription_plan_versions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"plan_id\\" UUID,\\n \\"plan_key\\" TEXT DEFAULT '',\\n \\"version\\" INTEGER DEFAULT 0,\\n \\"effective_from\\" TIMESTAMP,\\n \\"name\\" TEXT DEFAULT '',\\n \\"status\\" TEXT DEFAULT 'active',\\n \\"price_amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"billing_interval\\" TEXT DEFAULT 'month',\\n \\"pricing_mode\\" TEXT DEFAULT 'fixed',\\n \\"minimum_amount\\" INTEGER DEFAULT 0,\\n \\"suggested_amount\\" INTEGER DEFAULT 0,\\n \\"features\\" TEXT DEFAULT '[]',\\n \\"thresholds\\" TEXT DEFAULT '[]'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"plan_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_subscription_plans","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"plan_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"version":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"effective_from":{"type":"TIMESTAMP","notNull":false,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"active"},"price_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"billing_interval":{"type":"TEXT","notNull":false,"unique":false,"default":"month"},"pricing_mode":{"type":"TEXT","notNull":false,"unique":false,"default":"fixed"},"minimum_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"suggested_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"features":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"thresholds":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"}},"indexes":[{"name":"_smrt_subscription_plan_versions_plan_id_version_idx","columns":["plan_id","version"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_subscription_plan_versions_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_subscription_plan_versions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"f42156f9"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:TenantSubscriptionCollection":{"name":"tenantsubscriptioncollection","className":"TenantSubscriptionCollection","qualifiedName":"@happyvertical/smrt-subscriptions:TenantSubscriptionCollection","collection":"tenantsubscriptions","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/collections/TenantSubscriptionCollection.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{"findByTenant":{"name":"findByTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<TenantSubscription[]>","isStatic":false,"isPublic":true},"findCurrentForTenant":{"name":"findCurrentForTenant","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"now","type":"any","optional":true}],"returnType":"Promise<TenantSubscription | null>","isStatic":false,"isPublic":true},"findCurrentForSubscriber":{"name":"findCurrentForSubscriber","async":true,"parameters":[{"name":"subscriber","type":"Subscriber","optional":false},{"name":"now","type":"any","optional":true}],"returnType":"Promise<TenantSubscription | null>","isStatic":false,"isPublic":true},"findByStripeSubscriptionId":{"name":"findByStripeSubscriptionId","async":true,"parameters":[{"name":"stripeSubscriptionId","type":"string","optional":false}],"returnType":"Promise<TenantSubscription | null>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_tenant_subscriptions","api":{"include":["list","get","create","update"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"TenantSubscription","exportName":"TenantSubscriptionCollection","collectionExportName":"TenantSubscriptionCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:TenantSubscription","inheritedExposure":["api","mcp"],"schema":{"tableName":"_smrt_tenant_subscriptions","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_tenant_subscriptions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"plan_id\\" UUID,\\n \\"status\\" TEXT DEFAULT 'incomplete',\\n \\"started_at\\" TIMESTAMP,\\n \\"current_period_start\\" TIMESTAMP,\\n \\"current_period_end\\" TIMESTAMP,\\n \\"trial_ends_at\\" TIMESTAMP,\\n \\"cancel_at_period_end\\" BOOLEAN DEFAULT FALSE,\\n \\"canceled_at\\" TIMESTAMP,\\n \\"agreed_amount\\" INTEGER,\\n \\"plan_version_id\\" UUID,\\n \\"plan_version_pinned_at\\" TIMESTAMP,\\n \\"plan_version_pin_reason\\" TEXT,\\n \\"plan_version_pin_note\\" TEXT DEFAULT '',\\n \\"retains_paid_period\\" BOOLEAN DEFAULT FALSE,\\n \\"external_provider\\" TEXT,\\n \\"stripe_customer_id\\" TEXT DEFAULT '',\\n \\"stripe_subscription_id\\" TEXT DEFAULT '',\\n \\"stripe_checkout_session_id\\" TEXT DEFAULT '',\\n \\"metadata\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"plan_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_subscription_plans","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"incomplete"},"started_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"current_period_start":{"type":"TIMESTAMP","notNull":false,"unique":false},"current_period_end":{"type":"TIMESTAMP","notNull":false,"unique":false},"trial_ends_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"cancel_at_period_end":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"canceled_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"agreed_amount":{"type":"INTEGER","notNull":false,"unique":false},"plan_version_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_subscription_plan_versions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"plan_version_pinned_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"plan_version_pin_reason":{"type":"TEXT","notNull":false,"unique":false},"plan_version_pin_note":{"type":"TEXT","notNull":false,"unique":false,"default":""},"retains_paid_period":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"external_provider":{"type":"TEXT","notNull":false,"unique":false},"stripe_customer_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"stripe_subscription_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"stripe_checkout_session_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_tenant_subscriptions_tenant_id_subscriber_kind_idx","columns":["tenant_id","subscriber_kind","subscriber_external_id"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_tenant_subscriptions_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_tenant_subscriptions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_tenant_subscriptions_plan_id_idx","columns":["plan_id"]},{"name":"_smrt_tenant_subscriptions_plan_version_id_idx","columns":["plan_version_id"]}],"version":"c281741d"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:TenantUsageMetricCollection":{"name":"tenantusagemetriccollection","className":"TenantUsageMetricCollection","qualifiedName":"@happyvertical/smrt-subscriptions:TenantUsageMetricCollection","collection":"tenantusagemetrics","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/collections/TenantUsageMetricCollection.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{"recordUsage":{"name":"recordUsage","async":true,"parameters":[{"name":"options","type":"RecordUsageOptions","optional":false}],"returnType":"Promise<TenantUsageMetric>","isStatic":false,"isPublic":true},"findByTenantAndMetric":{"name":"findByTenantAndMetric","async":true,"parameters":[{"name":"tenantId","type":"string","optional":false},{"name":"metricKey","type":"string","optional":false}],"returnType":"Promise<TenantUsageMetric[]>","isStatic":false,"isPublic":true},"summarizeUsage":{"name":"summarizeUsage","async":true,"parameters":[{"name":"options","type":"SummarizeUsageOptions","optional":false}],"returnType":"Promise<UsageSummary>","isStatic":false,"isPublic":true},"summarizeUsageBatch":{"name":"summarizeUsageBatch","async":true,"parameters":[{"name":"options","type":"SummarizeUsageBatchOptions","optional":false}],"returnType":"Promise<UsageSummary[]>","isStatic":false,"isPublic":true},"summarizeTenantAiUsage":{"name":"summarizeTenantAiUsage","async":true,"parameters":[{"name":"options","type":"SummarizeAiUsageOptions","optional":false}],"returnType":"Promise<AiUsageSummary>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_tenant_usage_metrics","api":{"include":["list","get","create"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get","create"]}},"extends":"SmrtCollection","extendsTypeArg":"TenantUsageMetric","exportName":"TenantUsageMetricCollection","collectionExportName":"TenantUsageMetricCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:TenantUsageMetric","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_tenant_usage_metrics","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_tenant_usage_metrics\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"quantity\\" REAL DEFAULT 0,\\n \\"window_start\\" TIMESTAMP,\\n \\"window_end\\" TIMESTAMP,\\n \\"source\\" TEXT DEFAULT '',\\n \\"source_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"work_ref_type\\" TEXT DEFAULT '',\\n \\"work_ref_id\\" TEXT DEFAULT '',\\n \\"provider\\" TEXT DEFAULT '',\\n \\"dimensions\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"quantity":{"type":"REAL","notNull":false,"unique":false,"default":0},"window_start":{"type":"TIMESTAMP","notNull":false,"unique":false},"window_end":{"type":"TIMESTAMP","notNull":false,"unique":false},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_type":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":""},"dimensions":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_tenant_usage_metrics_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_tenant_usage_metrics_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"4884a70d"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:BillingCheckoutSession":{"name":"billingcheckoutsession","className":"BillingCheckoutSession","qualifiedName":"@happyvertical/smrt-subscriptions:BillingCheckoutSession","collection":"billingcheckoutsessions","description":"One Checkout session created by the billing host, recorded when the host creates it and required when the paid session completes, so signed metadata copied onto another integration's session is never\u2026","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/BillingCheckoutSession.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"sessionId":{"type":"text","required":true,"default":"","_meta":{"required":true}},"targetTenantId":{"type":"text","required":false,"default":"","description":"The tenant the host created the session for.","_meta":{"description":"The tenant the host created the session for."}},"status":{"type":"text","required":false,"default":"pending","enum":["pending","completed","needs_reconciliation","dismissed"]},"expiresAt":{"type":"datetime","required":false},"completedAt":{"type":"datetime","required":false},"reason":{"type":"text","required":false,"default":""},"detail":{"type":"text","required":false,"default":"{}"}},"methods":{},"decoratorConfig":{"tableName":"_smrt_billing_checkout_sessions","conflictColumns":["session_id"],"api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"BillingCheckoutSession","collectionExportName":"BillingCheckoutSessionCollection","validationRules":[{"field":"sessionId","rule":"required","fieldType":"text"}],"schema":{"tableName":"_smrt_billing_checkout_sessions","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_billing_checkout_sessions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"session_id\\" TEXT NOT NULL DEFAULT '',\\n \\"target_tenant_id\\" TEXT DEFAULT '',\\n \\"status\\" TEXT DEFAULT 'pending',\\n \\"expires_at\\" TIMESTAMP,\\n \\"completed_at\\" TIMESTAMP,\\n \\"reason\\" TEXT DEFAULT '',\\n \\"detail\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"session_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"target_tenant_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"pending"},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"reason":{"type":"TEXT","notNull":false,"unique":false,"default":""},"detail":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_billing_checkout_sessions_session_id_idx","columns":["session_id"],"unique":true},{"name":"_smrt_billing_checkout_sessions_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_billing_checkout_sessions_created_at_idx","columns":["created_at"]}],"version":"c1924881"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:BillingCheckoutSessionCollection":{"name":"billingcheckoutsessioncollection","className":"BillingCheckoutSessionCollection","qualifiedName":"@happyvertical/smrt-subscriptions:BillingCheckoutSessionCollection","collection":"billingcheckoutsessions","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/BillingCheckoutSession.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_billing_checkout_sessions","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"BillingCheckoutSession","exportName":"BillingCheckoutSessionCollection","collectionExportName":"BillingCheckoutSessionCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:BillingCheckoutSession","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_billing_checkout_sessions","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_billing_checkout_sessions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"session_id\\" TEXT NOT NULL DEFAULT '',\\n \\"target_tenant_id\\" TEXT DEFAULT '',\\n \\"status\\" TEXT DEFAULT 'pending',\\n \\"expires_at\\" TIMESTAMP,\\n \\"completed_at\\" TIMESTAMP,\\n \\"reason\\" TEXT DEFAULT '',\\n \\"detail\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"session_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"target_tenant_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"pending"},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"reason":{"type":"TEXT","notNull":false,"unique":false,"default":""},"detail":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_billing_checkout_sessions_session_id_idx","columns":["session_id"],"unique":true},{"name":"_smrt_billing_checkout_sessions_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_billing_checkout_sessions_created_at_idx","columns":["created_at"]}],"version":"c1924881"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:SubscriptionPlan":{"name":"subscriptionplan","className":"SubscriptionPlan","qualifiedName":"@happyvertical/smrt-subscriptions:SubscriptionPlan","collection":"subscriptionplans","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/SubscriptionPlan.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"planKey":{"type":"text","required":false,"default":"","description":"A short code that identifies the plan, such as starter or pro.","_meta":{"description":"A short code that identifies the plan, such as starter or pro."}},"name":{"type":"text","required":false,"default":"","description":"What the plan is called, as customers see it.","_meta":{"description":"What the plan is called, as customers see it."}},"description":{"type":"text","required":false,"default":"","description":"A sentence or two about what the plan offers.","_meta":{"description":"A sentence or two about what the plan offers."}},"status":{"type":"text","required":false,"default":"active","description":"Whether the plan is a draft, on sale (active) or archived.","_meta":{"description":"Whether the plan is a draft, on sale (active) or archived."},"enum":["active","archived","draft"]},"sortOrder":{"type":"integer","required":false,"default":0,"description":"Where the plan sits when plans are listed; lower numbers come first.","_meta":{"description":"Where the plan sits when plans are listed; lower numbers come first."}},"priceAmount":{"type":"integer","required":false,"default":0,"description":"What the plan costs each billing period, in cents, as a whole number.","_meta":{"description":"What the plan costs each billing period, in cents, as a whole number."}},"currency":{"type":"text","required":false,"default":"USD","description":"The currency the price is in, such as USD.","_meta":{"description":"The currency the price is in, such as USD."}},"billingInterval":{"type":"text","required":false,"default":"month","description":"How often the subscriber is billed: every day, week, month or year.","_meta":{"description":"How often the subscriber is billed: every day, week, month or year."},"enum":["day","week","month","year"]},"pricingMode":{"type":"text","required":false,"default":"fixed","description":"Whether the plan is free, has a fixed price, or lets the subscriber choose what to pay. It cannot change once the plan is saved.","_meta":{"description":"Whether the plan is free, has a fixed price, or lets the subscriber choose what to pay. It cannot change once the plan is saved."},"enum":["free","fixed","pay_what_you_can"]},"minimumAmount":{"type":"integer","required":false,"default":0,"description":"For a pay-what-you-can plan, the least a subscriber may pay, in cents.","_meta":{"description":"For a pay-what-you-can plan, the least a subscriber may pay, in cents."}},"suggestedAmount":{"type":"integer","required":false,"default":0,"description":"For a pay-what-you-can plan, the amount suggested to the subscriber, in cents.","_meta":{"description":"For a pay-what-you-can plan, the amount suggested to the subscriber, in cents."}},"externalProvider":{"type":"text","required":false},"providerProductId":{"type":"text","required":false},"providerPriceId":{"type":"text","required":false},"stripeProductId":{"type":"text","required":false},"stripePriceId":{"type":"text","required":false},"features":{"type":"text","required":false,"default":"[]"},"thresholds":{"type":"text","required":false,"default":"[]"},"metadata":{"type":"text","required":false,"default":"{}"}},"methods":{"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"getTerms":{"name":"getTerms","async":false,"parameters":[],"returnType":"PlanTerms","isStatic":false,"isPublic":true},"save":{"name":"save","async":true,"parameters":[{"name":"options","type":"SmrtSaveOptions","optional":true}],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"publishTerms":{"name":"publishTerms","async":true,"parameters":[{"name":"options","type":"object","optional":true,"memberTypes":["Date"]}],"returnType":"Promise<SubscriptionPlanVersion>","isStatic":false,"isPublic":true},"getVersionInForce":{"name":"getVersionInForce","async":true,"parameters":[{"name":"at","type":"any","optional":true}],"returnType":"Promise<SubscriptionPlanVersion | null>","isStatic":false,"isPublic":true},"getFeatureGrants":{"name":"getFeatureGrants","async":false,"parameters":[],"returnType":"PlanFeatureGrant[]","isStatic":false,"isPublic":true},"setFeatureGrants":{"name":"setFeatureGrants","async":false,"parameters":[{"name":"grants","type":"Array<string | PlanFeatureGrant>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getFeatureKeys":{"name":"getFeatureKeys","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"getThresholds":{"name":"getThresholds","async":false,"parameters":[],"returnType":"PlanThreshold[]","isStatic":false,"isPublic":true},"setThresholds":{"name":"setThresholds","async":false,"parameters":[{"name":"thresholds","type":"PlanThreshold[]","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"JsonObject","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"metadata","type":"JsonObject","optional":false}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_subscription_plans","api":{"include":["list","get","create","update"]},"cli":{"skipApiCheck":true},"mcp":{"include":["list","get"]},"conflictColumns":["tenant_id","plan_key"],"tenantScoped":{"mode":"optional"}},"extends":"SmrtObject","exportName":"SubscriptionPlan","collectionExportName":"SubscriptionPlanCollection","displayLabelField":"name","schema":{"tableName":"_smrt_subscription_plans","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_subscription_plans\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"plan_key\\" TEXT DEFAULT '',\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT '',\\n \\"status\\" TEXT DEFAULT 'active',\\n \\"sort_order\\" INTEGER DEFAULT 0,\\n \\"price_amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"billing_interval\\" TEXT DEFAULT 'month',\\n \\"pricing_mode\\" TEXT DEFAULT 'fixed',\\n \\"minimum_amount\\" INTEGER DEFAULT 0,\\n \\"suggested_amount\\" INTEGER DEFAULT 0,\\n \\"external_provider\\" TEXT,\\n \\"provider_product_id\\" TEXT,\\n \\"provider_price_id\\" TEXT,\\n \\"stripe_product_id\\" TEXT,\\n \\"stripe_price_id\\" TEXT,\\n \\"features\\" TEXT DEFAULT '[]',\\n \\"thresholds\\" TEXT DEFAULT '[]',\\n \\"metadata\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"plan_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"active"},"sort_order":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"price_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"billing_interval":{"type":"TEXT","notNull":false,"unique":false,"default":"month"},"pricing_mode":{"type":"TEXT","notNull":false,"unique":false,"default":"fixed"},"minimum_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"suggested_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"external_provider":{"type":"TEXT","notNull":false,"unique":false},"provider_product_id":{"type":"TEXT","notNull":false,"unique":false},"provider_price_id":{"type":"TEXT","notNull":false,"unique":false},"stripe_product_id":{"type":"TEXT","notNull":false,"unique":false},"stripe_price_id":{"type":"TEXT","notNull":false,"unique":false},"features":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"thresholds":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_subscription_plans_tenant_id_plan_key_idx","columns":["tenant_id","plan_key"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_subscription_plans_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_subscription_plans_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"458e59be"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:SubscriptionPlanVersion":{"name":"subscriptionplanversion","className":"SubscriptionPlanVersion","qualifiedName":"@happyvertical/smrt-subscriptions:SubscriptionPlanVersion","collection":"subscriptionplanversions","description":"An immutable, effective-dated snapshot of a plan's terms (#4032).","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/SubscriptionPlanVersion.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":false,"_meta":{"sqlType":"UUID","nullable":true,"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false}}},"planId":{"type":"foreignKey","required":false,"related":"SubscriptionPlan","description":"The plan this version belongs to.","_meta":{"description":"The plan this version belongs to."}},"planKey":{"type":"text","required":false,"default":"","description":"The plan code at the time this version was published.","_meta":{"description":"The plan code at the time this version was published."}},"version":{"type":"integer","required":false,"default":0,"description":"Which version of the plan this is, counting from 1.","_meta":{"description":"Which version of the plan this is, counting from 1."}},"effectiveFrom":{"type":"datetime","required":false,"description":"The date and time from which these terms apply.","_meta":{"description":"The date and time from which these terms apply."}},"name":{"type":"text","required":false,"default":"","description":"What the plan was called when this version was published.","_meta":{"description":"What the plan was called when this version was published."}},"status":{"type":"text","required":false,"default":"active","description":"Whether the plan was a draft, on sale (active) or archived under this version.","_meta":{"description":"Whether the plan was a draft, on sale (active) or archived under this version."},"enum":["active","archived","draft"]},"priceAmount":{"type":"integer","required":false,"default":0,"description":"What the plan cost each billing period under this version, in cents.","_meta":{"description":"What the plan cost each billing period under this version, in cents."}},"currency":{"type":"text","required":false,"default":"USD","description":"The currency the price is in, such as USD.","_meta":{"description":"The currency the price is in, such as USD."}},"billingInterval":{"type":"text","required":false,"default":"month","description":"How often the subscriber was billed: every day, week, month or year.","_meta":{"description":"How often the subscriber was billed: every day, week, month or year."},"enum":["day","week","month","year"]},"pricingMode":{"type":"text","required":false,"default":"fixed","description":"Whether the plan was free, had a fixed price, or let the subscriber choose what to pay.","_meta":{"description":"Whether the plan was free, had a fixed price, or let the subscriber choose what to pay."},"enum":["free","fixed","pay_what_you_can"]},"minimumAmount":{"type":"integer","required":false,"default":0,"description":"For a pay-what-you-can plan, the least a subscriber could pay, in cents.","_meta":{"description":"For a pay-what-you-can plan, the least a subscriber could pay, in cents."}},"suggestedAmount":{"type":"integer","required":false,"default":0,"description":"For a pay-what-you-can plan, the amount suggested to the subscriber, in cents.","_meta":{"description":"For a pay-what-you-can plan, the amount suggested to the subscriber, in cents."}},"features":{"type":"text","required":false,"default":"[]"},"thresholds":{"type":"text","required":false,"default":"[]"}},"methods":{"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"getTerms":{"name":"getTerms","async":false,"parameters":[],"returnType":"PlanTerms","isStatic":false,"isPublic":true},"getFeatureGrants":{"name":"getFeatureGrants","async":false,"parameters":[],"returnType":"PlanFeatureGrant[]","isStatic":false,"isPublic":true},"getFeatureKeys":{"name":"getFeatureKeys","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"getThresholds":{"name":"getThresholds","async":false,"parameters":[],"returnType":"PlanThreshold[]","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_subscription_plan_versions","api":{"include":["list","get"]},"cli":{"include":["list","get"]},"mcp":{"include":["list","get"]},"conflictColumns":["plan_id","version"],"hooks":{"beforeDelete":"refuseDelete"},"tenantScoped":{"mode":"optional"}},"extends":"SmrtObject","exportName":"SubscriptionPlanVersion","collectionExportName":"SubscriptionPlanVersionCollection","displayLabelField":"name","schema":{"tableName":"_smrt_subscription_plan_versions","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_subscription_plan_versions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"plan_id\\" UUID,\\n \\"plan_key\\" TEXT DEFAULT '',\\n \\"version\\" INTEGER DEFAULT 0,\\n \\"effective_from\\" TIMESTAMP,\\n \\"name\\" TEXT DEFAULT '',\\n \\"status\\" TEXT DEFAULT 'active',\\n \\"price_amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"billing_interval\\" TEXT DEFAULT 'month',\\n \\"pricing_mode\\" TEXT DEFAULT 'fixed',\\n \\"minimum_amount\\" INTEGER DEFAULT 0,\\n \\"suggested_amount\\" INTEGER DEFAULT 0,\\n \\"features\\" TEXT DEFAULT '[]',\\n \\"thresholds\\" TEXT DEFAULT '[]'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"plan_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_subscription_plans","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"plan_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"version":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"effective_from":{"type":"TIMESTAMP","notNull":false,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"active"},"price_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"billing_interval":{"type":"TEXT","notNull":false,"unique":false,"default":"month"},"pricing_mode":{"type":"TEXT","notNull":false,"unique":false,"default":"fixed"},"minimum_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"suggested_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"features":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"thresholds":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"}},"indexes":[{"name":"_smrt_subscription_plan_versions_plan_id_version_idx","columns":["plan_id","version"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_subscription_plan_versions_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_subscription_plan_versions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"f42156f9"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:TenantSubscription":{"name":"tenantsubscription","className":"TenantSubscription","qualifiedName":"@happyvertical/smrt-subscriptions:TenantSubscription","collection":"tenantsubscriptions","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/TenantSubscription.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"subscriberKind":{"type":"text","required":false,"default":"tenant","description":"Whether the subscriber is your own workspace (tenant) or an outside customer (external).","_meta":{"description":"Whether the subscriber is your own workspace (tenant) or an outside customer (external)."},"enum":["tenant","external"]},"subscriberExternalId":{"type":"text","required":false,"default":"","description":"Who the outside subscriber is, when the subscriber type is external.","_meta":{"description":"Who the outside subscriber is, when the subscriber type is external."}},"planId":{"type":"foreignKey","required":false,"related":"SubscriptionPlan","description":"The plan this subscription is for.","_meta":{"description":"The plan this subscription is for."}},"status":{"type":"text","required":false,"default":"incomplete","description":"Where the subscription stands: incomplete, trialing, active, past due, unpaid or cancelled.","_meta":{"description":"Where the subscription stands: incomplete, trialing, active, past due, unpaid or cancelled."},"enum":["active","canceled","incomplete","past_due","trialing","unpaid"]},"startedAt":{"type":"datetime","required":false,"description":"The day the subscription began.","_meta":{"description":"The day the subscription began."}},"currentPeriodStart":{"type":"datetime","required":false,"description":"When the current billing period began.","_meta":{"description":"When the current billing period began."}},"currentPeriodEnd":{"type":"datetime","required":false,"description":"When the current billing period ends and the next one is due.","_meta":{"description":"When the current billing period ends and the next one is due."}},"trialEndsAt":{"type":"datetime","required":false,"description":"When the free trial ends, if there is one.","_meta":{"description":"When the free trial ends, if there is one."}},"cancelAtPeriodEnd":{"type":"boolean","required":false,"default":false,"description":"Tick to let the subscription run out at the end of the current period instead of renewing.","_meta":{"description":"Tick to let the subscription run out at the end of the current period instead of renewing."}},"canceledAt":{"type":"datetime","required":false,"description":"When the subscription was cancelled.","_meta":{"description":"When the subscription was cancelled."}},"agreedAmount":{"type":"integer","required":false,"description":"For a pay-what-you-can plan, the amount the subscriber chose to pay, in cents.","_meta":{"description":"For a pay-what-you-can plan, the amount the subscriber chose to pay, in cents."}},"planVersionId":{"type":"foreignKey","required":false,"related":"SubscriptionPlanVersion","description":"The version of the plan terms this subscription is held to for the current period. It is kept up to date automatically.","_meta":{"description":"The version of the plan terms this subscription is held to for the current period. It is kept up to date automatically."}},"planVersionPinnedAt":{"type":"datetime","required":false},"planVersionPinReason":{"type":"text","required":false,"enum":["period_start","renewal","upgrade","authorized","migration"]},"planVersionPinNote":{"type":"text","required":false,"default":""},"retainsPaidPeriod":{"type":"boolean","required":false,"default":false},"externalProvider":{"type":"text","required":false},"stripeCustomerId":{"type":"text","required":false,"default":""},"stripeSubscriptionId":{"type":"text","required":false,"default":""},"stripeCheckoutSessionId":{"type":"text","required":false,"default":""},"metadata":{"type":"text","required":false,"default":"{}"}},"methods":{"replacePlanVersion":{"name":"replacePlanVersion","async":true,"parameters":[{"name":"options","type":"any","optional":false,"typeUnresolved":true}],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"isEntitled":{"name":"isEntitled","async":false,"parameters":[{"name":"now","type":"any","optional":true}],"returnType":"boolean","isStatic":false,"isPublic":true},"getSubscriber":{"name":"getSubscriber","async":false,"parameters":[],"returnType":"Subscriber | null","isStatic":false,"isPublic":true},"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"JsonObject","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"metadata","type":"JsonObject","optional":false}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_tenant_subscriptions","api":{"include":["list","get","create","update"]},"cli":{"skipApiCheck":true},"mcp":{"include":["list","get"]},"conflictColumns":["tenant_id","subscriber_kind","subscriber_external_id"],"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"TenantSubscription","collectionExportName":"TenantSubscriptionCollection","validationRules":[],"schema":{"tableName":"_smrt_tenant_subscriptions","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_tenant_subscriptions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"plan_id\\" UUID,\\n \\"status\\" TEXT DEFAULT 'incomplete',\\n \\"started_at\\" TIMESTAMP,\\n \\"current_period_start\\" TIMESTAMP,\\n \\"current_period_end\\" TIMESTAMP,\\n \\"trial_ends_at\\" TIMESTAMP,\\n \\"cancel_at_period_end\\" BOOLEAN DEFAULT FALSE,\\n \\"canceled_at\\" TIMESTAMP,\\n \\"agreed_amount\\" INTEGER,\\n \\"plan_version_id\\" UUID,\\n \\"plan_version_pinned_at\\" TIMESTAMP,\\n \\"plan_version_pin_reason\\" TEXT,\\n \\"plan_version_pin_note\\" TEXT DEFAULT '',\\n \\"retains_paid_period\\" BOOLEAN DEFAULT FALSE,\\n \\"external_provider\\" TEXT,\\n \\"stripe_customer_id\\" TEXT DEFAULT '',\\n \\"stripe_subscription_id\\" TEXT DEFAULT '',\\n \\"stripe_checkout_session_id\\" TEXT DEFAULT '',\\n \\"metadata\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"plan_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_subscription_plans","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"incomplete"},"started_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"current_period_start":{"type":"TIMESTAMP","notNull":false,"unique":false},"current_period_end":{"type":"TIMESTAMP","notNull":false,"unique":false},"trial_ends_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"cancel_at_period_end":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"canceled_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"agreed_amount":{"type":"INTEGER","notNull":false,"unique":false},"plan_version_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_subscription_plan_versions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"plan_version_pinned_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"plan_version_pin_reason":{"type":"TEXT","notNull":false,"unique":false},"plan_version_pin_note":{"type":"TEXT","notNull":false,"unique":false,"default":""},"retains_paid_period":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"external_provider":{"type":"TEXT","notNull":false,"unique":false},"stripe_customer_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"stripe_subscription_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"stripe_checkout_session_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_tenant_subscriptions_tenant_id_subscriber_kind_idx","columns":["tenant_id","subscriber_kind","subscriber_external_id"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_tenant_subscriptions_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_tenant_subscriptions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_tenant_subscriptions_plan_id_idx","columns":["plan_id"]},{"name":"_smrt_tenant_subscriptions_plan_version_id_idx","columns":["plan_version_id"]}],"version":"c281741d"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:TenantUsageMetric":{"name":"tenantusagemetric","className":"TenantUsageMetric","qualifiedName":"@happyvertical/smrt-subscriptions:TenantUsageMetric","collection":"tenantusagemetrics","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/TenantUsageMetric.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"subscriberKind":{"type":"text","required":false,"default":"tenant","enum":["tenant","external"]},"subscriberExternalId":{"type":"text","required":false,"default":""},"metricKey":{"type":"text","required":false,"default":""},"quantity":{"type":"decimal","required":false,"default":0},"windowStart":{"type":"datetime","required":false},"windowEnd":{"type":"datetime","required":false},"source":{"type":"text","required":false,"default":""},"sourceId":{"type":"text","required":false,"default":""},"projectId":{"type":"text","required":false,"default":""},"workRefType":{"type":"text","required":false,"default":""},"workRefId":{"type":"text","required":false,"default":""},"provider":{"type":"text","required":false,"default":""},"dimensions":{"type":"text","required":false,"default":"{}"}},"methods":{"getSubscriber":{"name":"getSubscriber","async":false,"parameters":[],"returnType":"Subscriber | null","isStatic":false,"isPublic":true},"getDimensions":{"name":"getDimensions","async":false,"parameters":[],"returnType":"JsonObject","isStatic":false,"isPublic":true},"setDimensions":{"name":"setDimensions","async":false,"parameters":[{"name":"dimensions","type":"JsonObject","optional":false}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_tenant_usage_metrics","api":{"include":["list","get","create"]},"cli":{"include":["list","get","create"]},"mcp":{"include":["list","get"]},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"TenantUsageMetric","collectionExportName":"TenantUsageMetricCollection","validationRules":[],"schema":{"tableName":"_smrt_tenant_usage_metrics","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_tenant_usage_metrics\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"quantity\\" REAL DEFAULT 0,\\n \\"window_start\\" TIMESTAMP,\\n \\"window_end\\" TIMESTAMP,\\n \\"source\\" TEXT DEFAULT '',\\n \\"source_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"work_ref_type\\" TEXT DEFAULT '',\\n \\"work_ref_id\\" TEXT DEFAULT '',\\n \\"provider\\" TEXT DEFAULT '',\\n \\"dimensions\\" TEXT DEFAULT '{}'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"quantity":{"type":"REAL","notNull":false,"unique":false,"default":0},"window_start":{"type":"TIMESTAMP","notNull":false,"unique":false},"window_end":{"type":"TIMESTAMP","notNull":false,"unique":false},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_type":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":""},"dimensions":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"}},"indexes":[{"name":"_smrt_tenant_usage_metrics_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_tenant_usage_metrics_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"4884a70d"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:PricingRule":{"name":"pricingrule","className":"PricingRule","qualifiedName":"@happyvertical/smrt-subscriptions:PricingRule","collection":"pricingrules","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"ruleKey":{"type":"text","required":false,"default":""},"metricKey":{"type":"text","required":false,"default":""},"serviceKey":{"type":"text","required":false,"default":""},"strategy":{"type":"text","required":false,"default":"fixed_unit","enum":["fixed_unit","cost_plus","multiplier","tiered","included_overage","flat","custom"]},"currency":{"type":"text","required":false,"default":"USD"},"effectiveFrom":{"type":"datetime","required":false},"effectiveTo":{"type":"datetime","required":false},"priority":{"type":"integer","required":false,"default":0},"terms":{"type":"text","required":false,"default":"{}"},"active":{"type":"boolean","required":false,"default":true},"priceBookId":{"type":"foreignKey","required":false,"related":"PriceBook"}},"methods":{"getTerms":{"name":"getTerms","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true},"setTerms":{"name":"setTerms","async":false,"parameters":[{"name":"value","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_pricing_rules","api":true,"cli":true,"mcp":true,"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"PricingRule","collectionExportName":"PricingRuleCollection","validationRules":[],"schema":{"tableName":"_smrt_pricing_rules","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_pricing_rules\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"rule_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"strategy\\" TEXT DEFAULT 'fixed_unit',\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"effective_from\\" TIMESTAMP,\\n \\"effective_to\\" TIMESTAMP,\\n \\"priority\\" INTEGER DEFAULT 0,\\n \\"terms\\" TEXT DEFAULT '{}',\\n \\"active\\" BOOLEAN DEFAULT TRUE,\\n \\"price_book_id\\" UUID\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"rule_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"strategy":{"type":"TEXT","notNull":false,"unique":false,"default":"fixed_unit"},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"effective_from":{"type":"TIMESTAMP","notNull":false,"unique":false},"effective_to":{"type":"TIMESTAMP","notNull":false,"unique":false},"priority":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"terms":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true},"price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}}},"indexes":[{"name":"_smrt_pricing_rules_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_pricing_rules_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_pricing_rules_price_book_id_idx","columns":["price_book_id"]}],"version":"37fd6ea9"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:ClientCharge":{"name":"clientcharge","className":"ClientCharge","qualifiedName":"@happyvertical/smrt-subscriptions:ClientCharge","collection":"clientcharges","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"usageEventId":{"type":"foreignKey","required":false,"related":"TenantUsageMetric"},"usageTenantId":{"type":"crossPackageRef","required":false,"related":"@happyvertical/smrt-users:Tenant"},"subscriberKind":{"type":"text","required":false,"default":"tenant"},"subscriberExternalId":{"type":"text","required":false,"default":""},"projectId":{"type":"text","required":false,"default":""},"workRefType":{"type":"text","required":false,"default":""},"workRefId":{"type":"text","required":false,"default":""},"provider":{"type":"text","required":false,"default":"","description":"Who supplied the service that was used.","_meta":{"description":"Who supplied the service that was used."}},"serviceKey":{"type":"text","required":false,"default":"","description":"The service that was used.","_meta":{"description":"The service that was used."}},"metricKey":{"type":"text","required":false,"default":"","description":"What was used, such as messages sent or minutes of audio.","_meta":{"description":"What was used, such as messages sent or minutes of audio."}},"quantity":{"type":"decimal","required":false,"default":0,"description":"How much of it was used.","_meta":{"description":"How much of it was used."}},"amount":{"type":"integer","required":false,"default":0,"description":"What it cost, in cents.","_meta":{"description":"What it cost, in cents."}},"currency":{"type":"text","required":false,"default":"USD","description":"The currency the amount is in, such as USD.","_meta":{"description":"The currency the amount is in, such as USD."}},"pricingRuleId":{"type":"foreignKey","required":false,"related":"PricingRule"},"priceBookId":{"type":"foreignKey","required":false,"related":"PriceBook"},"pricingSnapshot":{"type":"text","required":false,"default":"{}"},"status":{"type":"text","required":false,"default":"draft","description":"Where the charge stands: draft, approved or adjusted.","_meta":{"description":"Where the charge stands: draft, approved or adjusted."},"enum":["draft","approved","adjusted"]},"approvedAt":{"type":"datetime","required":false,"description":"When the charge was approved.","_meta":{"description":"When the charge was approved."}}},"methods":{"getPricingSnapshot":{"name":"getPricingSnapshot","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_client_charges","api":{"include":["list","get"]},"cli":{"include":["list","get"]},"mcp":{"include":["list","get"]},"conflictColumns":["usage_event_id"],"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"ClientCharge","collectionExportName":"ClientChargeCollection","validationRules":[],"schema":{"tableName":"_smrt_client_charges","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_client_charges\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"usage_event_id\\" UUID,\\n \\"usage_tenant_id\\" UUID,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"work_ref_type\\" TEXT DEFAULT '',\\n \\"work_ref_id\\" TEXT DEFAULT '',\\n \\"provider\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"quantity\\" REAL DEFAULT 0,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"pricing_rule_id\\" UUID,\\n \\"price_book_id\\" UUID,\\n \\"pricing_snapshot\\" TEXT DEFAULT '{}',\\n \\"status\\" TEXT DEFAULT 'draft',\\n \\"approved_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"usage_event_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_tenant_usage_metrics","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"usage_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_type":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"quantity":{"type":"REAL","notNull":false,"unique":false,"default":0},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"pricing_rule_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_pricing_rules","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pricing_snapshot":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"draft"},"approved_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_client_charges_usage_event_id_idx","columns":["usage_event_id"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_client_charges_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_client_charges_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_client_charges_usage_tenant_id_idx","columns":["usage_tenant_id"]},{"name":"_smrt_client_charges_pricing_rule_id_idx","columns":["pricing_rule_id"]},{"name":"_smrt_client_charges_price_book_id_idx","columns":["price_book_id"]}],"version":"92fb8003"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:BillingAdjustment":{"name":"billingadjustment","className":"BillingAdjustment","qualifiedName":"@happyvertical/smrt-subscriptions:BillingAdjustment","collection":"billingadjustments","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"clientChargeId":{"type":"foreignKey","required":false,"related":"ClientCharge"},"amount":{"type":"integer","required":false,"default":0},"currency":{"type":"text","required":false,"default":"USD"},"reason":{"type":"text","required":false,"default":""},"source":{"type":"text","required":false,"default":""},"sourceId":{"type":"text","required":false,"default":""},"createdBy":{"type":"text","required":false,"default":""}},"methods":{},"decoratorConfig":{"tableName":"_smrt_billing_adjustments","api":{"include":["list","get"]},"cli":{"include":["list","get"]},"mcp":{"include":["list","get"]},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"BillingAdjustment","collectionExportName":"BillingAdjustmentCollection","validationRules":[],"schema":{"tableName":"_smrt_billing_adjustments","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_billing_adjustments\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"client_charge_id\\" UUID,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"reason\\" TEXT DEFAULT '',\\n \\"source\\" TEXT DEFAULT '',\\n \\"source_id\\" TEXT DEFAULT '',\\n \\"created_by\\" TEXT DEFAULT ''\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"client_charge_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_client_charges","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"reason":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"created_by":{"type":"TEXT","notNull":false,"unique":false,"default":""}},"indexes":[{"name":"_smrt_billing_adjustments_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_billing_adjustments_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_billing_adjustments_client_charge_id_idx","columns":["client_charge_id"]}],"version":"cfbd2832"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:SpendingPolicy":{"name":"spendingpolicy","className":"SpendingPolicy","qualifiedName":"@happyvertical/smrt-subscriptions:SpendingPolicy","collection":"spendingpolicies","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"name":{"type":"text","required":false,"default":""},"subscriberKind":{"type":"text","required":false,"default":""},"subscriberExternalId":{"type":"text","required":false,"default":""},"projectId":{"type":"text","required":false,"default":""},"serviceKey":{"type":"text","required":false,"default":""},"metricKey":{"type":"text","required":false,"default":""},"period":{"type":"text","required":false,"default":"month","enum":["day","week","month","year","rolling","balance"]},"rollingSeconds":{"type":"integer","required":false,"default":0},"limitAmount":{"type":"integer","required":false,"default":0},"currency":{"type":"text","required":false,"default":"USD"},"behavior":{"type":"text","required":false,"default":"observe","enum":["observe","warn","block","approval_required"]},"priority":{"type":"integer","required":false,"default":0},"active":{"type":"boolean","required":false,"default":true},"basis":{"type":"text","required":false,"default":"billed","enum":["billed","retail","wholesale"]},"setByTenantId":{"type":"crossPackageRef","required":false,"related":"@happyvertical/smrt-users:Tenant"},"balanceFrom":{"type":"datetime","required":false}},"methods":{},"decoratorConfig":{"tableName":"_smrt_spending_policies","conflictColumns":["tenant_id","subscriber_kind","subscriber_external_id","project_id","service_key","metric_key","period","name"],"api":true,"cli":true,"mcp":true,"hooks":{"beforeDelete":"assertDelegationAuthority"},"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"SpendingPolicy","collectionExportName":"SpendingPolicyCollection","displayLabelField":"name","validationRules":[],"schema":{"tableName":"_smrt_spending_policies","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_spending_policies\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"name\\" TEXT DEFAULT '',\\n \\"subscriber_kind\\" TEXT DEFAULT '',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"period\\" TEXT DEFAULT 'month',\\n \\"rolling_seconds\\" INTEGER DEFAULT 0,\\n \\"limit_amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"behavior\\" TEXT DEFAULT 'observe',\\n \\"priority\\" INTEGER DEFAULT 0,\\n \\"active\\" BOOLEAN DEFAULT TRUE,\\n \\"basis\\" TEXT DEFAULT 'billed',\\n \\"set_by_tenant_id\\" UUID,\\n \\"balance_from\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":""},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"period":{"type":"TEXT","notNull":false,"unique":false,"default":"month"},"rolling_seconds":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"limit_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"behavior":{"type":"TEXT","notNull":false,"unique":false,"default":"observe"},"priority":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true},"basis":{"type":"TEXT","notNull":false,"unique":false,"default":"billed"},"set_by_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"balance_from":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_spending_policies_tenant_id_subscriber_kind_idx","columns":["tenant_id","subscriber_kind","subscriber_external_id","project_id","service_key","metric_key","period","name"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_spending_policies_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_spending_policies_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_spending_policies_set_by_tenant_id_idx","columns":["set_by_tenant_id"]}],"version":"21fbbb20"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:PricingRuleCollection":{"name":"pricingrulecollection","className":"PricingRuleCollection","qualifiedName":"@happyvertical/smrt-subscriptions:PricingRuleCollection","collection":"pricingrules","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_pricing_rules"},"extends":"SmrtCollection","extendsTypeArg":"PricingRule","exportName":"PricingRuleCollection","collectionExportName":"PricingRuleCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:PricingRule","schema":{"tableName":"_smrt_pricing_rules","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_pricing_rules\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"rule_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"strategy\\" TEXT DEFAULT 'fixed_unit',\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"effective_from\\" TIMESTAMP,\\n \\"effective_to\\" TIMESTAMP,\\n \\"priority\\" INTEGER DEFAULT 0,\\n \\"terms\\" TEXT DEFAULT '{}',\\n \\"active\\" BOOLEAN DEFAULT TRUE,\\n \\"price_book_id\\" UUID\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"rule_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"strategy":{"type":"TEXT","notNull":false,"unique":false,"default":"fixed_unit"},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"effective_from":{"type":"TIMESTAMP","notNull":false,"unique":false},"effective_to":{"type":"TIMESTAMP","notNull":false,"unique":false},"priority":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"terms":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true},"price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}}},"indexes":[{"name":"_smrt_pricing_rules_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_pricing_rules_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_pricing_rules_price_book_id_idx","columns":["price_book_id"]}],"version":"37fd6ea9"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:ClientChargeCollection":{"name":"clientchargecollection","className":"ClientChargeCollection","qualifiedName":"@happyvertical/smrt-subscriptions:ClientChargeCollection","collection":"clientcharges","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_client_charges","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"ClientCharge","exportName":"ClientChargeCollection","collectionExportName":"ClientChargeCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:ClientCharge","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_client_charges","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_client_charges\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"usage_event_id\\" UUID,\\n \\"usage_tenant_id\\" UUID,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"work_ref_type\\" TEXT DEFAULT '',\\n \\"work_ref_id\\" TEXT DEFAULT '',\\n \\"provider\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"quantity\\" REAL DEFAULT 0,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"pricing_rule_id\\" UUID,\\n \\"price_book_id\\" UUID,\\n \\"pricing_snapshot\\" TEXT DEFAULT '{}',\\n \\"status\\" TEXT DEFAULT 'draft',\\n \\"approved_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"usage_event_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_tenant_usage_metrics","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"usage_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_type":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"quantity":{"type":"REAL","notNull":false,"unique":false,"default":0},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"pricing_rule_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_pricing_rules","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pricing_snapshot":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"draft"},"approved_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_client_charges_usage_event_id_idx","columns":["usage_event_id"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_client_charges_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_client_charges_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_client_charges_usage_tenant_id_idx","columns":["usage_tenant_id"]},{"name":"_smrt_client_charges_pricing_rule_id_idx","columns":["pricing_rule_id"]},{"name":"_smrt_client_charges_price_book_id_idx","columns":["price_book_id"]}],"version":"92fb8003"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:BillingAdjustmentCollection":{"name":"billingadjustmentcollection","className":"BillingAdjustmentCollection","qualifiedName":"@happyvertical/smrt-subscriptions:BillingAdjustmentCollection","collection":"billingadjustments","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_billing_adjustments","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"BillingAdjustment","exportName":"BillingAdjustmentCollection","collectionExportName":"BillingAdjustmentCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:BillingAdjustment","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_billing_adjustments","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_billing_adjustments\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"client_charge_id\\" UUID,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"reason\\" TEXT DEFAULT '',\\n \\"source\\" TEXT DEFAULT '',\\n \\"source_id\\" TEXT DEFAULT '',\\n \\"created_by\\" TEXT DEFAULT ''\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"client_charge_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_client_charges","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"reason":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"created_by":{"type":"TEXT","notNull":false,"unique":false,"default":""}},"indexes":[{"name":"_smrt_billing_adjustments_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_billing_adjustments_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_billing_adjustments_client_charge_id_idx","columns":["client_charge_id"]}],"version":"cfbd2832"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:SpendingPolicyCollection":{"name":"spendingpolicycollection","className":"SpendingPolicyCollection","qualifiedName":"@happyvertical/smrt-subscriptions:SpendingPolicyCollection","collection":"spendingpolicies","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/commercial.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_spending_policies"},"extends":"SmrtCollection","extendsTypeArg":"SpendingPolicy","exportName":"SpendingPolicyCollection","collectionExportName":"SpendingPolicyCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:SpendingPolicy","schema":{"tableName":"_smrt_spending_policies","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_spending_policies\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"name\\" TEXT DEFAULT '',\\n \\"subscriber_kind\\" TEXT DEFAULT '',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"period\\" TEXT DEFAULT 'month',\\n \\"rolling_seconds\\" INTEGER DEFAULT 0,\\n \\"limit_amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"behavior\\" TEXT DEFAULT 'observe',\\n \\"priority\\" INTEGER DEFAULT 0,\\n \\"active\\" BOOLEAN DEFAULT TRUE,\\n \\"basis\\" TEXT DEFAULT 'billed',\\n \\"set_by_tenant_id\\" UUID,\\n \\"balance_from\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":""},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"period":{"type":"TEXT","notNull":false,"unique":false,"default":"month"},"rolling_seconds":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"limit_amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"behavior":{"type":"TEXT","notNull":false,"unique":false,"default":"observe"},"priority":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true},"basis":{"type":"TEXT","notNull":false,"unique":false,"default":"billed"},"set_by_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"balance_from":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_spending_policies_tenant_id_subscriber_kind_idx","columns":["tenant_id","subscriber_kind","subscriber_external_id","project_id","service_key","metric_key","period","name"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_spending_policies_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_spending_policies_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_spending_policies_set_by_tenant_id_idx","columns":["set_by_tenant_id"]}],"version":"21fbbb20"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:PriceBook":{"name":"pricebook","className":"PriceBook","qualifiedName":"@happyvertical/smrt-subscriptions:PriceBook","collection":"pricebooks","description":"A named set of prices published by one seller tenant. Its prices are ordinary PricingRule rows that carry this book's id and the same tenant; one rule per currency gives a price in several currencies.","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"bookKey":{"type":"text","required":false,"default":""},"name":{"type":"text","required":false,"default":""},"kind":{"type":"text","required":false,"default":"retail","enum":["wholesale","retail"]},"active":{"type":"boolean","required":false,"default":true}},"methods":{},"decoratorConfig":{"tableName":"_smrt_price_books","conflictColumns":["tenant_id","book_key"],"api":false,"cli":false,"mcp":false,"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"PriceBook","collectionExportName":"PriceBookCollection","displayLabelField":"name","validationRules":[],"schema":{"tableName":"_smrt_price_books","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_price_books\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"book_key\\" TEXT DEFAULT '',\\n \\"name\\" TEXT DEFAULT '',\\n \\"kind\\" TEXT DEFAULT 'retail',\\n \\"active\\" BOOLEAN DEFAULT TRUE\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"book_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"kind":{"type":"TEXT","notNull":false,"unique":false,"default":"retail"},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true}},"indexes":[{"name":"_smrt_price_books_tenant_id_book_key_idx","columns":["tenant_id","book_key"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_price_books_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_price_books_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"56296d2f"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:PriceBookAssignment":{"name":"pricebookassignment","className":"PriceBookAssignment","qualifiedName":"@happyvertical/smrt-subscriptions:PriceBookAssignment","collection":"pricebookassignments","description":"Which price books rate one child tenant's usage, keyed like the tenancy billing relationship it belongs to (one row per child).","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"childTenantId":{"type":"crossPackageRef","required":true,"related":"@happyvertical/smrt-users:Tenant","_meta":{"required":true}},"resellerTenantId":{"type":"crossPackageRef","required":true,"related":"@happyvertical/smrt-users:Tenant","_meta":{"required":true}},"wholesalePriceBookId":{"type":"foreignKey","required":false,"related":"PriceBook"},"wholesaleCurrency":{"type":"text","required":false,"default":""},"retailPriceBookId":{"type":"foreignKey","required":false,"related":"PriceBook"},"retailCurrency":{"type":"text","required":false,"default":""}},"methods":{},"decoratorConfig":{"tableName":"_smrt_price_book_assignments","conflictColumns":["child_tenant_id"],"api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"PriceBookAssignment","collectionExportName":"PriceBookAssignmentCollection","validationRules":[{"field":"childTenantId","rule":"required","fieldType":"crossPackageRef"},{"field":"resellerTenantId","rule":"required","fieldType":"crossPackageRef"}],"schema":{"tableName":"_smrt_price_book_assignments","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_price_book_assignments\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"child_tenant_id\\" UUID NOT NULL,\\n \\"reseller_tenant_id\\" UUID NOT NULL,\\n \\"wholesale_price_book_id\\" UUID,\\n \\"wholesale_currency\\" TEXT DEFAULT '',\\n \\"retail_price_book_id\\" UUID,\\n \\"retail_currency\\" TEXT DEFAULT ''\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"child_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"reseller_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"wholesale_price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"wholesale_currency":{"type":"TEXT","notNull":false,"unique":false,"default":""},"retail_price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"retail_currency":{"type":"TEXT","notNull":false,"unique":false,"default":""}},"indexes":[{"name":"_smrt_price_book_assignments_child_tenant_id_idx","columns":["child_tenant_id"],"unique":true},{"name":"_smrt_price_book_assignments_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_price_book_assignments_created_at_idx","columns":["created_at"]},{"name":"_smrt_price_book_assignments_reseller_tenant_id_idx","columns":["reseller_tenant_id"]},{"name":"_smrt_price_book_assignments_wholesale_price_book_id_idx","columns":["wholesale_price_book_id"]},{"name":"_smrt_price_book_assignments_retail_price_book_id_idx","columns":["retail_price_book_id"]}],"version":"990da9b7"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:RetailCharge":{"name":"retailcharge","className":"RetailCharge","qualifiedName":"@happyvertical/smrt-subscriptions:RetailCharge","collection":"retailcharges","description":"What a reseller charges one child for one usage event, priced from the reseller's retail book.","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"resellerTenantId":{"type":"crossPackageRef","required":false,"related":"@happyvertical/smrt-users:Tenant"},"usageEventId":{"type":"foreignKey","required":false,"related":"TenantUsageMetric"},"clientChargeId":{"type":"foreignKey","required":false,"related":"ClientCharge"},"subscriberKind":{"type":"text","required":false,"default":"tenant"},"subscriberExternalId":{"type":"text","required":false,"default":""},"projectId":{"type":"text","required":false,"default":""},"workRefType":{"type":"text","required":false,"default":""},"workRefId":{"type":"text","required":false,"default":""},"provider":{"type":"text","required":false,"default":""},"serviceKey":{"type":"text","required":false,"default":""},"metricKey":{"type":"text","required":false,"default":""},"quantity":{"type":"decimal","required":false,"default":0},"amount":{"type":"integer","required":false,"default":0},"currency":{"type":"text","required":false,"default":"USD"},"priceBookId":{"type":"foreignKey","required":false,"related":"PriceBook"},"pricingRuleId":{"type":"foreignKey","required":false,"related":"PricingRule"},"pricingSnapshot":{"type":"text","required":false,"default":"{}"},"status":{"type":"text","required":false,"default":"draft","enum":["draft","approved"]},"approvedAt":{"type":"datetime","required":false}},"methods":{"getPricingSnapshot":{"name":"getPricingSnapshot","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_retail_charges","api":{"include":["list","get"]},"cli":{"include":["list","get"]},"mcp":{"include":["list","get"]},"conflictColumns":["usage_event_id"],"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"RetailCharge","collectionExportName":"RetailChargeCollection","validationRules":[],"schema":{"tableName":"_smrt_retail_charges","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_retail_charges\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"reseller_tenant_id\\" UUID,\\n \\"usage_event_id\\" UUID,\\n \\"client_charge_id\\" UUID,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"work_ref_type\\" TEXT DEFAULT '',\\n \\"work_ref_id\\" TEXT DEFAULT '',\\n \\"provider\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"quantity\\" REAL DEFAULT 0,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"price_book_id\\" UUID,\\n \\"pricing_rule_id\\" UUID,\\n \\"pricing_snapshot\\" TEXT DEFAULT '{}',\\n \\"status\\" TEXT DEFAULT 'draft',\\n \\"approved_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"reseller_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"usage_event_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_tenant_usage_metrics","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"client_charge_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_client_charges","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_type":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"quantity":{"type":"REAL","notNull":false,"unique":false,"default":0},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pricing_rule_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_pricing_rules","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pricing_snapshot":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"draft"},"approved_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_retail_charges_usage_event_id_idx","columns":["usage_event_id"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_retail_charges_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_retail_charges_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_retail_charges_reseller_tenant_id_idx","columns":["reseller_tenant_id"]},{"name":"_smrt_retail_charges_client_charge_id_idx","columns":["client_charge_id"]},{"name":"_smrt_retail_charges_price_book_id_idx","columns":["price_book_id"]},{"name":"_smrt_retail_charges_pricing_rule_id_idx","columns":["pricing_rule_id"]}],"version":"ad6930a8"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:CreditGrant":{"name":"creditgrant","className":"CreditGrant","qualifiedName":"@happyvertical/smrt-subscriptions:CreditGrant","collection":"creditgrants","description":"An append-only credit on a prepaid (period: 'balance') spending policy. Positive amounts add credit; a negative amount reverses an earlier grant.","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{"tenantId":{"type":"text","required":true,"_meta":{"sqlType":"UUID","__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false}}},"spendingPolicyId":{"type":"foreignKey","required":false,"related":"SpendingPolicy"},"amount":{"type":"integer","required":false,"default":0},"currency":{"type":"text","required":false,"default":"USD"},"reason":{"type":"text","required":false,"default":""},"source":{"type":"text","required":false,"default":""},"sourceId":{"type":"text","required":false,"default":""},"grantedByTenantId":{"type":"crossPackageRef","required":false,"related":"@happyvertical/smrt-users:Tenant"}},"methods":{},"decoratorConfig":{"tableName":"_smrt_credit_grants","api":{"include":["list","get"]},"cli":{"include":["list","get"]},"mcp":{"include":["list","get"]},"hooks":{"beforeDelete":"refuseDelete"},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"CreditGrant","collectionExportName":"CreditGrantCollection","validationRules":[],"schema":{"tableName":"_smrt_credit_grants","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_credit_grants\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"spending_policy_id\\" UUID,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"reason\\" TEXT DEFAULT '',\\n \\"source\\" TEXT DEFAULT '',\\n \\"source_id\\" TEXT DEFAULT '',\\n \\"granted_by_tenant_id\\" UUID\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"spending_policy_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_spending_policies","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"reason":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"granted_by_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_credit_grants_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_credit_grants_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_credit_grants_spending_policy_id_idx","columns":["spending_policy_id"]},{"name":"_smrt_credit_grants_granted_by_tenant_id_idx","columns":["granted_by_tenant_id"]}],"version":"e11305fc"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:PriceBookCollection":{"name":"pricebookcollection","className":"PriceBookCollection","qualifiedName":"@happyvertical/smrt-subscriptions:PriceBookCollection","collection":"pricebooks","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_price_books","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"PriceBook","exportName":"PriceBookCollection","collectionExportName":"PriceBookCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:PriceBook","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_price_books","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_price_books\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"book_key\\" TEXT DEFAULT '',\\n \\"name\\" TEXT DEFAULT '',\\n \\"kind\\" TEXT DEFAULT 'retail',\\n \\"active\\" BOOLEAN DEFAULT TRUE\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"book_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"kind":{"type":"TEXT","notNull":false,"unique":false,"default":"retail"},"active":{"type":"BOOLEAN","notNull":false,"unique":false,"default":true}},"indexes":[{"name":"_smrt_price_books_tenant_id_book_key_idx","columns":["tenant_id","book_key"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_price_books_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_price_books_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"56296d2f"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:PriceBookAssignmentCollection":{"name":"pricebookassignmentcollection","className":"PriceBookAssignmentCollection","qualifiedName":"@happyvertical/smrt-subscriptions:PriceBookAssignmentCollection","collection":"pricebookassignments","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_price_book_assignments","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"PriceBookAssignment","exportName":"PriceBookAssignmentCollection","collectionExportName":"PriceBookAssignmentCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:PriceBookAssignment","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_price_book_assignments","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_price_book_assignments\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"child_tenant_id\\" UUID NOT NULL,\\n \\"reseller_tenant_id\\" UUID NOT NULL,\\n \\"wholesale_price_book_id\\" UUID,\\n \\"wholesale_currency\\" TEXT DEFAULT '',\\n \\"retail_price_book_id\\" UUID,\\n \\"retail_currency\\" TEXT DEFAULT ''\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"child_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"reseller_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"wholesale_price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"wholesale_currency":{"type":"TEXT","notNull":false,"unique":false,"default":""},"retail_price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"retail_currency":{"type":"TEXT","notNull":false,"unique":false,"default":""}},"indexes":[{"name":"_smrt_price_book_assignments_child_tenant_id_idx","columns":["child_tenant_id"],"unique":true},{"name":"_smrt_price_book_assignments_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_price_book_assignments_created_at_idx","columns":["created_at"]},{"name":"_smrt_price_book_assignments_reseller_tenant_id_idx","columns":["reseller_tenant_id"]},{"name":"_smrt_price_book_assignments_wholesale_price_book_id_idx","columns":["wholesale_price_book_id"]},{"name":"_smrt_price_book_assignments_retail_price_book_id_idx","columns":["retail_price_book_id"]}],"version":"990da9b7"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:RetailChargeCollection":{"name":"retailchargecollection","className":"RetailChargeCollection","qualifiedName":"@happyvertical/smrt-subscriptions:RetailChargeCollection","collection":"retailcharges","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_retail_charges","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"RetailCharge","exportName":"RetailChargeCollection","collectionExportName":"RetailChargeCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:RetailCharge","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_retail_charges","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_retail_charges\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"reseller_tenant_id\\" UUID,\\n \\"usage_event_id\\" UUID,\\n \\"client_charge_id\\" UUID,\\n \\"subscriber_kind\\" TEXT DEFAULT 'tenant',\\n \\"subscriber_external_id\\" TEXT DEFAULT '',\\n \\"project_id\\" TEXT DEFAULT '',\\n \\"work_ref_type\\" TEXT DEFAULT '',\\n \\"work_ref_id\\" TEXT DEFAULT '',\\n \\"provider\\" TEXT DEFAULT '',\\n \\"service_key\\" TEXT DEFAULT '',\\n \\"metric_key\\" TEXT DEFAULT '',\\n \\"quantity\\" REAL DEFAULT 0,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"price_book_id\\" UUID,\\n \\"pricing_rule_id\\" UUID,\\n \\"pricing_snapshot\\" TEXT DEFAULT '{}',\\n \\"status\\" TEXT DEFAULT 'draft',\\n \\"approved_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"reseller_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"usage_event_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_tenant_usage_metrics","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"client_charge_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_client_charges","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"subscriber_kind":{"type":"TEXT","notNull":false,"unique":false,"default":"tenant"},"subscriber_external_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"project_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_type":{"type":"TEXT","notNull":false,"unique":false,"default":""},"work_ref_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"provider":{"type":"TEXT","notNull":false,"unique":false,"default":""},"service_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"metric_key":{"type":"TEXT","notNull":false,"unique":false,"default":""},"quantity":{"type":"REAL","notNull":false,"unique":false,"default":0},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"price_book_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_price_books","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pricing_rule_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_pricing_rules","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"pricing_snapshot":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"status":{"type":"TEXT","notNull":false,"unique":false,"default":"draft"},"approved_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_retail_charges_usage_event_id_idx","columns":["usage_event_id"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_retail_charges_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_retail_charges_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_retail_charges_reseller_tenant_id_idx","columns":["reseller_tenant_id"]},{"name":"_smrt_retail_charges_client_charge_id_idx","columns":["client_charge_id"]},{"name":"_smrt_retail_charges_price_book_id_idx","columns":["price_book_id"]},{"name":"_smrt_retail_charges_pricing_rule_id_idx","columns":["pricing_rule_id"]}],"version":"ad6930a8"},"importPath":"@happyvertical/smrt-subscriptions"},"@happyvertical/smrt-subscriptions:CreditGrantCollection":{"name":"creditgrantcollection","className":"CreditGrantCollection","qualifiedName":"@happyvertical/smrt-subscriptions:CreditGrantCollection","collection":"creditgrants","filePath":"/home/runner/work/smrt/smrt/packages/subscriptions/src/models/reseller.ts","packageName":"@happyvertical/smrt-subscriptions","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_credit_grants","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"CreditGrant","exportName":"CreditGrantCollection","collectionExportName":"CreditGrantCollectionCollection","collectionOf":"@happyvertical/smrt-subscriptions:CreditGrant","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_credit_grants","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_credit_grants\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"spending_policy_id\\" UUID,\\n \\"amount\\" INTEGER DEFAULT 0,\\n \\"currency\\" TEXT DEFAULT 'USD',\\n \\"reason\\" TEXT DEFAULT '',\\n \\"source\\" TEXT DEFAULT '',\\n \\"source_id\\" TEXT DEFAULT '',\\n \\"granted_by_tenant_id\\" UUID\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"spending_policy_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"_smrt_spending_policies","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"amount":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"currency":{"type":"TEXT","notNull":false,"unique":false,"default":"USD"},"reason":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source":{"type":"TEXT","notNull":false,"unique":false,"default":""},"source_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"granted_by_tenant_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_credit_grants_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"_smrt_credit_grants_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_credit_grants_spending_policy_id_idx","columns":["spending_policy_id"]},{"name":"_smrt_credit_grants_granted_by_tenant_id_idx","columns":["granted_by_tenant_id"]}],"version":"e11305fc"},"importPath":"@happyvertical/smrt-subscriptions"}},"moduleType":"smrt","recipes":[{"id":"subscriptions.plans","className":"SubscriptionPlansRecipe","label":"Subscriptions","summary":"Sell plans that renew, see who is subscribed to which, and what their usage cost.","synonyms":["subscriptions","subscription plans","plans","memberships","recurring billing","pricing tiers"],"models":["@happyvertical/smrt-subscriptions:SubscriptionPlan","@happyvertical/smrt-subscriptions:SubscriptionPlanVersion","@happyvertical/smrt-subscriptions:TenantSubscription","@happyvertical/smrt-subscriptions:ClientCharge"],"nav":[{"label":"Plans","model":"@happyvertical/smrt-subscriptions:SubscriptionPlan","icon":"tag","description":"The plans you sell, with their price and how often they bill.","noun":"plan"},{"label":"Subscriptions","model":"@happyvertical/smrt-subscriptions:TenantSubscription","icon":"repeat","description":"Who is subscribed to which plan, and where each one stands.","noun":"subscription"},{"label":"Plan versions","model":"@happyvertical/smrt-subscriptions:SubscriptionPlanVersion","icon":"fileText","description":"Every set of terms a plan has had, and from when each applied.","noun":"plan version"},{"label":"Charges","model":"@happyvertical/smrt-subscriptions:ClientCharge","icon":"receipt","description":"What each subscriber used and what it cost them.","noun":"charge"}],"requires":[],"section":{"id":"sales","label":"Sales","icon":"shoppingBag","description":"Customers, orders and quotes: everything you sell."},"options":{"@happyvertical/smrt-subscriptions:SubscriptionPlan":{"fields":{"name":{"order":1},"planKey":{"label":"Plan code","order":2},"description":{"order":3},"status":{"order":4},"priceAmount":{"label":"Price (in cents)","order":5},"currency":{"order":6},"billingInterval":{"label":"Billed every","order":7},"pricingMode":{"label":"How it is priced","order":8},"minimumAmount":{"label":"Minimum (in cents)","visibility":"advanced"},"suggestedAmount":{"label":"Suggested (in cents)","visibility":"advanced"},"sortOrder":{"label":"Position in list","visibility":"advanced"},"tenantId":{"visibility":"hidden"},"features":{"visibility":"hidden"},"thresholds":{"visibility":"hidden"},"externalProvider":{"visibility":"hidden"},"providerProductId":{"visibility":"hidden"},"providerPriceId":{"visibility":"hidden"},"stripeProductId":{"visibility":"hidden"},"stripePriceId":{"visibility":"hidden"},"metadata":{"visibility":"hidden"}}},"@happyvertical/smrt-subscriptions:SubscriptionPlanVersion":{"fields":{"planId":{"label":"Plan","order":1},"version":{"label":"Version number","order":2},"effectiveFrom":{"label":"In force from","order":3},"name":{"order":4},"status":{"order":5},"priceAmount":{"label":"Price (in cents)","order":6},"currency":{"order":7},"billingInterval":{"label":"Billed every","order":8},"planKey":{"label":"Plan code","visibility":"advanced"},"pricingMode":{"label":"How it is priced","visibility":"advanced"},"minimumAmount":{"label":"Minimum (in cents)","visibility":"advanced"},"suggestedAmount":{"label":"Suggested (in cents)","visibility":"advanced"},"tenantId":{"visibility":"hidden"},"features":{"visibility":"hidden"},"thresholds":{"visibility":"hidden"}}},"@happyvertical/smrt-subscriptions:TenantSubscription":{"fields":{"planId":{"label":"Plan","order":1},"status":{"order":2},"startedAt":{"label":"Started on","order":3},"currentPeriodStart":{"label":"Current period starts","order":4},"currentPeriodEnd":{"label":"Current period ends","order":5},"trialEndsAt":{"label":"Trial ends","order":6},"cancelAtPeriodEnd":{"label":"Cancel at end of period","order":7},"canceledAt":{"label":"Cancelled on","visibility":"advanced"},"agreedAmount":{"label":"Agreed amount (in cents)","visibility":"advanced"},"subscriberKind":{"label":"Subscriber type","visibility":"advanced"},"subscriberExternalId":{"label":"Outside subscriber","visibility":"advanced"},"planVersionId":{"label":"Plan version","visibility":"advanced","locked":true},"tenantId":{"visibility":"hidden"},"planVersionPinnedAt":{"visibility":"hidden"},"planVersionPinReason":{"visibility":"hidden"},"planVersionPinNote":{"visibility":"hidden"},"retainsPaidPeriod":{"visibility":"hidden"},"externalProvider":{"visibility":"hidden"},"stripeCustomerId":{"visibility":"hidden"},"stripeSubscriptionId":{"visibility":"hidden"},"stripeCheckoutSessionId":{"visibility":"hidden"},"metadata":{"visibility":"hidden"}}},"@happyvertical/smrt-subscriptions:ClientCharge":{"fields":{"metricKey":{"label":"What was used","order":1},"quantity":{"label":"How much","order":2},"amount":{"label":"Amount (in cents)","order":3},"currency":{"order":4},"status":{"order":5},"approvedAt":{"label":"Approved on","order":6},"serviceKey":{"label":"Service","visibility":"advanced"},"provider":{"visibility":"advanced"},"tenantId":{"visibility":"hidden"},"usageEventId":{"visibility":"hidden"},"usageTenantId":{"visibility":"hidden"},"subscriberKind":{"visibility":"hidden"},"subscriberExternalId":{"visibility":"hidden"},"projectId":{"visibility":"hidden"},"workRefType":{"visibility":"hidden"},"workRefId":{"visibility":"hidden"},"pricingRuleId":{"visibility":"hidden"},"priceBookId":{"visibility":"hidden"},"pricingSnapshot":{"visibility":"hidden"}}}},"help":{"markdown":"## Overview\\n\\nSubscriptions is where you sell plans that renew. A plan says what it costs,\\nhow often it bills and whether it is free, a fixed price or pay what you can.\\nA subscription joins a subscriber to a plan and shows where it stands, from\\ntrial to active to cancelled. Every time you change a plan's terms, the\\nearlier terms are kept as a plan version, so a subscriber who already paid for\\na period keeps what they paid for until it renews. Charges show what each\\nsubscriber used and what it cost them.\\n\\nAll amounts are whole numbers of cents, with no decimal point.\\n\\n## Tasks\\n\\n### Set up a plan\\n\\n1. Open the plans and choose **New**.\\n2. Type the **{field:SubscriptionPlan.name}** customers will see and a short **{field:SubscriptionPlan.planKey}** such as \\"starter\\".\\n3. Choose **{field:SubscriptionPlan.pricingMode}**: free, a fixed price, or pay what you can. This cannot change once the plan is saved; make a new plan instead.\\n4. For a fixed price, enter the **{field:SubscriptionPlan.priceAmount}** in cents and the **{field:SubscriptionPlan.currency}**.\\n5. Set how often it bills in **{field:SubscriptionPlan.billingInterval}**.\\n6. Set the **{field:SubscriptionPlan.status}** to active when it is ready to sell.\\n7. Save.\\n\\n### Change a plan's price or terms\\n\\n1. Open the plan and edit the **{field:SubscriptionPlan.priceAmount}**, **{field:SubscriptionPlan.billingInterval}** or **{field:SubscriptionPlan.status}**.\\n2. Save. The new terms apply to new subscribers and to existing ones from their next renewal; a period already paid for keeps its old terms.\\n\\n### Retire a plan\\n\\n1. Open the plan and set its **{field:SubscriptionPlan.status}** to archived.\\n2. Save. No one new can subscribe to it; existing subscribers keep going until they cancel.\\n\\n### Subscribe someone to a plan\\n\\n1. Open the subscriptions and choose **New**.\\n2. Pick the **{field:TenantSubscription.planId}**.\\n3. Enter the day it **{field:TenantSubscription.startedAt}** and, if there is a free trial, when the **{field:TenantSubscription.trialEndsAt}**.\\n4. Save. The **{field:TenantSubscription.status}** shows where the subscription stands once it has been paid for.\\n\\n### See where a subscription stands\\n\\n1. Open the subscriptions and find the one you want.\\n2. The **{field:TenantSubscription.status}** shows whether it is still incomplete, on trial, active, past due, unpaid or cancelled.\\n3. **{field:TenantSubscription.currentPeriodStart}** and **{field:TenantSubscription.currentPeriodEnd}** show the period that has been paid for.\\n\\n### Cancel a subscription\\n\\n1. Open the subscription.\\n2. Tick **{field:TenantSubscription.cancelAtPeriodEnd}** so it runs out when the current period ends instead of renewing.\\n3. Save.\\n\\n### Look up the terms a subscriber was sold\\n\\nPlan versions are written automatically whenever a plan is saved with changed\\nterms; you cannot add or edit them here.\\n\\n1. Open the plan versions and find the **{field:SubscriptionPlanVersion.planId}** you are interested in.\\n2. Each row shows the **{field:SubscriptionPlanVersion.version}** and the date it was **{field:SubscriptionPlanVersion.effectiveFrom}**.\\n3. Read the **{field:SubscriptionPlanVersion.priceAmount}**, **{field:SubscriptionPlanVersion.currency}** and **{field:SubscriptionPlanVersion.billingInterval}** that applied under it.\\n\\n### See what a subscriber was charged\\n\\nCharges are created by the usage and billing service as usage is recorded;\\nyou cannot add or edit them here.\\n\\n1. Open the charges.\\n2. Each row shows **{field:ClientCharge.metricKey}**, **{field:ClientCharge.quantity}** and the **{field:ClientCharge.amount}** in cents.\\n3. The **{field:ClientCharge.status}** shows whether the charge is still a draft, approved or adjusted.\\n","fieldRefs":["ClientCharge.amount","ClientCharge.metricKey","ClientCharge.quantity","ClientCharge.status","SubscriptionPlan.billingInterval","SubscriptionPlan.currency","SubscriptionPlan.name","SubscriptionPlan.planKey","SubscriptionPlan.priceAmount","SubscriptionPlan.pricingMode","SubscriptionPlan.status","SubscriptionPlanVersion.billingInterval","SubscriptionPlanVersion.currency","SubscriptionPlanVersion.effectiveFrom","SubscriptionPlanVersion.planId","SubscriptionPlanVersion.priceAmount","SubscriptionPlanVersion.version","TenantSubscription.cancelAtPeriodEnd","TenantSubscription.currentPeriodEnd","TenantSubscription.currentPeriodStart","TenantSubscription.planId","TenantSubscription.startedAt","TenantSubscription.status","TenantSubscription.trialEndsAt"]},"demo":{"mode":"server","reasons":["Needs a server because its package does not build for a browser: core migrations (node:crypto, node:os); and its package depends on @happyvertical/smrt-profiles, @happyvertical/smrt-tenancy, @happyvertical/smrt-users, which do not build for a browser (#3617, #3624, #3626)."]}}],"smrtDependencies":["@happyvertical/smrt-core","@happyvertical/smrt-features","@happyvertical/smrt-tenancy","@happyvertical/smrt-users"],"browser":{"status":"server-only","issues":["#3617","#3624","#3626"],"reason":"core migrations (node:crypto, node:os)","via":["@happyvertical/smrt-profiles","@happyvertical/smrt-tenancy","@happyvertical/smrt-users"]},"stampsConstructors":true}`));
12
+ //#endregion
13
+ //#region src/billing/config.ts
14
+ var BILLING_ENV = {
15
+ secretKey: "STRIPE_SECRET_KEY",
16
+ webhookSecret: "STRIPE_WEBHOOK_SECRET",
17
+ webhookTolerance: "STRIPE_WEBHOOK_TOLERANCE",
18
+ metadataSecret: "BILLING_METADATA_SECRET",
19
+ metadataPreviousSecrets: "BILLING_METADATA_PREVIOUS_SECRETS",
20
+ successUrl: "BILLING_SUCCESS_URL",
21
+ cancelUrl: "BILLING_CANCEL_URL",
22
+ portalReturnUrl: "BILLING_PORTAL_RETURN_URL"
23
+ };
24
+ var DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
25
+ var MAX_WEBHOOK_TOLERANCE_SECONDS = 900;
26
+ function priceEnvName(planKey) {
27
+ return `STRIPE_PRICE_${planKey.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}`;
28
+ }
29
+ function read(env, name) {
30
+ const value = env[name]?.trim();
31
+ return value ? value : void 0;
32
+ }
33
+ function required(env, name) {
34
+ const value = read(env, name);
35
+ if (!value) throw new Error(`${name} is required.`);
36
+ return value;
37
+ }
38
+ function assertBillingUrl(name, value) {
39
+ let url;
40
+ try {
41
+ url = new URL(value);
42
+ } catch {
43
+ throw new Error(`${name} must be an absolute URL.`);
44
+ }
45
+ const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]" || url.hostname.endsWith(".localhost");
46
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) throw new Error(`${name} must use https.`);
47
+ if (url.username || url.password) throw new Error(`${name} must not contain credentials.`);
48
+ return value;
49
+ }
50
+ function assertWebhookTolerance(seconds) {
51
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > 900) throw new Error(`The webhook tolerance must be a whole number of seconds from 1 to 900.`);
52
+ return seconds;
53
+ }
54
+ function readBillingEnv(env, options) {
55
+ const secretKey = required(env, BILLING_ENV.secretKey);
56
+ if (!/^(sk|rk)_/.test(secretKey)) throw new Error(`${BILLING_ENV.secretKey} must be a secret key (sk_ or rk_).`);
57
+ const webhookSecret = required(env, BILLING_ENV.webhookSecret);
58
+ if (!webhookSecret.startsWith("whsec_")) throw new Error(`${BILLING_ENV.webhookSecret} must be a webhook signing secret (whsec_).`);
59
+ const toleranceText = read(env, BILLING_ENV.webhookTolerance);
60
+ const tolerance = toleranceText ? Number(toleranceText) : 300;
61
+ try {
62
+ assertWebhookTolerance(tolerance);
63
+ } catch {
64
+ throw new Error(`${BILLING_ENV.webhookTolerance} must be a whole number of seconds from 1 to 900.`);
65
+ }
66
+ const prices = {};
67
+ for (const planKey of options.planKeys) {
68
+ const price = read(env, priceEnvName(planKey));
69
+ if (price) prices[planKey] = price;
70
+ }
71
+ const stripe = { webhookTolerance: tolerance };
72
+ Object.defineProperty(stripe, "secretKey", {
73
+ value: secretKey,
74
+ enumerable: false
75
+ });
76
+ Object.defineProperty(stripe, "webhookSecret", {
77
+ value: webhookSecret,
78
+ enumerable: false
79
+ });
80
+ const metadata = {};
81
+ Object.defineProperty(metadata, "signingSecret", {
82
+ value: read(env, BILLING_ENV.metadataSecret),
83
+ enumerable: false
84
+ });
85
+ Object.defineProperty(metadata, "previousSecrets", {
86
+ value: (read(env, BILLING_ENV.metadataPreviousSecrets) ?? "").split(",").map((entry) => entry.trim()).filter(Boolean),
87
+ enumerable: false
88
+ });
89
+ return {
90
+ stripe,
91
+ metadata,
92
+ prices,
93
+ urls: {
94
+ successUrl: assertBillingUrl(BILLING_ENV.successUrl, required(env, BILLING_ENV.successUrl)),
95
+ cancelUrl: assertBillingUrl(BILLING_ENV.cancelUrl, required(env, BILLING_ENV.cancelUrl)),
96
+ portalReturnUrl: assertBillingUrl(BILLING_ENV.portalReturnUrl, required(env, BILLING_ENV.portalReturnUrl))
97
+ }
98
+ };
99
+ }
11
100
  //#endregion
12
101
  //#region src/models/TenantSubscription.ts
13
- var __defProp$3 = Object.defineProperty;
14
- var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
15
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, {
102
+ var __defProp$4 = Object.defineProperty;
103
+ var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
104
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, {
16
105
  enumerable: true,
17
106
  configurable: true,
18
107
  writable: true,
19
108
  value
20
109
  }) : obj[key] = value;
21
- var __decorateClass$3 = (decorators, target, key, kind) => {
22
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
110
+ var __decorateClass$4 = (decorators, target, key, kind) => {
111
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$4(target, key) : target;
23
112
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
24
- if (kind && result) __defProp$3(target, key, result);
113
+ if (kind && result) __defProp$4(target, key, result);
25
114
  return result;
26
115
  };
27
- var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
116
+ var __publicField$4 = (obj, key, value) => __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
28
117
  var pendingReplacements = /* @__PURE__ */ new WeakMap();
29
118
  var TenantSubscription = class extends SmrtObject {
30
119
  tenantId;
@@ -196,21 +285,21 @@ var TenantSubscription = class extends SmrtObject {
196
285
  this.metadata = stringifyJson(metadata);
197
286
  }
198
287
  };
199
- __publicField$3(TenantSubscription, "__smrtPackage__", "@happyvertical/smrt-subscriptions");
200
- __decorateClass$3([tenantId()], TenantSubscription.prototype, "tenantId", 2);
201
- __decorateClass$3([field({ description: "Whether the subscriber is your own workspace (tenant) or an outside customer (external)." })], TenantSubscription.prototype, "subscriberKind", 2);
202
- __decorateClass$3([field({ description: "Who the outside subscriber is, when the subscriber type is external." })], TenantSubscription.prototype, "subscriberExternalId", 2);
203
- __decorateClass$3([field({ description: "The plan this subscription is for." }), foreignKey("SubscriptionPlan")], TenantSubscription.prototype, "planId", 2);
204
- __decorateClass$3([field({ description: "Where the subscription stands: incomplete, trialing, active, past due, unpaid or cancelled." })], TenantSubscription.prototype, "status", 2);
205
- __decorateClass$3([field({ description: "The day the subscription began." })], TenantSubscription.prototype, "startedAt", 2);
206
- __decorateClass$3([field({ description: "When the current billing period began." })], TenantSubscription.prototype, "currentPeriodStart", 2);
207
- __decorateClass$3([field({ description: "When the current billing period ends and the next one is due." })], TenantSubscription.prototype, "currentPeriodEnd", 2);
208
- __decorateClass$3([field({ description: "When the free trial ends, if there is one." })], TenantSubscription.prototype, "trialEndsAt", 2);
209
- __decorateClass$3([field({ description: "Tick to let the subscription run out at the end of the current period instead of renewing." })], TenantSubscription.prototype, "cancelAtPeriodEnd", 2);
210
- __decorateClass$3([field({ description: "When the subscription was cancelled." })], TenantSubscription.prototype, "canceledAt", 2);
211
- __decorateClass$3([field({ description: "For a pay-what-you-can plan, the amount the subscriber chose to pay, in cents." })], TenantSubscription.prototype, "agreedAmount", 2);
212
- __decorateClass$3([field({ description: "The version of the plan terms this subscription is held to for the current period. It is kept up to date automatically." }), foreignKey("SubscriptionPlanVersion")], TenantSubscription.prototype, "planVersionId", 2);
213
- TenantSubscription = __decorateClass$3([TenantScoped({ mode: "required" }), smrt({
288
+ __publicField$4(TenantSubscription, "__smrtPackage__", "@happyvertical/smrt-subscriptions");
289
+ __decorateClass$4([tenantId()], TenantSubscription.prototype, "tenantId", 2);
290
+ __decorateClass$4([field({ description: "Whether the subscriber is your own workspace (tenant) or an outside customer (external)." })], TenantSubscription.prototype, "subscriberKind", 2);
291
+ __decorateClass$4([field({ description: "Who the outside subscriber is, when the subscriber type is external." })], TenantSubscription.prototype, "subscriberExternalId", 2);
292
+ __decorateClass$4([field({ description: "The plan this subscription is for." }), foreignKey("SubscriptionPlan")], TenantSubscription.prototype, "planId", 2);
293
+ __decorateClass$4([field({ description: "Where the subscription stands: incomplete, trialing, active, past due, unpaid or cancelled." })], TenantSubscription.prototype, "status", 2);
294
+ __decorateClass$4([field({ description: "The day the subscription began." })], TenantSubscription.prototype, "startedAt", 2);
295
+ __decorateClass$4([field({ description: "When the current billing period began." })], TenantSubscription.prototype, "currentPeriodStart", 2);
296
+ __decorateClass$4([field({ description: "When the current billing period ends and the next one is due." })], TenantSubscription.prototype, "currentPeriodEnd", 2);
297
+ __decorateClass$4([field({ description: "When the free trial ends, if there is one." })], TenantSubscription.prototype, "trialEndsAt", 2);
298
+ __decorateClass$4([field({ description: "Tick to let the subscription run out at the end of the current period instead of renewing." })], TenantSubscription.prototype, "cancelAtPeriodEnd", 2);
299
+ __decorateClass$4([field({ description: "When the subscription was cancelled." })], TenantSubscription.prototype, "canceledAt", 2);
300
+ __decorateClass$4([field({ description: "For a pay-what-you-can plan, the amount the subscriber chose to pay, in cents." })], TenantSubscription.prototype, "agreedAmount", 2);
301
+ __decorateClass$4([field({ description: "The version of the plan terms this subscription is held to for the current period. It is kept up to date automatically." }), foreignKey("SubscriptionPlanVersion")], TenantSubscription.prototype, "planVersionId", 2);
302
+ TenantSubscription = __decorateClass$4([TenantScoped({ mode: "required" }), smrt({
214
303
  tableName: "_smrt_tenant_subscriptions",
215
304
  api: { include: [
216
305
  "list",
@@ -281,6 +370,1290 @@ var TenantSubscriptionCollection = class extends SmrtCollection {
281
370
  }
282
371
  };
283
372
  //#endregion
373
+ //#region src/models/BillingCheckoutSession.ts
374
+ var __defProp$3 = Object.defineProperty;
375
+ var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
376
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, {
377
+ enumerable: true,
378
+ configurable: true,
379
+ writable: true,
380
+ value
381
+ }) : obj[key] = value;
382
+ var __decorateClass$3 = (decorators, target, key, kind) => {
383
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
384
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
385
+ if (kind && result) __defProp$3(target, key, result);
386
+ return result;
387
+ };
388
+ var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
389
+ var BillingCheckoutSession = class extends SmrtObject {
390
+ sessionId = "";
391
+ targetTenantId = "";
392
+ status = "pending";
393
+ expiresAt = /* @__PURE__ */ new Date(0);
394
+ completedAt = null;
395
+ /** Why the row needs reconciliation (a code, never provider text). */
396
+ reason = "";
397
+ /** JSON ids needed to reconcile: event, subscription, customer, plan. */
398
+ detail = "{}";
399
+ };
400
+ __publicField$3(BillingCheckoutSession, "__smrtPackage__", "@happyvertical/smrt-subscriptions");
401
+ __decorateClass$3([field({ required: true })], BillingCheckoutSession.prototype, "sessionId", 2);
402
+ __decorateClass$3([field({ description: "The tenant the host created the session for." })], BillingCheckoutSession.prototype, "targetTenantId", 2);
403
+ BillingCheckoutSession = __decorateClass$3([smrt({
404
+ tableName: "_smrt_billing_checkout_sessions",
405
+ conflictColumns: ["session_id"],
406
+ api: false,
407
+ cli: false,
408
+ mcp: false
409
+ })], BillingCheckoutSession);
410
+ var BillingCheckoutSessionCollection = class extends SmrtCollection {
411
+ static _itemClass = BillingCheckoutSession;
412
+ };
413
+ //#endregion
414
+ //#region src/billing/events.ts
415
+ var SUBSCRIPTION_EVENT_TYPES = /* @__PURE__ */ new Set([
416
+ "customer.subscription.created",
417
+ "customer.subscription.updated",
418
+ "customer.subscription.deleted",
419
+ "customer.subscription.paused",
420
+ "customer.subscription.resumed"
421
+ ]);
422
+ var CHECKOUT_COMPLETED = "checkout.session.completed";
423
+ function asRecord(value) {
424
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
425
+ }
426
+ function asString(value) {
427
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
428
+ }
429
+ function externalId(value) {
430
+ return asString(value) ?? asString(asRecord(value)?.id);
431
+ }
432
+ function stripeObject(payload) {
433
+ return asRecord(asRecord(asRecord(payload)?.data)?.object);
434
+ }
435
+ function toDate(value) {
436
+ if (value instanceof Date) return Number.isFinite(value.getTime()) ? value : null;
437
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) return /* @__PURE__ */ new Date(value * 1e3);
438
+ return null;
439
+ }
440
+ var STATUS_MAP = {
441
+ active: "active",
442
+ trialing: "trialing",
443
+ past_due: "past_due",
444
+ unpaid: "unpaid",
445
+ canceled: "canceled",
446
+ incomplete: "incomplete",
447
+ incomplete_expired: "canceled",
448
+ paused: "unpaid"
449
+ };
450
+ function mapSubscriptionStatus(value) {
451
+ return value && STATUS_MAP[value] || "incomplete";
452
+ }
453
+ function stringMap(value) {
454
+ const result = {};
455
+ const record = asRecord(value);
456
+ if (!record) return result;
457
+ for (const [key, entry] of Object.entries(record)) if (typeof entry === "string") result[key] = entry;
458
+ return result;
459
+ }
460
+ function itemList(object) {
461
+ const data = asRecord(object.items)?.data;
462
+ return Array.isArray(data) ? data.map(asRecord).filter((item) => item !== null) : [];
463
+ }
464
+ function subscriptionPriceId(object) {
465
+ for (const item of itemList(object)) {
466
+ const price = externalId(asRecord(item.price)?.id ?? item.price);
467
+ if (price) return price;
468
+ }
469
+ }
470
+ function periodDate(object, key) {
471
+ if (key in object) return toDate(object[key]);
472
+ for (const item of itemList(object)) if (key in item) return toDate(item[key]);
473
+ }
474
+ function subscriptionSnapshotFromObject(object, eventType) {
475
+ const subscriptionId = asString(object.id);
476
+ const customerId = externalId(object.customer);
477
+ if (!subscriptionId || !customerId) return null;
478
+ return {
479
+ subscriptionId,
480
+ customerId,
481
+ status: eventType === "customer.subscription.deleted" ? "canceled" : mapSubscriptionStatus(asString(object.status)),
482
+ priceId: subscriptionPriceId(object),
483
+ startedAt: toDate(object.start_date),
484
+ currentPeriodStart: periodDate(object, "current_period_start"),
485
+ currentPeriodEnd: periodDate(object, "current_period_end"),
486
+ trialEndsAt: "trial_end" in object ? toDate(object.trial_end) : void 0,
487
+ cancelAtPeriodEnd: typeof object.cancel_at_period_end === "boolean" ? object.cancel_at_period_end : void 0,
488
+ canceledAt: "canceled_at" in object ? toDate(object.canceled_at) : void 0,
489
+ endedAt: "ended_at" in object ? toDate(object.ended_at) : void 0
490
+ };
491
+ }
492
+ function subscriptionSnapshotFromState(state) {
493
+ const raw = asRecord(state.raw);
494
+ return {
495
+ subscriptionId: state.externalId,
496
+ customerId: state.customerExternalId,
497
+ status: mapSubscriptionStatus(state.status),
498
+ priceId: raw ? subscriptionPriceId(raw) : void 0,
499
+ startedAt: raw && "start_date" in raw ? toDate(raw.start_date) : void 0,
500
+ currentPeriodStart: state.currentPeriodStart ?? (raw ? periodDate(raw, "current_period_start") : void 0),
501
+ currentPeriodEnd: state.currentPeriodEnd ?? (raw ? periodDate(raw, "current_period_end") : void 0),
502
+ trialEndsAt: state.trialEnd ?? null,
503
+ cancelAtPeriodEnd: state.cancelAtPeriodEnd,
504
+ canceledAt: state.canceledAt ?? null,
505
+ endedAt: raw && "ended_at" in raw ? toDate(raw.ended_at) : void 0
506
+ };
507
+ }
508
+ function checkoutFactsFromObject(object) {
509
+ const sessionId = asString(object.id);
510
+ if (!sessionId) return null;
511
+ return {
512
+ sessionId,
513
+ mode: asString(object.mode),
514
+ paymentStatus: asString(object.payment_status),
515
+ customerId: externalId(object.customer),
516
+ subscriptionId: externalId(object.subscription),
517
+ metadata: stringMap(object.metadata)
518
+ };
519
+ }
520
+ //#endregion
521
+ //#region src/billing/plans.ts
522
+ function planVisibleToTenant(plan, tenantId) {
523
+ return plan.tenantId === null || plan.tenantId === tenantId;
524
+ }
525
+ function providerIsStripe(plan) {
526
+ return !plan.externalProvider || plan.externalProvider === "stripe";
527
+ }
528
+ function priceIdForPlan(plan, prices) {
529
+ const configured = prices?.[plan.planKey]?.trim();
530
+ if (configured) return configured;
531
+ if (!providerIsStripe(plan)) return void 0;
532
+ return plan.providerPriceId?.trim() || plan.stripePriceId?.trim() || void 0;
533
+ }
534
+ var PlanDirectory = class {
535
+ constructor(db, prices, tenantPlans = "deny") {
536
+ this.db = db;
537
+ this.prices = prices;
538
+ this.tenantPlans = tenantPlans;
539
+ }
540
+ db;
541
+ prices;
542
+ tenantPlans;
543
+ sellable(plan, tenantId) {
544
+ return this.tenantPlans === "allow" ? planVisibleToTenant(plan, tenantId) : plan.tenantId === null;
545
+ }
546
+ /**
547
+ * The plan a subscription row already points at, for status-only updates:
548
+ * visibility only, so a row on a legacy tenant plan keeps resolving.
549
+ */
550
+ async findExisting(tenantId, planId) {
551
+ return withSystemContext(async () => {
552
+ const plan = await (await this.collection()).get({ id: planId }, { cache: false });
553
+ return plan && planVisibleToTenant(plan, tenantId) ? plan : null;
554
+ });
555
+ }
556
+ collection() {
557
+ return SubscriptionPlanCollection.create({ db: this.db });
558
+ }
559
+ /** A plan `tenantId` may buy, by key (own plan first if allowed) or by id. */
560
+ async find(tenantId, ref) {
561
+ return withSystemContext(async () => {
562
+ const plans = await this.collection();
563
+ if (ref.planId) {
564
+ const plan = await plans.get({ id: ref.planId }, { cache: false });
565
+ return plan && this.sellable(plan, tenantId) ? plan : null;
566
+ }
567
+ if (ref.planKey) return (this.tenantPlans === "allow" ? await plans.findByPlanKey(tenantId, ref.planKey) : null) ?? await plans.findByPlanKey(null, ref.planKey);
568
+ return null;
569
+ });
570
+ }
571
+ /**
572
+ * The plan a provider price id is sold as, for `tenantId`: configured
573
+ * price map first, then plan price bindings. The tenant's own plan beats a
574
+ * global one.
575
+ */
576
+ async findByPriceId(tenantId, priceId) {
577
+ const mappedKeys = Object.entries(this.prices ?? {}).filter(([, price]) => price === priceId).map(([planKey]) => planKey);
578
+ return withSystemContext(async () => {
579
+ const plans = await this.collection();
580
+ const candidates = [];
581
+ for (const planKey of mappedKeys) {
582
+ const own = this.tenantPlans === "allow" ? await plans.findByPlanKey(tenantId, planKey) : null;
583
+ const global = await plans.findByPlanKey(null, planKey);
584
+ if (own) candidates.push(own);
585
+ if (global) candidates.push(global);
586
+ }
587
+ if (candidates.length === 0) candidates.push(...await plans.list({ where: { providerPriceId: priceId } }), ...await plans.list({ where: { stripePriceId: priceId } }));
588
+ return candidates.filter((plan) => this.sellable(plan, tenantId) && providerIsStripe(plan)).sort((a, b) => Number(b.tenantId === tenantId) - Number(a.tenantId === tenantId))[0] ?? null;
589
+ });
590
+ }
591
+ };
592
+ //#endregion
593
+ //#region src/billing/apply.ts
594
+ var ENTITLEMENT_CLAIMING = /* @__PURE__ */ new Set([
595
+ "active",
596
+ "trialing",
597
+ "past_due",
598
+ "unpaid"
599
+ ]);
600
+ async function lockBillingKeys(ctx, keys) {
601
+ if (!ctx.postgres) return;
602
+ for (const key of [...new Set(keys)].sort()) await ctx.db.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", `smrt-subscriptions:billing:${key}`);
603
+ }
604
+ function ignored(ctx, facts, reason, fields = {}) {
605
+ ctx.logger?.warn?.("billing.event.ignored", {
606
+ eventId: facts.eventId,
607
+ eventType: facts.eventType,
608
+ reason,
609
+ ...fields
610
+ });
611
+ return {
612
+ action: "ignored",
613
+ reason
614
+ };
615
+ }
616
+ function readLastApplied(row) {
617
+ const stripe = row.getMetadata().stripe;
618
+ if (!stripe || typeof stripe !== "object" || Array.isArray(stripe)) return { terminal: false };
619
+ const block = stripe;
620
+ const at = typeof block.lastEventAt === "string" ? new Date(block.lastEventAt) : null;
621
+ return {
622
+ eventId: typeof block.lastEventId === "string" ? block.lastEventId : void 0,
623
+ at: at && Number.isFinite(at.getTime()) ? at : void 0,
624
+ terminal: block.terminal === true
625
+ };
626
+ }
627
+ function readRecordedPrice(row) {
628
+ const stripe = row.getMetadata().stripe;
629
+ if (!stripe || typeof stripe !== "object" || Array.isArray(stripe)) return;
630
+ const price = stripe.priceId;
631
+ return typeof price === "string" && price ? price : void 0;
632
+ }
633
+ function isHeldSubscription(row) {
634
+ const stripe = row.getMetadata().stripe;
635
+ return row.status !== "canceled" && !!stripe && typeof stripe === "object" && !Array.isArray(stripe) && stripe.held === HELD_PRICE_UNMAPPED;
636
+ }
637
+ var HELD_PRICE_UNMAPPED = "price_unmapped";
638
+ var HELD_STATUS = {
639
+ active: "incomplete",
640
+ trialing: "incomplete",
641
+ past_due: "incomplete"
642
+ };
643
+ function isStale(last, facts) {
644
+ if (last.eventId && last.eventId === facts.eventId) return true;
645
+ if (!last.at) return false;
646
+ const delta = facts.eventCreated.getTime() - last.at.getTime();
647
+ if (delta < 0) return true;
648
+ return delta === 0 && last.terminal && facts.eventType !== "checkout.session.completed";
649
+ }
650
+ function stripeMetadata(row, facts, snapshot, planKey, resetProvider, held = false) {
651
+ const base = row ? row.getMetadata() : {};
652
+ const prior = !resetProvider && base.stripe && typeof base.stripe === "object" && !Array.isArray(base.stripe) ? base.stripe : {};
653
+ const observed = facts.observedAt ? /* @__PURE__ */ new Date(Math.floor(facts.observedAt.getTime() / 1e3) * 1e3) : void 0;
654
+ const at = observed && observed.getTime() > facts.eventCreated.getTime() ? observed : facts.eventCreated;
655
+ const { held: _previouslyHeld, ...carried } = prior;
656
+ return {
657
+ ...base,
658
+ planKey,
659
+ stripe: {
660
+ ...carried,
661
+ ...held ? { held: HELD_PRICE_UNMAPPED } : {},
662
+ lastEventId: facts.eventId,
663
+ lastEventType: facts.eventType,
664
+ lastEventAt: at.toISOString(),
665
+ priceId: snapshot.priceId ?? prior.priceId ?? null,
666
+ terminal: snapshot.status === "canceled"
667
+ }
668
+ };
669
+ }
670
+ async function listRows(db, where) {
671
+ return (await TenantSubscriptionCollection.create({ db })).list({
672
+ where,
673
+ limit: 3
674
+ });
675
+ }
676
+ function dateOrKeep(next, current) {
677
+ return next !== void 0 ? next : current ?? null;
678
+ }
679
+ async function writeRow(ctx, write) {
680
+ const { existing, plan, snapshot, facts } = write;
681
+ const planId = String(plan.id);
682
+ const newSubscription = !existing || existing.stripeSubscriptionId !== snapshot.subscriptionId;
683
+ const base = newSubscription ? null : existing;
684
+ let periodEnd = dateOrKeep(snapshot.currentPeriodEnd, base?.currentPeriodEnd);
685
+ if (snapshot.status === "canceled") {
686
+ const endedAt = new Date(Math.min((snapshot.endedAt ?? snapshot.canceledAt ?? facts.eventCreated).getTime(), Date.now()));
687
+ if (!periodEnd || periodEnd.getTime() > endedAt.getTime()) periodEnd = endedAt;
688
+ }
689
+ const fields = {
690
+ status: snapshot.status,
691
+ startedAt: snapshot.startedAt ?? base?.startedAt ?? facts.eventCreated,
692
+ currentPeriodStart: dateOrKeep(snapshot.currentPeriodStart, base?.currentPeriodStart),
693
+ currentPeriodEnd: periodEnd,
694
+ trialEndsAt: dateOrKeep(snapshot.trialEndsAt, base?.trialEndsAt),
695
+ cancelAtPeriodEnd: snapshot.cancelAtPeriodEnd ?? base?.cancelAtPeriodEnd ?? false,
696
+ canceledAt: snapshot.canceledAt !== void 0 ? snapshot.canceledAt : snapshot.status === "canceled" ? base?.canceledAt ?? facts.eventCreated : base?.canceledAt ?? null,
697
+ externalProvider: "stripe",
698
+ stripeCustomerId: snapshot.customerId,
699
+ stripeSubscriptionId: snapshot.subscriptionId,
700
+ stripeCheckoutSessionId: write.checkoutSessionId ?? base?.stripeCheckoutSessionId ?? ""
701
+ };
702
+ const subscriptions = await TenantSubscriptionCollection.create({ db: ctx.db });
703
+ let row;
704
+ if (existing) {
705
+ Object.assign(existing, fields);
706
+ existing.setMetadata(stripeMetadata(existing, facts, snapshot, plan.planKey, newSubscription, write.held));
707
+ if (existing.planId !== planId) await existing.replacePlanVersion({
708
+ planId,
709
+ policy: "authorized",
710
+ reason: `stripe:${facts.eventId}`
711
+ });
712
+ else await existing.save();
713
+ row = existing;
714
+ } else row = await subscriptions.create({
715
+ tenantId: write.tenantId,
716
+ subscriberKind: "tenant",
717
+ subscriberExternalId: "",
718
+ planId,
719
+ ...fields,
720
+ metadata: JSON.stringify(stripeMetadata(null, facts, snapshot, plan.planKey, true))
721
+ });
722
+ ctx.logger?.info?.("billing.subscription.applied", {
723
+ eventId: facts.eventId,
724
+ eventType: facts.eventType,
725
+ tenantId: write.tenantId,
726
+ subscriptionRowId: String(row.id),
727
+ planKey: plan.planKey,
728
+ status: snapshot.status
729
+ });
730
+ return { action: "applied" };
731
+ }
732
+ async function applySubscriptionEvent(ctx, facts, snapshot) {
733
+ return withSystemContext(async () => {
734
+ await lockBillingKeys(ctx, [`subscription:${snapshot.subscriptionId}`]);
735
+ const linked = await listRows(ctx.db, { stripeSubscriptionId: snapshot.subscriptionId });
736
+ if (linked.length === 0) return ignored(ctx, facts, "unlinked_subscription");
737
+ if (linked.length > 1) return ignored(ctx, facts, "ambiguous_subscription");
738
+ const tenantId = String(linked[0].tenantId);
739
+ await lockBillingKeys(ctx, [`subscription:${snapshot.subscriptionId}`, `tenant:${tenantId}`]);
740
+ const current = await listRows(ctx.db, { stripeSubscriptionId: snapshot.subscriptionId });
741
+ if (current.length !== 1 || current[0]?.tenantId !== tenantId) return ignored(ctx, facts, "unlinked_subscription");
742
+ const row = current[0];
743
+ if (row.stripeCustomerId && row.stripeCustomerId !== snapshot.customerId) return ignored(ctx, facts, "customer_mismatch", { tenantId });
744
+ if (isStale(readLastApplied(row), facts)) return ignored(ctx, facts, "stale_event", { tenantId });
745
+ const directory = new PlanDirectory(ctx.db, ctx.prices, ctx.tenantPlans);
746
+ const priced = snapshot.priceId ? await directory.findByPriceId(tenantId, snapshot.priceId) : null;
747
+ const plan = priced ?? await directory.findExisting(tenantId, row.planId);
748
+ if (!plan) throw new Error("The subscription plan could not be resolved.");
749
+ if (!priced && snapshot.priceId) {
750
+ const recorded = readRecordedPrice(row);
751
+ if (snapshot.priceId !== recorded) {
752
+ ctx.logger?.error?.("billing.price.unmapped_held", {
753
+ eventId: facts.eventId,
754
+ tenantId,
755
+ providerStatus: snapshot.status
756
+ });
757
+ return writeRow(ctx, {
758
+ tenantId,
759
+ existing: row,
760
+ plan,
761
+ snapshot: {
762
+ ...snapshot,
763
+ status: HELD_STATUS[snapshot.status] ?? snapshot.status,
764
+ priceId: recorded
765
+ },
766
+ facts,
767
+ held: snapshot.status !== "canceled"
768
+ });
769
+ }
770
+ ctx.logger?.warn?.("billing.price.unmapped", {
771
+ eventId: facts.eventId,
772
+ tenantId
773
+ });
774
+ }
775
+ return writeRow(ctx, {
776
+ tenantId,
777
+ existing: row,
778
+ plan,
779
+ snapshot,
780
+ facts
781
+ });
782
+ });
783
+ }
784
+ async function applyCheckoutCompleted(ctx, facts, link, snapshot) {
785
+ return withSystemContext(async () => {
786
+ const { tenantId } = link;
787
+ await lockBillingKeys(ctx, [`subscription:${snapshot.subscriptionId}`, `tenant:${tenantId}`]);
788
+ const bySubscription = await listRows(ctx.db, { stripeSubscriptionId: snapshot.subscriptionId });
789
+ const byCustomer = await listRows(ctx.db, { stripeCustomerId: snapshot.customerId });
790
+ if ([...bySubscription, ...byCustomer].some((row) => row.tenantId !== tenantId)) return ignored(ctx, facts, "tenant_mismatch", { tenantId });
791
+ if (bySubscription.length > 1) return ignored(ctx, facts, "ambiguous_subscription", { tenantId });
792
+ const ownRows = await listRows(ctx.db, {
793
+ tenantId,
794
+ subscriberKind: "tenant"
795
+ });
796
+ const existing = bySubscription[0] ?? ownRows[0] ?? null;
797
+ if (existing?.stripeSubscriptionId && existing.stripeSubscriptionId !== snapshot.subscriptionId && (ENTITLEMENT_CLAIMING.has(existing.status) || isHeldSubscription(existing))) {
798
+ if (ENTITLEMENT_CLAIMING.has(snapshot.status)) ctx.logger?.error?.("billing.checkout.orphaned_subscription", {
799
+ eventId: facts.eventId,
800
+ tenantId,
801
+ subscriptionId: snapshot.subscriptionId
802
+ });
803
+ return ignored(ctx, facts, "already_subscribed", { tenantId });
804
+ }
805
+ if (existing && existing.stripeSubscriptionId === snapshot.subscriptionId && isStale(readLastApplied(existing), facts)) return ignored(ctx, facts, "stale_event", { tenantId });
806
+ const directory = new PlanDirectory(ctx.db, ctx.prices, ctx.tenantPlans);
807
+ const priced = snapshot.priceId ? await directory.findByPriceId(tenantId, snapshot.priceId) : null;
808
+ const named = await directory.find(tenantId, { planId: link.planId });
809
+ if (priced && named && priced.id !== named.id) ctx.logger?.warn?.("billing.checkout.plan_price_disagree", {
810
+ eventId: facts.eventId,
811
+ tenantId
812
+ });
813
+ const plan = priced ?? named;
814
+ if (!plan) throw new Error("The checkout plan could not be resolved.");
815
+ return writeRow(ctx, {
816
+ tenantId,
817
+ existing,
818
+ plan,
819
+ snapshot,
820
+ facts,
821
+ checkoutSessionId: link.checkoutSessionId
822
+ });
823
+ });
824
+ }
825
+ //#endregion
826
+ //#region src/billing/checkout-sessions.ts
827
+ var METADATA_EXPIRY_KEY = "smrt_exp";
828
+ var CHECKOUT_SESSION_TTL_MS = 1500 * 60 * 1e3;
829
+ function checkBinding(record, input) {
830
+ if (!record) return {
831
+ kind: "reconcile",
832
+ reason: "session_record_missing"
833
+ };
834
+ if (record.status === "completed") return {
835
+ kind: "replay",
836
+ reason: "session_already_completed"
837
+ };
838
+ if (record.status === "needs_reconciliation") return {
839
+ kind: "replay",
840
+ reason: "session_needs_reconciliation"
841
+ };
842
+ if (record.targetTenantId !== input.tenantId) return {
843
+ kind: "reconcile",
844
+ reason: "session_record_mismatch"
845
+ };
846
+ if (!input.exp || !/^\d{1,12}$/.test(input.exp)) return {
847
+ kind: "reconcile",
848
+ reason: "session_record_mismatch"
849
+ };
850
+ const at = input.eventTime.getTime();
851
+ if (at > Number.parseInt(input.exp, 10) * 1e3 || at > new Date(record.expiresAt).getTime()) return {
852
+ kind: "reconcile",
853
+ reason: "session_expired"
854
+ };
855
+ return { kind: "bound" };
856
+ }
857
+ async function recordCheckoutSession(db, input) {
858
+ const sessions = await BillingCheckoutSessionCollection.create({ db });
859
+ if (await sessions.get({ sessionId: input.sessionId })) return;
860
+ try {
861
+ await sessions.create({
862
+ sessionId: input.sessionId,
863
+ targetTenantId: input.tenantId,
864
+ status: "pending",
865
+ expiresAt: input.expiresAt
866
+ });
867
+ } catch (error) {
868
+ if (!await sessions.get({ sessionId: input.sessionId })) throw error;
869
+ }
870
+ }
871
+ function parseReconcileContext(record) {
872
+ try {
873
+ const value = JSON.parse(record.detail);
874
+ const text = (key) => typeof value[key] === "string" ? value[key] : "";
875
+ const parsed = {
876
+ eventId: text("eventId"),
877
+ eventCreated: text("eventCreated"),
878
+ subscriptionId: text("subscriptionId"),
879
+ customerId: text("customerId"),
880
+ planId: text("planId"),
881
+ claimedTenantId: text("claimedTenantId")
882
+ };
883
+ return parsed.subscriptionId && parsed.customerId && Number.isFinite(Date.parse(parsed.eventCreated)) ? parsed : null;
884
+ } catch {
885
+ return null;
886
+ }
887
+ }
888
+ async function completeBoundCheckout(ctx, input, facts, snapshot) {
889
+ await lockBillingKeys(ctx, [`checkout:${input.sessionId}`]);
890
+ const sessions = await BillingCheckoutSessionCollection.create({ db: ctx.db });
891
+ const record = await sessions.get({ sessionId: input.sessionId });
892
+ const verdict = checkBinding(record, input);
893
+ if (verdict.kind === "replay") {
894
+ ctx.logger?.warn?.("billing.checkout.not_relinked", {
895
+ eventId: input.eventId,
896
+ sessionId: input.sessionId,
897
+ reason: verdict.reason
898
+ });
899
+ return {
900
+ action: "ignored",
901
+ reason: verdict.reason
902
+ };
903
+ }
904
+ if (verdict.kind === "reconcile") {
905
+ const context = {
906
+ eventId: input.eventId,
907
+ eventCreated: input.eventTime.toISOString(),
908
+ subscriptionId: snapshot.subscriptionId,
909
+ customerId: snapshot.customerId,
910
+ planId: input.planId,
911
+ claimedTenantId: input.tenantId
912
+ };
913
+ if (record) {
914
+ record.status = "needs_reconciliation";
915
+ record.reason = verdict.reason;
916
+ record.detail = JSON.stringify(context);
917
+ await record.save();
918
+ } else await sessions.create({
919
+ sessionId: input.sessionId,
920
+ targetTenantId: "",
921
+ status: "needs_reconciliation",
922
+ expiresAt: input.eventTime,
923
+ reason: verdict.reason,
924
+ detail: JSON.stringify(context)
925
+ });
926
+ ctx.logger?.error?.("billing.checkout.needs_reconciliation", {
927
+ eventId: input.eventId,
928
+ sessionId: input.sessionId,
929
+ reason: verdict.reason,
930
+ claimedTenantId: input.tenantId,
931
+ subscriptionId: snapshot.subscriptionId
932
+ });
933
+ return {
934
+ action: "needs_reconciliation",
935
+ reason: verdict.reason
936
+ };
937
+ }
938
+ const outcome = await applyCheckoutCompleted(ctx, facts, {
939
+ tenantId: input.tenantId,
940
+ planId: input.planId,
941
+ checkoutSessionId: input.sessionId
942
+ }, snapshot);
943
+ if (outcome.action === "applied" && record) {
944
+ record.status = "completed";
945
+ record.completedAt = /* @__PURE__ */ new Date();
946
+ await record.save();
947
+ }
948
+ return outcome;
949
+ }
950
+ async function loadFlaggedCheckout(db, sessionId) {
951
+ const record = await (await BillingCheckoutSessionCollection.create({ db })).get({ sessionId });
952
+ if (record?.status !== "needs_reconciliation") return null;
953
+ const flagged = parseReconcileContext(record);
954
+ return flagged ? {
955
+ record,
956
+ flagged
957
+ } : null;
958
+ }
959
+ async function reconcileFlaggedCheckout(ctx, input) {
960
+ await lockBillingKeys(ctx, [`checkout:${input.sessionId}`]);
961
+ const loaded = await loadFlaggedCheckout(ctx.db, input.sessionId);
962
+ const planId = input.planId ?? loaded?.flagged.planId;
963
+ if (!loaded || !planId) return null;
964
+ const { record, flagged } = loaded;
965
+ if (input.snapshot.subscriptionId !== flagged.subscriptionId || input.snapshot.customerId !== flagged.customerId) return {
966
+ action: "ignored",
967
+ reason: "checkout_subscription_mismatch"
968
+ };
969
+ const outcome = await applyCheckoutCompleted(ctx, {
970
+ eventId: `reconcile:${input.sessionId}`,
971
+ eventType: CHECKOUT_COMPLETED,
972
+ eventCreated: new Date(flagged.eventCreated),
973
+ observedAt: /* @__PURE__ */ new Date()
974
+ }, {
975
+ tenantId: input.tenantId,
976
+ planId,
977
+ checkoutSessionId: input.sessionId
978
+ }, input.snapshot);
979
+ if (outcome.action === "applied") {
980
+ record.status = "completed";
981
+ record.targetTenantId = input.tenantId;
982
+ record.reason = "reconciled";
983
+ record.completedAt = /* @__PURE__ */ new Date();
984
+ await record.save();
985
+ ctx.logger?.warn?.("billing.checkout.reconciled", {
986
+ sessionId: input.sessionId,
987
+ tenantId: input.tenantId,
988
+ operatorId: input.operatorId,
989
+ subscriptionId: flagged.subscriptionId
990
+ });
991
+ }
992
+ return outcome;
993
+ }
994
+ async function dismissFlaggedCheckout(ctx, input) {
995
+ await lockBillingKeys(ctx, [`checkout:${input.sessionId}`]);
996
+ const loaded = await loadFlaggedCheckout(ctx.db, input.sessionId);
997
+ if (!loaded) return false;
998
+ loaded.record.status = "dismissed";
999
+ loaded.record.reason = "dismissed";
1000
+ loaded.record.completedAt = /* @__PURE__ */ new Date();
1001
+ await loaded.record.save();
1002
+ ctx.logger?.warn?.("billing.checkout.dismissed", {
1003
+ sessionId: input.sessionId,
1004
+ operatorId: input.operatorId,
1005
+ reason: input.reason,
1006
+ subscriptionId: loaded.flagged.subscriptionId
1007
+ });
1008
+ return true;
1009
+ }
1010
+ //#endregion
1011
+ //#region src/billing/signing.ts
1012
+ var METADATA_SIGNATURE_KEY = "smrt_sig";
1013
+ var METADATA_PURPOSE = "tenant_subscription";
1014
+ var encoder$1 = new TextEncoder();
1015
+ function toHex(bytes) {
1016
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1017
+ }
1018
+ async function hmacHex(secret, message) {
1019
+ const key = await crypto.subtle.importKey("raw", encoder$1.encode(secret), {
1020
+ name: "HMAC",
1021
+ hash: "SHA-256"
1022
+ }, false, ["sign"]);
1023
+ return toHex(new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder$1.encode(message))));
1024
+ }
1025
+ function constantTimeEqual(left, right) {
1026
+ if (left.length !== right.length) return false;
1027
+ let diff = 0;
1028
+ for (let index = 0; index < left.length; index += 1) diff |= left.charCodeAt(index) ^ right.charCodeAt(index);
1029
+ return diff === 0;
1030
+ }
1031
+ function canonical(metadata) {
1032
+ return JSON.stringify(Object.entries(metadata).filter(([key, value]) => key.startsWith("smrt_") && key !== "smrt_sig" && value !== "").sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
1033
+ }
1034
+ async function signCheckoutMetadata(metadata, secret) {
1035
+ return {
1036
+ ...metadata,
1037
+ [METADATA_SIGNATURE_KEY]: await hmacHex(`smrt-subscription-checkout:${secret}`, canonical(metadata))
1038
+ };
1039
+ }
1040
+ async function checkoutMetadataValid(metadata, secret) {
1041
+ const given = metadata[METADATA_SIGNATURE_KEY];
1042
+ if (!given) return false;
1043
+ return constantTimeEqual(given, await hmacHex(`smrt-subscription-checkout:${secret}`, canonical(metadata)));
1044
+ }
1045
+ var SECRET_PATTERN = /\b(?:sk|rk|pk|whsec)_[A-Za-z0-9_]{4,}/g;
1046
+ function redactSecrets(text) {
1047
+ return text.replace(SECRET_PATTERN, "[redacted]");
1048
+ }
1049
+ function safeErrorMessage(error) {
1050
+ return redactSecrets(error instanceof Error ? error.message : String(error)).slice(0, 300);
1051
+ }
1052
+ //#endregion
1053
+ //#region src/billing/types.ts
1054
+ var STATUS_BY_CODE = {
1055
+ invalid_request: 400,
1056
+ tenant_mismatch: 403,
1057
+ plan_forbidden: 403,
1058
+ plan_unavailable: 404,
1059
+ plan_not_purchasable: 409,
1060
+ already_subscribed: 409,
1061
+ no_billing_account: 409,
1062
+ checkout_not_reconcilable: 409,
1063
+ price_unconfigured: 503,
1064
+ provider_error: 502
1065
+ };
1066
+ var MESSAGE_BY_CODE = {
1067
+ invalid_request: "The request is not valid.",
1068
+ tenant_mismatch: "The request does not match the signed-in workspace.",
1069
+ plan_unavailable: "That plan is not available.",
1070
+ plan_forbidden: "This workspace cannot buy that plan.",
1071
+ plan_not_purchasable: "That plan cannot be bought online.",
1072
+ price_unconfigured: "Billing is not configured for that plan.",
1073
+ already_subscribed: "This workspace already has a subscription. Use the billing portal to change it.",
1074
+ no_billing_account: "This workspace has no billing account yet.",
1075
+ checkout_not_reconcilable: "That checkout cannot be reconciled.",
1076
+ provider_error: "The billing provider could not complete the request."
1077
+ };
1078
+ var BillingHostError = class extends Error {
1079
+ code;
1080
+ status;
1081
+ constructor(code) {
1082
+ super(MESSAGE_BY_CODE[code]);
1083
+ this.name = "BillingHostError";
1084
+ this.code = code;
1085
+ this.status = STATUS_BY_CODE[code];
1086
+ }
1087
+ };
1088
+ //#endregion
1089
+ //#region src/billing/host.ts
1090
+ var DEFAULT_MAX_WEBHOOK_BODY_BYTES = 1024 * 1024;
1091
+ var MAX_REQUEST_BODY_BYTES = 8 * 1024;
1092
+ var CLAIM_SCOPE = "smrt-subscriptions:billing-webhook";
1093
+ var CHECKOUT_KEY_WINDOW_MS = 600 * 1e3;
1094
+ var REF_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
1095
+ var EMAIL_PATTERN = /^[^\s@]{1,64}@[^\s@]{1,190}\.[^\s@]{1,63}$/;
1096
+ var LIVE_STATUSES = /* @__PURE__ */ new Set([
1097
+ "active",
1098
+ "trialing",
1099
+ "past_due",
1100
+ "unpaid"
1101
+ ]);
1102
+ var encoder = new TextEncoder();
1103
+ async function sha256Hex(value) {
1104
+ const digest = await crypto.subtle.digest("SHA-256", encoder.encode(value));
1105
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
1106
+ }
1107
+ function jsonResponse(status, body, headers = {}) {
1108
+ return new Response(JSON.stringify(body), {
1109
+ status,
1110
+ headers: {
1111
+ "content-type": "application/json; charset=utf-8",
1112
+ "cache-control": "no-store",
1113
+ ...headers
1114
+ }
1115
+ });
1116
+ }
1117
+ function signatureTimestamp(header) {
1118
+ let found = null;
1119
+ for (const part of header.split(",")) {
1120
+ const [key, value] = part.trim().split("=", 2);
1121
+ if (key !== "t") continue;
1122
+ if (found !== null || !value || !/^\d{1,12}$/.test(value)) return null;
1123
+ found = Number.parseInt(value, 10);
1124
+ }
1125
+ return found;
1126
+ }
1127
+ async function readBoundedText(request, limit) {
1128
+ if (Number(request.headers.get("content-length") ?? 0) > limit) return null;
1129
+ if (!request.body) return "";
1130
+ const reader = request.body.getReader();
1131
+ const chunks = [];
1132
+ let total = 0;
1133
+ for (;;) {
1134
+ const { done, value } = await reader.read();
1135
+ if (done) break;
1136
+ total += value.byteLength;
1137
+ if (total > limit) {
1138
+ await reader.cancel();
1139
+ return null;
1140
+ }
1141
+ chunks.push(value);
1142
+ }
1143
+ const bytes = new Uint8Array(total);
1144
+ let offset = 0;
1145
+ for (const chunk of chunks) {
1146
+ bytes.set(chunk, offset);
1147
+ offset += chunk.byteLength;
1148
+ }
1149
+ return new TextDecoder().decode(bytes);
1150
+ }
1151
+ function createBillingHost(options) {
1152
+ const { provider, db, urls: rawUrls, prices, canPurchasePlan, logger } = options;
1153
+ if (typeof options.webhookSecret !== "string" || options.webhookSecret.trim() === "") throw new Error("A webhook signing secret is required.");
1154
+ const webhookSecret = options.webhookSecret.trim();
1155
+ const signingSecret = options.metadataSigningSecret?.trim() || webhookSecret;
1156
+ const verificationSecrets = [.../* @__PURE__ */ new Set([signingSecret, ...(options.metadataVerificationSecrets ?? []).map((secret) => secret.trim()).filter(Boolean)])];
1157
+ if (typeof db?.transaction !== "function") throw new Error("The billing host needs a database handle with transaction() support.");
1158
+ const toleranceSeconds = assertWebhookTolerance(options.webhookToleranceSeconds ?? 300);
1159
+ const maxBodyBytes = options.maxWebhookBodyBytes ?? DEFAULT_MAX_WEBHOOK_BODY_BYTES;
1160
+ if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1) throw new Error("maxWebhookBodyBytes must be a positive integer.");
1161
+ const urls = {
1162
+ successUrl: assertBillingUrl("successUrl", rawUrls.successUrl),
1163
+ cancelUrl: assertBillingUrl("cancelUrl", rawUrls.cancelUrl),
1164
+ portalReturnUrl: assertBillingUrl("portalReturnUrl", rawUrls.portalReturnUrl)
1165
+ };
1166
+ const postgres = isPostgresDatabase(db);
1167
+ const tenantPlans = options.tenantPlans ?? "deny";
1168
+ if (tenantPlans !== "deny" && tenantPlans !== "allow") throw new Error("tenantPlans must be 'deny' or 'allow'.");
1169
+ const claimActor = `billing-webhook:${options.accountKey ?? "default"}`;
1170
+ function assertTenant(auth) {
1171
+ const tenantId = auth?.tenantId;
1172
+ if (typeof tenantId !== "string" || tenantId.trim() === "") throw new BillingHostError("invalid_request");
1173
+ const ambient = getTenantId();
1174
+ if (ambient && ambient !== tenantId) throw new BillingHostError("tenant_mismatch");
1175
+ return tenantId;
1176
+ }
1177
+ async function currentSubscription(tenantId) {
1178
+ return withTenant({ tenantId }, async () => {
1179
+ const row = (await (await TenantSubscriptionCollection.create({ db })).list({
1180
+ where: {
1181
+ tenantId,
1182
+ subscriberKind: "tenant"
1183
+ },
1184
+ limit: 1
1185
+ }))[0] ?? null;
1186
+ return row && row.tenantId === tenantId ? row : null;
1187
+ });
1188
+ }
1189
+ async function createCheckout(auth, input) {
1190
+ const tenantId = assertTenant(auth);
1191
+ const planKey = input?.planKey;
1192
+ const planId = input?.planId;
1193
+ if (planKey === void 0 === (planId === void 0) || planKey !== void 0 && !REF_PATTERN.test(planKey) || planId !== void 0 && !REF_PATTERN.test(planId)) throw new BillingHostError("invalid_request");
1194
+ const email = auth.email?.trim();
1195
+ if (email && !EMAIL_PATTERN.test(email)) throw new BillingHostError("invalid_request");
1196
+ const plan = await new PlanDirectory(db, prices, tenantPlans).find(tenantId, {
1197
+ planKey,
1198
+ planId
1199
+ });
1200
+ if (!plan?.isActive()) throw new BillingHostError("plan_unavailable");
1201
+ if (plan.pricingMode !== "fixed" || plan.priceAmount <= 0 || plan.externalProvider && plan.externalProvider !== "stripe") throw new BillingHostError("plan_not_purchasable");
1202
+ const priceId = priceIdForPlan(plan, prices);
1203
+ if (!priceId) throw new BillingHostError("price_unconfigured");
1204
+ const current = await currentSubscription(tenantId);
1205
+ if (current?.stripeSubscriptionId && (LIVE_STATUSES.has(current.status) || isHeldSubscription(current))) throw new BillingHostError("already_subscribed");
1206
+ if (canPurchasePlan && !await canPurchasePlan({
1207
+ tenantId,
1208
+ plan
1209
+ })) throw new BillingHostError("plan_forbidden");
1210
+ const customerExternalId = current?.stripeCustomerId || void 0;
1211
+ const bucket = Math.floor(Date.now() / CHECKOUT_KEY_WINDOW_MS);
1212
+ const expiresAt = new Date((bucket + 1) * CHECKOUT_KEY_WINDOW_MS + CHECKOUT_SESSION_TTL_MS);
1213
+ const idempotencyKey = `smrt-sub-checkout:${(await sha256Hex([
1214
+ tenantId,
1215
+ String(plan.id),
1216
+ priceId,
1217
+ customerExternalId ?? email ?? "",
1218
+ bucket
1219
+ ].join("|"))).slice(0, 48)}`;
1220
+ let session;
1221
+ try {
1222
+ session = await provider.billing.createCheckoutSession({
1223
+ mode: "subscription",
1224
+ successUrl: urls.successUrl,
1225
+ cancelUrl: urls.cancelUrl,
1226
+ ...customerExternalId ? { customerExternalId } : email ? { customerEmail: email } : {},
1227
+ clientReferenceId: tenantId,
1228
+ lineItems: [{
1229
+ price: priceId,
1230
+ quantity: 1
1231
+ }],
1232
+ metadata: await signCheckoutMetadata({
1233
+ smrt_purpose: METADATA_PURPOSE,
1234
+ smrt_tenant_id: tenantId,
1235
+ smrt_plan_id: String(plan.id),
1236
+ smrt_price_id: priceId,
1237
+ [METADATA_EXPIRY_KEY]: String(Math.floor(expiresAt.getTime() / 1e3)),
1238
+ ...customerExternalId ? { smrt_customer_id: customerExternalId } : {}
1239
+ }, signingSecret),
1240
+ idempotencyKey
1241
+ });
1242
+ if (!session.url) throw new Error("Checkout returned no URL.");
1243
+ } catch (error) {
1244
+ logger?.error?.("billing.checkout.provider_error", {
1245
+ tenantId,
1246
+ message: safeErrorMessage(error)
1247
+ });
1248
+ throw new BillingHostError("provider_error");
1249
+ }
1250
+ await withSystemContext(() => recordCheckoutSession(db, {
1251
+ sessionId: session.externalId,
1252
+ tenantId,
1253
+ expiresAt
1254
+ }));
1255
+ return {
1256
+ url: session.url,
1257
+ sessionId: session.externalId
1258
+ };
1259
+ }
1260
+ async function createPortalLink(auth) {
1261
+ const tenantId = assertTenant(auth);
1262
+ const current = await currentSubscription(tenantId);
1263
+ if (!current?.stripeCustomerId) throw new BillingHostError("no_billing_account");
1264
+ try {
1265
+ const session = await provider.billing.createCustomerPortalSession({
1266
+ customerExternalId: current.stripeCustomerId,
1267
+ returnUrl: urls.portalReturnUrl
1268
+ });
1269
+ if (!session.url) throw new Error("Portal returned no URL.");
1270
+ return { url: session.url };
1271
+ } catch (error) {
1272
+ logger?.error?.("billing.portal.provider_error", {
1273
+ tenantId,
1274
+ message: safeErrorMessage(error)
1275
+ });
1276
+ throw new BillingHostError("provider_error");
1277
+ }
1278
+ }
1279
+ function reject(status, error, reason, fields = {}) {
1280
+ logger?.warn?.("billing.webhook.rejected", {
1281
+ reason,
1282
+ ...fields
1283
+ });
1284
+ return {
1285
+ status,
1286
+ body: {
1287
+ received: false,
1288
+ error
1289
+ }
1290
+ };
1291
+ }
1292
+ async function claimExists(eventId) {
1293
+ const claimKey = deriveRunOnceClaimKey({
1294
+ tenantId: CLAIM_SCOPE,
1295
+ actor: claimActor,
1296
+ token: eventId,
1297
+ contentDigest: digestRunOnceContent({ provider: "stripe" })
1298
+ });
1299
+ return (await db.get(RUN_ONCE_CLAIMS_TABLE, {
1300
+ claim_key: claimKey,
1301
+ tenant_id: CLAIM_SCOPE
1302
+ }))?.status === "completed";
1303
+ }
1304
+ async function handleWebhook(input) {
1305
+ const { payload, signature } = input;
1306
+ if (typeof payload !== "string") return reject(400, "invalid_payload", "payload_not_text");
1307
+ if (encoder.encode(payload).byteLength > maxBodyBytes) return reject(413, "payload_too_large", "payload_too_large");
1308
+ if (!signature) return reject(400, "invalid_signature", "missing_signature");
1309
+ const timestamp = signatureTimestamp(signature);
1310
+ if (timestamp === null) return reject(400, "invalid_signature", "malformed_signature");
1311
+ if (Math.abs(Date.now() / 1e3 - timestamp) > toleranceSeconds) return reject(400, "invalid_signature", "timestamp_outside_tolerance");
1312
+ let verified = false;
1313
+ try {
1314
+ verified = provider.webhooks.verify(payload, signature, webhookSecret);
1315
+ } catch {
1316
+ verified = false;
1317
+ }
1318
+ if (!verified) return reject(400, "invalid_signature", "bad_signature");
1319
+ let event;
1320
+ try {
1321
+ event = provider.webhooks.parse(payload);
1322
+ } catch {
1323
+ return reject(400, "invalid_payload", "unparseable_payload");
1324
+ }
1325
+ const eventId = event.id;
1326
+ if (!eventId) return reject(400, "invalid_payload", "missing_event_id");
1327
+ const object = stripeObject(event.payload);
1328
+ const eventLog = {
1329
+ eventId,
1330
+ eventType: event.type
1331
+ };
1332
+ const ignoredResponse = (reason) => {
1333
+ logger?.info?.("billing.webhook.ignored", {
1334
+ ...eventLog,
1335
+ reason
1336
+ });
1337
+ return {
1338
+ status: 200,
1339
+ body: {
1340
+ received: true,
1341
+ outcome: "ignored"
1342
+ }
1343
+ };
1344
+ };
1345
+ const isSubscriptionEvent = SUBSCRIPTION_EVENT_TYPES.has(event.type);
1346
+ if (!isSubscriptionEvent && event.type !== "checkout.session.completed") return ignoredResponse("event_type_not_handled");
1347
+ if (!object) return ignoredResponse("malformed_object");
1348
+ const facts = {
1349
+ eventId,
1350
+ eventType: event.type,
1351
+ eventCreated: event.timestamp
1352
+ };
1353
+ try {
1354
+ if (await claimExists(eventId)) {
1355
+ logger?.info?.("billing.webhook.duplicate", eventLog);
1356
+ return {
1357
+ status: 200,
1358
+ body: {
1359
+ received: true,
1360
+ outcome: "duplicate"
1361
+ }
1362
+ };
1363
+ }
1364
+ let work;
1365
+ if (isSubscriptionEvent) {
1366
+ const snapshot = subscriptionSnapshotFromObject(object, event.type);
1367
+ if (!snapshot) return ignoredResponse("malformed_object");
1368
+ work = (tx) => applySubscriptionEvent({
1369
+ db: tx,
1370
+ postgres,
1371
+ tenantPlans,
1372
+ prices,
1373
+ logger
1374
+ }, facts, snapshot);
1375
+ } else {
1376
+ const checkout = checkoutFactsFromObject(object);
1377
+ if (checkout?.mode !== "subscription") return ignoredResponse("not_a_subscription_checkout");
1378
+ const { metadata } = checkout;
1379
+ if (metadata.smrt_purpose !== "tenant_subscription") {
1380
+ logger?.warn?.("billing.webhook.unsigned_checkout", eventLog);
1381
+ return ignoredResponse("checkout_metadata_not_signed");
1382
+ }
1383
+ let signedByUs = false;
1384
+ for (const secret of verificationSecrets) if (await checkoutMetadataValid(metadata, secret)) {
1385
+ signedByUs = true;
1386
+ break;
1387
+ }
1388
+ if (!signedByUs) {
1389
+ logger?.error?.("billing.webhook.checkout_signature_invalid", {
1390
+ ...eventLog,
1391
+ sessionId: checkout.sessionId
1392
+ });
1393
+ return ignoredResponse("checkout_metadata_not_signed");
1394
+ }
1395
+ const tenantId = metadata.smrt_tenant_id;
1396
+ const planId = metadata.smrt_plan_id;
1397
+ if (!tenantId || !planId || !checkout.subscriptionId || !checkout.customerId) return ignoredResponse("checkout_incomplete");
1398
+ const observedAt = /* @__PURE__ */ new Date();
1399
+ const state = await provider.billing.retrieveSubscriptionStatus(checkout.subscriptionId);
1400
+ if (state.externalId !== checkout.subscriptionId || state.customerExternalId !== checkout.customerId) return ignoredResponse("checkout_subscription_mismatch");
1401
+ const snapshot = subscriptionSnapshotFromState(state);
1402
+ if (!metadata.smrt_price_id || snapshot.priceId !== metadata.smrt_price_id || metadata.smrt_customer_id && metadata.smrt_customer_id !== checkout.customerId) {
1403
+ logger?.error?.("billing.checkout.binding_mismatch", {
1404
+ ...eventLog,
1405
+ subscriptionId: state.externalId
1406
+ });
1407
+ return ignoredResponse("checkout_binding_mismatch");
1408
+ }
1409
+ await BillingCheckoutSessionCollection.create({ db });
1410
+ work = (tx) => completeBoundCheckout({
1411
+ db: tx,
1412
+ postgres,
1413
+ tenantPlans,
1414
+ prices,
1415
+ logger
1416
+ }, {
1417
+ sessionId: checkout.sessionId,
1418
+ tenantId,
1419
+ planId,
1420
+ exp: metadata[METADATA_EXPIRY_KEY],
1421
+ eventId,
1422
+ eventTime: event.timestamp
1423
+ }, {
1424
+ ...facts,
1425
+ observedAt
1426
+ }, snapshot);
1427
+ }
1428
+ const outcome = await withSystemContext(() => runOnce({
1429
+ db,
1430
+ tenantId: CLAIM_SCOPE,
1431
+ actor: claimActor,
1432
+ token: eventId,
1433
+ content: { provider: "stripe" }
1434
+ }, work));
1435
+ logger?.info?.("billing.webhook.processed", {
1436
+ ...eventLog,
1437
+ outcome: outcome.action,
1438
+ ...outcome.reason ? { reason: outcome.reason } : {}
1439
+ });
1440
+ return {
1441
+ status: 200,
1442
+ body: {
1443
+ received: true,
1444
+ outcome: outcome.action
1445
+ }
1446
+ };
1447
+ } catch (error) {
1448
+ if (error instanceof RunOnceClaimError) {
1449
+ logger?.warn?.("billing.webhook.in_flight", eventLog);
1450
+ return {
1451
+ status: 409,
1452
+ body: {
1453
+ received: false,
1454
+ error: "in_flight"
1455
+ }
1456
+ };
1457
+ }
1458
+ logger?.error?.("billing.webhook.failed", {
1459
+ ...eventLog,
1460
+ message: safeErrorMessage(error)
1461
+ });
1462
+ return {
1463
+ status: 500,
1464
+ body: {
1465
+ received: false,
1466
+ error: "processing_failed"
1467
+ }
1468
+ };
1469
+ }
1470
+ }
1471
+ async function listCheckoutsNeedingReconciliation(options2) {
1472
+ const limit = Math.min(Math.max(Math.trunc(Number(options2?.limit ?? 200)) || 200, 1), 1e3);
1473
+ const offset = Math.max(Math.trunc(Number(options2?.offset ?? 0)) || 0, 0);
1474
+ return withSystemContext(async () => {
1475
+ const sessions = await BillingCheckoutSessionCollection.create({ db });
1476
+ const rows = await sessions.list({
1477
+ where: { status: "needs_reconciliation" },
1478
+ orderBy: "created_at ASC",
1479
+ limit,
1480
+ offset
1481
+ });
1482
+ const result = [];
1483
+ for (const row of rows) {
1484
+ const flagged = parseReconcileContext(row);
1485
+ const claimed = flagged?.claimedTenantId ?? "";
1486
+ let hasOwn = false;
1487
+ if (claimed) {
1488
+ for (const status of ["pending", "completed"]) if ((await sessions.list({
1489
+ where: {
1490
+ targetTenantId: claimed,
1491
+ status
1492
+ },
1493
+ limit: 1
1494
+ })).length > 0) hasOwn = true;
1495
+ }
1496
+ result.push({
1497
+ sessionId: row.sessionId,
1498
+ reason: row.reason,
1499
+ claimedTenantId: claimed,
1500
+ subscriptionId: flagged?.subscriptionId ?? "",
1501
+ customerId: flagged?.customerId ?? "",
1502
+ targetTenantId: row.targetTenantId,
1503
+ claimedTenantHasOwnSession: hasOwn,
1504
+ eventId: flagged?.eventId ?? "",
1505
+ flaggedAt: new Date(row.updated_at ?? row.created_at ?? Date.now())
1506
+ });
1507
+ }
1508
+ return result;
1509
+ });
1510
+ }
1511
+ async function countCheckoutsNeedingReconciliation() {
1512
+ return withSystemContext(async () => {
1513
+ return (await BillingCheckoutSessionCollection.create({ db })).count({ where: { status: "needs_reconciliation" } });
1514
+ });
1515
+ }
1516
+ async function dismissCheckout(input) {
1517
+ const { sessionId, operatorId, reason } = input ?? {};
1518
+ if (typeof sessionId !== "string" || !REF_PATTERN.test(sessionId) || typeof operatorId !== "string" || !/^\S{1,128}$/.test(operatorId) || typeof reason !== "string" || reason.trim().length === 0 || reason.length > 200) throw new BillingHostError("invalid_request");
1519
+ await withSystemContext(async () => {
1520
+ if (!await db.transaction?.((tx) => dismissFlaggedCheckout({
1521
+ db: tx,
1522
+ postgres,
1523
+ tenantPlans,
1524
+ prices,
1525
+ logger
1526
+ }, {
1527
+ sessionId,
1528
+ operatorId,
1529
+ reason: reason.trim()
1530
+ }))) throw new BillingHostError("checkout_not_reconcilable");
1531
+ });
1532
+ }
1533
+ async function reconcileCheckout(input) {
1534
+ const { sessionId, tenantId, planId, operatorId } = input ?? {};
1535
+ if (typeof sessionId !== "string" || !REF_PATTERN.test(sessionId) || typeof tenantId !== "string" || !REF_PATTERN.test(tenantId) || planId !== void 0 && (typeof planId !== "string" || !REF_PATTERN.test(planId)) || typeof operatorId !== "string" || !/^\S{1,128}$/.test(operatorId)) throw new BillingHostError("invalid_request");
1536
+ return withSystemContext(async () => {
1537
+ const loaded = await loadFlaggedCheckout(db, sessionId);
1538
+ if (!loaded) throw new BillingHostError("checkout_not_reconcilable");
1539
+ let snapshot;
1540
+ try {
1541
+ snapshot = subscriptionSnapshotFromState(await provider.billing.retrieveSubscriptionStatus(loaded.flagged.subscriptionId));
1542
+ } catch (error) {
1543
+ logger?.error?.("billing.reconcile.provider_error", {
1544
+ sessionId,
1545
+ message: safeErrorMessage(error)
1546
+ });
1547
+ throw new BillingHostError("provider_error");
1548
+ }
1549
+ const outcome = await db.transaction?.((tx) => reconcileFlaggedCheckout({
1550
+ db: tx,
1551
+ postgres,
1552
+ tenantPlans,
1553
+ prices,
1554
+ logger
1555
+ }, {
1556
+ sessionId,
1557
+ tenantId,
1558
+ planId,
1559
+ operatorId,
1560
+ snapshot
1561
+ }));
1562
+ if (!outcome) throw new BillingHostError("checkout_not_reconcilable");
1563
+ return {
1564
+ outcome: outcome.action === "applied" ? "applied" : "ignored",
1565
+ ...outcome.reason ? { reason: outcome.reason } : {}
1566
+ };
1567
+ });
1568
+ }
1569
+ function errorResponse(error) {
1570
+ if (error instanceof BillingHostError) return jsonResponse(error.status, {
1571
+ error: error.code,
1572
+ message: error.message
1573
+ });
1574
+ logger?.error?.("billing.request.failed", { message: safeErrorMessage(error) });
1575
+ return jsonResponse(500, { error: "internal_error" });
1576
+ }
1577
+ async function readSmallBody(request) {
1578
+ const text = await readBoundedText(request, MAX_REQUEST_BODY_BYTES);
1579
+ if (text === null) throw new BillingHostError("invalid_request");
1580
+ return text;
1581
+ }
1582
+ async function readPlanRef(request) {
1583
+ const type = request.headers.get("content-type") ?? "";
1584
+ let values;
1585
+ try {
1586
+ if (type.includes("application/json")) {
1587
+ const parsed = JSON.parse(await readSmallBody(request));
1588
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
1589
+ values = parsed;
1590
+ } else {
1591
+ const form = new URLSearchParams(await readSmallBody(request));
1592
+ values = Object.fromEntries(form.entries());
1593
+ }
1594
+ } catch (error) {
1595
+ if (error instanceof BillingHostError) throw error;
1596
+ throw new BillingHostError("invalid_request");
1597
+ }
1598
+ const ref = {};
1599
+ if (values.planKey !== void 0) {
1600
+ if (typeof values.planKey !== "string") throw new BillingHostError("invalid_request");
1601
+ ref.planKey = values.planKey;
1602
+ }
1603
+ if (values.planId !== void 0) {
1604
+ if (typeof values.planId !== "string") throw new BillingHostError("invalid_request");
1605
+ ref.planId = values.planId;
1606
+ }
1607
+ return ref;
1608
+ }
1609
+ return {
1610
+ createCheckout,
1611
+ createPortalLink,
1612
+ listCheckoutsNeedingReconciliation,
1613
+ countCheckoutsNeedingReconciliation,
1614
+ dismissCheckout,
1615
+ reconcileCheckout,
1616
+ handleWebhook,
1617
+ handlers: {
1618
+ async checkout(request, auth) {
1619
+ if (request.method !== "POST") return jsonResponse(405, { error: "method_not_allowed" }, { allow: "POST" });
1620
+ try {
1621
+ return jsonResponse(200, await createCheckout(auth, await readPlanRef(request)));
1622
+ } catch (error) {
1623
+ return errorResponse(error);
1624
+ }
1625
+ },
1626
+ async portal(request, auth) {
1627
+ if (request.method !== "POST" && request.method !== "GET") return jsonResponse(405, { error: "method_not_allowed" }, { allow: "GET, POST" });
1628
+ try {
1629
+ return jsonResponse(200, await createPortalLink(auth));
1630
+ } catch (error) {
1631
+ return errorResponse(error);
1632
+ }
1633
+ },
1634
+ async webhook(request) {
1635
+ if (request.method !== "POST") return jsonResponse(405, { error: "method_not_allowed" }, { allow: "POST" });
1636
+ let payload;
1637
+ try {
1638
+ payload = await readBoundedText(request, maxBodyBytes);
1639
+ } catch {
1640
+ const rejected = reject(400, "invalid_payload", "unreadable_body");
1641
+ return jsonResponse(rejected.status, rejected.body);
1642
+ }
1643
+ if (payload === null) {
1644
+ const rejected = reject(413, "payload_too_large", "payload_too_large");
1645
+ return jsonResponse(rejected.status, rejected.body);
1646
+ }
1647
+ const result = await handleWebhook({
1648
+ payload,
1649
+ signature: request.headers.get("stripe-signature")
1650
+ });
1651
+ return jsonResponse(result.status, result.body);
1652
+ }
1653
+ }
1654
+ };
1655
+ }
1656
+ //#endregion
284
1657
  //#region src/models/TenantUsageMetric.ts
285
1658
  var __defProp$2 = Object.defineProperty;
286
1659
  var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
@@ -3623,6 +4996,255 @@ var ResellerBillingService = class ResellerBillingService {
3623
4996
  }
3624
4997
  };
3625
4998
  //#endregion
3626
- export { AI_HOSTED_SPEND_METRIC, AI_HOSTED_USER_SPEND_METRIC, BillingAdjustment, BillingAdjustmentCollection, ClientCharge, ClientChargeCollection, CommercialBillingStorageConfigurationError, CommercialUsageService, CreditGrant, CreditGrantCollection, ENTITLEMENT_CHANGE_LISTENERS_SLOT_KEY, FEATURE_GRANT_SOURCE_SLOT_KEY, HostedAiSpendEvaluator, HostedAiSpendPolicyError, MICROS_PER_USD, PLAN_TERM_FIELDS, PriceBook, PriceBookAssignment, PriceBookCollection, PricingRule, PricingRuleCollection, ResellerBillingError, ResellerBillingService, RetailCharge, RetailChargeCollection, SUBSCRIPTIONS_MONEY_COLUMNS, SUBSCRIPTIONS_MONEY_MINOR_UNITS_BACKFILL, SpendingPolicy, SpendingPolicyCollection, SpendingPolicyEvaluator, SubscriptionFeatureSource, SubscriptionPlan, SubscriptionPlanCollection, SubscriptionPlanVersion, SubscriptionPlanVersionCollection, SubscriptionPlansRecipe, SubscriptionResolver, TenantSubscription, TenantSubscriptionCollection, TenantUsageMeter, TenantUsageMetric, TenantUsageMetricCollection, UnsupportedCommercialBillingStorageError, assertCommercialBillingStorageSupported, assertSubscriberInvariant, createHostedAiSpendReader, decideHostedAiSpend, diffEntitlements, emptyEntitlementSnapshot, enabledFeatureKeys, evaluateHostedAiSpendThreshold, evaluateThreshold, evaluateThresholds, extractPlanTerms, getEntitlementChangeListeners, getWindowForThreshold, getWindowKey, hasEntitlementChange, hostedAiSpendThresholds, hostedAiTagFragment, isCurrencyCode, isEntitlementUpgrade, isMissingSubscriptionTableError, isPriceBookKind, isValidThreshold, migrateSubscriptionPlanVersions, migrateSubscriptionsMoneyToMinorUnits, normalizeFeatureGrants, normalizeSubscriber, notifyEntitlementChange, preflightSubscriptionsMoneyMinorUnits, registerEntitlementChangeListener, registerSubscriptionFeatureSource, samePlanTerms, snapshotEntitlements, subscriberToColumns, trackEntitlementChange, validThresholds };
4999
+ //#region src/vault-account/errors.ts
5000
+ var NOT_OWNER_CODE = "not_owner";
5001
+ var NotOwnerError = class extends Error {
5002
+ code = NOT_OWNER_CODE;
5003
+ constructor(message = "Only the account owner may do this.") {
5004
+ super(message);
5005
+ this.name = "NotOwnerError";
5006
+ }
5007
+ };
5008
+ var VaultAccountAdminError = class extends Error {
5009
+ code;
5010
+ constructor(code, message = "The vault account action failed.") {
5011
+ super(message);
5012
+ this.name = "VaultAccountAdminError";
5013
+ this.code = code;
5014
+ }
5015
+ };
5016
+ //#endregion
5017
+ //#region src/vault-account/actions.ts
5018
+ var IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
5019
+ function errorCode(error) {
5020
+ if (error && typeof error === "object") {
5021
+ const code = error.code;
5022
+ if (typeof code === "string" && /^[\w.:-]{1,64}$/.test(code)) return code;
5023
+ const name = error.name;
5024
+ if (typeof name === "string") return name.slice(0, 64);
5025
+ }
5026
+ return "unknown";
5027
+ }
5028
+ var Gate = class {
5029
+ constructor(deps, action, session, subject) {
5030
+ this.deps = deps;
5031
+ this.action = action;
5032
+ this.session = session;
5033
+ this.subject = subject;
5034
+ this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
5035
+ }
5036
+ deps;
5037
+ action;
5038
+ session;
5039
+ subject;
5040
+ now;
5041
+ entry(outcome, extra = {}) {
5042
+ const entry = {
5043
+ at: this.now().toISOString(),
5044
+ action: this.action,
5045
+ outcome,
5046
+ actorUserId: this.session?.user?.id ?? null,
5047
+ tenantId: this.session?.tenantId ?? null,
5048
+ ...extra
5049
+ };
5050
+ for (const [key, value] of Object.entries(this.subject)) if (typeof value === "string") entry[key] = value;
5051
+ return entry;
5052
+ }
5053
+ async deny(error) {
5054
+ await this.recordQuietly(this.entry("denied", { denial: error.code }));
5055
+ throw error;
5056
+ }
5057
+ /**
5058
+ * Run both checks, then the audit-before-act record. Throws
5059
+ * {@link NotOwnerError} or {@link StepUpRequiredError}; resolves with the
5060
+ * verified tenant id.
5061
+ */
5062
+ async authorize(accounts, validate) {
5063
+ const session = this.session;
5064
+ const isOwner = this.deps.isOwner ?? isTenantOwnerSession;
5065
+ let owner = false;
5066
+ try {
5067
+ owner = Boolean(session && isOwner(session));
5068
+ } catch {
5069
+ owner = false;
5070
+ }
5071
+ if (!session || !owner || !session.tenantId || !session.user?.id) return this.deny(new NotOwnerError());
5072
+ const tenantId = session.tenantId;
5073
+ const userId = session.user.id;
5074
+ for (const accountId of accounts) {
5075
+ let owningTenant = null;
5076
+ if (IDENTIFIER.test(accountId)) try {
5077
+ owningTenant = await this.deps.directory.tenantForAccount(accountId);
5078
+ } catch {
5079
+ owningTenant = null;
5080
+ }
5081
+ if (owningTenant !== tenantId) return this.deny(new NotOwnerError());
5082
+ }
5083
+ try {
5084
+ requireRecentAuthentication(session, {
5085
+ maxAgeSeconds: this.deps.stepUpMaxAgeSeconds ?? DEFAULT_STEP_UP_MAX_AGE_SECONDS,
5086
+ now: this.now,
5087
+ expectedSessionId: session.sessionId,
5088
+ expectedUserId: userId
5089
+ });
5090
+ } catch {
5091
+ return this.deny(new StepUpRequiredError());
5092
+ }
5093
+ try {
5094
+ await validate?.(tenantId);
5095
+ } catch (error) {
5096
+ if (error instanceof NotOwnerError) return this.deny(error);
5097
+ throw error;
5098
+ }
5099
+ try {
5100
+ await this.deps.audit.record(this.entry("authorized"));
5101
+ } catch {
5102
+ throw new VaultAccountAdminError("audit_unavailable", "The action could not be recorded, so it was not performed.");
5103
+ }
5104
+ return tenantId;
5105
+ }
5106
+ /** Record the relay call's outcome; a sink failure never undoes the call. */
5107
+ async finish(outcome, extra = {}) {
5108
+ await this.recordQuietly(this.entry(outcome, extra));
5109
+ }
5110
+ async recordQuietly(entry) {
5111
+ try {
5112
+ await this.deps.audit.record(entry);
5113
+ } catch {}
5114
+ }
5115
+ /** Run the single relay call and audit its outcome. */
5116
+ async perform(call, update = {}) {
5117
+ let result;
5118
+ try {
5119
+ result = await call();
5120
+ } catch (error) {
5121
+ await this.finish("failed", {
5122
+ ...update,
5123
+ errorCode: errorCode(error)
5124
+ });
5125
+ throw error;
5126
+ }
5127
+ await this.finish("succeeded", {
5128
+ ...update,
5129
+ result: String(result)
5130
+ });
5131
+ return result;
5132
+ }
5133
+ };
5134
+ function invalid(field) {
5135
+ return new VaultAccountAdminError("invalid_request", `Invalid request: ${field}.`);
5136
+ }
5137
+ async function supersedeVaultAccount(input) {
5138
+ const { oldAccount, newAccount } = input;
5139
+ const gate = new Gate(input, "supersede", input.session, {
5140
+ oldAccountId: oldAccount,
5141
+ newAccountId: newAccount
5142
+ });
5143
+ await gate.authorize([oldAccount, newAccount], () => {
5144
+ if (oldAccount === newAccount) throw invalid("newAccount");
5145
+ });
5146
+ return gate.perform(() => input.relay.supersedeAccount(oldAccount, newAccount));
5147
+ }
5148
+ async function unsupersedeVaultAccount(input) {
5149
+ const { oldAccount } = input;
5150
+ const gate = new Gate(input, "unsupersede", input.session, { oldAccountId: oldAccount });
5151
+ await gate.authorize([oldAccount]);
5152
+ return gate.perform(() => input.relay.clearSupersession(oldAccount));
5153
+ }
5154
+ async function provisionRestartAccount(input) {
5155
+ const { oldAccount, deviceId, devicePublicKey } = input;
5156
+ const subject = {
5157
+ oldAccountId: oldAccount,
5158
+ deviceId
5159
+ };
5160
+ const gate = new Gate(input, "provision_restart_account", input.session, subject);
5161
+ let accountId = "";
5162
+ const tenantId = await gate.authorize([oldAccount], async (tenantId2) => {
5163
+ if (!IDENTIFIER.test(deviceId)) throw invalid("deviceId");
5164
+ if (typeof devicePublicKey !== "string" || !devicePublicKey) throw invalid("devicePublicKey");
5165
+ accountId = await (input.newAccountId ?? (() => crypto.randomUUID()))();
5166
+ if (!IDENTIFIER.test(accountId) || accountId === oldAccount) throw invalid("newAccountId");
5167
+ subject.newAccountId = accountId;
5168
+ let owningTenant;
5169
+ try {
5170
+ owningTenant = await input.directory.tenantForAccount(accountId);
5171
+ } catch {
5172
+ owningTenant = null;
5173
+ }
5174
+ if (owningTenant !== null && owningTenant !== tenantId2) throw new NotOwnerError();
5175
+ });
5176
+ const device = await gate.perform(async () => {
5177
+ await input.directory.linkAccount(tenantId, accountId);
5178
+ const registered = await input.relay.registerDevice(accountId, deviceId, devicePublicKey);
5179
+ if (registered === "conflict") throw new VaultAccountAdminError("device_conflict");
5180
+ return registered;
5181
+ });
5182
+ return {
5183
+ accountId,
5184
+ deviceId,
5185
+ device
5186
+ };
5187
+ }
5188
+ //#endregion
5189
+ //#region src/vault-account/relay-admin-client.ts
5190
+ var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
5191
+ function segment(value) {
5192
+ if (!SEGMENT.test(value)) throw new VaultAccountAdminError("invalid_request");
5193
+ return value;
5194
+ }
5195
+ function createVaultRelayAdminClient(options) {
5196
+ if (!options.adminToken || options.adminToken.length < 32) throw new Error("vault relay admin client: the admin token is required");
5197
+ const base = new URL(options.baseUrl);
5198
+ const token = options.adminToken;
5199
+ const doFetch = options.fetch ?? fetch;
5200
+ async function call(method, path, body) {
5201
+ const response = await doFetch(new URL(path, base), {
5202
+ method,
5203
+ redirect: "error",
5204
+ headers: {
5205
+ authorization: `Bearer ${token}`,
5206
+ ...body ? { "content-type": "application/json" } : {}
5207
+ },
5208
+ ...body ? { body: JSON.stringify(body) } : {}
5209
+ });
5210
+ let code = null;
5211
+ if (response.status >= 400) try {
5212
+ const parsed = await response.json();
5213
+ if (typeof parsed.error === "string" && /^\w{1,64}$/.test(parsed.error)) code = parsed.error;
5214
+ } catch {
5215
+ code = null;
5216
+ }
5217
+ return {
5218
+ status: response.status,
5219
+ code
5220
+ };
5221
+ }
5222
+ const fail = (status, code) => {
5223
+ throw new VaultAccountAdminError(code ?? `relay_${status}`, `The vault relay refused the request (${status}).`);
5224
+ };
5225
+ return {
5226
+ async registerDevice(accountId, deviceId, publicKey) {
5227
+ const { status, code } = await call("PUT", `/admin/v1/accounts/${segment(accountId)}/devices/${segment(deviceId)}`, { publicKey });
5228
+ if (status === 201) return "registered";
5229
+ if (status === 200) return "unchanged";
5230
+ if (status === 409) return "conflict";
5231
+ return fail(status, code);
5232
+ },
5233
+ async supersedeAccount(accountId, supersededBy) {
5234
+ const { status, code } = await call("PUT", `/admin/v1/accounts/${segment(accountId)}/superseded-by`, { supersededBy: segment(supersededBy) });
5235
+ if (status === 201) return "superseded";
5236
+ if (status === 200) return "unchanged";
5237
+ return fail(status, code);
5238
+ },
5239
+ async clearSupersession(accountId) {
5240
+ const { status, code } = await call("DELETE", `/admin/v1/accounts/${segment(accountId)}/superseded-by`);
5241
+ if (status === 204) return true;
5242
+ if (status === 404 && code === "no_supersession") return false;
5243
+ return fail(status, code);
5244
+ }
5245
+ };
5246
+ }
5247
+ //#endregion
5248
+ export { AI_HOSTED_SPEND_METRIC, AI_HOSTED_USER_SPEND_METRIC, BILLING_ENV, BillingAdjustment, BillingAdjustmentCollection, BillingCheckoutSession, BillingHostError, ClientCharge, ClientChargeCollection, CommercialBillingStorageConfigurationError, CommercialUsageService, CreditGrant, CreditGrantCollection, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, ENTITLEMENT_CHANGE_LISTENERS_SLOT_KEY, FEATURE_GRANT_SOURCE_SLOT_KEY, HostedAiSpendEvaluator, HostedAiSpendPolicyError, MAX_WEBHOOK_TOLERANCE_SECONDS, MICROS_PER_USD, NOT_OWNER_CODE, NotOwnerError, PLAN_TERM_FIELDS, PriceBook, PriceBookAssignment, PriceBookCollection, PricingRule, PricingRuleCollection, ResellerBillingError, ResellerBillingService, RetailCharge, RetailChargeCollection, SUBSCRIPTIONS_MONEY_COLUMNS, SUBSCRIPTIONS_MONEY_MINOR_UNITS_BACKFILL, SpendingPolicy, SpendingPolicyCollection, SpendingPolicyEvaluator, StepUpRequiredError, SubscriptionFeatureSource, SubscriptionPlan, SubscriptionPlanCollection, SubscriptionPlanVersion, SubscriptionPlanVersionCollection, SubscriptionPlansRecipe, SubscriptionResolver, TenantSubscription, TenantSubscriptionCollection, TenantUsageMeter, TenantUsageMetric, TenantUsageMetricCollection, UnsupportedCommercialBillingStorageError, VaultAccountAdminError, assertCommercialBillingStorageSupported, assertSubscriberInvariant, createBillingHost, createHostedAiSpendReader, createVaultRelayAdminClient, decideHostedAiSpend, diffEntitlements, emptyEntitlementSnapshot, enabledFeatureKeys, evaluateHostedAiSpendThreshold, evaluateThreshold, evaluateThresholds, extractPlanTerms, getEntitlementChangeListeners, getWindowForThreshold, getWindowKey, hasEntitlementChange, hostedAiSpendThresholds, hostedAiTagFragment, isCurrencyCode, isEntitlementUpgrade, isMissingSubscriptionTableError, isPriceBookKind, isValidThreshold, migrateSubscriptionPlanVersions, migrateSubscriptionsMoneyToMinorUnits, normalizeFeatureGrants, normalizeSubscriber, notifyEntitlementChange, preflightSubscriptionsMoneyMinorUnits, priceEnvName, provisionRestartAccount, readBillingEnv, registerEntitlementChangeListener, registerSubscriptionFeatureSource, samePlanTerms, snapshotEntitlements, subscriberToColumns, supersedeVaultAccount, trackEntitlementChange, unsupersedeVaultAccount, validThresholds };
3627
5249
 
3628
5250
  //# sourceMappingURL=index.js.map