@vibes.diy/prompts 14.3.204 → 14.3.205

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -6,7 +6,6 @@ export * from "./json-docs.js";
6
6
  export * from "./view-state.js";
7
7
  export * from "./style-prompts.js";
8
8
  export * from "./restyle.js";
9
- export * from "./look-restyle.js";
10
9
  export * from "./themes/index.js";
11
10
  export * from "./themes/looks/index.js";
12
11
  export { parseContent } from "./segment-parser.js";
package/index.js CHANGED
@@ -6,7 +6,6 @@ export * from "./json-docs.js";
6
6
  export * from "./view-state.js";
7
7
  export * from "./style-prompts.js";
8
8
  export * from "./restyle.js";
9
- export * from "./look-restyle.js";
10
9
  export * from "./themes/index.js";
11
10
  export * from "./themes/looks/index.js";
12
11
  export { parseContent } from "./segment-parser.js";
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../jsr/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,yBAAyB,CAAC;AACxC,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,cAAc,CAAC;AAC7B,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGnD,OAAO,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAEvG,OAAO,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAI7F,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,UAAU,EAAE,gBAAgB,EAAE,aAAa,EAAwB,MAAM,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../jsr/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,yBAAyB,CAAC;AACxC,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,cAAc,CAAC;AAC7B,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGnD,OAAO,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAEvG,OAAO,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAI7F,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,UAAU,EAAE,gBAAgB,EAAE,aAAa,EAAwB,MAAM,iBAAiB,CAAC"}
package/llms/backend.md CHANGED
@@ -1210,6 +1210,20 @@ Two rules keep change-reactions sane:
1210
1210
  same-database ping-pong is still wasted work. Different db + dbName guard
1211
1211
  makes loops structurally impossible.
1212
1212
 
1213
+ Example records from `seed.json` are written without running `onChange`, so a
1214
+ handler reacts to real activity only. A handler that reaches outside the app
1215
+ (an email to the owner, a webhook, a notification) also starts with a one-line
1216
+ check that keeps it to real records — seeded ones carry an `_id` that starts
1217
+ with `seed:`:
1218
+
1219
+ ```js
1220
+ export async function onChange(event, ctx) {
1221
+ if (event.dbName !== "requests" || event.deleted) return;
1222
+ if (event.docId.startsWith("seed:")) return; // example records stay in the app
1223
+ await ctx.notify({ toHandle: event.doc.assignee, body: "New request", dedupeKey: `request-${event.docId}` });
1224
+ }
1225
+ ```
1226
+
1213
1227
  ### `onChange` reads what the triggering user could read
1214
1228
 
1215
1229
  A reaction usually needs the set its write joins — the siblings, the existing
package/llms/github.md CHANGED
@@ -620,6 +620,11 @@ channel.
620
620
  - **Connecting a repo takes write access to it on GitHub.** The picker offers
621
621
  the repos the person can push to, and shows the rest greyed out. Suggest that
622
622
  someone with read-only access ask a maintainer to connect the repo.
623
+ - **A job's log is plain text at `/actions/jobs/{id}/logs`** (`actions:read`).
624
+ GitHub redirects that call, and archives and artifacts, to a signed download;
625
+ `ctx.github.fetch` follows it and hands back the body, so read it with
626
+ `res.text()`. A finished run never changes: read the log once, keep what the
627
+ page shows, and serve that from the database rather than GitHub on every view.
623
628
  - **Repo names are case-insensitive on GitHub.** Lower-case them in `_id`s and
624
629
  comparisons, as the example does, and keep GitHub's spelling for display.
625
630
  - **Taking a repo off this app:** the person presses Connect again and unticks
