@odla-ai/chapter 0.47.8 → 0.47.9

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.
@@ -1525,12 +1525,12 @@ function validateControlledApplication(chapter, document) {
1525
1525
  return [...document.application.required, ...document.application.optional].filter((field) => !declared.has(field)).map((field) => `document.application field "${field}" is not declared by this chapter schema`);
1526
1526
  }
1527
1527
  function groupAttrs(document) {
1528
- const first4 = [...document.tiers].filter((tier) => tier.available).sort((a, b) => a.sortOrder - b.sortOrder)[0];
1528
+ const first5 = [...document.tiers].filter((tier) => tier.available).sort((a, b) => a.sortOrder - b.sortOrder)[0];
1529
1529
  const firstPaid = [...document.tiers].find((tier) => tier.available && tier.priceCents > 0);
1530
1530
  return {
1531
- ...first4 ? { standardPriceCents: first4.priceCents } : {},
1532
- currency: first4?.currency ?? "usd",
1533
- interval: first4?.interval ?? "year",
1531
+ ...first5 ? { standardPriceCents: first5.priceCents } : {},
1532
+ currency: first5?.currency ?? "usd",
1533
+ interval: first5?.interval ?? "year",
1534
1534
  foundingDiscountCents: 0,
1535
1535
  ...firstPaid?.stripePriceId ? { stripePriceId: firstPaid.stripePriceId } : {},
1536
1536
  ...document.policy ?? {},
@@ -4498,12 +4498,130 @@ async function resolveStripeWebhookSecret(db, runtime) {
4498
4498
 
4499
4499
  // src/payments-route-support.ts
4500
4500
  var paymentErrorCode = (error) => error && typeof error === "object" && typeof error.code === "string" ? error.code : "unknown";
4501
- function paymentLineItems(group) {
4501
+ function paymentLineItems(group, tier) {
4502
4502
  const standard = Number(group.standardPriceCents ?? 0);
4503
4503
  const discount = Number(group.foundingDiscountCents ?? 0);
4504
+ const legacyTier = !tier || tier.id === "standard" && tier.priceCents === standard && tier.stripePriceId === group.stripePriceId;
4505
+ if (!legacyTier) {
4506
+ return { standardCents: tier.priceCents, discountCents: 0, dueTodayCents: tier.priceCents };
4507
+ }
4504
4508
  return { standardCents: standard, discountCents: discount, dueTodayCents: standard - discount };
4505
4509
  }
4506
4510
 
4511
+ // src/subscription-checkout.ts
4512
+ var first3 = (value) => Array.isArray(value) ? value[0] : void 0;
4513
+ function mismatch() {
4514
+ const error = new Error("subscription checkout intent does not match this checkout");
4515
+ error.code = "checkout_intent_mismatch";
4516
+ throw error;
4517
+ }
4518
+ function intentAttrs(input) {
4519
+ return {
4520
+ id: input.applicationId,
4521
+ applicationId: input.applicationId,
4522
+ appId: input.appId,
4523
+ chapterId: input.chapterId,
4524
+ environment: input.environment,
4525
+ ...input.runtime ? { runtime: input.runtime } : {},
4526
+ groupId: input.groupId,
4527
+ tierId: input.tierId,
4528
+ priceId: input.priceId,
4529
+ priceCents: input.priceCents,
4530
+ currency: input.currency,
4531
+ interval: input.interval,
4532
+ purchaserEmailNormalized: input.emailNormalized,
4533
+ ...input.existingCustomerId ? { requestedCustomerId: input.existingCustomerId } : {},
4534
+ status: "created",
4535
+ createdAt: input.now,
4536
+ updatedAt: input.now
4537
+ };
4538
+ }
4539
+ function matchesIntent(stored, expected) {
4540
+ return [
4541
+ "id",
4542
+ "applicationId",
4543
+ "appId",
4544
+ "chapterId",
4545
+ "environment",
4546
+ "runtime",
4547
+ "groupId",
4548
+ "tierId",
4549
+ "priceId",
4550
+ "priceCents",
4551
+ "currency",
4552
+ "interval",
4553
+ "purchaserEmailNormalized",
4554
+ "requestedCustomerId"
4555
+ ].every((key) => stored[key] === expected[key]);
4556
+ }
4557
+ async function loadIntent(db, id) {
4558
+ return first3((await db.query({
4559
+ subscriptionCheckoutIntents: { $: { where: { id }, limit: 1 } }
4560
+ })).subscriptionCheckoutIntents);
4561
+ }
4562
+ async function startSubscriptionCheckout(db, provider, input) {
4563
+ const expected = intentAttrs(input);
4564
+ let stored = await loadIntent(db, input.applicationId);
4565
+ if (!stored) {
4566
+ const write = await db.transact([{
4567
+ t: "update",
4568
+ ns: "subscriptionCheckoutIntents",
4569
+ id: input.applicationId,
4570
+ attrs: expected
4571
+ }], {
4572
+ mutationId: `subscription-checkout-intent:${input.applicationId}`,
4573
+ guards: [{ ns: "subscriptionCheckoutIntents", id: input.applicationId, exists: false }]
4574
+ });
4575
+ stored = write.duplicate ? await loadIntent(db, input.applicationId) : expected;
4576
+ }
4577
+ if (!stored || !matchesIntent(stored, expected)) mismatch();
4578
+ if (stored.status !== "created" && stored.status !== "checkout_ready") mismatch();
4579
+ const result = await provider.createSubscription({
4580
+ appId: input.appId,
4581
+ chapterId: input.chapterId,
4582
+ environment: input.environment,
4583
+ ...input.runtime ? { runtime: input.runtime } : {},
4584
+ applicationId: input.applicationId,
4585
+ groupId: input.groupId,
4586
+ email: input.email,
4587
+ name: input.name,
4588
+ priceId: input.priceId,
4589
+ existingCustomerId: typeof stored.providerCustomerId === "string" ? stored.providerCustomerId : input.existingCustomerId
4590
+ });
4591
+ if (stored.providerCustomerId && stored.providerCustomerId !== result.customerId || stored.providerSubscriptionId && stored.providerSubscriptionId !== result.subscriptionId) mismatch();
4592
+ await db.transact([
4593
+ {
4594
+ t: "update",
4595
+ ns: "subscriptionCheckoutIntents",
4596
+ id: input.applicationId,
4597
+ attrs: {
4598
+ status: "checkout_ready",
4599
+ providerCustomerId: result.customerId,
4600
+ providerSubscriptionId: result.subscriptionId,
4601
+ updatedAt: input.now
4602
+ }
4603
+ },
4604
+ {
4605
+ t: "update",
4606
+ ns: "applications",
4607
+ id: input.applicationId,
4608
+ attrs: {
4609
+ stripeCustomerId: result.customerId,
4610
+ stripeSubscriptionId: result.subscriptionId,
4611
+ ...input.runtime ? { stripeRuntime: input.runtime } : {},
4612
+ refundPolicyAckAt: input.now
4613
+ }
4614
+ }
4615
+ ], {
4616
+ mutationId: `subscription-checkout-ready:${input.applicationId}:${result.subscriptionId}`,
4617
+ guards: [
4618
+ { ns: "subscriptionCheckoutIntents", id: input.applicationId, exists: true, equals: { status: stored.status } },
4619
+ { ns: "applications", id: input.applicationId, exists: true, equals: { status: "submitted" } }
4620
+ ]
4621
+ });
4622
+ return result;
4623
+ }
4624
+
4507
4625
  // src/member-system-contract.ts
4508
4626
  function classifyMemberStripeEvent(identity, target, hasProvenLegacyLocalLink) {
4509
4627
  const keys = ["appId", "environment", "dataEnvironment", "runtime", "chapterId"];
@@ -4672,35 +4790,29 @@ async function startSubscription(req, env, ctx) {
4672
4790
  const provider = createStripeProvider({ secretKey });
4673
4791
  let result;
4674
4792
  try {
4675
- result = await provider.createSubscription({
4793
+ result = await startSubscriptionCheckout(db, provider, {
4676
4794
  appId: env.ODLA_APP_ID,
4677
4795
  chapterId: ctx.chapter.id,
4678
4796
  environment: env.ODLA_ENV,
4679
4797
  runtime: stripeRuntimeIdentity(env.ODLA_RUNTIME),
4680
4798
  applicationId,
4681
4799
  groupId: String(group.id),
4800
+ tierId: tier.id,
4801
+ priceCents: tier.priceCents,
4802
+ currency: tier.currency ?? String(group.currency ?? "usd"),
4803
+ interval: tier.interval ?? (group.interval === "month" ? "month" : "year"),
4682
4804
  email: String(app.email ?? ""),
4805
+ emailNormalized: normalizeChapterEmail(String(app.email ?? "")),
4683
4806
  name: `${app.firstName ?? ""} ${app.lastName ?? ""}`.trim(),
4684
4807
  priceId: String(priceId),
4685
- existingCustomerId: typeof app.stripeCustomerId === "string" ? app.stripeCustomerId : void 0
4808
+ existingCustomerId: typeof app.stripeCustomerId === "string" ? app.stripeCustomerId : void 0,
4809
+ now: Date.now()
4686
4810
  });
4687
4811
  } catch (err) {
4688
- return json({ error: "payment setup failed", code: paymentErrorCode(err) }, 502);
4812
+ const code = paymentErrorCode(err);
4813
+ return json({ error: "payment setup failed", code }, code === "checkout_intent_mismatch" ? 409 : 502);
4689
4814
  }
4690
- await db.transact([
4691
- {
4692
- t: "update",
4693
- ns: "applications",
4694
- id: applicationId,
4695
- attrs: {
4696
- stripeCustomerId: result.customerId,
4697
- stripeSubscriptionId: result.subscriptionId,
4698
- stripeRuntime: stripeRuntimeIdentity(env.ODLA_RUNTIME),
4699
- refundPolicyAckAt: Date.now()
4700
- }
4701
- }
4702
- ]);
4703
- return json({ clientSecret: result.clientSecret, publishableKey: group.stripePublishableKey ?? null, lineItems: paymentLineItems(group) });
4815
+ return json({ clientSecret: result.clientSecret, publishableKey: group.stripePublishableKey ?? null, lineItems: paymentLineItems(group, tier) });
4704
4816
  }
4705
4817
  async function ingestWebhook(req, env, ctx) {
4706
4818
  const db = ctx.makeDb(env);
@@ -4812,18 +4924,18 @@ var handlePayments = async (req, url, env, ctx) => {
4812
4924
  };
4813
4925
 
4814
4926
  // src/worker-routes-gifts.ts
4815
- var first3 = (value) => Array.isArray(value) ? value[0] : void 0;
4927
+ var first4 = (value) => Array.isArray(value) ? value[0] : void 0;
4816
4928
  var rows2 = (value) => Array.isArray(value) ? value : [];
4817
4929
  var invalid = () => json({ error: "gift code is invalid or unavailable" }, 400);
4818
4930
  var userFor = async (req, env, ctx) => {
4819
4931
  const user = await ctx.verifyUser(req, env);
4820
4932
  return user?.email ? user : null;
4821
4933
  };
4822
- var loadClaim = async (db, id) => first3((await db.query({ giftClaims: { $: { where: { id }, limit: 1 } } })).giftClaims);
4934
+ var loadClaim = async (db, id) => first4((await db.query({ giftClaims: { $: { where: { id }, limit: 1 } } })).giftClaims);
4823
4935
  async function consumeRateLimit(db, chapterId, requester, now) {
4824
4936
  const bucket = await giftRequesterBucket(chapterId, requester);
4825
4937
  const id = `gift-rate:${chapterId}:${bucket}`;
4826
- const current = first3((await db.query({ giftRedemptionAttempts: { $: { where: { id }, limit: 1 } } })).giftRedemptionAttempts);
4938
+ const current = first4((await db.query({ giftRedemptionAttempts: { $: { where: { id }, limit: 1 } } })).giftRedemptionAttempts);
4827
4939
  const within = Boolean(current && now - Number(current.windowStartedAt) < 15 * 6e4);
4828
4940
  const attemptCount = within ? Number(current?.attemptCount ?? 0) + 1 : 1;
4829
4941
  if (attemptCount > 10) return false;
@@ -4848,7 +4960,7 @@ var handleGifts = async (req, url, env, ctx) => {
4848
4960
  purchaserEmailNormalized: normalizeChapterEmail(user.email),
4849
4961
  chapterId: ctx.chapter.id
4850
4962
  }, limit: 200 } } });
4851
- const group = first3((await db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } })).groups);
4963
+ const group = first4((await db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } })).groups);
4852
4964
  return json({
4853
4965
  offers: publicGiftOffers(control3?.document.giftOffers, Date.now()),
4854
4966
  claims: buyerGiftClaims(rows2(found.giftClaims).sort((a, b) => Number(b.createdAt) - Number(a.createdAt)), Date.now()),
@@ -4870,7 +4982,7 @@ var handleGifts = async (req, url, env, ctx) => {
4870
4982
  const control3 = await loadActiveSignupControl(db, ctx.chapter.id, env.ODLA_ENV);
4871
4983
  const offer = findGiftOffer(control3?.document.giftOffers, typeof body.offerId === "string" ? body.offerId : "", Date.now());
4872
4984
  if (!offer) return json({ error: "gift offer is unavailable" }, 409);
4873
- const group = first3((await db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } })).groups);
4985
+ const group = first4((await db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } })).groups);
4874
4986
  const stripeSecret = await getVaultSecret(db, "stripe_secret_key");
