cascivo 1.7.0 → 1.8.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.
Files changed (178) hide show
  1. package/README.md +1 -0
  2. package/dist/app-DDq0Utmj.mjs +5 -0
  3. package/dist/app-DDq0Utmj.mjs.map +1 -0
  4. package/dist/{args-DEL5BZq7.mjs → args-B4PN85cC.mjs} +2 -2
  5. package/dist/{args-DEL5BZq7.mjs.map → args-B4PN85cC.mjs.map} +1 -1
  6. package/dist/blueprint-eOLGuyAi.mjs +2 -0
  7. package/dist/blueprint-eOLGuyAi.mjs.map +1 -0
  8. package/dist/cmdspec.json +107 -2
  9. package/dist/config-CTk7uDrh.mjs +2 -0
  10. package/dist/config-CTk7uDrh.mjs.map +1 -0
  11. package/dist/create-BA9GQ8nl.mjs +1991 -0
  12. package/dist/create-BA9GQ8nl.mjs.map +1 -0
  13. package/dist/{email-BzLRydvR.mjs → email-Drn2bDlp.mjs} +2 -2
  14. package/dist/{email-BzLRydvR.mjs.map → email-Drn2bDlp.mjs.map} +1 -1
  15. package/dist/generated/audit-contract.json +38 -38
  16. package/dist/index.d.mts.map +1 -1
  17. package/dist/index.mjs +64 -49
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/mcp-CqX_Yi06.mjs +2 -0
  20. package/dist/mcp-CqX_Yi06.mjs.map +1 -0
  21. package/dist/merge-D332dc_m.mjs +8 -0
  22. package/dist/merge-D332dc_m.mjs.map +1 -0
  23. package/dist/rolldown-runtime-DT7IzrpZ.mjs +1 -0
  24. package/package.json +5 -4
  25. package/readme.body.md +1 -0
  26. package/recipes/README.md +21 -0
  27. package/recipes/accounts/recipe.json +12 -0
  28. package/recipes/accounts/src/auth.ts +7 -0
  29. package/recipes/agent/recipe.json +16 -0
  30. package/recipes/agent/src/assistant.module.css +33 -0
  31. package/recipes/agent/src/assistant.ts +26 -0
  32. package/recipes/agent/src/routes/assistant.tsx +130 -0
  33. package/recipes/agent/worker/assistant.ts +55 -0
  34. package/recipes/agent/worker/scripted-model.ts +102 -0
  35. package/recipes/auth-email/recipe.json +7 -0
  36. package/recipes/auth-email/src/routes/signin/verify.tsx +50 -0
  37. package/recipes/auth-email/worker/auth.ts +37 -0
  38. package/recipes/billing/recipe.json +14 -0
  39. package/recipes/billing/src/billing.ts +90 -0
  40. package/recipes/billing/src/routes/billing.tsx +150 -0
  41. package/recipes/billing/worker/billing.ts +325 -0
  42. package/recipes/block-auth-login/recipe.json +7 -0
  43. package/recipes/block-auth-login/src/blocks/auth-login.module.css +86 -0
  44. package/recipes/block-auth-login/src/blocks/auth-login.tsx +80 -0
  45. package/recipes/block-auth-signup/recipe.json +7 -0
  46. package/recipes/block-auth-signup/src/blocks/auth-signup.module.css +80 -0
  47. package/recipes/block-auth-signup/src/blocks/auth-signup.tsx +118 -0
  48. package/recipes/block-dashboard-charts/recipe.json +9 -0
  49. package/recipes/block-dashboard-charts/src/blocks/dashboard-charts.tsx +80 -0
  50. package/recipes/block-dashboard-overview/recipe.json +7 -0
  51. package/recipes/block-dashboard-overview/src/blocks/dashboard-overview.module.css +83 -0
  52. package/recipes/block-dashboard-overview/src/blocks/dashboard-overview.tsx +53 -0
  53. package/recipes/block-dashboard-table/recipe.json +7 -0
  54. package/recipes/block-dashboard-table/src/blocks/dashboard-table.module.css +74 -0
  55. package/recipes/block-dashboard-table/src/blocks/dashboard-table.tsx +203 -0
  56. package/recipes/block-empty-dashboard/recipe.json +6 -0
  57. package/recipes/block-empty-dashboard/src/blocks/empty-dashboard.tsx +20 -0
  58. package/recipes/block-faq/recipe.json +7 -0
  59. package/recipes/block-faq/src/blocks/faq.module.css +35 -0
  60. package/recipes/block-faq/src/blocks/faq.tsx +55 -0
  61. package/recipes/block-login-page/recipe.json +6 -0
  62. package/recipes/block-login-page/src/blocks/login-page.tsx +51 -0
  63. package/recipes/block-marketing-features/recipe.json +7 -0
  64. package/recipes/block-marketing-features/src/blocks/marketing-features.module.css +77 -0
  65. package/recipes/block-marketing-features/src/blocks/marketing-features.tsx +71 -0
  66. package/recipes/block-marketing-hero/recipe.json +7 -0
  67. package/recipes/block-marketing-hero/src/blocks/marketing-hero.module.css +51 -0
  68. package/recipes/block-marketing-hero/src/blocks/marketing-hero.tsx +38 -0
  69. package/recipes/block-notification-center/recipe.json +6 -0
  70. package/recipes/block-notification-center/src/blocks/notification-center.tsx +62 -0
  71. package/recipes/block-page-with-breadcrumb/recipe.json +6 -0
  72. package/recipes/block-page-with-breadcrumb/src/blocks/page-with-breadcrumb.tsx +23 -0
  73. package/recipes/block-pricing/recipe.json +7 -0
  74. package/recipes/block-pricing/src/blocks/pricing.module.css +102 -0
  75. package/recipes/block-pricing/src/blocks/pricing.tsx +90 -0
  76. package/recipes/block-settings-form-page/recipe.json +6 -0
  77. package/recipes/block-settings-form-page/src/blocks/settings-form-page.tsx +85 -0
  78. package/recipes/block-settings-profile/recipe.json +7 -0
  79. package/recipes/block-settings-profile/src/blocks/settings-profile.module.css +92 -0
  80. package/recipes/block-settings-profile/src/blocks/settings-profile.tsx +127 -0
  81. package/recipes/block-site-footer/recipe.json +7 -0
  82. package/recipes/block-site-footer/src/blocks/site-footer.module.css +83 -0
  83. package/recipes/block-site-footer/src/blocks/site-footer.tsx +72 -0
  84. package/recipes/block-stats-cards/recipe.json +6 -0
  85. package/recipes/block-stats-cards/src/blocks/stats-cards.tsx +49 -0
  86. package/recipes/block-testimonials/recipe.json +7 -0
  87. package/recipes/block-testimonials/src/blocks/testimonials.module.css +67 -0
  88. package/recipes/block-testimonials/src/blocks/testimonials.tsx +57 -0
  89. package/recipes/block-users-table-page/recipe.json +6 -0
  90. package/recipes/block-users-table-page/src/blocks/users-table-page.tsx +60 -0
  91. package/recipes/board/recipe.json +14 -0
  92. package/recipes/board/src/board.module.css +40 -0
  93. package/recipes/board/src/board.ts +51 -0
  94. package/recipes/board/src/routes/board.tsx +124 -0
  95. package/recipes/checkout/recipe.json +15 -0
  96. package/recipes/checkout/src/checkout.ts +93 -0
  97. package/recipes/checkout/src/routes/checkout/[order].tsx +131 -0
  98. package/recipes/checkout/src/routes/checkout.tsx +70 -0
  99. package/recipes/checkout/worker/checkout.ts +357 -0
  100. package/recipes/cloudflare/recipe.json +10 -0
  101. package/recipes/cloudflare/src/LiveCard.tsx +55 -0
  102. package/recipes/cloudflare/src/live.ts +43 -0
  103. package/recipes/cloudflare/src/main.tsx +17 -0
  104. package/recipes/cloudflare/src/router.ts +6 -0
  105. package/recipes/cloudflare/src/routes/404.tsx +5 -0
  106. package/recipes/crud/recipe.json +16 -0
  107. package/recipes/crud/src/customers-page.ts +55 -0
  108. package/recipes/crud/src/customers.ts +76 -0
  109. package/recipes/crud/src/routes/customers.tsx +180 -0
  110. package/recipes/crud/worker/customers.ts +69 -0
  111. package/recipes/crud/worker/migrations.ts +50 -0
  112. package/recipes/digest/recipe.json +14 -0
  113. package/recipes/digest/src/digest.ts +47 -0
  114. package/recipes/digest/src/routes/digest.tsx +82 -0
  115. package/recipes/digest/worker/digest.ts +129 -0
  116. package/recipes/export/recipe.json +12 -0
  117. package/recipes/export/src/routes/report.tsx +68 -0
  118. package/recipes/files/recipe.json +15 -0
  119. package/recipes/files/src/files.module.css +16 -0
  120. package/recipes/files/src/files.ts +37 -0
  121. package/recipes/files/src/routes/files.tsx +81 -0
  122. package/recipes/files/src/upload-policy.ts +12 -0
  123. package/recipes/import/recipe.json +15 -0
  124. package/recipes/import/src/import-job.ts +60 -0
  125. package/recipes/import/src/import-page.ts +36 -0
  126. package/recipes/import/src/routes/import.tsx +112 -0
  127. package/recipes/import/worker/import-job.ts +86 -0
  128. package/recipes/live/recipe.json +13 -0
  129. package/recipes/live/src/ops.ts +22 -0
  130. package/recipes/live/src/routes/ops.tsx +123 -0
  131. package/recipes/newsletter/recipe.json +22 -0
  132. package/recipes/newsletter/src/newsletter.ts +139 -0
  133. package/recipes/newsletter/src/routes/newsletter/confirm.tsx +58 -0
  134. package/recipes/newsletter/src/routes/newsletter/send.tsx +192 -0
  135. package/recipes/newsletter/src/routes/newsletter/unsubscribe.tsx +56 -0
  136. package/recipes/newsletter/src/routes/newsletter.tsx +82 -0
  137. package/recipes/newsletter/worker/newsletter-email.ts +90 -0
  138. package/recipes/newsletter/worker/newsletter.ts +455 -0
  139. package/recipes/notes/recipe.json +13 -0
  140. package/recipes/notes/src/notes.ts +61 -0
  141. package/recipes/notes/src/routes/notes.tsx +76 -0
  142. package/recipes/publish/recipe.json +16 -0
  143. package/recipes/publish/src/pages.ts +72 -0
  144. package/recipes/publish/src/routes/p/[slug].tsx +50 -0
  145. package/recipes/publish/src/routes/publish.tsx +160 -0
  146. package/recipes/publish/worker/page-html.ts +126 -0
  147. package/recipes/publish/worker/pages.ts +65 -0
  148. package/recipes/publish-preview/recipe.json +6 -0
  149. package/recipes/publish-preview/worker/page-preview.ts +57 -0
  150. package/recipes/search/recipe.json +15 -0
  151. package/recipes/search/src/routes/search.tsx +128 -0
  152. package/recipes/search/src/search.ts +64 -0
  153. package/recipes/search/worker/articles.ts +126 -0
  154. package/recipes/search/worker/search.ts +146 -0
  155. package/recipes/social/recipe.json +15 -0
  156. package/recipes/social/src/routes/social.tsx +456 -0
  157. package/recipes/social/src/social.ts +349 -0
  158. package/recipes/social/worker/social-post.ts +199 -0
  159. package/recipes/social/worker/social.ts +719 -0
  160. package/recipes/usage/recipe.json +14 -0
  161. package/recipes/usage/src/routes/usage.tsx +88 -0
  162. package/recipes/usage/src/usage.ts +61 -0
  163. package/recipes/usage/worker/usage.ts +75 -0
  164. package/recipes/voice/recipe.json +15 -0
  165. package/recipes/voice/src/routes/voice.tsx +117 -0
  166. package/recipes/voice/src/voice.ts +91 -0
  167. package/recipes/voice/worker/scripted-voice.ts +46 -0
  168. package/recipes/voice/worker/voice.ts +64 -0
  169. package/recipes/webhooks/recipe.json +14 -0
  170. package/recipes/webhooks/src/routes/webhooks.tsx +106 -0
  171. package/recipes/webhooks/src/webhooks.ts +43 -0
  172. package/recipes/webhooks/worker/webhooks.ts +118 -0
  173. package/dist/config-CpoAu8C-.mjs +0 -2
  174. package/dist/config-CpoAu8C-.mjs.map +0 -1
  175. package/dist/create-BcfPWm1F.mjs +0 -9976
  176. package/dist/create-BcfPWm1F.mjs.map +0 -1
  177. package/dist/mcp-jwnfOQIt.mjs +0 -2
  178. package/dist/mcp-jwnfOQIt.mjs.map +0 -1
