@zachristudio/buyblock 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ Buyblock: Sell Products & Digital Downloads (EmDash plugin)
2
+ Copyright (c) 2026 zachristudio.com. All rights reserved.
3
+
4
+ This software is proprietary. It is licensed, not sold.
5
+ You may install and use the free edition on any number of sites at no
6
+ cost. Pro features may be used only on the sites covered by a valid Pro
7
+ licence purchased from the copyright holder, under the terms of that licence.
8
+
9
+ You may not copy, modify, redistribute, sublicense, resell or publish this
10
+ software or any part of it, in source or compiled form, except as the
11
+ licence expressly permits.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM,
15
+ DAMAGES OR OTHER LIABILITY ARISING FROM THE USE OF THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,131 @@
1
- # Temporary Holding Version
1
+ <p><picture><source media="(prefers-color-scheme: dark)" srcset="https://cdn.jsdelivr.net/npm/@zachristudio/buyblock/brand/buyblock-lockup-light.png"><img src="https://cdn.jsdelivr.net/npm/@zachristudio/buyblock/brand/buyblock-lockup.png" alt="Buyblock" width="264" height="53"></picture></p>
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # Buyblock: Sell Products & Digital Downloads (EmDash)
4
+
5
+ By zachristudio.com. PayPal is a trademark of PayPal, Inc.; this plugin is not affiliated with or endorsed by PayPal.
6
+
7
+ Sell products and digital downloads on an [EmDash](https://github.com/emdash-cms/emdash) site with buy buttons. Payments go through PayPal today; the code is organised per gateway (`src/gateways/`) so more can be added. Successor of `@zachristudio/buyblock-paypal` (plugin id `paypal`), which is no longer developed: see [Moving from buyblock-paypal](#moving-from-buyblock-paypal).
8
+
9
+ - **One admin app, "Buyblock"**, with three tabs: **Orders** (home, with totals), **Products** and **Settings**. Built with EmDash's Kumo components, so it follows the admin's light/dark theme.
10
+ - **Two-step setup:** connect Sandbox keys, then create a first product. Keys are verified with PayPal before they're saved.
11
+ - **Go live dialog:** add Live keys (verified), optionally delete test orders, then switch. Sandbox and Live keep separate key pairs.
12
+ - **A "Buy button" block** can be dropped into any page or post (type `/` in the editor). One product can be on many pages; the Products tab shows where.
13
+ - **Per-product button style:** label, colour and corners, with a preview.
14
+ - **Orders** are created and captured **on the server** with your own PayPal REST app keys. The price always comes from the store, so buyers can't change it in the browser. Captured amounts are checked against the expected total.
15
+ - **PayPal JS SDK v6** (`<paypal-button>` web component), not the deprecated v5 SDK.
16
+ - **Dashboard widget:** setup prompt, then 30-day revenue and order counts.
17
+ - **Free vs Pro:** free includes unlimited products and shows the last 30 days of orders; full history and CSV export are Pro (locked, with an "Upgrade to Pro" link). Pro isn't on sale yet, so every site is on free (`src/plan.ts`).
18
+ - **Pro tab (coming soon):** the top Pro features; every tile and lock opens an early-access email to hello@zachristudio.com with the feature in the subject. The plugin itself sends nothing.
19
+
20
+ ## Why a trusted (native) plugin?
21
+
22
+ Rendering a payment button on public pages needs a site component and a client script. EmDash only allows that for trusted plugins added in `astro.config.mjs`, not for sandboxed registry plugins.
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ npm i @zachristudio/buyblock
28
+ ```
29
+
30
+ ```js
31
+ // astro.config.mjs
32
+ import { buyblock, buyblockPlugin } from "@zachristudio/buyblock";
33
+
34
+ integrations: [
35
+ emdash({
36
+ // …database, storage…
37
+ plugins: [buyblockPlugin()],
38
+ }),
39
+ buyblock(), // digital downloads: the buyer's order page and download links
40
+ ],
41
+ ```
42
+
43
+ Redeploy, then open **Buyblock** in the admin sidebar. The free edition needs no account or key. Requires EmDash 1.5 or newer.
44
+
45
+ ## Moving from buyblock-paypal
46
+
47
+ Buyblock is a new plugin, so nothing is copied over from `@zachristudio/buyblock-paypal`: keys, products, buttons and orders start fresh. Both plugins can run side by side, so you can switch page by page and keep selling the whole time.
48
+
49
+ 1. **Install Buyblock next to the old plugin.** Keep `paypalPlugin()` for now:
50
+
51
+ ```js
52
+ import { paypalPlugin } from "@zachristudio/buyblock-paypal";
53
+ import { buyblock, buyblockPlugin } from "@zachristudio/buyblock";
54
+
55
+ plugins: [paypalPlugin(), buyblockPlugin()],
56
+ // …and add buyblock() to integrations, as in Install above
57
+ ```
58
+
59
+ Redeploy. The sidebar now shows **Buyblock** twice. The new one opens `/_emdash/admin/plugins/buyblock`, the old one `/_emdash/admin/plugins/paypal`.
60
+ 2. **Add your PayPal keys again** in the new Buyblock: Sandbox first, then **Go live** with your Live keys. Copy them from [developer.paypal.com](https://developer.paypal.com) → **Apps & Credentials**; you can keep using the same PayPal app.
61
+ 3. **Recreate your products** with the same name, price, currency and button style. Optionally add a **Digital file**.
62
+ 4. **Swap the buttons.** On every page with a **PayPal button** block, put a **Buy button** block in the same spot, pick the product and publish. The old plugin's **Products** tab shows which pages use each product. Don't leave an old and a new button on the same page: both load PayPal's script and one of them may not work.
63
+ 5. **Keep what you need from the old Orders tab.** Past orders aren't moved into Buyblock. They stay in your PayPal account (**Activity**), and in your database, untouched: reinstalling the old plugin shows them again.
64
+ 6. **Remove the old plugin.** Delete `paypalPlugin()` and its import, run `npm uninstall @zachristudio/buyblock-paypal`, and redeploy. A **PayPal button** block you missed then simply stops showing (no error on the page), so check your pages first.
65
+
66
+ ## Digital downloads (Free)
67
+
68
+ Add a file to any product (Products → Edit → **Digital file**, up to 2 GB). After paying, the buyer gets a **Download** button right in the PayPal block, plus a private order page at `/buyblock/order` to download again later (also findable with the PayPal transaction ID and email, or through the **Order lookup** block).
69
+
70
+ - **Where files live** (Settings → Downloads → File storage): a private folder on the server (`./.buyblock/downloads`, the default on Node/VPS hosts; back it up with your database), or a Cloudflare R2 bucket bound as `DOWNLOADS` (needed on Cloudflare, which has no server disk). Files never go to the media library, which is public.
71
+ - **Access:** unlimited downloads by default; each download link works for 1 hour and big files resume. Optionally limit downloads per order and the number of days.
72
+ - Taxes on your sales are your responsibility as the seller.
73
+
74
+ **Dev tip (slow "Loading EmDash…"):** EmDash's dev server doesn't pre-bundle the UI libraries a trusted plugin's admin imports, so Kumo pulls in every Phosphor icon as a separate file (about 3,000 requests). Add this to `astro.config.mjs` (dev only; production builds are unaffected):
75
+
76
+ ```js
77
+ export default defineConfig({
78
+ vite: { optimizeDeps: { include: ["@cloudflare/kumo", "@phosphor-icons/react"] } },
79
+ // …
80
+ });
81
+ ```
82
+
83
+ ## Develop
84
+
85
+ - `npm run build` writes the published code to `dist/`: minified ESM, no source maps. `PayPalButton.astro` ships as source because Astro compiles it on the site. `npm pack` runs the build first.
86
+ - `npm run typecheck` and `npm test` (rate limiter).
87
+ - The test site installs the packed tarball (`file:../buyblock/zachristudio-buyblock-<version>.tgz`). After editing, run `npm run sync:buyblock` in the test site to rebuild and copy `dist/`, then **restart its dev server**: Vite keeps serving the old module until it restarts.
88
+
89
+ ## Security
90
+
91
+ - Prices always come from the store; PayPal's captured amount is checked against the expected total.
92
+ - `create-order` and `capture-order` are rate-limited per visitor (hashed IP, never stored raw) and site-wide (`src/ratelimit.ts`).
93
+ - Capture is idempotent: repeated or concurrent calls never capture twice and get the same answer.
94
+ - Logs carry status codes, PayPal debug IDs, order IDs and amounts, never buyer details.
95
+
96
+ ## Set up PayPal
97
+
98
+ 1. Go to [developer.paypal.com](https://developer.paypal.com) → **Apps & Credentials**. **Sandbox** already has a *Default Application*.
99
+ 2. In EmDash, open **Buyblock** in the sidebar. Paste the Sandbox **Client ID** and **Secret**, then create your first product.
100
+ 3. Insert a **Buy button** block in a page and make a test purchase with a sandbox buyer account.
101
+ 4. When ready: **Go live** (needs a Live app from a PayPal Business account).
102
+
103
+ Sandbox buyer logins are under **Testing Tools → Sandbox Accounts** in the PayPal developer dashboard.
104
+
105
+ ## Routes
106
+
107
+ | Route | Access | Purpose |
108
+ |---|---|---|
109
+ | `button` | public | Product + public button config (never the secret) |
110
+ | `create-order` | public | Creates a PayPal order from the stored price |
111
+ | `capture-order` | public | Captures an order this site created; verifies amount and currency; returns the download links for a product with a file |
112
+ | `download/authorize`, `order/lookup`, `order/view` | public | Used by the `/buyblock/*` buyer pages (signed links, rate-limited lookup) |
113
+ | `products/options` | editors | Product list for the block's picker |
114
+ | `state`, `products/*`, `orders/*`, `connection/*`, `store/save`, `files/*`, `downloads/*` | editors read, admins write | JSON API for the React admin (`files/part` takes raw bytes, ≤ 8 MB per part) |
115
+
116
+ ## Licence
117
+
118
+ Proprietary, see `LICENSE`: the free edition may be used on any number of sites; Pro needs a licence.
119
+
120
+ ## Release
121
+
122
+ 1. Bump `version` in `package.json` and add the release to the site changelog (`zachristudio/src/docs/changelog.html`).
123
+ 2. `npm run typecheck && npm test && npm pack --dry-run` and check the file list (no `src/`).
124
+ 3. `npm publish` (runs the build through `prepack`; asks for the 2FA code).
125
+ 4. Deploy the site, then add a changelog line to `listing/sections/changelog.md` and run `npx emdash-plugin update-package --yes` in `listing/`.
126
+
127
+ ## Not included yet
128
+
129
+ - **Webhooks:** a payment that settles later (`PENDING`) isn't updated automatically. Check PayPal.
130
+ - **Refunds:** refund in PayPal; the plugin doesn't sync refunds yet.
131
+ - **Cart, coupons, tax, subscriptions.**
@@ -0,0 +1,33 @@
1
+ # Buyblock logo
2
+
3
+ Chosen 2026-11-15: proposal B, "Square O". Design canvas: https://claude.ai/artifact/6eUofi9qdGiramUDBJSThY (Logo row).
4
+
5
+ ## Files
6
+
7
+ All text is outlined (no font needed).
8
+
9
+ | File | Use |
10
+ |---|---|
11
+ | `buyblock-mark.svg` | App icon: the b plus the block on an ink tile. Registry icon, favicons, docs. |
12
+ | `buyblock-mark-dark.svg` | Same, with a lighter tile for dark backgrounds. |
13
+ | `buyblock-wordmark.svg` | "Buyblock" with the o as a block, ink, for light backgrounds. |
14
+ | `buyblock-wordmark-light.svg` | Same in paper colour, for dark backgrounds. |
15
+ | `buyblock-lockup.svg` | Mark + wordmark, for light backgrounds. |
16
+ | `buyblock-lockup-light.svg` | Mark + wordmark, for dark backgrounds. |
17
+ | `buyblock-icon-512.png`, `buyblock-icon-256.png` | PNG of the mark (transparent corners). Registry listing icon, social avatars. |
18
+ | `buyblock-icon-dark-512.png` | PNG of the dark-tile mark. |
19
+ | `buyblock-lockup.png`, `buyblock-lockup-light.png` | PNG lockups at 2× (1056×212), for light and dark backgrounds. |
20
+
21
+ ## Spec
22
+
23
+ - **Typeface:** Fraunces SemiBold (SIL Open Font License), letter-spacing -0.02em. The o is a square 0.47em wide with 0.08em corner radius, 0.035em space each side.
24
+ - **Colours:** ink `#1A1A1F`, clay `#C2603A` (the block), paper `#F6F2EC`. Dark tile `#2A2A31`.
25
+ - **Mark:** 64-unit grid, tile 56 with 14 radius; b from Fraunces SemiBold at 42 units; block 15 units with 3.5 radius.
26
+ - **EmDash admin:** the sidebar only accepts monochrome Phosphor icon names, so the sidebar uses `square`. The full mark sits next to the "Buyblock" header (`BuyblockMark` in `src/admin.tsx`); in dark mode its tile switches to the dark tile `#2A2A31` via CSS `light-dark()`, following both the OS setting and EmDash's own theme toggle.
27
+ - **Never** use PayPal's logo, monogram or colours in our marks.
28
+
29
+ ## PNG exports
30
+
31
+ Rendered from the SVGs with headless Chrome (2026-11-15). The registry listing doesn't accept SVG, so it uses `buyblock-icon-512.png` (13 KB, well under its 1 MiB limit).
32
+
33
+ The npm package ships only `buyblock-icon-512.png` and the two lockup PNGs. The package README shows the lockup through jsDelivr (npm doesn't serve package files itself), in a `<picture>` that switches to the light lockup on dark backgrounds.
Binary file
Binary file
Binary file
package/dist/admin.js ADDED
@@ -0,0 +1,11 @@
1
+ /*! Buyblock: Sell Products & Digital Downloads v0.3.0 · (c) zachristudio.com · See LICENSE */
2
+ import{Badge as T,Banner as Ce,Button as m,Dialog as _,Input as I,LinkButton as H,Loader as X,Select as ce,Switch as V,Tabs as te}from"@cloudflare/kumo";import{Clock as Re}from"@phosphor-icons/react/dist/csr/Clock";import{Copy as Pe}from"@phosphor-icons/react/dist/csr/Copy";import{DownloadSimple as De}from"@phosphor-icons/react/dist/csr/DownloadSimple";import{EnvelopeSimple as ae}from"@phosphor-icons/react/dist/csr/EnvelopeSimple";import{File as ue}from"@phosphor-icons/react/dist/csr/File";import{Key as pe}from"@phosphor-icons/react/dist/csr/Key";import{ListBullets as ze}from"@phosphor-icons/react/dist/csr/ListBullets";import{Plus as Be}from"@phosphor-icons/react/dist/csr/Plus";import{Prohibit as Ie}from"@phosphor-icons/react/dist/csr/Prohibit";import{ClockCounterClockwise as Ee}from"@phosphor-icons/react/dist/csr/ClockCounterClockwise";import{UploadSimple as Ae}from"@phosphor-icons/react/dist/csr/UploadSimple";import{Eye as Oe}from"@phosphor-icons/react/dist/csr/Eye";import{Heart as Fe}from"@phosphor-icons/react/dist/csr/Heart";import{Lightning as Ne}from"@phosphor-icons/react/dist/csr/Lightning";import{LockSimple as ne}from"@phosphor-icons/react/dist/csr/LockSimple";import{PencilSimple as Te}from"@phosphor-icons/react/dist/csr/PencilSimple";import{Repeat as $e}from"@phosphor-icons/react/dist/csr/Repeat";import{Trash as Le}from"@phosphor-icons/react/dist/csr/Trash";import{X as ye}from"@phosphor-icons/react/dist/csr/X";import{Lifebuoy as We}from"@phosphor-icons/react/dist/csr/Lifebuoy";import{Package as Me}from"@phosphor-icons/react/dist/csr/Package";import{Swatches as Qe}from"@phosphor-icons/react/dist/csr/Swatches";import{Ticket as Ue}from"@phosphor-icons/react/dist/csr/Ticket";import{Truck as Ve}from"@phosphor-icons/react/dist/csr/Truck";import{Wallet as He}from"@phosphor-icons/react/dist/csr/Wallet";import{apiFetch as fe,parseApiResponse as ge}from"emdash/plugin-utils";import*as i from"react";var Z="hello@zachristudio.com",ke={"auto-status":"Payments update themselves",emails:"Order and receipt emails","license-keys":"License keys & updates","multiple-files":"Several files per product",versions:"File versions","resend-link":"Email the link to the buyer","download-log":"Download log","revoke-on-refund":"Turn off downloads on refund",donations:"Donations, pay what you want",subscriptions:"Subscriptions","full-history":"Full order history","csv-export":"CSV export"};function G(t){let l=t==="pro"?null:ke[t],d=typeof window>"u"?"":window.location.origin,s=`Buyblock Pro early access${l?` (${l})`:""}`,n=`Hi Zachri Studio,
3
+
4
+ I'd like early access to Buyblock Pro${l?`, mainly for: ${l}`:""}.
5
+
6
+ Site: ${d}
7
+ `;return`mailto:${Z}?subject=${encodeURIComponent(s)}&body=${encodeURIComponent(n)}`}var le=[{id:"auto-status",icon:"lightning",title:"Payments update themselves",detail:"Pending payments turn Paid. Refunds sync and turn off downloads."},{id:"emails",icon:"envelope",title:"Order and receipt emails",detail:"You hear about every sale; buyers get a receipt and their link."},{id:"license-keys",icon:"key",title:"License keys & updates",detail:"License keys, several files and versions, resend links and a download log."},{id:"donations",icon:"heart",title:"Donations, pay what you want",detail:"Let buyers choose the amount."},{id:"subscriptions",icon:"repeat",title:"Subscriptions",detail:"Recurring payments through PayPal."},{id:"full-history",icon:"clock",title:"Full order history",detail:"Every order, not just the last 30 days, with CSV export."}],se=[{icon:"swatches",label:"Options and variants"},{icon:"package",label:"Stock limits"},{icon:"ticket",label:"Coupons"},{icon:"truck",label:"Tax and shipping"},{icon:"wallet",label:"Pay Later and Venmo"},{icon:"lifebuoy",label:"Priority support"}];import{Fragment as Y,jsx as e,jsxs as a}from"react/jsx-runtime";var me="/_emdash/api/plugins/buyblock",W="/_emdash/admin/plugins/buyblock",ve="/_emdash/admin/content/pages",M=new Map;async function R(t,l={}){let d=await fe(`${me}/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});return ge(d,"Something went wrong. Try again.")}function $(t,l){return t instanceof Error&&t.message?t.message:l}function he(){let[t,l]=i.useState(()=>M.get("state")??null),[d,s]=i.useState(""),n=i.useCallback(async()=>{try{let p=await R("state");M.set("state",p),l(p),s("")}catch(p){s($(p,"Couldn\u2019t load Buyblock."))}},[]);return i.useEffect(()=>{n()},[n]),{state:t,error:d,reload:n}}var o={subtle:"var(--text-color-kumo-subtle)",warning:"var(--text-color-kumo-warning)",danger:"var(--text-color-kumo-danger)",line:"var(--color-kumo-line)",tint:"var(--color-kumo-tint)",brand:"var(--color-kumo-brand)"},be=Object.fromEntries(["EUR","USD","GBP","AUD","CAD","CHF","SEK","NOK","DKK","PLN","CZK","HUF","JPY"].map(t=>[t,t])),A={border:`1px solid ${o.line}`,borderRadius:12},F={paddingBlock:10,paddingInline:14,fontWeight:500,fontSize:13,color:o.subtle,textAlign:"start"},N={paddingBlock:12,paddingInline:14};function ee(t,l){return`${t} ${l}`}function Ge(t){return new Date(t).toLocaleString(void 0,{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})}var q={COMPLETED:{label:"Paid",variant:"success"},CREATED:{label:"Not paid",variant:"neutral"},PENDING:{label:"Pending",variant:"warning"},DECLINED:{label:"Failed",variant:"error"},FAILED:{label:"Failed",variant:"error"},MISMATCH:{label:"Amount mismatch",variant:"error"}};function K({title:t,onClose:l,children:d}){return e(_.Root,{open:!0,onOpenChange:s=>!s&&l(),children:a(_,{size:"lg",style:{padding:24,display:"flex",flexDirection:"column",gap:18,maxHeight:"85vh",overflowY:"auto"},children:[a("div",{style:{display:"flex",alignItems:"center",gap:12},children:[e(_.Title,{style:{margin:0,fontSize:20,fontWeight:600},children:t}),e(_.Close,{"aria-label":"Close",render:s=>e(m,{...s,variant:"ghost",shape:"square",size:"sm",icon:e(ye,{}),"aria-label":"Close",style:{marginInlineStart:"auto"}})})]}),d]})})}function _e({style:t}){let l={gold:"#FFC439",blue:"#0070E0",white:"#FFFFFF"}[t.color],d=t.color==="blue"?"#FFFFFF":"#111111",s={rect:4,pill:999,sharp:0}[t.shape],n={buynow:"Buy Now",checkout:"Checkout",pay:"Pay"}[t.label];return e("div",{style:{padding:14,background:"#F7F8FA",borderRadius:10},children:a("div",{"aria-hidden":"true",style:{height:44,display:"flex",alignItems:"center",justifyContent:"center",gap:6,background:l,color:d,borderRadius:s,border:t.color==="white"?"1px solid #555555":0,font:"700 15px system-ui, sans-serif"},children:["PayPal ",e("span",{style:{fontWeight:500},children:n})]})})}function J({label:t,value:l,options:d,onChange:s}){return a("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[e("span",{style:{width:64,fontSize:13,color:o.subtle},children:t}),e(te,{variant:"segmented",size:"sm",value:l,onValueChange:n=>s(n),tabs:d.map(([n,p])=>({value:n,label:p}))})]})}var qe="M22.03 17.12L22.03 44.75L19.59 46.79Q18.54 47.21 18.08 47.35Q17.62 47.48 17.20 47.48Q16.72 47.48 16.41 47.21Q16.11 46.94 16.11 46.37L16.11 20.64Q16.11 20.12 15.95 19.89Q15.79 19.66 15.44 19.59L14.32 19.51Q13.95 19.41 13.78 19.22Q13.61 19.03 13.61 18.73Q13.61 18.40 13.82 18.19Q14.03 17.98 14.57 17.77L18.48 16.34Q19.32 16.02 19.79 15.90Q20.27 15.77 20.64 15.77Q21.34 15.77 21.68 16.14Q22.03 16.51 22.03 17.12ZM20.83 33.31L19.89 32.11Q21.57 29.53 23.73 28.08Q25.89 26.63 28.52 26.63Q31.00 26.63 32.95 27.89Q34.90 29.15 36.03 31.39Q37.15 33.62 37.15 36.54Q37.15 39.88 35.82 42.35Q34.48 44.82 32.19 46.17Q29.91 47.52 27.07 47.52Q24.57 47.52 22.64 46.35Q20.71 45.17 19.45 42.95L20.90 41.73Q21.93 43.45 23.22 44.29Q24.51 45.13 26.00 45.13Q27.45 45.13 28.57 44.29Q29.70 43.45 30.35 41.68Q31.00 39.90 31.00 37.17Q31.00 34.61 30.37 32.93Q29.74 31.25 28.63 30.42Q27.53 29.59 26.13 29.59Q24.61 29.59 23.28 30.50Q21.95 31.42 20.83 33.31Z";function je({size:t=32}){return a("svg",{width:t,height:t,viewBox:"0 0 64 64","aria-hidden":"true",style:{flex:"none"},children:[e("rect",{x:"4.5",y:"4.5",width:"55",height:"55",rx:"13.5",fill:"#1A1A1F",style:{fill:"light-dark(#1A1A1F, #2A2A31)"},stroke:o.line,strokeWidth:"1.5"}),e("path",{transform:"translate(-1.5 0)",fill:"#F6F2EC",d:qe}),e("rect",{x:"38",y:"31",width:"15",height:"15",rx:"3.5",fill:"#C2603A"})]})}function xe({children:t}){return e("p",{style:{...A,margin:0,padding:32,textAlign:"center",color:o.subtle},children:t})}var Ke={orders:W,products:`${W}/products`,settings:`${W}/settings`,pro:`${W}/pro`};function re(){let t=window.location.pathname.replace(/\/$/,"");return t.endsWith("/products")?"products":t.endsWith("/settings")?"settings":t.endsWith("/pro")?"pro":"orders"}function j(){let[t,l]=i.useState(re);i.useEffect(()=>{let s=()=>l(re());return window.addEventListener("popstate",s),()=>window.removeEventListener("popstate",s)},[]);let d=s=>{s!==t&&(window.history.pushState(null,"",Ke[s]),l(s))};return e(Ye,{tab:t,onTab:d,children:(s,n)=>t==="orders"?e(Je,{state:s,onUpgrade:()=>d("pro")}):t==="products"?e(tt,{}):t==="pro"?e(lt,{}):e(nt,{state:s,reload:n})})}function Ye({tab:t,onTab:l,children:d}){let{state:s,error:n,reload:p}=he(),[u,v]=i.useState(!1),[y,x]=i.useState(!1);return n?e(Ce,{variant:"error",title:"Buyblock",description:n}):s?!s.connected||u?e(Xe,{state:s,onStart:()=>v(!0),onDone:async()=>{v(!1),await p()},reload:p}):a("div",{style:{display:"flex",flexDirection:"column",gap:24},children:[a("header",{style:{display:"flex",flexDirection:"column",gap:12},children:[a("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[e(je,{size:44}),a("div",{style:{display:"flex",flexDirection:"column"},children:[e("h1",{style:{margin:0,fontSize:26,fontWeight:700,lineHeight:1.2},children:"Buyblock"}),e("span",{style:{fontSize:14,color:o.subtle},children:"Sell products & digital downloads"})]}),s.mode==="live"?e(T,{variant:"success",children:"Live"}):e(T,{variant:"warning",children:"Sandbox"}),s.mode==="sandbox"&&e(m,{variant:"ghost",size:"sm",onClick:()=>x(!0),children:"Go live"})]}),e(te,{variant:"underline",value:t,onValueChange:h=>l(h),tabs:[{value:"orders",label:"Orders"},{value:"products",label:"Products"},{value:"settings",label:"Settings"},{value:"pro",label:"Pro"}]})]}),d(s,p),y&&e(Se,{state:s,onClose:()=>x(!1),onDone:p})]}):e("div",{style:{padding:48,display:"flex",justifyContent:"center"},children:e(X,{})})}function Xe({state:t,onStart:l,onDone:d,reload:s}){let[n,p]=i.useState(t.connected?2:1),[u,v]=i.useState(!1),[y,x]=i.useState(""),[h,C]=i.useState(""),[w,k]=i.useState(""),[S,c]=i.useState(""),[g,r]=i.useState(""),[b,f]=i.useState(t.currency||"EUR");async function D(P){P.preventDefault(),v(!0),x("");try{l(),await R("connection/save",{env:"sandbox",clientId:h,clientSecret:w,activate:!0}),await s(),p(2)}catch(B){x($(B,"Couldn\u2019t connect."))}finally{v(!1)}}async function O(P){P.preventDefault(),v(!0),x("");try{await R("products/save",{name:S,price:g,currency:b,active:!0}),p(3)}catch(B){x($(B,"Couldn\u2019t save the product."))}finally{v(!1)}}return a("div",{style:{maxWidth:520,marginBlock:48,marginInline:"auto",display:"flex",flexDirection:"column",gap:28},children:[a("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[a("span",{style:{fontSize:14,color:o.subtle},children:["Buyblock \xB7 ",n===3?"Done":`Step ${n} of 2`]}),e("div",{"aria-hidden":"true",style:{height:4,borderRadius:2,background:o.tint},children:e("div",{style:{height:4,borderRadius:2,background:o.brand,width:`${n===1?33:n===2?66:100}%`}})})]}),n===1&&a("form",{onSubmit:D,style:{display:"flex",flexDirection:"column",gap:20},children:[a("div",{children:[e("h1",{style:{marginBlock:"0 8px",fontSize:28},children:"Connect PayPal"}),e("p",{style:{margin:0,color:o.subtle,lineHeight:1.5},children:"Paste the keys from your PayPal app. You\u2019ll start in Sandbox, so nothing is charged while you test."})]}),e(I,{label:"Client ID",value:h,onChange:P=>C(P.target.value),autoComplete:"off",required:!0}),e(I,{label:"Secret",type:"password",value:w,onChange:P=>k(P.target.value),autoComplete:"off",required:!0,error:y||void 0}),a("div",{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"},children:[e(m,{type:"submit",variant:"primary",disabled:u||!h||!w,children:u?"Checking\u2026":"Connect"}),e("a",{href:"https://developer.paypal.com/dashboard/applications/sandbox",target:"_blank",rel:"noreferrer",children:"Where do I find these?"})]})]}),n===2&&a("form",{onSubmit:O,style:{display:"flex",flexDirection:"column",gap:20},children:[a("div",{children:[e("h1",{style:{marginBlock:"0 8px",fontSize:28},children:"Add your first product"}),e("p",{style:{margin:0,color:o.subtle},children:"You can add more and fine-tune them later."})]}),e(I,{label:"Name",value:S,onChange:P=>c(P.target.value),required:!0}),a("div",{style:{display:"flex",gap:12,alignItems:"flex-end"},children:[e("div",{style:{width:120},children:e(ce,{label:"Currency",value:b,onValueChange:P=>f(P??b),items:be,disabled:t.hasOrders})}),e("div",{style:{flex:1},children:e(I,{label:"Price",value:g,onChange:P=>r(P.target.value),inputMode:"decimal",placeholder:"19.99",required:!0})})]}),y&&e("span",{role:"alert",style:{color:o.danger,fontSize:14},children:y}),e("div",{children:e(m,{type:"submit",variant:"primary",disabled:u||!S||!g,children:u?"Saving\u2026":"Create product"})})]}),n===3&&a("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[a("div",{children:[e("h1",{style:{marginBlock:"0 8px",fontSize:28},children:"You\u2019re ready to sell"}),a("p",{style:{margin:0,color:o.subtle,lineHeight:1.5},children:["Put the button on a page: open any page, type ",e("kbd",{children:"/"})," and choose ",e("b",{children:"Buy button"}),"."]})]}),a("div",{style:{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"},children:[e(H,{href:ve,variant:"primary",children:"Open a page"}),e(m,{variant:"ghost",onClick:()=>{d()},children:"Go to Orders"})]})]})]})}function Se({state:t,onClose:l,onDone:d}){let[s,n]=i.useState(t.live.set?2:1),[p,u]=i.useState(""),[v,y]=i.useState(""),[x,h]=i.useState(!0),[C,w]=i.useState(!1),[k,S]=i.useState("");async function c(b){b.preventDefault(),w(!0),S("");try{await R("connection/save",{env:"live",clientId:p,clientSecret:v}),n(2)}catch(f){S($(f,"Couldn\u2019t verify these keys."))}finally{w(!1)}}async function g(){w(!0),S("");try{await R("connection/switch",{env:"live",deleteSandboxOrders:x}),n(3)}catch(b){S($(b,"Couldn\u2019t switch."))}finally{w(!1)}}return a(K,{title:s===1?"Go live":s===2?"Switch to Live?":"You\u2019re live",onClose:l,children:[s===1&&a("form",{onSubmit:c,style:{display:"flex",flexDirection:"column",gap:16},children:[e("p",{style:{margin:0,color:o.subtle,lineHeight:1.5},children:"Paste the keys from your Live PayPal app. Needs a PayPal Business account."}),e(I,{label:"Live Client ID",value:p,onChange:b=>u(b.target.value),autoComplete:"off"}),e(I,{label:"Live Secret",type:"password",value:v,onChange:b=>y(b.target.value),autoComplete:"off",error:k||void 0}),a("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e(m,{variant:"ghost",onClick:l,children:"Cancel"}),e(m,{type:"submit",variant:"primary",disabled:C||!p||!v,children:C?"Checking\u2026":"Verify keys"})]})]}),s===2&&a("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e("p",{style:{margin:0,color:o.subtle,lineHeight:1.5},children:"From now on, every PayPal button on your site takes real payments."}),t.sandboxOrderCount>0&&e(V,{label:`Delete the ${t.sandboxOrderCount} test ${t.sandboxOrderCount===1?"order":"orders"}`,checked:x,onCheckedChange:h}),k&&e("span",{role:"alert",style:{color:o.danger},children:k}),a("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e(m,{variant:"ghost",onClick:l,children:"Not now"}),e(m,{variant:"primary",onClick:()=>{g()},disabled:C,children:"Switch to Live"})]})]}),s===3&&a("div",{style:{display:"flex",flexDirection:"column",gap:16,alignItems:"flex-start"},children:[e(T,{variant:"success",children:"Live"}),e("p",{style:{margin:0,color:o.subtle,lineHeight:1.5},children:"Tip: buy your own product once and refund it in PayPal to be sure."}),e(m,{variant:"primary",onClick:()=>{l(),d()},children:"Done"})]})]})}function Ze({state:t}){let l=[["Connect PayPal",t.setup.connected],["Add to a page",t.setup.onPage],["Test purchase",t.setup.testPurchase]],d=l.filter(([,n])=>n).length,s=l.find(([,n])=>!n)?.[0];return d===l.length?null:a("section",{"aria-label":"Finish setup",style:{...A,display:"flex",alignItems:"center",gap:20,flexWrap:"wrap",paddingBlock:18,paddingInline:20},children:[a("div",{style:{flex:"1 1 220px"},children:[a("strong",{children:["Finish setup \xB7 ",d," of ",l.length," done"]}),a("div",{style:{fontSize:14,color:o.subtle},children:["Next: ",s==="Add to a page"?"add the Buy button to a page.":"buy your product once with a sandbox buyer account."]})]}),e("ol",{style:{listStyle:"none",margin:0,padding:0,display:"flex",gap:16,fontSize:14,flexWrap:"wrap"},children:l.map(([n,p])=>a("li",{style:{color:p?o.subtle:void 0,fontWeight:n===s?600:400},children:[p?"\u2713 ":"\u25CB ",n]},n))}),e(H,{href:ve,variant:"primary",size:"sm",children:"Open a page"})]})}function Je({state:t,onUpgrade:l}){let[d,s]=i.useState("all"),[n,p]=i.useState(""),[u,v]=i.useState(()=>M.get("orders")??null),[y,x]=i.useState(null),[h,C]=i.useState(!1),w=i.useCallback(async()=>{let r=await R("orders/list",{filter:d,q:n});d==="all"&&!n&&M.set("orders",r),v(r)},[d,n]);i.useEffect(()=>{let r=setTimeout(()=>{w()},n?250:0);return()=>clearTimeout(r)},[w,n]);async function k(){let{csv:r}=await R("orders/export",{filter:d,q:n}),b=URL.createObjectURL(new Blob([r],{type:"text/csv"})),f=document.createElement("a");f.href=b,f.download=`buyblock-orders-${new Date().toISOString().slice(0,10)}.csv`,f.click(),URL.revokeObjectURL(b)}async function S(r){C(!0);try{x(await R("orders/refresh",{id:r.gatewayOrderId})),await w()}finally{C(!1)}}let c=r=>u?` ${u.counts[r]??0}`:"",g=[["Revenue \xB7 30 days",t.stats.revenue==="0"?`0 ${t.currency}`:t.stats.revenue],["Paid orders",t.stats.paid],["Started, not paid",t.stats.unpaid]];return a("div",{style:{display:"flex",flexDirection:"column",gap:24},children:[e(Ze,{state:t}),e("dl",{style:{margin:0,display:"flex",gap:48,flexWrap:"wrap"},children:g.map(([r,b])=>a("div",{children:[e("dt",{style:{fontSize:13,color:o.subtle},children:r}),e("dd",{style:{margin:0,fontSize:26,fontWeight:700,fontVariantNumeric:"tabular-nums"},children:b})]},r))}),a("div",{style:{display:"flex",gap:20,flexWrap:"wrap",alignItems:"flex-start"},children:[a("section",{"aria-label":"Orders",style:{flex:"999 1 480px",minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[a("div",{style:{display:"flex",gap:10,flexWrap:"wrap",alignItems:"center"},children:[e(te,{variant:"segmented",size:"sm",value:d,onValueChange:r=>s(r),tabs:[{value:"all",label:`All${c("all")}`},{value:"paid",label:`Paid${c("paid")}`},{value:"unpaid",label:`Unpaid${c("unpaid")}`},{value:"issues",label:`Issues${c("issues")}`}]}),e("div",{style:{flex:"1 1 200px"},children:e(I,{"aria-label":"Search orders",placeholder:"Search name, email or PayPal ID",value:n,onChange:r=>p(r.target.value),size:"sm"})}),t.pro?e(m,{size:"sm",variant:"outline",onClick:()=>{k()},children:"Export CSV"}):e(ut,{label:"Export CSV",onUpgrade:l})]}),u?u.items.length===0?e(xe,{children:u.counts.all===0?"No orders yet. They appear as soon as someone clicks a PayPal button.":"No orders match."}):e("div",{style:{...A,overflowX:"auto"},children:a("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:14,minWidth:560},children:[e("thead",{children:a("tr",{children:[e("th",{scope:"col",style:F,children:"Date"}),e("th",{scope:"col",style:F,children:"Customer"}),e("th",{scope:"col",style:F,children:"Product"}),e("th",{scope:"col",style:{...F,textAlign:"end"},children:"Amount"}),e("th",{scope:"col",style:F,children:"Status"}),e("th",{scope:"col",style:{...F,width:48},children:e("span",{style:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)"},children:"View"})})]})}),e("tbody",{children:u.items.map(r=>{let b=()=>x(r),f=y?.gatewayOrderId===r.gatewayOrderId;return a("tr",{tabIndex:0,"aria-selected":f,onClick:b,onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),b())},style:{cursor:"pointer",borderTop:`1px solid ${o.line}`,background:f?o.tint:void 0},children:[e("td",{style:{...N,color:o.subtle,whiteSpace:"nowrap"},children:Ge(r.capturedAt??r.createdAt)}),e("td",{style:{...N,fontWeight:500},children:r.payerName||"\u2014"}),e("td",{style:N,children:r.quantity>1?`${r.productName} \xD7 ${r.quantity}`:r.productName}),e("td",{style:{...N,textAlign:"end",fontVariantNumeric:"tabular-nums"},children:ee(r.amount,r.currency)}),e("td",{style:N,children:e(T,{variant:q[r.status].variant,children:q[r.status].label})}),e("td",{style:{...N,paddingBlock:6,textAlign:"end"},children:e(m,{variant:"ghost",shape:"square",size:"sm",icon:e(Oe,{}),"aria-label":`View order ${r.gatewayOrderId}`,tabIndex:-1,onClick:D=>{D.stopPropagation(),b()}})})]},r.gatewayOrderId)})})]})}):e(X,{}),u?.historyDays&&a("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap",fontSize:14,color:o.subtle},children:[e(ne,{"aria-hidden":"true"}),a("span",{children:[u.older>0?`${u.older} older ${u.older===1?"order is":"orders are"} hidden. `:"","Free shows the last ",u.historyDays," days. Full history and CSV export are in Pro."]}),e(m,{variant:"ghost",size:"sm",onClick:l,children:"Upgrade to Pro"})]})]}),y&&a("aside",{"aria-label":"Order details",style:{...A,flex:"1 1 320px",maxWidth:"100%",boxSizing:"border-box",display:"flex",flexDirection:"column",gap:16,padding:20},children:[a("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[a("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e("strong",{style:{fontSize:24,fontVariantNumeric:"tabular-nums"},children:ee(y.amount,y.currency)}),e(T,{variant:q[y.status].variant,children:q[y.status].label})]}),e(m,{variant:"ghost",shape:"square",size:"sm",icon:e(ye,{}),"aria-label":"Close order details",style:{marginInlineStart:"auto"},onClick:()=>x(null)})]}),a("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"auto 1fr",rowGap:10,columnGap:16,fontSize:14},children:[e("dt",{style:{color:o.subtle},children:"Customer"}),e("dd",{style:{margin:0},children:y.payerName||"\u2014"}),e("dt",{style:{color:o.subtle},children:"Email"}),e("dd",{style:{margin:0,wordBreak:"break-all"},children:y.payerEmail||"\u2014"}),e("dt",{style:{color:o.subtle},children:"Product"}),e("dd",{style:{margin:0},children:y.quantity>1?`${y.productName} \xD7 ${y.quantity}`:y.productName}),(y.shippingName||y.shippingAddress)&&a(Y,{children:[e("dt",{style:{color:o.subtle},children:"Ship to"}),e("dd",{style:{margin:0},children:[y.shippingName,y.shippingAddress].filter(Boolean).join(", ")})]}),e("dt",{style:{color:o.subtle},children:"PayPal ID"}),e("dd",{style:{margin:0,fontFamily:"ui-monospace, monospace",fontSize:13},children:y.gatewayOrderId})]}),y.status==="CREATED"&&e("span",{style:{fontSize:14,color:o.subtle},children:"The buyer opened PayPal but didn\u2019t pay."}),e(dt,{order:y}),a("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[y.status!=="COMPLETED"&&e(m,{size:"sm",variant:"outline",disabled:h,onClick:()=>{S(y)},children:"Check status with PayPal"}),y.status==="COMPLETED"&&e(H,{size:"sm",variant:"outline",external:!0,href:`https://www.${y.mode==="sandbox"?"sandbox.":""}paypal.com/activity`,children:"View in PayPal"})]})]})]})]})}var de=t=>({...t,file:t.file?{name:t.file.name,size:t.file.size}:null}),et={name:"",price:"",description:"",allowQuantity:!1,collectShipping:!1,active:!0,style:{label:"buynow",color:"gold",shape:"rect"},file:null};function tt(){let[t,l]=i.useState(()=>M.get("products")??null),[d,s]=i.useState(""),[n,p]=i.useState(null),[u,v]=i.useState(null),[y,x]=i.useState(!1),h=i.useCallback(async()=>{let c=await R("products/list");M.set("products",c),l(c)},[]);i.useEffect(()=>{h()},[h]);async function C(c){await R("products/active",{id:c.id,active:!c.active}),await h()}async function w(c){x(!0);try{await R("products/archive",{id:c.id}),v(null),n?.id===c.id&&p(null),await h()}finally{x(!1)}}let k=(t?.items??[]).filter(c=>!d||c.name.toLowerCase().includes(d.toLowerCase())),S=n&&e(at,{draft:n,currency:t?.currency??"",onSaved:async()=>{p(null),await h()},onCancel:()=>p(null)},n.id??"new");return a("div",{style:{display:"flex",gap:20,flexWrap:"wrap",alignItems:"flex-start"},children:[a("section",{"aria-label":"Products",style:{flex:"999 1 460px",minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[a("div",{style:{display:"flex",gap:10,alignItems:"center"},children:[e("div",{style:{flex:1},children:e(I,{"aria-label":"Search products",placeholder:"Search products",value:d,onChange:c=>s(c.target.value),size:"sm"})}),e(m,{variant:"primary",size:"sm",onClick:()=>p({...et}),children:"New product"})]}),t?k.length===0?e(xe,{children:d?"No products match.":"No products yet."}):e("div",{style:{...A,overflowX:"auto"},children:a("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:14,minWidth:700},children:[e("thead",{children:a("tr",{children:[e("th",{scope:"col",style:F,children:"Product"}),e("th",{scope:"col",style:{...F,textAlign:"end"},children:"Price"}),e("th",{scope:"col",style:F,children:"Delivers"}),e("th",{scope:"col",style:F,children:"On pages"}),e("th",{scope:"col",style:{...F,textAlign:"end"},children:"Sales"}),e("th",{scope:"col",style:F,children:"Active"}),e("th",{scope:"col",style:{...F,width:84},children:e("span",{style:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"},children:"Actions"})})]})}),e("tbody",{children:k.map(c=>a("tr",{style:{borderTop:`1px solid ${o.line}`,background:n?.id===c.id?o.tint:void 0},children:[e("td",{style:N,children:e(m,{variant:"ghost",size:"sm",onClick:()=>p(de(c)),style:{fontWeight:600,opacity:c.active?1:.6,marginInlineStart:-8},children:c.name})}),e("td",{style:{...N,textAlign:"end",fontVariantNumeric:"tabular-nums"},children:ee(c.price,t.currency)}),e("td",{style:N,children:c.file?a("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[e(De,{"aria-label":"Digital file",style:{color:o.brand,flex:"none"}}),e("span",{style:{fontFamily:"ui-monospace, monospace",fontSize:13,wordBreak:"break-all"},children:c.file.name}),a("span",{style:{color:o.subtle,whiteSpace:"nowrap"},children:["\xB7 ",oe(c.file.size)]})]}):e("span",{style:{color:o.subtle},children:"\u2014"})}),e("td",{style:{...N,color:c.pages.length?void 0:o.warning},children:c.pages.length||"None"}),e("td",{style:{...N,textAlign:"end"},children:c.sales}),e("td",{style:N,children:e(V,{"aria-label":`${c.name} active`,checked:c.active,onCheckedChange:()=>{C(c)},size:"sm"})}),e("td",{style:{...N,paddingInline:6},children:a("div",{style:{display:"flex",justifyContent:"flex-end",gap:2},children:[e(m,{variant:"ghost",shape:"square",size:"sm",icon:e(Te,{}),"aria-label":`Edit ${c.name}`,title:"Edit",onClick:()=>p(de(c))}),e(m,{variant:"ghost",shape:"square",size:"sm",icon:e(Le,{}),"aria-label":`Delete ${c.name}`,title:"Delete",onClick:()=>v(c),style:{color:o.danger}})]})})]},c.id))})]})}):e(X,{})]}),n&&e(K,{title:n.id?"Edit product":"New product",onClose:()=>p(null),children:S}),u&&a(K,{title:`Delete \u201C${u.name}\u201D?`,onClose:()=>v(null),children:[a("p",{style:{margin:0,color:o.subtle,lineHeight:1.5},children:[u.pages.length?`Its PayPal button disappears from ${u.pages.length===1?"1 page":`${u.pages.length} pages`}. `:"",u.sales?"Past orders are kept.":"This can\u2019t be undone."]}),a("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e(m,{variant:"ghost",onClick:()=>v(null),children:"Cancel"}),e(m,{variant:"destructive",disabled:y,onClick:()=>{w(u)},children:y?"Deleting\u2026":"Delete"})]})]})]})}function at({draft:t,currency:l,onSaved:d,onCancel:s}){let[n,p]=i.useState(t),[u,v]=i.useState(!1),[y,x]=i.useState(""),[h,C]=i.useState(!1),[w,k]=i.useState(!1),S=(g,r)=>p(b=>({...b,[g]:r}));async function c(g){g.preventDefault(),C(!0),x("");try{let{fileChanged:r,file:b,...f}=n;await R("products/save",r?{...f,file:b?.key?{key:b.key}:null}:f),await d()}catch(r){x($(r,"Couldn\u2019t save."))}finally{C(!1)}}return a("form",{onSubmit:c,"aria-label":n.id?"Edit product":"New product",style:{display:"flex",flexDirection:"column",gap:16},children:[e(I,{label:"Name",value:n.name,onChange:g=>S("name",g.target.value),required:!0,autoFocus:!n.id}),e(I,{label:`Price (${l})`,value:n.price,onChange:g=>S("price",g.target.value),inputMode:"decimal",placeholder:"19.99",required:!0}),e(I,{label:"Description (optional)",value:n.description,onChange:g=>S("description",g.target.value)}),e(rt,{value:n.file,onChange:g=>p(r=>({...r,file:g,fileChanged:!0})),onBusy:k}),e(V,{label:"Buyers can choose a quantity",checked:n.allowQuantity,onCheckedChange:g=>S("allowQuantity",g)}),e(V,{label:"Collect a shipping address",checked:n.collectShipping,onCheckedChange:g=>S("collectShipping",g)}),a("div",{style:{display:"flex",flexDirection:"column",gap:10,paddingBlockStart:14,borderBlockStart:`1px solid ${o.line}`},children:[a("div",{style:{display:"flex",alignItems:"center"},children:[e("span",{style:{fontSize:14,fontWeight:500},children:"Button"}),e(m,{variant:"ghost",size:"sm",style:{marginInlineStart:"auto"},"aria-expanded":u,onClick:()=>v(g=>!g),children:u?"Done":"Customize"})]}),e(_e,{style:n.style}),u&&a("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e(J,{label:"Label",value:n.style.label,options:[["buynow","Buy Now"],["checkout","Checkout"],["pay","Pay"]],onChange:g=>S("style",{...n.style,label:g})}),e(J,{label:"Colour",value:n.style.color,options:[["gold","Gold"],["blue","Blue"],["white","White"]],onChange:g=>S("style",{...n.style,color:g})}),e(J,{label:"Corners",value:n.style.shape,options:[["rect","Rounded"],["pill","Pill"],["sharp","Square"]],onChange:g=>S("style",{...n.style,shape:g})})]})]}),n.id&&e("div",{style:{paddingBlockStart:14,borderBlockStart:`1px solid ${o.line}`,fontSize:14,display:"flex",gap:6,flexWrap:"wrap"},children:n.pages&&n.pages.length?a(Y,{children:[a("span",{children:["On ",n.pages.length," ",n.pages.length===1?"page":"pages",":"]}),n.pages.map((g,r)=>a("span",{children:[e("a",{href:g.editUrl,children:g.title}),r<n.pages.length-1?" \xB7":""]},g.collection+g.id))]}):e("span",{style:{color:o.subtle},children:"Not on a page yet. Open a page, type / and choose Buy button."})}),y&&e("span",{role:"alert",style:{color:o.danger,fontSize:14},children:y}),a("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[e(m,{type:"submit",variant:"primary",disabled:h||w,children:h?"Saving\u2026":n.id?"Save":"Create product"}),e(m,{variant:"ghost",onClick:s,children:"Cancel"})]})]})}function nt({state:t,reload:l}){let[d,s]=i.useState(!1),[n,p]=i.useState(""),[u,v]=i.useState(""),[y,x]=i.useState(""),[h,C]=i.useState({currency:t.currency,brandName:t.brandName,successMessage:t.successMessage}),[w,k]=i.useState(""),[S,c]=i.useState(!1),[g,r]=i.useState(!1),[b,f]=i.useState(!1);async function D(z){z.preventDefault(),f(!0),x("");try{await R("connection/save",{env:t.mode,clientId:n,clientSecret:u}),s(!1),p(""),v(""),await l()}catch(L){x($(L,"Couldn\u2019t verify."))}finally{f(!1)}}async function O(z){z.preventDefault(),f(!0);try{await R("store/save",h),k("Saved"),await l(),setTimeout(()=>k(""),2e3)}finally{f(!1)}}let P={display:"flex",alignItems:"center",gap:16,paddingBlock:16,paddingInline:18,flexWrap:"wrap"},B={margin:0,fontSize:15,fontWeight:500,color:o.subtle},Q=t.mode==="live"?"Live":"Sandbox";return a("div",{style:{maxWidth:720,display:"flex",flexDirection:"column",gap:32},children:[a("section",{"aria-labelledby":"pp-acct",style:{display:"flex",flexDirection:"column",gap:10},children:[e("h2",{id:"pp-acct",style:B,children:"PayPal account"}),a("div",{style:A,children:[a("div",{style:P,children:[a("div",{style:{flex:"1 1 240px"},children:[e("strong",{children:Q}),a("div",{style:{fontSize:14,color:o.subtle},children:["Connected \xB7 Client ID ending ",t[t.mode].tail]})]}),!d&&e(m,{variant:"outline",size:"sm",onClick:()=>s(!0),children:"Change keys"})]}),d&&a("form",{onSubmit:D,style:{...P,alignItems:"flex-end",borderBlockStart:`1px solid ${o.line}`},children:[e("div",{style:{flex:"1 1 200px"},children:e(I,{label:`${Q} Client ID`,value:n,onChange:z=>p(z.target.value),autoComplete:"off"})}),e("div",{style:{flex:"1 1 200px"},children:e(I,{label:`${Q} Secret`,type:"password",value:u,onChange:z=>v(z.target.value),autoComplete:"off",error:y||void 0})}),e(m,{type:"submit",variant:"primary",size:"sm",disabled:b||!n||!u,children:"Verify & save"}),e(m,{variant:"ghost",size:"sm",onClick:()=>s(!1),children:"Cancel"})]}),t.mode==="sandbox"&&a("div",{style:{...P,borderBlockStart:`1px solid ${o.line}`},children:[a("div",{style:{flex:"1 1 240px"},children:[e("strong",{children:"Live"}),e("div",{style:{fontSize:14,color:o.subtle},children:t.live.set?`Keys saved \xB7 ending ${t.live.tail}`:"Not set up"})]}),e(m,{variant:"primary",size:"sm",onClick:()=>c(!0),children:"Go live"})]})]})]}),a("form",{onSubmit:O,"aria-labelledby":"pp-store",style:{display:"flex",flexDirection:"column",gap:10},children:[e("h2",{id:"pp-store",style:B,children:"Store"}),a("div",{style:{...A,display:"flex",flexDirection:"column",gap:16,padding:18},children:[a("div",{style:{display:"flex",gap:16,flexWrap:"wrap",alignItems:"flex-end"},children:[e("div",{style:{width:140},children:e(ce,{label:"Currency",value:h.currency,onValueChange:z=>C({...h,currency:z??h.currency}),items:be})}),e("div",{style:{flex:"1 1 240px"},children:e(I,{label:"Name shown on PayPal",value:h.brandName,onChange:z=>C({...h,brandName:z.target.value}),placeholder:"Your PayPal business name"})})]}),e(I,{label:"Message after payment",value:h.successMessage,onChange:z=>C({...h,successMessage:z.target.value})}),a("div",{style:{display:"flex",alignItems:"center",gap:12},children:[e(m,{type:"submit",variant:"primary",size:"sm",disabled:b,children:"Save"}),w&&e("span",{role:"status",style:{fontSize:14,color:o.subtle},children:w})]})]})]}),e(ct,{}),a("div",{style:{display:"flex",alignItems:"center",gap:12,paddingBlockStart:20,borderBlockStart:`1px solid ${o.line}`,flexWrap:"wrap"},children:[e("span",{style:{fontSize:14,color:o.subtle},children:"Removes your keys. Buttons stop working; orders are kept."}),e(m,{variant:"secondary-destructive",size:"sm",style:{marginInlineStart:"auto"},onClick:()=>r(!0),children:"Disconnect PayPal"})]}),S&&e(Se,{state:t,onClose:()=>c(!1),onDone:l}),g&&a(K,{title:"Disconnect PayPal?",onClose:()=>r(!1),children:[e("p",{style:{margin:0,color:o.subtle,lineHeight:1.5},children:"Your keys are deleted and the buttons on your site stop working until you connect again."}),a("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e(m,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e(m,{variant:"destructive",onClick:async()=>{await R("connection/disconnect"),window.location.href=W},children:"Disconnect"})]})]})]})}var ot={lightning:e(Ne,{size:20}),envelope:e(ae,{size:20}),key:e(pe,{size:20}),heart:e(Fe,{size:20}),repeat:e($e,{size:20}),clock:e(Re,{size:20})},it={swatches:e(Qe,{size:18}),package:e(Me,{size:18}),ticket:e(Ue,{size:18}),truck:e(Ve,{size:18}),wallet:e(He,{size:18}),lifebuoy:e(We,{size:18})};function lt(){return a("div",{style:{width:"100%",maxWidth:680,marginInline:"auto",display:"flex",flexDirection:"column",gap:28,paddingBlock:8},children:[a("section",{"aria-labelledby":"pro-title",style:{display:"flex",flexDirection:"column",alignItems:"center",gap:12,textAlign:"center"},children:[e(T,{variant:"secondary",children:"Coming soon"}),e("h2",{id:"pro-title",style:{margin:0,fontSize:30,fontWeight:700,letterSpacing:"-0.02em"},children:"Buyblock Pro"}),a("p",{style:{margin:0,color:o.subtle,fontSize:16,lineHeight:1.5,maxWidth:520,textWrap:"balance"},children:["For when you sell every week. Get early access and ",e("strong",{style:{color:"inherit"},children:"40% off your first year"}),"."]}),e(H,{href:G("pro"),variant:"primary",icon:e(ae,{}),style:{marginBlockStart:4},children:"Get early access"}),a("span",{style:{fontSize:13,color:o.subtle,lineHeight:1.5},children:["Opens your email app with a message to ",Z,". We\u2019ll write once, when Pro is ready."]})]}),e("ul",{"aria-label":"What Pro adds",style:{listStyle:"none",margin:0,padding:0,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:12},children:le.map(t=>e("li",{style:{display:"flex"},children:a("a",{href:G(t.id),style:{...A,flex:1,display:"flex",gap:12,alignItems:"flex-start",padding:16,color:"inherit",textDecoration:"none"},children:[e("span",{"aria-hidden":"true",style:{flex:"none",width:36,height:36,borderRadius:10,background:o.tint,color:o.brand,display:"flex",alignItems:"center",justifyContent:"center"},children:ot[t.icon]}),a("span",{style:{display:"flex",flexDirection:"column",gap:2},children:[e("strong",{style:{fontSize:15},children:t.title}),e("span",{style:{fontSize:13,color:o.subtle,lineHeight:1.4},children:t.detail})]})]})},t.title))}),a("section",{"aria-labelledby":"pro-more",style:{background:o.tint,borderRadius:12,paddingBlock:18,paddingInline:20,display:"flex",flexDirection:"column",gap:14},children:[e("h3",{id:"pro-more",style:{margin:0,fontSize:13,fontWeight:500,color:o.subtle},children:"Also on the roadmap"}),e("ul",{style:{listStyle:"none",margin:0,padding:0,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",rowGap:12,columnGap:20},children:se.map(t=>a("li",{style:{display:"flex",alignItems:"center",gap:10,fontSize:14,fontWeight:500},children:[e("span",{"aria-hidden":"true",style:{display:"flex",color:o.brand},children:it[t.icon]}),t.label]},t.label))})]})]})}function U({feature:t,icon:l,label:d}){return a("a",{href:G(t),title:`${d} is part of Buyblock Pro`,style:{display:"flex",alignItems:"center",gap:10,minHeight:40,color:o.subtle,fontSize:14,textDecoration:"none"},children:[e("span",{"aria-hidden":"true",style:{display:"flex"},children:l}),e("span",{style:{flex:1},children:d}),e(T,{variant:"secondary",children:a("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e(ne,{size:12,"aria-hidden":"true"}),"Pro"]})})]})}function oe(t){return t<1024*1024?`${Math.max(1,Math.round(t/1024))} KB`:t<1024*1024*1024?`${(t/1024/1024).toFixed(1)} MB`:`${(t/1024/1024/1024).toFixed(2)} GB`}function we(){let[t,l]=i.useState(()=>M.get("downloads")??null),d=i.useCallback(async()=>{try{let s=await R("downloads/state");M.set("downloads",s),l(s)}catch{}},[]);return i.useEffect(()=>{d()},[d]),{state:t,reload:d}}var st=2*1024*1024*1024;function rt({value:t,onChange:l,onBusy:d}){let{state:s}=we(),[n,p]=i.useState(null),[u,v]=i.useState(""),[y,x]=i.useState(!1),[h,C]=i.useState(!1),w=i.useRef(null),k=i.useRef(!1),S=!!s&&s.onCloudflare&&!s.hasBinding;async function c(f){if(v(""),f.size===0)return v("This file is empty.");if(f.size>st)return v("Files can be up to 2 GB.");k.current=!1,d(!0),p({name:f.name,size:f.size,sent:0});let D="";try{let O=await R("files/begin",{name:f.name,size:f.size,type:f.type});D=O.id;for(let B=1;B<=O.parts;B++){if(k.current)throw new Error("cancelled");let Q=f.slice((B-1)*O.partSize,Math.min(B*O.partSize,f.size));for(let z=1;;z++)try{let L=await fe(`${me}/files/part?id=${D}&n=${B}`,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:Q});await ge(L,"The upload was interrupted. Try again.");break}catch(L){if(z>=3||k.current)throw L}p({name:f.name,size:f.size,sent:Math.min(B*O.partSize,f.size)})}if(k.current)throw new Error("cancelled");let P=await R("files/complete",{id:D});k.current||l(P.file)}catch(O){D&&R("files/abort",{id:D}).catch(()=>{}),k.current||v($(O,"The upload failed. Try again."))}finally{p(null),d(!1),w.current&&(w.current.value="")}}let g=()=>w.current?.click(),r=n?Math.round(n.sent/n.size*100):0,b=f=>(f/1024/1024).toFixed(f<10*1024*1024?1:0);return a("section",{"aria-labelledby":"df-h",style:{display:"flex",flexDirection:"column",gap:10,paddingBlockStart:14,borderBlockStart:`1px solid ${o.line}`},children:[a("div",{style:{display:"flex",alignItems:"baseline",gap:10,flexWrap:"wrap"},children:[e("h3",{id:"df-h",style:{margin:0,fontSize:15},children:"Digital file"}),e("span",{style:{fontSize:13,color:o.subtle},children:"Optional. Buyers get it right after they pay."})]}),e("input",{ref:w,type:"file",hidden:!0,onChange:f=>f.target.files?.[0]&&void c(f.target.files[0])}),S?a("div",{style:{...A,display:"flex",alignItems:"center",gap:12,flexWrap:"wrap",padding:14,fontSize:14},children:[e("span",{style:{flex:"1 1 240px",lineHeight:1.5},children:"This site runs on Cloudflare, so files need an R2 bucket to live in."}),e("a",{href:`${W}/settings`,children:"Choose storage"})]}):n?a("div",{style:{...A,display:"flex",flexDirection:"column",gap:10,padding:14},children:[a("div",{style:{display:"flex",gap:8,fontSize:14,flexWrap:"wrap"},children:[e("span",{style:{fontFamily:"ui-monospace, monospace",fontSize:13,wordBreak:"break-all"},children:n.name}),a("span",{style:{marginInlineStart:"auto",color:o.subtle,fontVariantNumeric:"tabular-nums"},children:[b(n.sent)," of ",b(n.size)," MB \xB7 ",r,"%"]})]}),e("div",{role:"progressbar","aria-label":"Upload progress","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":r,style:{height:8,borderRadius:999,background:o.tint,overflow:"hidden"},children:e("div",{style:{height:"100%",width:`${r}%`,background:o.brand,transition:"width 200ms"}})}),a("div",{style:{display:"flex",alignItems:"center",gap:10,fontSize:13,color:o.subtle},children:[e("span",{children:"Keep this window open until the upload finishes."}),e(m,{variant:"ghost",size:"sm",style:{marginInlineStart:"auto",color:o.danger},onClick:()=>{k.current=!0},children:"Cancel"})]})]}):t&&!y?a("div",{style:{...A,display:"flex",alignItems:"center",gap:12,padding:14,fontSize:14,flexWrap:"wrap"},children:[e(ue,{size:18,"aria-hidden":"true",style:{color:o.subtle,flex:"none"}}),a("span",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0,flex:"1 1 200px"},children:[e("span",{style:{fontFamily:"ui-monospace, monospace",fontSize:13,wordBreak:"break-all"},children:t.name}),a("span",{style:{color:o.subtle},children:[oe(t.size),t.key?" \xB7 uploaded, save to attach":""]})]}),e(m,{variant:"ghost",size:"sm",onClick:g,children:"Replace"}),e(m,{variant:"ghost",size:"sm",style:{color:o.danger},onClick:()=>x(!0),children:"Remove"})]}):t&&y?a("div",{role:"alert",style:{...A,display:"flex",alignItems:"center",gap:12,flexWrap:"wrap",padding:12,fontSize:14},children:[e("span",{style:{flex:"1 1 240px",lineHeight:1.45},children:"Remove the file? After you save, past buyers can no longer download it."}),e(m,{variant:"destructive",size:"sm",onClick:()=>{x(!1),l(null)},children:"Remove"}),e(m,{variant:"ghost",size:"sm",onClick:()=>x(!1),children:"Keep"})]}):a("button",{type:"button",onClick:g,onDragOver:f=>{f.preventDefault(),C(!0)},onDragLeave:()=>C(!1),onDrop:f=>{f.preventDefault(),C(!1);let D=f.dataTransfer.files?.[0];D&&c(D)},style:{display:"flex",flexDirection:"column",alignItems:"center",gap:6,paddingBlock:22,paddingInline:16,background:h?o.tint:"transparent",color:"inherit",border:`1px dashed ${o.line}`,borderRadius:12,cursor:"pointer",font:"inherit"},children:[e(Ae,{size:22,"aria-hidden":"true",style:{color:o.brand}}),e("span",{style:{fontWeight:500},children:"Drop a file here or choose one"}),e("span",{style:{fontSize:13,color:o.subtle},children:"Any type, up to 2 GB. Stored privately, never in the media library."})]}),u&&e("span",{role:"alert",style:{color:o.danger,fontSize:14},children:u}),a("div",{style:{display:"flex",flexDirection:"column"},children:[e(U,{feature:"multiple-files",icon:e(Be,{size:16}),label:"Add another file"}),e(U,{feature:"versions",icon:e(Ee,{size:16}),label:"Versions: upload v2, past buyers get it too"}),e(U,{feature:"license-keys",icon:e(pe,{size:16}),label:"Give each buyer a license key"})]})]})}function dt({order:t}){let[l,d]=i.useState(null),[s,n]=i.useState(!1);if(i.useEffect(()=>{let u=!0;return d(null),n(!1),(t.status==="COMPLETED"||t.status==="PENDING")&&R("orders/download",{id:t.gatewayOrderId}).then(v=>u&&d(v)).catch(()=>{}),()=>{u=!1}},[t.gatewayOrderId,t.status]),!l?.digital)return null;if(t.status==="PENDING")return a("p",{style:{margin:0,paddingBlockStart:14,borderBlockStart:`1px solid ${o.line}`,fontSize:14,color:o.subtle,lineHeight:1.5},children:["The download unlocks when PayPal completes the payment. Use ",e("b",{children:"Check status with PayPal"})," to update it."]});async function p(){l?.orderUrl&&(await navigator.clipboard.writeText(new URL(l.orderUrl,window.location.origin).href),n(!0),setTimeout(()=>n(!1),2e3))}return a("section",{"aria-labelledby":"od-dl",style:{display:"flex",flexDirection:"column",gap:12,paddingBlockStart:14,borderBlockStart:`1px solid ${o.line}`},children:[e("h3",{id:"od-dl",style:{margin:0,fontSize:15},children:"Download"}),a("div",{style:{display:"flex",alignItems:"center",gap:10,fontSize:14,flexWrap:"wrap"},children:[e(ue,{size:16,"aria-hidden":"true",style:{color:o.subtle}}),e("span",{style:{fontFamily:"ui-monospace, monospace",fontSize:13,wordBreak:"break-all"},children:l.fileName}),e("span",{style:{marginInlineStart:"auto",color:o.subtle},children:l.count?`Downloaded ${l.count} ${l.count===1?"time":"times"}`:"Not downloaded yet"})]}),a("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e(m,{variant:"outline",size:"sm",icon:e(Pe,{}),onClick:()=>{p()},children:s?"Copied":"Copy buyer\u2019s order link"}),e("span",{style:{fontSize:13,color:o.subtle,lineHeight:1.4},children:"Their private order page. Send it yourself if the buyer asks for their file."})]}),a("div",{style:{display:"flex",flexDirection:"column"},children:[e(U,{feature:"resend-link",icon:e(ae,{size:16}),label:"Email the link to the buyer"}),e(U,{feature:"download-log",icon:e(ze,{size:16}),label:"Download log (when, which country)"}),e(U,{feature:"revoke-on-refund",icon:e(Ie,{size:16}),label:"Turn off access when refunded"})]})]})}function ct(){let{state:t,reload:l}=we(),[d,s]=i.useState(!1),[n,p]=i.useState("folder"),[u,v]=i.useState(null),[y,x]=i.useState(!1),[h,C]=i.useState(!1),[w,k]=i.useState("5"),[S,c]=i.useState(""),[g,r]=i.useState(""),[b,f]=i.useState(null);i.useEffect(()=>{t&&(p(t.storage),C(t.limit>0||t.days>0),k(t.limit?String(t.limit):""),c(t.days?String(t.days):""))},[t?.storage,t?.limit,t?.days]),i.useEffect(()=>{fetch("/buyblock/order?ping=1",{headers:{Accept:"application/json"}}).then(async E=>f(E.ok&&(await E.json().catch(()=>null))?.buyblock===!0)).catch(()=>f(!1))},[]);async function D(){x(!0),v(null);try{let E=await R("downloads/check",{storage:n});v(E),E.ok&&(await R("downloads/save",{storage:n}),await l())}catch(E){v({ok:!1,message:$(E,"Couldn\u2019t save.")})}finally{x(!1)}}async function O(E){E.preventDefault(),x(!0);try{await R("downloads/save",{limit:h&&Number(w)||0,days:h&&Number(S)||0}),await l(),r("Saved"),setTimeout(()=>r(""),2e3)}finally{x(!1)}}let P={margin:0,fontSize:15,fontWeight:500,color:o.subtle},B={display:"flex",flexDirection:"column",gap:12,paddingBlock:16,paddingInline:18},Q=t?t.storage==="r2"?"Cloudflare R2 bucket DOWNLOADS":"Private folder on this server":"",z={display:"block",padding:10,borderRadius:8,background:o.tint,fontFamily:"ui-monospace, monospace",fontSize:13,whiteSpace:"pre",overflowX:"auto"},L=(E,ie=!1)=>({...A,display:"flex",gap:12,alignItems:"flex-start",padding:14,cursor:ie?"default":"pointer",opacity:ie?.6:1,borderColor:E?o.brand:o.line});return a("section",{"aria-labelledby":"pp-dl",style:{display:"flex",flexDirection:"column",gap:10},children:[e("h2",{id:"pp-dl",style:P,children:"Downloads"}),a("div",{style:A,children:[a("div",{style:B,children:[a("div",{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"},children:[a("div",{style:{flex:"1 1 240px"},children:[e("strong",{children:"File storage"}),e("div",{style:{fontSize:14,color:o.subtle},children:t?`${Q} \xB7 ${t.files} ${t.files===1?"file":"files"} \xB7 ${oe(t.bytes)}`:"\u2026"})]}),!d&&e(m,{variant:"outline",size:"sm",onClick:()=>s(!0),children:"Change"})]}),d&&t&&a("div",{role:"radiogroup","aria-label":"File storage",style:{display:"flex",flexDirection:"column",gap:10},children:[a("label",{style:L(n==="folder",t.onCloudflare),children:[e("input",{type:"radio",name:"dl-store",checked:n==="folder",disabled:t.onCloudflare,onChange:()=>p("folder"),style:{marginBlockStart:3}}),a("span",{style:{display:"flex",flexDirection:"column",gap:4,fontSize:14},children:[a("strong",{children:["Private folder on this server ",e(T,{variant:"secondary",children:"Default"})]}),e("span",{style:{color:o.subtle},children:t.onCloudflare?"Not available here: sites on Cloudflare have no server disk.":a(Y,{children:["For sites on a VPS or any Node server. Nothing to set up. Files go to ",e("code",{children:t.folderPath}),", outside the site\u2019s public files; back it up with your database."]})})]})]}),a("label",{style:L(n==="r2"),children:[e("input",{type:"radio",name:"dl-store",checked:n==="r2",onChange:()=>p("r2"),style:{marginBlockStart:3}}),a("span",{style:{display:"flex",flexDirection:"column",gap:6,fontSize:14,minWidth:0},children:[e("strong",{children:"Cloudflare R2 bucket"}),e("span",{style:{color:o.subtle},children:"For sites on Cloudflare, or several servers that share the same files."}),n==="r2"&&!t.hasBinding&&a(Y,{children:[e("span",{children:"1. Create a bucket and leave public access off."}),e("code",{style:z,children:"npx wrangler r2 bucket create my-site-downloads"}),a("span",{children:["2. Bind it as ",e("code",{children:"DOWNLOADS"})," in ",e("code",{children:"wrangler.jsonc"}),", then deploy."]}),e("code",{style:z,children:`"r2_buckets": [
8
+ { "binding": "DOWNLOADS", "bucket_name": "my-site-downloads" }
9
+ ]`})]})]})]}),u&&e("span",{role:u.ok?"status":"alert",style:{fontSize:14,color:u.ok?void 0:o.danger},children:u.ok?"\u2713 Storage works: wrote, read and deleted a test file.":u.message||"The check failed."}),a("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[e(m,{variant:"primary",size:"sm",disabled:y,onClick:()=>{D()},children:y?"Checking\u2026":"Save and check"}),e(m,{variant:"ghost",size:"sm",onClick:()=>{s(!1),v(null)},children:"Close"}),e("span",{style:{fontSize:13,color:o.subtle},children:"Switching later doesn\u2019t move files you already uploaded."})]})]})]}),a("form",{onSubmit:O,style:{...B,borderBlockStart:`1px solid ${o.line}`},children:[a("div",{children:[e("strong",{children:"Buyer access"}),e("div",{style:{fontSize:14,color:o.subtle,lineHeight:1.5},children:"Buyers download as often as they like from their order page. Each download link works for 1 hour, so a shared link soon stops working."})]}),e(V,{label:"Limit downloads",checked:h,onCheckedChange:C}),h&&a("div",{style:{display:"flex",gap:12,flexWrap:"wrap"},children:[e("div",{style:{flex:"1 1 160px"},children:e(I,{label:"Downloads per order",value:w,onChange:E=>k(E.target.value.replace(/\D/g,"")),inputMode:"numeric",placeholder:"Unlimited"})}),e("div",{style:{flex:"1 1 160px"},children:e(I,{label:"Access for (days)",value:S,onChange:E=>c(E.target.value.replace(/\D/g,"")),inputMode:"numeric",placeholder:"Forever"})})]}),a("div",{style:{display:"flex",alignItems:"center",gap:12},children:[e(m,{type:"submit",variant:"primary",size:"sm",disabled:y,children:"Save"}),g&&e("span",{role:"status",style:{fontSize:14,color:o.subtle},children:g})]})]}),a("div",{style:{...B,borderBlockStart:`1px solid ${o.line}`,fontSize:14},children:[a("div",{children:[e("strong",{children:"Order page"}),e("div",{style:{color:o.subtle,lineHeight:1.5},children:"Buyers find their files again with the PayPal transaction ID and their email."})]}),a("div",{style:{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"},children:[e("code",{children:"/buyblock/order"}),e("a",{href:"/buyblock/order",target:"_blank",rel:"noreferrer",children:"Open \u2197"})]}),a("span",{style:{color:o.subtle,lineHeight:1.5},children:["Prefer your own page? Add the ",e("b",{children:"Order lookup"})," block to any page."]}),b===!1&&a("div",{role:"alert",style:{display:"flex",flexDirection:"column",gap:8,padding:12,borderRadius:10,background:o.tint},children:[a("span",{children:["Buyers can\u2019t reach their files yet. Add ",e("code",{children:"buyblock()"})," to ",e("code",{children:"astro.config.mjs"}),", after ",e("code",{children:"emdash()"}),", then redeploy:"]}),e("code",{style:z,children:`import { buyblock, buyblockPlugin } from "@zachristudio/buyblock";
10
+
11
+ integrations: [emdash({ plugins: [buyblockPlugin()] }), buyblock()]`})]})]})]})]})}function ut({label:t,onUpgrade:l}){return a(m,{variant:"outline",size:"sm",icon:e(ne,{}),onClick:l,title:`${t} is part of Buyblock Pro`,children:[t," ",e(T,{variant:"secondary",children:"Pro"})]})}function pt(){let{state:t}=he();return t?t.connected?a("div",{style:{display:"flex",flexDirection:"column",gap:8,alignItems:"flex-start"},children:[a("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e("span",{style:{fontSize:13,color:o.subtle},children:"Revenue \xB7 30 days"}),t.mode==="sandbox"&&e(T,{variant:"warning",children:"Sandbox"})]}),e("strong",{style:{fontSize:24},children:t.stats.revenue==="0"?`0 ${t.currency}`:t.stats.revenue}),a("span",{style:{fontSize:14},children:[t.stats.paid," paid \xB7 ",t.stats.unpaid," not paid"]}),e("a",{href:W,children:"Open orders"})]}):a("div",{style:{display:"flex",flexDirection:"column",gap:10,alignItems:"flex-start"},children:[e("strong",{children:"Connect PayPal to start selling"}),e("span",{style:{fontSize:13,color:o.subtle},children:"Two steps, about 2 minutes"}),e(H,{href:W,variant:"primary",size:"sm",children:"Set up"})]}):e(X,{})}var Ut={"/":j,"/products":j,"/settings":j,"/pro":j},Vt={sales:pt};export{Ut as pages,Vt as widgets};
@@ -0,0 +1,193 @@
1
+ ---
2
+ /**
3
+ * "Buy button" Portable Text block (pays with PayPal today).
4
+ * Server-renders the product, then the client script loads PayPal's v6 SDK and wires the button.
5
+ * Renders nothing when the product is missing/inactive or PayPal isn't configured.
6
+ */
7
+ import { getPublicPluginApiRouteHandler } from "emdash/plugin-utils";
8
+
9
+ interface ButtonStyle {
10
+ label: "buynow" | "checkout" | "pay";
11
+ color: "gold" | "blue" | "white";
12
+ shape: "rect" | "pill" | "sharp";
13
+ }
14
+ interface PublicButtonConfig {
15
+ gateway: GatewayId;
16
+ product: {
17
+ id: string;
18
+ name: string;
19
+ description: string;
20
+ price: string;
21
+ allowQuantity: boolean;
22
+ };
23
+ clientId: string;
24
+ mode: PayPalMode;
25
+ currency: string;
26
+ style: ButtonStyle;
27
+ successMessage: string;
28
+ }
29
+
30
+
31
+ interface Props {
32
+ node: { productId?: string; showDetails?: boolean };
33
+ }
34
+
35
+ const { node } = Astro.props;
36
+ const productId = typeof node?.productId === "string" ? node.productId : "";
37
+ const showDetails = node?.showDetails !== false;
38
+
39
+ let config: PublicButtonConfig | null = null;
40
+ let unavailable = "";
41
+
42
+ const handle = getPublicPluginApiRouteHandler(Astro.locals);
43
+ if (productId && handle) {
44
+ try {
45
+ const res = await handle(
46
+ "buyblock",
47
+ "POST",
48
+ "/button",
49
+ new Request(new URL("/_emdash/api/plugins/buyblock/button", Astro.url), {
50
+ method: "POST",
51
+ headers: { "Content-Type": "application/json" },
52
+ body: JSON.stringify({ productId }),
53
+ }),
54
+ );
55
+ const data = res.success ? (res.data as PublicButtonConfig | { unavailable: string }) : null;
56
+ if (data && "unavailable" in data) unavailable = data.unavailable;
57
+ else if (data) config = data;
58
+ } catch (error) {
59
+ console.warn("[buyblock] could not load button config:", error);
60
+ }
61
+ }
62
+
63
+ const radius = config?.style.shape === "pill" ? "999px" : config?.style.shape === "sharp" ? "0px" : "4px";
64
+ const instance = Math.random().toString(36).slice(2, 8);
65
+ ---
66
+
67
+ {
68
+ config && (
69
+ <div
70
+ class="buyblock"
71
+ data-buyblock
72
+ data-gateway={config.gateway}
73
+ data-product-id={config.product.id}
74
+ data-client-id={config.clientId}
75
+ data-mode={config.mode}
76
+ data-currency={config.currency}
77
+ data-success={config.successMessage}
78
+ style={`--paypal-button-border-radius:${radius};`}
79
+ >
80
+ {showDetails && (
81
+ <div class="buyblock__details">
82
+ <strong class="buyblock__name">{config.product.name}</strong>
83
+ <span class="buyblock__price">
84
+ {config.product.price} {config.currency}
85
+ </span>
86
+ {config.product.description && <p class="buyblock__desc">{config.product.description}</p>}
87
+ </div>
88
+ )}
89
+ {config.product.allowQuantity && (
90
+ <label class="buyblock__qty" for={`paypal-qty-${instance}`}>
91
+ Quantity
92
+ <input id={`paypal-qty-${instance}`} type="number" min="1" max="99" value="1" inputmode="numeric" data-paypal-qty />
93
+ </label>
94
+ )}
95
+ <paypal-button type={config.style.label} class={`paypal-${config.style.color}`} hidden data-paypal-btn />
96
+ <p class="buyblock__status" data-paypal-status aria-live="polite" hidden />
97
+ <noscript>
98
+ <p class="buyblock__status">Enable JavaScript to pay with PayPal.</p>
99
+ </noscript>
100
+ </div>
101
+ )
102
+ }
103
+ {
104
+ !config && unavailable && import.meta.env.DEV && (
105
+ <p class="buyblock__status">[Buy button hidden: {unavailable}]</p>
106
+ )
107
+ }
108
+
109
+ <style>
110
+ .buyblock {
111
+ max-width: 320px;
112
+ margin: 1.5rem 0;
113
+ display: grid;
114
+ gap: 0.75rem;
115
+ }
116
+ .buyblock__details {
117
+ display: grid;
118
+ gap: 0.15rem;
119
+ }
120
+ .buyblock__price {
121
+ font-variant-numeric: tabular-nums;
122
+ opacity: 0.85;
123
+ }
124
+ .buyblock__desc {
125
+ margin: 0.25rem 0 0;
126
+ font-size: 0.9em;
127
+ opacity: 0.8;
128
+ }
129
+ .buyblock__qty {
130
+ display: flex;
131
+ align-items: center;
132
+ gap: 0.5rem;
133
+ font-size: 0.9em;
134
+ }
135
+ .buyblock__qty input {
136
+ width: 4.5rem;
137
+ padding: 0.3rem 0.4rem;
138
+ font: inherit;
139
+ }
140
+ .buyblock paypal-button {
141
+ display: block;
142
+ width: 100%;
143
+ }
144
+ .buyblock__status {
145
+ margin: 0;
146
+ font-size: 0.95em;
147
+ }
148
+ .buyblock__status[data-kind="error"] {
149
+ color: #b42318;
150
+ }
151
+ /* Built by the client script after payment, so not scoped by Astro. */
152
+ .buyblock :global(.buyblock__download) {
153
+ display: grid;
154
+ gap: 0.5rem;
155
+ }
156
+ .buyblock :global(.buyblock__dl-btn) {
157
+ display: flex;
158
+ align-items: center;
159
+ justify-content: center;
160
+ min-height: 46px;
161
+ padding: 0 1rem;
162
+ background: #14161b;
163
+ color: #fff;
164
+ border-radius: 8px;
165
+ font-weight: 600;
166
+ text-decoration: none;
167
+ overflow-wrap: anywhere;
168
+ text-align: center;
169
+ }
170
+ .buyblock :global(.buyblock__dl-meta) {
171
+ text-align: center;
172
+ font-size: 0.85em;
173
+ opacity: 0.8;
174
+ }
175
+ .buyblock :global(.buyblock__dl-note) {
176
+ margin: 0;
177
+ font-size: 0.9em;
178
+ opacity: 0.85;
179
+ }
180
+ .buyblock :global(.buyblock__download .buyblock__status[data-kind="error"]) {
181
+ color: #b42318;
182
+ margin: 0;
183
+ }
184
+ .buyblock__status[data-kind="success"] {
185
+ color: #067647;
186
+ font-weight: 600;
187
+ }
188
+ </style>
189
+
190
+ <script>
191
+ import { initBuyButtons } from "@zachristudio/buyblock/client";
192
+ initBuyButtons();
193
+ </script>
@@ -0,0 +1,56 @@
1
+ ---
2
+ /**
3
+ * "Order lookup" Portable Text block: buyers find their downloads with their PayPal transaction ID.
4
+ * Posts to /buyblock/order (added by the buyblock() integration), which opens the order page.
5
+ * Inherits the theme's font and colours.
6
+ */
7
+ interface Props {
8
+ node: { showTitle?: boolean };
9
+ }
10
+ const { node } = Astro.props;
11
+ const showTitle = node?.showTitle !== false;
12
+ const id = Math.random().toString(36).slice(2, 8);
13
+ ---
14
+
15
+ <form class="buyblock-lookup" method="post" action="/buyblock/order">
16
+ {showTitle && <strong class="buyblock-lookup__title">Find your order</strong>}
17
+ <p class="buyblock-lookup__hint">Download your files again. The transaction ID is in your PayPal receipt.</p>
18
+ <label for={`bb-tx-${id}`}>PayPal transaction ID</label>
19
+ <input id={`bb-tx-${id}`} name="tx" autocomplete="off" required maxlength="64" />
20
+ <label for={`bb-em-${id}`}>Email you paid with</label>
21
+ <input id={`bb-em-${id}`} name="email" type="email" autocomplete="email" required maxlength="254" />
22
+ <button type="submit">Find my order</button>
23
+ </form>
24
+
25
+ <style>
26
+ .buyblock-lookup {
27
+ max-width: 420px;
28
+ margin: 1.5rem 0;
29
+ display: grid;
30
+ gap: 0.5rem;
31
+ }
32
+ .buyblock-lookup__title {
33
+ font-size: 1.15em;
34
+ }
35
+ .buyblock-lookup__hint {
36
+ margin: 0 0 0.5rem;
37
+ font-size: 0.92em;
38
+ opacity: 0.8;
39
+ }
40
+ .buyblock-lookup label {
41
+ font-weight: 600;
42
+ font-size: 0.95em;
43
+ }
44
+ .buyblock-lookup input {
45
+ min-height: 44px;
46
+ padding: 0 0.75rem;
47
+ font: inherit;
48
+ margin-bottom: 0.5rem;
49
+ }
50
+ .buyblock-lookup button {
51
+ min-height: 44px;
52
+ font: inherit;
53
+ font-weight: 600;
54
+ cursor: pointer;
55
+ }
56
+ </style>
@@ -0,0 +1,2 @@
1
+ /*! Buyblock: Sell Products & Digital Downloads v0.3.0 · (c) zachristudio.com · See LICENSE */
2
+ import o from"./OrderLookup.astro";import r from"./BuyButton.astro";const b={"buyblock-button":r,"buyblock-order-lookup":o};export{b as blockComponents};
package/dist/client.js ADDED
@@ -0,0 +1,2 @@
1
+ /*! Buyblock: Sell Products & Digital Downloads v0.3.0 · (c) zachristudio.com · See LICENSE */
2
+ var b="/_emdash/api/plugins/buyblock",k={sandbox:"https://www.sandbox.paypal.com/web-sdk/v6/core",live:"https://www.paypal.com/web-sdk/v6/core"},f=new Map,g=new Map,P=new Map;function E(e){let a=k[e],n=f.get(a);return n||(n=new Promise((t,l)=>{if(window.paypal?.createInstance)return t(window.paypal);let o=document.createElement("script");o.src=a,o.async=!0,o.onload=()=>window.paypal?t(window.paypal):l(new Error("PayPal SDK did not initialise")),o.onerror=()=>l(new Error("Could not load the PayPal SDK")),document.head.appendChild(o)}),f.set(a,n)),n}function M(e,a){let n=`${e}:${a}`,t=P.get(n);return t||(t=E(e).then(l=>l.createInstance({clientId:a,components:["paypal-payments"],pageType:"product-details"})),P.set(n,t)),t}async function w(e,a){let n=await fetch(`${b}/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),t=await n.json().catch(()=>null);if(!n.ok||!t?.data)throw new Error(t?.error?.message||"Something went wrong. Please try again.");return t.data}function s(e,a,n){let t=e.querySelector("[data-paypal-status]");t&&(t.hidden=!1,t.dataset.kind=a,t.textContent=n)}function T(e){return e<1024*1024?`${Math.max(1,Math.round(e/1024))} KB`:e<1024*1024*1024?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}function u(e,a,n){let t=document.createElement(e);return t.className=a,n&&(t.textContent=n),t}function v(e,a){e.querySelector("[data-paypal-download]")?.remove();let n=u("div","buyblock__download");if(n.dataset.paypalDownload="",a.fileUrl&&a.name){let o=u("a","buyblock__dl-btn",`Download ${a.name}`);o.href=a.fileUrl,o.addEventListener("click",()=>{s(e,"success","Your download has started."),o.textContent="Download again"}),n.append(o);let c=[a.size?T(a.size):"",a.limitText??""].filter(Boolean).join(" \xB7 ");c&&n.append(u("span","buyblock__dl-meta",c))}else if(a.testOrder)n.append(u("p","buyblock__status","This was a test purchase. Test purchases don\u2019t include downloads now that the shop is live."));else if(a.unavailable){let o=u("p","buyblock__status","The file can\u2019t be downloaded right now. It will be on your order page once the shop fixes this.");o.dataset.kind="error",o.setAttribute("role","alert"),n.append(o)}let t=u("p","buyblock__dl-note"),l=u("a","","your order page");l.href=a.orderUrl,t.append(document.createTextNode("Save "),l,document.createTextNode(a.pending?" and check back later.":" to download it again later.")),n.append(t),e.append(n)}async function S(e){if(e.dataset.paypalReady||(e.dataset.paypalReady="1",(e.dataset.gateway??"paypal")!=="paypal"))return;let{productId:a="",clientId:n="",currency:t="USD",success:l="Thank you!"}=e.dataset,o=e.dataset.mode==="live"?"live":"sandbox",c=e.querySelector("[data-paypal-btn]"),y=e.querySelector("[data-paypal-qty]");if(!c||!a||!n)return;let m;try{if(m=await M(o,n),!(await m.findEligibleMethods({currencyCode:t})).isEligible("paypal")){s(e,"info","PayPal isn't available for this purchase.");return}}catch(i){console.error("[buyblock]",i),s(e,"error","PayPal couldn't be loaded. Please refresh the page and try again.");return}let p=!1,h=m.createPayPalOneTimePaymentSession({async onApprove({orderId:i}){s(e,"info","Confirming your payment\u2026");try{let r=await w("capture-order",{orderId:i,claim:g.get(i)});r.status==="COMPLETED"?(c.hidden=!0,y&&(y.disabled=!0),s(e,"success",l)):r.download?(c.hidden=!0,s(e,"info","Your payment is pending at PayPal. Your download unlocks on your order page once PayPal completes it.")):s(e,"info","Your payment is pending at PayPal. You'll get an email from PayPal once it completes."),r.download&&v(e,r.download),e.dispatchEvent(new CustomEvent("buyblock:paid",{bubbles:!0,detail:{orderId:i,productId:a,status:r.status}}))}catch(r){s(e,"error",r instanceof Error?r.message:"The payment could not be completed.")}finally{p=!1}},onCancel(){p=!1,s(e,"info","Payment cancelled.")},onError(i){p=!1,console.error("[buyblock]",i),s(e,"error","Something went wrong with PayPal. Please try again.")}});c.hidden=!1,c.addEventListener("click",async()=>{if(p)return;p=!0;let i=y?Math.max(1,Math.min(99,Math.trunc(Number(y.value)||1))):1,r=w("create-order",{productId:a,quantity:i});r.then(d=>d.claim&&g.set(d.orderId,d.claim)).catch(()=>{}),r.catch(d=>{p=!1,s(e,"error",d instanceof Error?d.message:"Could not start the payment.")});try{await h.start({presentationMode:"auto"},r)}catch(d){console.error("[buyblock]",d),s(e,"error","PayPal couldn't open. Allow pop-ups for this site and try again.")}finally{p=!1}})}function L(){let e=()=>document.querySelectorAll("[data-buyblock]").forEach(a=>{S(a)});document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e(),document.addEventListener("astro:page-load",e)}export{L as initBuyButtons};
@@ -0,0 +1,8 @@
1
+ import type { PluginDescriptor, ResolvedPlugin } from "emdash";
2
+ export declare const PLUGIN_ID = "buyblock";
3
+ /** Descriptor for astro.config.mjs: emdash({ plugins: [buyblockPlugin()] }) */
4
+ export declare function buyblockPlugin(): PluginDescriptor;
5
+ export declare function createPlugin(): ResolvedPlugin;
6
+ /** Astro integration for Buyblock Downloads: the buyer's order page and download links. List it after emdash(). */
7
+ export declare function buyblock(): { name: string; hooks: Record<string, (options: any) => void> };
8
+ export default createPlugin;
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ /*! Buyblock: Sell Products & Digital Downloads v0.3.0 · (c) zachristudio.com · See LICENSE */
2
+ import{definePlugin as Pn}from"emdash";import{PluginRouteError as m}from"emdash";import{PluginRouteError as w}from"emdash";import{PluginRouteError as Bt}from"emdash";var Gt=600*1e3,ae="rl:";async function Kt(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(t).slice(0,8)].map(n=>n.toString(16).padStart(2,"0")).join("")}async function jt(e,t,n,r){for(let o=0;o<4;o++){let a=await e.kv.getVersioned(t),i=a?.value&&a.value.window===r?a.value:{window:r,count:0};if(i.count>=n)return!1;if((await e.kv.compareAndSet(t,a?.revision??null,{window:r,count:i.count+1})).applied)return!0}return!1}async function qt(e,t){if(!(Math.random()>.02))for(let{key:n,value:r}of await e.kv.list(ae))r?.window!==t&&await e.kv.delete(n)}async function U(e,t,n,r){let o=Math.floor(Date.now()/Gt),a=e.requestMeta?.ip,i=a?await Kt(a):null,s=r.map(l=>[`${ae}${t}:site:${l.key}`,l.max]);if(i)for(let l of n)s.push([`${ae}${t}:${i}:${l.key}`,l.max]);for(let[l,c]of s)if(!await jt(e,l,c,o))throw new Bt("RATE_LIMITED","Too many checkout attempts. Please wait a few minutes and try again.",429);await qt(e,o).catch(()=>{})}var q={label:"buynow",color:"gold",shape:"rect"};var Y=["USD","EUR","GBP","AUD","CAD","CHF","CZK","DKK","HKD","HUF","ILS","JPY","MXN","NOK","NZD","PHP","PLN","SEK","SGD","THB","TWD","BRL","MYR","CNY"],Re=new Set(["HUF","JPY","TWD"]),ie="Thank you! Your payment was received.",ve={paypalSandboxSecret:{type:"secret",label:"PayPal Sandbox secret",description:"Managed in Buyblock \u2192 Settings."},paypalLiveSecret:{type:"secret",label:"PayPal Live secret",description:"Managed in Buyblock \u2192 Settings."}},T=e=>{let t=e==="live"?"Live":"Sandbox";return{clientId:`paypal${t}ClientId`,secret:`paypal${t}Secret`}};async function A(e,t){try{return await e.settings.get(t)}catch{return null}}var R=e=>typeof e=="string"?e.trim():"";async function f(e){let t=T("sandbox"),n=T("live"),[r,o,a,i,s,l,c,u]=await Promise.all([A(e,"mode"),A(e,t.clientId),A(e,t.secret),A(e,n.clientId),A(e,n.secret),A(e,"currency"),A(e,"brandName"),A(e,"successMessage")]),d=r==="live"?"live":"sandbox",p={clientId:R(o),clientSecret:R(a)},k={clientId:R(i),clientSecret:R(s)},j=d==="live"?k:p;return{mode:d,clientId:j.clientId,clientSecret:j.clientSecret,sandbox:p,live:k,currency:Y.includes(R(l))?R(l):"EUR",brandName:R(c).slice(0,127),successMessage:R(u)||ie}}function H(e){let t=e&&typeof e=="object"?e:{};return{label:t.label==="checkout"||t.label==="pay"?t.label:q.label,color:t.color==="blue"||t.color==="white"?t.color:q.color,shape:t.shape==="pill"||t.shape==="sharp"?t.shape:q.shape}}var Yt=/^\d{1,7}(\.\d{1,2})?$/;function Te(e,t){let n=e.trim().replace(",",".");if(!Yt.test(n))return null;let r=$(n,t);return r===null||r<=0?null:_(r,t)}function $(e,t){let[n="0",r=""]=e.split(".");return Re.has(t)?r&&Number(r)!==0?null:Number(n):Number(n)*100+Number(r.padEnd(2,"0"))}function _(e,t){if(Re.has(t))return String(e);let n=Math.floor(e/100),r=String(e%100).padStart(2,"0");return`${n}.${r}`}var Oe="DOWNLOADS";var V=/^f_[a-f0-9]{32}$/,Vt=/^[A-Za-z0-9_.~+/=-]{8,512}$/;function S(e=16){return Array.from(crypto.getRandomValues(new Uint8Array(e)),t=>t.toString(16).padStart(2,"0")).join("")}var F=e=>import(e),De;function se(){return De??=(async()=>{try{return(await F("cloudflare:workers"))?.env??null}catch{return null}})(),De}async function _e(){let t=(await se())?.[Oe];return t&&typeof t.createMultipartUpload=="function"?t:null}async function ce(){return{onCloudflare:await se()!==null,hasBinding:await _e()!==null,folderPath:"./.buyblock/downloads"}}async function W(e){let t=await ce();return t.onCloudflare?"r2":e==="r2"||e==="folder"?e:t.hasBinding?"r2":"folder"}var N=class extends Error{};async function C(e){if(e==="r2"){let t=await _e();if(!t)throw new N(`No R2 bucket is bound as ${Oe}.`);return Qt(t)}if(await se()!==null)throw new N("This site runs on Cloudflare, which has no server folder. Use an R2 bucket.");return Wt()}async function Wt(){let e=await F("node:fs/promises"),t=await F("node:path"),{createReadStream:n}=await F("node:fs"),{Readable:r}=await F("node:stream"),o=t.join(process.cwd(),".buyblock"),a=t.join(o,"downloads"),i=t.join(o,"uploads"),s=c=>{if(!V.test(c))throw new Error("Invalid file key");return t.join(a,c)},l=c=>{if(!/^[a-f0-9]{32}$/.test(c))throw new Error("Invalid upload");return t.join(i,c)};return{kind:"folder",async begin(c){s(c);let u=S();return await e.mkdir(l(u),{recursive:!0}),u},async part(c,u,d,p){return s(c),await e.writeFile(t.join(l(u),String(d)),p),String(p.byteLength)},async complete(c,u,d){let p=s(c);await e.mkdir(a,{recursive:!0});let k=`${p}.tmp`;await e.writeFile(k,new Uint8Array);for(let j of[...d].sort((Ft,zt)=>Ft.n-zt.n))await e.appendFile(k,await e.readFile(t.join(l(u),String(j.n))));return await e.rename(k,p),await e.rm(l(u),{recursive:!0,force:!0}),(await e.stat(p)).size},async abort(c,u){await e.rm(l(u),{recursive:!0,force:!0})},async size(c){try{return(await e.stat(s(c))).size}catch{return null}},async open(c,u){let d;try{d=(await e.stat(s(c))).size}catch{return null}let p=n(s(c),u?{start:u.start,end:u.end}:void 0);return{body:r.toWeb(p),size:d}},async remove(c){await e.rm(s(c),{force:!0})},async check(){await e.mkdir(a,{recursive:!0});let c=t.join(a,`.check-${S(4)}`);await e.writeFile(c,"ok");let u=await e.readFile(c,"utf8");if(await e.rm(c,{force:!0}),u!=="ok")throw new Error("Read back a different value.")}}}function Qt(e){let t=r=>{if(!V.test(r))throw new Error("Invalid file key")},n=r=>{if(!Vt.test(r))throw new Error("Invalid upload")};return{kind:"r2",async begin(r){return t(r),(await e.createMultipartUpload(r)).uploadId},async part(r,o,a,i){return t(r),n(o),(await e.resumeMultipartUpload(r,o).uploadPart(a,i)).etag},async complete(r,o,a){return t(r),n(o),(await e.resumeMultipartUpload(r,o).complete([...a].sort((s,l)=>s.n-l.n).map(s=>({partNumber:s.n,etag:s.etag})))).size},async abort(r,o){t(r),n(o),await e.resumeMultipartUpload(r,o).abort()},async size(r){return t(r),(await e.head(r))?.size??null},async open(r,o){t(r);let a=await e.get(r,o?{range:{offset:o.start,length:o.end-o.start+1}}:void 0);return a?{body:a.body,size:a.size}:null},async remove(r){t(r),await e.delete(r)},async check(){let r=`.check-${S(4)}`;await e.put(r,"ok");let o=await(await e.get(r))?.text();if(await e.delete(r),o!=="ok")throw new Error("Read back a different value.")}}}var xe="/buyblock",Zt=3600*1e3,le="dl:secret",Le=/^[A-Za-z0-9_-]{1,64}$/,ue=new TextEncoder,Ne=new Map;async function Xt(e){let t=await e.kv.get(le);if(t)return t;let n=S(32);return(await e.kv.compareAndSet(le,null,n)).applied?n:await e.kv.get(le)??n}function Jt(e){let t="";for(let n of new Uint8Array(e))t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function de(e,t,n){let r=await Xt(e),o=Ne.get(r);return o||(o=crypto.subtle.importKey("raw",ue.encode(r),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),Ne.set(r,o)),Jt(await crypto.subtle.sign("HMAC",await o,ue.encode(t))).slice(0,n)}async function pe(e){let t=await crypto.subtle.digest("SHA-256",ue.encode(e));return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}function Q(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function Me(e,t){return de(e,`order:${t}`,22)}async function Ue(e,t,n){return!Le.test(t)||typeof n!="string"?!1:Q(await Me(e,t),n)}async function x(e,t){return`${xe}/order?o=${encodeURIComponent(t)}&k=${await Me(e,t)}`}async function He(e,t,n=Date.now()){let r=Math.floor((n+Zt)/1e3),o=await de(e,`file:${t}:${r}`,32);return`${xe}/download/${t}.${r}.${o}`}async function $e(e,t,n=Date.now()){let r=typeof t=="string"?t.split("."):[];if(r.length!==3)return{ok:!1,reason:"INVALID"};let[o,a,i]=r,s=Number(a);return!Le.test(o)||!/^\d{1,12}$/.test(a)||!Q(await de(e,`file:${o}:${s}`,32),i)?{ok:!1,reason:"INVALID"}:s*1e3<n?{ok:!1,reason:"EXPIRED",orderId:o}:{ok:!0,orderId:o}}var B=e=>e.storage.products,z=e=>e.storage.orders,Z=864e5,ge=Z,Fe={perVisitor:10,siteWide:300};function E(e){let t=e.input;return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Uint8Array)?t:{}}var I=(e,t=500)=>typeof e=="string"?e.trim().slice(0,t):"";async function fe(e,t){try{return await e.settings.get(t)}catch{return null}}async function G(e){let[t,n,r]=await Promise.all([fe(e,"dlStorage"),fe(e,"dlLimit"),fe(e,"dlDays")]),o=a=>typeof a=="number"&&Number.isInteger(a)&&a>0?Math.min(a,1e5):0;return{storage:t==="r2"||t==="folder"?t:"",limit:o(n),days:o(r)}}function ye(e){throw e instanceof N?new w("STORAGE_UNAVAILABLE",e.message,409):e}var me=e=>`dl:n:${e}`;async function ze(e,t){return await e.kv.get(me(t))??{count:0}}async function tn(e,t,n){for(let r=0;r<5;r++){let o=await e.kv.getVersioned(me(t)),a=o?.value.count??0;if(n&&a>=n)return!1;if((await e.kv.compareAndSet(me(t),o?.revision??null,{count:a+1,last:new Date().toISOString()})).applied)return!0}return!0}function nn(e,t){let n=[];if(e.limit&&n.push(`${e.limit} ${e.limit===1?"download":"downloads"}`),e.days&&t){let r=new Date(Date.parse(t)+e.days*Z);n.push(`until ${r.toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric",timeZone:"UTC"})}`)}return n.length?n.join(", "):void 0}async function Be(e,t){return t.mode==="sandbox"&&(await f(e)).mode==="live"}async function Ge(e){try{return await(await C(e.store)).size(e.key)!==null}catch{return!1}}async function we(e,t){if(t.status!=="COMPLETED"&&t.status!=="PENDING")return null;let n=await B(e).get(t.productId);if(!n?.file)return null;let r=await x(e,t.gatewayOrderId);if(t.status==="PENDING")return{orderUrl:r,pending:!0};if(await Be(e,t))return{orderUrl:r,testOrder:!0};let o=await G(e);return await Ge(n.file)?{orderUrl:r,fileUrl:await He(e,t.gatewayOrderId),name:n.file.name,size:n.file.size,limitText:nn(o,t.capturedAt)}:{orderUrl:r,unavailable:!0}}async function Ke(e){let t=E(e),n=await $e(e,I(t.token,200));if(!n.ok)return{ok:!1,reason:n.reason,orderUrl:n.orderId?await x(e,n.orderId):void 0};let r=await z(e).get(n.orderId);if(!r)return{ok:!1,reason:"INVALID"};let o=await x(e,r.gatewayOrderId),a=r.transactionId??r.gatewayOrderId;if(r.status!=="COMPLETED")return{ok:!1,reason:"NOT_PAID",orderUrl:o};if(await Be(e,r))return{ok:!1,reason:"TEST",orderUrl:o,tx:a};let i=await B(e).get(r.productId);if(!i?.file)return{ok:!1,reason:"MISSING",orderUrl:o,tx:a};let s=await G(e);if(s.days&&r.capturedAt&&Date.parse(r.capturedAt)+s.days*Z<Date.now()){let c=new Date(Date.parse(r.capturedAt)+s.days*Z).toISOString();return{ok:!1,reason:"ENDED",orderUrl:o,tx:a,until:c}}if(!await Ge(i.file))return{ok:!1,reason:"MISSING",orderUrl:o,tx:a};if(t.count===!0){if(!await tn(e,r.gatewayOrderId,s.limit))return{ok:!1,reason:"LIMIT",orderUrl:o,tx:a,limit:s.limit}}else if(s.limit&&(await ze(e,r.gatewayOrderId)).count>s.limit)return{ok:!1,reason:"LIMIT",orderUrl:o,tx:a,limit:s.limit};let l=i.file;return{ok:!0,key:l.key,store:l.store,name:l.name,size:l.size,type:l.type}}var rn=/^[A-Za-z0-9_-]{6,64}$/;async function je(e){let t=E(e);await U(e,"lookup",[{key:"all",max:Fe.perVisitor}],[{key:"all",max:Fe.siteWide}]);let n=I(t.tx,64).toUpperCase(),r=I(t.email,254).toLowerCase();if(!rn.test(n)||!r.includes("@"))return{found:!1};let o=[],a=await z(e).query({where:{transactionId:n},limit:5});o.push(...a.items.map(l=>l.data));let i=await z(e).get(n);i&&o.push(i);let s=o.find(l=>(l.status==="COMPLETED"||l.status==="PENDING")&&(l.payerEmail??"").toLowerCase()===r);return s?{found:!0,url:await x(e,s.gatewayOrderId)}:{found:!1}}async function qe(e){let t=E(e),n=I(t.o,64);if(!await Ue(e,n,I(t.k,64)))return{found:!1};let r=await z(e).get(n);if(!r||r.status!=="COMPLETED"&&r.status!=="PENDING")return{found:!1};let o=await f(e),a=await we(e,r),i=await B(e).get(r.productId);return{found:!0,shop:o.brandName,productName:r.productName,quantity:r.quantity,amount:r.amount,currency:r.currency,status:r.status,date:r.capturedAt??r.createdAt,tx:r.transactionId??r.gatewayOrderId,file:i?.file?{name:i.file.name,size:i.file.size}:null,delivery:a}}var M=e=>`dl:up:${e}`,he=e=>`dl:file:${e}`;function on(e){return(e.split(/[\\/]/).pop()??"").replace(/[\u0000-\u001f\u007f"<>|*?:]/g,"").trim().slice(0,180)||"download"}function an(e){return/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/i.test(e)?e.toLowerCase():"application/octet-stream"}async function sn(e){let t=Date.now();for(let{key:n,value:r}of await e.kv.list("dl:up:")){let o=r;o&&t-o.createdAt<=ge||(o&&await C(o.store).then(a=>a.abort(o.key,o.uploadId)).catch(()=>{}),await e.kv.delete(n))}for(let{key:n,value:r}of await e.kv.list("dl:file:")){let o=r;o&&t-o.at<=ge||(o&&await X(e,o),await e.kv.delete(n))}}async function Ye(e){let t=E(e);await sn(e).catch(l=>e.log.warn("Couldn't clean up old uploads",{error:String(l)}));let n=Number(t.size);if(!Number.isInteger(n)||n<=0)throw w.badRequest("This file is empty.");if(n>2147483648)throw w.badRequest("Files can be up to 2 GB.");let r=await G(e),o=await W(r.storage),a,i=`f_${S()}`;try{a=await(await C(o)).begin(i)}catch(l){ye(l)}let s=S();return await e.kv.set(M(s),{key:i,uploadId:a,store:o,name:on(I(t.name,400)),size:n,type:an(I(t.type,120)),parts:[],createdAt:Date.now()}),{id:s,partSize:6291456,parts:Math.ceil(n/6291456)}}async function Ve(e,t){if(!/^[a-f0-9]{32}$/.test(t))throw w.badRequest("Unknown upload.");let n=await e.kv.get(M(t));if(!n||Date.now()-n.createdAt>ge)throw w.notFound("This upload expired. Choose the file again.");return n}async function We(e){let t=new URL(e.request.url),n=await Ve(e,t.searchParams.get("id")??""),r=Number(t.searchParams.get("n")),o=Math.ceil(n.size/6291456);if(!Number.isInteger(r)||r<1||r>o)throw w.badRequest("Invalid part.");let a=e.input instanceof Uint8Array?e.input:null,i=r<o?6291456:n.size-6291456*(o-1);if(!a||a.byteLength!==i)throw w.badRequest("The upload was interrupted. Try again.");let s;try{s=await(await C(n.store)).part(n.key,n.uploadId,r,a)}catch(c){ye(c)}let l=n.parts.filter(c=>c.n!==r).concat({n:r,etag:s});return await e.kv.set(M(t.searchParams.get("id")),{...n,parts:l}),{ok:!0,received:l.length,of:o}}async function Qe(e){let t=I(E(e).id,64),n=await Ve(e,t),r=Math.ceil(n.size/6291456);if(n.parts.length!==r)throw w.badRequest("Some parts are missing. Try the upload again.");let o;try{o=await(await C(n.store)).complete(n.key,n.uploadId,n.parts)}catch(i){ye(i)}if(o!==n.size)throw new w("UPLOAD_SIZE","The uploaded file has a different size. Try again.",500);let a={key:n.key,name:n.name,size:o,type:n.type,store:n.store,uploadedAt:new Date().toISOString()};return await e.kv.set(he(n.key),{...a,at:Date.now()}),await e.kv.delete(M(t)),{file:{key:a.key,name:a.name,size:a.size}}}async function Ze(e){let t=I(E(e).id,64),n=await e.kv.get(M(t));return n&&(await(await C(n.store)).abort(n.key,n.uploadId).catch(()=>{}),await e.kv.delete(M(t))),{ok:!0}}async function Xe(e,t,n){if(t===void 0)return n;if(t===null)return;let r=t&&typeof t=="object"?t.key:void 0;if(typeof r!="string"||!V.test(r))throw w.badRequest("Invalid file.");if(n?.key===r)return n;let o=await e.kv.get(he(r));if(!o)throw w.badRequest("That upload expired. Upload the file again.");let{at:a,...i}=o;return i}async function Je(e,t,n){n&&await e.kv.delete(he(n.key)),t&&t.key!==n?.key&&await X(e,t)}async function X(e,t){try{await(await C(t.store)).remove(t.key)}catch(n){e.log.warn("Couldn't delete a download file",{key:t.key,error:String(n)})}}async function et(e){let t=await G(e),n=await ce(),r=await W(t.storage),{items:o}=await B(e).query({orderBy:{createdAt:"desc"},limit:100}),a=o.map(i=>i.data.file).filter(i=>!!i&&i.store===r);return{storage:r,onCloudflare:n.onCloudflare,hasBinding:n.hasBinding,folderPath:n.folderPath,files:a.length,bytes:a.reduce((i,s)=>i+s.size,0),limit:t.limit,days:t.days}}async function tt(e){let t=E(e),n=(r,o)=>{let a=Number(r);return Number.isInteger(a)&&a>0?Math.min(a,o):0};return(t.storage==="folder"||t.storage==="r2")&&await e.settings.set("dlStorage",t.storage),"limit"in t&&await e.settings.set("dlLimit",n(t.limit,1e3)),"days"in t&&await e.settings.set("dlDays",n(t.days,3650)),{ok:!0}}async function nt(e){let t=E(e),n=await G(e),r=t.storage==="folder"||t.storage==="r2"?t.storage:await W(n.storage);try{return await(await C(r)).check(),{ok:!0,storage:r}}catch(o){return{ok:!1,storage:r,message:o instanceof Error?o.message:"The check failed."}}}async function rt(e){let t=I(E(e).id,64),n=await z(e).get(t);if(!n)throw w.notFound("Order not found.");let r=await B(e).get(n.productId);if(!r?.file)return{digital:!1};let{count:o,last:a}=await ze(e,t);return{digital:!0,fileName:r.file.name,count:o,last:a??null,orderUrl:n.status==="COMPLETED"||n.status==="PENDING"?await x(e,t):null}}var J={sandbox:"https://api-m.sandbox.paypal.com",live:"https://api-m.paypal.com"},g=class extends Error{constructor(n,r,o,a){super(n);this.status=r;this.issue=o;this.debugId=a;this.name="PayPalError"}status;issue;debugId};function ee(e){if(!e.http)throw new g("Network access is not available to the plugin",500);return e.http}function cn(e){return`${e.mode}:${e.clientId}:${e.clientSecret.length}:${e.clientSecret.slice(-4)}`}function D(e){return e.clientId.length>0&&e.clientSecret.length>0}async function at(e,t,n,r){let o=await ee(e).fetch(`${J[t]}/v1/oauth2/token`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${n}:${r}`)}`,"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:"grant_type=client_credentials"});if(o.ok)return;let a=t==="live"?"sandbox":"live";throw(await ee(e).fetch(`${J[a]}/v1/oauth2/token`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${n}:${r}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:"grant_type=client_credentials"})).ok?new g(t==="sandbox"?"These are Live keys. Use your Sandbox app\u2019s keys here.":"These are Sandbox keys. Use your Live app\u2019s keys here.",400,"WRONG_ENVIRONMENT"):new g("PayPal didn\u2019t accept these keys. Check the Client ID and Secret.",o.status,"AUTH_FAILED")}async function ot(e,t,n=!1){if(!D(t))throw new g("PayPal Client ID and Secret are not set",400,"MISSING_CREDENTIALS");let r=`paypal:token:${t.mode}`,o=cn(t);if(!n){let s=await e.kv.get(r);if(s&&s.key===o&&s.expiresAt>Date.now()+6e4)return s.token}let a=await ee(e).fetch(`${J[t.mode]}/v1/oauth2/token`,{method:"POST",headers:{Authorization:`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`,"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:"grant_type=client_credentials"}),i=await a.json().catch(()=>({}));if(!a.ok||!i.access_token){let s=i.error_description||i.error||`HTTP ${a.status}`;throw new g(`PayPal rejected the credentials (${s}). Check the Client ID, Secret and Environment.`,a.status,"AUTH_FAILED")}return await e.kv.set(r,{token:i.access_token,expiresAt:Date.now()+(i.expires_in??3e3)*1e3,key:o}),i.access_token}async function Pe(e,t,n,r,o,a){let i=async c=>ee(e).fetch(`${J[t.mode]}${r}`,{method:n,headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json",Prefer:"return=representation",...a?{"PayPal-Request-Id":a}:{}},body:o===void 0?void 0:JSON.stringify(o)}),s=await i(await ot(e,t));s.status===401&&(s=await i(await ot(e,t,!0)));let l=await s.json().catch(()=>({}));if(!s.ok){let c=Array.isArray(l.details)?l.details[0]:void 0,u=c?.issue??l.name,d=c?.description??l.message??`HTTP ${s.status}`;throw new g(d,s.status,u,l.debug_id)}return l}async function it(e,t,n){let r=o=>({currency_code:n.currency,value:o});return Pe(e,t,"POST","/v2/checkout/orders",{intent:"CAPTURE",purchase_units:[{reference_id:n.referenceId.slice(0,256),custom_id:n.referenceId.slice(0,127),description:n.name.slice(0,127),amount:{...r(n.total),breakdown:{item_total:r(n.total)}},items:[{name:n.name.slice(0,127),...n.description?{description:n.description.slice(0,127)}:{},...n.sku?{sku:n.sku.slice(0,127)}:{},quantity:String(n.quantity),unit_amount:r(n.unitPrice),category:n.collectShipping?"PHYSICAL_GOODS":"DIGITAL_GOODS"}]}],payment_source:{paypal:{experience_context:{user_action:"PAY_NOW",shipping_preference:n.collectShipping?"GET_FROM_FILE":"NO_SHIPPING",...n.brandName?{brand_name:n.brandName}:{}}}}})}async function st(e,t,n){return Pe(e,t,"POST",`/v2/checkout/orders/${encodeURIComponent(n)}/capture`,{},`capture-${n}`)}async function te(e,t,n){return Pe(e,t,"GET",`/v2/checkout/orders/${encodeURIComponent(n)}`)}import{PluginRouteError as h}from"emdash";var be="paypal";var b=e=>e.storage.products,P=e=>e.storage.orders,ct=99,ke={perVisitor:{all:20,perProduct:10},siteWide:600},lt={perVisitor:30,siteWide:1200},ln=6e4,un=/^[A-Za-z0-9_-]{1,64}$/;function Se(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ie(e,t){if(typeof e!="string"||!un.test(e))throw h.badRequest(`Invalid ${t}`);return e}function ne(e,t,n){throw t instanceof g?(e.log.warn(`PayPal ${n} failed`,{status:t.status,issue:t.issue,debugId:t.debugId}),t.issue==="MISSING_CREDENTIALS"||t.issue==="AUTH_FAILED"?new h("NOT_CONFIGURED","PayPal payments are not set up on this site yet.",503):t.issue==="INSTRUMENT_DECLINED"?new h("INSTRUMENT_DECLINED","PayPal declined the payment method. Please try another one.",402):new h("PAYPAL_ERROR",`PayPal could not ${n} the order. Please try again.`,502)):t}async function ut(e){let t=Ie(Se(e.input).productId,"product"),n=await b(e).get(t);if(!n||!n.active||n.archived)return{unavailable:"This product is not available."};let r=await f(e);return D(r)?{gateway:be,product:{id:t,name:n.name,description:n.description,price:n.price,allowQuantity:n.allowQuantity},clientId:r.clientId,mode:r.mode,currency:r.currency,style:H(n.style),successMessage:r.successMessage}:{unavailable:"PayPal payments are not set up on this site yet."}}async function dt(e){let t=Se(e.input),n=Ie(t.productId,"product"),r=Number(t.quantity??1),o=await b(e).get(n);if(!o||!o.active||o.archived)throw h.notFound("This product is not available.");let a=o.allowQuantity?Math.trunc(r):1;if(!Number.isFinite(a)||a<1||a>ct)throw h.badRequest(`Quantity must be between 1 and ${ct}.`);await U(e,"create",[{key:"all",max:ke.perVisitor.all},{key:`p:${n}`,max:ke.perVisitor.perProduct}],[{key:"all",max:ke.siteWide}]);let i=await f(e),s=$(o.price,i.currency);if(s===null||s<=0)throw new h("PRICE_INVALID","This product's price is not valid for the store currency.",500);let l=_(s*a,i.currency),c=_(s,i.currency),u;try{u=await it(e,i,{referenceId:n,name:o.name,description:o.description,sku:o.sku??"",quantity:a,unitPrice:c,total:l,currency:i.currency,collectShipping:o.collectShipping,brandName:i.brandName})}catch(p){ne(e,p,"create")}let d=S(16);return await P(e).put(u.id,{claimHash:await pe(d),gateway:be,gatewayOrderId:u.id,productId:n,productName:o.name,quantity:a,amount:l,currency:i.currency,mode:i.mode,status:"CREATED",createdAt:new Date().toISOString()}),{orderId:u.id,claim:d}}function dn(e){if(!e)return;let t=[e.address_line_1,e.address_line_2,[e.postal_code,e.admin_area_2].filter(Boolean).join(" "),e.admin_area_1,e.country_code].filter(n=>n&&n.trim());return t.length?t.join(", "):void 0}async function re(e,t,n){let{status:r}=t;if(r!=="COMPLETED"&&r!=="PENDING")throw new h("PAYMENT_NOT_COMPLETED","The payment was not completed.",402);if(!n||!t.claimHash||!Q(await pe(n),t.claimHash))return{status:r};let o=null;try{o=await we(e,t)}catch(a){e.log.error("Couldn't prepare the download link",{orderId:t.gatewayOrderId,error:String(a)})}return o?{status:r,download:o}:{status:r}}var pn=e=>new Promise(t=>setTimeout(t,e));async function fn(e,t,n){for(let r=0;r<20;r++){await pn(500);let o=await P(e).get(t);if(o&&o.status!=="CREATED")return re(e,o,n)}throw h.conflict("This payment is still being processed. Refresh the page in a moment.")}async function gn(e,t){let n=Date.now();if((await e.kv.compareAndSet(t,null,{at:n})).applied)return!0;let r=await e.kv.getVersioned(t);return r?n-r.value.at<ln?!1:(await e.kv.compareAndSet(t,r.revision,{at:n})).applied:(await e.kv.compareAndSet(t,null,{at:n})).applied}async function pt(e){let t=Se(e.input),n=Ie(t.orderId,"order"),r=typeof t.claim=="string"&&/^[a-f0-9]{32}$/.test(t.claim)?t.claim:"",o=await P(e).get(n);if(!o)throw h.notFound("Unknown order.");if(o.status!=="CREATED")return re(e,o,r);await U(e,"capture",[{key:"all",max:lt.perVisitor}],[{key:"all",max:lt.siteWide}]);let a=await f(e);if(a.mode!==o.mode)throw h.conflict("The store's PayPal environment changed after this order was created.");let i=`capture-lock:${n}`;if(!await gn(e,i))return fn(e,n,r);try{let s=await P(e).get(n);if(!s)throw h.notFound("Unknown order.");return s.status!=="CREATED"?re(e,s,r):await mn(e,a,n,s,r)}finally{await e.kv.delete(i).catch(()=>!1)}}async function mn(e,t,n,r,o){let a;try{a=await st(e,t,n)}catch(p){if(p instanceof g&&p.issue==="ORDER_ALREADY_CAPTURED")try{a=await te(e,t,n)}catch(k){ne(e,k,"capture")}else p instanceof g&&p.issue==="INSTRUMENT_DECLINED"&&ne(e,p,"capture"),await P(e).put(n,{...r,status:"FAILED",error:p instanceof Error?p.message.slice(0,300):"Capture failed"}),ne(e,p,"capture")}let i=a.purchase_units?.[0],s=i?.payments?.captures?.[0],l=[a.payer?.name?.given_name,a.payer?.name?.surname].filter(Boolean).join(" "),c=s?.status==="COMPLETED"?"COMPLETED":s?.status==="PENDING"?"PENDING":s?.status==="DECLINED"?"DECLINED":"FAILED",u=s?.amount;(c==="COMPLETED"||c==="PENDING")&&(!u||u.currency_code!==r.currency||u.value!==r.amount)&&(c="MISMATCH",e.log.error("PayPal captured a different amount than expected",{orderId:n,expected:`${r.amount} ${r.currency}`,charged:u?`${u.value} ${u.currency_code}`:"none"}));let d={...r,status:c,transactionId:s?.id,payerEmail:a.payer?.email_address,payerName:l||void 0,shippingName:i?.shipping?.name?.full_name,shippingAddress:dn(i?.shipping?.address),capturedAt:new Date().toISOString()};return await P(e).put(n,d),re(e,d,o)}async function ft(e){let{items:t}=await b(e).query({orderBy:{createdAt:"desc"},limit:100});return{items:t.filter(({data:n})=>!n.archived).map(({id:n,data:r})=>({id:n,name:`${r.name} \xB7 ${r.price}${r.active?"":" (hidden)"}`}))}}async function oe(e){return!1}var gt="usage:v1";function Ce(e,t){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let r of e)Ce(r,t);return}let n=e;n._type==="buyblock-button"&&typeof n.productId=="string"&&t.add(n.productId);for(let r of Object.values(n))r&&typeof r=="object"&&Ce(r,t)}async function Ee(e,t=!1){if(!t){let o=await e.kv.get(gt);if(o&&Date.now()-o.at<6e4)return o.map}let n={};if(!e.content||!e.schema)return n;let r=[];try{r=await e.schema.listCollections()}catch{return n}for(let o of r){let a;for(let i=0;i<5;i++){let s;try{s=await e.content.list(o.slug,{limit:100,cursor:a,where:{status:"published"}})}catch{break}for(let l of s.items){let c=new Set;if(Ce(l.data,c),!c.size)continue;let u=o.titleField??"title",d=l.data[u]??l.data.title,p={collection:o.slug,id:l.id,title:typeof d=="string"&&d?d:l.slug??l.id,editUrl:`/_emdash/admin/content/${encodeURIComponent(o.slug)}/${encodeURIComponent(l.id)}`};for(let k of c)(n[k]??=[]).push(p)}if(!s.hasMore||!s.cursor)break;a=s.cursor}}return await e.kv.set(gt,{at:Date.now(),map:n}),n}var wt=864e5;function v(e){let t=e.input;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}var y=(e,t=500)=>typeof e=="string"?e.trim().slice(0,t):"",ht=e=>e==="live"?"live":"sandbox";async function K(e,t=500){let n=[],r;for(;n.length<t;){let o=await P(e).query({orderBy:{createdAt:"desc"},limit:100,cursor:r});if(n.push(...o.items.map(a=>a.data)),!o.hasMore||!o.cursor)break;r=o.cursor}return n}async function Pt(e){let{items:t}=await b(e).query({orderBy:{createdAt:"desc"},limit:100});return t}function yt(e){return e?e.slice(-4):""}function yn(e){let t=new Map;for(let n of e)n.status==="COMPLETED"&&t.set(n.currency,(t.get(n.currency)??0)+($(n.amount,n.currency)??0));return t.size?[...t].map(([n,r])=>`${_(r,n)} ${n}`).join(" + "):"0"}async function bt(e){let t=await f(e),[n,r,o]=await Promise.all([Pt(e),K(e),Ee(e)]),a=r.filter(c=>c.mode===t.mode),i=Date.now()-30*wt,s=a.filter(c=>Date.parse(c.createdAt)>=i),l=n.filter(c=>!c.data.archived);return{pro:await oe(e),mode:t.mode,connected:D(t),sandbox:{set:!!(t.sandbox.clientId&&t.sandbox.clientSecret),tail:yt(t.sandbox.clientId)},live:{set:!!(t.live.clientId&&t.live.clientSecret),tail:yt(t.live.clientId)},currency:t.currency,brandName:t.brandName,successMessage:t.successMessage,sandboxOrderCount:r.filter(c=>c.mode==="sandbox").length,hasOrders:r.length>0,setup:{connected:D(t),product:l.length>0,onPage:Object.keys(o).length>0,testPurchase:r.some(c=>c.status==="COMPLETED")},stats:{revenue:yn(s),paid:s.filter(c=>c.status==="COMPLETED").length,unpaid:s.filter(c=>c.status==="CREATED").length}}}function kt(e,t){throw t instanceof g?new m(t.issue??"PAYPAL_ERROR",t.message,400):(e.log.warn("Key check failed",{error:String(t)}),new m("PAYPAL_UNREACHABLE","Couldn\u2019t reach PayPal. Try again.",502))}async function St(e){let t=v(e),n=ht(t.env),r=y(t.clientId,200),o=y(t.clientSecret,200);if(!r||!o)throw m.badRequest("Paste both the Client ID and the Secret.");try{await at(e,n,r,o)}catch(i){kt(e,i)}await e.settings.set(T(n).clientId,r),await e.settings.set(T(n).secret,o);let a=await f(e);return(t.activate===!0||!D(a))&&await e.settings.set("mode",n),await e.kv.delete(`paypal:token:${n}`),{ok:!0}}async function It(e){let t=v(e),n=ht(t.env),r=await f(e),o=n==="live"?r.live:r.sandbox;if(!o.clientId||!o.clientSecret)throw m.badRequest(`Add your ${n==="live"?"Live":"Sandbox"} keys first.`);if(t.deleteSandboxOrders===!0){let a=(await K(e,5e3)).filter(i=>i.mode==="sandbox").map(i=>i.gatewayOrderId);a.length&&await P(e).deleteMany(a);for(let i of a)await e.kv.delete(`dl:n:${i}`)}return await e.settings.set("mode",n),{ok:!0}}async function Ct(e){for(let t of["sandbox","live"])await e.settings.delete(T(t).clientId),await e.settings.delete(T(t).secret);return await e.settings.set("mode","sandbox"),await e.kv.delete("paypal:token:sandbox"),await e.kv.delete("paypal:token:live"),{ok:!0}}async function Et(e){let t=v(e),n=y(t.currency,3).toUpperCase();if(!Y.includes(n))throw m.badRequest("Choose a currency PayPal supports.");return await e.settings.set("currency",n),await e.settings.set("brandName",y(t.brandName,127)),await e.settings.set("successMessage",y(t.successMessage,300)||ie),{ok:!0}}async function At(e){let[t,n,r,o]=await Promise.all([Pt(e),K(e),Ee(e,!0),f(e)]),a=new Map;for(let i of n)i.status==="COMPLETED"&&i.mode===o.mode&&a.set(i.productId,(a.get(i.productId)??0)+1);return{currency:o.currency,items:t.filter(({data:i})=>!i.archived).map(({id:i,data:s})=>({id:i,name:s.name,price:s.price,description:s.description,allowQuantity:s.allowQuantity,collectShipping:s.collectShipping,active:s.active,style:H(s.style),pages:r[i]??[],sales:a.get(i)??0,file:s.file?{name:s.file.name,size:s.file.size}:null}))}}async function Rt(e){let t=v(e),n=await f(e);if(typeof t.currency=="string"&&t.currency){let d=t.currency.toUpperCase();Y.includes(d)&&!(await K(e,1)).length&&(await e.settings.set("currency",d),n.currency=d)}let r=y(t.name,127);if(!r)throw m.badRequest("Give the product a name.");let o=Te(y(t.price,20),n.currency);if(!o)throw m.badRequest("Enter a price above 0, like 19.99.");let a=typeof t.id=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(t.id)?t.id:null,i=a?await b(e).get(a):null;if(a&&!i)throw m.notFound("Product not found.");let s=new Date().toISOString(),l=a??`p_${Date.now().toString(36)}${Array.from(crypto.getRandomValues(new Uint8Array(5)),d=>d.toString(16).padStart(2,"0")).join("")}`,c=await Xe(e,t.file,i?.file),u={...i??{},file:c,name:r,price:o,description:y(t.description,127),allowQuantity:t.allowQuantity===!0,collectShipping:t.collectShipping===!0,active:t.active!==!1,style:H(t.style),createdAt:i?.createdAt??s,updatedAt:s};return c||delete u.file,await b(e).put(l,u),await Je(e,i?.file,c),{id:l}}async function vt(e){let t=v(e),n=y(t.id,64),r=await b(e).get(n);if(!r)throw m.notFound("Product not found.");return await b(e).put(n,{...r,active:t.active===!0,updatedAt:new Date().toISOString()}),{ok:!0}}async function Tt(e){let t=y(v(e).id,64),n=await b(e).get(t);if(!n)throw m.notFound("Product not found.");let r=await P(e).count({productId:t})>0;return r?await b(e).put(t,{...n,archived:!0,active:!1,updatedAt:new Date().toISOString()}):(await b(e).delete(t),n.file&&await X(e,n.file)),{archived:r}}var Dt=new Set(["PENDING","FAILED","DECLINED","MISMATCH"]);function wn(e,t,n){return t==="paid"&&e.status!=="COMPLETED"||t==="unpaid"&&e.status!=="CREATED"||t==="issues"&&!Dt.has(e.status)?!1:n?[e.payerName,e.payerEmail,e.gatewayOrderId,e.productName].join(" ").toLowerCase().includes(n.toLowerCase()):!0}async function Ae(e){let t=v(e),n=await f(e),r=(await K(e)).filter(c=>c.mode===n.mode),o=await oe(e),a=Date.now()-30*wt,i=o?r:r.filter(c=>Date.parse(c.createdAt)>=a),s=y(t.filter,10)||"all",l=y(t.q,100);return{historyDays:o?null:30,older:r.length-i.length,counts:{all:i.length,paid:i.filter(c=>c.status==="COMPLETED").length,unpaid:i.filter(c=>c.status==="CREATED").length,issues:i.filter(c=>Dt.has(c.status)).length},items:i.filter(c=>wn(c,s,l)).slice(0,200)}}async function Ot(e){let t=y(v(e).id,64),n=await P(e).get(t);if(!n)throw m.notFound("Order not found.");let r=await f(e);if(r.mode!==n.mode)throw m.badRequest("This order belongs to the other environment.");let o;try{o=await te(e,r,t)}catch(l){kt(e,l)}let a=o.purchase_units?.[0]?.payments?.captures?.[0],i=n.status;a?.status==="COMPLETED"?i=a.amount?.value===n.amount&&a.amount?.currency_code===n.currency?"COMPLETED":"MISMATCH":a?.status==="PENDING"?i="PENDING":(a?.status==="DECLINED"||a?.status==="FAILED")&&(i="FAILED");let s={...n,status:i,transactionId:a?.id??n.transactionId};return await P(e).put(t,s),s}function hn(e){let t=e==null?"":String(e);return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}async function _t(e){if(!await oe(e))throw new m("PRO_REQUIRED","CSV export is part of Buyblock Pro.",403);let{items:t}=await Ae(e),n=["Date","Status","Product","Quantity","Amount","Currency","Customer","Email","Ship to","PayPal order","Capture"],r=t.map(o=>[o.capturedAt??o.createdAt,o.status,o.productName,o.quantity,o.amount,o.currency,o.payerName,o.payerEmail,[o.shippingName,o.shippingAddress].filter(Boolean).join(", "),o.gatewayOrderId,o.transactionId]);return{csv:[n,...r].map(o=>o.map(hn).join(",")).join(`
3
+ `)}}var Nt="buyblock",xt="0.3.0",Lt=["network:request","content:read","schema:read"],Mt=["api-m.sandbox.paypal.com","api-m.paypal.com"],Ut={products:{indexes:["createdAt","active"]},orders:{indexes:["createdAt","status","productId","transactionId"]}},Ht=[{path:"/",label:"Buyblock",icon:"square"}],$t=[{id:"sales",title:"Buyblock",size:"third"}];function sr(){return{id:Nt,displayName:"Buyblock: Sell Products & Digital Downloads",description:"Sell products and digital downloads with buy buttons on any page. Pay with PayPal.",version:xt,format:"native",entrypoint:"@zachristudio/buyblock",adminEntry:"@zachristudio/buyblock/admin",componentsEntry:"@zachristudio/buyblock/astro",capabilities:Lt,allowedHosts:Mt,adminPages:Ht,adminWidgets:$t,storage:Ut}}var O="plugins:read";function bn(){return Pn({id:Nt,version:xt,capabilities:Lt,allowedHosts:Mt,storage:Ut,routes:{button:{public:!0,methods:["POST"],handler:ut},"create-order":{public:!0,methods:["POST"],handler:dt},"capture-order":{public:!0,methods:["POST"],handler:pt},"download/authorize":{public:!0,methods:["POST"],handler:Ke},"order/lookup":{public:!0,methods:["POST"],handler:je},"order/view":{public:!0,methods:["POST"],handler:qe},state:{permission:O,handler:bt},"products/options":{permission:O,handler:ft},"products/list":{permission:O,handler:At},"products/save":{methods:["POST"],handler:Rt},"products/active":{methods:["POST"],handler:vt},"products/archive":{methods:["POST"],handler:Tt},"orders/list":{permission:O,handler:Ae},"orders/refresh":{methods:["POST"],handler:Ot},"orders/export":{permission:O,handler:_t},"connection/save":{methods:["POST"],handler:St},"connection/switch":{methods:["POST"],handler:It},"connection/disconnect":{methods:["POST"],handler:Ct},"store/save":{methods:["POST"],handler:Et},"files/begin":{methods:["POST"],handler:Ye},"files/part":{methods:["POST"],request:{body:"bytes",maxBytes:8*1024*1024},handler:We},"files/complete":{methods:["POST"],handler:Qe},"files/abort":{methods:["POST"],handler:Ze},"downloads/state":{permission:O,handler:et},"downloads/save":{methods:["POST"],handler:tt},"downloads/check":{methods:["POST"],handler:nt},"orders/download":{permission:O,handler:rt}},admin:{entry:"@zachristudio/buyblock/admin",settingsSchema:ve,pages:Ht,widgets:$t,portableTextBlocks:[{type:"buyblock-button",label:"Buy button",icon:"link-external",description:"Sell a product with a PayPal button",fields:[{type:"select",action_id:"productId",label:"Product",options:[],optionsRoute:"products/options"},{type:"toggle",action_id:"showDetails",label:"Show name and price",initial_value:!0}]},{type:"buyblock-order-lookup",label:"Order lookup",icon:"link",description:"Buyers find their downloads with their PayPal transaction ID",fields:[{type:"toggle",action_id:"showTitle",label:"Show the title",initial_value:!0}]}]}})}function cr(){return{name:"buyblock",hooks:{"astro:config:setup":({injectRoute:e})=>{e({pattern:"/buyblock/order",entrypoint:"@zachristudio/buyblock/routes/order",prerender:!1}),e({pattern:"/buyblock/download/[token]",entrypoint:"@zachristudio/buyblock/routes/download",prerender:!1})}}}}var lr=bn;export{Nt as PLUGIN_ID,cr as buyblock,sr as buyblockPlugin,bn as createPlugin,lr as default};
@@ -0,0 +1,39 @@
1
+ /*! Buyblock: Sell Products & Digital Downloads v0.3.0 · (c) zachristudio.com · See LICENSE */
2
+ var x="DOWNLOADS";var k=/^f_[a-f0-9]{32}$/,D=/^[A-Za-z0-9_.~+/=-]{8,512}$/;function y(e=16){return Array.from(crypto.getRandomValues(new Uint8Array(e)),t=>t.toString(16).padStart(2,"0")).join("")}var f=e=>import(e),b;function R(){return b??=(async()=>{try{return(await f("cloudflare:workers"))?.env??null}catch{return null}})(),b}async function $(){let t=(await R())?.[x];return t&&typeof t.createMultipartUpload=="function"?t:null}var w=class extends Error{};async function v(e){if(e==="r2"){let t=await $();if(!t)throw new w(`No R2 bucket is bound as ${x}.`);return T(t)}if(await R()!==null)throw new w("This site runs on Cloudflare, which has no server folder. Use an R2 bucket.");return C()}async function C(){let e=await f("node:fs/promises"),t=await f("node:path"),{createReadStream:a}=await f("node:fs"),{Readable:r}=await f("node:stream"),o=t.join(process.cwd(),".buyblock"),i=t.join(o,"downloads"),d=t.join(o,"uploads"),u=n=>{if(!k.test(n))throw new Error("Invalid file key");return t.join(i,n)},s=n=>{if(!/^[a-f0-9]{32}$/.test(n))throw new Error("Invalid upload");return t.join(d,n)};return{kind:"folder",async begin(n){u(n);let l=y();return await e.mkdir(s(l),{recursive:!0}),l},async part(n,l,p,c){return u(n),await e.writeFile(t.join(s(l),String(p)),c),String(c.byteLength)},async complete(n,l,p){let c=u(n);await e.mkdir(i,{recursive:!0});let m=`${c}.tmp`;await e.writeFile(m,new Uint8Array);for(let I of[...p].sort((A,F)=>A.n-F.n))await e.appendFile(m,await e.readFile(t.join(s(l),String(I.n))));return await e.rename(m,c),await e.rm(s(l),{recursive:!0,force:!0}),(await e.stat(c)).size},async abort(n,l){await e.rm(s(l),{recursive:!0,force:!0})},async size(n){try{return(await e.stat(u(n))).size}catch{return null}},async open(n,l){let p;try{p=(await e.stat(u(n))).size}catch{return null}let c=a(u(n),l?{start:l.start,end:l.end}:void 0);return{body:r.toWeb(c),size:p}},async remove(n){await e.rm(u(n),{force:!0})},async check(){await e.mkdir(i,{recursive:!0});let n=t.join(i,`.check-${y(4)}`);await e.writeFile(n,"ok");let l=await e.readFile(n,"utf8");if(await e.rm(n,{force:!0}),l!=="ok")throw new Error("Read back a different value.")}}}function T(e){let t=r=>{if(!k.test(r))throw new Error("Invalid file key")},a=r=>{if(!D.test(r))throw new Error("Invalid upload")};return{kind:"r2",async begin(r){return t(r),(await e.createMultipartUpload(r)).uploadId},async part(r,o,i,d){return t(r),a(o),(await e.resumeMultipartUpload(r,o).uploadPart(i,d)).etag},async complete(r,o,i){return t(r),a(o),(await e.resumeMultipartUpload(r,o).complete([...i].sort((u,s)=>u.n-s.n).map(u=>({partNumber:u.n,etag:u.etag})))).size},async abort(r,o){t(r),a(o),await e.resumeMultipartUpload(r,o).abort()},async size(r){return t(r),(await e.head(r))?.size??null},async open(r,o){t(r);let i=await e.get(r,o?{range:{offset:o.start,length:o.end-o.start+1}}:void 0);return i?{body:i.body,size:i.size}:null},async remove(r){t(r),await e.delete(r)},async check(){let r=`.check-${y(4)}`;await e.put(r,"ok");let o=await(await e.get(r))?.text();if(await e.delete(r),o!=="ok")throw new Error("Read back a different value.")}}}var U=["cf-connecting-ip","x-forwarded-for","x-real-ip","user-agent","accept-language"];async function P(e,t,a){let r=e.locals?.emdash?.handlePublicPluginApiRoute;if(typeof r!="function")return{ok:!1,code:"NOT_READY",message:"The shop isn't ready yet."};let o=new Headers({"Content-Type":"application/json"});for(let s of U){let n=e.request.headers.get(s);n&&o.set(s,n)}let i=e.request.cf,d={method:"POST",headers:o,body:JSON.stringify(a)};i&&(d.cf=i);let u=new Request(new URL(`/_emdash/api/plugins/buyblock/${t}`,e.url),d);try{let s=await r("buyblock","POST",`/${t}`,u);return s.success?{ok:!0,data:s.data}:{ok:!1,code:s.error?.code??"ERROR",message:s.error?.message??"Something went wrong."}}catch(s){return console.error("[buyblock]",s),{ok:!1,code:"ERROR",message:"Something went wrong. Please try again."}}}function g(e){return String(e??"").replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}var z=`
3
+ :root{color-scheme:light dark;--bg:#FAFAF8;--fg:#14161B;--muted:#4B5260;--line:#E3E5E8;--card:#FFFFFF;--btn:#14161B;--btnfg:#FFFFFF;--ok-bg:#E4F2EE;--ok:#0B5444;--warn-bg:#FDF4DC;--warn:#6B4E00;--err-bg:#FDECEA;--err:#8F1D14;--link:#0B6E57}
4
+ @media (prefers-color-scheme:dark){:root{--bg:#111216;--fg:#ECEEF2;--muted:#A3A9B5;--line:#2A2D35;--card:#16181D;--btn:#ECEEF2;--btnfg:#111216;--ok-bg:#0F2E27;--ok:#B6F0DF;--warn-bg:#2A220C;--warn:#F5D04A;--err-bg:#3A1714;--err:#FFC9C3;--link:#5FD3B4}}
5
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}
6
+ a{color:var(--link)}header{padding:20px 24px;border-bottom:1px solid var(--line)}header a{color:var(--fg);font-weight:700;text-decoration:none}
7
+ main{max-width:520px;margin:0 auto;padding:48px 20px 64px;display:flex;flex-direction:column;gap:22px}
8
+ h1{margin:0;font-size:30px;line-height:1.2;letter-spacing:-.02em}p{margin:0}.muted{color:var(--muted)}
9
+ .card{display:flex;flex-direction:column;gap:14px;padding:22px;background:var(--card);border:1px solid var(--line);border-radius:14px}
10
+ .row{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.grow{flex:1 1 200px;min-width:0;overflow-wrap:anywhere}
11
+ .btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:46px;padding:0 18px;background:var(--btn);color:var(--btnfg);border:0;border-radius:8px;font:600 15px system-ui,sans-serif;text-decoration:none;cursor:pointer}
12
+ .btn.secondary{background:transparent;color:var(--fg);border:1px solid var(--muted)}
13
+ .note{padding:14px 16px;border-radius:10px}.ok{background:var(--ok-bg);color:var(--ok)}.warn{background:var(--warn-bg);color:var(--warn)}.err{background:var(--err-bg);color:var(--err)}
14
+ form{display:flex;flex-direction:column;gap:18px}label{display:flex;flex-direction:column;gap:6px;font-weight:600;font-size:15px}
15
+ input{min-height:48px;padding:0 14px;background:var(--card);color:var(--fg);border:1px solid var(--muted);border-radius:8px;font:400 16px system-ui,sans-serif}
16
+ code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9em;overflow-wrap:anywhere}
17
+ `;function S(e){let t=`<!doctype html>
18
+ <html lang="en">
19
+ <head>
20
+ <meta charset="utf-8">
21
+ <meta name="viewport" content="width=device-width, initial-scale=1">
22
+ <meta name="robots" content="noindex, nofollow">
23
+ <meta name="referrer" content="no-referrer">
24
+ <title>${g(e.title)}${e.shop?` \xB7 ${g(e.shop)}`:""}</title>
25
+ <style>${z}</style>
26
+ </head>
27
+ <body>
28
+ <header><a href="/">${g(e.shop||"Home")}</a></header>
29
+ <main>
30
+ ${e.body}
31
+ </main>
32
+ </body>
33
+ </html>`;return new Response(t,{status:e.status??200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"private, no-store","Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex, nofollow","X-Content-Type-Options":"nosniff"}})}var q=!1;function N(e,t){if(!e)return null;let a=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!a||!a[1]&&!a[2])return null;let r,o;if(a[1])r=Number(a[1]),o=a[2]?Math.min(Number(a[2]),t-1):t-1;else{let i=Number(a[2]);if(i<=0)return"invalid";r=Math.max(0,t-i),o=t-1}return r>=t||o<r?"invalid":{start:r,end:o}}function M(e){let t=e.replace(/[^\x20-\x7e]/g,"_").replace(/["\\]/g,"_"),a=encodeURIComponent(e).replace(/[!'()*]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase()}`);return`attachment; filename="${t}"; filename*=UTF-8''${a}`}var O={EXPIRED:{title:"This download link has expired",text:"Download links work for 1 hour. Your order page gives you a fresh one.",status:410},INVALID:{title:"This link isn\u2019t valid",text:"It may be incomplete. Open your order with the transaction ID from your PayPal receipt.",status:404},NOT_PAID:{title:"This order isn\u2019t paid yet",text:"The download unlocks when PayPal completes your payment. Check your order page later.",status:402},TEST:{title:"This was a test purchase",text:"Test purchases don\u2019t include downloads now that the shop is live.",status:403},LIMIT:{title:"You\u2019ve used all your downloads",text:"If you still need the file, contact the shop and quote your transaction ID.",status:403},ENDED:{title:"Access to this file has ended",text:"Contact the shop if you still need it, and quote your transaction ID.",status:403},MISSING:{title:"The file isn\u2019t available right now",text:"Please try again later. If it keeps happening, contact the shop with your transaction ID.",status:503},ERROR:{title:"The file isn\u2019t available right now",text:"Please try again later. If it keeps happening, contact the shop with your transaction ID.",status:503}};function h(e,t={}){let a=O[e],r=a.title,o=a.text;e==="LIMIT"&&t.limit&&(r=`You\u2019ve used all ${t.limit} downloads`,o=`This shop allows ${t.limit} ${t.limit===1?"download":"downloads"} per order. ${a.text}`),e==="ENDED"&&t.until&&(o=`Downloads for this order were open until ${new Date(t.until).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric",timeZone:"UTC"})}. ${a.text}`);let i=t.orderUrl&&(e==="EXPIRED"||e==="NOT_PAID"),d=`<div class="card">
34
+ <h1>${g(r)}</h1>
35
+ <p class="muted">${g(o)}</p>
36
+ ${t.tx?`<p><code>${g(t.tx)}</code></p>`:""}
37
+ ${i?`<p><a class="btn" href="${g(t.orderUrl)}">Go to my order</a></p>`:""}
38
+ ${e==="INVALID"?'<p><a class="btn secondary" href="/buyblock/order">Find my order</a></p>':""}
39
+ </div>`;return S({title:r,body:d,status:a.status})}async function E(e,t){let a=e.params.token??"",r=e.request.headers.get("range"),o=!r||/^bytes=0-$/.test(r.trim()),i=await P(e,"download/authorize",{token:a,count:!t&&o});if(!i.ok)return h("ERROR");let d=i.data;if(!d.ok)return h(d.reason,d);let u;try{u=await v(d.store)}catch(m){return console.error("[buyblock] storage unavailable:",m),h("MISSING")}let s=await u.size(d.key)??-1;if(s<0)return h("MISSING");let n=N(r,s),l=new Headers({"Content-Type":d.type||"application/octet-stream","Content-Disposition":M(d.name),"Accept-Ranges":"bytes","Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"});if(n==="invalid")return l.set("Content-Range",`bytes */${s}`),new Response(null,{status:416,headers:l});let p=n?n.end-n.start+1:s;if(l.set("Content-Length",String(p)),n&&l.set("Content-Range",`bytes ${n.start}-${n.end}/${s}`),t)return new Response(null,{status:n?206:200,headers:l});let c=await u.open(d.key,n??void 0);return c?new Response(c.body,{status:n?206:200,headers:l}):h("MISSING")}var G=e=>E(e,!1),H=e=>E(e,!0);export{G as GET,H as HEAD,q as prerender};
@@ -0,0 +1,53 @@
1
+ /*! Buyblock: Sell Products & Digital Downloads v0.3.0 · (c) zachristudio.com · See LICENSE */
2
+ var f=["cf-connecting-ip","x-forwarded-for","x-real-ip","user-agent","accept-language"];async function d(e,r,a){let t=e.locals?.emdash?.handlePublicPluginApiRoute;if(typeof t!="function")return{ok:!1,code:"NOT_READY",message:"The shop isn't ready yet."};let o=new Headers({"Content-Type":"application/json"});for(let i of f){let p=e.request.headers.get(i);p&&o.set(i,p)}let l=e.request.cf,c={method:"POST",headers:o,body:JSON.stringify(a)};l&&(c.cf=l);let m=new Request(new URL(`/_emdash/api/plugins/buyblock/${r}`,e.url),c);try{let i=await t("buyblock","POST",`/${r}`,m);return i.success?{ok:!0,data:i.data}:{ok:!1,code:i.error?.code??"ERROR",message:i.error?.message??"Something went wrong."}}catch(i){return console.error("[buyblock]",i),{ok:!1,code:"ERROR",message:"Something went wrong. Please try again."}}}function n(e){return String(e??"").replace(/[&<>"']/g,r=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[r])}function g(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:e<1024*1024*1024?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}var h=`
3
+ :root{color-scheme:light dark;--bg:#FAFAF8;--fg:#14161B;--muted:#4B5260;--line:#E3E5E8;--card:#FFFFFF;--btn:#14161B;--btnfg:#FFFFFF;--ok-bg:#E4F2EE;--ok:#0B5444;--warn-bg:#FDF4DC;--warn:#6B4E00;--err-bg:#FDECEA;--err:#8F1D14;--link:#0B6E57}
4
+ @media (prefers-color-scheme:dark){:root{--bg:#111216;--fg:#ECEEF2;--muted:#A3A9B5;--line:#2A2D35;--card:#16181D;--btn:#ECEEF2;--btnfg:#111216;--ok-bg:#0F2E27;--ok:#B6F0DF;--warn-bg:#2A220C;--warn:#F5D04A;--err-bg:#3A1714;--err:#FFC9C3;--link:#5FD3B4}}
5
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}
6
+ a{color:var(--link)}header{padding:20px 24px;border-bottom:1px solid var(--line)}header a{color:var(--fg);font-weight:700;text-decoration:none}
7
+ main{max-width:520px;margin:0 auto;padding:48px 20px 64px;display:flex;flex-direction:column;gap:22px}
8
+ h1{margin:0;font-size:30px;line-height:1.2;letter-spacing:-.02em}p{margin:0}.muted{color:var(--muted)}
9
+ .card{display:flex;flex-direction:column;gap:14px;padding:22px;background:var(--card);border:1px solid var(--line);border-radius:14px}
10
+ .row{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.grow{flex:1 1 200px;min-width:0;overflow-wrap:anywhere}
11
+ .btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:46px;padding:0 18px;background:var(--btn);color:var(--btnfg);border:0;border-radius:8px;font:600 15px system-ui,sans-serif;text-decoration:none;cursor:pointer}
12
+ .btn.secondary{background:transparent;color:var(--fg);border:1px solid var(--muted)}
13
+ .note{padding:14px 16px;border-radius:10px}.ok{background:var(--ok-bg);color:var(--ok)}.warn{background:var(--warn-bg);color:var(--warn)}.err{background:var(--err-bg);color:var(--err)}
14
+ form{display:flex;flex-direction:column;gap:18px}label{display:flex;flex-direction:column;gap:6px;font-weight:600;font-size:15px}
15
+ input{min-height:48px;padding:0 14px;background:var(--card);color:var(--fg);border:1px solid var(--muted);border-radius:8px;font:400 16px system-ui,sans-serif}
16
+ code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9em;overflow-wrap:anywhere}
17
+ `;function u(e){let r=`<!doctype html>
18
+ <html lang="en">
19
+ <head>
20
+ <meta charset="utf-8">
21
+ <meta name="viewport" content="width=device-width, initial-scale=1">
22
+ <meta name="robots" content="noindex, nofollow">
23
+ <meta name="referrer" content="no-referrer">
24
+ <title>${n(e.title)}${e.shop?` \xB7 ${n(e.shop)}`:""}</title>
25
+ <style>${h}</style>
26
+ </head>
27
+ <body>
28
+ <header><a href="/">${n(e.shop||"Home")}</a></header>
29
+ <main>
30
+ ${e.body}
31
+ </main>
32
+ </body>
33
+ </html>`;return new Response(r,{status:e.status??200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"private, no-store","Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex, nofollow","X-Content-Type-Options":"nosniff"}})}var k=!1,y='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 4v11"/><path d="M7 10l5 5 5-5"/><path d="M5 20h14"/></svg>';function s(e){let r=`<div style="display:flex;flex-direction:column;gap:8px">
34
+ <h1>Find your order</h1>
35
+ <p class="muted">Download your files again. You\u2019ll find the transaction ID in the receipt PayPal emailed you.</p>
36
+ </div>
37
+ ${e.error?`<p class="note err" role="alert">${n(e.error)}</p>`:""}
38
+ <form method="post" action="/buyblock/order">
39
+ <label>PayPal transaction ID<input name="tx" value="${n(e.tx)}" autocomplete="off" required maxlength="64" placeholder="e.g. 8MC58145K2289241X" style="font-family:ui-monospace,monospace"></label>
40
+ <label>Email you paid with<input name="email" type="email" value="${n(e.email)}" autocomplete="email" required maxlength="254" placeholder="you@example.com"></label>
41
+ <button class="btn" type="submit">Find my order</button>
42
+ </form>`;return u({title:"Find your order",shop:e.shop,body:r,status:e.status})}function x(e){let r=e.date?new Date(e.date).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}):"",a=e.quantity&&e.quantity>1?`${e.productName} \xD7 ${e.quantity}`:e.productName,t=e.delivery,o="";t?.testOrder?o='<p class="note warn" role="status">This was a test purchase. Test purchases don\u2019t include downloads now that the shop is live.</p>':e.status==="PENDING"?o='<p class="note warn" role="status">Your payment is still pending at PayPal. Your download appears here as soon as it completes.</p>':t?.unavailable||e.file&&!t?.fileUrl?o='<p class="note err" role="alert">The file can\u2019t be downloaded right now. Please try again later, or contact the shop with your transaction ID.</p>':t?.fileUrl&&e.file?o=`<section class="card" aria-labelledby="dl">
43
+ <h2 id="dl" style="margin:0;font-size:16px">Your download</h2>
44
+ <div class="row"><span class="grow"><strong>${n(e.file.name)}</strong><br><span class="muted">${n(g(e.file.size))}${t.limitText?` \xB7 ${n(t.limitText)}`:""}</span></span>
45
+ <a class="btn" href="${n(t.fileUrl)}">${y}Download</a></div>
46
+ </section>`:o='<p class="muted">This order has no file to download.</p>';let l=`<div style="display:flex;flex-direction:column;gap:8px">
47
+ <span class="muted">${e.status==="PENDING"?"Ordered":"Paid"} ${n(r)} \xB7 ${n(e.amount)} ${n(e.currency)}</span>
48
+ <h1>${n(a)}</h1>
49
+ </div>
50
+ ${o}
51
+ <p class="muted">Bookmark this page to download again later. Keep the link private: anyone with it can download your file.</p>
52
+ <p class="muted">Transaction <code>${n(e.tx)}</code></p>
53
+ <p><a href="/buyblock/order">Look up another order</a></p>`;return u({title:"Your order",shop:e.shop,body:l})}async function P(e){let r=e.url.searchParams;if(r.get("ping")==="1")return new Response(JSON.stringify({buyblock:!0}),{headers:{"Content-Type":"application/json","Cache-Control":"no-store"}});let a=r.get("o"),t=r.get("k");if(!a||!t)return s({});let o=await d(e,"order/view",{o:a,k:t});return o.ok?o.data.found?x(o.data):s({error:"This order link isn\u2019t valid. Look the order up with your PayPal transaction ID instead.",status:404}):s({error:"Something went wrong. Please try again.",status:503})}async function F(e){let r="",a="";try{let o=await e.request.formData();r=String(o.get("tx")??"").trim().slice(0,64),a=String(o.get("email")??"").trim().slice(0,254)}catch{return s({error:"Please fill in both fields.",status:400})}let t=await d(e,"order/lookup",{tx:r,email:a});if(!t.ok){let o=t.code==="RATE_LIMITED";return s({tx:r,email:a,error:o?"Too many tries. Please wait a few minutes and try again.":"Something went wrong. Please try again.",status:o?429:503})}return!t.data.found||!t.data.url?s({tx:r,email:a,error:"We couldn\u2019t find a paid order with those details. Check the transaction ID in your PayPal receipt and use the email you paid with.",status:404}):new Response(null,{status:303,headers:{Location:t.data.url,"Cache-Control":"no-store"}})}export{P as GET,F as POST,k as prerender};
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "@zachristudio/buyblock",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Buyblock: sell products and digital downloads on EmDash. Buy buttons on any page, files delivered after payment from your own private storage, orders dashboard. Pays with PayPal (more gateways planned). Free plan, no key.",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "author": "Zachri Studio (https://zachristudio.com)",
7
+ "homepage": "https://zachristudio.com/buyblock/docs/",
8
+ "type": "module",
9
+ "main": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "./admin": "./dist/admin.js",
17
+ "./astro": "./dist/astro/index.js",
18
+ "./client": "./dist/client.js",
19
+ "./routes/order": "./dist/routes/order.js",
20
+ "./routes/download": "./dist/routes/download.js"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "brand/buyblock-icon-512.png",
25
+ "brand/buyblock-lockup.png",
26
+ "brand/buyblock-lockup-light.png",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "sideEffects": false,
31
+ "scripts": {
32
+ "build": "node scripts/build.mjs",
33
+ "prepack": "node scripts/build.mjs",
34
+ "typecheck": "tsc -p .",
35
+ "test": "esbuild test/ratelimit.test.ts --bundle --platform=node --format=esm --external:emdash --outfile=node_modules/.cache/ratelimit.test.mjs --log-level=warning && node node_modules/.cache/ratelimit.test.mjs && esbuild test/downloads.test.ts --bundle --platform=node --format=esm --external:emdash --outfile=node_modules/.cache/downloads.test.mjs --log-level=warning && node node_modules/.cache/downloads.test.mjs"
36
+ },
37
+ "keywords": [
38
+ "emdash",
39
+ "emdash-plugin",
40
+ "astro",
41
+ "sell",
42
+ "digital-downloads",
43
+ "downloads",
44
+ "ebook",
45
+ "buy-button",
46
+ "payments",
47
+ "checkout",
48
+ "paypal",
49
+ "ecommerce"
50
+ ],
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "peerDependencies": {
55
+ "@cloudflare/kumo": ">=2.6.0",
56
+ "@phosphor-icons/react": "^2.1.0",
57
+ "astro": ">=6.0.0",
58
+ "emdash": ">=1.5.0",
59
+ "react": "^19.0.0"
60
+ },
61
+ "devDependencies": {
62
+ "@types/react": "19.3.0",
63
+ "esbuild": "0.28.2",
64
+ "typescript": "6.0.3"
65
+ },
66
+ "bugs": {
67
+ "url": "https://zachristudio.com/buyblock/docs/support/"
68
+ }
69
+ }