4875
4987
  if (!group || !stripeSecret || typeof group.stripePublishableKey !== "string") return json({ error: "payments not configured" }, 503);
4876
4988
  const emailNormalized = normalizeChapterEmail(user.email);
@@ -4939,16 +5051,16 @@ var handleGifts = async (req, url, env, ctx) => {
4939
5051
  return invalid();
4940
5052
  }
4941
5053
  if (!/^gift1_[A-Za-z0-9_-]{43}$/.test(code) || !applicationId) return invalid();
4942
- const app = first3((await db.query({ applications: { $: { where: { id: applicationId }, limit: 1 } } })).applications);
5054
+ const app = first4((await db.query({ applications: { $: { where: { id: applicationId }, limit: 1 } } })).applications);
4943
5055
  const emailNormalized = normalizeChapterEmail(user.email);
4944
5056
  if (!app || String(app.groupId ?? "") !== ctx.chapter.id || String(app.emailNormalized ?? "") !== emailNormalized || typeof app.clerkUserId === "string" && app.clerkUserId !== user.userId) return invalid();
4945
5057
  const codeHash = await hashGiftCode(ctx.chapter.id, code);
4946
- const claim = first3((await db.query({ giftClaims: { $: { where: { codeHash }, limit: 1 } } })).giftClaims);
5058
+ const claim = first4((await db.query({ giftClaims: { $: { where: { codeHash }, limit: 1 } } })).giftClaims);
4947
5059
  if (!claim || claim.chapterId !== ctx.chapter.id) return invalid();