@@ -1,7 +1,7 @@
1
1
  export const stripeSubscriptionsConfig = {
2
2
  name: "stripe-subscriptions",
3
3
  label: "Stripe subscriptions",
4
- description: "A paid membership or subscription through Stripe Checkout in subscription mode, ONLY when the person asks for recurring money — monthly, yearly, subscribe, membership fee, paid tier, paywall — into the owner's own Stripe account through ctx.stripe, connected once with Connect Stripe: the Connect Stripe and Customer Portal setup items, test mode first with the membership's mode passed on every call and live once the owner takes this app live, every Stripe call in backend.js with no Stripe.js in the page, one pending membership then one Checkout Session opened in a new tab, entitlement computed from Stripe's status plus one GRACE_DAYS knob for a past_due card, members-only content as a channel the membership record grants and the backend withdraws, cancellation and card changes in Stripe's Customer Portal, and a scheduled sweep that re-reads every live subscription. A one-time charge (dues once, a ticket, a deposit) is the stripe skill; an app with members-only content that charges nothing does not need this — offer it as the [pay] option instead",
4
+ description: "A paid membership or subscription through Stripe Checkout in subscription mode, ONLY when the person asks for recurring money — monthly, yearly, subscribe, membership fee, paid tier, paywall — into the owner's own Stripe account through ctx.stripe, connected once with Connect Stripe: the plans are the owner's, plan records in the app's database with a price and a month or year interval that only the owner writes (access.js) from the app's own Plans screen, starting empty with the owner's first plan, and backend.js subscribes at the price it reads from the plan the member names, never an amount from the browser or a constant in backend.js; the Connect Stripe and Customer Portal setup items, test mode first with the membership's mode passed on every call and live once the owner takes this app live, every Stripe call in backend.js with no Stripe.js in the page, one pending membership then one Checkout Session opened in a new tab, entitlement computed from Stripe's status plus one GRACE_DAYS knob for a past_due card, members-only content as a channel the membership record grants and the backend withdraws, cancellation and card changes in Stripe's Customer Portal, and a scheduled sweep that re-reads every live subscription. A one-time charge (dues once, a ticket, a deposit) is the stripe skill; an app with members-only content that charges nothing does not need this — offer it as the [pay] option instead",
5
5
  cues: [
6
6
  "subscription",
7
7
  "subscribe",
@@ -1 +1 @@
1
- {"version":3,"file":"stripe-subscriptions.js","sourceRoot":"","sources":["../../jsr/llms/stripe-subscriptions.ts"],"names":[],"mappings":"AAWA,MAAM,CAAC,MAAM,yBAAyB,GAAc;IAClD,IAAI,EAAE,sBAAsB;IAC5B,KAAK,EAAE,sBAAsB;IAC7B,WAAW,EACT,siCAAsiC;IACxiC,IAAI,EAAE;QACJ,cAAc;QACd,WAAW;QACX,SAAS;QACT,WAAW;QACX,SAAS;QACT,QAAQ;QACR,gBAAgB;QAChB,iBAAiB;QACjB,WAAW;QACX,SAAS;QACT,WAAW;QACX,cAAc;QACd,iBAAiB;KAClB;CACF,CAAC"}
1
+ {"version":3,"file":"stripe-subscriptions.js","sourceRoot":"","sources":["../../jsr/llms/stripe-subscriptions.ts"],"names":[],"mappings":"AAWA,MAAM,CAAC,MAAM,yBAAyB,GAAc;IAClD,IAAI,EAAE,sBAAsB;IAC5B,KAAK,EAAE,sBAAsB;IAC7B,WAAW,EACT,g5CAAg5C;IACl5C,IAAI,EAAE;QACJ,cAAc;QACd,WAAW;QACX,SAAS;QACT,WAAW;QACX,SAAS;QACT,QAAQ;QACR,gBAAgB;QAChB,iBAAiB;QACjB,WAAW;QACX,SAAS;QACT,WAAW;QACX,cAAc;QACd,iBAAiB;KAClB;CACF,CAAC"}
@@ -26,6 +26,26 @@ grants. An app where each visitor sells their own subscriptions is a
26
26
  marketplace, a bigger thing than this recipe — say so and build the
27
27
  one-merchant half.
28
28
 
29
+ **The plans are the owner's, and they live in the app.**
30
+
31
+ The plans are the owner's: each plan is a plan record in the app's own database that only the owner writes, from the app's own screen, and backend.js subscribes the member at the price and interval it reads from that record — never an amount the browser sends, never a constant in backend.js.
32
+
33
+ The owner names each plan, sets its price and whether it renews monthly or
34
+ yearly, and takes one off sale, all from the app's own **Plans** screen with no
35
+ new build — and asking the builder for "a $30 yearly plan" writes the same
36
+ record the screen does. `access.js` takes a `plan` record from the owner alone
37
+ and checks its price is whole cents and its interval is `month` or `year`. The
38
+ live list starts empty: the app's code writes no plan, so the owner's first view
39
+ is the form for their first plan, and a visitor sees *Memberships open soon*
40
+ until there is one. A `seed.json` may carry example plans for the screenshot;
41
+ they reach the live app only when the owner asks for the examples. A new price
42
+ applies to people who join from then on: Stripe keeps billing each current
43
+ member the price they joined at.
44
+
45
+ A page that sells both — monthly coffee plans and single bags — takes both
46
+ skills: the bags are products on the `stripe` skill's catalog and checkout,
47
+ the plans are this recipe, and each keeps its own records.
48
+
29
49
  ## 1. The setup items: Connect Stripe, and the Customer portal
30
50
 
31
51
  The owner sets up Stripe once. The Setup surface the two items land on — the
@@ -169,12 +189,16 @@ Every membership records the mode it was made in, and every ctx.stripe.fetch cal
169
189
  - `Idempotency-Key` is `<record id>:<attempt>`, so two first presses that both
170
190
  got past the claim (a record that does not exist yet has no revision to
171
191
  claim) mint one session at Stripe; and a second press on an open attempt
172
- reuses its session for the day rather than minting another.
192
+ reuses its session for the day rather than minting another. A press for a
193
+ different plan, or after the owner changed the price, first expires the open
194
+ session at Stripe (`POST /v1/checkout/sessions/<id>/expire`), so the tab
195
+ still showing it cannot start a second subscription; when Stripe answers
196
+ that it was already paid, the route settles it and that is the membership.
173
197
 
174
198
  Amounts are integers in the currency's smallest unit: $5 a month is unit_amount 500, never 5.0.
175
199
 
176
- The price lives in the app's own plan list on the server; the browser sends a
177
- plan name, never an amount. One subscription per person: `/subscribe` refuses
200
+ The price lives on the owner's plan record, which the server reads; the browser
201
+ sends a plan's id, never an amount. One subscription per person: `/subscribe` refuses
178
202
  while the member's subscription is **live at Stripe** — `active`, `trialing`,
179
203
  `past_due`, `unpaid` or `paused`, entitled or not — because a lapsed member
180
204
  whose card Stripe is still retrying must not be sold a second subscription
@@ -321,7 +345,7 @@ export const config = {
321
345
  scheduled: { interval: "30m" },
322
346
  // The routes read the member's own record; access.js binds the database, so the fetch lane needs
323
347
  // this declaration, and every route owes the check it waives: it reads membership-<mode>-<caller> only.
324
- fetch: { unfilteredReads: { dbs: ["club"], why: "the /subscribe, /confirm, /refresh and /portal routes read the signed-in member's own membership record in the app's current mode, membership-<mode>-<their handle>, and nothing else" } },
348
+ fetch: { unfilteredReads: { dbs: ["club"], why: "the /subscribe route reads the plan the member names from the owner's plans; the /subscribe, /confirm, /refresh and /portal routes read the signed-in member's own membership record in the app's current mode, membership-<mode>-<their handle>, and nothing else" } },
325
349
  };
326
350
 
327
351
  const DB = "club";
@@ -329,10 +353,16 @@ const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
329
353
  // The one knob: how long a past_due member stays in while Stripe retries the card. Zero locks
330
354
  // the moment a renewal fails.
331
355
  const GRACE_DAYS = 5;
332
- const PLANS = {
333
- monthly: { title: "Club membership (monthly)", amount: 500, currency: "usd", interval: "month" },
334
- yearly: { title: "Club membership (yearly)", amount: 5000, currency: "usd", interval: "year" },
335
- };
356
+ // The plans are the owner's: `plan` records in this database, written by the owner alone from the
357
+ // app's Plans screen (access.js), each priced in the currency's smallest unit with its interval.
358
+ // The browser names a plan, never an amount.
359
+ async function planFor(ctx, planId) {
360
+ if (typeof planId !== "string" || !planId.startsWith("plan-")) return null;
361
+ const plan = await ctx.db.get(planId, { db: DB });
362
+ if (plan?.type !== "plan" || plan.onSale !== true) return null;
363
+ if (!Number.isInteger(plan.amount) || plan.amount <= 0 || (plan.interval !== "month" && plan.interval !== "year")) return null;
364
+ return plan;
365
+ }
336
366
  // Nothing at Stripe will change these again; everything else is live and re-read.
337
367
  const TERMINAL = new Set(["canceled", "incomplete_expired"]);
338
368
 
@@ -516,7 +546,7 @@ export async function fetch(request, ctx) {
516
546
  const current = await ctx.db.get(id, { db: DB }); // null before the first attempt in this mode
517
547
 
518
548
  if (url.pathname === "/subscribe" && request.method === "POST") {
519
- const { plan, mode: shown } = await request.json();
549
+ const { planId, mode: shown } = await request.json();
520
550
  // The member joins in the mode their page showed them, or not at all: a page that still shows
521
551
  // the other mode refreshes first.
522
552
  if (shown !== mode) return json({ ok: false, reason: "mode-changed", mode }, 409);
@@ -524,14 +554,26 @@ export async function fetch(request, ctx) {
524
554
  // The portal is where a member cancels, so nobody joins before it exists: the KEPT verdict for
525
555
  // this mode, never a Stripe read per press.
526
556
  if ((await ctx.db.get(portalState(mode), { db: DB }))?.saved !== true) return json({ ok: false, reason: "setup-incomplete" }, 503);
527
- const price = PLANS[plan];
528
- if (!price) return json({ ok: false, reason: "unknown-plan" }, 400);
557
+ // The price and interval are the ones on the owner's plan record, read now: off sale, or no
558
+ // such plan, and nobody is subscribed.
559
+ const plan = await planFor(ctx, planId);
560
+ if (!plan) return json({ ok: false, reason: "unknown-plan" }, 400);
529
561
  // A subscription that is live at Stripe — entitled or not — is managed in the portal, never
530
562
  // doubled: a past_due member whose grace ran out still has a subscription Stripe is retrying.
531
563
  if (current?.subscriptionId && !TERMINAL.has(current.status)) return json({ ok: false, reason: "already-member" }, 409);
532
564
  // A second press, a retry, another tab: the open attempt is reused, never repeated.
533
- if (current?.status === "pending" && current.sessionUrl && Date.now() - current.sessionCreatedAt < SESSION_TTL_MS) {
534
- return json({ ok: true, url: current.sessionUrl });
565
+ if (current?.status === "pending" && current.sessionId && Date.now() - current.sessionCreatedAt < SESSION_TTL_MS) {
566
+ if (current.planId === plan._id && current.amount === plan.amount && current.currency === plan.currency && current.interval === plan.interval) {
567
+ return json({ ok: true, url: current.sessionUrl });
568
+ }
569
+ // A different plan, or a price the owner changed since, is a new attempt — but the open session
570
+ // could still complete in its own tab, and the record is about to forget it. Close it at Stripe
571
+ // first; Stripe refuses to expire a session already paid, and then that one is the membership.
572
+ const closed = await stripe(ctx, current.mode, "POST", `/checkout/sessions/${current.sessionId}/expire`);
573
+ if (!closed.ok) {
574
+ const settled = await settlePending(ctx, current, mode);
575
+ return json({ ok: false, reason: settled.subscriptionId ? "already-member" : "retry" }, 409);
576
+ }
535
577
  }
536
578
 
537
579
  const attempt = (current?.attempt ?? 0) + 1;
@@ -539,9 +581,11 @@ export async function fetch(request, ctx) {
539
581
  _id: id,
540
582
  type: "membership",
541
583
  memberHandle: me,
542
- plan,
543
- amount: price.amount,
544
- currency: price.currency,
584
+ planId: plan._id,
585
+ plan: plan.title,
586
+ amount: plan.amount, // the price this member joins at, whatever the plan says later
587
+ currency: plan.currency,
588
+ interval: plan.interval,
545
589
  mode, // the account this membership is made in; every later call for it passes the same mode
546
590
  status: "pending",
547
591
  entitled: false,
@@ -566,10 +610,10 @@ export async function fetch(request, ctx) {
566
610
  const form = new URLSearchParams({
567
611
  mode: "subscription",
568
612
  "line_items[0][quantity]": "1",
569
- "line_items[0][price_data][currency]": price.currency,
570
- "line_items[0][price_data][unit_amount]": String(price.amount),
571
- "line_items[0][price_data][recurring][interval]": price.interval,
572
- "line_items[0][price_data][product_data][name]": price.title,
613
+ "line_items[0][price_data][currency]": membership.currency,
614
+ "line_items[0][price_data][unit_amount]": String(membership.amount),
615
+ "line_items[0][price_data][recurring][interval]": membership.interval,
616
+ "line_items[0][price_data][product_data][name]": membership.plan,
573
617
  client_reference_id: id,
574
618
  "metadata[attempt]": String(attempt),
575
619
  success_url: appUrl(ctx, "#subscribed"),
@@ -658,6 +702,18 @@ export function club(doc, oldDoc, user, ctx) {
658
702
  return { channels: [mine, "memberships"], grant: { users: { [doc.memberHandle]: granted }, roles: { owner: ["memberships", "members"] } } };
659
703
  }
660
704
 
705
+ // A plan: the owner names it and sets its price and interval from the app's own screen, and anyone
706
+ // reads it. backend.js subscribes members at the price on this record, so the owner alone writes one.
707
+ if (doc.type === "plan") {
708
+ ctx.requireRole("owner");
709
+ const named = doc._id?.startsWith("plan-") && typeof doc.title === "string" && doc.title.trim() !== "";
710
+ const priced = Number.isInteger(doc.amount) && doc.amount > 0 && /^[a-z]{3}$/.test(doc.currency ?? "");
711
+ if (!named || !priced || (doc.interval !== "month" && doc.interval !== "year") || typeof doc.onSale !== "boolean") {
712
+ throw { forbidden: "a plan has a name, a whole-cent price, a currency and a month or year interval" };
713
+ }
714
+ return { channels: ["public"], grant: { public: ["public"] } };
715
+ }
716
+
661
717
  // A post: the owner writes it; members read it on the channel their membership record grants.
662
718
  if (doc.type === "post") {
663
719
  if (oldDoc && doc.authorHandle !== oldDoc.authorHandle) throw { forbidden: "a post keeps its author" };
@@ -683,7 +739,18 @@ export function club(doc, oldDoc, user, ctx) {
683
739
  import React, { useEffect, useRef, useState } from "react";
684
740
  import { useFireproof } from "use-fireproof";
685
741
  import { apiFetch, useViewer } from "use-vibes";
686
- import { Badge, Button, Heading, Row, Stack, Text } from "@vibes.diy/ui";
742
+ import { Badge, Button, Field, Heading, Input, Row, Segmented, Stack, Text } from "@vibes.diy/ui";
743
+ import { Checkbox } from "@vibes.diy/ui/interactive";
744
+
745
+ // Amounts are in the currency's smallest unit, the one Stripe charges in: cents for usd, whole yen
746
+ // for jpy. Show, edit and read them through that unit, never a fixed 100.
747
+ const digits = (currency) => new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits;
748
+ const money = (amount, currency) => new Intl.NumberFormat(undefined, { style: "currency", currency }).format(amount / 10 ** digits(currency));
749
+ const toMinor = (text, currency) => Math.round(Number(text) * 10 ** digits(currency));
750
+ const shown = (amount, currency) => (amount / 10 ** digits(currency)).toFixed(digits(currency));
751
+ const CURRENCY = "usd"; // the currency new plans are priced in
752
+ const INTERVALS = [{ value: "month", label: "Monthly" }, { value: "year", label: "Yearly" }];
753
+ const per = (plan) => `${money(plan.amount, plan.currency)} a ${plan.interval}`;
687
754
 
688
755
  // The setup verdict, read on mount and again whenever the app comes back into view: the owner
689
756
  // connects Stripe or saves the portal in another tab and returns, and the Join buttons unlock
@@ -774,13 +841,79 @@ function SetupScreen({ setup }) {
774
841
  );
775
842
  }
776
843
 
844
+ // One plan on the owner's list: its price edits in place, and On sale offers it to new members or
845
+ // stops. Members already in keep the price they joined at; Stripe bills them that.
846
+ function PlanRow({ plan, save }) {
847
+ const [price, setPrice] = useState(shown(plan.amount, plan.currency));
848
+ useEffect(() => setPrice(shown(plan.amount, plan.currency)), [plan.amount]);
849
+ const commit = () => {
850
+ const amount = toMinor(price, plan.currency);
851
+ if (Number.isInteger(amount) && amount > 0 && amount !== plan.amount) save({ ...plan, amount }, () => setPrice(shown(plan.amount, plan.currency)));
852
+ else setPrice(shown(plan.amount, plan.currency));
853
+ };
854
+ return (
855
+ <Row gap={2}>
856
+ <Text>{plan.title} · {plan.interval === "year" ? "yearly" : "monthly"}</Text>
857
+ <Field label="Price">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={price} onChange={setPrice} onBlur={commit} onKeyDown={(e) => e.key === "Enter" && commit()} inputMode="decimal" />}</Field>
858
+ <Checkbox label="On sale" checked={plan.onSale} onChange={(on) => save({ ...plan, onSale: on === true })} />
859
+ </Row>
860
+ );
861
+ }
862
+
863
+ // The owner's plans: each save is a `plan` record that access.js takes from the owner alone, and its
864
+ // price and interval are what /subscribe charges. Empty, the form for the first plan leads; from
865
+ // then on the list leads with a compact add on top.
866
+ function Plans({ plans, onAdd }) {
867
+ const { database } = useFireproof("club");
868
+ const [title, setTitle] = useState("");
869
+ const [price, setPrice] = useState("");
870
+ const [renews, setRenews] = useState("month");
871
+ const [error, setError] = useState(null);
872
+ // A put lands on this device at once; the server's verdict arrives on its receipt. A refused save
873
+ // converges back to what the server holds, and the owner gets their draft and the reason back.
874
+ const save = async (plan, undo) => {
875
+ setError(null);
876
+ const { synced } = await database.put(plan);
877
+ synced.on((s) => {
878
+ if (s.status !== "refused") return;
879
+ undo?.();
880
+ setError(s.message ?? "That did not save: a plan needs a name and a price like 5.00.");
881
+ });
882
+ };
883
+ const add = () => {
884
+ const amount = toMinor(price, CURRENCY);
885
+ if (!title.trim() || !Number.isInteger(amount) || amount <= 0) return setError("Give it a name and a price like 5.00.");
886
+ const plan = { _id: "plan-" + crypto.randomUUID(), type: "plan", title: title.trim(), amount, currency: CURRENCY, interval: renews, onSale: true, createdAt: Date.now() };
887
+ // The form empties as the owner presses Add; the draft comes back only if the write is refused.
888
+ // The owner stays here: the first entry would otherwise flip the default screen to the shop.
889
+ onAdd?.();
890
+ setTitle("");
891
+ setPrice("");
892
+ save(plan, () => { setTitle(plan.title); setPrice(shown(plan.amount, plan.currency)); });
893
+ };
894
+ return (
895
+ <Stack>
896
+ <Heading>{plans.length === 0 ? "Add your first plan" : "Plans"}</Heading>
897
+ <Row gap={2}>
898
+ <Field label="Name">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={title} onChange={setTitle} placeholder="Club membership" />}</Field>
899
+ <Field label="Price">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={price} onChange={setPrice} placeholder="5.00" inputMode="decimal" />}</Field>
900
+ <Segmented label="Renews" value={renews} onChange={setRenews} options={INTERVALS} />
901
+ <Button onClick={add}>Add</Button>
902
+ </Row>
903
+ {error && <Text>{error}</Text>}
904
+ {plans.map((p) => <PlanRow key={p._id} plan={p} save={save} />)}
905
+ </Stack>
906
+ );
907
+ }
908
+
777
909
  export default function App() {
778
910
  const { viewer, requestLogin } = useViewer();
779
911
  const { useLiveQuery } = useFireproof("club"); // memberships AND posts: one database, one grant set
780
912
  const { docs: memberships } = useLiveQuery("type", { key: "membership" });
781
913
  const { docs: posts } = useLiveQuery("type", { key: "post" });
914
+ const { docs: plans } = useLiveQuery("type", { key: "plan" });
782
915
  const setup = useSetup();
783
- const [screen, setScreen] = useState("club");
916
+ const [picked, setPicked] = useState(null);
784
917
  const [busy, setBusy] = useState(false);
785
918
  const [error, setError] = useState(null);
786
919
 
@@ -816,6 +949,7 @@ export default function App() {
816
949
  data.reason === "stripe" ? data.message
817
950
  : data.reason === "already-member" ? "You already have a membership — manage it below."
818
951
  : data.reason === "mode-changed" ? `Memberships here just moved to ${data.mode} mode. Refresh the page and press Join again.`
952
+ : data.reason === "unknown-plan" ? "That plan is no longer offered."
819
953
  : "Memberships are not open yet."
820
954
  );
821
955
  return;
@@ -831,36 +965,43 @@ export default function App() {
831
965
  const mine = viewer && setup ? memberships.find((m) => m._id === `membership-${setup.mode}-${viewer.userHandle}`) : undefined;
832
966
  const entitled = mine?.entitled === true;
833
967
  const ends = mine?.currentPeriodEnd ? new Date(mine.currentPeriodEnd).toLocaleDateString() : null;
968
+ const offered = plans.filter((p) => p.onSale);
969
+ const pitch = offered.length === 0 ? "Memberships open soon." : `Members read every post. Join for ${offered.map(per).join(" or ")}, cancel any time.`;
970
+ // The owner with no plans yet starts on Plans, the form for their first plan in front.
971
+ const screen = picked ?? (setup?.owner && plans.length === 0 ? "plans" : "club");
834
972
 
835
973
  return (
836
974
  <Stack>
837
975
  <Row gap={2}>
838
- <Button variant="quiet" onClick={() => setScreen("club")}>The club</Button>
839
- {/* The Setup entry: the owner's alone, highlighted while an item is still to do, quiet once done. */}
976
+ <Button variant="quiet" onClick={() => setPicked("club")}>The club</Button>
977
+ {/* The owner's own screens: the plans, and Setup highlighted while an item is still to do. */}
978
+ {setup?.owner && <Button variant="quiet" onClick={() => setPicked("plans")}>Plans</Button>}
840
979
  {setup?.owner && (
841
- <Button variant={ready ? "quiet" : "solid"} onClick={() => setScreen("setup")}>
980
+ <Button variant={ready ? "quiet" : "solid"} onClick={() => setPicked("setup")}>
842
981
  Setup{ready ? "" : " · to do"}
843
982
  </Button>
844
983
  )}
845
984
  </Row>
846
985
  {screen === "setup" && setup?.owner ? (
847
986
  <SetupScreen setup={setup} />
987
+ ) : screen === "plans" && setup?.owner ? (
988
+ <Plans plans={plans} onAdd={() => setPicked("plans")} />
848
989
  ) : (
849
990
  <Stack>
850
991
  <Heading>The club</Heading>
851
992
  {!viewer ? (
852
993
  <Stack>
853
- <Text>Members read every post. Join for $5 a month, cancel any time.</Text>
854
- <Button onClick={() => requestLogin()}>Sign in to join</Button>
994
+ <Text>{pitch}</Text>
995
+ {offered.length > 0 && <Button onClick={() => requestLogin()}>Sign in to join</Button>}
855
996
  </Stack>
856
997
  ) : entitled ? (
857
998
  <Badge tone="up">{mine.cancelAtPeriodEnd ? `Member until ${ends}` : mine.status === "past_due" ? "Payment due — please update your card" : "Member"}</Badge>
858
999
  ) : (
859
1000
  <Stack>
860
- <Text>Members read every post. Join for $5 a month, cancel any time.</Text>
1001
+ <Text>{pitch}</Text>
861
1002
  {mine?.subscriptionId && mine.status !== "canceled" ? (
862
1003
  <Text>Your last payment did not go through. Update your card below to keep reading.</Text>
863
- ) : ready ? (
1004
+ ) : ready && offered.length > 0 ? (
864
1005
  <Stack>
865
1006
  {/* Test mode is a rehearsal: the owner gets the test card, members learn it ends at go-live. */}
866
1007
  {setup.mode === "test" && (
@@ -869,13 +1010,16 @@ export default function App() {
869
1010
  <Text muted>{setup.owner ? "Join with the test card 4242 4242 4242 4242 and any future date." : "This is a rehearsal: test memberships end when the app goes live."}</Text>
870
1011
  </Row>
871
1012
  )}
872
- <Button onClick={() => openStripe("/subscribe", { plan: "monthly", mode: setup.mode })} disabled={busy} loading={busy}>
873
- Join — Stripe opens in a new tab
874
- </Button>
1013
+ {/* The page names the plan, never its price. */}
1014
+ {offered.map((p) => (
1015
+ <Button key={p._id} onClick={() => openStripe("/subscribe", { planId: p._id, mode: setup.mode })} disabled={busy} loading={busy}>
1016
+ Join {p.title} — {per(p)}, Stripe opens in a new tab
1017
+ </Button>
1018
+ ))}
875
1019
  </Stack>
876
- ) : (
1020
+ ) : offered.length > 0 ? (
877
1021
  <Text muted>Memberships are not open yet.</Text>
878
- )}
1022
+ ) : null}
879
1023
  </Stack>
880
1024
  )}
881
1025
  {/* The portal is reachable whenever Stripe knows this member, entitled or not: a lapsed
@@ -894,7 +1038,7 @@ export default function App() {
894
1038
  {setup?.owner && (
895
1039
  <ul>
896
1040
  {memberships.map((m) => (
897
- <li key={m._id}>@{m.memberHandle} · {m.mode} · {m.plan} · {m.status}{m.entitled ? " · entitled" : ""}{m.currentPeriodEnd ? ` · until ${new Date(m.currentPeriodEnd).toLocaleDateString()}` : ""}</li>
1041
+ <li key={m._id}>@{m.memberHandle} · {m.mode} · {m.plan} · {m.interval ? `${money(m.amount, m.currency)} a ${m.interval} · ` : ""}{m.status}{m.entitled ? " · entitled" : ""}{m.currentPeriodEnd ? ` · until ${new Date(m.currentPeriodEnd).toLocaleDateString()}` : ""}</li>
898
1042
  ))}
899
1043
  </ul>
900
1044
  )}
package/llms/stripe.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export const stripeConfig = {
2
2
  name: "stripe",
3
3
  label: "Stripe payments",
4
- description: "Taking real money through Stripe Checkout: load it whenever the person asks for money to move — pay the bill, split the check, a restaurant check, pay at the table or at the counter, a tip or a tip jar, donate or a donation page, sell tickets, a charge, a deposit, dues, a checkout, pay with Stripe, or the word Stripe — one-time charges into the owner's own Stripe account through ctx.stripe, connected once with Connect Stripe (a monthly or yearly subscription is the stripe-subscriptions skill): guest checkout by default for paying a venue (a check, a tip, a donation — no sign-in, the payment keyed to the thing paid and its session, written by backend.js for the guest) and a signed-in order where the record is the buyer's to keep (dues on a roster, my orders), one payer paying the whole check by default with splitting as a second choice and the balance reserved with a revision-checked write before any session opens, the Connect Stripe setup item read from ctx.stripe.status(), test mode first with the order's mode passed on every call and live once the owner takes this app live, every Stripe call in backend.js with no Stripe.js in the page, one pending order then one Checkout Session opened in a new tab, an order marked paid only after the backend reads the session back from Stripe and matches it to the order, integer amounts in cents, and a scheduled sweep that settles orders whose buyer never came back. A storefront, plans page or booking page that only records orders takes no payment and does not need this; offer it as the [pay] option instead",
4
+ description: "Taking real money through Stripe Checkout: load it whenever the person asks for money to move — pay the bill, split the check, a restaurant check, pay at the table or at the counter, a tip or a tip jar, donate or a donation page, sell tickets, sell products buyers pay for, buy now or purchase online, a charge, a deposit, dues, a checkout, pay with Stripe, or the word Stripe — one-time charges into the owner's own Stripe account through ctx.stripe, connected once with Connect Stripe (a monthly or yearly subscription is the stripe-subscriptions skill): what is for sale and its price is the owner's product catalog, product records in the app's database that only the owner writes (access.js) from the app's own Products screen, starting empty with the owner's first product, and backend.js charges the price it reads from the product the buyer names, never an amount from the browser or a constant in backend.js; guest checkout by default for paying a venue (a check, a tip, a donation — no sign-in, the payment keyed to the thing paid and its session, written by backend.js for the guest) and a signed-in order where the record is the buyer's to keep (dues on a roster, my orders), one payer paying the whole check by default with splitting as a second choice and the balance reserved with a revision-checked write before any session opens, the Connect Stripe setup item read from ctx.stripe.status(), test mode first with the order's mode passed on every call and live once the owner takes this app live, every Stripe call in backend.js with no Stripe.js in the page, one pending order then one Checkout Session opened in a new tab, an order marked paid only after the backend reads the session back from Stripe and matches it to the order, integer amounts in cents, and a scheduled sweep that settles orders whose buyer never came back. A storefront, plans page or booking page that only records orders takes no payment and does not need this; offer it as the [pay] option instead",
5
5
  cues: [
6
6
  "stripe",
7
7
  "take payments",
@@ -14,6 +14,10 @@ export const stripeConfig = {
14
14
  "deposit",
15
15
  "dues",
16
16
  "sell tickets",
17
+ "buy now",
18
+ "buy online",
19
+ "purchase online",
20
+ "make a purchase",
17
21
  "charge",
18
22
  "paywall",
19
23
  "pay the bill",
@@ -1 +1 @@
1
- {"version":3,"file":"stripe.js","sourceRoot":"","sources":["../../jsr/llms/stripe.ts"],"names":[],"mappings":"AAWA,MAAM,CAAC,MAAM,YAAY,GAAc;IACrC,IAAI,EAAE,QAAQ;IACd,KAAK,EAAE,iBAAiB;IACxB,WAAW,EACT,miDAAmiD;IACriD,IAAI,EAAE;QACJ,QAAQ;QACR,eAAe;QACf,cAAc;QACd,iBAAiB;QACjB,eAAe;QACf,cAAc;QACd,aAAa;QACb,UAAU;QACV,SAAS;QACT,MAAM;QACN,cAAc;QACd,QAAQ;QACR,SAAS;QACT,cAAc;QACd,iBAAiB;QACjB,kBAAkB;QAClB,kBAAkB;QAClB,oBAAoB;QACpB,SAAS;QACT,QAAQ;QACR,UAAU;QACV,WAAW;QACX,iBAAiB;KAClB;CACF,CAAC"}
1
+ {"version":3,"file":"stripe.js","sourceRoot":"","sources":["../../jsr/llms/stripe.ts"],"names":[],"mappings":"AAWA,MAAM,CAAC,MAAM,YAAY,GAAc;IACrC,IAAI,EAAE,QAAQ;IACd,KAAK,EAAE,iBAAiB;IACxB,WAAW,EACT,s8DAAs8D;IACx8D,IAAI,EAAE;QACJ,QAAQ;QACR,eAAe;QACf,cAAc;QACd,iBAAiB;QACjB,eAAe;QACf,cAAc;QACd,aAAa;QACb,UAAU;QACV,SAAS;QACT,MAAM;QACN,cAAc;QACd,SAAS;QACT,YAAY;QACZ,iBAAiB;QACjB,iBAAiB;QACjB,QAAQ;QACR,SAAS;QACT,cAAc;QACd,iBAAiB;QACjB,kBAAkB;QAClB,kBAAkB;QAClB,oBAAoB;QACpB,SAAS;QACT,QAAQ;QACR,UAAU;QACV,WAAW;QACX,iBAAiB;KAClB;CACF,CAAC"}