@@ -0,0 +1,1991 @@
1
+ import{a as e,r as t}from"./config-CTk7uDrh.mjs";import{i as n}from"./fs-B7O-fNID.mjs";import{n as r,r as i,t as a}from"./args-B4PN85cC.mjs";import{n as o}from"./mcp-CqX_Yi06.mjs";import{stdin as s,stdout as c}from"node:process";import{fileURLToPath as l}from"node:url";import{existsSync as u,readFileSync as d,readdirSync as f}from"node:fs";import{dirname as p,join as m,resolve as h}from"node:path";import{isSafeRelativePath as g}from"@cascivo/registry";import{createInterface as _}from"node:readline/promises";const v={"@cascivo/react":`1.9.0`,"@cascivo/themes":`1.0.3`,"@cascivo/charts":`1.9.0`,"@cascivo/icons":`1.1.1`,"@cascivo/eslint-config":`0.4.2`,"@cascivo/app":`1.9.0`,"@cascivo/render":`1.9.0`,"@cascivo/storage":`1.9.0`,"@cascivo/email":`0.6.1`},y=`>=3.0.0`,b=`1.8.0`;function x(e){let t=e.startsWith(`/`)?e:`/${e}`;return t.length>1?t.replace(/\/+$/,``)||`/`:t}function S(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function C(e){let t=x(e).split(`/`).filter(Boolean),n=[],r=[],i=``;return t.forEach((a,o)=>{if(a===`*`){if(o!==t.length-1)throw Error(`"*" must be the last segment of a path pattern: "${e}"`);n.push(`*`),r.push(1),i+=`(?:/(.*))?`}else if(a.startsWith(`:`)){let t=a.slice(1);if(!/^[A-Za-z_$][\w$]*$/.test(t))throw Error(`Invalid param name "${t}" in path pattern "${e}"`);n.push(t),r.push(2),i+=`/([^/]+)`}else r.push(3),i+=`/${S(a)}`}),{pattern:e,keys:n,regex:RegExp(`^${i||`/`}/?$`),score:r}}function w(e,t){let n=Math.max(e.score.length,t.score.length);for(let r=0;r<n;r++){let n=(t.score[r]??0)-(e.score[r]??0);if(n!==0)return n}return 0}var T=/\.(tsx|jsx)$/;function ee(e){if(!T.test(e)||/\.(test|spec)\.[jt]sx$/.test(e))return;let t=e.replace(T,``).split(`/`);if(!t.some(e=>e.startsWith(`_`)))return t.length===1&&t[0]===`404`?null:(t.at(-1)===`index`&&t.pop(),`/${t.map((n,r)=>{if(/^\[\.\.\.[A-Za-z_$][\w$]*\]$/.test(n)){if(r!==t.length-1)throw Error(`routes/${e}: a [...rest] segment must be last`);return`*`}let i=/^\[([A-Za-z_$][\w$]*)\]$/.exec(n);if(i)return`:${i[1]}`;if(/[[\]]/.test(n))throw Error(`routes/${e}: malformed segment "${n}"`);return n}).join(`/`)}`)}function te(e,t){let n=[],r=/* @__PURE__ */ new Map;for(let t of e){let e=ee(t);if(e===void 0)continue;let i=r.get(e);if(i)throw Error(`routes/${i} and routes/${t} both define ${e??`the 404 route`}`);r.set(e,t),n.push({file:t,path:e})}let i=e=>`${t}/${e.replace(T,``)}`,a=n.filter(e=>e.path!==null).map(e=>({...e,compiled:C(e.path)})).sort((e,t)=>w(e.compiled,t.compiled)||e.path.localeCompare(t.path)),o=n.find(e=>e.path===null);return[`// Generated by @cascivo/app/vite from the routes directory — do not edit.`,`// Add, rename or delete a route file and this file is rewritten.`,`import { lazyRoute } from '@cascivo/app'`,`import type { Route } from '@cascivo/app'`,``,`export const routes: Route[] = [`,...a.map(e=>` lazyRoute('${e.path}', () => import('${i(e.file)}')),`),`]`,``,o?`export const notFound: Route | undefined = lazyRoute('*', () => import('${i(o.file)}'))`:`export const notFound: Route | undefined = undefined`,``,"/** Every route pattern. Fill one with `buildPath` for a typed link. */",`export type AppPath = ${a.length>0?a.map(e=>`'${e.path}'`).join(` | `):`never`}`,``].join(`
2
+ `)}const E=p(l(import.meta.url));function D(){for(let e of[m(E,`..`,`recipes`),m(E,`..`,`..`,`recipes`)])if(u(m(e,`cloudflare`,`recipe.json`)))return e;throw Error(`cascivo: the scaffold recipes are missing (looked beside ${E}).`)}function O(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t}: a recipe must be an object.`);let{name:n,files:r,nav:i=[],dependencies:a=[]}=e;if(typeof n!=`string`||!/^[a-z][a-z0-9-]*$/.test(n))throw Error(`${t}: "name" must be a lower-case kebab-case string.`);if(!Array.isArray(r)||r.length===0)throw Error(`${t}: "files" must be a non-empty array of paths.`);let o=[];for(let e of r){if(!g(e))throw Error(`${t}: "${String(e)}" is not a safe relative path.`);o.push(e)}if(!Array.isArray(i))throw Error(`${t}: "nav" must be an array.`);let s=[];for(let e of i){let{label:n,href:r}=typeof e==`object`&&e?e:{};if(typeof n!=`string`||n===``||typeof r!=`string`||!r.startsWith(`/`))throw Error(`${t}: each "nav" entry needs a "label" and an "href" starting with "/".`);s.push({label:n,href:r})}if(!Array.isArray(a)||!a.every(e=>typeof e==`string`&&/^@cascivo\/[a-z-]+$/.test(e)))throw Error(`${t}: "dependencies" must be an array of @cascivo/* package names.`);return{name:n,files:o,nav:s,dependencies:a.map(String)}}const k=/* @__PURE__ */ new Map;function ne(e){let t=k.get(e);if(t)return t;let n=m(D(),e,`recipe.json`),r=O(JSON.parse(d(n,`utf8`)),n);if(r.name!==e)throw Error(`${n}: "name" must be "${e}".`);return k.set(e,r),r}const re=/\{\{(brand|appName|usageDataset)\}\}/g;function ie(e,t){let n=m(D(),e);return ne(e).files.map(e=>({path:e,contents:d(m(n,e),`utf8`).replace(re,(e,n)=>t[n])}))}function ae(){return f(D()).filter(e=>e.startsWith(`block-`)).map(e=>e.slice(6)).sort()}const A=U;function oe(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`cascivo: the scaffold wrote a package.json that is not an object`);return{...t}}function se(e){return typeof e!=`object`||!e?{}:Object.fromEntries(Object.entries(e).filter(e=>typeof e[1]==`string`))}const ce=/* @__PURE__ */ new Set([`.mcp.json`]);function le(e){let t=`@${e.packageName}`,n=`${t}/ui`,r=[];for(let i of e.app)if(!ce.has(i.path)){if(i.path===`package.json`){let a=oe(i.contents),o=se(a.scripts),s=se(a.devDependencies);r.push({path:`apps/web/package.json`,contents:A({...a,name:`${t}/web`,scripts:e.testable?{...o,test:`vitest run`}:o,dependencies:{[n]:`workspace:*`,...se(a.dependencies)},devDependencies:e.testable?{...s,"@testing-library/react":`^16.3.0`,jsdom:`^30.0.0`,vitest:`^5.0.0`}:s})});continue}r.push({path:`apps/web/${i.path}`,contents:i.contents})}e.testable&&r.push({path:`apps/web/vitest.config.ts`,contents:`import { defineConfig } from 'vitest/config'
3
+
4
+ export default defineConfig({
5
+ test: { environment: 'jsdom' },
6
+ })
7
+ `},{path:`apps/web/src/App.test.tsx`,contents:`import { render, screen } from '@testing-library/react'
8
+ import { expect, it } from 'vitest'
9
+ import App from './App'
10
+
11
+ it('renders the app shell and its navigation', () => {
12
+ render(<App />)
13
+ expect(screen.getAllByText('${e.firstLabel.replace(/'/g,`\\'`)}').length).toBeGreaterThan(0)
14
+ })
15
+ `}),r.push({path:`packages/ui/package.json`,contents:A({name:n,private:!0,version:`0.0.0`,type:`module`,exports:{".":`./src/index.ts`},scripts:{typecheck:`tsc --noEmit`},dependencies:{"@cascivo/react":e.reactVersion},peerDependencies:{react:`>=18.0.0`},devDependencies:{"@types/react":`^19.0.0`,typescript:`^5.7.0`}})},{path:`packages/ui/tsconfig.json`,contents:A({compilerOptions:{target:`ES2022`,module:`ESNext`,moduleResolution:`bundler`,jsx:`react-jsx`,strict:!0,noEmit:!0,skipLibCheck:!0},include:[`src`]})},{path:`packages/ui/src/index.ts`,contents:`// The team's own components, shared by every app in the workspace. Build them from
16
+ // @cascivo/react, or copy a cascivo component here to own its source:
17
+ // cd packages/ui && npx cascivo add <name>
18
+ // then export it below and import it in an app as \`import { … } from '${n}'\`.
19
+ export {}
20
+ `},{path:`package.json`,contents:A({name:e.packageName,private:!0,type:`module`,scripts:{dev:`pnpm --filter ./apps/web dev`,build:`vp run -r build`,typecheck:`vp run -r typecheck`,lint:`vp run -r lint`,...e.testable?{test:`vp run -r test`}:{},"format:check":`vp run -r format:check`},devDependencies:{"vite-plus":`^1.1.0`}})},{path:`pnpm-workspace.yaml`,contents:`packages:
21
+ - apps/*
22
+ - packages/*
23
+ # Install scripts pnpm runs: esbuild fetches the binary Vite builds with, workerd is the
24
+ # Workers runtime. allowBuilds is pnpm 11's form, onlyBuiltDependencies pnpm 10's.
25
+ allowBuilds:
26
+ esbuild: true
27
+ workerd: true
28
+ onlyBuiltDependencies:
29
+ - esbuild
30
+ - workerd
31
+ `},{path:`vite.config.ts`,contents:`// Vite+ configuration for the workspace: \`vp run\` caches each package's tasks.
32
+ import { defineConfig } from 'vite-plus'
33
+
34
+ export default defineConfig({
35
+ run: { cache: true },
36
+ })
37
+ `},{path:`.gitignore`,contents:`node_modules
38
+ dist
39
+ .vite
40
+ `},{path:`.github/workflows/ci.yml`,contents:`name: CI
41
+
42
+ on:
43
+ push:
44
+ pull_request:
45
+
46
+ jobs:
47
+ check:
48
+ runs-on: ubuntu-latest
49
+ steps:
50
+ - uses: actions/checkout@v4
51
+ - uses: pnpm/action-setup@v4
52
+ with:
53
+ version: 10
54
+ - uses: actions/setup-node@v4
55
+ with:
56
+ node-version: 22
57
+ cache: pnpm
58
+ - run: pnpm install --frozen-lockfile
59
+ - run: pnpm typecheck
60
+ - run: pnpm lint
61
+ ${e.testable?` - run: pnpm test
62
+ `:``} - run: pnpm build
63
+ `},{path:`AGENTS.md`,contents:`# Agent instructions — workspace
64
+
65
+ A pnpm workspace. Run every command from this directory unless a step says otherwise.
66
+
67
+ - \`apps/web\` is the app. Read \`apps/web/AGENTS.md\` before changing it. Grow it with
68
+ \`npx cascivo app add page "<title>" --block <name>\`, run in \`apps/web\`.
69
+ - \`packages/ui\` (\`${n}\`) holds the team's own components. Copy a cascivo component here to
70
+ own its source (\`cd packages/ui && npx cascivo add <name>\`), and export it from
71
+ \`src/index.ts\`.
72
+ - Checks: \`pnpm typecheck\`, \`pnpm lint\`,${e.testable?" `pnpm test`,":``} \`pnpm build\`. CI runs the same.
73
+ `},{path:`CLAUDE.md`,contents:`@AGENTS.md
74
+ `});let i=e.app.find(e=>e.path===`.mcp.json`);return i&&r.push(i),r}const j=v;function M(e){return e===`yarn`?`yarn`:`${e} install`}function N(e,t){return e===`npm`?`npm run ${t}`:`${e} ${t}`}function P(e,t){return`${e} run ${t}`}const F=[`react-vite`,`astro`,`cloudflare`],I=[`preact`,`react`],L=[`board`,`agent`,`notes`,`import`,`files`,`export`,`usage`,`crud`,`live`,`voice`,`publish`,`webhooks`,`digest`,`search`,`checkout`,`newsletter`,`social`];function R(e){return L.includes(e)}function z(e){return I.includes(e)}function ue(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`section`}function B(e){let t=e.trim().split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)||`Section`;return/^[0-9]/.test(t)?`Section${t}`:t}function V(e){let t=e.trim().split(/[^a-zA-Z0-9]+/).filter(e=>e!==``&&!/^\d+$/.test(e)&&!/^v\d+$/i.test(e)),n=[];for(let e of t){if(n.length>=3||n.length>0&&n.join(` `).length+1+e.length>24)break;n.push(e.charAt(0).toUpperCase()+e.slice(1))}return n.join(` `)||`App`}function H(e){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)||`cascivo-app`}function de(e,t=[]){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=[];for(let[a,o]of e.entries()){let e=o.trim();if(!e)continue;let s=ue(e),c=B(e),l=2;for(;n.has(s)||r.has(c);)s=`${ue(e)}-${l}`,c=`${B(e)}${l}`,l++;n.add(s),r.add(c);let u=t[a];i.push({key:s,label:e,component:c,...u?{block:u}:{}})}return i.length>0?i:[{key:`home`,label:`Home`,component:`Home`}]}function fe(e){let t={name:H(e.name),private:!0,version:`0.0.0`,type:`module`,scripts:{dev:`vite`,build:`tsc && vite build`,preview:`vite preview`,typecheck:`tsc --noEmit`,lint:`eslint .`,format:`prettier --write .`,"format:check":`prettier --check .`},dependencies:{...xe(e),"@cascivo/react":j[`@cascivo/react`],"@cascivo/themes":j[`@cascivo/themes`],"@preact/signals-react":y,react:`^19.0.0`,"react-dom":`^19.0.0`},devDependencies:{"@cascivo/eslint-config":j[`@cascivo/eslint-config`],"@eslint/js":`^9.0.0`,"@types/react":`^19.0.0`,"@types/react-dom":`^19.0.0`,"@vitejs/plugin-react":`^5.0.0`,eslint:`^9.0.0`,"eslint-plugin-react-hooks":`^7.0.0`,prettier:`^3.0.0`,typescript:`^5.7.0`,"typescript-eslint":`^8.0.0`,vite:`^7.0.0`}};return JSON.stringify(t,null,2)+`
75
+ `}function U(e){return JSON.stringify(e,null,2).replace(/\[\n\s+("[^"\n]*"(?:,\n\s+"[^"\n]*")*)\n\s*\]/g,(e,t)=>`[${t.split(/,\n\s+/).join(`, `)}]`)+`
76
+ `}function pe(){return U({compilerOptions:{target:`ES2022`,useDefineForClassFields:!0,lib:[`ES2022`,`DOM`,`DOM.Iterable`],module:`ESNext`,skipLibCheck:!0,moduleResolution:`bundler`,allowImportingTsExtensions:!0,resolveJsonModule:!0,isolatedModules:!0,moduleDetection:`force`,noEmit:!0,jsx:`react-jsx`,strict:!0,noUnusedLocals:!0,noUnusedParameters:!0,noFallthroughCasesInSwitch:!0},include:[`src`]})}function me(){return`import react from '@vitejs/plugin-react'
77
+ import { defineConfig } from 'vite'
78
+
79
+ export default defineConfig({
80
+ plugins: [react()],
81
+ })
82
+ `}function he(e){return`<!doctype html>
83
+ <html lang="en" data-theme="${e.theme}">
84
+ <head>
85
+ <meta charset="UTF-8" />
86
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
87
+ <title>${V(e.name)}</title>
88
+ <style>
89
+ @layer vendor, cascivo.reset, cascivo.base, cascivo.tokens, cascivo.component,
90
+ cascivo.platform, cascivo.theme, cascivo.blocks, cascivo.example, cascivo.override;
91
+ /* cascivo.example is this app's own slot — above the component/blocks layers so your
92
+ styles win, below cascivo.override which stays free for one-off hotfixes. The
93
+ generated AGENTS.md tells the agent to write there, and this statement is what makes
94
+ that legal: a layer used but never declared falls to the end of the cascade and
95
+ beats everything, which is the opposite of what the ordering is for. */
96
+ /* Third-party CSS goes in the low-priority vendor layer so it can't beat cascivo:
97
+ @import url('some-lib/styles.css') layer(vendor); — see docs/THIRD-PARTY-CSS.md */
98
+ @layer cascivo.reset {
99
+ *,
100
+ *::before,
101
+ *::after {
102
+ box-sizing: border-box;
103
+ margin: 0;
104
+ padding: 0;
105
+ }
106
+ }
107
+ @layer cascivo.base {
108
+ html,
109
+ body,
110
+ #root {
111
+ height: 100%;
112
+ }
113
+ }
114
+ </style>
115
+ </head>
116
+ <body>
117
+ <div id="root"></div>
118
+ <script type="module" src="/src/main.tsx"><\/script>
119
+ </body>
120
+ </html>
121
+ `}function ge(){return`import React from 'react'
122
+ import ReactDOM from 'react-dom/client'
123
+ import App from './App'
124
+
125
+ const root = document.getElementById('root')
126
+ if (root) {
127
+ ReactDOM.createRoot(root).render(
128
+ <React.StrictMode>
129
+ <App />
130
+ </React.StrictMode>,
131
+ )
132
+ }
133
+ `}function _e(){return`/// <reference types="vite/client" />
134
+ `}function ve(e){let t=e.map(e=>`import { ${e.component} } from './sections/${e.component}'`).join(`
135
+ `),n=`type Section = ${e.map(e=>`'${e.key}'`).join(` | `)}`,r=n.length<=100?n:`type Section =\n${e.map(e=>` | '${e.key}'`).join(`
136
+ `)}`,i=e.map(e=>` {
137
+ label: '${e.label.replace(/'/g,`\\'`)}',
138
+ active: section.value === '${e.key}',
139
+ onClick: (e) => {
140
+ e.preventDefault()
141
+ section.value = '${e.key}'
142
+ },
143
+ },`).join(`
144
+ `),a=e.map(e=>` {section.value === '${e.key}' && <${e.component} />}`).join(`
145
+ `);return`'use client'
146
+ import { signal, useSignals, type SideNavItem } from '@cascivo/react'
147
+ import { Shell } from './Shell'
148
+ ${t}
149
+
150
+ ${r}
151
+
152
+ const section = signal<Section>('${e[0].key}')
153
+
154
+ export default function App() {
155
+ useSignals()
156
+
157
+ const navItems: SideNavItem[] = [
158
+ ${i}
159
+ ]
160
+
161
+ return (
162
+ <Shell navItems={navItems}>
163
+ ${a}
164
+ </Shell>
165
+ )
166
+ }
167
+ `}function ye(e){return`'use client'
168
+ import { AppShell, ShellHeader, SideNav, type SideNavItem } from '@cascivo/react'
169
+ import type { ReactNode } from 'react'
170
+
171
+ import '@cascivo/themes/${e.theme}.css'
172
+ // No '@cascivo/react/styles.css' here. On a bundler build each component imports its
173
+ // own CSS, so you ship exactly what you use — this app emits well under 100 kB of entry
174
+ // CSS instead of the ~273 kB aggregate sheet. Import the aggregate ONLY if you drop the
175
+ // bundler (CDN / single-file setup). See https://cascivo.com/docs/getting-started.md
176
+ // The theme import above is always required — themes are never automatic.
177
+
178
+ export interface ShellProps {
179
+ /** Side-nav entries. Use \`href\` for a routed app, \`onClick\` for local state. */
180
+ navItems: SideNavItem[]
181
+ children: ReactNode
182
+ }
183
+
184
+ /**
185
+ * App shell: header + side nav + a content slot.
186
+ *
187
+ * Adding a router? Keep this file. Delete \`App.tsx\` and \`src/sections/\`, render
188
+ * \`<Shell navItems={…}>\` from your root route's layout with your \`<Outlet />\` as children,
189
+ * and give each nav item an \`href\` instead of an \`onClick\`.
190
+ *
191
+ * For those hrefs to become real router links, call \`setLinkComponent\` ONCE at startup in
192
+ * \`main.tsx\` — see the "Adding a router" section of README.md for the exact snippet, or
193
+ * https://cascivo.com/docs/using-with-a-router.md for the full recipe.
194
+ */
195
+ export function Shell({ navItems, children }: ShellProps) {
196
+ return (
197
+ ${Te(e,`navItems`)}
198
+ {children}
199
+ </AppShell>
200
+ )
201
+ }
202
+ `}function be(e,t){let n=B(e.block),r=n===e.component?`${n}Block`:n;return`import { ${r===n?n:`${n} as ${r}`} } from '../blocks/${e.block}'
203
+
204
+ ${t} ${e.component}() {
205
+ return <${r} />
206
+ }
207
+ `}function xe(e){let t=new Set((e.blocks??[]).flatMap(e=>e?ne(`block-${e}`).dependencies:[]));return Object.fromEntries([...t].sort().map(e=>{let t=j[e];if(!t)throw Error(`cascivo: no pinned version for ${e}`);return[e,t]}))}function Se(e,t){return[...new Set(e.flatMap(e=>e.block?[e.block]:[]))].flatMap(e=>ie(`block-${e}`,Ce(t)))}function Ce(e){return{brand:V(e.name),appName:e.name.replace(/[\\']/g,``),usageDataset:Qe(e)}}function we(e){return e.block?be(e,`export function`):`import { Card, CardContent, CardHeader, CardTitle, Flex, Heading, Text } from '@cascivo/react'
208
+
209
+ export function ${e.component}() {
210
+ return (
211
+ <Flex gap={6}>
212
+ <Flex gap={2}>
213
+ <Heading level={1}>${e.label}</Heading>
214
+ <Text muted>
215
+ Edit <code>src/sections/${e.component}.tsx</code> to build out this page.
216
+ </Text>
217
+ </Flex>
218
+
219
+ <Card>
220
+ <CardHeader>
221
+ <CardTitle>Get started</CardTitle>
222
+ </CardHeader>
223
+ <CardContent>
224
+ <Text>
225
+ This page is wired into the app shell. Add components with{' '}
226
+ <code>npx cascivo add &lt;component&gt;</code>.
227
+ </Text>
228
+ </CardContent>
229
+ </Card>
230
+ </Flex>
231
+ )
232
+ }
233
+ `}function W(){return`import js from '@eslint/js'
234
+ import tseslint from 'typescript-eslint'
235
+ import reactHooks from 'eslint-plugin-react-hooks'
236
+ import cascivo from '@cascivo/eslint-config'
237
+
238
+ export default [
239
+ { ignores: ['dist/**'] },
240
+ js.configs.recommended,
241
+ // Registers the TypeScript parser and the .ts/.tsx \`files\` patterns. WITHOUT THIS ESLINT
242
+ // LINTS NOTHING: its default \`files\` is **/*.{js,cjs,mjs}, so every file in this app is
243
+ // skipped with "File ignored because no matching configuration was supplied" and the
244
+ // \`lint\` script exits 0 having checked zero files.
245
+ ...tseslint.configs.recommended,
246
+ // NOTE the \`.flat\` — the plugin exports both \`configs['recommended-latest']\` (the legacy
247
+ // eslintrc shape, which applies NOTHING here and reports no error) and this one.
248
+ reactHooks.configs.flat['recommended-latest'],
249
+ // Spread LAST — flat config is last-wins. This turns off \`react-hooks/immutability\`,
250
+ // which reports cascivo's signal writes (\`signal.value = next\`) as errors. That rule
251
+ // fires on the very first \`signal.value = x\` you write, so this is not optional wiring:
252
+ // see https://cascivo.com/docs/using-with-strict-eslint.md
253
+ ...cascivo,
254
+ ]
255
+ `}function Te(e,t){let n=`header={<ShellHeader brand={{ name: '${V(e.name).replace(/'/g,`\\'`)}' }} />}`,r=`nav={<SideNav items={${t}} />}`,i=` <AppShell ${n} ${r}>`;return i.length<=100?i:` <AppShell\n ${n}\n ${r}\n >`}function G(){return JSON.stringify({semi:!1,singleQuote:!0,printWidth:100},null,2)+`
256
+ `}function K(){return`dist
257
+ node_modules
258
+ # Vendored cascivo source is formatted upstream — reformatting it makes every
259
+ # \`cascivo add\` update a merge conflict.
260
+ src/components/ui/
261
+ `}function Ee(){return`node_modules
262
+ dist
263
+ *.local
264
+ .DS_Store
265
+ `}function De(e){return`
266
+ ## Share a preview
267
+
268
+ No Cloudflare account needed. Run \`${N(e.pm??`npm`,`build`)}\`, then either:
269
+
270
+ - drag the \`dist/\` folder onto [Cloudflare Drop](https://www.cloudflare.com/drop/), or
271
+ - from a terminal: \`npx wrangler deploy --temporary --assets dist --name ${H(e.name)} --compatibility-date ${He}\`
272
+
273
+ Either way you get a public URL that lasts 60 minutes. Sign in to Cloudflare within that hour
274
+ to keep it.
275
+ `}function Oe(e){let t=e.pm??`npm`;return`# ${e.name}
276
+
277
+ A [cascivo](https://cascivo.com) app — Vite + React + TypeScript, pre-wired with
278
+ the cascivo app shell, side navigation, and the \`${e.theme}\` theme.
279
+
280
+ ## Develop
281
+
282
+ \`\`\`sh
283
+ ${M(t)}
284
+ ${N(t,`dev`)}
285
+ \`\`\`
286
+
287
+ ## Structure
288
+
289
+ - \`src/Shell.tsx\` — the app shell (header + side nav + content slot). Router-agnostic.
290
+ - \`src/App.tsx\` — nav items and which section is showing
291
+ - \`src/sections/\` — one component per nav item
292
+
293
+ Add more components with \`npx cascivo add <component>\`.
294
+
295
+ ## Adding a router
296
+
297
+ This app switches sections with a signal, not a router. To add one (React Router,
298
+ TanStack Router, …):
299
+
300
+ 1. **Keep \`src/Shell.tsx\`.** Delete \`src/App.tsx\` and \`src/sections/\`.
301
+ 2. Render \`<Shell navItems={…}>\` from your root route's layout, with your \`<Outlet />\`
302
+ as its children.
303
+ 3. Give each nav item an \`href\` instead of \`onClick\`.
304
+ 4. Register your router's Link **once** at startup, in \`src/main.tsx\`:
305
+
306
+ \`\`\`tsx
307
+ import { setLinkComponent } from '@cascivo/react'
308
+ import type { LinkComponentProps } from '@cascivo/react'
309
+ import { Link } from 'react-router'
310
+
311
+ setLinkComponent(({ href, ...rest }: LinkComponentProps) => <Link to={href ?? '#'} {...rest} />)
312
+ \`\`\`
313
+
314
+ That one call makes \`SideNav\`, \`ShellHeader\` and \`Breadcrumb\` render real router links.
315
+ Links you write in page content use \`<Link asChild>\` instead — two kinds of link, two
316
+ mechanisms. Full recipe: https://cascivo.com/docs/using-with-a-router.md
317
+ ${De(e)}`}function ke(e){return`# Agent instructions — ${e.name}
318
+
319
+ This is a [cascivo](https://cascivo.com) app. When generating or editing CSS, follow
320
+ the **layer contract** — cascivo styles live in cascade layers, and layer order beats
321
+ selector specificity.
322
+
323
+ ## CSS layer contract
324
+
325
+ 1. Every declaration goes inside an \`@layer\` block. Unlayered CSS beats all layers
326
+ regardless of specificity — never emit it.
327
+ 2. Never invent layer names. Write only: your app slot \`cascivo.example\` (declared in
328
+ the order statement in \`index.html\`) for page styles, and
329
+ \`@layer cascivo.override { … }\` for hotfixes / one-off overrides — it beats
330
+ everything cascivo ships.
331
+ 3. Never nest layers deeper than the shipped \`cascivo.blocks.<name>\` pattern. For
332
+ sub-elements, use native CSS nesting inside one layer block, not new sublayers.
333
+ 4. Third-party CSS: \`@import url('lib/styles.css') layer(vendor);\` with \`vendor\`
334
+ declared before the cascivo layers. Don't import vendor CSS from JavaScript — route it
335
+ through a CSS file, or use \`@cascivo/vite-plugin\` (\`cascivoLayers\`) to layer it.
336
+ 5. Style with \`--cascivo-*\` tokens, not raw values.
337
+
338
+ This app's declared layer order (in \`index.html\`):
339
+
340
+ \`\`\`css
341
+ @layer vendor, cascivo.reset, cascivo.base, cascivo.tokens, cascivo.component,
342
+ cascivo.platform, cascivo.theme, cascivo.blocks, cascivo.example, cascivo.override;
343
+ \`\`\`
344
+
345
+ ### Worked example — nesting, not new layers
346
+
347
+ \`\`\`css
348
+ @layer cascivo.override {
349
+ .projectCard {
350
+ /* Sub-elements nest inside the one block — no cascivo.card.status sublayer. */
351
+ .statusBadge {
352
+ color: var(--cascivo-color-text-subtle);
353
+ .pulseDot {
354
+ background: var(--cascivo-color-success);
355
+ }
356
+ }
357
+ }
358
+ }
359
+ \`\`\`
360
+
361
+ ## Routing
362
+
363
+ If you add a router, keep \`src/Shell.tsx\` and delete \`src/App.tsx\` + \`src/sections/\`.
364
+
365
+ cascivo links come in **two kinds**, wired two different ways. Do not intercept
366
+ \`onClick\`, and do not hand-wrap nav items:
367
+
368
+ 1. **Config-driven navs** (\`SideNav\`, \`ShellHeader\`, \`Breadcrumb\`, \`Switcher\`) render
369
+ through a module singleton. Register your router's Link once, in \`src/main.tsx\`:
370
+ \`setLinkComponent(({ href, ...rest }: LinkComponentProps) => <Link to={href ?? '#'} {...rest} />)\`
371
+ 2. **Links in page content** use \`asChild\`:
372
+ \`<Link asChild><RouterLink to="/x">x</RouterLink></Link>\`
373
+
374
+ Full recipe: https://cascivo.com/docs/using-with-a-router.md
375
+
376
+ ## Types
377
+
378
+ The vocabulary types are on a subpath: \`import type { Tone } from '@cascivo/react/types'\`
379
+ (also \`Progress\`, \`SpaceStep\`). \`Status.status\` and \`Badge.variant\` use them, so a
380
+ \`Record<MyState, Tone>\` is the supported way to map domain states onto tones. **Never**
381
+ add \`@cascivo/core\` to this app's dependencies — it is transitive here.
382
+
383
+ More: cascivo's machine-readable guide is at https://cascivo.com/llms.txt.
384
+ `}function Ae(e,t){return t===0?`/`:`/${e.key}`}function je(e,t){return t===0?`index.astro`:`${e.key}.astro`}function Me(e){let t={name:H(e.name),private:!0,version:`0.0.0`,type:`module`,scripts:{dev:`astro dev`,build:`astro build`,preview:`astro preview`,typecheck:`astro check`,lint:`eslint .`,format:`prettier --write .`,"format:check":`prettier --check .`},dependencies:{"@astrojs/react":`^5.0.0`,"@cascivo/react":j[`@cascivo/react`],"@cascivo/themes":j[`@cascivo/themes`],"@preact/signals-react":y,astro:`^7.0.0`,react:`^19.0.0`,"react-dom":`^19.0.0`},devDependencies:{"@astrojs/check":`^0.9.0`,"@cascivo/eslint-config":j[`@cascivo/eslint-config`],"@eslint/js":`^9.0.0`,"@types/react":`^19.0.0`,"@types/react-dom":`^19.0.0`,eslint:`^9.0.0`,"eslint-plugin-react-hooks":`^7.0.0`,prettier:`^3.0.0`,typescript:`^5.7.0`,"typescript-eslint":`^8.0.0`}};return JSON.stringify(t,null,2)+`
385
+ `}function Ne(){return`// @ts-check
386
+ import { defineConfig } from 'astro/config'
387
+ import react from '@astrojs/react'
388
+
389
+ export default defineConfig({
390
+ integrations: [react()],
391
+ vite: {
392
+ resolve: {
393
+ // REQUIRED, and the single least obvious line in this app.
394
+ //
395
+ // Vite externalizes node_modules packages in its server build, so an externalized
396
+ // @cascivo/react is imported by Node at runtime and its module graph is never walked
397
+ // — and Astro collects a page's CSS by walking that graph. Without this, SSR'd
398
+ // islands (client:load, client:visible) render with correct class names and no rules
399
+ // anywhere in the output. Nothing warns; it reads as a theming problem.
400
+ //
401
+ // It must be \`resolve.noExternal\`, NOT \`ssr.noExternal\`: Astro prerenders static
402
+ // routes in its own Vite environment, which \`ssr.*\` does not reach.
403
+ // https://cascivo.com/docs/using-with-astro.md
404
+ noExternal: [/^@cascivo\\//],
405
+ },
406
+ },
407
+ })
408
+ `}function Pe(){return JSON.stringify({extends:`astro/tsconfigs/strict`,include:[`.astro/types.d.ts`,`**/*`],exclude:[`dist`],compilerOptions:{jsx:`react-jsx`}},null,2)+`
409
+ `}function Fe(){return`/* Cascade layer order. Must load before any cascivo CSS — see the note in
410
+ src/layouts/Layout.astro. Later layers beat earlier ones regardless of specificity.
411
+
412
+ cascivo.example is this app's own slot: above the component and blocks layers so your
413
+ page styles win, below cascivo.override which stays free for one-off hotfixes.
414
+ Third-party CSS goes in vendor so it cannot beat cascivo:
415
+ @import url('some-lib/styles.css') layer(vendor);
416
+ See https://cascivo.com/docs/third-party-css.md */
417
+ @layer vendor, cascivo.reset, cascivo.base, cascivo.tokens, cascivo.component,
418
+ cascivo.platform, cascivo.theme, cascivo.blocks, cascivo.example, cascivo.override;
419
+
420
+ @layer cascivo.reset {
421
+ *,
422
+ *::before,
423
+ *::after {
424
+ box-sizing: border-box;
425
+ margin: 0;
426
+ padding: 0;
427
+ }
428
+ }
429
+
430
+ @layer cascivo.base {
431
+ html,
432
+ body {
433
+ block-size: 100%;
434
+ }
435
+ }
436
+ `}function Ie(e){return`---
437
+ // Import order matters: the layer statement must be established before any cascivo CSS.
438
+ import '../styles/layers.css'
439
+ import '@cascivo/themes/${e.theme}.css'
440
+
441
+ // No '@cascivo/react/styles.css'. Each component brings its own CSS through the module
442
+ // graph, so you ship only what your pages use. Import the aggregate ONLY if you drop the
443
+ // bundler entirely. The theme import above is always required — themes are never automatic.
444
+
445
+ interface Props {
446
+ title: string
447
+ }
448
+
449
+ const { title } = Astro.props
450
+ ---
451
+
452
+ <!doctype html>
453
+ <html lang="en" data-theme="${e.theme}">
454
+ <head>
455
+ <meta charset="UTF-8" />
456
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
457
+ <title>{title} · ${V(e.name)}</title>
458
+ </head>
459
+ <body>
460
+ <slot />
461
+ </body>
462
+ </html>
463
+ `}function Le(e,t){return`import { AppShell, ShellHeader, SideNav, type SideNavItem } from '@cascivo/react'
464
+ import type { ReactNode } from 'react'
465
+
466
+ const NAV: { label: string; href: string }[] = [
467
+ ${t.map((e,t)=>` { label: '${e.label.replace(/'/g,`\\'`)}', href: '${Ae(e,t)}' },`).join(`
468
+ `)}
469
+ ]
470
+
471
+ export interface ShellProps {
472
+ /** Current route, e.g. \`Astro.url.pathname\`. Marks the matching nav item active. */
473
+ activePath: string
474
+ children: ReactNode
475
+ }
476
+
477
+ /**
478
+ * Header + side nav + a content slot.
479
+ *
480
+ * Nav items carry \`href\`, so navigation is a real page load and Astro's router handles
481
+ * it — there is no client router to register and no \`setLinkComponent\` call to make.
482
+ */
483
+ export function Shell({ activePath, children }: ShellProps) {
484
+ const items: SideNavItem[] = NAV.map((item) => ({
485
+ ...item,
486
+ active: item.href === activePath,
487
+ }))
488
+
489
+ return (
490
+ ${Te(e,`items`)}
491
+ {children}
492
+ </AppShell>
493
+ )
494
+ }
495
+ `}function Re(e){return`import { Card, CardContent, CardHeader, CardTitle, Flex, Heading, Text } from '@cascivo/react'
496
+
497
+ export function ${e.component}() {
498
+ return (
499
+ <Flex gap={6}>
500
+ <Flex gap={2}>
501
+ <Heading level={1}>${e.label}</Heading>
502
+ <Text muted>
503
+ Edit <code>src/components/${e.component}.tsx</code> to build out this page.
504
+ </Text>
505
+ </Flex>
506
+
507
+ <Card>
508
+ <CardHeader>
509
+ <CardTitle>Get started</CardTitle>
510
+ </CardHeader>
511
+ <CardContent>
512
+ <Text>
513
+ This page is server-rendered — no JavaScript ships for it. Add components with{' '}
514
+ <code>npx cascivo add &lt;component&gt;</code>.
515
+ </Text>
516
+ </CardContent>
517
+ </Card>
518
+ </Flex>
519
+ )
520
+ }
521
+ `}function ze(e,t){return`---
522
+ import Layout from '../layouts/Layout.astro'
523
+ import { Shell } from '../components/Shell'
524
+ import { ${e.component} } from '../components/${e.component}'
525
+ ---
526
+
527
+ <Layout title="${e.label}">
528
+ {/* client:load hydrates the shell for its mobile nav drawer. The section below stays
529
+ server-rendered HTML — it is slotted in as children and ships no JS. */}
530
+ <Shell client:load activePath="${Ae(e,t)}">
531
+ <${e.component} />
532
+ </Shell>
533
+ </Layout>
534
+ `}function Be(){return`node_modules
535
+ dist
536
+ .astro
537
+ *.local
538
+ .DS_Store
539
+ `}function Ve(e,t){let n=e.pm??`npm`,r=t.map((e,t)=>`- \`${Ae(e,t)}\` — \`src/pages/${je(e,t)}\``).join(`
540
+ `);return`# ${e.name}
541
+
542
+ A [cascivo](https://cascivo.com) app — Astro + React islands + TypeScript, pre-wired with
543
+ the cascivo app shell, side navigation, and the \`${e.theme}\` theme.
544
+
545
+ ## Develop
546
+
547
+ \`\`\`sh
548
+ ${M(n)}
549
+ ${N(n,`dev`)}
550
+ \`\`\`
551
+
552
+ ## Routes
553
+
554
+ ${r}
555
+
556
+ Add a page by dropping a new \`.astro\` file in \`src/pages/\` — Astro routes it by filename.
557
+ Add it to \`NAV\` in \`src/components/Shell.tsx\` to get a nav entry.
558
+
559
+ ## What hydrates, and what doesn't
560
+
561
+ Only \`Shell\` carries a client directive (\`client:load\`), because its nav drawer is
562
+ interactive on small screens. Everything inside it is slotted in as children and stays
563
+ server-rendered HTML, so a page ships the shell's JavaScript and nothing else.
564
+
565
+ Need a section to be interactive? Give it a directive at the call site in the page:
566
+
567
+ \`\`\`astro
568
+ <${t[0].component} client:visible />
569
+ \`\`\`
570
+
571
+ A component that reads \`signal.value\` during render must also call \`useSignals()\` from
572
+ \`@cascivo/react\` as its first statement — Astro applies no signals transform.
573
+
574
+ ## Styling
575
+
576
+ \`src/styles/layers.css\` declares the cascade layer order and this app's own
577
+ \`cascivo.example\` slot. It is imported **before** the theme in \`src/layouts/Layout.astro\`,
578
+ and that order matters: layers take their position from first appearance, so a statement
579
+ loaded after the theme cannot reorder anything.
580
+
581
+ Add more components with \`npx cascivo add <component>\`.
582
+ ${De(e)}`}const He=`2026-09-01`;function Ue(e){let t=e.pm??`npm`,n=Q(e,`agent`),r=rt(e),i=it(e)===`preact`,a={name:H(e.name),private:!0,version:`0.0.0`,type:`module`,scripts:{dev:`vite`,build:r?`tsc && tsc -p tsconfig.worker.json && vite build`:`tsc && vite build`,preview:`vite preview`,deploy:`${N(t,`build`)} && wrangler deploy`,"deploy:preview":`${N(t,`build`)} && wrangler deploy --temporary`,typecheck:r?`tsc --noEmit && tsc --noEmit -p tsconfig.worker.json`:`tsc --noEmit`,lint:`eslint .`,format:`prettier --write .`,"format:check":`prettier --check .`},dependencies:{"@cascivo/app":j[`@cascivo/app`],...xe(e),"@cascivo/react":j[`@cascivo/react`],"@cascivo/themes":j[`@cascivo/themes`],"@preact/signals-react":y,...i?{preact:`^10.29.0`}:{react:`^19.0.0`,"react-dom":`^19.0.0`},...Q(e,`usage`)||Q(e,`live`)?{"@cascivo/charts":j[`@cascivo/charts`]}:{},...Q(e,`export`)?{"@cloudflare/puppeteer":`^1.4.0`}:{},...Q(e,`notes`)?{"@cascivo/storage":j[`@cascivo/storage`]}:{},...n?{"@ai-sdk/react":`^4.0.0`,"@cascivo/render":j[`@cascivo/render`],"@cloudflare/ai-chat":`^0.12.1`,agents:`^0.26.0`,ai:`^7.0.0`,"workers-ai-provider":`^4.0.0`,zod:`^4.0.0`}:{},...Q(e,`voice`)&&!n?{agents:`^0.26.0`}:{},...Q(e,`publish`)&&!n?{"@cascivo/render":j[`@cascivo/render`]}:{},...Q(e,`checkout`)||Q(e,`newsletter`)?{"@cascivo/email":j[`@cascivo/email`]}:{},...(Q(e,`publish`)||Q(e,`checkout`)||Q(e,`newsletter`))&&i?{"preact-render-to-string":`^6.5.0`}:{}},devDependencies:{"@cascivo/eslint-config":j[`@cascivo/eslint-config`],"@cloudflare/vite-plugin":`^1.62.0`,...r?{"@cloudflare/workers-types":`^5.0.0`}:{},"@eslint/js":`^9.0.0`,"@types/react":`^19.0.0`,"@types/react-dom":`^19.0.0`,...i?{"@babel/core":`^7.0.0`,"@preact/preset-vite":`^2.10.0`,react:`^19.0.0`,"react-dom":`^19.0.0`}:{"@vitejs/plugin-react":`^6.0.0`},eslint:`^9.0.0`,"eslint-plugin-react-hooks":`^7.0.0`,prettier:`^3.0.0`,typescript:`^5.7.0`,"typescript-eslint":`^8.0.0`,vite:`^8.0.0`,wrangler:`^4.143.0`}},o=xt(e);return JSON.stringify(Object.keys(o).length>0?{...a,cloudflare:{bindings:o}}:a,null,2)+`
583
+ `}function We(e){let t=JSON.parse(pe());return t.include=rt(e)?[`src`]:[`src`,`worker`],U(t)}function Ge(){return U({extends:`./tsconfig.json`,compilerOptions:{lib:[`ES2022`],types:[`@cloudflare/workers-types`,`vite/client`]},include:[`worker`]})}function Ke(e,t){let n=Q(t,`agent`),r=tt(t),i=e===`preact`?`import preact from '@preact/preset-vite'`:`import react from '@vitejs/plugin-react'`,a=e===`preact`?`preact()`:`react()`;return`${i}
584
+ import { cascivoRoutes } from '@cascivo/app/vite'
585
+ import { cloudflare } from '@cloudflare/vite-plugin'
586
+ import { defineConfig } from 'vite'
587
+
588
+ ${e===`preact`?`// The source is written against React's types; @preact/preset-vite aliases react and
589
+ // react-dom to preact/compat, so the bundle runs on Preact (about a third of React's JS in
590
+ // this starter: ~27 KB gzip against ~85 KB). To run on React instead, swap this plugin
591
+ // for @vitejs/plugin-react — no source changes.`:n?`// Runs on React: the /assistant page uses the Agents SDK's hooks, which call React 19's
592
+ // use() — preact/compat does not implement it, so this app cannot switch to Preact.`:`// Runs on React. To ship Preact instead (about a third of the JS in this starter), swap
593
+ // this plugin for @preact/preset-vite — it aliases react/react-dom to preact/compat; no
594
+ // source changes.`}
595
+ //
596
+ // cascivoRoutes() writes src/routes.gen.ts from src/routes/ — one file per page.
597
+ // cloudflare() runs worker/index.ts in workerd during \`vite dev\` and builds it with the
598
+ // client, so dev and production execute the same runtime. Request routing is in wrangler.jsonc.${r?`
599
+ //
600
+ // Workers AI has no local mode: with remote bindings on, \`vite dev\` needs a Cloudflare login.
601
+ // So they are off, ${Q(t,`search`)?`and:${[n?`the assistant answers from worker/scripted-model.ts`:``,Q(t,`voice`)?`the voice page uses the stand-ins in worker/scripted-voice.ts`:``,`search runs by keyword, on SQLite full-text search (worker/search.ts)`].filter(Boolean).map(e=>`\n// - ${e}`).join(``)}`:n&&Q(t,`voice`)?`the assistant answers from worker/scripted-model.ts, and the voice
602
+ // page uses the stand-ins in worker/scripted-voice.ts`:n?`and the assistant answers from worker/scripted-model.ts`:`and the voice page uses the stand-ins in worker/scripted-voice.ts`}. Run
603
+ // \`VITE_REAL_AI=1 vite dev\` (after \`wrangler login\`) to use Workers AI.`:``}
604
+ export default defineConfig({
605
+ ${r?` plugins: [
606
+ ${a},
607
+ cascivoRoutes(),
608
+ cloudflare({ remoteBindings: process.env['VITE_REAL_AI'] === '1' }),
609
+ ],`:` plugins: [${a}, cascivoRoutes(), cloudflare()],`}${Q(t,`publish`)?`
610
+ // A published page's HTML links the stylesheets its route needs, found in this manifest
611
+ // (worker/page-html.ts), so the page is styled for readers without JavaScript too.
612
+ build: { manifest: 'asset-manifest.json' },`:``}
613
+ })
614
+ `}function q(e,t,n){let r=`${e}"${t}": [${n.join(`, `)}],`;return r.length<=100?r:`${e}"${t}": [\n${n.map(t=>`${e} ${t},`).join(`
615
+ `)}\n${e}],`}function qe(e){let t=Q(e,`publish`),n=nt(e),r=Q(e,`agent`),i=$(e),a=[...n?[{name:`ROOMS`,className:`SyncRoom`}]:[],...r?[{name:`Assistant`,className:`Assistant`}]:[],...Q(e,`live`)?[{name:`LIVE`,className:`LiveRoom`}]:[],...Q(e,`voice`)?[{name:`Voice`,className:`Voice`}]:[]],o=[...n?[`// ROOMS: one SyncRoom per room (@cascivo/app/sync-server).`]:[],...r?[`// Assistant: one AIChatAgent per conversation; it stores the messages in SQLite.`]:[],...Q(e,`live`)?[`// LIVE: the /ops dashboard's per-second totals (@cascivo/app/live-server).`]:[],...Q(e,`voice`)?[`// Voice: one voice agent per conversation (agents/voice); it stores the transcript.`]:[]];return`// Cloudflare deploy config. \`${P(e.pm??`npm`,`deploy`)}\` builds and ships the SPA and
616
+ // the Worker together. https://developers.cloudflare.com/workers/wrangler/configuration/
617
+ {
618
+ "name": "${H(e.name)}",
619
+ "main": "./worker/index.ts",
620
+ "compatibility_date": "${He}",
621
+ "assets": {
622
+ // Client-side app: an unknown path serves index.html, and the client renders it.
623
+ "not_found_handling": "single-page-application",
624
+ // ${t?`Only the API and published pages reach the Worker; static assets are served
625
+ // without invoking it.`:`Only the API reaches the Worker; static assets are served without invoking it.`}
626
+ "run_worker_first": [${[`"/api/*"`,...i?[`"/agents/*"`]:[],...t?[`"/p/*"`]:[]].join(`, `)}],${t?`
627
+ // The Worker reads index.html through this to put a published page into it.
628
+ "binding": "ASSETS",`:``}
629
+ },
630
+ "observability": { "enabled": true },${a.length>0?`
631
+ ${o.join(`
632
+ `)}
633
+ "durable_objects": {
634
+ ${q(` `,`bindings`,a.map(e=>`{ "name": "${e.name}", "class_name": "${e.className}" }`))}
635
+ },
636
+ ${q(` `,`migrations`,[`{ "tag": "v1", "new_sqlite_classes": [${a.map(e=>`"${e.className}"`).join(`, `)}] }`])}`:``}${Q(e,`files`)||Q(e,`social`)?`
637
+ // ${[Q(e,`files`)?`Uploaded files, and Cloudflare Images for their resized previews`:``,Q(e,`social`)?`Images attached to social posts (worker/social.ts)`:``].filter(Boolean).join(`; `)}.
638
+ ${q(` `,`r2_buckets`,[...Q(e,`files`)?[`{ "binding": "FILES", "bucket_name": "${H(e.name)}-files" }`]:[],...Q(e,`social`)?[`{ "binding": "SOCIAL_MEDIA", "bucket_name": "${H(e.name)}-social-media" }`]:[]])}${Q(e,`files`)?`
639
+ "images": { "binding": "IMAGES" },`:``}`:``}${$e(e)?`
640
+ // ${[Q(e,`files`)?`Uploads`:``,Q(e,`export`)?`exports`:``,Q(e,`publish`)?`published pages`:``,Q(e,`digest`)?`digests sent now`:``,Q(e,`search`)?`search indexing`:``,Q(e,`checkout`)?`checkouts started`:``,Q(e,`newsletter`)?`newsletter sign-ups and composer requests`:``,Q(e,`social`)?`connecting accounts, posts and image uploads`:``,X(e)?`sign-in emails`:``].filter(Boolean).join(`, `).replace(/^./,e=>e.toUpperCase())} per caller: 20 a minute.
641
+ // namespace_id is any number unique within your account:
642
+ // https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/
643
+ ${q(` `,`ratelimits`,[`{ "name": "LIMITER", "namespace_id": "1001", "simple": { "limit": 20, "period": 60 } }`])}`:``}${Je(e)}${Q(e,`digest`)||Q(e,`social`)?`
644
+ // ${[Q(e,`digest`)?`The weekly digest: Mondays at 08:00 UTC (worker/digest.ts)`:``,Q(e,`social`)?`Threads tokens renewed and reconnect reminders sent, daily at 04:17 UTC (worker/social.ts)`:``].filter(Boolean).join(`; `)}.
645
+ "triggers": { "crons": [${[Q(e,`digest`)?`"0 8 * * 1"`:``,Q(e,`social`)?`"${ft}"`:``].filter(Boolean).join(`, `)}] },`:``}${et(e)?`
646
+ // Tables for ${[Q(e,`crud`)?`customers`:``,Q(e,`publish`)?`published pages`:``,Q(e,`webhooks`)?`webhook deliveries`:``,Q(e,`digest`)?`digest runs`:``,Q(e,`search`)?`help articles`:``,Q(e,`checkout`)?`orders`:``,Q(e,`newsletter`)?`newsletter subscribers and issues`:``,Y(e)?`accounts`:``].filter(Boolean).join(`, `)}.
647
+ // No database_id: wrangler creates the database on first deploy, and the Worker applies its
648
+ // own schema on its first query (\`migrate\`).
649
+ ${q(` `,`d1_databases`,[`{ "binding": "DB", "database_name": "${H(e.name)}-db" }`])}`:``}${Q(e,`usage`)?`
650
+ // Every API request is recorded here (worker/index.ts); /usage reads it back.
651
+ "analytics_engine_datasets": [{ "binding": "USAGE", "dataset": "${Qe(e)}" }],`:``}${Ye(e)}${Q(e,`import`)||Q(e,`social`)?`
652
+ // ${[Q(e,`import`)?`The CSV import runs as a Workflow (worker/import-job.ts); its progress is a room.`:``,Q(e,`social`)?`Each scheduled post is a Workflow that waits until it is due (worker/social-post.ts).`:``].filter(Boolean).join(`
653
+ // `)}
654
+ ${q(` `,`workflows`,[...Q(e,`import`)?[`{ "name": "import-job", "binding": "IMPORT_JOB", "class_name": "ImportJob" }`]:[],...Q(e,`social`)?[`{ "name": "${H(e.name)}-social-post", "binding": "SOCIAL_POST", "class_name": "SocialPost" }`]:[]])}`:``}${tt(e)?`
655
+ // Workers AI, which the ${[r?`assistant`:``,Q(e,`voice`)?`voice agent`:``,Q(e,`search`)?`search page`:``].filter(Boolean).join(` and `)} call${[r,Q(e,`voice`),Q(e,`search`)].filter(Boolean).length>1?``:`s`}.
656
+ "ai": { "binding": "AI" },`:``}${Q(e,`search`)?`
657
+ // The help articles' embeddings (worker/search.ts). Create it once before deploying (README).
658
+ ${q(` `,`vectorize`,[`{ "binding": "ARTICLES_INDEX", "index_name": "${H(e.name)}-articles" }`])}`:``}${Q(e,`export`)?`
659
+ // Browser Run: renders pages to PDF/PNG for /api/export.
660
+ "browser": { "binding": "BROWSER" },`:``}${i||Q(e,`export`)?`
661
+ // ${[i?`The Agents SDK`:``,Q(e,`export`)?`Cloudflare's puppeteer`:``].filter(Boolean).join(` and `)} use${i&&Q(e,`export`)?``:`s`} Node.js APIs.
662
+ "compatibility_flags": ["nodejs_compat"],`:``}
663
+ // Add bindings here (KV, D1, R2, Durable Objects, Workers AI) and read them from the
664
+ // \`env\` argument of the Worker's fetch handler.
665
+ }
666
+ `}function Je(e){let t=Q(e,`digest`),n=Q(e,`social`),r=Q(e,`checkout`),i=Q(e,`newsletter`),a=X(e),o=[...e.auth===`access`?[`Cloudflare Access (README). Until both are set, the Worker refuses every request.`]:[],...a?[`Sign-in links go out through Email Service (README). AUTH_FROM must be an address on a`,`domain you have onboarded; until it is set, sign-in fails with a clear error.`]:[],...t?[`The weekly digest (README): who gets it, who sends it, and the deployed app's URL,`,`which the browser opens. Until they are set, each run is recorded as skipped.`]:[],...n?[`Reminders to connect LinkedIn again go out through Email Service from REMINDER_FROM, an`,`address on a domain you have onboarded, with links to APP_URL (README). Until both are`,`set, no reminder is sent.`]:[],...r?[`Receipts for paid orders go out through Email Service from RECEIPT_FROM, an address`,`on a domain you have onboarded (README). Until it is set, no receipt is sent.`]:[],...i?[`The newsletter sends through Amazon SES (README): the region your sending identity is`,`verified in, its From address, and the SNS topic SES reports bounces and complaints to.`]:[]],s=[...e.auth===`access`?[`ACCESS_TEAM_DOMAIN`,`ACCESS_AUD`]:[],...a?[`AUTH_FROM`]:[],...t?[`DIGEST_TO`,`DIGEST_FROM`,`APP_URL`]:[],...n?[`REMINDER_FROM`,...t?[]:[`APP_URL`]]:[],...r?[`RECEIPT_FROM`]:[],...i?[`AWS_REGION`,`NEWSLETTER_FROM`,`SNS_TOPIC_ARN`]:[]];if(s.length===0)return``;let c=s.map(e=>`"${e}": ""`),l=` "vars": { ${c.join(`, `)} },`,u=l.length<=100?l:` "vars": {\n${c.map(e=>` ${e},`).join(`
667
+ `)}\n },`;return`
668
+ ${o.map(e=>` // ${e}`).join(`
669
+ `)}${a||t||r||n?`
670
+ "send_email": [{ "name": "EMAIL" }],`:``}
671
+ ${u}`}function Ye(e){let t=[...Q(e,`live`)?[{comment:[`Events for /ops: POST /api/events sends them, and the Worker's queue handler takes them in`,`batches of up to 100, or whatever arrived within a second.`],binding:`EVENTS`,queue:`${H(e.name)}-events`,consumer:[`"max_batch_size": 100`,`"max_batch_timeout": 1`]}]:[],...Q(e,`newsletter`)?[{comment:[`Newsletter sends (worker/newsletter.ts): one message of 25 readers at a time, so SES`,`is called at a steady pace. A throttled message is retried after 30 seconds.`],binding:`NEWSLETTER`,queue:Ze(e),consumer:[`"max_batch_size": 1`,`"max_concurrency": 1`,`"max_retries": 10`,`"retry_delay": 30`]}]:[]];return t.length===0?``:`
672
+ ${t.flatMap(e=>e.comment.map(e=>` // ${e}`)).join(`
673
+ `)}
674
+ "queues": {
675
+ ${q(` `,`producers`,t.map(e=>`{ "binding": "${e.binding}", "queue": "${e.queue}" }`))}
676
+ "consumers": [
677
+ ${t.map(e=>` {
678
+ "queue": "${e.queue}",
679
+ ${e.consumer.map(e=>` ${e},`).join(`
680
+ `)}
681
+ },`).join(`
682
+ `)}
683
+ ],
684
+ },`}function J(e){return Q(e,`checkout`)&&Y(e)}function Y(e){return X(e)||Z(e)}function X(e){return e.auth===`email`||e.auth===`email,oauth`}function Xe(e){let t=[...new Set((e??``).toLowerCase().split(`,`).map(e=>e.trim()))].filter(Boolean);if(t.length===0)return null;let n=t.sort().join(`,`);return n===`access`||n===`email`||n===`oauth`||n===`email,oauth`?n:`invalid`}function Z(e){return e.auth===`oauth`||e.auth===`email,oauth`}function Ze(e){return`${H(e.name)}-newsletter`}function Q(e,t){return e.examples?.includes(t)??!1}function Qe(e){return`${H(e.name).replace(/[^a-z0-9_]/g,`_`).replace(/^[^a-z_]/,`_$&`)}_usage`}function $e(e){return Q(e,`files`)||Q(e,`export`)||Q(e,`publish`)||Q(e,`digest`)||Q(e,`search`)||Q(e,`checkout`)||Q(e,`newsletter`)||Q(e,`social`)||X(e)}function et(e){return Q(e,`crud`)||Q(e,`publish`)||Q(e,`webhooks`)||Q(e,`digest`)||Q(e,`search`)||Q(e,`checkout`)||Q(e,`newsletter`)||Y(e)}function tt(e){return $(e)||Q(e,`search`)}function $(e){return Q(e,`agent`)||Q(e,`voice`)}function nt(e){return Q(e,`board`)||Q(e,`notes`)||Q(e,`import`)||Q(e,`webhooks`)||Q(e,`checkout`)||Q(e,`newsletter`)}function rt(e){return $(e)||Q(e,`import`)||Q(e,`social`)}function it(e){return e.runtime??(Q(e,`agent`)?`react`:`preact`)}function at(e){let t=Q(e,`import`),n=Q(e,`files`),r=Q(e,`usage`),i=Q(e,`crud`),a=Q(e,`live`),o=Q(e,`publish`),s=Q(e,`webhooks`),c=Q(e,`digest`),l=Q(e,`search`),u=Q(e,`checkout`),d=Q(e,`newsletter`),f=J(e),p=Q(e,`social`);return`import { defineApi, ${t||n||r||i||a||o||s||c||l||u||d||p?`endpoint, `:``}stream } from '@cascivo/app/api'
685
+ ${i?`import { parseTablePage, parseTableQuery } from '@cascivo/app/db'
686
+ `:``}${n?`import { parseStoredFile } from '@cascivo/app/uploads'
687
+ `:``}${t?`import { parseImportRequest, parseStarted } from './import-job'
688
+ `:``}${r?`import { parseUsageReport } from './usage'
689
+ `:``}${i?`import { parseCustomer, parseCustomerInput, parseDeleted } from './customers'
690
+ `:``}${a?`import { ops, parseAccepted } from './ops'
691
+ `:``}${o?`import { parsePage, parsePageInput, parsePageSummary } from './pages'
692
+ `:``}${s?`import { parseDeliveries, parseTestResult } from './webhooks'
693
+ `:``}${c?`import { parseDigestRun, parseDigestRuns } from './digest'
694
+ `:``}${l?`import { parseIndexed, parseSearchQuery, parseSearchResult } from './search'
695
+ `:``}${f?`import { parseBilling, parseRedirect, parseSyncInput } from './billing'
696
+ `:``}${u?`import { parseCheckoutStarted, parseOrder } from './checkout'
697
+ `:``}${d?`import {
698
+ parseConfirmed,
699
+ parseEmailInput,
700
+ parseIssue,
701
+ parseIssueInput,
702
+ parseKeyInput,
703
+ parseOverview,
704
+ parsePreview,
705
+ parseSubscribed,
706
+ parseTokenInput,
707
+ } from './newsletter'
708
+ `:``}${p?`import { parsePostInput, parseScheduledPost, parseSocial } from './social'
709
+ `:``}
710
+ /**
711
+ * The contract between the browser and the Worker. Both import this file: the Worker serves
712
+ * it with \`createHandler\`, the app calls it with \`createClient\`, and a change that breaks
713
+ * either side is a type error. Add an endpoint here, then its handler in worker/index.ts.
714
+ */
715
+
716
+ /** How many ticks one stream sends before it ends. */
717
+ export const TICKS_PER_STREAM = 30
718
+
719
+ export interface Tick {
720
+ n: number
721
+ /** ISO timestamp, set by the Worker. */
722
+ at: string
723
+ }
724
+
725
+ /**
726
+ * Parses one streamed tick. It crosses the network, so it is checked rather than cast —
727
+ * \`JSON.parse\` returns \`any\`, and \`as Tick\` would prove nothing.
728
+ */
729
+ export function parseTick(raw: unknown): Tick {
730
+ if (typeof raw === 'object' && raw !== null) {
731
+ const { n, at } = raw as Record<string, unknown>
732
+ if (typeof n === 'number' && typeof at === 'string') return { n, at }
733
+ }
734
+ throw new Error('Malformed tick')
735
+ }
736
+
737
+ export const api = defineApi({
738
+ ticks: stream({ method: 'GET', path: '/api/ticks', event: parseTick }),${t?`
739
+ // Starts a CSV import; returns the job id to watch (src/import-page.ts).
740
+ startImport: endpoint({
741
+ method: 'POST',
742
+ path: '/api/import',
743
+ input: parseImportRequest,
744
+ output: parseStarted,
745
+ }),`:``}${n?`
746
+ // The stored files (the uploads themselves are \`handleUploads\` in the Worker).
747
+ listFiles: endpoint({
748
+ method: 'GET',
749
+ path: '/api/files',
750
+ output: (raw) => {
751
+ if (!Array.isArray(raw)) throw new Error('Expected a list of files')
752
+ return raw.map(parseStoredFile)
753
+ },
754
+ }),`:``}${r?`
755
+ // The last 24 hours of API usage, read from Analytics Engine by the Worker.
756
+ usage: endpoint({ method: 'GET', path: '/api/usage', output: parseUsageReport }),`:``}${a?`
757
+ // Events for the /ops dashboard, at most 100 at a time, onto the EVENTS queue.
758
+ sendEvents: endpoint({
759
+ method: 'POST',
760
+ path: '/api/events',
761
+ input: ops.parseEvents,
762
+ output: parseAccepted,
763
+ }),`:``}${o?`
764
+ // Publishes a view as a page (checked against the manifests), and reads one back.
765
+ publishPage: endpoint({
766
+ method: 'POST',
767
+ path: '/api/pages',
768
+ input: parsePageInput,
769
+ output: parsePageSummary,
770
+ }),
771
+ getPage: endpoint({ method: 'GET', path: '/api/pages/:slug', output: parsePage }),`:``}${s?`
772
+ // The last 50 webhook deliveries (they arrive at /api/webhooks/github, signed).
773
+ listDeliveries: endpoint({ method: 'GET', path: '/api/webhooks', output: parseDeliveries }),
774
+ // Signs a sample delivery with WEBHOOK_SECRET and runs it through the same path.
775
+ sendTestDelivery: endpoint({
776
+ method: 'POST',
777
+ path: '/api/webhook-test',
778
+ output: parseTestResult,
779
+ }),`:``}${c?`
780
+ // The weekly digest's recent runs, and one run now (the Cron Trigger runs it on Mondays).
781
+ digestRuns: endpoint({ method: 'GET', path: '/api/digest/runs', output: parseDigestRuns }),
782
+ runDigest: endpoint({ method: 'POST', path: '/api/digest/run', output: parseDigestRun }),`:``}${l?`
783
+ // Help articles by meaning (Vectorize), or by keyword in vite dev.
784
+ search: endpoint({
785
+ method: 'POST',
786
+ path: '/api/search',
787
+ input: parseSearchQuery,
788
+ output: parseSearchResult,
789
+ }),
790
+ // Embeds every article into the Vectorize index.
791
+ indexArticles: endpoint({ method: 'POST', path: '/api/search/index', output: parseIndexed }),`:``}${u?`
792
+ // Opens a Stripe Checkout page for the product; the browser goes to its url.
793
+ startCheckout: endpoint({ method: 'POST', path: '/api/checkout', output: parseCheckoutStarted }),
794
+ // An order, checked with Stripe while it is pending (Stripe's webhook settles it too).
795
+ getOrder: endpoint({ method: 'GET', path: '/api/orders/:id', output: parseOrder }),`:``}${f?`
796
+ // The signed-in user's subscription (worker/billing.ts), and the ways to change it.
797
+ getBilling: endpoint({ method: 'GET', path: '/api/billing', output: parseBilling }),
798
+ startSubscription: endpoint({
799
+ method: 'POST',
800
+ path: '/api/billing/subscribe',
801
+ output: parseRedirect,
802
+ }),
803
+ syncBilling: endpoint({
804
+ method: 'POST',
805
+ path: '/api/billing/sync',
806
+ input: parseSyncInput,
807
+ output: parseBilling,
808
+ }),
809
+ openBillingPortal: endpoint({
810
+ method: 'POST',
811
+ path: '/api/billing/portal',
812
+ output: parseRedirect,
813
+ }),`:``}${d?`
814
+ // Signing up sends a confirmation link; only confirmed readers get issues.
815
+ subscribe: endpoint({
816
+ method: 'POST',
817
+ path: '/api/newsletter/subscribe',
818
+ input: parseEmailInput,
819
+ output: parseSubscribed,
820
+ }),
821
+ confirmSubscription: endpoint({
822
+ method: 'POST',
823
+ path: '/api/newsletter/confirm',
824
+ input: parseTokenInput,
825
+ output: parseConfirmed,
826
+ }),
827
+ // The composer's calls, each carrying NEWSLETTER_KEY.
828
+ newsletterOverview: endpoint({
829
+ method: 'POST',
830
+ path: '/api/newsletter/overview',
831
+ input: parseKeyInput,
832
+ output: parseOverview,
833
+ }),
834
+ previewIssue: endpoint({
835
+ method: 'POST',
836
+ path: '/api/newsletter/preview',
837
+ input: parseIssueInput,
838
+ output: parsePreview,
839
+ }),
840
+ sendIssue: endpoint({
841
+ method: 'POST',
842
+ path: '/api/newsletter/issues',
843
+ input: parseIssueInput,
844
+ output: parseIssue,
845
+ }),`:``}${i?`
846
+ // One page of customers for DataTable's query (sort, search, filters, page).
847
+ customers: endpoint({
848
+ method: 'POST',
849
+ path: '/api/customers/query',
850
+ input: parseTableQuery,
851
+ output: (raw) => parseTablePage(raw, parseCustomer),
852
+ }),
853
+ createCustomer: endpoint({
854
+ method: 'POST',
855
+ path: '/api/customers',
856
+ input: parseCustomerInput,
857
+ output: parseCustomer,
858
+ }),
859
+ updateCustomer: endpoint({
860
+ method: 'PUT',
861
+ path: '/api/customers/:id',
862
+ input: parseCustomerInput,
863
+ output: parseCustomer,
864
+ }),
865
+ deleteCustomer: endpoint({ method: 'DELETE', path: '/api/customers/:id', output: parseDeleted }),`:``}${p?`
866
+ // The signed-in user's connected accounts and posts (worker/social.ts).
867
+ getSocial: endpoint({ method: 'GET', path: '/api/social', output: parseSocial }),
868
+ schedulePost: endpoint({
869
+ method: 'POST',
870
+ path: '/api/social/posts',
871
+ input: parsePostInput,
872
+ output: parseScheduledPost,
873
+ }),
874
+ cancelPost: endpoint({
875
+ method: 'POST',
876
+ path: '/api/social/posts/:id/cancel',
877
+ output: parseScheduledPost,
878
+ }),`:``}
879
+ })
880
+ `}function ot(e){let t=nt(e),n=Q(e,`agent`),r=Q(e,`import`),i=Q(e,`files`),a=Q(e,`export`),o=Q(e,`usage`),s=Q(e,`crud`),c=Q(e,`live`),l=Q(e,`voice`),u=Q(e,`publish`),d=Q(e,`webhooks`),f=Q(e,`digest`),p=Q(e,`search`),m=Q(e,`checkout`),h=Q(e,`newsletter`),g=J(e),_=et(e),v=$(e),y=$e(e),b=e.auth===`access`,x=X(e),S=Z(e),C=Y(e),w=Q(e,`social`),T=[...b?[`requireAccess`]:[],...y?[`clientIp`,`rateLimit`]:[]],ee=t||v||i||a||b||c||y||u||C,te=v||i||a||b||y||d||u||m||h||C,E=[...r?[`job-`]:[],...d?[`webhooks$`]:[],...m?[`order-`]:[],...h?[`issue-`]:[]],D=[...d?[`/api/webhooks/`]:[],...m?[`/api/stripe/`]:[],...h?[`/api/sns/`]:[]],O=h?[`/api/newsletter/subscribe`,`/api/newsletter/confirm`,`/api/newsletter/unsubscribe`]:[],k=[...D,...O];return`${o?`import type { AnalyticsDataset } from '@cascivo/app/analytics'
881
+ `:``}${_?`import type { Database } from '@cascivo/app/db'
882
+ `:``}${a?`import { handleExport } from '@cascivo/app/export'
883
+ `:``}import { createHandler${u?`, HttpError`:``} } from '@cascivo/app/api'
884
+ ${C?`import { ${x?`handleAuth, `:``}requireUser } from '@cascivo/app/auth-server'\n`:``}${S?`import { github, google, linkedin } from '@cascivo/app/oauth'
885
+ import type { OAuthProvider } from '@cascivo/app/oauth'
886
+ import { handleOAuth } from '@cascivo/app/oauth-server'
887
+ `:``}${T.length>0||d||C?`import { ${[...T,`guardResponse`].sort().join(`, `)} } from '@cascivo/app/guard'\n${y?`import type { RateLimiter } from '@cascivo/app/guard'
888
+ `:``}`:``}${r?`import { jobReporter } from '@cascivo/app/jobs-server'
889
+ `:``}${i?`import { handleUploads, listUploads } from '@cascivo/app/uploads-server'
890
+ import type { ImageResizer, UploadBucket } from '@cascivo/app/uploads-server'
891
+ `:``}${c?`import { recordLive } from '@cascivo/app/live-server'
892
+ import type { LiveBatch, LiveQueue } from '@cascivo/app/live-server'
893
+ `:``}${t||c?`import { roomResponse } from '@cascivo/app/sync-server'
894
+ import type { RoomNamespace } from '@cascivo/app/sync-server'
895
+ `:``}${a?`import puppeteer from '@cloudflare/puppeteer'
896
+ import type { BrowserWorker } from '@cloudflare/puppeteer'
897
+ `:``}${v?`import { routeAgentRequest } from 'agents'
898
+ `:``}import { api, TICKS_PER_STREAM } from '../src/api'
899
+ import type { Tick } from '../src/api'
900
+ ${r?`import { importJob } from '../src/import-job'
901
+ `:``}${i?`import { uploads } from '../src/upload-policy'
902
+ `:``}${o?`import { usageMetrics } from '../src/usage'
903
+ import { usageReport } from './usage'
904
+ `:``}${c?`import { OPS_ROOM, ops } from '../src/ops'
905
+ `:``}${x?`import { sendSignInLink } from './auth'
906
+ import type { SignInSender } from './auth'
907
+ `:``}${s?`import * as customerStore from './customers'
908
+ `:``}${u?`import * as pageStore from './pages'\nimport { renderPageHtml } from './page-html'\nimport type { Assets } from './page-html'\n${a?`import { pagePreview } from './page-preview'
909
+ `:``}`:``}${d?`import * as webhookStore from './webhooks'
910
+ import { DELIVERIES_ROOM } from '../src/webhooks'
911
+ `:``}${f?`import * as digestJob from './digest'
912
+ import type { DigestSender } from './digest'
913
+ `:``}${p?`import * as articleSearch from './search'\nimport type { ${v?``:`Embedder, `}VectorIndex } from './search'\n`:``}${g?`import * as billingStore from './billing'
914
+ `:``}${w?`import * as socialStore from './social'
915
+ import type { ReminderSender, SocialMediaBucket, SocialPostParams } from './social'
916
+ `:``}${m?`import * as orderStore from './checkout'
917
+ import type { ReceiptSender } from './checkout'
918
+ import { ORDER_ID, orderRoom } from '../src/checkout'
919
+ `:``}${h?`import * as newsletterStore from './newsletter'
920
+ import type { NewsletterBatch, NewsletterQueue } from './newsletter'
921
+ import { ISSUE_ID, issueRoom } from '../src/newsletter'
922
+ `:``}${t?`
923
+ // The Durable Object class behind every room. wrangler.jsonc binds it as ROOMS, and it must be
924
+ // exported from the Worker's main module.
925
+ export { SyncRoom } from '@cascivo/app/sync-server'
926
+ `:``}${n?`
927
+ // The Durable Object behind /assistant: one per conversation (worker/assistant.ts).
928
+ export { Assistant } from './assistant'
929
+ `:``}${l?`
930
+ // The Durable Object behind /voice: one per conversation (worker/voice.ts).
931
+ export { Voice } from './voice'
932
+ `:``}${c?`
933
+ // The Durable Object behind /ops: the last two minutes, per second (src/ops.ts).
934
+ export { LiveRoom } from '@cascivo/app/live-server'
935
+ `:``}${r?`
936
+ // The Workflow behind /import (worker/import-job.ts), bound as IMPORT_JOB.
937
+ export { ImportJob } from './import-job'
938
+ `:``}${w?`
939
+ // The Workflow behind each scheduled post (worker/social-post.ts), bound as SOCIAL_POST.
940
+ export { SocialPost } from './social-post'
941
+ `:``}
942
+ /**
943
+ * Add bindings (KV, D1, R2, Durable Objects, Workers AI) in wrangler.jsonc and type them
944
+ * here; every handler receives them as \`env\`.
945
+ */
946
+ ${t||v||i||a||o||_||b||c||C||w||d||f||p||m||h?`export interface Env {${v?`
947
+ /** Workers AI, bound in wrangler.jsonc. */
948
+ AI: Ai`:p?`
949
+ /** Workers AI, bound in wrangler.jsonc. */
950
+ AI: Embedder`:``}${p?`
951
+ ARTICLES_INDEX: VectorIndex`:``}${t?`
952
+ ROOMS: RoomNamespace<unknown>`:``}${r?`
953
+ IMPORT_JOB: Workflow<{ csv: string }>`:``}${i?`
954
+ FILES: UploadBucket
955
+ IMAGES: ImageResizer`:``}${a?`
956
+ BROWSER: BrowserWorker`:``}${o?`
957
+ USAGE: AnalyticsDataset
958
+ /** Secrets for reading Analytics Engine back (see README). */
959
+ CF_ACCOUNT_ID?: string
960
+ CF_API_TOKEN?: string`:``}${_?`
961
+ DB: Database`:``}${u?`
962
+ ASSETS: Assets`:``}${c?`
963
+ LIVE: RoomNamespace<unknown>
964
+ EVENTS: LiveQueue`:``}${y?`
965
+ LIMITER: RateLimiter`:``}${b?`
966
+ /** Set in wrangler.jsonc (see README). */
967
+ ACCESS_TEAM_DOMAIN: string
968
+ ACCESS_AUD: string`:``}${d?`
969
+ /** The webhook signing secret: \`wrangler secret put WEBHOOK_SECRET\` (.dev.vars locally). */
970
+ WEBHOOK_SECRET: string`:``}${x||f||m||w?`\n EMAIL: ${[x?`SignInSender`:``,f?`DigestSender`:``,m?`ReceiptSender`:``,w?`ReminderSender`:``].filter(Boolean).join(` & `)}`:``}${x?`
971
+ /** The From address of sign-in emails, set in wrangler.jsonc. */
972
+ AUTH_FROM: string`:``}${S?`
973
+ /** Sign-in with GitHub, Google and LinkedIn: \`wrangler secret put\` (.dev.vars locally). A provider is
974
+ * offered once both its id and secret are set; AUTH_SECRET seals the sign-in state. */
975
+ AUTH_SECRET?: string
976
+ GITHUB_CLIENT_ID?: string
977
+ GITHUB_CLIENT_SECRET?: string
978
+ GOOGLE_CLIENT_ID?: string
979
+ GOOGLE_CLIENT_SECRET?: string
980
+ LINKEDIN_CLIENT_ID?: string
981
+ LINKEDIN_CLIENT_SECRET?: string`:w?`
982
+ /** Seals connected accounts' tokens, and LinkedIn's app: \`wrangler secret put\` (.dev.vars
983
+ * locally). LinkedIn is offered once both its values are set. */
984
+ AUTH_SECRET?: string
985
+ LINKEDIN_CLIENT_ID?: string
986
+ LINKEDIN_CLIENT_SECRET?: string`:``}${w?`
987
+ /** Bluesky: an ES256 private JWK (README); unset, the app is a public client. */
988
+ BLUESKY_PRIVATE_JWK?: string
989
+ /** A Buffer app client (README); Buffer is offered once its id is set. */
990
+ BUFFER_CLIENT_ID?: string
991
+ BUFFER_CLIENT_SECRET?: string
992
+ /** A Meta app with the Threads use case (README); Threads is offered once both are set. */
993
+ THREADS_APP_ID?: string
994
+ THREADS_APP_SECRET?: string
995
+ SOCIAL_POST: Workflow<SocialPostParams>
996
+ SOCIAL_MEDIA: SocialMediaBucket
997
+ /** Reconnect reminders (worker/social.ts), set in wrangler.jsonc. */
998
+ REMINDER_FROM: string`+(f?``:`
999
+ APP_URL: string`):``}${f?`
1000
+ /** The weekly digest (worker/digest.ts), set in wrangler.jsonc. */
1001
+ DIGEST_TO: string
1002
+ DIGEST_FROM: string
1003
+ APP_URL: string`:``}${m?`
1004
+ /** The From address of receipts, set in wrangler.jsonc. */
1005
+ RECEIPT_FROM: string
1006
+ /** Stripe secrets: \`wrangler secret put\` (.dev.vars locally). Unset until you add them. */
1007
+ STRIPE_SECRET_KEY?: string
1008
+ STRIPE_WEBHOOK_SECRET?: string`:``}${h?`
1009
+ NEWSLETTER: NewsletterQueue
1010
+ /** The newsletter (worker/newsletter.ts), set in wrangler.jsonc. */
1011
+ AWS_REGION: string
1012
+ NEWSLETTER_FROM: string
1013
+ SNS_TOPIC_ARN: string
1014
+ /** Secrets: \`wrangler secret put\` (.dev.vars locally). Unset until you add them. */
1015
+ AWS_ACCESS_KEY_ID?: string
1016
+ AWS_SECRET_ACCESS_KEY?: string
1017
+ NEWSLETTER_KEY?: string`:``}
1018
+ }`:`// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- bindings are added as members
1019
+ export interface Env {}`}
1020
+
1021
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
1022
+ ${S?`
1023
+ /** The sign-in providers with both an id and a secret set; the others are not offered. */
1024
+ function oauthProviders(env: Env): OAuthProvider[] {
1025
+ const providers: OAuthProvider[] = []
1026
+ if (env.GITHUB_CLIENT_ID && env.GITHUB_CLIENT_SECRET) {
1027
+ providers.push(
1028
+ github({ clientId: env.GITHUB_CLIENT_ID, clientSecret: env.GITHUB_CLIENT_SECRET }),
1029
+ )
1030
+ }
1031
+ if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) {
1032
+ providers.push(
1033
+ google({ clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET }),
1034
+ )
1035
+ }
1036
+ if (env.LINKEDIN_CLIENT_ID && env.LINKEDIN_CLIENT_SECRET) {
1037
+ providers.push(
1038
+ linkedin({ clientId: env.LINKEDIN_CLIENT_ID, clientSecret: env.LINKEDIN_CLIENT_SECRET }),
1039
+ )
1040
+ }
1041
+ return providers
1042
+ }
1043
+ `:``}${y?`
1044
+ /**
1045
+ * Requests that each count against LIMITER:
1046
+ ${[x?`a sign-in email`:``,f?`a digest sent now (it starts a browser)`:``,p?`indexing the articles (it embeds every one)`:``,m?`a checkout started (it creates a Stripe session and an order)`:``,g?`a subscription checkout or billing portal opened`:``,h?`a newsletter sign-up (it sends an email), and each use of the newsletter key`:``,i?`a new upload (not each part of one)`:``,a?`an export`:``,u?`a published page`:``,w?`connecting an account (Mastodon registers the app with the server), or a post`:``].filter(Boolean).map(e=>` * - ${e}`).join(`
1047
+ `)}
1048
+ */
1049
+ function countsAgainstLimit(request: Request): boolean {
1050
+ const url = new URL(request.url)${p?`
1051
+ if (url.pathname === '/api/search/index') return request.method === 'POST'`:``}${f?`
1052
+ if (url.pathname === '/api/digest/run') return request.method === 'POST'`:``}${m?`
1053
+ if (url.pathname === '/api/checkout') return request.method === 'POST'`:``}${g?`
1054
+ if (url.pathname === '/api/billing/subscribe' || url.pathname === '/api/billing/portal') {
1055
+ return request.method === 'POST'
1056
+ }`:``}${h?`
1057
+ if (/^\\/api\\/newsletter\\/(subscribe|overview|preview|issues)$/.test(url.pathname)) {
1058
+ return request.method === 'POST'
1059
+ }`:``}${x?`
1060
+ if (url.pathname === '/api/auth/start') return request.method === 'POST'`:``}${w?`
1061
+ if (/^\\/api\\/connections\\/[a-z-]+$/.test(url.pathname)) return request.method === 'GET'
1062
+ if (url.pathname === '/api/social/posts') return request.method === 'POST'
1063
+ if (url.pathname.startsWith('/api/social/images')) return request.method !== 'GET'`:``}${u?`
1064
+ if (url.pathname === '/api/pages') return request.method === 'POST'`:``}${i?`
1065
+ if (url.pathname === uploads.path) {
1066
+ const step = url.searchParams.get('multipart')
1067
+ return (request.method === 'PUT' && step === null) || step === 'start'
1068
+ }`:``}
1069
+ return ${a?`url.pathname === '/api/export'`:`false`}
1070
+ }
1071
+ `:``}
1072
+ /**
1073
+ * One handler per endpoint in src/api.ts, typed from it. A stream handler is an async
1074
+ * generator: each \`yield\` is one server-sent event, and returning ends the stream. When the
1075
+ * client disconnects, \`signal\` aborts.
1076
+ */
1077
+ const handleApi = createHandler<typeof api, Env>(api, {
1078
+ ticks: async function* ({ signal }) {
1079
+ for (let n = 1; n <= TICKS_PER_STREAM && !signal.aborted; n++) {
1080
+ const tick: Tick = { n, at: new Date().toISOString() }
1081
+ yield tick
1082
+ await sleep(1000)
1083
+ }
1084
+ },${r?`
1085
+ // The job's room exists (as "queued") before the Workflow starts, so the page has
1086
+ // something to show at once.
1087
+ startImport: async ({ body, env }) => {
1088
+ const id = crypto.randomUUID()
1089
+ await jobReporter(importJob, env.ROOMS, id).queued()
1090
+ await env.IMPORT_JOB.create({ id, params: { csv: body.csv } })
1091
+ return { id }
1092
+ },`:``}${i?`
1093
+ listFiles: ({ env }) => listUploads(env.FILES),`:``}${o?`
1094
+ usage: ({ env }) =>
1095
+ usageReport(
1096
+ env.CF_ACCOUNT_ID && env.CF_API_TOKEN
1097
+ ? { accountId: env.CF_ACCOUNT_ID, apiToken: env.CF_API_TOKEN }
1098
+ : null,
1099
+ ),`:``}${s?`
1100
+ customers: ({ body, env }) => customerStore.listCustomers(env.DB, body),
1101
+ createCustomer: ({ body, env }) => customerStore.createCustomer(env.DB, body),
1102
+ updateCustomer: ({ params, body, env }) => customerStore.updateCustomer(env.DB, params.id, body),
1103
+ deleteCustomer: ({ params, env }) => customerStore.deleteCustomer(env.DB, params.id),`:``}${u?`
1104
+ publishPage: ({ body, env }) => pageStore.publishPage(env.DB, body),
1105
+ getPage: ({ params, env }) => pageStore.getPage(env.DB, params.slug),`:``}${d?`
1106
+ listDeliveries: ({ env }) => webhookStore.listDeliveries(env.DB),
1107
+ sendTestDelivery: ({ request, env }) => webhookStore.sendTestDelivery(request.url, env),`:``}${p?`
1108
+ search: ({ body, env }) => articleSearch.search(env, body.q),
1109
+ indexArticles: ({ env }) => articleSearch.indexArticles(env),`:``}${m?`
1110
+ startCheckout: ({ request, env }) => orderStore.startCheckout(env, new URL(request.url).origin),
1111
+ getOrder: ({ params, request, env }) =>
1112
+ orderStore.getOrder(env, params.id, new URL(request.url).origin),`:``}${g?`
1113
+ getBilling: ({ request, env }) => billingStore.getBilling(env, request),
1114
+ startSubscription: ({ request, env }) =>
1115
+ billingStore.startSubscription(env, request, new URL(request.url).origin),
1116
+ syncBilling: ({ body, request, env }) => billingStore.syncBilling(env, request, body.sessionId),
1117
+ openBillingPortal: ({ request, env }) =>
1118
+ billingStore.openPortal(env, request, new URL(request.url).origin),`:``}${h?`
1119
+ subscribe: ({ body, request, env }) =>
1120
+ newsletterStore.subscribe(env, body.email, new URL(request.url).origin),
1121
+ confirmSubscription: ({ body, env }) => newsletterStore.confirm(env, body.token),
1122
+ newsletterOverview: ({ body, env }) => newsletterStore.overview(env, body.key),
1123
+ previewIssue: ({ body, request, env }) =>
1124
+ newsletterStore.preview(env, body, new URL(request.url).origin),
1125
+ sendIssue: ({ body, request, env }) =>
1126
+ newsletterStore.sendIssue(env, body, new URL(request.url).origin),`:``}${w?`
1127
+ getSocial: ({ request, env }) => socialStore.getSocial(env, request),
1128
+ schedulePost: ({ body, request, env }) => socialStore.schedulePost(env, request, body),
1129
+ cancelPost: ({ params, request, env }) => socialStore.cancelPost(env, request, params.id),`:``}${f?`
1130
+ digestRuns: ({ env }) => digestJob.listRuns(env.DB),
1131
+ runDigest: ({ request, env }) =>
1132
+ digestJob.runDigest(
1133
+ env,
1134
+ () => puppeteer.launch(env.BROWSER),
1135
+ 'manual',
1136
+ new URL(request.url).origin,
1137
+ ),`:``}${c?`
1138
+ // Each event is placed by the Worker's clock: a browser's is not trusted to say when.
1139
+ sendEvents: async ({ body, env }) => {
1140
+ const at = Date.now()
1141
+ if (body.length > 0) {
1142
+ await env.EVENTS.sendBatch(body.map((event) => ({ body: { at, values: event.values } })))
1143
+ }
1144
+ return { accepted: body.length }
1145
+ },`:``}
1146
+ })
1147
+ ${o?`
1148
+ /** Every API request, recorded in Analytics Engine; src/usage.ts names the columns. */
1149
+ async function handleAndRecord(request: Request, env: Env): Promise<Response> {
1150
+ const started = Date.now()
1151
+ const response = await handleApi(request, env)
1152
+ usageMetrics.write(env.USAGE, {
1153
+ path: new URL(request.url).pathname,
1154
+ method: request.method,
1155
+ status: response.status,
1156
+ duration_ms: Date.now() - started,
1157
+ })
1158
+ return response
1159
+ }
1160
+ `:``}
1161
+ // wrangler.jsonc routes only ${v?`/api/* and /agents/*`:`/api/*`} here; everything else is a static asset or index.html.
1162
+ export default {
1163
+ ${ee?` ${te?`async `:``}fetch(request: Request, env: Env): Promise<Response>${te?``:` | Response`} {${b?`
1164
+ // Cloudflare Access is in front of the app (README); this refuses a request that came
1165
+ // around it (straight to *.workers.dev, say). \`vite dev\` has no Access, so not there.
1166
+ if (!import.meta.env.DEV) {
1167
+ try {
1168
+ await requireAccess(request, {
1169
+ teamDomain: env.ACCESS_TEAM_DOMAIN,
1170
+ audience: env.ACCESS_AUD,
1171
+ })
1172
+ } catch (error) {
1173
+ return guardResponse(error)
1174
+ }
1175
+ }`:``}${y?`
1176
+ if (countsAgainstLimit(request)) {
1177
+ try {
1178
+ await rateLimit(env.LIMITER, clientIp(request))
1179
+ } catch (error) {
1180
+ return guardResponse(error)
1181
+ }
1182
+ }`:``}${C?`${x?`
1183
+ // Sign-in links and sessions: /api/auth/* is answered here (worker/auth.ts sends mail).
1184
+ const signIn = await handleAuth(env.DB, {
1185
+ sendLink: (email, url) => sendSignInLink(env.EMAIL, env.AUTH_FROM, email, url),
1186
+ exposeLink: import.meta.env.DEV,
1187
+ })(request)
1188
+ if (signIn) return signIn`:``}${S?`
1189
+ // Sign-in with GitHub, Google and LinkedIn: /api/auth/oauth/* (and /me, /signout). A failed
1190
+ // sign-in lands on /account with ?error=.
1191
+ const signInWith = await handleOAuth(env.DB, {
1192
+ secret: env.AUTH_SECRET ?? '',
1193
+ providers: oauthProviders(env),
1194
+ errorPath: '/account',
1195
+ })(request)
1196
+ if (signInWith) return signInWith`:``}
1197
+ // Every other API write needs a signed-in user; reads stay public.${D.length>0?`
1198
+ // Webhooks carry a signature instead of a session, and are checked by it.`:``}${O.length>0?`
1199
+ // Newsletter readers sign up, confirm and unsubscribe without an account.`:``}
1200
+ if (${k.length>0?`
1201
+ request.method !== 'GET' &&
1202
+ request.method !== 'HEAD' &&${k.map(e=>`\n !new URL(request.url).pathname.startsWith('${e}')`).join(` &&`)}
1203
+ `:`request.method !== 'GET' && request.method !== 'HEAD'`}) {
1204
+ try {
1205
+ await requireUser(env.DB, request)
1206
+ } catch (error) {
1207
+ return guardResponse(error)
1208
+ }
1209
+ }${w?`
1210
+ // The accounts a user connects to post with (worker/social.ts): /api/connections/*, and
1211
+ // the client metadata Bluesky's servers read.
1212
+ const blueskyClient = socialStore.blueskyClient(env, request)
1213
+ if (blueskyClient) return blueskyClient
1214
+ const connected = await socialStore.connections(env)(request)
1215
+ if (connected) return connected
1216
+ // Images for posts: the user's own uploads, and the signed links Threads and Buffer fetch.
1217
+ const image =
1218
+ (await socialStore.images(env, request)) ?? (await socialStore.media(env, request))
1219
+ if (image) return image`:``}`:``}${v?`
1220
+ // /agents/<agent>/<conversation>: the WebSocket ${[n?`useAgent()`:``,l?`VoiceClient`:``].filter(Boolean).join(` or `)} opens.
1221
+ const agent = await routeAgentRequest(request, env)
1222
+ if (agent) return agent`:``}${i?`
1223
+ // Uploads into R2 and the files they stored.${b?``:` Anyone can upload: see README.`}
1224
+ const upload = await handleUploads(uploads, env.FILES, { images: env.IMAGES })(request)
1225
+ if (upload) return upload`:``}${a?`
1226
+ // /api/export?page=/report&format=pdf — each export starts a browser.
1227
+ const exported = await handleExport(request, { launch: () => puppeteer.launch(env.BROWSER) })
1228
+ if (exported) return exported`:``}${c?`
1229
+ // The /ops dashboard's room: browsers watch it, and only the queue handler writes to it.
1230
+ if (new URL(request.url).pathname === '/api/live') {
1231
+ return roomResponse(request, env.LIVE, OPS_ROOM, { readOnly: true })
1232
+ }`:``}${u?`
1233
+ // A published page: its HTML carries the page's title, description and content, for link
1234
+ // previews and readers without JavaScript (worker/page-html.ts). An unknown slug gets the
1235
+ // app itself, which says so.
1236
+ const pagePath = new URL(request.url).pathname
1237
+ const published = /^\\/p\\/([a-z0-9]{10})$/.exec(pagePath)
1238
+ if (published && request.method === 'GET') {
1239
+ try {
1240
+ const page = await pageStore.getPage(env.DB, published[1]!)${a?"\n const image = new URL(`/api/pages/${page.slug}/preview.png`, request.url).href\n return await renderPageHtml(request, page, env.ASSETS, image)":`
1241
+ return await renderPageHtml(request, page, env.ASSETS, null)`}
1242
+ } catch (error) {
1243
+ if (!(error instanceof HttpError)) throw error
1244
+ return env.ASSETS.fetch(request)
1245
+ }
1246
+ }${a?`
1247
+ // Its link-preview image, rendered once by Browser Run (worker/page-preview.ts).
1248
+ const preview = /^\\/api\\/pages\\/([a-z0-9]{10})\\/preview\\.png$/.exec(pagePath)
1249
+ if (preview && request.method === 'GET') {
1250
+ try {
1251
+ return await pagePreview(env.DB, preview[1]!, new URL(request.url).origin, () =>
1252
+ puppeteer.launch(env.BROWSER),
1253
+ )
1254
+ } catch (error) {
1255
+ return guardResponse(error)
1256
+ }
1257
+ }`:``}`:``}${d?`
1258
+ const path = new URL(request.url).pathname
1259
+ // Signed deliveries from GitHub (worker/webhooks.ts); a bad signature is a 401.
1260
+ if (path === webhookStore.GITHUB_WEBHOOK_PATH && request.method === 'POST') {
1261
+ try {
1262
+ return await webhookStore.receiveGithub(request, env)
1263
+ } catch (error) {
1264
+ return guardResponse(error)
1265
+ }
1266
+ }
1267
+ // New deliveries, pushed to the /webhooks page: it may watch, never write.
1268
+ if (path === '/api/webhooks/live') {
1269
+ return roomResponse(request, env.ROOMS, DELIVERIES_ROOM, { readOnly: true })
1270
+ }`:``}${m?`
1271
+ const checkoutPath = new URL(request.url).pathname
1272
+ // Stripe's webhook (worker/checkout.ts); a bad signature is a 401.
1273
+ if (checkoutPath === orderStore.STRIPE_WEBHOOK_PATH && request.method === 'POST') {
1274
+ try {
1275
+ return await orderStore.receiveStripe(request, env${g?`, billingStore.billingHooks(env)`:``})
1276
+ } catch (error) {
1277
+ return guardResponse(error)
1278
+ }
1279
+ }
1280
+ // An order's page watches its room for what Stripe reports: it may watch, never write.
1281
+ const orderLive = /^\\/api\\/orders\\/([^/]+)\\/live$/.exec(checkoutPath)
1282
+ if (orderLive && ORDER_ID.test(orderLive[1]!)) {
1283
+ return roomResponse(request, env.ROOMS, orderRoom(orderLive[1]!), { readOnly: true })
1284
+ }`:``}${h?`
1285
+ const newsletterPath = new URL(request.url).pathname
1286
+ // One-click unsubscribe (RFC 8058) and the unsubscribe page's button.
1287
+ if (newsletterPath === '/api/newsletter/unsubscribe' && request.method === 'POST') {
1288
+ return newsletterStore.unsubscribe(request, env)
1289
+ }
1290
+ // SES bounces and complaints, delivered by SNS (worker/newsletter.ts); verified by signature.
1291
+ if (newsletterPath === '/api/sns/ses' && request.method === 'POST') {
1292
+ try {
1293
+ return await newsletterStore.receiveFeedback(request, env)
1294
+ } catch (error) {
1295
+ return guardResponse(error)
1296
+ }
1297
+ }
1298
+ // An issue's sending progress, for the composer: it may watch, never write.
1299
+ const issueLive = /^\\/api\\/newsletter\\/issues\\/([^/]+)\\/live$/.exec(newsletterPath)
1300
+ if (issueLive && ISSUE_ID.test(issueLive[1]!)) {
1301
+ return roomResponse(request, env.ROOMS, issueRoom(issueLive[1]!), { readOnly: true })
1302
+ }`:``}${Q(e,`board`)||Q(e,`notes`)?`
1303
+ const room = /^\\/api\\/rooms\\/([^/]+)$/.exec(new URL(request.url).pathname)${E.length>0?`
1304
+ // Rooms only the server writes are watched read-only at their own routes, never opened
1305
+ // here: ${[r?`a job's progress`:``,d?`webhook deliveries`:``,m?`orders`:``,h?`newsletter issues`:``].filter(Boolean).join(`, `)}.
1306
+ if (room && !/^(${E.join(`|`)})/.test(room[1]!)) {
1307
+ return roomResponse(request, env.ROOMS, room[1]!)
1308
+ }`:`
1309
+ if (room) return roomResponse(request, env.ROOMS, room[1]!)`}`:``}${r?`
1310
+ // A job's progress: the browser may watch its room, never write to it.
1311
+ const job = /^\\/api\\/jobs\\/([\\w-]{1,60})$/.exec(new URL(request.url).pathname)
1312
+ if (job) {
1313
+ return roomResponse(request, env.ROOMS, importJob.roomName(job[1]!), { readOnly: true })
1314
+ }`:``}
1315
+ return ${o?`handleAndRecord`:`handleApi`}(request, env)
1316
+ },`:` fetch: ${o?`handleAndRecord`:`handleApi`},`}${f&&w?`
1317
+ // The Cron Triggers in wrangler.jsonc, told apart by their schedule.
1318
+ async scheduled(event: { cron: string }, env: Env): Promise<void> {
1319
+ // Threads tokens renewed, and reminders for those that cannot be (worker/social.ts).
1320
+ if (event.cron === '${ft}') {
1321
+ await socialStore.renewConnections(env)
1322
+ return socialStore.remindExpiring(env)
1323
+ }
1324
+ // The weekly digest, recorded whatever happens.
1325
+ await digestJob.runDigest(env, () => puppeteer.launch(env.BROWSER), 'cron')
1326
+ },`:f?`
1327
+ // The Cron Trigger in wrangler.jsonc: the weekly digest, recorded whatever happens.
1328
+ async scheduled(_event: unknown, env: Env): Promise<void> {
1329
+ await digestJob.runDigest(env, () => puppeteer.launch(env.BROWSER), 'cron')
1330
+ },`:w?`
1331
+ // The Cron Trigger in wrangler.jsonc: Threads tokens renewed, then reminders for the ones
1332
+ // that cannot be (LinkedIn).
1333
+ async scheduled(_event: unknown, env: Env): Promise<void> {
1334
+ await socialStore.renewConnections(env)
1335
+ await socialStore.remindExpiring(env)
1336
+ },`:``}${c&&h?`
1337
+ // Two queues, one handler: each batch says which queue it came from. A throw retries it.
1338
+ async queue(batch: LiveBatch & NewsletterBatch & { queue: string }, env: Env): Promise<void> {
1339
+ // NEWSLETTER: one message of readers at a time, through SES (worker/newsletter.ts).
1340
+ if (batch.queue === '${Ze(e)}') return newsletterStore.deliver(env, batch)
1341
+ // EVENTS: into the dashboard's room.
1342
+ await recordLive(
1343
+ ops,
1344
+ env.LIVE,
1345
+ OPS_ROOM,
1346
+ batch.messages.map((message) => message.body),
1347
+ )
1348
+ },`:c?`
1349
+ // The EVENTS queue, a batch at a time, into the dashboard's room. A throw retries the batch.
1350
+ async queue(batch: LiveBatch, env: Env): Promise<void> {
1351
+ await recordLive(
1352
+ ops,
1353
+ env.LIVE,
1354
+ OPS_ROOM,
1355
+ batch.messages.map((message) => message.body),
1356
+ )
1357
+ },`:h?`
1358
+ // The NEWSLETTER queue: one message of readers at a time, through SES
1359
+ // (worker/newsletter.ts). A throw retries the message; readers already sent are skipped.
1360
+ async queue(batch: NewsletterBatch, env: Env): Promise<void> {
1361
+ await newsletterStore.deliver(env, batch)
1362
+ },`:``}
1363
+ }
1364
+ `}function st(e,t){return t===0?`/`:`/${e.key}`}function ct(e,t){return t===0?`index.tsx`:`${e.key}.tsx`}function lt(e,t,n){let r=[...e.map((e,t)=>({label:e.label,href:st(e,t)})),...t.flatMap(e=>ne(e).nav)].map(e=>` {
1365
+ label: '${e.label.replace(/'/g,`\\'`)}',
1366
+ href: '${e.href}',
1367
+ active: path === '${e.href}',
1368
+ },`).join(`
1369
+ `),i=Q(n,`export`);return`import { RouterView } from '@cascivo/app'
1370
+ ${i?`import { isExporting } from '@cascivo/app/export'
1371
+ `:``}import { Spinner, useSignals, type SideNavItem } from '@cascivo/react'
1372
+ import { router } from './router'
1373
+ import { Shell } from './Shell'
1374
+
1375
+ export default function App() {
1376
+ useSignals()
1377
+ const path = router.pathname.value
1378
+
1379
+ // \`href\`s, not click handlers: main.tsx registers the router's Link, so these navigate
1380
+ // client-side while middle-click and "open in new tab" still work.
1381
+ const navItems: SideNavItem[] = [
1382
+ ${r}
1383
+ ]
1384
+ ${i?`
1385
+ // Rendered by /api/export: the page alone, without the shell (which gave it its padding).
1386
+ if (isExporting()) {
1387
+ return (
1388
+ <div style={{ padding: 'var(--cascivo-space-8)' }}>
1389
+ <RouterView router={router} fallback={<Spinner label="Loading" />} />
1390
+ </div>
1391
+ )
1392
+ }
1393
+ `:``}
1394
+ return (
1395
+ <Shell navItems={navItems}>
1396
+ <RouterView router={router} fallback={<Spinner label="Loading" />} />
1397
+ </Shell>
1398
+ )
1399
+ }
1400
+ `}function ut(e){return`import { Flex, Heading, Text } from '@cascivo/react'
1401
+ import { LiveCard } from '../LiveCard'
1402
+
1403
+ export default function ${e.component}() {
1404
+ return (
1405
+ <Flex gap={6}>
1406
+ <Flex gap={2}>
1407
+ <Heading level={1}>${e.label}</Heading>
1408
+ <Text muted>
1409
+ Edit <code>src/routes/index.tsx</code> to build out this page.
1410
+ </Text>
1411
+ </Flex>
1412
+ <LiveCard />
1413
+ </Flex>
1414
+ )
1415
+ }
1416
+ `}function dt(e,t){return we(e).replace(`export function ${e.component}()`,`export default function ${e.component}()`).replace(`src/sections/${e.component}.tsx`,`src/routes/${ct(e,t)}`)}const ft=`17 4 * * *`;function pt(e){let t=X(e),n=Z(e),r=t?n?`Continue with GitHub, Google or LinkedIn, or get a one-time link by email. No password.`:`No password: we email you a link that signs you in once.`:`Continue with GitHub, Google or LinkedIn. No password.`;return`import {
1417
+ Alert,
1418
+ Button,
1419
+ Card,
1420
+ CardContent,
1421
+ Flex,
1422
+ Heading,${t?`
1423
+ Input,
1424
+ Link,`:``}
1425
+ Spinner,
1426
+ Text,
1427
+ signal,
1428
+ useSignals,
1429
+ } from '@cascivo/react'
1430
+ ${t?`import type { FormEvent } from 'react'
1431
+ `:``}import { auth } from '../auth'${n?`
1432
+ import { router } from '../router'`:``}
1433
+ ${t?`
1434
+ const sentTo = signal<string | null>(null)
1435
+ /** Set only in \`vite dev\`, where no email is sent: the link to open instead. */
1436
+ const devLink = signal<string | null>(null)
1437
+ const failure = signal<string | null>(null)
1438
+ const sending = signal(false)
1439
+
1440
+ async function start(event: FormEvent<HTMLFormElement>): Promise<void> {
1441
+ event.preventDefault()
1442
+ const email = new FormData(event.currentTarget).get('email')
1443
+ if (typeof email !== 'string') return
1444
+ failure.value = null
1445
+ sending.value = true
1446
+ try {
1447
+ const { link } = await auth.start(email)
1448
+ sentTo.value = email
1449
+ devLink.value = link
1450
+ } catch (error) {
1451
+ failure.value = error instanceof Error ? error.message : 'Could not send the link'
1452
+ } finally {
1453
+ sending.value = false
1454
+ }
1455
+ }
1456
+ `:``}${n?`
1457
+ const LABELS: Record<string, string> = { github: 'GitHub', google: 'Google', linkedin: 'LinkedIn' }
1458
+
1459
+ /** The providers the Worker offers: those with an id and a secret set (README). */
1460
+ const providers = signal<string[] | null>(null)
1461
+ auth.providers().then(
1462
+ (list) => {
1463
+ providers.value = list
1464
+ },
1465
+ () => {
1466
+ providers.value = []
1467
+ },
1468
+ )
1469
+
1470
+ /** Why the last sign-in with a provider failed: the Worker sends it back as \`?error=\`. */
1471
+ const REASONS: Record<string, string> = {
1472
+ denied: 'You did not allow access, so you are not signed in.',
1473
+ expired: 'The sign-in took too long, or started in another browser. Try again.',
1474
+ state_mismatch: 'That sign-in did not match the one this browser started. Try again.',
1475
+ provider_error: 'The provider did not confirm who you are. Try again, or use another way in.',
1476
+ identity_in_use: 'That account is already linked to another user here.',
1477
+ }
1478
+ `:``}
1479
+ export default function Account() {
1480
+ useSignals()
1481
+ const user = auth.user.value${n?`
1482
+ const reason = new URLSearchParams(router.search.value).get('error')`:``}
1483
+
1484
+ if (user === undefined) return <Spinner label="Loading" />
1485
+ if (user) {
1486
+ return (
1487
+ <Flex gap={4}>
1488
+ <Heading level={1}>Account</Heading>
1489
+ <Card>
1490
+ <CardContent>
1491
+ <Flex gap={3}>
1492
+ <Text>{user.email ? \`Signed in as \${user.email}\` : 'Signed in'}</Text>
1493
+ <Flex direction="horizontal">
1494
+ <Button variant="secondary" onClick={() => void auth.signOut()}>
1495
+ Sign out
1496
+ </Button>
1497
+ </Flex>
1498
+ </Flex>
1499
+ </CardContent>
1500
+ </Card>
1501
+ </Flex>
1502
+ )
1503
+ }
1504
+ return (
1505
+ <Flex gap={4}>
1506
+ <Flex gap={1}>
1507
+ <Heading level={1}>Sign in</Heading>
1508
+ ${`<Text muted>${r}</Text>`.length+8>100?`<Text muted>\n ${r}\n </Text>`:`<Text muted>${r}</Text>`}
1509
+ </Flex>${n?`
1510
+ {reason ? (
1511
+ <Alert variant="destructive" title="Not signed in">
1512
+ {REASONS[reason] ?? 'Sign-in failed. Try again.'}
1513
+ </Alert>
1514
+ ) : null}
1515
+ {providers.value === null ? (
1516
+ <Spinner label="Loading" />
1517
+ ) : providers.value.length === 0 ? (
1518
+ <Alert variant="info" title="No provider is set up yet">
1519
+ Set GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET, or the GOOGLE_ pair, in .dev.vars (README).
1520
+ </Alert>
1521
+ ) : (
1522
+ <Flex direction="horizontal" gap={2} wrap>
1523
+ {providers.value.map((id) => (
1524
+ // A plain link: the Worker redirects to the provider, and back here afterwards.
1525
+ <Button key={id} asChild variant="secondary">
1526
+ <a href={auth.signInUrl(id, '/account')}>Continue with {LABELS[id] ?? id}</a>
1527
+ </Button>
1528
+ ))}
1529
+ </Flex>
1530
+ )}`:``}${t?`
1531
+ {sentTo.value ? (
1532
+ <Alert variant="success" title="Check your email">
1533
+ We sent a sign-in link to {sentTo.value}. It works once, for 15 minutes.
1534
+ </Alert>
1535
+ ) : null}
1536
+ {devLink.value ? (
1537
+ <Alert variant="info" title="vite dev sends no email">
1538
+ <Link href={devLink.value}>Open the sign-in link</Link>
1539
+ </Alert>
1540
+ ) : null}
1541
+ {failure.value ? (
1542
+ <Alert variant="destructive" title="Not sent">
1543
+ {failure.value}
1544
+ </Alert>
1545
+ ) : null}
1546
+ <form onSubmit={(event) => void start(event)}>
1547
+ <Flex direction="horizontal" align="end" gap={2} wrap>
1548
+ <Input name="email" type="email" label="Email" autoComplete="email" required />
1549
+ <Button type="submit" loading={sending.value}>
1550
+ Email me a link
1551
+ </Button>
1552
+ </Flex>
1553
+ </form>`:``}
1554
+ </Flex>
1555
+ )
1556
+ }
1557
+ `}function mt(){return`${K()}# Rewritten by @cascivo/app/vite whenever a route file changes.
1558
+ src/routes.gen.ts
1559
+ `}function ht(){return`node_modules
1560
+ dist
1561
+ .wrangler
1562
+ .dev.vars*
1563
+ !.dev.vars.example
1564
+ *.local
1565
+ .DS_Store
1566
+ `}function gt(e){let t=e.pm??`npm`,n=it(e);return`# ${e.name}
1567
+
1568
+ A [cascivo](https://cascivo.com) app on Cloudflare: a client-rendered
1569
+ ${n===`preact`?`Preact`:`React`} app and its API, deployed as one Worker.
1570
+ There is no server rendering; the browser gets the app, and \`/api/*\` reaches the Worker.
1571
+
1572
+ ## Develop
1573
+
1574
+ \`\`\`sh
1575
+ ${M(t)}
1576
+ ${N(t,`dev`)}
1577
+ \`\`\`
1578
+
1579
+ \`vite dev\` runs \`worker/index.ts\` in workerd, the same runtime as production, via
1580
+ \`@cloudflare/vite-plugin\`.
1581
+
1582
+ ## Deploy
1583
+
1584
+ \`\`\`sh
1585
+ npx wrangler login # once
1586
+ ${P(t,`deploy`)}
1587
+ \`\`\`
1588
+
1589
+ ## Share a preview (no account)
1590
+
1591
+ \`\`\`sh
1592
+ ${P(t,`deploy:preview`)}
1593
+ \`\`\`
1594
+
1595
+ This builds the app, then deploys it to a temporary Cloudflare account with
1596
+ \`wrangler deploy --temporary\`. You need no sign-up. It prints two URLs:
1597
+
1598
+ - **A public \`workers.dev\` URL** for the app.
1599
+ - **A claim URL.** Open it and sign in within 60 minutes to keep the deployment; otherwise it is deleted.
1600
+
1601
+ It works only while wrangler is logged out. If you are logged in, use \`deploy\` instead.
1602
+ A temporary account supports Workers, static assets, KV, D1 and Durable Objects. It does not
1603
+ support Workers AI, R2, Workflows or Browser Run.${$(e)?` So a preview serves the app, but its ${Q(e,`agent`)?`assistant`:`voice page`} cannot reach the model: deploy it\nto your own account for that.`:``}
1604
+
1605
+ ## Structure
1606
+
1607
+ - \`src/routes/\` — one file per page. \`index.tsx\` is \`/\`, \`settings.tsx\` is
1608
+ \`/settings\`, \`c/[id].tsx\` is \`/c/:id\` (it receives \`params.id\`), \`404.tsx\` is
1609
+ everything else. \`src/routes.gen.ts\` is rewritten from this folder; do not edit it.
1610
+ - \`src/api.ts\` — the API contract both sides import: endpoints, their paths, and parsers
1611
+ for what crosses the network.
1612
+ - \`worker/index.ts\` — the API's handlers, typed from \`src/api.ts\`. Add bindings (KV,
1613
+ D1, R2, Durable Objects, Workers AI) in \`wrangler.jsonc\`; handlers receive them as \`env\`.
1614
+ - \`src/live.ts\` + \`src/LiveCard.tsx\` — a streaming endpoint read through the typed
1615
+ client into signals.
1616
+ - \`src/App.tsx\` — the nav (real \`href\`s) and the \`RouterView\`.
1617
+ - \`src/Shell.tsx\` — the app shell (header + side nav + content slot).
1618
+
1619
+ Persist client state with \`persistedSignal\` from \`@cascivo/storage\` (localStorage or
1620
+ IndexedDB).${Q(e,`board`)?"\n\n## Board (multiplayer)\n\n`/board` is a shared board. Open it in two windows: notes, edits and cursors sync live.\n\n- `src/board.ts` — `connectRoom('/api/rooms/<name>')` from `@cascivo/app/sync`; `room.map('notes', parseNote)`\n is a signal every visitor shares, and `room.presence` carries cursors.\n- `worker/index.ts` — exports `SyncRoom`, one Durable Object per room, and routes\n `/api/rooms/:name` to it (bound as `ROOMS` in `wrangler.jsonc`).\n- `/board?room=team` is a separate board.\n\nEach path (one note) is last-writer-wins in the order the room receives writes, so two people\nediting the same note at once settle on one value; editing different notes never collides.\nDurable Objects work on a temporary account, so `deploy:preview` shares a live board with\nno Cloudflare account.":``}${Q(e,`notes`)?"\n\n## Notes (local-first)\n\n`/notes` keeps working when the connection drops. Edits are saved on this device and sync\nwhen the room is reachable again; a badge shows how many are still waiting.\n\n- `src/notes.ts` — `connectRoom(url, { storage: indexedDBDriver() })`: the room's last\n state and every unconfirmed edit are kept in IndexedDB, so offline edits survive a reload\n or a closed tab and go out on the next connection. `room.unsynced` counts them. (Opening\n the app with no network at all also needs its files cached, by a service worker.)\n- The list is `/notes?list=<name>`. Without one, each browser makes its own and remembers\n it; open the same `?list=` on another device to sync with it.\n- It uses the same `SyncRoom` Durable Object as any other room (`ROOMS` in\n `wrangler.jsonc`). To query notes across lists, override `SyncRoom.onWrite` and mirror\n each write into D1.\n\nA note is last-writer-wins: an edit made offline replaces whatever the note held when it\narrives. Edits to different notes never collide.":``}${Q(e,`import`)?"\n\n## Import (background job)\n\n`/import` runs a CSV import as a Cloudflare Workflow and shows its progress live.\n\n- `worker/import-job.ts` — `ImportJob`, the Workflow. Each `step.do` is retried on its own\n and its result kept, so a failure or a deploy resumes the job where it was. Put your writes\n in `importContacts`.\n- `src/import-job.ts` — the job (`defineJob` from `@cascivo/app/jobs`): its steps and the\n parser for its result, shared by both sides.\n- Progress is a read-only room: the Workflow reports with `jobReporter`\n (`@cascivo/app/jobs-server`), and the page watches `/api/jobs/:id` with `watchJob`. The job\n id is in the URL, so a reload or another tab picks the job back up.\n\nReport from inside a `step.do`: a Workflow replays `run()` from the top after each step, and\na report outside one would run again. Workflows run in `vite dev` locally, but not on a\ntemporary account, so `deploy:preview` serves the page without starting imports.":``}${Q(e,`files`)?`
1621
+
1622
+ ## Files (uploads)
1623
+
1624
+ \`/files\` uploads into R2 through the Worker, with progress, and shows resized previews.
1625
+
1626
+ - \`src/upload-policy.ts\` — what the app accepts (types, size), shared by both sides: the page
1627
+ checks a file before sending it, and the Worker enforces the same policy. SVG and HTML are
1628
+ refused by design; served from your origin they would run script.
1629
+ - \`worker/index.ts\` — \`handleUploads\` (\`@cascivo/app/uploads-server\`) stores uploads, in
1630
+ parts above 16 MiB, under keys the Worker chooses, and serves them back with headers that
1631
+ stop any file running script. \`?w=320\` returns a WebP preview from Cloudflare Images.
1632
+ - \`src/files.ts\` — \`startUpload\` gives each file progress and status signals.
1633
+
1634
+ Each caller (by IP) may start 20 uploads a minute (\`ratelimits\` in \`wrangler.jsonc\`).${e.auth?``:"\n**It has no auth.** Anyone who can reach the app can upload: put Cloudflare Access in front of\nit (`--auth access`), add accounts (`--auth email`), or check who is asking in\n`worker/index.ts` before `handleUploads` runs."} Create the bucket once before deploying:
1635
+ \`npx wrangler r2 bucket create ${H(e.name)}-files\`. R2 and Images do not run on a
1636
+ temporary account.`:``}${Q(e,`export`)?'\n\n## Report (PDF and PNG export)\n\n`/report` has "Download PDF" and "Download PNG" buttons. The Worker renders the page in\nCloudflare\'s Browser Run and returns the file.\n\n- `worker/index.ts` — `handleExport` (`@cascivo/app/export`) serves\n `/api/export?page=/report&format=pdf`. It opens the page at this app\'s own origin with\n `?export=1`, waits for the network to go quiet, and prints it. Only paths of this app\n outside `/api/` can be exported.\n- `src/App.tsx` — `isExporting()` drops the shell, so the file holds the page alone.\n- For a scheduled report, call `exportPage` from a Cron Trigger and attach the PDF to an\n email (`sendEmail` from `@cascivo/email` takes `attachments`).\n\nThe browser opens the page without the visitor\'s cookies, so a page that needs a session\nrenders signed out. Each export starts a browser session, which is billed, so each caller\n(by IP) may start 20 a minute (`ratelimits` in `wrangler.jsonc`). In `vite dev` Browser Run starts a local Chrome (downloaded on\nfirst use); it does not run on a temporary account.':``}${Q(e,`live`)?`
1637
+
1638
+ ## Ops (live dashboard)
1639
+
1640
+ \`/ops\` charts orders, revenue and errors per second, and every open copy of the page moves
1641
+ together as events arrive.
1642
+
1643
+ - \`src/ops.ts\` — \`defineLive\` (\`@cascivo/app/live\`): the metrics, and two minutes of
1644
+ per-second history.
1645
+ - \`worker/index.ts\` — \`POST /api/events\` puts events on the \`EVENTS\` queue. The \`queue\`
1646
+ handler adds each batch into a \`LiveRoom\` Durable Object with \`recordLive\`, which keeps
1647
+ per-second totals and sends each change to the browsers watching \`/api/live\` (read-only).
1648
+ - \`src/routes/ops.tsx\` — \`watchLive\` gives the window as a signal; the page sends simulated
1649
+ traffic while its switch is on. Real producers are anything with the queue binding: another
1650
+ Worker, a cron, a webhook handler.
1651
+
1652
+ A new viewer, or one back from a dropped connection, starts with the whole window. Delivery is
1653
+ at least once: a batch retried after a lost reply counts twice. \`/api/events\` has no auth, so
1654
+ anyone can move the numbers: check who is sending before real use (\`--auth access\` puts
1655
+ Cloudflare Access in front of the Worker). Create the queue once before deploying:
1656
+ \`npx wrangler queues create ${H(e.name)}-events\`.`:``}${Q(e,`usage`)?"\n\n## Usage (analytics)\n\nEvery API request is recorded in Workers Analytics Engine, and `/usage` charts the last\n24 hours: requests per hour, the busiest routes, errors and latency.\n\n- `src/usage.ts` — `defineMetrics` (`@cascivo/app/analytics`) names the columns once\n (`path`, `method`, `status`, `duration_ms`), so writes and queries never disagree about\n which blob is which.\n- `worker/index.ts` — `handleAndRecord` writes one data point per API request.\n- `worker/usage.ts` — the queries, over Analytics Engine's SQL API.\n\nWriting needs only the binding. **Reading needs two secrets**, because the SQL API is HTTP\nwith an account token:\n\n```sh\nnpx wrangler secret put CF_ACCOUNT_ID\nnpx wrangler secret put CF_API_TOKEN # a token with Account Analytics: Read\n```\n\nFor `vite dev`, put both in `.dev.vars`. Data written locally is not in your account's\ndataset, so in development the charts show what your deployed app recorded. Until the secrets\nexist, the page says what to set.":``}${Q(e,`search`)?`
1657
+
1658
+ ## Search (by meaning)
1659
+
1660
+ \`/search\` finds help articles by what a question means: "how do I get my money back" finds
1661
+ Refunds, though they share no words. Each article is embedded with Workers AI
1662
+ (\`@cf/baai/bge-base-en-v1.5\`) into a Vectorize index; a question is embedded the same way
1663
+ and matched against it.
1664
+
1665
+ - \`worker/articles.ts\` — the articles, seeded into D1. Replace them with your own content.
1666
+ - \`worker/search.ts\` — \`search\` and \`indexArticles\`. "Index articles" on the page embeds
1667
+ every article; Vectorize applies writes a few seconds later.
1668
+
1669
+ Create the index once before deploying, with the embedding model's dimensions:
1670
+ \`npx wrangler vectorize create ${H(e.name)}-articles --dimensions=768 --metric=cosine\`.
1671
+ Neither Vectorize nor Workers AI runs locally, so \`vite dev\` searches by keyword with SQLite's
1672
+ full-text search instead, and the page says so. \`VITE_REAL_AI=1 ${N(t,`dev`)}\` uses the real ones
1673
+ (after \`npx wrangler login\`). Workers AI and Vectorize bill per use beyond their free
1674
+ allocations, and a temporary account has neither.`:``}${Q(e,`digest`)?'\n\n## Weekly digest (Cron Trigger)\n\nEvery Monday at 08:00 UTC (`triggers.crons` in `wrangler.jsonc`), the Worker renders\n`/report` to a PDF with Browser Run and emails it. `/digest` lists each run — sent,\nskipped or failed, and why — and "Send now" runs one at once.\n\n- `worker/digest.ts` — `runDigest`: `exportPage` (`@cascivo/app/export`), then Email\n Service with the PDF attached. Every run is recorded in D1, so a digest that did not arrive\n says why.\n- `worker/index.ts` — the `scheduled` handler the Cron Trigger calls.\n\nSet `DIGEST_TO` (comma-separated), `DIGEST_FROM` (an address on a domain onboarded to Email\nService) and `APP_URL` (the deployed app\'s origin: a cron has no request to read it from) in\n`wrangler.jsonc`. Until they are set, runs are recorded as skipped. To fire the cron in\n`vite dev`, open `/cdn-cgi/handler/scheduled`; "Send now" uses the page\'s own origin, so it\nneeds no `APP_URL`. Browser Run starts a local Chrome in development.':``}${Q(e,`webhooks`)?"\n\n## Webhooks\n\n`/webhooks` lists GitHub webhook deliveries as they arrive. Point a repository's webhook at\n`https://<your app>/api/webhooks/github` (content type `application/json`) with a secret, and\ngive the Worker the same secret:\n`npx wrangler secret put WEBHOOK_SECRET`. Locally it is in `.dev.vars`, and \"Send a test\ndelivery\" signs one with it.\n\n- `worker/webhooks.ts` — `verifyWebhook` (`@cascivo/app/guard`) checks the\n `X-Hub-Signature-256` HMAC over the raw body before anything is parsed, and refuses a bad\n signature with a 401. Each delivery is stored in D1 under GitHub's delivery id, so a retry is ignored, and a\n new one is written to a read-only room the page watches.\n- `verifyWebhook` also checks Stripe (`scheme: 'stripe'`) and Standard Webhooks\n (`'standard'`: Svix, Clerk, Resend…), both with a five-minute timestamp window against\n replays.\n\nThe page answers within milliseconds, well inside GitHub's ten seconds. For slow work, send the\ndelivery to a Queue from `receiveGithub` and answer at once.":``}${Q(e,`checkout`)?`
1675
+
1676
+ ## Checkout (Stripe)
1677
+
1678
+ \`/checkout\` sells one product on Stripe's hosted Checkout page: the card never touches this
1679
+ app. Stripe tells the Worker when the payment succeeds; the Worker marks the order paid, pushes
1680
+ it to the order page, and emails a receipt rendered with \`@cascivo/email\`.
1681
+
1682
+ 1. In the Stripe dashboard, in test mode, copy the secret key (\`sk_test_…\`) into \`.dev.vars\`
1683
+ as \`STRIPE_SECRET_KEY\`, then run the app and buy with the card \`4242 4242 4242 4242\`.
1684
+ The order page confirms the payment by reading the session back from Stripe, so this works
1685
+ before any webhook is set up.
1686
+ 2. To receive the webhook locally, run
1687
+ \`stripe listen --forward-to localhost:5173/api/stripe/webhook\` (the Stripe CLI) and put the
1688
+ \`whsec_…\` secret it prints in \`.dev.vars\` as \`STRIPE_WEBHOOK_SECRET\`.
1689
+ 3. Deployed: \`npx wrangler secret put STRIPE_SECRET_KEY\` and
1690
+ \`npx wrangler secret put STRIPE_WEBHOOK_SECRET\`. In the dashboard, add a webhook endpoint
1691
+ at \`https://<your app>/api/stripe/webhook\` for \`checkout.session.completed\`,
1692
+ \`checkout.session.async_payment_succeeded\`, \`checkout.session.async_payment_failed\`,
1693
+ \`checkout.session.expired\`, \`charge.refunded\`, \`charge.dispute.created\` and
1694
+ \`charge.dispute.closed\`; its signing secret is \`STRIPE_WEBHOOK_SECRET\`.
1695
+ 4. Receipts: set \`RECEIPT_FROM\` in \`wrangler.jsonc\` to an address on a domain you have
1696
+ onboarded to Email Service. \`vite dev\` renders each receipt and logs it instead.
1697
+
1698
+ What you sell is \`PRODUCT\` in \`src/checkout.ts\`. The Worker sends that price to Stripe, so a
1699
+ browser cannot change it.
1700
+
1701
+ - \`worker/checkout.ts\` — \`createStripe\` (\`@cascivo/app/stripe\`) creates the session, with
1702
+ the order id as its idempotency key. The webhook is checked by \`verifyWebhook\` (scheme
1703
+ \`stripe\`: signature and a five-minute window) before \`parseStripeEvent\` reads it.
1704
+ - An order moves from \`pending\` to \`paid\`, \`failed\` or \`expired\` once. A retried event, or
1705
+ the page getting there before the webhook, changes nothing, so the receipt goes out once.
1706
+ Orders are found by Stripe's session id, never by \`client_reference_id\`, which a buyer can
1707
+ set on a Payment Link.
1708
+ - A bank debit completes the session as \`unpaid\`: the order stays pending until
1709
+ \`async_payment_succeeded\` or \`async_payment_failed\` arrives, possibly days later.
1710
+ - Refunds are made in the Stripe dashboard (or with \`createRefund\`); \`charge.refunded\` records
1711
+ the amount, and an order refunded in full becomes \`refunded\`. A chargeback makes it
1712
+ \`disputed\` until it is decided: answer it with evidence in the dashboard. Both find the
1713
+ order by the payment it stored when it was paid.
1714
+ - \`src/routes/checkout/[order].tsx\` — where Stripe sends the buyer back. It watches the
1715
+ order's read-only room, so it updates when the webhook arrives.
1716
+
1717
+ Each caller (by IP) may start 20 checkouts a minute.${J(e)?`
1718
+
1719
+ ### Subscriptions (\`/billing\`)
1720
+
1721
+ Signed-in users subscribe to \`PLAN\` (\`src/billing.ts\`) on Stripe's checkout and change,
1722
+ pause or cancel it in Stripe's hosted billing portal, so the app has no billing screens to build.
1723
+
1724
+ 1. Add \`customer.subscription.created\`, \`customer.subscription.updated\`,
1725
+ \`customer.subscription.deleted\` and \`invoice.payment_failed\` to the webhook endpoint's
1726
+ events.
1727
+ 2. In the Stripe dashboard, save the Customer Portal's settings once (test mode too): until
1728
+ then, Stripe refuses to open it.
1729
+ 3. Gate a paid feature in the Worker with \`await billingStore.requirePlan(env, request)\` (402
1730
+ without the plan), never on what the page shows.
1731
+
1732
+ - \`worker/billing.ts\` — the subscription names its user in its metadata, which only the
1733
+ Worker sets (\`client_reference_id\` can be set by a buyer on a Payment Link). Every
1734
+ subscription event is read back from Stripe before it is stored, because events arrive out of
1735
+ order, and a late event about an older subscription cannot end a live one.
1736
+ - Back from checkout, \`/billing\` reads the session and its subscription at once, so it is right
1737
+ before the webhook arrives, and only for the user the subscription names.
1738
+ - A renewal that cannot be charged leaves the plan on (\`past_due\`) while Stripe retries, and
1739
+ emails the customer once per attempt with Stripe's page to pay with another card. How long
1740
+ Stripe retries, and whether it then cancels, is set in the dashboard (Billing → Subscriptions
1741
+ and emails); turn off Stripe's own failed-payment emails there, or customers get two.`:`
1742
+
1743
+ Subscriptions need an account to belong to: \`cascivo create --framework cloudflare
1744
+ --example checkout --auth email\` adds a \`/billing\` page with a monthly plan and Stripe's
1745
+ billing portal.`}`:``}${Q(e,`newsletter`)?`
1746
+
1747
+ ## Newsletter (Amazon SES)
1748
+
1749
+ \`/newsletter\` signs readers up; \`/newsletter/send\` writes an issue in Markdown, previews it
1750
+ as the email it will be (rendered with \`@cascivo/email\`), and sends it to every confirmed
1751
+ reader through Amazon SES. It runs in \`vite dev\` with nothing set up: emails are logged instead
1752
+ of sent, and the sign-up page shows the confirmation link. The composer's key is in
1753
+ \`.dev.vars\` (\`NEWSLETTER_KEY\`).
1754
+
1755
+ To send for real:
1756
+
1757
+ 1. In SES, verify the domain you send from (SES gives DNS records for DKIM; add them in
1758
+ Cloudflare DNS, with an SPF and a DMARC record), and ask AWS to move the account out of the
1759
+ sandbox, where it can mail only verified addresses.
1760
+ 2. Create an IAM user allowed \`ses:SendEmail\` and nothing else, and give its keys to the
1761
+ Worker: \`npx wrangler secret put AWS_ACCESS_KEY_ID\` and \`AWS_SECRET_ACCESS_KEY\` (in
1762
+ \`.dev.vars\` locally). Set \`AWS_REGION\` and \`NEWSLETTER_FROM\` in \`wrangler.jsonc\`, and
1763
+ \`npx wrangler secret put NEWSLETTER_KEY\` to a long random value.
1764
+ 3. Bounces and complaints: create an SNS topic, set it as the SES identity's bounce and
1765
+ complaint notification topic, and subscribe \`https://<your app>/api/sns/ses\` to it (HTTPS).
1766
+ Put the topic's ARN in \`SNS_TOPIC_ARN\`. The Worker confirms the subscription itself.
1767
+ 4. Create the queue once: \`npx wrangler queues create ${Ze(e)}\`.
1768
+
1769
+ - \`worker/newsletter.ts\` — double opt-in: a sign-up gets a confirmation link (valid a day,
1770
+ resent at most every ten minutes) and gets no issue until it is opened. Sending stores the
1771
+ issue and puts its readers on the \`NEWSLETTER\` queue, 25 per message; the consumer sends
1772
+ them one by one through \`createSes\` (\`@cascivo/app/ses\`), handed to \`sendEmail\` from
1773
+ \`@cascivo/email\`, which checks each message before it leaves, one message at a time. Each
1774
+ send is recorded, so a message retried after SES throttling skips whoever already has it.
1775
+ - Every issue carries \`List-Unsubscribe\` and \`List-Unsubscribe-Post\` (one-click
1776
+ unsubscribe, RFC 8058, which Gmail and Yahoo require of bulk senders) and a footer link to
1777
+ \`/newsletter/unsubscribe\`.
1778
+ - \`handleSns\` checks each SNS message's signature against SNS's certificate before
1779
+ \`parseSesNotification\` reads it. A permanent bounce or a complaint suppresses the address
1780
+ for good: mailing it again is what gets an SES account reviewed.
1781
+ - \`worker/newsletter-email.ts\` — the issue and confirmation emails. The body is Markdown drawn
1782
+ through the email primitives; raw HTML in it stays literal text.
1783
+
1784
+ Sign-ups and every use of the newsletter key count against the rate limit (20 a minute per
1785
+ IP). Sending reads every confirmed address into memory; past a few hundred thousand readers,
1786
+ page through them instead.`:``}${Q(e,`social`)?`
1787
+
1788
+ ## Social posts
1789
+
1790
+ \`/social\` connects Bluesky, Buffer, LinkedIn, Mastodon and Threads accounts and posts to them,
1791
+ now or at a time you pick.
1792
+
1793
+ - \`worker/social.ts\` — \`handleConnections\` (\`@cascivo/app/oauth-server\`) answers
1794
+ \`/api/connections/*\`: connect, list, remove. Tokens are sealed in D1 with \`AUTH_SECRET\`.
1795
+ Scheduling checks that each account is yours and connected, and that each network's
1796
+ publisher (\`@cascivo/app/social\`) accepts the post, before anything is stored.
1797
+ - \`worker/social-post.ts\` — \`SocialPost\`, a Workflow per post: it sleeps until the post
1798
+ is due, then posts to each account in its own step. Bluesky and Mastodon steps retry, safely:
1799
+ Mastodon takes an idempotency key, and a Bluesky post's record key is fixed by its time and
1800
+ id. Buffer, LinkedIn and Threads steps never do: they cannot deduplicate, so an interrupted
1801
+ post there is reported for you to check rather than sent twice.
1802
+ - \`src/social.ts\` — the shared types, and the publishers the page also runs, so what a
1803
+ network would refuse shows while you type.
1804
+ - Images: the composer uploads them into the \`SOCIAL_MEDIA\` R2 bucket through the Worker
1805
+ (\`@cascivo/app/uploads\`), each user under their own prefix; up to 4, JPEG or PNG, 1 MB each
1806
+ (Bluesky's limit), each with a description. Bluesky, LinkedIn and Mastodon get the bytes.
1807
+ Threads and Buffer fetch images by URL, so they get a link to \`/api/social/media/…\` signed
1808
+ with \`AUTH_SECRET\`. It is valid until a day after the post is due, and needs \`APP_URL\` set
1809
+ to the deployed app. Uploads stay in R2: add a lifecycle rule
1810
+ (\`wrangler r2 bucket lifecycle add\`) to expire old ones.
1811
+
1812
+ **Bluesky** needs no set-up either: people type their handle. Bluesky's servers read this
1813
+ app's client metadata from \`/api/bluesky/client-metadata.json\`, so the deployed app must be
1814
+ reachable at its URL. In \`vite dev\` the app is Bluesky's development client, which may only
1815
+ return to \`127.0.0.1\`: open \`http://127.0.0.1:5173\`, not \`localhost\`. Without a key the app is a
1816
+ public client and sessions end after two weeks; for sessions that last, make a key and set it
1817
+ as the \`BLUESKY_PRIVATE_JWK\` secret:
1818
+
1819
+ \`\`\`sh
1820
+ node -e "crypto.subtle.generateKey({name:'ECDSA',namedCurve:'P-256'},true,['sign']).then(k=>crypto.subtle.exportKey('jwk',k.privateKey)).then(j=>console.log(JSON.stringify({...j,kid:'k1'})))"
1821
+ \`\`\`
1822
+
1823
+ **Mastodon** needs no set-up: people type their server, and the app registers itself there
1824
+ on first use.
1825
+
1826
+ **Buffer** reaches the networks connected there (X, Instagram, TikTok, …): register an app
1827
+ client at https://publish.buffer.com/settings/api with \`…/api/connections/buffer/callback\` as
1828
+ its redirect URL, and set \`BUFFER_CLIENT_ID\` (and \`BUFFER_CLIENT_SECRET\` for a confidential
1829
+ client). Each channel in a connected Buffer is an account in the composer, checked against
1830
+ its network's limit. Buffer counts every request against your plan's budget (100 per 15
1831
+ minutes on every plan), for all your users together, so the channel list is kept for an hour.
1832
+ Buffer cannot deduplicate, so its posts are never retried, like LinkedIn's. **LinkedIn** needs an app at https://www.linkedin.com/developers/apps with the
1833
+ "Share on LinkedIn" product${Z(e)?` (the same app as sign-in works, with both products)`:``}; add
1834
+ \`…/api/connections/linkedin/callback\` as a redirect URL and set \`LINKEDIN_CLIENT_ID\` and
1835
+ \`LINKEDIN_CLIENT_SECRET\`. LinkedIn tokens last 60 days and cannot be renewed: the page shows
1836
+ "expires soon" a week ahead, and connecting again renews the account in place. The daily Cron
1837
+ Trigger also emails the owner once, a week ahead, with a link to connect again
1838
+ (\`remindExpiring\`): set \`REMINDER_FROM\` in \`wrangler.jsonc\` to an address on a domain you
1839
+ have onboarded to Email Service, and \`APP_URL\` to the deployed app. People whose provider shared
1840
+ no email see the page's notice only.
1841
+
1842
+ **Threads** needs a Meta app with the "Access the Threads API" use case
1843
+ (https://developers.facebook.com/apps), the \`threads_basic\` and \`threads_content_publish\`
1844
+ permissions, and \`…/api/connections/threads/callback\` as a redirect callback URL; set
1845
+ \`THREADS_APP_ID\` and \`THREADS_APP_SECRET\` (the Threads app id and secret, not the Meta
1846
+ app's). Until Meta's App Review and business verification pass, only people added as testers
1847
+ on the app can connect. A Threads token lasts 60 days and renews itself only while it still
1848
+ works, so a daily Cron Trigger (\`${ft}\`, \`renewConnections\`) renews those in their last
1849
+ 30 days; try it in \`vite dev\` at \`/cdn-cgi/handler/scheduled\`. Threads takes 500 characters,
1850
+ counting an emoji as several, and cannot deduplicate either.
1851
+
1852
+ Connecting an account and posting count against the rate limit (20 a minute per IP).
1853
+ Workflows need a real Cloudflare account to deploy.`:``}${Y(e)?`
1854
+
1855
+ ## Accounts (${X(e)?Z(e)?`email, GitHub, Google and LinkedIn sign-in`:`email sign-in`:`GitHub, Google and LinkedIn sign-in`})
1856
+
1857
+ ${X(e)&&Z(e)?"Anyone can create an account by continuing with GitHub, Google or LinkedIn, or with their email address, on `/account`.":Z(e)?"Anyone can create an account by continuing with GitHub, Google or LinkedIn on `/account`.":"Anyone can create an account with their email address: `/account` emails a one-time link, and opening it signs them in with a session cookie."} **Every API write needs a signed-in user; reads stay public.**
1858
+
1859
+ - \`worker/index.ts\` — ${[X(e)?"`handleAuth` (`@cascivo/app/auth-server`)":``,Z(e)?"`handleOAuth` (`@cascivo/app/oauth-server`)":``].filter(Boolean).join(` and `)} answer${X(e)&&Z(e)?``:`s`} \`/api/auth/*\`, and
1860
+ \`requireUser\` refuses any other write without a session (401) or from another site (403).
1861
+ Call \`requireUser(env.DB, request)\` in a handler to know who is asking.${X(e)?"\n- `worker/auth.ts` — sends the link through Email Service. Set `AUTH_FROM` in\n `wrangler.jsonc` to an address on a domain you have onboarded to Email Service.":``}
1862
+ - \`src/auth.ts\` — \`auth.user\`, a signal every page can read. \`user.email\` is \`null\` for
1863
+ someone whose provider shared no verified address.${X(e)?`
1864
+ - \`src/routes/signin/verify.tsx\` — the page a link opens. It signs in on a button press,
1865
+ because mail scanners open every link in a message.`:``}
1866
+
1867
+ Users${X(e)?`, links`:``} and sessions live in D1, stored as hashes. ${X(e)?`Links expire after 15 minutes and work once; sessions`:`Sessions`} last 30 days.${X(e)?" Each caller (by IP) may request 20 links a minute. In `vite dev` no email is sent: the Account page shows the link instead.":``} WebSocket connections
1868
+ (rooms, agents) are not covered by the write rule; check \`currentUser\` before forwarding them
1869
+ if they need a user.${Z(e)?`
1870
+
1871
+ ### GitHub, Google and LinkedIn
1872
+
1873
+ 1. **GitHub**: create an OAuth App at https://github.com/settings/developers with the
1874
+ callback URL \`http://localhost:5173/api/auth/oauth/github/callback\` for \`vite dev\`
1875
+ (an OAuth App takes one callback URL, so make a second app for the deployed one).
1876
+ 2. **Google**: in the Google Cloud console, create an OAuth client of type "Web application"
1877
+ with the redirect URIs \`http://localhost:5173/api/auth/oauth/google/callback\` and
1878
+ \`https://<your app>/api/auth/oauth/google/callback\`.
1879
+ 3. **LinkedIn**: create an app at https://www.linkedin.com/developers/apps, add the product
1880
+ "Sign In with LinkedIn using OpenID Connect", and under Auth add both redirect URLs
1881
+ (\`…/api/auth/oauth/linkedin/callback\` on localhost and on your app).
1882
+ 4. Put the ids and secrets in \`.dev.vars\`. Deployed: \`npx wrangler secret put\` each
1883
+ \`*_CLIENT_ID\` and \`*_CLIENT_SECRET\` you use, and \`AUTH_SECRET\` (a random one:
1884
+ \`openssl rand -base64 32\`). A provider is offered once both its values are set.
1885
+
1886
+ People are matched by their account at the provider, not by email. A new sign-in joins an
1887
+ existing account only through an email the provider has verified (GitHub's primary verified
1888
+ address, Google's and LinkedIn's \`email_verified\`). A signed-in user who follows another provider's link
1889
+ adds it to their account.`:``}`:``}${e.auth===`access`?'\n\n## Access (who may use the app)\n\nThe Worker refuses every request Cloudflare Access did not let through: `requireAccess`\n(`@cascivo/app/guard`) at the top of `worker/index.ts` verifies the token Access signs.\n\n1. In Cloudflare One (Zero Trust), add a self-hosted Access application for this app\'s\n hostname, with a policy saying who may sign in.\n2. Put your team domain (`<team>.cloudflareaccess.com`) and the application\'s Audience (AUD)\n tag in `vars` in `wrangler.jsonc`, and deploy.\n\nUntil both are set, every API request answers 500 ("Access is not configured"). Access guards\nthe pages at the edge; the Worker\'s check also refuses API calls that reach it around Access,\nat `*.workers.dev` for example (set `"workers_dev": false` if the app should have no public\naddress at all). `vite dev` skips the check. A temporary account has no Access, so an app made\nwith `--auth access` cannot use `deploy:preview`.':``}${Q(e,`crud`)?"\n\n## Customers (D1)\n\n`/customers` is a D1 table behind `DataTable`'s server mode: sorting, search, the name and\nseats filters, and paging all run as SQL in the Worker, and the page shows one page at a time.\n\n- `src/customers.ts` — `defineTable` (`@cascivo/app/db`) lists what may be sorted, searched and\n filtered. `queryTable` builds SQL from that list only, with every value a bound parameter:\n a query for any other column is refused with a 400.\n- `worker/migrations.ts` — the schema and 60 sample rows. The Worker applies them itself on its\n first query (`migrate`), so a fresh deploy, the Deploy button and `deploy:preview` need no\n migration step. Append migrations; never edit one that has shipped.\n- `worker/customers.ts` — create, update and delete, each checked by `parseCustomerInput`.\n\nD1 works on a temporary account, so `deploy:preview` shares the table with no sign-up. If you\nprefer wrangler's own migrations (`wrangler d1 migrations apply`), move the SQL into\n`migrations/` and drop the `migrate` call.":``}${Q(e,`agent`)?`
1890
+
1891
+ ## Assistant (generative UI)
1892
+
1893
+ \`/assistant\` is a chat whose answers can be UI. The model calls a \`show_view\` tool with a view
1894
+ config; the Worker checks it against the component manifests (\`validateView\` from
1895
+ \`@cascivo/render/validate\`) and returns any errors to the model, which fixes them and calls
1896
+ again. The page renders the result with \`<CascivoView>\`: real components, no generated code.
1897
+
1898
+ - \`worker/assistant.ts\` — \`Assistant\`, an \`AIChatAgent\` (Cloudflare's Agents SDK): one
1899
+ Durable Object per conversation, which stores the messages and streams replies to every open
1900
+ tab. The system prompt, the \`show_view\` tool and the model (\`MODEL\`, any Workers AI model
1901
+ with tool calling) are here.
1902
+ - \`src/assistant.ts\` — \`checkView\`, the one check both sides run on a view.
1903
+ - \`src/routes/assistant.tsx\` — \`useAgent\` + \`useAgentChat\`; one conversation per browser.
1904
+ - \`worker/scripted-model.ts\` — \`vite dev\` answers from this scripted model, so the page works
1905
+ offline and without an account. \`VITE_REAL_AI=1 ${N(t,`dev`)}\` uses Workers AI instead
1906
+ (after \`npx wrangler login\`); a deployed Worker always does.
1907
+
1908
+ Workers AI bills per use beyond its free daily allocation.`:``}${Q(e,`publish`)?`
1909
+
1910
+ ## Publish (views as pages)
1911
+
1912
+ \`/publish\` turns a view — the JSON that \`<CascivoView>\` renders, which an agent can write
1913
+ too — into a page at \`/p/<slug>\`, with no deploy. A view is data, not code: it can only
1914
+ arrange this app's components with props their manifests allow, so a published page runs no
1915
+ code of its author's and needs no sandbox.
1916
+
1917
+ - \`src/pages.ts\` — \`parsePageInput\` checks a page with \`validateView\`
1918
+ (\`@cascivo/render/validate\`): known components and props, and no link or image URL that
1919
+ could run script. The Worker runs it before storing a page; \`<CascivoView>\` checks again
1920
+ before rendering one.
1921
+ - \`worker/pages.ts\` — pages in D1, under a random ten-character slug.
1922
+ - \`src/routes/publish.tsx\` — the editor, with a live preview.
1923
+ - \`src/routes/p/[slug].tsx\` — a published page.
1924
+ - \`worker/page-html.ts\` — the Worker answers \`/p/<slug>\` with index.html carrying the
1925
+ page's title, description and Open Graph tags, so a shared link previews properly, and the
1926
+ rendered page in a \`<noscript>\` for readers without JavaScript.${Q(e,`export`)?"\n- `worker/page-preview.ts` — the preview image (`og:image`, 1200 × 630): Browser Run\n renders the page once, and D1 keeps the PNG.":``}
1927
+
1928
+ ${e.auth?``:"**Anyone who can reach the app can publish**, and a page is served from your domain: put\nCloudflare Access in front (`--auth access`), add accounts (`--auth email`), or check who\nis publishing in `worker/index.ts`. "}Each caller (by IP) may publish 20 pages a minute (\`ratelimits\` in
1929
+ \`wrangler.jsonc\`). D1 works on a temporary account.`:``}${Q(e,`voice`)?`
1930
+
1931
+ ## Voice
1932
+
1933
+ \`/voice\` is a voice assistant: press "Start call", talk, and it answers aloud. Talk over a
1934
+ reply to interrupt it. Typed messages work too.
1935
+
1936
+ - \`worker/voice.ts\` — \`Voice\`, an Agent with the Agents SDK's voice pipeline
1937
+ (\`withVoice\` from \`agents/voice\`): Workers AI speech to text (Flux, which also decides when
1938
+ you have finished speaking), a text model (\`MODEL\`) and text to speech. One Durable Object
1939
+ per conversation stores the transcript, which the model gets as context.
1940
+ - \`src/voice.ts\` — \`VoiceClient\` (\`agents/voice/client\`) captures the microphone, streams
1941
+ it, and plays the replies; its events become signals the page reads.
1942
+ - \`worker/scripted-voice.ts\` — \`vite dev\` stand-ins, because Workers AI has no local mode:
1943
+ the transcriber "hears" a fixed question for every three seconds of sound, and the replies
1944
+ are text only. \`VITE_REAL_AI=1 ${N(t,`dev`)}\` uses Workers AI instead (after
1945
+ \`npx wrangler login\`); a deployed Worker always does.
1946
+
1947
+ Browsers allow the microphone only on a secure origin: \`localhost\` or HTTPS. Workers AI
1948
+ bills per use beyond its free daily allocation, and a temporary account has no Workers AI.`:``}
1949
+
1950
+ Add more components with \`npx cascivo add <component>\`.
1951
+
1952
+ ## ${n===`preact`?`Preact or React`:`React or Preact`}
1953
+
1954
+ ${Q(e,`agent`)?`This app runs on React. The Agents SDK's hooks call React 19's \`use()\`, which
1955
+ Preact's compat layer does not implement, so the assistant page needs React. (The other pages
1956
+ would run on Preact unchanged: the source is typed against React either way.)`:"The source is typed against React. The runtime is one plugin in `vite.config.ts`:\n`@preact/preset-vite` runs it on Preact, `@vitejs/plugin-react` on React. Switching\nneeds no source changes; swap the plugin and the matching dependencies. For this starter,\nPreact ships about a third of the client JS (~27 KB gzip against ~85 KB)."}
1957
+ `}function _t(e){return`${ke(e)}
1958
+ ## Server
1959
+
1960
+ The API contract is \`src/api.ts\` (\`defineApi\` from \`@cascivo/app/api\`); its handlers are
1961
+ \`worker/index.ts\` (\`createHandler\`), and the app calls it through \`createClient\`. Add an
1962
+ endpoint to the contract first, with a parser for its input and output: parse every payload
1963
+ that crosses the network, never cast it. A streaming endpoint's handler is an async
1964
+ generator. \`wrangler.jsonc\` routes only \`/api/*\` to the Worker.
1965
+
1966
+ ## Pages
1967
+
1968
+ A page is a file in \`src/routes/\` with a default export: \`c/[id].tsx\` serves \`/c/:id\` and
1969
+ receives \`{ params }: RouteProps<'/c/:id'>\`. Never edit \`src/routes.gen.ts\`. Link with
1970
+ \`href\`s (SideNav items, \`router.Link\`); navigate from code with \`router.navigate(path)\`,
1971
+ and build a path with \`buildPath('/c/:id', { id })\`, both from \`@cascivo/app\`.
1972
+
1973
+ ## Sharing
1974
+
1975
+ To show the user a running version, run \`${P(e.pm??`npm`,`deploy:preview`)}\`.
1976
+ It needs no Cloudflare account. Give the user both URLs it prints: the live one, and the
1977
+ claim URL. The deployment is public, and it is deleted after 60 minutes unless the user
1978
+ opens the claim URL and signs in.
1979
+ `}function vt(e){let t=ye(e),n=t.indexOf(` * Adding a router?`),r=t.indexOf(` */
1980
+ export function Shell`);return t.slice(0,n)+` * Routing lives in src/router.ts; nav items carry \`href\`s, and main.tsx registers the
1981
+ * router's Link so they navigate client-side.
1982
+ `+t.slice(r)}function yt(e){return[...Q(e,`webhooks`)?[`# The secret vite dev signs and checks test webhook deliveries with.`,`WEBHOOK_SECRET=dev-only-webhook-secret`]:[],...Q(e,`checkout`)?[`# Stripe, in test mode (README): the secret key from the dashboard, and the signing`,"# secret `stripe listen` prints.",`STRIPE_SECRET_KEY=`,`STRIPE_WEBHOOK_SECRET=`]:[],...Q(e,`newsletter`)?[`# The key /newsletter/send asks for. Deployed, choose a long random one.`,`NEWSLETTER_KEY=dev-only-newsletter-key`,`# An IAM user allowed ses:SendEmail (README). Without them, vite dev logs each email.`,`AWS_ACCESS_KEY_ID=`,`AWS_SECRET_ACCESS_KEY=`]:[],...Z(e)?[`# Seals the sign-in state between the redirect and the callback. Deployed, a random one:`,`# openssl rand -base64 32`,`AUTH_SECRET=dev-only-auth-secret-0123456789abcdef`,`# A GitHub OAuth App, a Google OAuth client and a LinkedIn app (README).`,`# Each provider is offered once both its id and secret are set.`,`GITHUB_CLIENT_ID=`,`GITHUB_CLIENT_SECRET=`,`GOOGLE_CLIENT_ID=`,`GOOGLE_CLIENT_SECRET=`,`LINKEDIN_CLIENT_ID=`,`LINKEDIN_CLIENT_SECRET=`]:Q(e,`social`)?[`# Seals connected accounts' tokens. Deployed, a random one: openssl rand -base64 32`,`AUTH_SECRET=dev-only-auth-secret-0123456789abcdef`,`# A LinkedIn app with "Share on LinkedIn" (README). Mastodon needs nothing.`,`LINKEDIN_CLIENT_ID=`,`LINKEDIN_CLIENT_SECRET=`]:[],...Q(e,`social`)?[`# Optional: an ES256 private JWK with a kid, so Bluesky sessions last (README).`,`BLUESKY_PRIVATE_JWK=`,`# Optional: a Buffer app client (publish.buffer.com/settings/api), to post to its channels.`,`BUFFER_CLIENT_ID=`,`BUFFER_CLIENT_SECRET=`,`# Optional: a Meta app with the Threads use case (README), to post to Threads.`,`THREADS_APP_ID=`,`THREADS_APP_SECRET=`]:[]].map(e=>`${e}\n`).join(``)}function bt(e){return yt(e).split(`
1983
+ `).map(e=>e.startsWith(`#`)?e:e.replace(/=.*$/,`=`)).join(`
1984
+ `)}function xt(e){let t=e=>Object.fromEntries(e.map(([e,t])=>[e,{description:t}]));return{...Q(e,`webhooks`)?t([[`WEBHOOK_SECRET`,"The secret of the GitHub webhook that posts to `/api/webhooks/github`."]]):{},...Q(e,`checkout`)?t([[`STRIPE_SECRET_KEY`,"Your Stripe secret key, from the [API keys page](https://dashboard.stripe.com/test/apikeys). A test key (`sk_test_…`) takes test cards only."],[`STRIPE_WEBHOOK_SECRET`,"The signing secret (`whsec_…`) of a Stripe webhook endpoint at `https://<this app>/api/stripe/webhook`. No endpoint yet? Enter `later`: orders are confirmed on their own page without it. Set the real one with `npx wrangler secret put STRIPE_WEBHOOK_SECRET`."],[`RECEIPT_FROM`,`The From address of receipts, on a domain onboarded to Cloudflare Email Service. Leave it empty to send none.`]]):{},...Q(e,`newsletter`)?t([[`NEWSLETTER_KEY`,"The key `/newsletter/send` asks for. Make a long random one: `openssl rand -hex 32`."],[`AWS_ACCESS_KEY_ID`,"An IAM user allowed `ses:SendEmail` and nothing else (README)."],[`AWS_SECRET_ACCESS_KEY`,`That IAM user's secret access key.`],[`AWS_REGION`,"The SES region your sending domain is verified in, e.g. `eu-west-1`."],[`NEWSLETTER_FROM`,`The From address of issues, on your SES-verified domain.`],[`SNS_TOPIC_ARN`,"The SNS topic SES reports bounces and complaints to, subscribed to `https://<this app>/api/sns/ses`."]]):{},...Z(e)?t([[`AUTH_SECRET`,"Seals the sign-in state between the redirect to GitHub, Google or LinkedIn and the way back. Make a random one: `openssl rand -base64 32`."],[`GITHUB_CLIENT_ID`,"The client id of a [GitHub OAuth App](https://github.com/settings/developers) whose callback URL is `https://<this app>/api/auth/oauth/github/callback`. Leave it empty to offer no GitHub sign-in."],[`GITHUB_CLIENT_SECRET`,`That OAuth App's client secret.`],[`GOOGLE_CLIENT_ID`,"The client id of a Google OAuth client (Web application) with the redirect URI `https://<this app>/api/auth/oauth/google/callback`. Leave it empty to offer no Google sign-in."],[`GOOGLE_CLIENT_SECRET`,`That OAuth client's secret.`],[`LINKEDIN_CLIENT_ID`,'The client id of a LinkedIn app with the "Sign In with LinkedIn using OpenID Connect" product and the redirect URL `https://<this app>/api/auth/oauth/linkedin/callback`. Leave it empty to offer no LinkedIn sign-in.'],[`LINKEDIN_CLIENT_SECRET`,`That LinkedIn app's primary client secret.`]]):Q(e,`social`)?t([[`AUTH_SECRET`,"Seals the tokens of the accounts people connect. Make a random one: `openssl rand -base64 32`."],[`LINKEDIN_CLIENT_ID`,'The client id of a LinkedIn app with the "Share on LinkedIn" product and the redirect URL `https://<this app>/api/connections/linkedin/callback`. Leave it empty to offer no LinkedIn.'],[`LINKEDIN_CLIENT_SECRET`,`That LinkedIn app's primary client secret.`]]):{},...Q(e,`social`)?t([[`BLUESKY_PRIVATE_JWK`,"Optional. An ES256 private key as a JWK with a `kid` (README shows how to make one). With it, Bluesky sessions last until revoked; without it, two weeks."],[`BUFFER_CLIENT_ID`,"Optional. A Buffer app client (https://publish.buffer.com/settings/api) with the redirect URL `https://<this app>/api/connections/buffer/callback`. Leave it empty to offer no Buffer."],[`BUFFER_CLIENT_SECRET`,`That Buffer app client's secret (none for a public client).`],[`THREADS_APP_ID`,"Optional. The Threads app id of a Meta app with the Threads use case, and `https://<this app>/api/connections/threads/callback` as its redirect callback URL. Leave it empty to offer no Threads."],[`THREADS_APP_SECRET`,`That Threads app's secret.`]]):{}}}const St=[`agent`,`board`,`notes`,`import`,`files`,`export`,`usage`,`crud`,`live`,`voice`,`publish`,`publish-preview`,`webhooks`,`digest`,`search`,`checkout`,`billing`,`newsletter`,`social`,`accounts`,`auth-email`];function Ct(e,t){switch(e){case`publish-preview`:return Q(t,`publish`)&&Q(t,`export`);case`billing`:return J(t);case`accounts`:return Y(t);case`auth-email`:return X(t);default:return Q(t,e)}}function wt(e){return[`cloudflare`,...St.filter(t=>Ct(t,e))]}function Tt(e,t){let n=it(e),r=wt(e),i=r.flatMap(t=>ie(t,Ce(e))),a=[...t.map((e,t)=>({file:ct(e,t),contents:e.block?be(e,`export default function`):t===0?ut(e):dt(e,t)})),...Y(e)?[{file:`account.tsx`,contents:pt(e)}]:[]],o=[...a.map(e=>e.file),...i.filter(e=>e.path.startsWith(`src/routes/`)).map(e=>e.path.slice(11))];return[{path:`package.json`,contents:Ue(e)},{path:`tsconfig.json`,contents:We(e)},...rt(e)?[{path:`tsconfig.worker.json`,contents:Ge()}]:[],{path:`vite.config.ts`,contents:Ke(n,e)},{path:`wrangler.jsonc`,contents:qe(e)},{path:`index.html`,contents:he(e)},{path:`eslint.config.js`,contents:W()},{path:`.prettierrc`,contents:G()},{path:`.prettierignore`,contents:mt()},{path:`.gitignore`,contents:ht()},{path:`README.md`,contents:gt(e)},{path:`AGENTS.md`,contents:_t(e)},{path:`worker/index.ts`,contents:ot(e)},{path:`src/api.ts`,contents:at(e)},{path:`src/vite-env.d.ts`,contents:_e()},{path:`src/App.tsx`,contents:lt(t,r,e)},{path:`src/Shell.tsx`,contents:vt(e)},...Q(e,`webhooks`)||Q(e,`checkout`)||Q(e,`newsletter`)||Q(e,`social`)||Z(e)?[{path:`.dev.vars`,contents:yt(e)},{path:`.dev.vars.example`,contents:bt(e)}]:[],...i,...Se(t,e),...a.map(({file:e,contents:t})=>({path:`src/routes/${e}`,contents:t})),{path:`src/routes.gen.ts`,contents:te(o,`./routes`)}]}function Et(e,t){return U({name:e.name,framework:e.framework??`react-vite`,theme:e.theme,pages:t.map(e=>({title:e.label,...e.block?{block:e.block}:{}})),...e.runtime?{runtime:e.runtime}:{},...e.examples&&e.examples.length>0?{examples:e.examples}:{},...e.auth?{auth:e.auth}:{},cascivo:b})}function Dt(e){let t=de(e.sections,e.blocks),n=[...kt(e,t),{path:`cascivo.app.json`,contents:Et(e,t)},...Ot()];return e.workspace?le({packageName:H(e.name),app:n,firstLabel:t[0].label,testable:(e.framework??`react-vite`)===`react-vite`,reactVersion:j[`@cascivo/react`]}):n}function Ot(){let e=o(void 0,`claude`);if(e.kind!==`added`)throw Error(`cascivo: could not build .mcp.json`);return[{path:`CLAUDE.md`,contents:`@AGENTS.md
1985
+ `},{path:`.mcp.json`,contents:U(e.config)}]}function kt(e,t){if(e.framework===`astro`)return At(e,t);if(e.framework===`cloudflare`){let n=e.examples?.includes(`digest`)&&!e.examples.includes(`export`)?[...e.examples,`export`]:e.examples,r=e.auth??(n?.includes(`social`)?`oauth`:void 0);return Tt({...e,...n?{examples:n}:{},...r?{auth:r}:{}},t)}return[{path:`package.json`,contents:fe(e)},{path:`tsconfig.json`,contents:pe()},{path:`vite.config.ts`,contents:me()},{path:`index.html`,contents:he(e)},{path:`eslint.config.js`,contents:W()},{path:`.prettierrc`,contents:G()},{path:`.prettierignore`,contents:K()},{path:`.gitignore`,contents:Ee()},{path:`README.md`,contents:Oe(e)},{path:`AGENTS.md`,contents:ke(e)},{path:`src/main.tsx`,contents:ge()},{path:`src/vite-env.d.ts`,contents:_e()},{path:`src/App.tsx`,contents:ve(t)},{path:`src/Shell.tsx`,contents:ye(e)},...t.map(e=>({path:`src/sections/${e.component}.tsx`,contents:we(e)})),...Se(t,e)]}function At(e,t){return[{path:`package.json`,contents:Me(e)},{path:`tsconfig.json`,contents:Pe()},{path:`astro.config.mjs`,contents:Ne()},{path:`eslint.config.js`,contents:W()},{path:`.prettierrc`,contents:G()},{path:`.prettierignore`,contents:K()},{path:`.gitignore`,contents:Be()},{path:`README.md`,contents:Ve(e,t)},{path:`AGENTS.md`,contents:ke(e)},{path:`src/styles/layers.css`,contents:Fe()},{path:`src/layouts/Layout.astro`,contents:Ie(e)},{path:`src/components/Shell.tsx`,contents:Le(e,t)},...t.map((e,t)=>({path:`src/pages/${je(e,t)}`,contents:ze(e,t)})),...t.map(e=>({path:`src/components/${e.component}.tsx`,contents:Re(e)}))]}const jt=[`Dashboard`,`Reports`,`Settings`];function Mt(e){let t=e.examples??[];return t.length>0&&e.framework!==`cloudflare`?`--example needs --framework cloudflare (it adds a Worker-backed page).`:t.includes(`social`)&&e.auth===`access`?`--example social needs accounts (posts belong to a user): use --auth email, oauth or email,oauth, or leave --auth out to get oauth.`:e.auth&&e.framework!==`cloudflare`?`--auth needs --framework cloudflare (it guards the Worker).`:e.workspace&&e.framework===`astro`?`--workspace needs --framework react-vite or cloudflare.`:t.includes(`agent`)&&e.runtime===`preact`?`--example agent needs --runtime react: the Agents SDK's hooks call React 19's use(), which Preact does not implement.`:null}async function Nt(e,t){let{readFileSync:n}=await import(`node:fs`),{parseBlueprint:r,blueprintOptions:i}=await import(`./blueprint-eOLGuyAi.mjs`);try{return i(r(JSON.parse(n(h(t,e),`utf8`)),e))}catch(e){return console.error(e instanceof Error?e.message:String(e)),null}}async function Pt(o,l=process.cwd()){let d=o.includes(`--yes`)||o.includes(`-y`),p=r(o,[`pm`,`package-manager`,`theme`,`sections`,`template`,`framework`,`runtime`,`example`,`auth`,`from`])[0],h=a(o,`theme`),g=a(o,`sections`),v=(a(o,`framework`)??``).toLowerCase();if(v&&!F.includes(v)){console.error(`Unknown framework "${v}". Expected one of: ${F.join(`, `)}.`),process.exitCode=1;return}let y=(a(o,`runtime`)??``).toLowerCase();if(y&&!z(y)){console.error(`Unknown runtime "${y}". Expected one of: ${I.join(`, `)}.`),process.exitCode=1;return}let b=(a(o,`example`)??``).split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean),x=b.find(e=>!R(e));if(x){console.error(`Unknown example "${x}". Expected one of: ${L.join(`, `)}.`),process.exitCode=1;return}let S=Xe(a(o,`auth`));if(S===`invalid`){console.error(`Unknown auth "${a(o,`auth`)??``}". Expected: access, email, oauth or email,oauth.`),process.exitCode=1;return}let C=i(o);if(`error`in C){console.error(C.error),process.exitCode=1;return}let w=e(l,{preferLockfileOverUserAgent:!0,...C.pm?{override:C.pm}:{}}),T=!d&&s.isTTY?_({input:s,output:c}):null,ee=async()=>{let e=p;!e&&T&&(e=(await T.question(`Project name? [my-cascivo-app]: `)).trim()),e||=`my-cascivo-app`;let n=(h??``).toLowerCase();!t.includes(n)&&T&&(n=(await T.question(`Theme? (${t.join(`/`)}) [light]: `)).trim().toLowerCase());let r=t.includes(n)?n:`light`,i=g;!i&&T&&(i=(await T.question(`Nav sections? (comma-separated) [${jt.join(`, `)}]: `)).trim());let a=(i??``).split(`,`).map(e=>e.trim()).filter(Boolean),o=v;!o&&T&&(o=(await T.question(`Framework? (${F.join(`/`)}) [react-vite]: `)).trim().toLowerCase());let s=F.includes(o)?o:`react-vite`;return{name:e,framework:s,theme:r,sections:a.length>0?a:jt,...z(y)?{runtime:y}:{},...b.length>0?{examples:b.filter(R)}:{},...S?{auth:S}:{}}};try{let e=a(o,`from`),t=e?await Nt(e,l):await ee();if(!t){process.exitCode=1;return}let r=o.includes(`--workspace`),i={...t,...e&&p?{name:p}:{},pm:r?`pnpm`:w,...r?{workspace:r}:{}},s=Mt(i);if(s){console.error(s),process.exitCode=1;return}let c=i.name,d=i.framework??`react-vite`,h=i.theme,g=m(l,c);if(u(g)&&f(g).length>0){console.error(`Target directory "${c}" already exists and is not empty.`),process.exitCode=1;return}let _=Dt(i);for(let e of _)await n(m(g,e.path),e.contents);console.log(`\nCreated ${c} (${d}) with the ${h} theme (${_.length} files).`);let v=a(o,`template`);if(v){let{add:e}=await import(`./index.mjs`).then(e=>e.t),{loadConfig:t}=await import(`./config-CTk7uDrh.mjs`).then(e=>e.i);console.log(`\nInstalling template "${v}"…`),await e([v],await t(),{cwd:g,pm:w})}console.log(`
1986
+ Next steps:`),console.log(` cd ${c}`),console.log(` ${M(w)}`),console.log(` ${N(w,`dev`)}`),console.log(`
1987
+ Good to know:`),console.log(` No cascivo.config.ts is written — this app uses the prebuilt @cascivo/react`),console.log(" packages and never copies source. `cascivo add <component>` writes the"),console.log(` config itself the first time you vendor a component.`),d===`cloudflare`?(console.log("\n worker/index.ts is the API (wrangler.jsonc routes /api/* to it); `dev`"),console.log(" runs it in workerd. Deploy with `npx wrangler login` once, then the"),console.log(` deploy script: ${P(w,`deploy`)}`),console.log(`
1988
+ No account yet? Share a 60-minute preview, claimable into a free account:`),console.log(` ${P(w,`deploy:preview`)}`)):d===`astro`?(console.log(`
1989
+ Pages are real Astro routes — no client router to add. Only src/`),console.log(` components/Shell.tsx hydrates (client:load, for the mobile nav drawer);`),console.log(` page content is server-rendered and ships no JS. See`),console.log(` https://cascivo.com/docs/using-with-astro.md`)):(console.log(`
1990
+ Adding a router? Keep src/Shell.tsx, delete src/App.tsx + src/sections/,`),console.log(` and register your Link once with setLinkComponent — see`),console.log(` https://cascivo.com/docs/using-with-a-router.md`))}finally{T?.close()}}export{L as EXAMPLES,F as FRAMEWORKS,I as RUNTIMES,Dt as buildScaffold,Pt as create,R as isExample,z as isRuntime,b as n,Mt as optionsError,Xe as parseAuth,ae as t};
1991
+ //# sourceMappingURL=create-BA9GQ8nl.mjs.map