4948
5060
  const sameRedemption = (candidate) => candidate.status === "redeemed" && candidate.applicationId === applicationId && candidate.beneficiaryEmailNormalized === emailNormalized && candidate.beneficiaryUserId === user.userId;
4949
5061
  const success = async () => {
4950
- const current = first3((await db.query({ applications: { $: { where: { id: applicationId }, limit: 1 } } })).applications);
4951
- const group2 = first3((await db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } })).groups);
5062
+ const current = first4((await db.query({ applications: { $: { where: { id: applicationId }, limit: 1 } } })).applications);
5063
+ const group2 = first4((await db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } })).groups);
4952
5064
  const state = current && group2 ? await continueJoin(db, ctx, env, url.origin, current, group2) : null;
4953
5065
  return json({
4954
5066
  ok: true,
@@ -4967,7 +5079,7 @@ var handleGifts = async (req, url, env, ctx) => {
4967
5079
  return invalid();
4968
5080
  }
4969
5081
  const target = claim.target;
4970
- const group = first3((await db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } })).groups);
5082
+ const group = first4((await db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } })).groups);
4971
5083
  const tier = group ? findTier(await loadTiers(db, group), typeof app.tierId === "string" ? app.tierId : null) : void 0;
4972
5084
  if (String(app.status ?? "") !== "submitted" || typeof app.stripeSubscriptionId === "string" || typeof app.giftClaimId === "string" || !tier || tierIsFree(tier) || target?.type !== "tier" || target.tierId !== app.tierId) return invalid();
4973
5085
  const redeemed = await redeemGiftClaim(db, claim, {