cascivo 1.8.2 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/{app-BhCskK3W.mjs → app-Dt98v4Zq.mjs} +3 -3
- package/dist/{app-BhCskK3W.mjs.map → app-Dt98v4Zq.mjs.map} +1 -1
- package/dist/{blueprint-B6Z8NrCr.mjs → blueprint-BBrlwJhm.mjs} +2 -2
- package/dist/{blueprint-B6Z8NrCr.mjs.map → blueprint-BBrlwJhm.mjs.map} +1 -1
- package/dist/cmdspec.json +310 -1
- package/dist/{create-DIaknp48.mjs → create-BMqDBB8r.mjs} +3 -3
- package/dist/{create-DIaknp48.mjs.map → create-BMqDBB8r.mjs.map} +1 -1
- package/dist/design-CYQqMPQB.mjs +3 -0
- package/dist/design-CYQqMPQB.mjs.map +1 -0
- package/dist/generated/audit-contract.json +3 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +70 -33
- package/dist/index.mjs.map +1 -1
- package/dist/skills/cascivo-design/SKILL.md +44 -0
- package/dist/skills/cascivo-design/references/check-rules.md +37 -0
- package/dist/skills/cascivo-design/references/critique-rubric.md +26 -0
- package/dist/skills/cascivo-design/references/direction.md +113 -0
- package/dist/skills/cascivo-design/references/without-cascivo.md +17 -0
- package/package.json +8 -3
- package/readme.body.md +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-DIaknp48.mjs","names":["t","e","detectPackageManager","THEMES","writeFileSafe","positionalArgs","resolvePackageManagerFlag","flagValue","mergeMcpConfig","CASCIVO_VERSIONS","SIGNALS_PEER","CLI_VERSION","normalizePath","escapeRegex","compilePath","compareSpecificity","f","fileToRoutePath","generateRoutes","i","a","e","n","t","specifier","r","o","s","HERE","dirname","fileURLToPath","recipesDir","candidate","join","existsSync","parseRecipe","raw","source","name","files","paths","file","isSafeRelativePath","nav","items","item","label","href","dependencies","d","cache","loadRecipe","cached","recipe","readFileSync","PLACEHOLDER","recipeFiles","dir","path","vars","key","blockNames","readdirSync","json","formatJson","parsePackageJson","contents","record","value","entry","ROOT_FILES","buildWorkspace","scope","input","ui","pkg","scripts","devDependencies","mcp","V","installAllCommand","pm","runScriptCommand","script","runExplicitCommand","FRAMEWORKS","RUNTIMES","EXAMPLES","isExample","isRuntime","slug","pascalCase","safe","p","brandName","words","w","kept","word","packageName","resolveSections","seenKeys","seenComponents","sections","index","labels","trimmed","component","block","blocks","packageJson","opts","blockDependencies","tsconfig","viteConfig","indexHtml","mainTsx","viteEnv","appTsx","sectionImports","oneLine","sectionType","navItems","renderedSections","shellTsx","appShellOpenTag","blockPageTsx","section","local","declaration","packages","version","blockFiles","recipeVars","usageDataset","sectionTsx","eslintConfig","header","line","prettierrc","prettierIgnore","gitignore","staticShareSection","COMPATIBILITY_DATE","readme","agentsMd","sectionPath","sectionPageFile","astroPackageJson","astroConfig","ASTRO_LAYER_ORDER","astroTsconfig","astroLayersCss","astroLayout","astroShellTsx","astroSectionTsx","astroPage","astroGitignore","astroReadme","routes","cfPackageJson","agent","hasExample","workerTypes","needsWorkerTypes","preact","runtimeOf","bindings","cfBindingDescriptions","cfTsconfig","cfg","cfWorkerTsconfig","cfViteConfig","ai","usesWorkersAi","plugin","runtime","call","clause","jsoncArray","indent","wranglerJsonc","publish","rooms","usesRooms","usesAgents","objects","comments","usesLimiter","emailSignIn","c","wranglerVars","SOCIAL_CRON","usesD1","hasAccounts","wranglerQueues","digest","social","checkout","newsletter","emailAuth","names","entries","comment","queues","newsletterQueue","q","usesBilling","oauthSignIn","parseAuth","parts","example","cfApiTs","imports","usage","crud","live","webhooks","search","billing","cfWorkerTs","exports","voice","d1","limiter","access","oauth","accounts","guards","custom","isAsync","serverRooms","signedPaths","readerPaths","openPaths","prefix","cfSectionPath","cfSectionFile","cfAppTsx","recipes","cfFirstRouteTsx","cfRouteTsx","cfAccountRouteTsx","email","lead","cfPrettierIgnore","cfGitignore","cfReadme","cfAgentsMd","cfShellTsx","shell","start","end","cfDevVars","cfDevVarsExample","describe","description","CLOUDFLARE_RECIPES","includesRecipe","cloudflareRecipes","buildCloudflareScaffold","recipeOutput","routeFiles","blueprintJson","buildScaffold","app","buildFrameworkScaffold","agentFiles","buildAstroScaffold","examples","auth","DEFAULT_SECTIONS","optionsError","readBlueprint","blueprintOptions","parseBlueprint","resolve","cwd","create","yes","args","nameArg","themeArg","sectionsArg","frameworkArg","runtimeArg","exampleArgs","badExample","authArg","pmFlag","rl","stdin","createInterface","stdout","prompted","theme","resolvedTheme","sectionsInput","framework","resolvedFramework","fromArg","chosen","workspace","problem","targetDir","templateSpec","add","loadConfig"],"sources":["../src/generated/versions.ts","../../app/dist/path-DJjeYL9s.js","../../app/dist/vite.js","../src/scaffold/recipes.ts","../src/scaffold/workspace.ts","../src/commands/create.ts"],"sourcesContent":["// GENERATED by scripts/registry/cli-versions.ts — do not edit by hand.\n/**\n * Exact published versions, baked in at build time.\n *\n * Scaffolded apps pin these rather than `\"latest\"`: the cascivo packages version\n * independently on 0.x, so a floating specifier can resolve a mutually incompatible set,\n * and GETTING-STARTED.md tells adopters to pin exactly. Regenerate with `pnpm regen`.\n */\nexport const CASCIVO_VERSIONS: Record<string, string> = {\n '@cascivo/react': '1.11.0',\n '@cascivo/themes': '1.0.3',\n '@cascivo/astro': '1.11.0',\n '@cascivo/charts': '1.11.0',\n '@cascivo/icons': '1.1.1',\n '@cascivo/eslint-config': '0.4.2',\n '@cascivo/app': '1.11.0',\n '@cascivo/render': '1.11.0',\n '@cascivo/storage': '1.11.0',\n '@cascivo/email': '0.6.1',\n}\n\n/** `@cascivo/core`'s declared `@preact/signals-react` peer range. */\nexport const SIGNALS_PEER = '>=3.0.0'\n\n/**\n * This CLI's own version, stamped into every scaffold's cascivo.app.json. `cascivo app`\n * regenerates an app's original files with exactly this version as its merge base.\n */\nexport const CLI_VERSION = '1.8.2'\n","function normalizePath(e){let t=e.startsWith(`/`)?e:`/${e}`;return t.length>1?t.replace(/\\/+$/,``)||`/`:t}function escapeRegex(e){return e.replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}function compilePath(e){let t=normalizePath(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+=`/${escapeRegex(a)}`}),{pattern:e,keys:n,regex:RegExp(`^${i||`/`}/?$`),score:r}}function matchPath(e,t){let n=e.regex.exec(normalizePath(t));if(!n)return null;let r={};try{e.keys.forEach((e,t)=>{let i=n[t+1]??``;r[e]=e===`*`?i.split(`/`).map(decodeURIComponent).join(`/`):decodeURIComponent(i)})}catch{return null}return r}function compareSpecificity(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}function buildPath(e,t){let n=t;return`/${normalizePath(e).split(`/`).filter(Boolean).map(t=>{if(t===`*`)return(n[`*`]??``).split(`/`).map(encodeURIComponent).join(`/`);if(t.startsWith(`:`)){let r=n[t.slice(1)];if(r===void 0)throw Error(`Missing param \"${t.slice(1)}\" for \"${e}\"`);return encodeURIComponent(r)}return t}).filter(e=>e!==``).join(`/`)}`}export{normalizePath as a,matchPath as i,compareSpecificity as n,compilePath as r,buildPath as t};","import{n as e,r as t}from\"./path-DJjeYL9s.js\";import{existsSync as n,readFileSync as r,readdirSync as i,statSync as a,writeFileSync as o}from\"node:fs\";import{dirname as s,join as c,relative as l,resolve as u,sep as d}from\"node:path\";var f=/\\.(tsx|jsx)$/;function fileToRoutePath(e){if(!f.test(e)||/\\.(test|spec)\\.[jt]sx$/.test(e))return;let t=e.replace(f,``).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 scanRoutes(e){if(!n(e))return[];let t=[],walk=n=>{for(let r of i(n).sort()){let i=c(n,r);a(i).isDirectory()?walk(i):t.push(l(e,i).split(d).join(`/`))}};return walk(e),t}function generateRoutes(n,r){let i=[],a=/* @__PURE__ */ new Map;for(let e of n){let t=fileToRoutePath(e);if(t===void 0)continue;let n=a.get(t);if(n)throw Error(`routes/${n} and routes/${e} both define ${t??`the 404 route`}`);a.set(t,e),i.push({file:e,path:t})}let specifier=e=>`${r}/${e.replace(f,``)}`,o=i.filter(e=>e.path!==null).map(e=>({...e,compiled:t(e.path)})).sort((t,n)=>e(t.compiled,n.compiled)||t.path.localeCompare(n.path)),s=i.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[] = [`,...o.map(e=>` lazyRoute('${e.path}', () => import('${specifier(e.file)}')),`),`]`,``,s?`export const notFound: Route | undefined = lazyRoute('*', () => import('${specifier(s.file)}'))`:`export const notFound: Route | undefined = undefined`,``,\"/** Every route pattern. Fill one with `buildPath` for a typed link. */\",`export type AppPath = ${o.length>0?o.map(e=>`'${e.path}'`).join(` | `):`never`}`,``].join(`\n`)}function cascivoRoutes(e={}){let t=process.cwd(),dir=()=>u(t,e.dir??`src/routes`),out=()=>u(t,e.out??`src/routes.gen.ts`);function write(){let e=l(s(out()),dir()).split(d).join(`/`);e.startsWith(`.`)||(e=`./${e}`);let t=generateRoutes(scanRoutes(dir()),e);(n(out())?r(out(),`utf8`):null)!==t&&o(out(),t)}return{name:`cascivo:routes`,enforce:`pre`,configResolved(e){t=e.root},buildStart(){write()},configureServer(e){e.watcher.add(dir());let onChange=e=>{u(e).startsWith(dir()+d)&&write()};e.watcher.on(`add`,onChange),e.watcher.on(`unlink`,onChange)}}}export{cascivoRoutes,fileToRoutePath,generateRoutes,scanRoutes};","import { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { isSafeRelativePath } from '@cascivo/registry'\n\n/**\n * A recipe is one feature of a scaffold as data: a directory under `packages/cli/recipes/`\n * holding a `recipe.json` and the files it adds, at the paths they take in the app. The files\n * are the app's real source rather than template literals, so composing a scaffold is choosing\n * recipes, not threading conditionals through one generator.\n */\nexport interface Recipe {\n name: string\n /** App-relative paths, each a file in the recipe's directory. */\n files: string[]\n /** Side-nav entries for the pages the recipe adds, in the order they appear. */\n nav: RecipeNavItem[]\n /** `@cascivo/*` packages the files import, added to the app at the CLI's pinned version. */\n dependencies: string[]\n}\n\nexport interface RecipeNavItem {\n label: string\n /** An app path, starting with `/`. */\n href: string\n}\n\n/** The values a recipe file may reference as `{{key}}`. Unknown keys are left as written. */\nexport interface RecipeVars {\n /** The app's display name, as `brandName` derives it. */\n brand: string\n /** The project name with quotes and backslashes removed, for a single-quoted string. */\n appName: string\n /** The Workers Analytics Engine dataset the `usage` recipe writes to. */\n usageDataset: string\n}\n\nconst HERE = dirname(fileURLToPath(import.meta.url))\n\n/** `recipes/` beside `dist/` in the published package, or beside `src/` in the repo. */\nfunction recipesDir(): string {\n for (const candidate of [join(HERE, '..', 'recipes'), join(HERE, '..', '..', 'recipes')]) {\n if (existsSync(join(candidate, 'cloudflare', 'recipe.json'))) return candidate\n }\n throw new Error(`cascivo: the scaffold recipes are missing (looked beside ${HERE}).`)\n}\n\n/** Parse a `recipe.json`. `source` names the file in errors. */\nexport function parseRecipe(raw: unknown, source: string): Recipe {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw new Error(`${source}: a recipe must be an object.`)\n }\n const { name, files, nav = [], dependencies = [] } = raw as Record<string, unknown>\n if (typeof name !== 'string' || !/^[a-z][a-z0-9-]*$/.test(name)) {\n throw new Error(`${source}: \"name\" must be a lower-case kebab-case string.`)\n }\n if (!Array.isArray(files) || files.length === 0) {\n throw new Error(`${source}: \"files\" must be a non-empty array of paths.`)\n }\n const paths: string[] = []\n for (const file of files) {\n if (!isSafeRelativePath(file)) {\n throw new Error(`${source}: \"${String(file)}\" is not a safe relative path.`)\n }\n paths.push(file)\n }\n if (!Array.isArray(nav)) throw new Error(`${source}: \"nav\" must be an array.`)\n const items: RecipeNavItem[] = []\n for (const item of nav) {\n const { label, href } = (typeof item === 'object' && item !== null ? item : {}) as Record<\n string,\n unknown\n >\n if (\n typeof label !== 'string' ||\n label === '' ||\n typeof href !== 'string' ||\n !href.startsWith('/')\n ) {\n throw new Error(\n `${source}: each \"nav\" entry needs a \"label\" and an \"href\" starting with \"/\".`,\n )\n }\n items.push({ label, href })\n }\n if (\n !Array.isArray(dependencies) ||\n !dependencies.every((d) => typeof d === 'string' && /^@cascivo\\/[a-z-]+$/.test(d))\n ) {\n throw new Error(`${source}: \"dependencies\" must be an array of @cascivo/* package names.`)\n }\n return { name, files: paths, nav: items, dependencies: dependencies.map(String) }\n}\n\nconst cache = new Map<string, Recipe>()\n\nexport function loadRecipe(name: string): Recipe {\n const cached = cache.get(name)\n if (cached) return cached\n const source = join(recipesDir(), name, 'recipe.json')\n const recipe = parseRecipe(JSON.parse(readFileSync(source, 'utf8')) as unknown, source)\n if (recipe.name !== name) throw new Error(`${source}: \"name\" must be \"${name}\".`)\n cache.set(name, recipe)\n return recipe\n}\n\nconst PLACEHOLDER = /\\{\\{(brand|appName|usageDataset)\\}\\}/g\n\n/** The files a recipe adds, with `{{key}}` placeholders filled from `vars`. */\nexport function recipeFiles(name: string, vars: RecipeVars): { path: string; contents: string }[] {\n const dir = join(recipesDir(), name)\n return loadRecipe(name).files.map((path) => ({\n path,\n contents: readFileSync(join(dir, path), 'utf8').replace(\n PLACEHOLDER,\n (_, key: keyof RecipeVars) => vars[key],\n ),\n }))\n}\n\n/** The registry blocks a blueprint page can render: each has a `block-<name>` recipe. */\nexport function blockNames(): string[] {\n return readdirSync(recipesDir())\n .filter((dir) => dir.startsWith('block-'))\n .map((dir) => dir.slice('block-'.length))\n .sort()\n}\n","import { formatJson } from '../commands/create.js'\nimport type { ScaffoldFile } from '../commands/create.js'\n\n/**\n * `cascivo create --workspace`: the app inside a pnpm monorepo with the tooling a team would set\n * up next anyway. The app itself is the ordinary scaffold, moved to `apps/web`, so everything\n * `cascivo app` does keeps working from that directory.\n *\n * - `packages/ui`: the team's own components, imported by the app. Copying cascivo source to\n * own it (`cascivo add`) happens here, so every app in the workspace shares one copy.\n * - Vite+ (`vp run`) runs each package's scripts across the workspace, in dependency order\n * and cached.\n * - CI runs the same scripts on every push.\n */\nexport interface WorkspaceInput {\n /** The npm package name of the app; the workspace packages are scoped under it. */\n packageName: string\n /** The scaffold's files, as `cascivo create` writes them for a single app. */\n app: ScaffoldFile[]\n /** The first nav label, which the smoke test looks for. */\n firstLabel: string\n /** React + Vite apps get a component test setup; the cloudflare app tests its Worker itself. */\n testable: boolean\n /** The `@cascivo/react` version the app pins, for packages/ui. */\n reactVersion: string\n}\n\n// As Prettier prints it, so the app's own `format:check` passes on what it was given.\nconst json = formatJson\n\n/** Keys of a package.json that JSON.parse returned, with `dependencies`-like maps narrowed. */\nfunction parsePackageJson(contents: string): Record<string, unknown> {\n const raw: unknown = JSON.parse(contents)\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw new Error('cascivo: the scaffold wrote a package.json that is not an object')\n }\n return { ...raw }\n}\n\nfunction record(value: unknown): Record<string, string> {\n if (typeof value !== 'object' || value === null) return {}\n return Object.fromEntries(\n Object.entries(value).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string',\n ),\n )\n}\n\nconst ROOT_FILES = new Set(['.mcp.json'])\n\nexport function buildWorkspace(input: WorkspaceInput): ScaffoldFile[] {\n const scope = `@${input.packageName}`\n const ui = `${scope}/ui`\n const files: ScaffoldFile[] = []\n\n for (const file of input.app) {\n if (ROOT_FILES.has(file.path)) continue\n if (file.path === 'package.json') {\n const pkg = parsePackageJson(file.contents)\n const scripts = record(pkg.scripts)\n const devDependencies = record(pkg.devDependencies)\n files.push({\n path: 'apps/web/package.json',\n contents: json({\n ...pkg,\n name: `${scope}/web`,\n scripts: input.testable ? { ...scripts, test: 'vitest run' } : scripts,\n dependencies: { [ui]: 'workspace:*', ...record(pkg.dependencies) },\n devDependencies: input.testable\n ? {\n ...devDependencies,\n '@testing-library/react': '^16.3.0',\n jsdom: '^30.0.0',\n vitest: '^5.0.0',\n }\n : devDependencies,\n }),\n })\n continue\n }\n files.push({ path: `apps/web/${file.path}`, contents: file.contents })\n }\n\n if (input.testable) {\n files.push(\n {\n path: 'apps/web/vitest.config.ts',\n contents: `import { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n test: { environment: 'jsdom' },\n})\n`,\n },\n {\n path: 'apps/web/src/App.test.tsx',\n contents: `import { render, screen } from '@testing-library/react'\nimport { expect, it } from 'vitest'\nimport App from './App'\n\nit('renders the app shell and its navigation', () => {\n render(<App />)\n expect(screen.getAllByText('${input.firstLabel.replace(/'/g, \"\\\\'\")}').length).toBeGreaterThan(0)\n})\n`,\n },\n )\n }\n\n files.push(\n {\n path: 'packages/ui/package.json',\n contents: json({\n name: ui,\n private: true,\n version: '0.0.0',\n type: 'module',\n exports: { '.': './src/index.ts' },\n scripts: { typecheck: 'tsc --noEmit' },\n dependencies: { '@cascivo/react': input.reactVersion },\n peerDependencies: { react: '>=18.0.0' },\n devDependencies: { '@types/react': '^19.0.0', typescript: '^5.7.0' },\n }),\n },\n {\n path: 'packages/ui/tsconfig.json',\n contents: json({\n compilerOptions: {\n target: 'ES2022',\n module: 'ESNext',\n moduleResolution: 'bundler',\n jsx: 'react-jsx',\n strict: true,\n noEmit: true,\n skipLibCheck: true,\n },\n include: ['src'],\n }),\n },\n {\n path: 'packages/ui/src/index.ts',\n contents: `// The team's own components, shared by every app in the workspace. Build them from\n// @cascivo/react, or copy a cascivo component here to own its source:\n// cd packages/ui && npx cascivo add <name>\n// then export it below and import it in an app as \\`import { … } from '${ui}'\\`.\nexport {}\n`,\n },\n {\n path: 'package.json',\n contents: json({\n name: input.packageName,\n private: true,\n type: 'module',\n scripts: {\n dev: 'pnpm --filter ./apps/web dev',\n build: 'vp run -r build',\n typecheck: 'vp run -r typecheck',\n lint: 'vp run -r lint',\n ...(input.testable ? { test: 'vp run -r test' } : {}),\n 'format:check': 'vp run -r format:check',\n },\n devDependencies: { 'vite-plus': '^1.1.0' },\n }),\n },\n {\n path: 'pnpm-workspace.yaml',\n contents: `packages:\n - apps/*\n - packages/*\n# Install scripts pnpm runs: esbuild fetches the binary Vite builds with, workerd is the\n# Workers runtime. allowBuilds is pnpm 11's form, onlyBuiltDependencies pnpm 10's.\nallowBuilds:\n esbuild: true\n workerd: true\nonlyBuiltDependencies:\n - esbuild\n - workerd\n`,\n },\n {\n path: 'vite.config.ts',\n contents: `// Vite+ configuration for the workspace: \\`vp run\\` caches each package's tasks.\nimport { defineConfig } from 'vite-plus'\n\nexport default defineConfig({\n run: { cache: true },\n})\n`,\n },\n {\n path: '.gitignore',\n contents: 'node_modules\\ndist\\n.vite\\n',\n },\n {\n path: '.github/workflows/ci.yml',\n contents: `name: CI\n\non:\n push:\n pull_request:\n\njobs:\n check:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: pnpm/action-setup@v4\n with:\n version: 10\n - uses: actions/setup-node@v4\n with:\n node-version: 22\n cache: pnpm\n - run: pnpm install --frozen-lockfile\n - run: pnpm typecheck\n - run: pnpm lint\n${input.testable ? ' - run: pnpm test\\n' : ''} - run: pnpm build\n`,\n },\n {\n path: 'AGENTS.md',\n contents: `# Agent instructions — workspace\n\nA pnpm workspace. Run every command from this directory unless a step says otherwise.\n\n- \\`apps/web\\` is the app. Read \\`apps/web/AGENTS.md\\` before changing it. Grow it with\n \\`npx cascivo app add page \"<title>\" --block <name>\\`, run in \\`apps/web\\`.\n- \\`packages/ui\\` (\\`${ui}\\`) holds the team's own components. Copy a cascivo component here to\n own its source (\\`cd packages/ui && npx cascivo add <name>\\`), and export it from\n \\`src/index.ts\\`.\n- Checks: \\`pnpm typecheck\\`, \\`pnpm lint\\`,${input.testable ? ' `pnpm test`,' : ''} \\`pnpm build\\`. CI runs the same.\n`,\n },\n { path: 'CLAUDE.md', contents: '@AGENTS.md\\n' },\n )\n const mcp = input.app.find((f) => f.path === '.mcp.json')\n if (mcp) files.push(mcp)\n return files\n}\n","import { existsSync, readdirSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { stdin, stdout } from 'node:process'\nimport { createInterface } from 'node:readline/promises'\nimport {\n detectPackageManager,\n THEMES,\n type PackageManager,\n type ThemeName,\n} from '../utils/config.js'\nimport { flagValue, positionalArgs, resolvePackageManagerFlag } from '../utils/args.js'\nimport { writeFileSafe } from '../utils/fs.js'\nimport { CASCIVO_VERSIONS, CLI_VERSION, SIGNALS_PEER } from '../generated/versions.js'\n// Bundled into the CLI (a devDependency): the scaffold writes the same routes.gen.ts the\n// app's own Vite plugin will, so the two cannot drift.\nimport { generateRoutes } from '@cascivo/app/vite'\nimport { loadRecipe, recipeFiles } from '../scaffold/recipes.js'\nimport { mergeMcpConfig } from './mcp.js'\nimport { buildWorkspace } from '../scaffold/workspace.js'\nimport type { RecipeVars } from '../scaffold/recipes.js'\n\n/**\n * Exact published versions, baked in at build time by `scripts/registry/cli-versions.ts`.\n *\n * This used to be the literal `'latest'` for every cascivo dependency — the loosest\n * possible specifier on a set of independently-versioned 0.x packages, and the direct\n * opposite of GETTING-STARTED.md's \"pin **exact** versions (no `^`)\". A scaffold that\n * contradicts the docs on the very first file an adopter opens undermines every other rule\n * those docs state, so the pins are generated rather than hand-written.\n */\nconst V = CASCIVO_VERSIONS\n\n/** Install-everything command for a package manager (`pnpm install`, `yarn`, …). */\nfunction installAllCommand(pm: PackageManager): string {\n return pm === 'yarn' ? 'yarn' : `${pm} install`\n}\n\n/** Run-a-script command for a package manager (`npm run dev` vs `pnpm dev`). */\nfunction runScriptCommand(pm: PackageManager, script: string): string {\n return pm === 'npm' ? `npm run ${script}` : `${pm} ${script}`\n}\n\n/**\n * Like `runScriptCommand`, but always through `run`. A script named after a built-in\n * command needs it: `pnpm deploy` is pnpm's own workspace deploy, not the `deploy` script.\n */\nfunction runExplicitCommand(pm: PackageManager, script: string): string {\n return `${pm} run ${script}`\n}\n\n/** Project shape `create` emits. */\nexport type Framework = 'react-vite' | 'astro' | 'cloudflare'\n\nexport const FRAMEWORKS = ['react-vite', 'astro', 'cloudflare'] as const\n\n/** Client runtime for `--framework cloudflare`. The source is identical for both. */\nexport type Runtime = 'preact' | 'react'\n\nexport const RUNTIMES = ['preact', 'react'] as const\n\n/** Optional demo pages for `--framework cloudflare`. */\nexport type Example =\n | 'board'\n | 'agent'\n | 'notes'\n | 'import'\n | 'files'\n | 'export'\n | 'usage'\n | 'crud'\n | 'live'\n | 'voice'\n | 'publish'\n | 'webhooks'\n | 'digest'\n | 'search'\n | 'checkout'\n | 'newsletter'\n | 'social'\n\nexport const EXAMPLES = [\n 'board',\n 'agent',\n 'notes',\n 'import',\n 'files',\n 'export',\n 'usage',\n 'crud',\n 'live',\n 'voice',\n 'publish',\n 'webhooks',\n 'digest',\n 'search',\n 'checkout',\n 'newsletter',\n 'social',\n] as const\n\nexport function isExample(value: string): value is Example {\n return (EXAMPLES as readonly string[]).includes(value)\n}\n\nexport function isRuntime(value: string): value is Runtime {\n return (RUNTIMES as readonly string[]).includes(value)\n}\n\nexport interface ScaffoldOptions {\n /** Project directory + package name. */\n name: string\n /** Project shape. Defaults to `react-vite`. */\n framework?: Framework\n /** Theme imported in the entry CSS and set on `<html data-theme>`. */\n theme: ThemeName\n /** Display labels for the side-nav sections (one section component each). */\n sections: string[]\n /** Package manager for the generated README's commands (default npm). */\n pm?: PackageManager\n /**\n * Client runtime for the `cloudflare` framework. Defaults to `preact`, or `react` with the\n * `agent` example, whose Agents SDK hooks need React (see {@link runtimeOf}).\n */\n runtime?: Runtime\n /** Extra demo pages for the `cloudflare` framework. */\n examples?: Example[]\n /**\n * `cloudflare` framework only. `access`: the Worker refuses every request Cloudflare Access\n * did not let through. `email`: accounts with emailed sign-in links; `oauth`: accounts with\n * GitHub, Google and LinkedIn sign-in; `email,oauth`: both on one page. With accounts, every API write\n * needs a signed-in user.\n */\n auth?: Auth\n /**\n * The registry block each section's page renders, aligned with `sections` (a blueprint's\n * `pages[].block`). `undefined` keeps the placeholder page.\n */\n blocks?: (string | undefined)[]\n /** Put the app in a pnpm workspace (`apps/web` + `packages/ui`, Vite+, CI). */\n workspace?: boolean\n}\n\nexport type Auth = 'access' | 'email' | 'oauth' | 'email,oauth'\n\nexport interface ScaffoldFile {\n /** Path relative to the project root. */\n path: string\n contents: string\n}\n\ninterface Section {\n /** Discriminant used in the section signal + conditional render. */\n key: string\n /** Human-readable label shown in the nav and section heading. */\n label: string\n /** PascalCase component + file name. */\n component: string\n /** The registry block the page renders, from a blueprint (`recipes/block-<block>`). */\n block?: string\n}\n\n/** Slug suitable for a union-member string literal: lower-kebab, alnum only. */\nfunction slug(label: string): string {\n return (\n label\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'section'\n )\n}\n\n/** PascalCase identifier derived from a free-text label. */\nfunction pascalCase(label: string): string {\n const parts = label\n .trim()\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean)\n const joined = parts.map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('')\n const safe = joined || 'Section'\n return /^[0-9]/.test(safe) ? `Section${safe}` : safe\n}\n\n/**\n * Short, human-readable brand for the shell header.\n *\n * The directory name is the wrong thing to render verbatim: a dated demo directory\n * (`vercel-dashboard-2026-07-30-take2`) produced a 45-character brand in the top-left of\n * every page. Take the leading words, title-case them, and stop — a brand is a label, not a\n * slug. Bare numbers and `v2`-style segments are dropped rather than counted.\n */\nexport function brandName(name: string): string {\n const words = name\n .trim()\n .split(/[^a-zA-Z0-9]+/)\n .filter((w) => w !== '' && !/^\\d+$/.test(w) && !/^v\\d+$/i.test(w))\n const kept: string[] = []\n for (const word of words) {\n if (kept.length >= 3) break\n if (kept.length > 0 && kept.join(' ').length + 1 + word.length > 24) break\n kept.push(word.charAt(0).toUpperCase() + word.slice(1))\n }\n return kept.join(' ') || 'App'\n}\n\n/** Normalize the project name into a valid npm package name. */\nfunction packageName(name: string): string {\n return (\n name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'cascivo-app'\n )\n}\n\n/** Turn raw section labels into unique keyed/component-named sections. */\nfunction resolveSections(labels: string[], blocks: (string | undefined)[] = []): Section[] {\n const seenKeys = new Set<string>()\n const seenComponents = new Set<string>()\n const sections: Section[] = []\n for (const [index, label] of labels.entries()) {\n const trimmed = label.trim()\n if (!trimmed) continue\n let key = slug(trimmed)\n let component = pascalCase(trimmed)\n let n = 2\n while (seenKeys.has(key) || seenComponents.has(component)) {\n key = `${slug(trimmed)}-${n}`\n component = `${pascalCase(trimmed)}${n}`\n n++\n }\n seenKeys.add(key)\n seenComponents.add(component)\n const block = blocks[index]\n sections.push({ key, label: trimmed, component, ...(block ? { block } : {}) })\n }\n return sections.length > 0 ? sections : [{ key: 'home', label: 'Home', component: 'Home' }]\n}\n\nfunction packageJson(opts: ScaffoldOptions): string {\n const pkg = {\n name: packageName(opts.name),\n private: true,\n version: '0.0.0',\n type: 'module',\n scripts: {\n dev: 'vite',\n build: 'tsc && vite build',\n preview: 'vite preview',\n typecheck: 'tsc --noEmit',\n lint: 'eslint .',\n format: 'prettier --write .',\n 'format:check': 'prettier --check .',\n },\n // Prebuilt path (Path B): `@cascivo/react` and `@cascivo/themes` only.\n //\n // `@cascivo/core` and `@cascivo/tokens` are deliberately absent. AI-RULES.md: \"**Never**\n // add `@cascivo/core` to a prebuilt-path app's package.json — it is only a transitive\n // dependency there, and everything is re-exported from `@cascivo/react`.\"\n // GETTING-STARTED.md says the same of `@cascivo/tokens`, which arrives with\n // `@cascivo/themes` as a direct dependency. The scaffold used to declare both and then\n // import from them, so it violated two documented rules and taught the pattern by example.\n //\n // `@preact/signals-react` IS declared: it is a required peer that the generated\n // `App.tsx` calls into via `useSignals()`. It used to be omitted entirely and survived\n // only by hoisting — a phantom dependency that breaks under pnpm's strict layout.\n dependencies: {\n ...blockDependencies(opts),\n '@cascivo/react': V['@cascivo/react']!,\n '@cascivo/themes': V['@cascivo/themes']!,\n '@preact/signals-react': SIGNALS_PEER,\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n },\n devDependencies: {\n '@cascivo/eslint-config': V['@cascivo/eslint-config']!,\n '@eslint/js': '^9.0.0',\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n '@vitejs/plugin-react': '^5.0.0',\n eslint: '^9.0.0',\n 'eslint-plugin-react-hooks': '^7.0.0',\n prettier: '^3.0.0',\n typescript: '^5.7.0',\n // Registers the TypeScript parser AND the `files` patterns that make ESLint look at\n // .ts/.tsx at all. Without it ESLint 9's default `files` is **/*.{js,cjs,mjs}, so\n // `lint` on a TypeScript-only app exits 0 having inspected zero files — a green check\n // that proves nothing (2026-08-08 report B).\n 'typescript-eslint': '^8.0.0',\n vite: '^7.0.0',\n },\n }\n return JSON.stringify(pkg, null, 2) + '\\n'\n}\n\n/**\n * JSON as Prettier prints it: an array of strings stays on one line. `JSON.stringify` breaks\n * every array across lines, so a fresh app failed its own `format:check` on tsconfig.json.\n */\nexport function formatJson(value: unknown): string {\n const json = JSON.stringify(value, null, 2).replace(\n /\\[\\n\\s+(\"[^\"\\n]*\"(?:,\\n\\s+\"[^\"\\n]*\")*)\\n\\s*\\]/g,\n (_, items: string) => `[${items.split(/,\\n\\s+/).join(', ')}]`,\n )\n return json + '\\n'\n}\n\nfunction tsconfig(): string {\n const cfg = {\n compilerOptions: {\n target: 'ES2022',\n useDefineForClassFields: true,\n lib: ['ES2022', 'DOM', 'DOM.Iterable'],\n module: 'ESNext',\n skipLibCheck: true,\n moduleResolution: 'bundler',\n allowImportingTsExtensions: true,\n resolveJsonModule: true,\n isolatedModules: true,\n moduleDetection: 'force',\n noEmit: true,\n jsx: 'react-jsx',\n strict: true,\n noUnusedLocals: true,\n noUnusedParameters: true,\n noFallthroughCasesInSwitch: true,\n },\n include: ['src'],\n }\n return formatJson(cfg)\n}\n\nfunction viteConfig(): string {\n return `import react from '@vitejs/plugin-react'\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n plugins: [react()],\n})\n`\n}\n\nfunction indexHtml(opts: ScaffoldOptions): string {\n return `<!doctype html>\n<html lang=\"en\" data-theme=\"${opts.theme}\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${brandName(opts.name)}</title>\n <style>\n @layer vendor, cascivo.reset, cascivo.base, cascivo.tokens, cascivo.component,\n cascivo.platform, cascivo.theme, cascivo.blocks, cascivo.example, cascivo.override;\n /* cascivo.example is this app's own slot — above the component/blocks layers so your\n styles win, below cascivo.override which stays free for one-off hotfixes. The\n generated AGENTS.md tells the agent to write there, and this statement is what makes\n that legal: a layer used but never declared falls to the end of the cascade and\n beats everything, which is the opposite of what the ordering is for. */\n /* Third-party CSS goes in the low-priority vendor layer so it can't beat cascivo:\n @import url('some-lib/styles.css') layer(vendor); — see docs/THIRD-PARTY-CSS.md */\n @layer cascivo.reset {\n *,\n *::before,\n *::after {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n }\n }\n @layer cascivo.base {\n html,\n body,\n #root {\n height: 100%;\n }\n }\n </style>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/src/main.tsx\"></script>\n </body>\n</html>\n`\n}\n\nfunction mainTsx(): string {\n return `import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\n\nconst root = document.getElementById('root')\nif (root) {\n ReactDOM.createRoot(root).render(\n <React.StrictMode>\n <App />\n </React.StrictMode>,\n )\n}\n`\n}\n\nfunction viteEnv(): string {\n return `/// <reference types=\"vite/client\" />\\n`\n}\n\n// No `opts`: the theme import and the brand moved to `Shell.tsx`, which owns the app chrome.\nfunction appTsx(sections: Section[]): string {\n const sectionImports = sections\n .map((s) => `import { ${s.component} } from './sections/${s.component}'`)\n .join('\\n')\n\n // As Prettier prints it (printWidth 100): one line while it fits, else one member per line.\n // A long section list otherwise fails the app's own `format:check`.\n const oneLine = `type Section = ${sections.map((s) => `'${s.key}'`).join(' | ')}`\n const sectionType =\n oneLine.length <= 100\n ? oneLine\n : `type Section =\\n${sections.map((s) => ` | '${s.key}'`).join('\\n')}`\n\n const navItems = sections\n .map(\n (s) => ` {\n label: '${s.label.replace(/'/g, \"\\\\'\")}',\n active: section.value === '${s.key}',\n onClick: (e) => {\n e.preventDefault()\n section.value = '${s.key}'\n },\n },`,\n )\n .join('\\n')\n\n const renderedSections = sections\n .map((s) => ` {section.value === '${s.key}' && <${s.component} />}`)\n .join('\\n')\n\n // Everything comes from `@cascivo/react` on the prebuilt path — it re-exports the\n // `@cascivo/core` primitives, so importing from `@cascivo/core` directly would make it a\n // phantom dependency (and AI-RULES.md forbids declaring it here). There is likewise no\n // `import '@cascivo/tokens'`: the tokens arrive with the theme stylesheet.\n return `'use client'\nimport { signal, useSignals, type SideNavItem } from '@cascivo/react'\nimport { Shell } from './Shell'\n${sectionImports}\n\n${sectionType}\n\nconst section = signal<Section>('${sections[0]!.key}')\n\nexport default function App() {\n useSignals()\n\n const navItems: SideNavItem[] = [\n${navItems}\n ]\n\n return (\n <Shell navItems={navItems}>\n${renderedSections}\n </Shell>\n )\n}\n`\n}\n\n/**\n * The app shell, as its own component with a `children` slot.\n *\n * Split out of `App.tsx` because the shell composition — AppShell + ShellHeader + SideNav —\n * is the valuable part of the scaffold, and it used to be welded to the signal-driven\n * section switcher. A 2026-08-14 adopter prompted for \"a dashboard with Vite and React\n * Router\", then deleted `App.tsx` and all of `src/sections/` — the majority of what `create`\n * generated — and re-derived this wiring by hand.\n *\n * Now adding a router means deleting `App.tsx` + `src/sections/` and rendering `<Shell>` from\n * the root route's layout, with `navItems` carrying `href` instead of `onClick`. Nothing in\n * here needs to change.\n */\nfunction shellTsx(opts: ScaffoldOptions): string {\n return `'use client'\nimport { AppShell, ShellHeader, SideNav, type SideNavItem } from '@cascivo/react'\nimport type { ReactNode } from 'react'\n\nimport '@cascivo/themes/${opts.theme}.css'\n// No '@cascivo/react/styles.css' here. On a bundler build each component imports its\n// own CSS, so you ship exactly what you use — this app emits well under 100 kB of entry\n// CSS instead of the ~273 kB aggregate sheet. Import the aggregate ONLY if you drop the\n// bundler (CDN / single-file setup). See https://cascivo.com/docs/getting-started.md\n// The theme import above is always required — themes are never automatic.\n\nexport interface ShellProps {\n /** Side-nav entries. Use \\`href\\` for a routed app, \\`onClick\\` for local state. */\n navItems: SideNavItem[]\n children: ReactNode\n}\n\n/**\n * App shell: header + side nav + a content slot.\n *\n * Adding a router? Keep this file. Delete \\`App.tsx\\` and \\`src/sections/\\`, render\n * \\`<Shell navItems={…}>\\` from your root route's layout with your \\`<Outlet />\\` as children,\n * and give each nav item an \\`href\\` instead of an \\`onClick\\`.\n *\n * For those hrefs to become real router links, call \\`setLinkComponent\\` ONCE at startup in\n * \\`main.tsx\\` — see the \"Adding a router\" section of README.md for the exact snippet, or\n * https://cascivo.com/docs/using-with-a-router.md for the full recipe.\n */\nexport function Shell({ navItems, children }: ShellProps) {\n return (\n${appShellOpenTag(opts, 'navItems')}\n {children}\n </AppShell>\n )\n}\n`\n}\n\n/**\n * A page that renders a registry block. The block's source is the app's own, in `src/blocks/`,\n * written there by its `block-<name>` recipe.\n */\nfunction blockPageTsx(\n section: Section,\n declaration: 'export function' | 'export default function',\n): string {\n const block = pascalCase(section.block!)\n const local = block === section.component ? `${block}Block` : block\n return `import { ${local === block ? block : `${block} as ${local}`} } from '../blocks/${section.block}'\n\n${declaration} ${section.component}() {\n return <${local} />\n}\n`\n}\n\n/** The packages the pages' blocks bring (`@cascivo/charts`), at the versions this CLI pins. */\nfunction blockDependencies(opts: ScaffoldOptions): Record<string, string> {\n const packages = new Set(\n (opts.blocks ?? []).flatMap((block) =>\n block ? loadRecipe(`block-${block}`).dependencies : [],\n ),\n )\n return Object.fromEntries(\n [...packages].sort().map((name) => {\n const version = V[name]\n if (!version) throw new Error(`cascivo: no pinned version for ${name}`)\n return [name, version]\n }),\n )\n}\n\n/** The recipe files for every block the pages render, each once. */\nfunction blockFiles(sections: Section[], opts: ScaffoldOptions): ScaffoldFile[] {\n const blocks = [...new Set(sections.flatMap((s) => (s.block ? [s.block] : [])))]\n return blocks.flatMap((block) => recipeFiles(`block-${block}`, recipeVars(opts)))\n}\n\nfunction recipeVars(opts: ScaffoldOptions): RecipeVars {\n return {\n brand: brandName(opts.name),\n appName: opts.name.replace(/[\\\\']/g, ''),\n usageDataset: usageDataset(opts),\n }\n}\n\nfunction sectionTsx(section: Section): string {\n if (section.block) return blockPageTsx(section, 'export function')\n // No inline styles: the generated AGENTS.md tells the agent not to write them, and a\n // scaffold that models the opposite teaches the opposite. The page inset comes from\n // AppShell's own \\`padding\\` prop, and the stacking from \\`Flex\\` — note \\`gap\\` takes a\n // NUMBER (a space-scale step), not a string.\n return `import { Card, CardContent, CardHeader, CardTitle, Flex, Heading, Text } from '@cascivo/react'\n\nexport function ${section.component}() {\n return (\n <Flex gap={6}>\n <Flex gap={2}>\n <Heading level={1}>${section.label}</Heading>\n <Text muted>\n Edit <code>src/sections/${section.component}.tsx</code> to build out this page.\n </Text>\n </Flex>\n\n <Card>\n <CardHeader>\n <CardTitle>Get started</CardTitle>\n </CardHeader>\n <CardContent>\n <Text>\n This page is wired into the app shell. Add components with{' '}\n <code>npx cascivo add <component></code>.\n </Text>\n </CardContent>\n </Card>\n </Flex>\n )\n}\n`\n}\n\n/**\n * ESLint flat config for the scaffold.\n *\n * `@cascivo/eslint-config` is wired in from the start because\n * `eslint-plugin-react-hooks@7`'s `recommended-latest` reports every `signal.value = next`\n * — the idiom AI-RULES.md mandates and the generated `App.tsx` below uses — as\n * `Error: This value cannot be modified`. Without this, `pnpm lint` on a freshly scaffolded\n * app errors on every piece of state it ships with.\n */\nfunction eslintConfig(): string {\n return `import js from '@eslint/js'\nimport tseslint from 'typescript-eslint'\nimport reactHooks from 'eslint-plugin-react-hooks'\nimport cascivo from '@cascivo/eslint-config'\n\nexport default [\n { ignores: ['dist/**'] },\n js.configs.recommended,\n // Registers the TypeScript parser and the .ts/.tsx \\`files\\` patterns. WITHOUT THIS ESLINT\n // LINTS NOTHING: its default \\`files\\` is **/*.{js,cjs,mjs}, so every file in this app is\n // skipped with \"File ignored because no matching configuration was supplied\" and the\n // \\`lint\\` script exits 0 having checked zero files.\n ...tseslint.configs.recommended,\n // NOTE the \\`.flat\\` — the plugin exports both \\`configs['recommended-latest']\\` (the legacy\n // eslintrc shape, which applies NOTHING here and reports no error) and this one.\n reactHooks.configs.flat['recommended-latest'],\n // Spread LAST — flat config is last-wins. This turns off \\`react-hooks/immutability\\`,\n // which reports cascivo's signal writes (\\`signal.value = next\\`) as errors. That rule\n // fires on the very first \\`signal.value = x\\` you write, so this is not optional wiring:\n // see https://cascivo.com/docs/using-with-strict-eslint.md\n ...cascivo,\n]\n`\n}\n\n/** Prettier config matching the style the scaffold's own generated source is written in. */\n/**\n * The shell's `<AppShell …>` opening tag, laid out as Prettier lays it out: on one line when it\n * fits in the 100-column print width (a short app name), split over its attributes otherwise.\n * Always writing the split form made a fresh app with a short name fail its own format:check.\n */\nfunction appShellOpenTag(opts: ScaffoldOptions, items: string): string {\n const header = `header={<ShellHeader brand={{ name: '${brandName(opts.name).replace(/'/g, \"\\\\'\")}' }} />}`\n const nav = `nav={<SideNav items={${items}} />}`\n const line = ` <AppShell ${header} ${nav}>`\n return line.length <= 100 ? line : ` <AppShell\\n ${header}\\n ${nav}\\n >`\n}\n\nfunction prettierrc(): string {\n return JSON.stringify({ semi: false, singleQuote: true, printWidth: 100 }, null, 2) + '\\n'\n}\n\nfunction prettierIgnore(): string {\n return `dist\nnode_modules\n# Vendored cascivo source is formatted upstream — reformatting it makes every\n# \\`cascivo add\\` update a merge conflict.\nsrc/components/ui/\n`\n}\n\nfunction gitignore(): string {\n return `node_modules\ndist\n*.local\n.DS_Store\n`\n}\n\n/**\n * \"Share a preview\" for a static build: Cloudflare Drop takes the folder with no account, and\n * `wrangler deploy --temporary --assets` is the same thing from a terminal (or an agent).\n */\nfunction staticShareSection(opts: ScaffoldOptions): string {\n const pm = opts.pm ?? 'npm'\n return `\n## Share a preview\n\nNo Cloudflare account needed. Run \\`${runScriptCommand(pm, 'build')}\\`, then either:\n\n- drag the \\`dist/\\` folder onto [Cloudflare Drop](https://www.cloudflare.com/drop/), or\n- from a terminal: \\`npx wrangler deploy --temporary --assets dist --name ${packageName(opts.name)} --compatibility-date ${COMPATIBILITY_DATE}\\`\n\nEither way you get a public URL that lasts 60 minutes. Sign in to Cloudflare within that hour\nto keep it.\n`\n}\n\nfunction readme(opts: ScaffoldOptions): string {\n const pm = opts.pm ?? 'npm'\n return `# ${opts.name}\n\nA [cascivo](https://cascivo.com) app — Vite + React + TypeScript, pre-wired with\nthe cascivo app shell, side navigation, and the \\`${opts.theme}\\` theme.\n\n## Develop\n\n\\`\\`\\`sh\n${installAllCommand(pm)}\n${runScriptCommand(pm, 'dev')}\n\\`\\`\\`\n\n## Structure\n\n- \\`src/Shell.tsx\\` — the app shell (header + side nav + content slot). Router-agnostic.\n- \\`src/App.tsx\\` — nav items and which section is showing\n- \\`src/sections/\\` — one component per nav item\n\nAdd more components with \\`npx cascivo add <component>\\`.\n\n## Adding a router\n\nThis app switches sections with a signal, not a router. To add one (React Router,\nTanStack Router, …):\n\n1. **Keep \\`src/Shell.tsx\\`.** Delete \\`src/App.tsx\\` and \\`src/sections/\\`.\n2. Render \\`<Shell navItems={…}>\\` from your root route's layout, with your \\`<Outlet />\\`\n as its children.\n3. Give each nav item an \\`href\\` instead of \\`onClick\\`.\n4. Register your router's Link **once** at startup, in \\`src/main.tsx\\`:\n\n\\`\\`\\`tsx\nimport { setLinkComponent } from '@cascivo/react'\nimport type { LinkComponentProps } from '@cascivo/react'\nimport { Link } from 'react-router'\n\nsetLinkComponent(({ href, ...rest }: LinkComponentProps) => <Link to={href ?? '#'} {...rest} />)\n\\`\\`\\`\n\nThat one call makes \\`SideNav\\`, \\`ShellHeader\\` and \\`Breadcrumb\\` render real router links.\nLinks you write in page content use \\`<Link asChild>\\` instead — two kinds of link, two\nmechanisms. Full recipe: https://cascivo.com/docs/using-with-a-router.md\n${staticShareSection(opts)}`\n}\n\nfunction agentsMd(opts: ScaffoldOptions): string {\n return `# Agent instructions — ${opts.name}\n\nThis is a [cascivo](https://cascivo.com) app. When generating or editing CSS, follow\nthe **layer contract** — cascivo styles live in cascade layers, and layer order beats\nselector specificity.\n\n## CSS layer contract\n\n1. Every declaration goes inside an \\`@layer\\` block. Unlayered CSS beats all layers\n regardless of specificity — never emit it.\n2. Never invent layer names. Write only: your app slot \\`cascivo.example\\` (declared in\n the order statement in \\`index.html\\`) for page styles, and\n \\`@layer cascivo.override { … }\\` for hotfixes / one-off overrides — it beats\n everything cascivo ships.\n3. Never nest layers deeper than the shipped \\`cascivo.blocks.<name>\\` pattern. For\n sub-elements, use native CSS nesting inside one layer block, not new sublayers.\n4. Third-party CSS: \\`@import url('lib/styles.css') layer(vendor);\\` with \\`vendor\\`\n declared before the cascivo layers. Don't import vendor CSS from JavaScript — route it\n through a CSS file, or use \\`@cascivo/vite-plugin\\` (\\`cascivoLayers\\`) to layer it.\n5. Style with \\`--cascivo-*\\` tokens, not raw values.\n\nThis app's declared layer order (in \\`index.html\\`):\n\n\\`\\`\\`css\n@layer vendor, cascivo.reset, cascivo.base, cascivo.tokens, cascivo.component,\n cascivo.platform, cascivo.theme, cascivo.blocks, cascivo.example, cascivo.override;\n\\`\\`\\`\n\n### Worked example — nesting, not new layers\n\n\\`\\`\\`css\n@layer cascivo.override {\n .projectCard {\n /* Sub-elements nest inside the one block — no cascivo.card.status sublayer. */\n .statusBadge {\n color: var(--cascivo-color-text-subtle);\n .pulseDot {\n background: var(--cascivo-color-success);\n }\n }\n }\n}\n\\`\\`\\`\n\n## Routing\n\nIf you add a router, keep \\`src/Shell.tsx\\` and delete \\`src/App.tsx\\` + \\`src/sections/\\`.\n\ncascivo links come in **two kinds**, wired two different ways. Do not intercept\n\\`onClick\\`, and do not hand-wrap nav items:\n\n1. **Config-driven navs** (\\`SideNav\\`, \\`ShellHeader\\`, \\`Breadcrumb\\`, \\`Switcher\\`) render\n through a module singleton. Register your router's Link once, in \\`src/main.tsx\\`:\n \\`setLinkComponent(({ href, ...rest }: LinkComponentProps) => <Link to={href ?? '#'} {...rest} />)\\`\n2. **Links in page content** use \\`asChild\\`:\n \\`<Link asChild><RouterLink to=\"/x\">x</RouterLink></Link>\\`\n\nFull recipe: https://cascivo.com/docs/using-with-a-router.md\n\n## Types\n\nThe vocabulary types are on a subpath: \\`import type { Tone } from '@cascivo/react/types'\\`\n(also \\`Progress\\`, \\`SpaceStep\\`). \\`Status.status\\` and \\`Badge.variant\\` use them, so a\n\\`Record<MyState, Tone>\\` is the supported way to map domain states onto tones. **Never**\nadd \\`@cascivo/core\\` to this app's dependencies — it is transitive here.\n\nMore: cascivo's machine-readable guide is at https://cascivo.com/llms.txt.\n`\n}\n\n/** Build the full set of files for a new cascivo app. Pure — no filesystem I/O. */\n/* ------------------------------------------------------------------------- *\n * Astro scaffold (`--framework astro`)\n *\n * Shaped around what Astro is actually for, rather than transliterating the Vite SPA:\n * pages are real routes (no router to add later), page CONTENT is cascivo components\n * rendered with no client directive at all — server HTML, zero JS — and the only island\n * is the shell, which needs JS for its mobile nav drawer.\n *\n * The `astro.config.mjs` this emits carries one non-obvious required line —\n * `vite.resolve.noExternal` — without which SSR'd islands render unstyled. Baking that in\n * is most of why this scaffold is worth having; see the comment on `astroConfig` and\n * docs/USING-WITH-ASTRO.md.\n * ------------------------------------------------------------------------- */\n\n/** Route for a section. The first section owns the index route. */\nfunction sectionPath(section: Section, index: number): string {\n return index === 0 ? '/' : `/${section.key}`\n}\n\n/** Page file for a section, relative to `src/pages/`. */\nfunction sectionPageFile(section: Section, index: number): string {\n return index === 0 ? 'index.astro' : `${section.key}.astro`\n}\n\nfunction astroPackageJson(opts: ScaffoldOptions): string {\n const pkg = {\n name: packageName(opts.name),\n private: true,\n version: '0.0.0',\n type: 'module',\n scripts: {\n dev: 'astro dev',\n build: 'astro build',\n preview: 'astro preview',\n typecheck: 'astro check',\n lint: 'eslint .',\n format: 'prettier --write .',\n 'format:check': 'prettier --check .',\n },\n // Same prebuilt-path rule as the Vite scaffold: `@cascivo/react` + `@cascivo/themes`\n // only. `@cascivo/core` and `@cascivo/tokens` are transitive and must not be declared.\n dependencies: {\n '@astrojs/react': '^7.1.0',\n '@cascivo/astro': V['@cascivo/astro']!,\n '@cascivo/react': V['@cascivo/react']!,\n '@cascivo/themes': V['@cascivo/themes']!,\n '@preact/signals-react': SIGNALS_PEER,\n astro: '^7.0.0',\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n },\n devDependencies: {\n // @astrojs/check 0.9 peers TypeScript ^5 || ^6 and refuses 7, so `typescript` below stays on 5.\n '@astrojs/check': '^0.9.0',\n '@cascivo/eslint-config': V['@cascivo/eslint-config']!,\n '@eslint/js': '^9.0.0',\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n eslint: '^9.0.0',\n 'eslint-plugin-react-hooks': '^7.0.0',\n prettier: '^3.0.0',\n typescript: '^5.7.0',\n 'typescript-eslint': '^8.0.0',\n },\n }\n return JSON.stringify(pkg, null, 2) + '\\n'\n}\n\nfunction astroConfig(opts: ScaffoldOptions): string {\n return `// @ts-check\nimport { defineConfig } from 'astro/config'\nimport react from '@astrojs/react'\nimport cascivo from '@cascivo/astro'\n\nexport default defineConfig({\n // @cascivo/astro injects, on every page and ahead of any other CSS, the layer order and then\n // the theme, and inlines a no-flash theme script that survives <ClientRouter /> swaps.\n // \\`layers\\` is the statement in src/styles/layers.css, this app's cascivo.example slot included.\n // Both theme options name the app's theme: the defaults (light-dark.css and the OS\n // preference) would repaint any other theme as plain light or dark.\n integrations: [\n react(),\n cascivo({\n layers:\n '${ASTRO_LAYER_ORDER}',\n theme: '@cascivo/themes/${opts.theme}.css',\n themeScript: { defaultTheme: '${opts.theme}' },\n }),\n ],\n vite: {\n resolve: {\n // Kept for @cascivo/react 1.9.0 and older; @cascivo/astro sets it too, and newer\n // versions do not need it (their package carries the \\`astro-component\\` keyword).\n //\n // Vite externalizes node_modules packages in its server build, so an externalized\n // @cascivo/react is imported by Node at runtime and its module graph is never walked\n // — and Astro collects a page's CSS by walking that graph. On those versions, without\n // it, SSR'd islands (client:load, client:visible) render with correct class names and no\n // rules anywhere in the output. Nothing warns; it reads as a theming problem.\n //\n // It must be \\`resolve.noExternal\\`, NOT \\`ssr.noExternal\\`: Astro prerenders static\n // routes in its own Vite environment, which \\`ssr.*\\` does not reach.\n // https://cascivo.com/docs/using-with-astro.md\n noExternal: [/^@cascivo\\\\//],\n },\n },\n})\n`\n}\n\nfunction astroTsconfig(): string {\n const cfg = {\n extends: 'astro/tsconfigs/strict',\n include: ['.astro/types.d.ts', '**/*'],\n exclude: ['dist'],\n compilerOptions: { jsx: 'react-jsx' },\n }\n return JSON.stringify(cfg, null, 2) + '\\n'\n}\n\n/**\n * The Astro scaffold's complete layer order: `vendor` lowest, the canonical cascivo layers,\n * and this app's `cascivo.example` slot just below `cascivo.override`. One constant, because\n * it is both passed to `@cascivo/astro` (which injects it first on every page) and repeated\n * in `src/styles/layers.css`; two copies would drift. One literal, not a concatenation:\n * scripts/checks/layer-order.test.ts scans this file for `@layer …;` statements, and a split\n * string would hide this one from it.\n */\nconst ASTRO_LAYER_ORDER =\n '@layer vendor, cascivo.reset, cascivo.base, cascivo.tokens, cascivo.component, cascivo.platform, cascivo.theme, cascivo.blocks, cascivo.example, cascivo.override;'\n\n/**\n * The reset and base rules, under the same order statement `@cascivo/astro` injects first.\n *\n * Layers take their order from first appearance, so the statement that counts is the\n * integration's, which lands before any cascivo CSS; a statement that only arrived after the\n * theme could reorder nothing, and `vendor` would win over every cascivo layer. Repeating the\n * identical statement here is idempotent and keeps the file readable on its own.\n */\nfunction astroLayersCss(): string {\n return `/* Cascade layer order. Later layers beat earlier ones regardless of specificity.\n @cascivo/astro injects this same statement first on every page (\\`layers\\` in\n astro.config.mjs); keep the two identical. Repeating it here is harmless.\n\n cascivo.example is this app's own slot: above the component and blocks layers so your\n page styles win, below cascivo.override which stays free for one-off hotfixes.\n Third-party CSS goes in vendor so it cannot beat cascivo:\n @import url('some-lib/styles.css') layer(vendor);\n See https://cascivo.com/docs/third-party-css.md */\n${ASTRO_LAYER_ORDER}\n\n@layer cascivo.reset {\n *,\n *::before,\n *::after {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n }\n}\n\n@layer cascivo.base {\n html,\n body {\n block-size: 100%;\n }\n}\n`\n}\n\nfunction astroLayout(opts: ScaffoldOptions): string {\n return `---\n// The layer order and the ${opts.theme} theme come from @cascivo/astro in astro.config.mjs,\n// injected ahead of this file on every page. This adds the reset and base rules.\nimport '../styles/layers.css'\n\n// No '@cascivo/react/styles.css'. Each component brings its own CSS through the module\n// graph, so you ship only what your pages use. Import the aggregate ONLY if you drop the\n// bundler entirely.\n\ninterface Props {\n title: string\n}\n\nconst { title } = Astro.props\n---\n\n<!doctype html>\n<html lang=\"en\" data-theme=\"${opts.theme}\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>{title} · ${brandName(opts.name)}</title>\n </head>\n <body>\n <slot />\n </body>\n</html>\n`\n}\n\n/**\n * The app shell — the ONLY island in the scaffold.\n *\n * It is hydrated because AppShell's nav drawer is interactive on small screens. Page\n * content is slotted in as children and stays server-rendered HTML, so a page costs the\n * shell's JS and nothing more.\n */\nfunction astroShellTsx(opts: ScaffoldOptions, sections: Section[]): string {\n const navItems = sections\n .map((s, i) => ` { label: '${s.label.replace(/'/g, \"\\\\'\")}', href: '${sectionPath(s, i)}' },`)\n .join('\\n')\n\n return `import { AppShell, ShellHeader, SideNav, type SideNavItem } from '@cascivo/react'\nimport type { ReactNode } from 'react'\n\nconst NAV: { label: string; href: string }[] = [\n${navItems}\n]\n\nexport interface ShellProps {\n /** Current route, e.g. \\`Astro.url.pathname\\`. Marks the matching nav item active. */\n activePath: string\n children: ReactNode\n}\n\n/**\n * Header + side nav + a content slot.\n *\n * Nav items carry \\`href\\`, so navigation is a real page load and Astro's router handles\n * it — there is no client router to register and no \\`setLinkComponent\\` call to make.\n */\nexport function Shell({ activePath, children }: ShellProps) {\n const items: SideNavItem[] = NAV.map((item) => ({\n ...item,\n active: item.href === activePath,\n }))\n\n return (\n${appShellOpenTag(opts, 'items')}\n {children}\n </AppShell>\n )\n}\n`\n}\n\n/**\n * A section's content as a plain React component with NO \\`'use client'\\`.\n *\n * Astro renders it on the server and ships no JavaScript for it. Add a client directive at\n * the call site in the page only when a section actually needs interactivity.\n */\nfunction astroSectionTsx(section: Section): string {\n return `import { Card, CardContent, CardHeader, CardTitle, Flex, Heading, Text } from '@cascivo/react'\n\nexport function ${section.component}() {\n return (\n <Flex gap={6}>\n <Flex gap={2}>\n <Heading level={1}>${section.label}</Heading>\n <Text muted>\n Edit <code>src/components/${section.component}.tsx</code> to build out this page.\n </Text>\n </Flex>\n\n <Card>\n <CardHeader>\n <CardTitle>Get started</CardTitle>\n </CardHeader>\n <CardContent>\n <Text>\n This page is server-rendered — no JavaScript ships for it. Add components with{' '}\n <code>npx cascivo add <component></code>.\n </Text>\n </CardContent>\n </Card>\n </Flex>\n )\n}\n`\n}\n\nfunction astroPage(section: Section, index: number): string {\n return `---\nimport Layout from '../layouts/Layout.astro'\nimport { Shell } from '../components/Shell'\nimport { ${section.component} } from '../components/${section.component}'\n---\n\n<Layout title=\"${section.label}\">\n {/* client:load hydrates the shell for its mobile nav drawer. The section below stays\n server-rendered HTML — it is slotted in as children and ships no JS. */}\n <Shell client:load activePath=\"${sectionPath(section, index)}\">\n <${section.component} />\n </Shell>\n</Layout>\n`\n}\n\nfunction astroGitignore(): string {\n return `node_modules\ndist\n.astro\n*.local\n.DS_Store\n`\n}\n\nfunction astroReadme(opts: ScaffoldOptions, sections: Section[]): string {\n const pm = opts.pm ?? 'npm'\n const routes = sections\n .map((s, i) => `- \\`${sectionPath(s, i)}\\` — \\`src/pages/${sectionPageFile(s, i)}\\``)\n .join('\\n')\n\n return `# ${opts.name}\n\nA [cascivo](https://cascivo.com) app — Astro + React islands + TypeScript, pre-wired with\nthe cascivo app shell, side navigation, and the \\`${opts.theme}\\` theme.\n\n## Develop\n\n\\`\\`\\`sh\n${installAllCommand(pm)}\n${runScriptCommand(pm, 'dev')}\n\\`\\`\\`\n\n## Routes\n\n${routes}\n\nAdd a page by dropping a new \\`.astro\\` file in \\`src/pages/\\` — Astro routes it by filename.\nAdd it to \\`NAV\\` in \\`src/components/Shell.tsx\\` to get a nav entry.\n\n## What hydrates, and what doesn't\n\nOnly \\`Shell\\` carries a client directive (\\`client:load\\`), because its nav drawer is\ninteractive on small screens. Everything inside it is slotted in as children and stays\nserver-rendered HTML, so a page ships the shell's JavaScript and nothing else.\n\nNeed a section to be interactive? Give it a directive at the call site in the page:\n\n\\`\\`\\`astro\n<${sections[0]!.component} client:visible />\n\\`\\`\\`\n\nA component that reads \\`signal.value\\` during render must also call \\`useSignals()\\` from\n\\`@cascivo/react\\` as its first statement — Astro applies no signals transform.\n\n## Styling\n\n\\`@cascivo/astro\\` (in \\`astro.config.mjs\\`) injects the cascade layer order, then the\n\\`${opts.theme}\\` theme, ahead of any other CSS on every page, and inlines a no-flash theme\nscript. Its \\`layers\\` option is the same statement as \\`src/styles/layers.css\\`, which adds\nthis app's own \\`cascivo.example\\` slot; keep the two identical. Layers take their position\nfrom first appearance, so a statement loaded after the theme cannot reorder anything.\n\nAdd more components with \\`npx cascivo add <component>\\`.\n${staticShareSection(opts)}`\n}\n\n/* ------------------------------------------------------------------------- *\n * Cloudflare scaffold (`--framework cloudflare`)\n *\n * A client-rendered app and its API, deployed as ONE Worker with static assets. No SSR:\n * the browser gets the SPA, `/api/*` reaches the Worker, and `@cloudflare/vite-plugin`\n * runs that Worker in workerd during `vite dev`, so dev and production execute the same\n * runtime. The shape comes from `apps/examples/chat` (its FINDINGS.md), not from a design\n * exercise: the source is typed against React and the runtime is picked in the bundler,\n * shared wire types live in one file both sides import, and streaming goes through\n * `@cascivo/data`.\n * ------------------------------------------------------------------------- */\n\n/** Workers runtime date the scaffold targets. Bump deliberately, never to \"today\". */\nconst COMPATIBILITY_DATE = '2026-09-01'\n\nfunction cfPackageJson(opts: ScaffoldOptions): string {\n const pm = opts.pm ?? 'npm'\n const agent = hasExample(opts, 'agent')\n const workerTypes = needsWorkerTypes(opts)\n const preact = runtimeOf(opts) === 'preact'\n const pkg = {\n name: packageName(opts.name),\n private: true,\n version: '0.0.0',\n type: 'module',\n scripts: {\n dev: 'vite',\n build: workerTypes ? 'tsc && tsc -p tsconfig.worker.json && vite build' : 'tsc && vite build',\n preview: 'vite preview',\n deploy: `${runScriptCommand(pm, 'build')} && wrangler deploy`,\n // No account: a temporary one, live for 60 minutes unless claimed (see README).\n 'deploy:preview': `${runScriptCommand(pm, 'build')} && wrangler deploy --temporary`,\n typecheck: workerTypes\n ? 'tsc --noEmit && tsc --noEmit -p tsconfig.worker.json'\n : 'tsc --noEmit',\n lint: 'eslint .',\n format: 'prettier --write .',\n 'format:check': 'prettier --check .',\n },\n // Same prebuilt-path rules as the Vite scaffold (see `packageJson`): no @cascivo/core,\n // no @cascivo/tokens. `@cascivo/app` is the router + typed API this app imports;\n // `@cascivo/data` arrives with it.\n dependencies: {\n '@cascivo/app': V['@cascivo/app']!,\n ...blockDependencies(opts),\n '@cascivo/react': V['@cascivo/react']!,\n '@cascivo/themes': V['@cascivo/themes']!,\n '@preact/signals-react': SIGNALS_PEER,\n ...(preact ? { preact: '^10.29.0' } : { react: '^19.0.0', 'react-dom': '^19.0.0' }),\n // The /usage and /ops pages' charts.\n ...(hasExample(opts, 'usage') || hasExample(opts, 'live')\n ? { '@cascivo/charts': V['@cascivo/charts']! }\n : {}),\n // The /report page's PDF/PNG export drives Browser Run through Cloudflare's puppeteer.\n ...(hasExample(opts, 'export') ? { '@cloudflare/puppeteer': '^1.4.0' } : {}),\n // The /notes page keeps its room in IndexedDB.\n ...(hasExample(opts, 'notes') ? { '@cascivo/storage': V['@cascivo/storage']! } : {}),\n // The /assistant page: Cloudflare's Agents SDK on the AI SDK, and @cascivo/render to\n // draw (and validate) the views the model builds.\n ...(agent\n ? {\n '@ai-sdk/react': '^4.0.0',\n '@cascivo/render': V['@cascivo/render']!,\n '@cloudflare/ai-chat': '^0.12.1',\n agents: '^0.26.0',\n ai: '^7.0.0',\n 'workers-ai-provider': '^4.0.0',\n zod: '^4.0.0',\n }\n : {}),\n // The /voice page: the Agents SDK's voice pipeline and its browser client.\n ...(hasExample(opts, 'voice') && !agent ? { agents: '^0.26.0' } : {}),\n // The /publish page and published pages render views with @cascivo/render.\n ...(hasExample(opts, 'publish') && !agent\n ? { '@cascivo/render': V['@cascivo/render']! }\n : {}),\n // The Worker renders receipts and newsletters with @cascivo/email (react-dom/server\n // underneath).\n ...(hasExample(opts, 'checkout') || hasExample(opts, 'newsletter')\n ? { '@cascivo/email': V['@cascivo/email']! }\n : {}),\n // The Worker server-renders published pages and emails; under Preact, react-dom/server\n // is preact/compat/server, which needs this.\n ...((hasExample(opts, 'publish') ||\n hasExample(opts, 'checkout') ||\n hasExample(opts, 'newsletter')) &&\n preact\n ? { 'preact-render-to-string': '^6.5.0' }\n : {}),\n },\n devDependencies: {\n '@cascivo/eslint-config': V['@cascivo/eslint-config']!,\n '@cloudflare/vite-plugin': '^1.62.0',\n // Types for worker/ (tsconfig.worker.json): the Agents SDK and Workflows extend runtime\n // classes only these declare. Kept out of the app's DOM-typed tsconfig.\n ...(workerTypes ? { '@cloudflare/workers-types': '^5.0.0' } : {}),\n '@eslint/js': '^9.0.0',\n // The source is typed against React even when Preact runs it (see vite.config.ts), so\n // React's types are always installed. Under Preact, `react`/`react-dom` are dev-only:\n // they satisfy cascivo's peer ranges and are aliased away at build time.\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n ...(preact\n ? {\n '@babel/core': '^7.0.0',\n '@preact/preset-vite': '^2.10.0',\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n }\n : { '@vitejs/plugin-react': '^6.0.0' }),\n eslint: '^9.0.0',\n 'eslint-plugin-react-hooks': '^7.0.0',\n prettier: '^3.0.0',\n typescript: '^5.7.0',\n 'typescript-eslint': '^8.0.0',\n vite: '^8.0.0',\n wrangler: '^4.143.0',\n },\n }\n const bindings = cfBindingDescriptions(opts)\n return (\n JSON.stringify(\n Object.keys(bindings).length > 0 ? { ...pkg, cloudflare: { bindings } } : pkg,\n null,\n 2,\n ) + '\\n'\n )\n}\n\nfunction cfTsconfig(opts: ScaffoldOptions): string {\n const cfg = JSON.parse(tsconfig()) as { include: string[] }\n // `worker/` is type-checked with the app: it imports `src/api.ts`, and a contract change\n // should fail `tsc` on whichever side was not updated. When the Worker needs Cloudflare's\n // runtime types (see needsWorkerTypes), which clash with the DOM's, it gets its own config\n // (tsconfig.worker.json) and both run in `typecheck`.\n cfg.include = needsWorkerTypes(opts) ? ['src'] : ['src', 'worker']\n return formatJson(cfg)\n}\n\nfunction cfWorkerTsconfig(): string {\n return formatJson({\n extends: './tsconfig.json',\n compilerOptions: {\n lib: ['ES2022'],\n types: ['@cloudflare/workers-types', 'vite/client'],\n },\n include: ['worker'],\n })\n}\n\nfunction cfViteConfig(runtime: Runtime, opts: ScaffoldOptions): string {\n const agent = hasExample(opts, 'agent')\n const ai = usesWorkersAi(opts)\n const plugin =\n runtime === 'preact'\n ? `import preact from '@preact/preset-vite'`\n : `import react from '@vitejs/plugin-react'`\n const call = runtime === 'preact' ? 'preact()' : 'react()'\n const note =\n runtime === 'preact'\n ? `// The source is written against React's types; @preact/preset-vite aliases react and\n// react-dom to preact/compat, so the bundle runs on Preact (about a third of React's JS in\n// this starter: ~27 KB gzip against ~85 KB). To run on React instead, swap this plugin\n// for @vitejs/plugin-react — no source changes.`\n : agent\n ? `// Runs on React: the /assistant page uses the Agents SDK's hooks, which call React 19's\n// use() — preact/compat does not implement it, so this app cannot switch to Preact.`\n : `// Runs on React. To ship Preact instead (about a third of the JS in this starter), swap\n// this plugin for @preact/preset-vite — it aliases react/react-dom to preact/compat; no\n// source changes.`\n return `${plugin}\nimport { cascivoRoutes } from '@cascivo/app/vite'\nimport { cloudflare } from '@cloudflare/vite-plugin'\nimport { defineConfig } from 'vite'\n\n${note}\n//\n// cascivoRoutes() writes src/routes.gen.ts from src/routes/ — one file per page.\n// cloudflare() runs worker/index.ts in workerd during \\`vite dev\\` and builds it with the\n// client, so dev and production execute the same runtime. Request routing is in wrangler.jsonc.${\n ai\n ? `\n//\n// Workers AI has no local mode: with remote bindings on, \\`vite dev\\` needs a Cloudflare login.\n// So they are off, ${\n hasExample(opts, 'search')\n ? `and:${[\n agent ? 'the assistant answers from worker/scripted-model.ts' : '',\n hasExample(opts, 'voice')\n ? 'the voice page uses the stand-ins in worker/scripted-voice.ts'\n : '',\n 'search runs by keyword, on SQLite full-text search (worker/search.ts)',\n ]\n .filter(Boolean)\n .map((clause) => `\\n// - ${clause}`)\n .join('')}`\n : agent && hasExample(opts, 'voice')\n ? `the assistant answers from worker/scripted-model.ts, and the voice\n// page uses the stand-ins in worker/scripted-voice.ts`\n : agent\n ? 'and the assistant answers from worker/scripted-model.ts'\n : 'and the voice page uses the stand-ins in worker/scripted-voice.ts'\n }. Run\n// \\`VITE_REAL_AI=1 vite dev\\` (after \\`wrangler login\\`) to use Workers AI.`\n : ''\n }\nexport default defineConfig({\n${\n ai\n ? ` plugins: [\n ${call},\n cascivoRoutes(),\n cloudflare({ remoteBindings: process.env['VITE_REAL_AI'] === '1' }),\n ],`\n : ` plugins: [${call}, cascivoRoutes(), cloudflare()],`\n}${\n hasExample(opts, 'publish')\n ? `\n // A published page's HTML links the stylesheets its route needs, found in this manifest\n // (worker/page-html.ts), so the page is styled for readers without JavaScript too.\n build: { manifest: 'asset-manifest.json' },`\n : ''\n }\n})\n`\n}\n\n/** A JSONC array property laid out as Prettier does: one line when it fits in 100 columns. */\nfunction jsoncArray(indent: string, key: string, items: string[]): string {\n const line = `${indent}\"${key}\": [${items.join(', ')}],`\n if (line.length <= 100) return line\n return `${indent}\"${key}\": [\\n${items.map((i) => `${indent} ${i},`).join('\\n')}\\n${indent}],`\n}\n\nfunction wranglerJsonc(opts: ScaffoldOptions): string {\n const publish = hasExample(opts, 'publish')\n const rooms = usesRooms(opts)\n const agent = hasExample(opts, 'agent')\n const ai = usesAgents(opts)\n // One Durable Object class per example; a fresh app declares them all in one migration.\n const objects = [\n ...(rooms ? [{ name: 'ROOMS', className: 'SyncRoom' }] : []),\n ...(agent ? [{ name: 'Assistant', className: 'Assistant' }] : []),\n ...(hasExample(opts, 'live') ? [{ name: 'LIVE', className: 'LiveRoom' }] : []),\n ...(hasExample(opts, 'voice') ? [{ name: 'Voice', className: 'Voice' }] : []),\n ]\n const comments = [\n ...(rooms ? ['// ROOMS: one SyncRoom per room (@cascivo/app/sync-server).'] : []),\n ...(agent\n ? ['// Assistant: one AIChatAgent per conversation; it stores the messages in SQLite.']\n : []),\n ...(hasExample(opts, 'live')\n ? [\"// LIVE: the /ops dashboard's per-second totals (@cascivo/app/live-server).\"]\n : []),\n ...(hasExample(opts, 'voice')\n ? ['// Voice: one voice agent per conversation (agents/voice); it stores the transcript.']\n : []),\n ]\n return `// Cloudflare deploy config. \\`${runExplicitCommand(opts.pm ?? 'npm', 'deploy')}\\` builds and ships the SPA and\n// the Worker together. https://developers.cloudflare.com/workers/wrangler/configuration/\n{\n \"name\": \"${packageName(opts.name)}\",\n \"main\": \"./worker/index.ts\",\n \"compatibility_date\": \"${COMPATIBILITY_DATE}\",\n \"assets\": {\n // Client-side app: an unknown path serves index.html, and the client renders it.\n \"not_found_handling\": \"single-page-application\",\n // ${\n publish\n ? 'Only the API and published pages reach the Worker; static assets are served\\n // without invoking it.'\n : 'Only the API reaches the Worker; static assets are served without invoking it.'\n }\n \"run_worker_first\": [${['\"/api/*\"', ...(ai ? ['\"/agents/*\"'] : []), ...(publish ? ['\"/p/*\"'] : [])].join(', ')}],${\n publish\n ? `\n // The Worker reads index.html through this to put a published page into it.\n \"binding\": \"ASSETS\",`\n : ''\n }\n },\n \"observability\": { \"enabled\": true },${\n objects.length > 0\n ? `\n ${comments.join('\\n ')}\n \"durable_objects\": {\n${jsoncArray(\n ' ',\n 'bindings',\n objects.map((o) => `{ \"name\": \"${o.name}\", \"class_name\": \"${o.className}\" }`),\n)}\n },\n${jsoncArray(' ', 'migrations', [`{ \"tag\": \"v1\", \"new_sqlite_classes\": [${objects.map((o) => `\"${o.className}\"`).join(', ')}] }`])}`\n : ''\n }${\n hasExample(opts, 'files') || hasExample(opts, 'social')\n ? `\n // ${[\n hasExample(opts, 'files')\n ? 'Uploaded files, and Cloudflare Images for their resized previews'\n : '',\n hasExample(opts, 'social') ? 'Images attached to social posts (worker/social.ts)' : '',\n ]\n .filter(Boolean)\n .join('; ')}.\n${jsoncArray(' ', 'r2_buckets', [\n ...(hasExample(opts, 'files')\n ? [`{ \"binding\": \"FILES\", \"bucket_name\": \"${packageName(opts.name)}-files\" }`]\n : []),\n ...(hasExample(opts, 'social')\n ? [`{ \"binding\": \"SOCIAL_MEDIA\", \"bucket_name\": \"${packageName(opts.name)}-social-media\" }`]\n : []),\n])}${hasExample(opts, 'files') ? '\\n \"images\": { \"binding\": \"IMAGES\" },' : ''}`\n : ''\n }${\n usesLimiter(opts)\n ? `\n // ${[\n hasExample(opts, 'files') ? 'Uploads' : '',\n hasExample(opts, 'export') ? 'exports' : '',\n hasExample(opts, 'publish') ? 'published pages' : '',\n hasExample(opts, 'digest') ? 'digests sent now' : '',\n hasExample(opts, 'search') ? 'search indexing' : '',\n hasExample(opts, 'checkout') ? 'checkouts started' : '',\n hasExample(opts, 'newsletter') ? 'newsletter sign-ups and composer requests' : '',\n hasExample(opts, 'social') ? 'connecting accounts, posts and image uploads' : '',\n emailSignIn(opts) ? 'sign-in emails' : '',\n ]\n .filter(Boolean)\n .join(', ')\n .replace(/^./, (c) => c.toUpperCase())} per caller: 20 a minute.\n // namespace_id is any number unique within your account:\n // https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/\n${jsoncArray(' ', 'ratelimits', ['{ \"name\": \"LIMITER\", \"namespace_id\": \"1001\", \"simple\": { \"limit\": 20, \"period\": 60 } }'])}`\n : ''\n }${wranglerVars(opts)}${\n hasExample(opts, 'digest') || hasExample(opts, 'social')\n ? `\n // ${[\n hasExample(opts, 'digest') ? 'The weekly digest: Mondays at 08:00 UTC (worker/digest.ts)' : '',\n hasExample(opts, 'social')\n ? 'Threads tokens renewed and reconnect reminders sent, daily at 04:17 UTC (worker/social.ts)'\n : '',\n ]\n .filter(Boolean)\n .join('; ')}.\n \"triggers\": { \"crons\": [${[\n hasExample(opts, 'digest') ? '\"0 8 * * 1\"' : '',\n hasExample(opts, 'social') ? `\"${SOCIAL_CRON}\"` : '',\n ]\n .filter(Boolean)\n .join(', ')}] },`\n : ''\n }${\n usesD1(opts)\n ? `\n // Tables for ${[\n hasExample(opts, 'crud') ? 'customers' : '',\n hasExample(opts, 'publish') ? 'published pages' : '',\n hasExample(opts, 'webhooks') ? 'webhook deliveries' : '',\n hasExample(opts, 'digest') ? 'digest runs' : '',\n hasExample(opts, 'search') ? 'help articles' : '',\n hasExample(opts, 'checkout') ? 'orders' : '',\n hasExample(opts, 'newsletter') ? 'newsletter subscribers and issues' : '',\n hasAccounts(opts) ? 'accounts' : '',\n ]\n .filter(Boolean)\n .join(', ')}.\n // No database_id: wrangler creates the database on first deploy, and the Worker applies its\n // own schema on its first query (\\`migrate\\`).\n${jsoncArray(' ', 'd1_databases', [`{ \"binding\": \"DB\", \"database_name\": \"${packageName(opts.name)}-db\" }`])}`\n : ''\n }${\n hasExample(opts, 'usage')\n ? `\n // Every API request is recorded here (worker/index.ts); /usage reads it back.\n \"analytics_engine_datasets\": [{ \"binding\": \"USAGE\", \"dataset\": \"${usageDataset(opts)}\" }],`\n : ''\n }${wranglerQueues(opts)}${\n hasExample(opts, 'import') || hasExample(opts, 'social')\n ? `\n // ${[\n hasExample(opts, 'import')\n ? 'The CSV import runs as a Workflow (worker/import-job.ts); its progress is a room.'\n : '',\n hasExample(opts, 'social')\n ? 'Each scheduled post is a Workflow that waits until it is due (worker/social-post.ts).'\n : '',\n ]\n .filter(Boolean)\n .join('\\n // ')}\n${jsoncArray(' ', 'workflows', [\n ...(hasExample(opts, 'import')\n ? ['{ \"name\": \"import-job\", \"binding\": \"IMPORT_JOB\", \"class_name\": \"ImportJob\" }']\n : []),\n ...(hasExample(opts, 'social')\n ? [\n `{ \"name\": \"${packageName(opts.name)}-social-post\", \"binding\": \"SOCIAL_POST\", \"class_name\": \"SocialPost\" }`,\n ]\n : []),\n])}`\n : ''\n }${\n usesWorkersAi(opts)\n ? `\n // Workers AI, which the ${[agent ? 'assistant' : '', hasExample(opts, 'voice') ? 'voice agent' : '', hasExample(opts, 'search') ? 'search page' : ''].filter(Boolean).join(' and ')} call${[agent, hasExample(opts, 'voice'), hasExample(opts, 'search')].filter(Boolean).length > 1 ? '' : 's'}.\n \"ai\": { \"binding\": \"AI\" },`\n : ''\n }${\n hasExample(opts, 'search')\n ? `\n // The help articles' embeddings (worker/search.ts). Create it once before deploying (README).\n${jsoncArray(' ', 'vectorize', [`{ \"binding\": \"ARTICLES_INDEX\", \"index_name\": \"${packageName(opts.name)}-articles\" }`])}`\n : ''\n }${\n hasExample(opts, 'export')\n ? `\n // Browser Run: renders pages to PDF/PNG for /api/export.\n \"browser\": { \"binding\": \"BROWSER\" },`\n : ''\n }${\n ai || hasExample(opts, 'export')\n ? `\n // ${[ai ? 'The Agents SDK' : '', hasExample(opts, 'export') ? \"Cloudflare's puppeteer\" : ''].filter(Boolean).join(' and ')} use${ai && hasExample(opts, 'export') ? '' : 's'} Node.js APIs.\n \"compatibility_flags\": [\"nodejs_compat\"],`\n : ''\n }\n // Add bindings here (KV, D1, R2, Durable Objects, Workers AI) and read them from the\n // \\`env\\` argument of the Worker's fetch handler.\n}\n`\n}\n\n/**\n * wrangler.jsonc's plain-text settings, in one `vars` object (a second one would replace the\n * first), and the Email Service binding when anything sends mail.\n */\nfunction wranglerVars(opts: ScaffoldOptions): string {\n const digest = hasExample(opts, 'digest')\n const social = hasExample(opts, 'social')\n const checkout = hasExample(opts, 'checkout')\n const newsletter = hasExample(opts, 'newsletter')\n const emailAuth = emailSignIn(opts)\n const comments = [\n ...(opts.auth === 'access'\n ? ['Cloudflare Access (README). Until both are set, the Worker refuses every request.']\n : []),\n ...(emailAuth\n ? [\n 'Sign-in links go out through Email Service (README). AUTH_FROM must be an address on a',\n 'domain you have onboarded; until it is set, sign-in fails with a clear error.',\n ]\n : []),\n ...(digest\n ? [\n \"The weekly digest (README): who gets it, who sends it, and the deployed app's URL,\",\n 'which the browser opens. Until they are set, each run is recorded as skipped.',\n ]\n : []),\n ...(social\n ? [\n 'Reminders to connect LinkedIn again go out through Email Service from REMINDER_FROM, an',\n `address on a domain you have onboarded, with links to APP_URL (README). Until both are`,\n 'set, no reminder is sent.',\n ]\n : []),\n ...(checkout\n ? [\n 'Receipts for paid orders go out through Email Service from RECEIPT_FROM, an address',\n 'on a domain you have onboarded (README). Until it is set, no receipt is sent.',\n ]\n : []),\n ...(newsletter\n ? [\n 'The newsletter sends through Amazon SES (README): the region your sending identity is',\n 'verified in, its From address, and the SNS topic SES reports bounces and complaints to.',\n ]\n : []),\n ]\n const names = [\n ...(opts.auth === 'access' ? ['ACCESS_TEAM_DOMAIN', 'ACCESS_AUD'] : []),\n ...(emailAuth ? ['AUTH_FROM'] : []),\n ...(digest ? ['DIGEST_TO', 'DIGEST_FROM', 'APP_URL'] : []),\n ...(social ? ['REMINDER_FROM', ...(digest ? [] : ['APP_URL'])] : []),\n ...(checkout ? ['RECEIPT_FROM'] : []),\n ...(newsletter ? ['AWS_REGION', 'NEWSLETTER_FROM', 'SNS_TOPIC_ARN'] : []),\n ]\n if (names.length === 0) return ''\n const entries = names.map((name) => `\"${name}\": \"\"`)\n const line = ` \"vars\": { ${entries.join(', ')} },`\n const vars =\n line.length <= 100\n ? line\n : ` \"vars\": {\\n${entries.map((entry) => ` ${entry},`).join('\\n')}\\n },`\n return `\n${comments.map((comment) => ` // ${comment}`).join('\\n')}${emailAuth || digest || checkout || social ? '\\n \"send_email\": [{ \"name\": \"EMAIL\" }],' : ''}\n${vars}`\n}\n\n/** One `queues` object for every example that has a queue (a second one would replace the first). */\nfunction wranglerQueues(opts: ScaffoldOptions): string {\n const queues = [\n ...(hasExample(opts, 'live')\n ? [\n {\n comment: [\n \"Events for /ops: POST /api/events sends them, and the Worker's queue handler takes them in\",\n 'batches of up to 100, or whatever arrived within a second.',\n ],\n binding: 'EVENTS',\n queue: `${packageName(opts.name)}-events`,\n consumer: ['\"max_batch_size\": 100', '\"max_batch_timeout\": 1'],\n },\n ]\n : []),\n ...(hasExample(opts, 'newsletter')\n ? [\n {\n comment: [\n 'Newsletter sends (worker/newsletter.ts): one message of 25 readers at a time, so SES',\n 'is called at a steady pace. A throttled message is retried after 30 seconds.',\n ],\n binding: 'NEWSLETTER',\n queue: newsletterQueue(opts),\n consumer: [\n '\"max_batch_size\": 1',\n '\"max_concurrency\": 1',\n '\"max_retries\": 10',\n '\"retry_delay\": 30',\n ],\n },\n ]\n : []),\n ]\n if (queues.length === 0) return ''\n return `\n${queues.flatMap((q) => q.comment.map((line) => ` // ${line}`)).join('\\n')}\n \"queues\": {\n${jsoncArray(\n ' ',\n 'producers',\n queues.map((q) => `{ \"binding\": \"${q.binding}\", \"queue\": \"${q.queue}\" }`),\n)}\n \"consumers\": [\n${queues\n .map(\n (q) => ` {\n \"queue\": \"${q.queue}\",\n${q.consumer.map((line) => ` ${line},`).join('\\n')}\n },`,\n )\n .join('\\n')}\n ],\n },`\n}\n\n/** A subscription plan needs an account to belong to: checkout with accounts bills one. */\nfunction usesBilling(opts: ScaffoldOptions): boolean {\n return hasExample(opts, 'checkout') && hasAccounts(opts)\n}\n\n/** Accounts of any kind: users, sessions, and API writes that need a signed-in user. */\nfunction hasAccounts(opts: ScaffoldOptions): boolean {\n return emailSignIn(opts) || oauthSignIn(opts)\n}\n\n/** Sign-in by an emailed one-time link (`handleAuth`). */\nfunction emailSignIn(opts: ScaffoldOptions): boolean {\n return opts.auth === 'email' || opts.auth === 'email,oauth'\n}\n\n/**\n * `--auth`: `access`, `email`, `oauth`, or `email,oauth` (either order); `null` when absent,\n * `'invalid'` for anything else, including `access` combined with a sign-in method.\n */\nexport function parseAuth(raw: string | undefined): Auth | null | 'invalid' {\n const parts = [\n ...new Set(\n (raw ?? '')\n .toLowerCase()\n .split(',')\n .map((p) => p.trim()),\n ),\n ].filter(Boolean)\n if (parts.length === 0) return null\n const key = parts.sort().join(',')\n return key === 'access' || key === 'email' || key === 'oauth' || key === 'email,oauth'\n ? key\n : 'invalid'\n}\n\n/** Sign-in with GitHub, Google and LinkedIn (`handleOAuth`). */\nfunction oauthSignIn(opts: ScaffoldOptions): boolean {\n return opts.auth === 'oauth' || opts.auth === 'email,oauth'\n}\n\n/** The newsletter's queue, named after the app like every other resource. */\nfunction newsletterQueue(opts: ScaffoldOptions): string {\n return `${packageName(opts.name)}-newsletter`\n}\n\nfunction hasExample(opts: ScaffoldOptions, example: Example): boolean {\n return opts.examples?.includes(example) ?? false\n}\n\n/**\n * Examples that live in `SyncRoom`s: the board and the notes (at /api/rooms/:name), and the\n * import's job progress (a read-only room at /api/jobs/:id).\n */\n/** The Analytics Engine dataset for `--example usage`: one per app, named after it. */\nfunction usageDataset(opts: ScaffoldOptions): string {\n return `${packageName(opts.name)\n .replace(/[^a-z0-9_]/g, '_')\n .replace(/^[^a-z_]/, '_$&')}_usage`\n}\n\n/**\n * Examples with requests that cost money (storage, a browser) or put content on the app's\n * origin (a published page): rate-limited per caller.\n */\nfunction usesLimiter(opts: ScaffoldOptions): boolean {\n return (\n hasExample(opts, 'files') ||\n hasExample(opts, 'export') ||\n hasExample(opts, 'publish') ||\n hasExample(opts, 'digest') ||\n hasExample(opts, 'search') ||\n hasExample(opts, 'checkout') ||\n hasExample(opts, 'newsletter') ||\n hasExample(opts, 'social') ||\n emailSignIn(opts)\n )\n}\n\n/** Examples that keep tables in D1, bound as DB. */\nfunction usesD1(opts: ScaffoldOptions): boolean {\n return (\n hasExample(opts, 'crud') ||\n hasExample(opts, 'publish') ||\n hasExample(opts, 'webhooks') ||\n hasExample(opts, 'digest') ||\n hasExample(opts, 'search') ||\n hasExample(opts, 'checkout') ||\n hasExample(opts, 'newsletter') ||\n hasAccounts(opts)\n )\n}\n\n/** Examples that call Workers AI: the Agents SDK ones, and search's embeddings. */\nfunction usesWorkersAi(opts: ScaffoldOptions): boolean {\n return usesAgents(opts) || hasExample(opts, 'search')\n}\n\n/** Examples on Cloudflare's Agents SDK: routed under /agents/*, calling Workers AI. */\nfunction usesAgents(opts: ScaffoldOptions): boolean {\n return hasExample(opts, 'agent') || hasExample(opts, 'voice')\n}\n\nfunction usesRooms(opts: ScaffoldOptions): boolean {\n return (\n hasExample(opts, 'board') ||\n hasExample(opts, 'notes') ||\n hasExample(opts, 'import') ||\n hasExample(opts, 'webhooks') ||\n hasExample(opts, 'checkout') ||\n hasExample(opts, 'newsletter')\n )\n}\n\n/**\n * Worker code that extends a runtime class (the Agents SDK's Durable Object, a Workflow)\n * needs Cloudflare's runtime types, which clash with the DOM's: those apps type-check\n * worker/ on its own (tsconfig.worker.json).\n */\nfunction needsWorkerTypes(opts: ScaffoldOptions): boolean {\n return usesAgents(opts) || hasExample(opts, 'import') || hasExample(opts, 'social')\n}\n\n/**\n * The client runtime. Preact by default; React with the `agent` example, because the Agents\n * SDK's hooks (`useAgent`, `useAgentChat`) call React 19's `use()`, which preact/compat\n * does not implement — the build fails on the missing export.\n */\nfunction runtimeOf(opts: ScaffoldOptions): Runtime {\n return opts.runtime ?? (hasExample(opts, 'agent') ? 'react' : 'preact')\n}\n\nfunction cfApiTs(opts: ScaffoldOptions): string {\n const imports = hasExample(opts, 'import')\n const files = hasExample(opts, 'files')\n const usage = hasExample(opts, 'usage')\n const crud = hasExample(opts, 'crud')\n const live = hasExample(opts, 'live')\n const publish = hasExample(opts, 'publish')\n const webhooks = hasExample(opts, 'webhooks')\n const digest = hasExample(opts, 'digest')\n const search = hasExample(opts, 'search')\n const checkout = hasExample(opts, 'checkout')\n const newsletter = hasExample(opts, 'newsletter')\n const billing = usesBilling(opts)\n const social = hasExample(opts, 'social')\n return `import { defineApi, ${imports || files || usage || crud || live || publish || webhooks || digest || search || checkout || newsletter || social ? 'endpoint, ' : ''}stream } from '@cascivo/app/api'\n${crud ? `import { parseTablePage, parseTableQuery } from '@cascivo/app/db'\\n` : ''}${files ? `import { parseStoredFile } from '@cascivo/app/uploads'\\n` : ''}${imports ? `import { parseImportRequest, parseStarted } from './import-job'\\n` : ''}${usage ? `import { parseUsageReport } from './usage'\\n` : ''}${crud ? `import { parseCustomer, parseCustomerInput, parseDeleted } from './customers'\\n` : ''}${live ? `import { ops, parseAccepted } from './ops'\\n` : ''}${publish ? `import { parsePage, parsePageInput, parsePageSummary } from './pages'\\n` : ''}${webhooks ? `import { parseDeliveries, parseTestResult } from './webhooks'\\n` : ''}${digest ? `import { parseDigestRun, parseDigestRuns } from './digest'\\n` : ''}${search ? `import { parseIndexed, parseSearchQuery, parseSearchResult } from './search'\\n` : ''}${billing ? `import { parseBilling, parseRedirect, parseSyncInput } from './billing'\\n` : ''}${checkout ? `import { parseCheckoutStarted, parseOrder } from './checkout'\\n` : ''}${\n newsletter\n ? `import {\n parseConfirmed,\n parseEmailInput,\n parseIssue,\n parseIssueInput,\n parseKeyInput,\n parseOverview,\n parsePreview,\n parseSubscribed,\n parseTokenInput,\n} from './newsletter'\\n`\n : ''\n }${social ? `import { parsePostInput, parseScheduledPost, parseSocial } from './social'\\n` : ''}\n/**\n * The contract between the browser and the Worker. Both import this file: the Worker serves\n * it with \\`createHandler\\`, the app calls it with \\`createClient\\`, and a change that breaks\n * either side is a type error. Add an endpoint here, then its handler in worker/index.ts.\n */\n\n/** How many ticks one stream sends before it ends. */\nexport const TICKS_PER_STREAM = 30\n\nexport interface Tick {\n n: number\n /** ISO timestamp, set by the Worker. */\n at: string\n}\n\n/**\n * Parses one streamed tick. It crosses the network, so it is checked rather than cast —\n * \\`JSON.parse\\` returns \\`any\\`, and \\`as Tick\\` would prove nothing.\n */\nexport function parseTick(raw: unknown): Tick {\n if (typeof raw === 'object' && raw !== null) {\n const { n, at } = raw as Record<string, unknown>\n if (typeof n === 'number' && typeof at === 'string') return { n, at }\n }\n throw new Error('Malformed tick')\n}\n\nexport const api = defineApi({\n ticks: stream({ method: 'GET', path: '/api/ticks', event: parseTick }),${\n imports\n ? `\n // Starts a CSV import; returns the job id to watch (src/import-page.ts).\n startImport: endpoint({\n method: 'POST',\n path: '/api/import',\n input: parseImportRequest,\n output: parseStarted,\n }),`\n : ''\n }${\n files\n ? `\n // The stored files (the uploads themselves are \\`handleUploads\\` in the Worker).\n listFiles: endpoint({\n method: 'GET',\n path: '/api/files',\n output: (raw) => {\n if (!Array.isArray(raw)) throw new Error('Expected a list of files')\n return raw.map(parseStoredFile)\n },\n }),`\n : ''\n }${\n usage\n ? `\n // The last 24 hours of API usage, read from Analytics Engine by the Worker.\n usage: endpoint({ method: 'GET', path: '/api/usage', output: parseUsageReport }),`\n : ''\n }${\n live\n ? `\n // Events for the /ops dashboard, at most 100 at a time, onto the EVENTS queue.\n sendEvents: endpoint({\n method: 'POST',\n path: '/api/events',\n input: ops.parseEvents,\n output: parseAccepted,\n }),`\n : ''\n }${\n publish\n ? `\n // Publishes a view as a page (checked against the manifests), and reads one back.\n publishPage: endpoint({\n method: 'POST',\n path: '/api/pages',\n input: parsePageInput,\n output: parsePageSummary,\n }),\n getPage: endpoint({ method: 'GET', path: '/api/pages/:slug', output: parsePage }),`\n : ''\n }${\n webhooks\n ? `\n // The last 50 webhook deliveries (they arrive at /api/webhooks/github, signed).\n listDeliveries: endpoint({ method: 'GET', path: '/api/webhooks', output: parseDeliveries }),\n // Signs a sample delivery with WEBHOOK_SECRET and runs it through the same path.\n sendTestDelivery: endpoint({\n method: 'POST',\n path: '/api/webhook-test',\n output: parseTestResult,\n }),`\n : ''\n }${\n digest\n ? `\n // The weekly digest's recent runs, and one run now (the Cron Trigger runs it on Mondays).\n digestRuns: endpoint({ method: 'GET', path: '/api/digest/runs', output: parseDigestRuns }),\n runDigest: endpoint({ method: 'POST', path: '/api/digest/run', output: parseDigestRun }),`\n : ''\n }${\n search\n ? `\n // Help articles by meaning (Vectorize), or by keyword in vite dev.\n search: endpoint({\n method: 'POST',\n path: '/api/search',\n input: parseSearchQuery,\n output: parseSearchResult,\n }),\n // Embeds every article into the Vectorize index.\n indexArticles: endpoint({ method: 'POST', path: '/api/search/index', output: parseIndexed }),`\n : ''\n }${\n checkout\n ? `\n // Opens a Stripe Checkout page for the product; the browser goes to its url.\n startCheckout: endpoint({ method: 'POST', path: '/api/checkout', output: parseCheckoutStarted }),\n // An order, checked with Stripe while it is pending (Stripe's webhook settles it too).\n getOrder: endpoint({ method: 'GET', path: '/api/orders/:id', output: parseOrder }),`\n : ''\n }${\n billing\n ? `\n // The signed-in user's subscription (worker/billing.ts), and the ways to change it.\n getBilling: endpoint({ method: 'GET', path: '/api/billing', output: parseBilling }),\n startSubscription: endpoint({\n method: 'POST',\n path: '/api/billing/subscribe',\n output: parseRedirect,\n }),\n syncBilling: endpoint({\n method: 'POST',\n path: '/api/billing/sync',\n input: parseSyncInput,\n output: parseBilling,\n }),\n openBillingPortal: endpoint({\n method: 'POST',\n path: '/api/billing/portal',\n output: parseRedirect,\n }),`\n : ''\n }${\n newsletter\n ? `\n // Signing up sends a confirmation link; only confirmed readers get issues.\n subscribe: endpoint({\n method: 'POST',\n path: '/api/newsletter/subscribe',\n input: parseEmailInput,\n output: parseSubscribed,\n }),\n confirmSubscription: endpoint({\n method: 'POST',\n path: '/api/newsletter/confirm',\n input: parseTokenInput,\n output: parseConfirmed,\n }),\n // The composer's calls, each carrying NEWSLETTER_KEY.\n newsletterOverview: endpoint({\n method: 'POST',\n path: '/api/newsletter/overview',\n input: parseKeyInput,\n output: parseOverview,\n }),\n previewIssue: endpoint({\n method: 'POST',\n path: '/api/newsletter/preview',\n input: parseIssueInput,\n output: parsePreview,\n }),\n sendIssue: endpoint({\n method: 'POST',\n path: '/api/newsletter/issues',\n input: parseIssueInput,\n output: parseIssue,\n }),`\n : ''\n }${\n crud\n ? `\n // One page of customers for DataTable's query (sort, search, filters, page).\n customers: endpoint({\n method: 'POST',\n path: '/api/customers/query',\n input: parseTableQuery,\n output: (raw) => parseTablePage(raw, parseCustomer),\n }),\n createCustomer: endpoint({\n method: 'POST',\n path: '/api/customers',\n input: parseCustomerInput,\n output: parseCustomer,\n }),\n updateCustomer: endpoint({\n method: 'PUT',\n path: '/api/customers/:id',\n input: parseCustomerInput,\n output: parseCustomer,\n }),\n deleteCustomer: endpoint({ method: 'DELETE', path: '/api/customers/:id', output: parseDeleted }),`\n : ''\n }${\n social\n ? `\n // The signed-in user's connected accounts and posts (worker/social.ts).\n getSocial: endpoint({ method: 'GET', path: '/api/social', output: parseSocial }),\n schedulePost: endpoint({\n method: 'POST',\n path: '/api/social/posts',\n input: parsePostInput,\n output: parseScheduledPost,\n }),\n cancelPost: endpoint({\n method: 'POST',\n path: '/api/social/posts/:id/cancel',\n output: parseScheduledPost,\n }),`\n : ''\n }\n})\n`\n}\n\nfunction cfWorkerTs(opts: ScaffoldOptions): string {\n const rooms = usesRooms(opts)\n const agent = hasExample(opts, 'agent')\n const imports = hasExample(opts, 'import')\n const files = hasExample(opts, 'files')\n const exports = hasExample(opts, 'export')\n const usage = hasExample(opts, 'usage')\n const crud = hasExample(opts, 'crud')\n const live = hasExample(opts, 'live')\n const voice = hasExample(opts, 'voice')\n const publish = hasExample(opts, 'publish')\n const webhooks = hasExample(opts, 'webhooks')\n const digest = hasExample(opts, 'digest')\n const search = hasExample(opts, 'search')\n const checkout = hasExample(opts, 'checkout')\n const newsletter = hasExample(opts, 'newsletter')\n const billing = usesBilling(opts)\n const d1 = usesD1(opts)\n const ai = usesAgents(opts)\n const limiter = usesLimiter(opts)\n const access = opts.auth === 'access'\n const emailAuth = emailSignIn(opts)\n const oauth = oauthSignIn(opts)\n const accounts = hasAccounts(opts)\n const social = hasExample(opts, 'social')\n const guards = [\n ...(access ? ['requireAccess'] : []),\n ...(limiter ? ['clientIp', 'rateLimit'] : []),\n ]\n const custom = rooms || ai || files || exports || access || live || limiter || publish || accounts\n const isAsync =\n ai ||\n files ||\n exports ||\n access ||\n limiter ||\n webhooks ||\n publish ||\n checkout ||\n newsletter ||\n accounts\n // Rooms the server writes: never opened through /api/rooms/:name, where clients may write.\n const serverRooms = [\n ...(imports ? ['job-'] : []),\n ...(webhooks ? ['webhooks$'] : []),\n ...(checkout ? ['order-'] : []),\n ...(newsletter ? ['issue-'] : []),\n ]\n // Writes that need no signed-in user even with accounts: webhooks carry a signature instead of a\n // session, and a newsletter's readers have no account.\n const signedPaths = [\n ...(webhooks ? ['/api/webhooks/'] : []),\n ...(checkout ? ['/api/stripe/'] : []),\n ...(newsletter ? ['/api/sns/'] : []),\n ]\n const readerPaths = newsletter\n ? ['/api/newsletter/subscribe', '/api/newsletter/confirm', '/api/newsletter/unsubscribe']\n : []\n const openPaths = [...signedPaths, ...readerPaths]\n return `${usage ? `import type { AnalyticsDataset } from '@cascivo/app/analytics'\\n` : ''}${d1 ? `import type { Database } from '@cascivo/app/db'\\n` : ''}${exports ? `import { handleExport } from '@cascivo/app/export'\\n` : ''}import { createHandler${publish ? ', HttpError' : ''} } from '@cascivo/app/api'\n${accounts ? `import { ${emailAuth ? 'handleAuth, ' : ''}requireUser } from '@cascivo/app/auth-server'\\n` : ''}${oauth ? `import { github, google, linkedin } from '@cascivo/app/oauth'\\nimport type { OAuthProvider } from '@cascivo/app/oauth'\\nimport { handleOAuth } from '@cascivo/app/oauth-server'\\n` : ''}${guards.length > 0 || webhooks || accounts ? `import { ${[...guards, 'guardResponse'].sort().join(', ')} } from '@cascivo/app/guard'\\n${limiter ? `import type { RateLimiter } from '@cascivo/app/guard'\\n` : ''}` : ''}${imports ? `import { jobReporter } from '@cascivo/app/jobs-server'\\n` : ''}${\n files\n ? `import { handleUploads, listUploads } from '@cascivo/app/uploads-server'\nimport type { ImageResizer, UploadBucket } from '@cascivo/app/uploads-server'\n`\n : ''\n }${\n live\n ? `import { recordLive } from '@cascivo/app/live-server'\nimport type { LiveBatch, LiveQueue } from '@cascivo/app/live-server'\n`\n : ''\n }${\n rooms || live\n ? `import { roomResponse } from '@cascivo/app/sync-server'\nimport type { RoomNamespace } from '@cascivo/app/sync-server'\n`\n : ''\n }${\n exports\n ? `import puppeteer from '@cloudflare/puppeteer'\nimport type { BrowserWorker } from '@cloudflare/puppeteer'\n`\n : ''\n }${ai ? `import { routeAgentRequest } from 'agents'\\n` : ''}import { api, TICKS_PER_STREAM } from '../src/api'\nimport type { Tick } from '../src/api'\n${imports ? `import { importJob } from '../src/import-job'\\n` : ''}${files ? `import { uploads } from '../src/upload-policy'\\n` : ''}${usage ? `import { usageMetrics } from '../src/usage'\\nimport { usageReport } from './usage'\\n` : ''}${live ? `import { OPS_ROOM, ops } from '../src/ops'\\n` : ''}${emailAuth ? `import { sendSignInLink } from './auth'\\nimport type { SignInSender } from './auth'\\n` : ''}${crud ? `import * as customerStore from './customers'\\n` : ''}${publish ? `import * as pageStore from './pages'\\nimport { renderPageHtml } from './page-html'\\nimport type { Assets } from './page-html'\\n${exports ? `import { pagePreview } from './page-preview'\\n` : ''}` : ''}${webhooks ? `import * as webhookStore from './webhooks'\\nimport { DELIVERIES_ROOM } from '../src/webhooks'\\n` : ''}${digest ? `import * as digestJob from './digest'\\nimport type { DigestSender } from './digest'\\n` : ''}${search ? `import * as articleSearch from './search'\\nimport type { ${ai ? '' : 'Embedder, '}VectorIndex } from './search'\\n` : ''}${billing ? `import * as billingStore from './billing'\\n` : ''}${social ? `import * as socialStore from './social'\\nimport type { ReminderSender, SocialMediaBucket, SocialPostParams } from './social'\\n` : ''}${checkout ? `import * as orderStore from './checkout'\\nimport type { ReceiptSender } from './checkout'\\nimport { ORDER_ID, orderRoom } from '../src/checkout'\\n` : ''}${newsletter ? `import * as newsletterStore from './newsletter'\\nimport type { NewsletterBatch, NewsletterQueue } from './newsletter'\\nimport { ISSUE_ID, issueRoom } from '../src/newsletter'\\n` : ''}${\n rooms\n ? `\n// The Durable Object class behind every room. wrangler.jsonc binds it as ROOMS, and it must be\n// exported from the Worker's main module.\nexport { SyncRoom } from '@cascivo/app/sync-server'\n`\n : ''\n }${\n agent\n ? `\n// The Durable Object behind /assistant: one per conversation (worker/assistant.ts).\nexport { Assistant } from './assistant'\n`\n : ''\n }${\n voice\n ? `\n// The Durable Object behind /voice: one per conversation (worker/voice.ts).\nexport { Voice } from './voice'\n`\n : ''\n }${\n live\n ? `\n// The Durable Object behind /ops: the last two minutes, per second (src/ops.ts).\nexport { LiveRoom } from '@cascivo/app/live-server'\n`\n : ''\n }${\n imports\n ? `\n// The Workflow behind /import (worker/import-job.ts), bound as IMPORT_JOB.\nexport { ImportJob } from './import-job'\n`\n : ''\n }${\n social\n ? `\n// The Workflow behind each scheduled post (worker/social-post.ts), bound as SOCIAL_POST.\nexport { SocialPost } from './social-post'\n`\n : ''\n }\n/**\n * Add bindings (KV, D1, R2, Durable Objects, Workers AI) in wrangler.jsonc and type them\n * here; every handler receives them as \\`env\\`.\n */\n${\n rooms ||\n ai ||\n files ||\n exports ||\n usage ||\n d1 ||\n access ||\n live ||\n accounts ||\n social ||\n webhooks ||\n digest ||\n search ||\n checkout ||\n newsletter\n ? `export interface Env {${ai ? '\\n /** Workers AI, bound in wrangler.jsonc. */\\n AI: Ai' : search ? '\\n /** Workers AI, bound in wrangler.jsonc. */\\n AI: Embedder' : ''}${search ? '\\n ARTICLES_INDEX: VectorIndex' : ''}${rooms ? '\\n ROOMS: RoomNamespace<unknown>' : ''}${imports ? '\\n IMPORT_JOB: Workflow<{ csv: string }>' : ''}${files ? '\\n FILES: UploadBucket\\n IMAGES: ImageResizer' : ''}${exports ? '\\n BROWSER: BrowserWorker' : ''}${usage ? '\\n USAGE: AnalyticsDataset\\n /** Secrets for reading Analytics Engine back (see README). */\\n CF_ACCOUNT_ID?: string\\n CF_API_TOKEN?: string' : ''}${d1 ? '\\n DB: Database' : ''}${publish ? '\\n ASSETS: Assets' : ''}${live ? '\\n LIVE: RoomNamespace<unknown>\\n EVENTS: LiveQueue' : ''}${limiter ? '\\n LIMITER: RateLimiter' : ''}${access ? '\\n /** Set in wrangler.jsonc (see README). */\\n ACCESS_TEAM_DOMAIN: string\\n ACCESS_AUD: string' : ''}${webhooks ? '\\n /** The webhook signing secret: `wrangler secret put WEBHOOK_SECRET` (.dev.vars locally). */\\n WEBHOOK_SECRET: string' : ''}${emailAuth || digest || checkout || social ? `\\n EMAIL: ${[emailAuth ? 'SignInSender' : '', digest ? 'DigestSender' : '', checkout ? 'ReceiptSender' : '', social ? 'ReminderSender' : ''].filter(Boolean).join(' & ')}` : ''}${emailAuth ? '\\n /** The From address of sign-in emails, set in wrangler.jsonc. */\\n AUTH_FROM: string' : ''}${oauth ? '\\n /** Sign-in with GitHub, Google and LinkedIn: `wrangler secret put` (.dev.vars locally). A provider is\\n * offered once both its id and secret are set; AUTH_SECRET seals the sign-in state. */\\n AUTH_SECRET?: string\\n GITHUB_CLIENT_ID?: string\\n GITHUB_CLIENT_SECRET?: string\\n GOOGLE_CLIENT_ID?: string\\n GOOGLE_CLIENT_SECRET?: string\\n LINKEDIN_CLIENT_ID?: string\\n LINKEDIN_CLIENT_SECRET?: string' : social ? \"\\n /** Seals connected accounts' tokens, and LinkedIn's app: `wrangler secret put` (.dev.vars\\n * locally). LinkedIn is offered once both its values are set. */\\n AUTH_SECRET?: string\\n LINKEDIN_CLIENT_ID?: string\\n LINKEDIN_CLIENT_SECRET?: string\" : ''}${social ? '\\n /** Bluesky: an ES256 private JWK (README); unset, the app is a public client. */\\n BLUESKY_PRIVATE_JWK?: string\\n /** A Buffer app client (README); Buffer is offered once its id is set. */\\n BUFFER_CLIENT_ID?: string\\n BUFFER_CLIENT_SECRET?: string\\n /** A Meta app with the Threads use case (README); Threads is offered once both are set. */\\n THREADS_APP_ID?: string\\n THREADS_APP_SECRET?: string\\n SOCIAL_POST: Workflow<SocialPostParams>\\n SOCIAL_MEDIA: SocialMediaBucket\\n /** Reconnect reminders (worker/social.ts), set in wrangler.jsonc. */\\n REMINDER_FROM: string' + (digest ? '' : '\\n APP_URL: string') : ''}${digest ? '\\n /** The weekly digest (worker/digest.ts), set in wrangler.jsonc. */\\n DIGEST_TO: string\\n DIGEST_FROM: string\\n APP_URL: string' : ''}${checkout ? '\\n /** The From address of receipts, set in wrangler.jsonc. */\\n RECEIPT_FROM: string\\n /** Stripe secrets: `wrangler secret put` (.dev.vars locally). Unset until you add them. */\\n STRIPE_SECRET_KEY?: string\\n STRIPE_WEBHOOK_SECRET?: string' : ''}${newsletter ? '\\n NEWSLETTER: NewsletterQueue\\n /** The newsletter (worker/newsletter.ts), set in wrangler.jsonc. */\\n AWS_REGION: string\\n NEWSLETTER_FROM: string\\n SNS_TOPIC_ARN: string\\n /** Secrets: `wrangler secret put` (.dev.vars locally). Unset until you add them. */\\n AWS_ACCESS_KEY_ID?: string\\n AWS_SECRET_ACCESS_KEY?: string\\n NEWSLETTER_KEY?: string' : ''}\n}`\n : `// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- bindings are added as members\nexport interface Env {}`\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n${\n oauth\n ? `\n/** The sign-in providers with both an id and a secret set; the others are not offered. */\nfunction oauthProviders(env: Env): OAuthProvider[] {\n const providers: OAuthProvider[] = []\n if (env.GITHUB_CLIENT_ID && env.GITHUB_CLIENT_SECRET) {\n providers.push(\n github({ clientId: env.GITHUB_CLIENT_ID, clientSecret: env.GITHUB_CLIENT_SECRET }),\n )\n }\n if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) {\n providers.push(\n google({ clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET }),\n )\n }\n if (env.LINKEDIN_CLIENT_ID && env.LINKEDIN_CLIENT_SECRET) {\n providers.push(\n linkedin({ clientId: env.LINKEDIN_CLIENT_ID, clientSecret: env.LINKEDIN_CLIENT_SECRET }),\n )\n }\n return providers\n}\n`\n : ''\n}${\n limiter\n ? `\n/**\n * Requests that each count against LIMITER:\n${[\n emailAuth ? 'a sign-in email' : '',\n digest ? 'a digest sent now (it starts a browser)' : '',\n search ? 'indexing the articles (it embeds every one)' : '',\n checkout ? 'a checkout started (it creates a Stripe session and an order)' : '',\n billing ? 'a subscription checkout or billing portal opened' : '',\n newsletter ? 'a newsletter sign-up (it sends an email), and each use of the newsletter key' : '',\n files ? 'a new upload (not each part of one)' : '',\n exports ? 'an export' : '',\n publish ? 'a published page' : '',\n social ? 'connecting an account (Mastodon registers the app with the server), or a post' : '',\n]\n .filter(Boolean)\n .map((item) => ` * - ${item}`)\n .join('\\n')}\n */\nfunction countsAgainstLimit(request: Request): boolean {\n const url = new URL(request.url)${\n search\n ? `\n if (url.pathname === '/api/search/index') return request.method === 'POST'`\n : ''\n }${\n digest\n ? `\n if (url.pathname === '/api/digest/run') return request.method === 'POST'`\n : ''\n }${\n checkout\n ? `\n if (url.pathname === '/api/checkout') return request.method === 'POST'`\n : ''\n }${\n billing\n ? `\n if (url.pathname === '/api/billing/subscribe' || url.pathname === '/api/billing/portal') {\n return request.method === 'POST'\n }`\n : ''\n }${\n newsletter\n ? `\n if (/^\\\\/api\\\\/newsletter\\\\/(subscribe|overview|preview|issues)$/.test(url.pathname)) {\n return request.method === 'POST'\n }`\n : ''\n }${\n emailAuth\n ? `\n if (url.pathname === '/api/auth/start') return request.method === 'POST'`\n : ''\n }${\n social\n ? `\n if (/^\\\\/api\\\\/connections\\\\/[a-z-]+$/.test(url.pathname)) return request.method === 'GET'\n if (url.pathname === '/api/social/posts') return request.method === 'POST'\n if (url.pathname.startsWith('/api/social/images')) return request.method !== 'GET'`\n : ''\n }${\n publish\n ? `\n if (url.pathname === '/api/pages') return request.method === 'POST'`\n : ''\n }${\n files\n ? `\n if (url.pathname === uploads.path) {\n const step = url.searchParams.get('multipart')\n return (request.method === 'PUT' && step === null) || step === 'start'\n }`\n : ''\n }\n return ${exports ? \"url.pathname === '/api/export'\" : 'false'}\n}\n`\n : ''\n }\n/**\n * One handler per endpoint in src/api.ts, typed from it. A stream handler is an async\n * generator: each \\`yield\\` is one server-sent event, and returning ends the stream. When the\n * client disconnects, \\`signal\\` aborts.\n */\nconst handleApi = createHandler<typeof api, Env>(api, {\n ticks: async function* ({ signal }) {\n for (let n = 1; n <= TICKS_PER_STREAM && !signal.aborted; n++) {\n const tick: Tick = { n, at: new Date().toISOString() }\n yield tick\n await sleep(1000)\n }\n },${\n imports\n ? `\n // The job's room exists (as \"queued\") before the Workflow starts, so the page has\n // something to show at once.\n startImport: async ({ body, env }) => {\n const id = crypto.randomUUID()\n await jobReporter(importJob, env.ROOMS, id).queued()\n await env.IMPORT_JOB.create({ id, params: { csv: body.csv } })\n return { id }\n },`\n : ''\n }${files ? `\\n listFiles: ({ env }) => listUploads(env.FILES),` : ''}${\n usage\n ? `\n usage: ({ env }) =>\n usageReport(\n env.CF_ACCOUNT_ID && env.CF_API_TOKEN\n ? { accountId: env.CF_ACCOUNT_ID, apiToken: env.CF_API_TOKEN }\n : null,\n ),`\n : ''\n }${\n crud\n ? `\n customers: ({ body, env }) => customerStore.listCustomers(env.DB, body),\n createCustomer: ({ body, env }) => customerStore.createCustomer(env.DB, body),\n updateCustomer: ({ params, body, env }) => customerStore.updateCustomer(env.DB, params.id, body),\n deleteCustomer: ({ params, env }) => customerStore.deleteCustomer(env.DB, params.id),`\n : ''\n }${\n publish\n ? `\n publishPage: ({ body, env }) => pageStore.publishPage(env.DB, body),\n getPage: ({ params, env }) => pageStore.getPage(env.DB, params.slug),`\n : ''\n }${\n webhooks\n ? `\n listDeliveries: ({ env }) => webhookStore.listDeliveries(env.DB),\n sendTestDelivery: ({ request, env }) => webhookStore.sendTestDelivery(request.url, env),`\n : ''\n }${\n search\n ? `\n search: ({ body, env }) => articleSearch.search(env, body.q),\n indexArticles: ({ env }) => articleSearch.indexArticles(env),`\n : ''\n }${\n checkout\n ? `\n startCheckout: ({ request, env }) => orderStore.startCheckout(env, new URL(request.url).origin),\n getOrder: ({ params, request, env }) =>\n orderStore.getOrder(env, params.id, new URL(request.url).origin),`\n : ''\n }${\n billing\n ? `\n getBilling: ({ request, env }) => billingStore.getBilling(env, request),\n startSubscription: ({ request, env }) =>\n billingStore.startSubscription(env, request, new URL(request.url).origin),\n syncBilling: ({ body, request, env }) => billingStore.syncBilling(env, request, body.sessionId),\n openBillingPortal: ({ request, env }) =>\n billingStore.openPortal(env, request, new URL(request.url).origin),`\n : ''\n }${\n newsletter\n ? `\n subscribe: ({ body, request, env }) =>\n newsletterStore.subscribe(env, body.email, new URL(request.url).origin),\n confirmSubscription: ({ body, env }) => newsletterStore.confirm(env, body.token),\n newsletterOverview: ({ body, env }) => newsletterStore.overview(env, body.key),\n previewIssue: ({ body, request, env }) =>\n newsletterStore.preview(env, body, new URL(request.url).origin),\n sendIssue: ({ body, request, env }) =>\n newsletterStore.sendIssue(env, body, new URL(request.url).origin),`\n : ''\n }${\n social\n ? `\n getSocial: ({ request, env }) => socialStore.getSocial(env, request),\n schedulePost: ({ body, request, env }) => socialStore.schedulePost(env, request, body),\n cancelPost: ({ params, request, env }) => socialStore.cancelPost(env, request, params.id),`\n : ''\n }${\n digest\n ? `\n digestRuns: ({ env }) => digestJob.listRuns(env.DB),\n runDigest: ({ request, env }) =>\n digestJob.runDigest(\n env,\n () => puppeteer.launch(env.BROWSER),\n 'manual',\n new URL(request.url).origin,\n ),`\n : ''\n }${\n live\n ? `\n // Each event is placed by the Worker's clock: a browser's is not trusted to say when.\n sendEvents: async ({ body, env }) => {\n const at = Date.now()\n if (body.length > 0) {\n await env.EVENTS.sendBatch(body.map((event) => ({ body: { at, values: event.values } })))\n }\n return { accepted: body.length }\n },`\n : ''\n }\n})\n${\n usage\n ? `\n/** Every API request, recorded in Analytics Engine; src/usage.ts names the columns. */\nasync function handleAndRecord(request: Request, env: Env): Promise<Response> {\n const started = Date.now()\n const response = await handleApi(request, env)\n usageMetrics.write(env.USAGE, {\n path: new URL(request.url).pathname,\n method: request.method,\n status: response.status,\n duration_ms: Date.now() - started,\n })\n return response\n}\n`\n : ''\n}\n// wrangler.jsonc routes only ${ai ? '/api/* and /agents/*' : '/api/*'} here; everything else is a static asset or index.html.\nexport default {\n${\n custom\n ? ` ${isAsync ? 'async ' : ''}fetch(request: Request, env: Env): Promise<Response>${isAsync ? '' : ' | Response'} {${\n access\n ? `\n // Cloudflare Access is in front of the app (README); this refuses a request that came\n // around it (straight to *.workers.dev, say). \\`vite dev\\` has no Access, so not there.\n if (!import.meta.env.DEV) {\n try {\n await requireAccess(request, {\n teamDomain: env.ACCESS_TEAM_DOMAIN,\n audience: env.ACCESS_AUD,\n })\n } catch (error) {\n return guardResponse(error)\n }\n }`\n : ''\n }${\n limiter\n ? `\n if (countsAgainstLimit(request)) {\n try {\n await rateLimit(env.LIMITER, clientIp(request))\n } catch (error) {\n return guardResponse(error)\n }\n }`\n : ''\n }${\n accounts\n ? `${\n emailAuth\n ? `\n // Sign-in links and sessions: /api/auth/* is answered here (worker/auth.ts sends mail).\n const signIn = await handleAuth(env.DB, {\n sendLink: (email, url) => sendSignInLink(env.EMAIL, env.AUTH_FROM, email, url),\n exposeLink: import.meta.env.DEV,\n })(request)\n if (signIn) return signIn`\n : ''\n }${\n oauth\n ? `\n // Sign-in with GitHub, Google and LinkedIn: /api/auth/oauth/* (and /me, /signout). A failed\n // sign-in lands on /account with ?error=.\n const signInWith = await handleOAuth(env.DB, {\n secret: env.AUTH_SECRET ?? '',\n providers: oauthProviders(env),\n errorPath: '/account',\n })(request)\n if (signInWith) return signInWith`\n : ''\n }\n // Every other API write needs a signed-in user; reads stay public.${signedPaths.length > 0 ? '\\n // Webhooks carry a signature instead of a session, and are checked by it.' : ''}${readerPaths.length > 0 ? '\\n // Newsletter readers sign up, confirm and unsubscribe without an account.' : ''}\n if (${\n openPaths.length > 0\n ? `\n request.method !== 'GET' &&\n request.method !== 'HEAD' &&${openPaths\n .map((prefix) => `\\n !new URL(request.url).pathname.startsWith('${prefix}')`)\n .join(' &&')}\n `\n : \"request.method !== 'GET' && request.method !== 'HEAD'\"\n }) {\n try {\n await requireUser(env.DB, request)\n } catch (error) {\n return guardResponse(error)\n }\n }${\n social\n ? `\n // The accounts a user connects to post with (worker/social.ts): /api/connections/*, and\n // the client metadata Bluesky's servers read.\n const blueskyClient = socialStore.blueskyClient(env, request)\n if (blueskyClient) return blueskyClient\n const connected = await socialStore.connections(env)(request)\n if (connected) return connected\n // Images for posts: the user's own uploads, and the signed links Threads and Buffer fetch.\n const image =\n (await socialStore.images(env, request)) ?? (await socialStore.media(env, request))\n if (image) return image`\n : ''\n }`\n : ''\n }${\n ai\n ? `\n // /agents/<agent>/<conversation>: the WebSocket ${[agent ? 'useAgent()' : '', voice ? 'VoiceClient' : ''].filter(Boolean).join(' or ')} opens.\n const agent = await routeAgentRequest(request, env)\n if (agent) return agent`\n : ''\n }${\n files\n ? `\n // Uploads into R2 and the files they stored.${access ? '' : ' Anyone can upload: see README.'}\n const upload = await handleUploads(uploads, env.FILES, { images: env.IMAGES })(request)\n if (upload) return upload`\n : ''\n }${\n exports\n ? `\n // /api/export?page=/report&format=pdf — each export starts a browser.\n const exported = await handleExport(request, { launch: () => puppeteer.launch(env.BROWSER) })\n if (exported) return exported`\n : ''\n }${\n live\n ? `\n // The /ops dashboard's room: browsers watch it, and only the queue handler writes to it.\n if (new URL(request.url).pathname === '/api/live') {\n return roomResponse(request, env.LIVE, OPS_ROOM, { readOnly: true })\n }`\n : ''\n }${\n publish\n ? `\n // A published page: its HTML carries the page's title, description and content, for link\n // previews and readers without JavaScript (worker/page-html.ts). An unknown slug gets the\n // app itself, which says so.\n const pagePath = new URL(request.url).pathname\n const published = /^\\\\/p\\\\/([a-z0-9]{10})$/.exec(pagePath)\n if (published && request.method === 'GET') {\n try {\n const page = await pageStore.getPage(env.DB, published[1]!)${\n exports\n ? `\n const image = new URL(\\`/api/pages/\\${page.slug}/preview.png\\`, request.url).href\n return await renderPageHtml(request, page, env.ASSETS, image)`\n : `\n return await renderPageHtml(request, page, env.ASSETS, null)`\n }\n } catch (error) {\n if (!(error instanceof HttpError)) throw error\n return env.ASSETS.fetch(request)\n }\n }${\n exports\n ? `\n // Its link-preview image, rendered once by Browser Run (worker/page-preview.ts).\n const preview = /^\\\\/api\\\\/pages\\\\/([a-z0-9]{10})\\\\/preview\\\\.png$/.exec(pagePath)\n if (preview && request.method === 'GET') {\n try {\n return await pagePreview(env.DB, preview[1]!, new URL(request.url).origin, () =>\n puppeteer.launch(env.BROWSER),\n )\n } catch (error) {\n return guardResponse(error)\n }\n }`\n : ''\n }`\n : ''\n }${\n webhooks\n ? `\n const path = new URL(request.url).pathname\n // Signed deliveries from GitHub (worker/webhooks.ts); a bad signature is a 401.\n if (path === webhookStore.GITHUB_WEBHOOK_PATH && request.method === 'POST') {\n try {\n return await webhookStore.receiveGithub(request, env)\n } catch (error) {\n return guardResponse(error)\n }\n }\n // New deliveries, pushed to the /webhooks page: it may watch, never write.\n if (path === '/api/webhooks/live') {\n return roomResponse(request, env.ROOMS, DELIVERIES_ROOM, { readOnly: true })\n }`\n : ''\n }${\n checkout\n ? `\n const checkoutPath = new URL(request.url).pathname\n // Stripe's webhook (worker/checkout.ts); a bad signature is a 401.\n if (checkoutPath === orderStore.STRIPE_WEBHOOK_PATH && request.method === 'POST') {\n try {\n return await orderStore.receiveStripe(request, env${\n billing ? ', billingStore.billingHooks(env)' : ''\n })\n } catch (error) {\n return guardResponse(error)\n }\n }\n // An order's page watches its room for what Stripe reports: it may watch, never write.\n const orderLive = /^\\\\/api\\\\/orders\\\\/([^/]+)\\\\/live$/.exec(checkoutPath)\n if (orderLive && ORDER_ID.test(orderLive[1]!)) {\n return roomResponse(request, env.ROOMS, orderRoom(orderLive[1]!), { readOnly: true })\n }`\n : ''\n }${\n newsletter\n ? `\n const newsletterPath = new URL(request.url).pathname\n // One-click unsubscribe (RFC 8058) and the unsubscribe page's button.\n if (newsletterPath === '/api/newsletter/unsubscribe' && request.method === 'POST') {\n return newsletterStore.unsubscribe(request, env)\n }\n // SES bounces and complaints, delivered by SNS (worker/newsletter.ts); verified by signature.\n if (newsletterPath === '/api/sns/ses' && request.method === 'POST') {\n try {\n return await newsletterStore.receiveFeedback(request, env)\n } catch (error) {\n return guardResponse(error)\n }\n }\n // An issue's sending progress, for the composer: it may watch, never write.\n const issueLive = /^\\\\/api\\\\/newsletter\\\\/issues\\\\/([^/]+)\\\\/live$/.exec(newsletterPath)\n if (issueLive && ISSUE_ID.test(issueLive[1]!)) {\n return roomResponse(request, env.ROOMS, issueRoom(issueLive[1]!), { readOnly: true })\n }`\n : ''\n }${\n hasExample(opts, 'board') || hasExample(opts, 'notes')\n ? `\n const room = /^\\\\/api\\\\/rooms\\\\/([^/]+)$/.exec(new URL(request.url).pathname)${\n serverRooms.length > 0\n ? `\n // Rooms only the server writes are watched read-only at their own routes, never opened\n // here: ${[imports ? \"a job's progress\" : '', webhooks ? 'webhook deliveries' : '', checkout ? 'orders' : '', newsletter ? 'newsletter issues' : ''].filter(Boolean).join(', ')}.\n if (room && !/^(${serverRooms.join('|')})/.test(room[1]!)) {\n return roomResponse(request, env.ROOMS, room[1]!)\n }`\n : `\n if (room) return roomResponse(request, env.ROOMS, room[1]!)`\n }`\n : ''\n }${\n imports\n ? `\n // A job's progress: the browser may watch its room, never write to it.\n const job = /^\\\\/api\\\\/jobs\\\\/([\\\\w-]{1,60})$/.exec(new URL(request.url).pathname)\n if (job) {\n return roomResponse(request, env.ROOMS, importJob.roomName(job[1]!), { readOnly: true })\n }`\n : ''\n }\n return ${usage ? 'handleAndRecord' : 'handleApi'}(request, env)\n },`\n : ` fetch: ${usage ? 'handleAndRecord' : 'handleApi'},`\n}${\n digest && social\n ? `\n // The Cron Triggers in wrangler.jsonc, told apart by their schedule.\n async scheduled(event: { cron: string }, env: Env): Promise<void> {\n // Threads tokens renewed, and reminders for those that cannot be (worker/social.ts).\n if (event.cron === '${SOCIAL_CRON}') {\n await socialStore.renewConnections(env)\n return socialStore.remindExpiring(env)\n }\n // The weekly digest, recorded whatever happens.\n await digestJob.runDigest(env, () => puppeteer.launch(env.BROWSER), 'cron')\n },`\n : digest\n ? `\n // The Cron Trigger in wrangler.jsonc: the weekly digest, recorded whatever happens.\n async scheduled(_event: unknown, env: Env): Promise<void> {\n await digestJob.runDigest(env, () => puppeteer.launch(env.BROWSER), 'cron')\n },`\n : social\n ? `\n // The Cron Trigger in wrangler.jsonc: Threads tokens renewed, then reminders for the ones\n // that cannot be (LinkedIn).\n async scheduled(_event: unknown, env: Env): Promise<void> {\n await socialStore.renewConnections(env)\n await socialStore.remindExpiring(env)\n },`\n : ''\n }${\n live && newsletter\n ? `\n // Two queues, one handler: each batch says which queue it came from. A throw retries it.\n async queue(batch: LiveBatch & NewsletterBatch & { queue: string }, env: Env): Promise<void> {\n // NEWSLETTER: one message of readers at a time, through SES (worker/newsletter.ts).\n if (batch.queue === '${newsletterQueue(opts)}') return newsletterStore.deliver(env, batch)\n // EVENTS: into the dashboard's room.\n await recordLive(\n ops,\n env.LIVE,\n OPS_ROOM,\n batch.messages.map((message) => message.body),\n )\n },`\n : live\n ? `\n // The EVENTS queue, a batch at a time, into the dashboard's room. A throw retries the batch.\n async queue(batch: LiveBatch, env: Env): Promise<void> {\n await recordLive(\n ops,\n env.LIVE,\n OPS_ROOM,\n batch.messages.map((message) => message.body),\n )\n },`\n : newsletter\n ? `\n // The NEWSLETTER queue: one message of readers at a time, through SES\n // (worker/newsletter.ts). A throw retries the message; readers already sent are skipped.\n async queue(batch: NewsletterBatch, env: Env): Promise<void> {\n await newsletterStore.deliver(env, batch)\n },`\n : ''\n }\n}\n`\n}\n\n/** Route pattern for a section: the first is `/`, the rest by key. */\nfunction cfSectionPath(section: Section, index: number): string {\n return index === 0 ? '/' : `/${section.key}`\n}\n\n/** Route file for a section, relative to `src/routes/`. */\nfunction cfSectionFile(section: Section, index: number): string {\n return index === 0 ? 'index.tsx' : `${section.key}.tsx`\n}\n\nfunction cfAppTsx(sections: Section[], recipes: string[], opts: ScaffoldOptions): string {\n const items = [\n ...sections.map((s, i) => ({ label: s.label, href: cfSectionPath(s, i) })),\n ...recipes.flatMap((recipe) => loadRecipe(recipe).nav),\n ]\n const navItems = items\n .map(\n (item) => ` {\n label: '${item.label.replace(/'/g, \"\\\\'\")}',\n href: '${item.href}',\n active: path === '${item.href}',\n },`,\n )\n .join('\\n')\n const exports = hasExample(opts, 'export')\n return `import { RouterView } from '@cascivo/app'\n${exports ? `import { isExporting } from '@cascivo/app/export'\\n` : ''}import { Spinner, useSignals, type SideNavItem } from '@cascivo/react'\nimport { router } from './router'\nimport { Shell } from './Shell'\n\nexport default function App() {\n useSignals()\n const path = router.pathname.value\n\n // \\`href\\`s, not click handlers: main.tsx registers the router's Link, so these navigate\n // client-side while middle-click and \"open in new tab\" still work.\n const navItems: SideNavItem[] = [\n${navItems}\n ]\n${\n exports\n ? `\n // Rendered by /api/export: the page alone, without the shell (which gave it its padding).\n if (isExporting()) {\n return (\n <div style={{ padding: 'var(--cascivo-space-8)' }}>\n <RouterView router={router} fallback={<Spinner label=\"Loading\" />} />\n </div>\n )\n }\n`\n : ''\n}\n return (\n <Shell navItems={navItems}>\n <RouterView router={router} fallback={<Spinner label=\"Loading\" />} />\n </Shell>\n )\n}\n`\n}\n\nfunction cfFirstRouteTsx(section: Section): string {\n return `import { Flex, Heading, Text } from '@cascivo/react'\nimport { LiveCard } from '../LiveCard'\n\nexport default function ${section.component}() {\n return (\n <Flex gap={6}>\n <Flex gap={2}>\n <Heading level={1}>${section.label}</Heading>\n <Text muted>\n Edit <code>src/routes/index.tsx</code> to build out this page.\n </Text>\n </Flex>\n <LiveCard />\n </Flex>\n )\n}\n`\n}\n\nfunction cfRouteTsx(section: Section, index: number): string {\n // The Vite scaffold's section, as a route file: a default export, at its own URL.\n return sectionTsx(section)\n .replace(\n `export function ${section.component}()`,\n `export default function ${section.component}()`,\n )\n .replace(`src/sections/${section.component}.tsx`, `src/routes/${cfSectionFile(section, index)}`)\n}\n\n/* --- `--example social`: scheduled posts to connected LinkedIn and Mastodon accounts --- */\n\n/** Daily, off the hour: renews Threads tokens in their last 30 days (\\`renewConnections\\`). */\nconst SOCIAL_CRON = '17 4 * * *'\n\nfunction cfAccountRouteTsx(opts: ScaffoldOptions): string {\n const email = emailSignIn(opts)\n const oauth = oauthSignIn(opts)\n const lead = email\n ? oauth\n ? 'Continue with GitHub, Google or LinkedIn, or get a one-time link by email. No password.'\n : 'No password: we email you a link that signs you in once.'\n : 'Continue with GitHub, Google or LinkedIn. No password.'\n return `import {\n Alert,\n Button,\n Card,\n CardContent,\n Flex,\n Heading,${email ? '\\n Input,\\n Link,' : ''}\n Spinner,\n Text,\n signal,\n useSignals,\n} from '@cascivo/react'\n${email ? \"import type { FormEvent } from 'react'\\n\" : ''}import { auth } from '../auth'${oauth ? \"\\nimport { router } from '../router'\" : ''}\n${\n email\n ? `\nconst sentTo = signal<string | null>(null)\n/** Set only in \\`vite dev\\`, where no email is sent: the link to open instead. */\nconst devLink = signal<string | null>(null)\nconst failure = signal<string | null>(null)\nconst sending = signal(false)\n\nasync function start(event: FormEvent<HTMLFormElement>): Promise<void> {\n event.preventDefault()\n const email = new FormData(event.currentTarget).get('email')\n if (typeof email !== 'string') return\n failure.value = null\n sending.value = true\n try {\n const { link } = await auth.start(email)\n sentTo.value = email\n devLink.value = link\n } catch (error) {\n failure.value = error instanceof Error ? error.message : 'Could not send the link'\n } finally {\n sending.value = false\n }\n}\n`\n : ''\n}${\n oauth\n ? `\nconst LABELS: Record<string, string> = { github: 'GitHub', google: 'Google', linkedin: 'LinkedIn' }\n\n/** The providers the Worker offers: those with an id and a secret set (README). */\nconst providers = signal<string[] | null>(null)\nauth.providers().then(\n (list) => {\n providers.value = list\n },\n () => {\n providers.value = []\n },\n)\n\n/** Why the last sign-in with a provider failed: the Worker sends it back as \\`?error=\\`. */\nconst REASONS: Record<string, string> = {\n denied: 'You did not allow access, so you are not signed in.',\n expired: 'The sign-in took too long, or started in another browser. Try again.',\n state_mismatch: 'That sign-in did not match the one this browser started. Try again.',\n provider_error: 'The provider did not confirm who you are. Try again, or use another way in.',\n identity_in_use: 'That account is already linked to another user here.',\n}\n`\n : ''\n }\nexport default function Account() {\n useSignals()\n const user = auth.user.value${\n oauth\n ? `\n const reason = new URLSearchParams(router.search.value).get('error')`\n : ''\n }\n\n if (user === undefined) return <Spinner label=\"Loading\" />\n if (user) {\n return (\n <Flex gap={4}>\n <Heading level={1}>Account</Heading>\n <Card>\n <CardContent>\n <Flex gap={3}>\n <Text>{user.email ? \\`Signed in as \\${user.email}\\` : 'Signed in'}</Text>\n <Flex direction=\"horizontal\">\n <Button variant=\"secondary\" onClick={() => void auth.signOut()}>\n Sign out\n </Button>\n </Flex>\n </Flex>\n </CardContent>\n </Card>\n </Flex>\n )\n }\n return (\n <Flex gap={4}>\n <Flex gap={1}>\n <Heading level={1}>Sign in</Heading>\n ${\n // Prettier's width: a lead too long for one line goes on its own.\n `<Text muted>${lead}</Text>`.length + 8 > 100\n ? `<Text muted>\\n ${lead}\\n </Text>`\n : `<Text muted>${lead}</Text>`\n }\n </Flex>${\n oauth\n ? `\n {reason ? (\n <Alert variant=\"destructive\" title=\"Not signed in\">\n {REASONS[reason] ?? 'Sign-in failed. Try again.'}\n </Alert>\n ) : null}\n {providers.value === null ? (\n <Spinner label=\"Loading\" />\n ) : providers.value.length === 0 ? (\n <Alert variant=\"info\" title=\"No provider is set up yet\">\n Set GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET, or the GOOGLE_ pair, in .dev.vars (README).\n </Alert>\n ) : (\n <Flex direction=\"horizontal\" gap={2} wrap>\n {providers.value.map((id) => (\n // A plain link: the Worker redirects to the provider, and back here afterwards.\n <Button key={id} asChild variant=\"secondary\">\n <a href={auth.signInUrl(id, '/account')}>Continue with {LABELS[id] ?? id}</a>\n </Button>\n ))}\n </Flex>\n )}`\n : ''\n }${\n email\n ? `\n {sentTo.value ? (\n <Alert variant=\"success\" title=\"Check your email\">\n We sent a sign-in link to {sentTo.value}. It works once, for 15 minutes.\n </Alert>\n ) : null}\n {devLink.value ? (\n <Alert variant=\"info\" title=\"vite dev sends no email\">\n <Link href={devLink.value}>Open the sign-in link</Link>\n </Alert>\n ) : null}\n {failure.value ? (\n <Alert variant=\"destructive\" title=\"Not sent\">\n {failure.value}\n </Alert>\n ) : null}\n <form onSubmit={(event) => void start(event)}>\n <Flex direction=\"horizontal\" align=\"end\" gap={2} wrap>\n <Input name=\"email\" type=\"email\" label=\"Email\" autoComplete=\"email\" required />\n <Button type=\"submit\" loading={sending.value}>\n Email me a link\n </Button>\n </Flex>\n </form>`\n : ''\n }\n </Flex>\n )\n}\n`\n}\n\nfunction cfPrettierIgnore(): string {\n return `${prettierIgnore()}# Rewritten by @cascivo/app/vite whenever a route file changes.\nsrc/routes.gen.ts\n`\n}\n\nfunction cfGitignore(): string {\n return `node_modules\ndist\n.wrangler\n.dev.vars*\n!.dev.vars.example\n*.local\n.DS_Store\n`\n}\n\nfunction cfReadme(opts: ScaffoldOptions): string {\n const pm = opts.pm ?? 'npm'\n const runtime = runtimeOf(opts)\n return `# ${opts.name}\n\nA [cascivo](https://cascivo.com) app on Cloudflare: a client-rendered\n${runtime === 'preact' ? 'Preact' : 'React'} app and its API, deployed as one Worker.\nThere is no server rendering; the browser gets the app, and \\`/api/*\\` reaches the Worker.\n\n## Develop\n\n\\`\\`\\`sh\n${installAllCommand(pm)}\n${runScriptCommand(pm, 'dev')}\n\\`\\`\\`\n\n\\`vite dev\\` runs \\`worker/index.ts\\` in workerd, the same runtime as production, via\n\\`@cloudflare/vite-plugin\\`.\n\n## Deploy\n\n\\`\\`\\`sh\nnpx wrangler login # once\n${runExplicitCommand(pm, 'deploy')}\n\\`\\`\\`\n\n## Share a preview (no account)\n\n\\`\\`\\`sh\n${runExplicitCommand(pm, 'deploy:preview')}\n\\`\\`\\`\n\nThis builds the app, then deploys it to a temporary Cloudflare account with\n\\`wrangler deploy --temporary\\`. You need no sign-up. It prints two URLs:\n\n- **A public \\`workers.dev\\` URL** for the app.\n- **A claim URL.** Open it and sign in within 60 minutes to keep the deployment; otherwise it is deleted.\n\nIt works only while wrangler is logged out. If you are logged in, use \\`deploy\\` instead.\nA temporary account supports Workers, static assets, KV, D1 and Durable Objects. It does not\nsupport Workers AI, R2, Workflows or Browser Run.${\n usesAgents(opts)\n ? ` So a preview serves the app, but its ${hasExample(opts, 'agent') ? 'assistant' : 'voice page'} cannot reach the model: deploy it\\nto your own account for that.`\n : ''\n }\n\n## Structure\n\n- \\`src/routes/\\` — one file per page. \\`index.tsx\\` is \\`/\\`, \\`settings.tsx\\` is\n \\`/settings\\`, \\`c/[id].tsx\\` is \\`/c/:id\\` (it receives \\`params.id\\`), \\`404.tsx\\` is\n everything else. \\`src/routes.gen.ts\\` is rewritten from this folder; do not edit it.\n- \\`src/api.ts\\` — the API contract both sides import: endpoints, their paths, and parsers\n for what crosses the network.\n- \\`worker/index.ts\\` — the API's handlers, typed from \\`src/api.ts\\`. Add bindings (KV,\n D1, R2, Durable Objects, Workers AI) in \\`wrangler.jsonc\\`; handlers receive them as \\`env\\`.\n- \\`src/live.ts\\` + \\`src/LiveCard.tsx\\` — a streaming endpoint read through the typed\n client into signals.\n- \\`src/App.tsx\\` — the nav (real \\`href\\`s) and the \\`RouterView\\`.\n- \\`src/Shell.tsx\\` — the app shell (header + side nav + content slot).\n\nPersist client state with \\`persistedSignal\\` from \\`@cascivo/storage\\` (localStorage or\nIndexedDB).${\n hasExample(opts, 'board')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'notes')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'import')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'files')\n ? `\n\n## Files (uploads)\n\n\\`/files\\` uploads into R2 through the Worker, with progress, and shows resized previews.\n\n- \\`src/upload-policy.ts\\` — what the app accepts (types, size), shared by both sides: the page\n checks a file before sending it, and the Worker enforces the same policy. SVG and HTML are\n refused by design; served from your origin they would run script.\n- \\`worker/index.ts\\` — \\`handleUploads\\` (\\`@cascivo/app/uploads-server\\`) stores uploads, in\n parts above 16 MiB, under keys the Worker chooses, and serves them back with headers that\n stop any file running script. \\`?w=320\\` returns a WebP preview from Cloudflare Images.\n- \\`src/files.ts\\` — \\`startUpload\\` gives each file progress and status signals.\n\nEach caller (by IP) may start 20 uploads a minute (\\`ratelimits\\` in \\`wrangler.jsonc\\`).${\n opts.auth\n ? ''\n : `\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.`\n } Create the bucket once before deploying:\n\\`npx wrangler r2 bucket create ${packageName(opts.name)}-files\\`. R2 and Images do not run on a\ntemporary account.`\n : ''\n }${\n hasExample(opts, 'export')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'live')\n ? `\n\n## Ops (live dashboard)\n\n\\`/ops\\` charts orders, revenue and errors per second, and every open copy of the page moves\ntogether as events arrive.\n\n- \\`src/ops.ts\\` — \\`defineLive\\` (\\`@cascivo/app/live\\`): the metrics, and two minutes of\n per-second history.\n- \\`worker/index.ts\\` — \\`POST /api/events\\` puts events on the \\`EVENTS\\` queue. The \\`queue\\`\n handler adds each batch into a \\`LiveRoom\\` Durable Object with \\`recordLive\\`, which keeps\n per-second totals and sends each change to the browsers watching \\`/api/live\\` (read-only).\n- \\`src/routes/ops.tsx\\` — \\`watchLive\\` gives the window as a signal; the page sends simulated\n traffic while its switch is on. Real producers are anything with the queue binding: another\n Worker, a cron, a webhook handler.\n\nA new viewer, or one back from a dropped connection, starts with the whole window. Delivery is\nat least once: a batch retried after a lost reply counts twice. \\`/api/events\\` has no auth, so\nanyone can move the numbers: check who is sending before real use (\\`--auth access\\` puts\nCloudflare Access in front of the Worker). Create the queue once before deploying:\n\\`npx wrangler queues create ${packageName(opts.name)}-events\\`.`\n : ''\n }${\n hasExample(opts, 'usage')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'search')\n ? `\n\n## Search (by meaning)\n\n\\`/search\\` finds help articles by what a question means: \"how do I get my money back\" finds\nRefunds, though they share no words. Each article is embedded with Workers AI\n(\\`@cf/baai/bge-base-en-v1.5\\`) into a Vectorize index; a question is embedded the same way\nand matched against it.\n\n- \\`worker/articles.ts\\` — the articles, seeded into D1. Replace them with your own content.\n- \\`worker/search.ts\\` — \\`search\\` and \\`indexArticles\\`. \"Index articles\" on the page embeds\n every article; Vectorize applies writes a few seconds later.\n\nCreate the index once before deploying, with the embedding model's dimensions:\n\\`npx wrangler vectorize create ${packageName(opts.name)}-articles --dimensions=768 --metric=cosine\\`.\nNeither Vectorize nor Workers AI runs locally, so \\`vite dev\\` searches by keyword with SQLite's\nfull-text search instead, and the page says so. \\`VITE_REAL_AI=1 ${runScriptCommand(pm, 'dev')}\\` uses the real ones\n(after \\`npx wrangler login\\`). Workers AI and Vectorize bill per use beyond their free\nallocations, and a temporary account has neither.`\n : ''\n }${\n hasExample(opts, 'digest')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'webhooks')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'checkout')\n ? `\n\n## Checkout (Stripe)\n\n\\`/checkout\\` sells one product on Stripe's hosted Checkout page: the card never touches this\napp. Stripe tells the Worker when the payment succeeds; the Worker marks the order paid, pushes\nit to the order page, and emails a receipt rendered with \\`@cascivo/email\\`.\n\n1. In the Stripe dashboard, in test mode, copy the secret key (\\`sk_test_…\\`) into \\`.dev.vars\\`\n as \\`STRIPE_SECRET_KEY\\`, then run the app and buy with the card \\`4242 4242 4242 4242\\`.\n The order page confirms the payment by reading the session back from Stripe, so this works\n before any webhook is set up.\n2. To receive the webhook locally, run\n \\`stripe listen --forward-to localhost:5173/api/stripe/webhook\\` (the Stripe CLI) and put the\n \\`whsec_…\\` secret it prints in \\`.dev.vars\\` as \\`STRIPE_WEBHOOK_SECRET\\`.\n3. Deployed: \\`npx wrangler secret put STRIPE_SECRET_KEY\\` and\n \\`npx wrangler secret put STRIPE_WEBHOOK_SECRET\\`. In the dashboard, add a webhook endpoint\n at \\`https://<your app>/api/stripe/webhook\\` for \\`checkout.session.completed\\`,\n \\`checkout.session.async_payment_succeeded\\`, \\`checkout.session.async_payment_failed\\`,\n \\`checkout.session.expired\\`, \\`charge.refunded\\`, \\`charge.dispute.created\\` and\n \\`charge.dispute.closed\\`; its signing secret is \\`STRIPE_WEBHOOK_SECRET\\`.\n4. Receipts: set \\`RECEIPT_FROM\\` in \\`wrangler.jsonc\\` to an address on a domain you have\n onboarded to Email Service. \\`vite dev\\` renders each receipt and logs it instead.\n\nWhat you sell is \\`PRODUCT\\` in \\`src/checkout.ts\\`. The Worker sends that price to Stripe, so a\nbrowser cannot change it.\n\n- \\`worker/checkout.ts\\` — \\`createStripe\\` (\\`@cascivo/app/stripe\\`) creates the session, with\n the order id as its idempotency key. The webhook is checked by \\`verifyWebhook\\` (scheme\n \\`stripe\\`: signature and a five-minute window) before \\`parseStripeEvent\\` reads it.\n- An order moves from \\`pending\\` to \\`paid\\`, \\`failed\\` or \\`expired\\` once. A retried event, or\n the page getting there before the webhook, changes nothing, so the receipt goes out once.\n Orders are found by Stripe's session id, never by \\`client_reference_id\\`, which a buyer can\n set on a Payment Link.\n- A bank debit completes the session as \\`unpaid\\`: the order stays pending until\n \\`async_payment_succeeded\\` or \\`async_payment_failed\\` arrives, possibly days later.\n- Refunds are made in the Stripe dashboard (or with \\`createRefund\\`); \\`charge.refunded\\` records\n the amount, and an order refunded in full becomes \\`refunded\\`. A chargeback makes it\n \\`disputed\\` until it is decided: answer it with evidence in the dashboard. Both find the\n order by the payment it stored when it was paid.\n- \\`src/routes/checkout/[order].tsx\\` — where Stripe sends the buyer back. It watches the\n order's read-only room, so it updates when the webhook arrives.\n\nEach caller (by IP) may start 20 checkouts a minute.${\n usesBilling(opts)\n ? `\n\n### Subscriptions (\\`/billing\\`)\n\nSigned-in users subscribe to \\`PLAN\\` (\\`src/billing.ts\\`) on Stripe's checkout and change,\npause or cancel it in Stripe's hosted billing portal, so the app has no billing screens to build.\n\n1. Add \\`customer.subscription.created\\`, \\`customer.subscription.updated\\`,\n \\`customer.subscription.deleted\\` and \\`invoice.payment_failed\\` to the webhook endpoint's\n events.\n2. In the Stripe dashboard, save the Customer Portal's settings once (test mode too): until\n then, Stripe refuses to open it.\n3. Gate a paid feature in the Worker with \\`await billingStore.requirePlan(env, request)\\` (402\n without the plan), never on what the page shows.\n\n- \\`worker/billing.ts\\` — the subscription names its user in its metadata, which only the\n Worker sets (\\`client_reference_id\\` can be set by a buyer on a Payment Link). Every\n subscription event is read back from Stripe before it is stored, because events arrive out of\n order, and a late event about an older subscription cannot end a live one.\n- Back from checkout, \\`/billing\\` reads the session and its subscription at once, so it is right\n before the webhook arrives, and only for the user the subscription names.\n- A renewal that cannot be charged leaves the plan on (\\`past_due\\`) while Stripe retries, and\n emails the customer once per attempt with Stripe's page to pay with another card. How long\n Stripe retries, and whether it then cancels, is set in the dashboard (Billing → Subscriptions\n and emails); turn off Stripe's own failed-payment emails there, or customers get two.`\n : `\n\nSubscriptions need an account to belong to: \\`cascivo create --framework cloudflare\n--example checkout --auth email\\` adds a \\`/billing\\` page with a monthly plan and Stripe's\nbilling portal.`\n }`\n : ''\n }${\n hasExample(opts, 'newsletter')\n ? `\n\n## Newsletter (Amazon SES)\n\n\\`/newsletter\\` signs readers up; \\`/newsletter/send\\` writes an issue in Markdown, previews it\nas the email it will be (rendered with \\`@cascivo/email\\`), and sends it to every confirmed\nreader through Amazon SES. It runs in \\`vite dev\\` with nothing set up: emails are logged instead\nof sent, and the sign-up page shows the confirmation link. The composer's key is in\n\\`.dev.vars\\` (\\`NEWSLETTER_KEY\\`).\n\nTo send for real:\n\n1. In SES, verify the domain you send from (SES gives DNS records for DKIM; add them in\n Cloudflare DNS, with an SPF and a DMARC record), and ask AWS to move the account out of the\n sandbox, where it can mail only verified addresses.\n2. Create an IAM user allowed \\`ses:SendEmail\\` and nothing else, and give its keys to the\n Worker: \\`npx wrangler secret put AWS_ACCESS_KEY_ID\\` and \\`AWS_SECRET_ACCESS_KEY\\` (in\n \\`.dev.vars\\` locally). Set \\`AWS_REGION\\` and \\`NEWSLETTER_FROM\\` in \\`wrangler.jsonc\\`, and\n \\`npx wrangler secret put NEWSLETTER_KEY\\` to a long random value.\n3. Bounces and complaints: create an SNS topic, set it as the SES identity's bounce and\n complaint notification topic, and subscribe \\`https://<your app>/api/sns/ses\\` to it (HTTPS).\n Put the topic's ARN in \\`SNS_TOPIC_ARN\\`. The Worker confirms the subscription itself.\n4. Create the queue once: \\`npx wrangler queues create ${newsletterQueue(opts)}\\`.\n\n- \\`worker/newsletter.ts\\` — double opt-in: a sign-up gets a confirmation link (valid a day,\n resent at most every ten minutes) and gets no issue until it is opened. Sending stores the\n issue and puts its readers on the \\`NEWSLETTER\\` queue, 25 per message; the consumer sends\n them one by one through \\`createSes\\` (\\`@cascivo/app/ses\\`), handed to \\`sendEmail\\` from\n \\`@cascivo/email\\`, which checks each message before it leaves, one message at a time. Each\n send is recorded, so a message retried after SES throttling skips whoever already has it.\n- Every issue carries \\`List-Unsubscribe\\` and \\`List-Unsubscribe-Post\\` (one-click\n unsubscribe, RFC 8058, which Gmail and Yahoo require of bulk senders) and a footer link to\n \\`/newsletter/unsubscribe\\`.\n- \\`handleSns\\` checks each SNS message's signature against SNS's certificate before\n \\`parseSesNotification\\` reads it. A permanent bounce or a complaint suppresses the address\n for good: mailing it again is what gets an SES account reviewed.\n- \\`worker/newsletter-email.ts\\` — the issue and confirmation emails. The body is Markdown drawn\n through the email primitives; raw HTML in it stays literal text.\n\nSign-ups and every use of the newsletter key count against the rate limit (20 a minute per\nIP). Sending reads every confirmed address into memory; past a few hundred thousand readers,\npage through them instead.`\n : ''\n }${\n hasExample(opts, 'social')\n ? `\n\n## Social posts\n\n\\`/social\\` connects Bluesky, Buffer, LinkedIn, Mastodon and Threads accounts and posts to them,\nnow or at a time you pick.\n\n- \\`worker/social.ts\\` — \\`handleConnections\\` (\\`@cascivo/app/oauth-server\\`) answers\n \\`/api/connections/*\\`: connect, list, remove. Tokens are sealed in D1 with \\`AUTH_SECRET\\`.\n Scheduling checks that each account is yours and connected, and that each network's\n publisher (\\`@cascivo/app/social\\`) accepts the post, before anything is stored.\n- \\`worker/social-post.ts\\` — \\`SocialPost\\`, a Workflow per post: it sleeps until the post\n is due, then posts to each account in its own step. Bluesky and Mastodon steps retry, safely:\n Mastodon takes an idempotency key, and a Bluesky post's record key is fixed by its time and\n id. Buffer, LinkedIn and Threads steps never do: they cannot deduplicate, so an interrupted\n post there is reported for you to check rather than sent twice.\n- \\`src/social.ts\\` — the shared types, and the publishers the page also runs, so what a\n network would refuse shows while you type.\n- Images: the composer uploads them into the \\`SOCIAL_MEDIA\\` R2 bucket through the Worker\n (\\`@cascivo/app/uploads\\`), each user under their own prefix; up to 4, JPEG or PNG, 1 MB each\n (Bluesky's limit), each with a description. Bluesky, LinkedIn and Mastodon get the bytes.\n Threads and Buffer fetch images by URL, so they get a link to \\`/api/social/media/…\\` signed\n with \\`AUTH_SECRET\\`. It is valid until a day after the post is due, and needs \\`APP_URL\\` set\n to the deployed app. Uploads stay in R2: add a lifecycle rule\n (\\`wrangler r2 bucket lifecycle add\\`) to expire old ones.\n\n**Bluesky** needs no set-up either: people type their handle. Bluesky's servers read this\napp's client metadata from \\`/api/bluesky/client-metadata.json\\`, so the deployed app must be\nreachable at its URL. In \\`vite dev\\` the app is Bluesky's development client, which may only\nreturn to \\`127.0.0.1\\`: open \\`http://127.0.0.1:5173\\`, not \\`localhost\\`. Without a key the app is a\npublic client and sessions end after two weeks; for sessions that last, make a key and set it\nas the \\`BLUESKY_PRIVATE_JWK\\` secret:\n\n\\`\\`\\`sh\nnode -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'})))\"\n\\`\\`\\`\n\n**Mastodon** needs no set-up: people type their server, and the app registers itself there\non first use.\n\n**Buffer** reaches the networks connected there (X, Instagram, TikTok, …): register an app\nclient at https://publish.buffer.com/settings/api with \\`…/api/connections/buffer/callback\\` as\nits redirect URL, and set \\`BUFFER_CLIENT_ID\\` (and \\`BUFFER_CLIENT_SECRET\\` for a confidential\nclient). Each channel in a connected Buffer is an account in the composer, checked against\nits network's limit. Buffer counts every request against your plan's budget (100 per 15\nminutes on every plan), for all your users together, so the channel list is kept for an hour.\nBuffer cannot deduplicate, so its posts are never retried, like LinkedIn's. **LinkedIn** needs an app at https://www.linkedin.com/developers/apps with the\n\"Share on LinkedIn\" product${oauthSignIn(opts) ? ' (the same app as sign-in works, with both products)' : ''}; add\n\\`…/api/connections/linkedin/callback\\` as a redirect URL and set \\`LINKEDIN_CLIENT_ID\\` and\n\\`LINKEDIN_CLIENT_SECRET\\`. LinkedIn tokens last 60 days and cannot be renewed: the page shows\n\"expires soon\" a week ahead, and connecting again renews the account in place. The daily Cron\nTrigger also emails the owner once, a week ahead, with a link to connect again\n(\\`remindExpiring\\`): set \\`REMINDER_FROM\\` in \\`wrangler.jsonc\\` to an address on a domain you\nhave onboarded to Email Service, and \\`APP_URL\\` to the deployed app. People whose provider shared\nno email see the page's notice only.\n\n**Threads** needs a Meta app with the \"Access the Threads API\" use case\n(https://developers.facebook.com/apps), the \\`threads_basic\\` and \\`threads_content_publish\\`\npermissions, and \\`…/api/connections/threads/callback\\` as a redirect callback URL; set\n\\`THREADS_APP_ID\\` and \\`THREADS_APP_SECRET\\` (the Threads app id and secret, not the Meta\napp's). Until Meta's App Review and business verification pass, only people added as testers\non the app can connect. A Threads token lasts 60 days and renews itself only while it still\nworks, so a daily Cron Trigger (\\`${SOCIAL_CRON}\\`, \\`renewConnections\\`) renews those in their last\n30 days; try it in \\`vite dev\\` at \\`/cdn-cgi/handler/scheduled\\`. Threads takes 500 characters,\ncounting an emoji as several, and cannot deduplicate either.\n\nConnecting an account and posting count against the rate limit (20 a minute per IP).\nWorkflows need a real Cloudflare account to deploy.`\n : ''\n }${\n hasAccounts(opts)\n ? `\n\n## Accounts (${emailSignIn(opts) ? (oauthSignIn(opts) ? 'email, GitHub, Google and LinkedIn sign-in' : 'email sign-in') : 'GitHub, Google and LinkedIn sign-in'})\n\n${\n emailSignIn(opts) && oauthSignIn(opts)\n ? 'Anyone can create an account by continuing with GitHub, Google or LinkedIn, or with their email address, on `/account`.'\n : oauthSignIn(opts)\n ? 'Anyone can create an account by continuing with GitHub, Google or LinkedIn on `/account`.'\n : '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.'\n} **Every API write needs a signed-in user; reads stay public.**\n\n- \\`worker/index.ts\\` — ${[emailSignIn(opts) ? '`handleAuth` (`@cascivo/app/auth-server`)' : '', oauthSignIn(opts) ? '`handleOAuth` (`@cascivo/app/oauth-server`)' : ''].filter(Boolean).join(' and ')} answer${emailSignIn(opts) && oauthSignIn(opts) ? '' : 's'} \\`/api/auth/*\\`, and\n \\`requireUser\\` refuses any other write without a session (401) or from another site (403).\n Call \\`requireUser(env.DB, request)\\` in a handler to know who is asking.${\n emailSignIn(opts)\n ? `\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.`\n : ''\n }\n- \\`src/auth.ts\\` — \\`auth.user\\`, a signal every page can read. \\`user.email\\` is \\`null\\` for\n someone whose provider shared no verified address.${\n emailSignIn(opts)\n ? `\n- \\`src/routes/signin/verify.tsx\\` — the page a link opens. It signs in on a button press,\n because mail scanners open every link in a message.`\n : ''\n }\n\nUsers${emailSignIn(opts) ? ', links' : ''} and sessions live in D1, stored as hashes. ${emailSignIn(opts) ? 'Links expire after 15 minutes and work once; sessions' : 'Sessions'} last 30 days.${emailSignIn(opts) ? ' 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\n(rooms, agents) are not covered by the write rule; check \\`currentUser\\` before forwarding them\nif they need a user.${\n oauthSignIn(opts)\n ? `\n\n### GitHub, Google and LinkedIn\n\n1. **GitHub**: create an OAuth App at https://github.com/settings/developers with the\n callback URL \\`http://localhost:5173/api/auth/oauth/github/callback\\` for \\`vite dev\\`\n (an OAuth App takes one callback URL, so make a second app for the deployed one).\n2. **Google**: in the Google Cloud console, create an OAuth client of type \"Web application\"\n with the redirect URIs \\`http://localhost:5173/api/auth/oauth/google/callback\\` and\n \\`https://<your app>/api/auth/oauth/google/callback\\`.\n3. **LinkedIn**: create an app at https://www.linkedin.com/developers/apps, add the product\n \"Sign In with LinkedIn using OpenID Connect\", and under Auth add both redirect URLs\n (\\`…/api/auth/oauth/linkedin/callback\\` on localhost and on your app).\n4. Put the ids and secrets in \\`.dev.vars\\`. Deployed: \\`npx wrangler secret put\\` each\n \\`*_CLIENT_ID\\` and \\`*_CLIENT_SECRET\\` you use, and \\`AUTH_SECRET\\` (a random one:\n \\`openssl rand -base64 32\\`). A provider is offered once both its values are set.\n\nPeople are matched by their account at the provider, not by email. A new sign-in joins an\nexisting account only through an email the provider has verified (GitHub's primary verified\naddress, Google's and LinkedIn's \\`email_verified\\`). A signed-in user who follows another provider's link\nadds it to their account.`\n : ''\n }`\n : ''\n }${\n opts.auth === 'access'\n ? `\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\\`.`\n : ''\n }${\n hasExample(opts, 'crud')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'agent')\n ? `\n\n## Assistant (generative UI)\n\n\\`/assistant\\` is a chat whose answers can be UI. The model calls a \\`show_view\\` tool with a view\nconfig; the Worker checks it against the component manifests (\\`validateView\\` from\n\\`@cascivo/render/validate\\`) and returns any errors to the model, which fixes them and calls\nagain. The page renders the result with \\`<CascivoView>\\`: real components, no generated code.\n\n- \\`worker/assistant.ts\\` — \\`Assistant\\`, an \\`AIChatAgent\\` (Cloudflare's Agents SDK): one\n Durable Object per conversation, which stores the messages and streams replies to every open\n tab. The system prompt, the \\`show_view\\` tool and the model (\\`MODEL\\`, any Workers AI model\n with tool calling) are here.\n- \\`src/assistant.ts\\` — \\`checkView\\`, the one check both sides run on a view.\n- \\`src/routes/assistant.tsx\\` — \\`useAgent\\` + \\`useAgentChat\\`; one conversation per browser.\n- \\`worker/scripted-model.ts\\` — \\`vite dev\\` answers from this scripted model, so the page works\n offline and without an account. \\`VITE_REAL_AI=1 ${runScriptCommand(pm, 'dev')}\\` uses Workers AI instead\n (after \\`npx wrangler login\\`); a deployed Worker always does.\n\nWorkers AI bills per use beyond its free daily allocation.`\n : ''\n }${\n hasExample(opts, 'publish')\n ? `\n\n## Publish (views as pages)\n\n\\`/publish\\` turns a view — the JSON that \\`<CascivoView>\\` renders, which an agent can write\ntoo — into a page at \\`/p/<slug>\\`, with no deploy. A view is data, not code: it can only\narrange this app's components with props their manifests allow, so a published page runs no\ncode of its author's and needs no sandbox.\n\n- \\`src/pages.ts\\` — \\`parsePageInput\\` checks a page with \\`validateView\\`\n (\\`@cascivo/render/validate\\`): known components and props, and no link or image URL that\n could run script. The Worker runs it before storing a page; \\`<CascivoView>\\` checks again\n before rendering one.\n- \\`worker/pages.ts\\` — pages in D1, under a random ten-character slug.\n- \\`src/routes/publish.tsx\\` — the editor, with a live preview.\n- \\`src/routes/p/[slug].tsx\\` — a published page.\n- \\`worker/page-html.ts\\` — the Worker answers \\`/p/<slug>\\` with index.html carrying the\n page's title, description and Open Graph tags, so a shared link previews properly, and the\n rendered page in a \\`<noscript>\\` for readers without JavaScript.${\n hasExample(opts, 'export')\n ? `\n- \\`worker/page-preview.ts\\` — the preview image (\\`og:image\\`, 1200 × 630): Browser Run\n renders the page once, and D1 keeps the PNG.`\n : ''\n }\n\n${\n opts.auth\n ? ''\n : `**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\\`. `\n}Each caller (by IP) may publish 20 pages a minute (\\`ratelimits\\` in\n\\`wrangler.jsonc\\`). D1 works on a temporary account.`\n : ''\n }${\n hasExample(opts, 'voice')\n ? `\n\n## Voice\n\n\\`/voice\\` is a voice assistant: press \"Start call\", talk, and it answers aloud. Talk over a\nreply to interrupt it. Typed messages work too.\n\n- \\`worker/voice.ts\\` — \\`Voice\\`, an Agent with the Agents SDK's voice pipeline\n (\\`withVoice\\` from \\`agents/voice\\`): Workers AI speech to text (Flux, which also decides when\n you have finished speaking), a text model (\\`MODEL\\`) and text to speech. One Durable Object\n per conversation stores the transcript, which the model gets as context.\n- \\`src/voice.ts\\` — \\`VoiceClient\\` (\\`agents/voice/client\\`) captures the microphone, streams\n it, and plays the replies; its events become signals the page reads.\n- \\`worker/scripted-voice.ts\\` — \\`vite dev\\` stand-ins, because Workers AI has no local mode:\n the transcriber \"hears\" a fixed question for every three seconds of sound, and the replies\n are text only. \\`VITE_REAL_AI=1 ${runScriptCommand(pm, 'dev')}\\` uses Workers AI instead (after\n \\`npx wrangler login\\`); a deployed Worker always does.\n\nBrowsers allow the microphone only on a secure origin: \\`localhost\\` or HTTPS. Workers AI\nbills per use beyond its free daily allocation, and a temporary account has no Workers AI.`\n : ''\n }\n\nAdd more components with \\`npx cascivo add <component>\\`.\n\n## ${runtime === 'preact' ? 'Preact or React' : 'React or Preact'}\n\n${\n hasExample(opts, 'agent')\n ? `This app runs on React. The Agents SDK's hooks call React 19's \\`use()\\`, which\nPreact's compat layer does not implement, so the assistant page needs React. (The other pages\nwould run on Preact unchanged: the source is typed against React either way.)`\n : `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).`\n}\n`\n}\n\nfunction cfAgentsMd(opts: ScaffoldOptions): string {\n return `${agentsMd(opts)}\n## Server\n\nThe API contract is \\`src/api.ts\\` (\\`defineApi\\` from \\`@cascivo/app/api\\`); its handlers are\n\\`worker/index.ts\\` (\\`createHandler\\`), and the app calls it through \\`createClient\\`. Add an\nendpoint to the contract first, with a parser for its input and output: parse every payload\nthat crosses the network, never cast it. A streaming endpoint's handler is an async\ngenerator. \\`wrangler.jsonc\\` routes only \\`/api/*\\` to the Worker.\n\n## Pages\n\nA page is a file in \\`src/routes/\\` with a default export: \\`c/[id].tsx\\` serves \\`/c/:id\\` and\nreceives \\`{ params }: RouteProps<'/c/:id'>\\`. Never edit \\`src/routes.gen.ts\\`. Link with\n\\`href\\`s (SideNav items, \\`router.Link\\`); navigate from code with \\`router.navigate(path)\\`,\nand build a path with \\`buildPath('/c/:id', { id })\\`, both from \\`@cascivo/app\\`.\n\n## Sharing\n\nTo show the user a running version, run \\`${runExplicitCommand(opts.pm ?? 'npm', 'deploy:preview')}\\`.\nIt needs no Cloudflare account. Give the user both URLs it prints: the live one, and the\nclaim URL. The deployment is public, and it is deleted after 60 minutes unless the user\nopens the claim URL and signs in.\n`\n}\n\nfunction cfShellTsx(opts: ScaffoldOptions): string {\n const shell = shellTsx(opts)\n const start = shell.indexOf(' * Adding a router?')\n const end = shell.indexOf(' */\\nexport function Shell')\n // This app already routes, so the Vite scaffold's \"adding a router\" advice does not apply.\n return (\n shell.slice(0, start) +\n ' * Routing lives in src/router.ts; nav items carry `href`s, and main.tsx registers the\\n' +\n \" * router's Link so they navigate client-side.\\n\" +\n shell.slice(end)\n )\n}\n\n/** Local secrets for `vite dev` (.gitignore'd); deployed, each is a `wrangler secret`. */\nfunction cfDevVars(opts: ScaffoldOptions): string {\n return [\n ...(hasExample(opts, 'webhooks')\n ? [\n '# The secret vite dev signs and checks test webhook deliveries with.',\n 'WEBHOOK_SECRET=dev-only-webhook-secret',\n ]\n : []),\n ...(hasExample(opts, 'checkout')\n ? [\n '# Stripe, in test mode (README): the secret key from the dashboard, and the signing',\n '# secret `stripe listen` prints.',\n 'STRIPE_SECRET_KEY=',\n 'STRIPE_WEBHOOK_SECRET=',\n ]\n : []),\n ...(hasExample(opts, 'newsletter')\n ? [\n '# The key /newsletter/send asks for. Deployed, choose a long random one.',\n 'NEWSLETTER_KEY=dev-only-newsletter-key',\n '# An IAM user allowed ses:SendEmail (README). Without them, vite dev logs each email.',\n 'AWS_ACCESS_KEY_ID=',\n 'AWS_SECRET_ACCESS_KEY=',\n ]\n : []),\n ...(oauthSignIn(opts)\n ? [\n '# Seals the sign-in state between the redirect and the callback. Deployed, a random one:',\n '# openssl rand -base64 32',\n 'AUTH_SECRET=dev-only-auth-secret-0123456789abcdef',\n '# A GitHub OAuth App, a Google OAuth client and a LinkedIn app (README).',\n '# Each provider is offered once both its id and secret are set.',\n 'GITHUB_CLIENT_ID=',\n 'GITHUB_CLIENT_SECRET=',\n 'GOOGLE_CLIENT_ID=',\n 'GOOGLE_CLIENT_SECRET=',\n 'LINKEDIN_CLIENT_ID=',\n 'LINKEDIN_CLIENT_SECRET=',\n ]\n : hasExample(opts, 'social')\n ? [\n \"# Seals connected accounts' tokens. Deployed, a random one: openssl rand -base64 32\",\n 'AUTH_SECRET=dev-only-auth-secret-0123456789abcdef',\n '# A LinkedIn app with \"Share on LinkedIn\" (README). Mastodon needs nothing.',\n 'LINKEDIN_CLIENT_ID=',\n 'LINKEDIN_CLIENT_SECRET=',\n ]\n : []),\n ...(hasExample(opts, 'social')\n ? [\n '# Optional: an ES256 private JWK with a kid, so Bluesky sessions last (README).',\n 'BLUESKY_PRIVATE_JWK=',\n '# Optional: a Buffer app client (publish.buffer.com/settings/api), to post to its channels.',\n 'BUFFER_CLIENT_ID=',\n 'BUFFER_CLIENT_SECRET=',\n '# Optional: a Meta app with the Threads use case (README), to post to Threads.',\n 'THREADS_APP_ID=',\n 'THREADS_APP_SECRET=',\n ]\n : []),\n ]\n .map((line) => `${line}\\n`)\n .join('')\n}\n\n/**\n * The secrets the app reads, with no values: committed, unlike .dev.vars. The \"Deploy to\n * Cloudflare\" button asks for each one it lists; `cp .dev.vars.example .dev.vars` starts a\n * fresh clone.\n */\nfunction cfDevVarsExample(opts: ScaffoldOptions): string {\n return cfDevVars(opts)\n .split('\\n')\n .map((line) => (line.startsWith('#') ? line : line.replace(/=.*$/, '=')))\n .join('\\n')\n}\n\n/**\n * What each setting is for, in package.json's \\`cloudflare.bindings\\`: the \"Deploy to Cloudflare\"\n * button shows it beside the field it asks the deployer to fill in.\n */\nfunction cfBindingDescriptions(opts: ScaffoldOptions): Record<string, { description: string }> {\n const describe = (entries: [string, string][]) =>\n Object.fromEntries(entries.map(([name, description]) => [name, { description }]))\n return {\n ...(hasExample(opts, 'webhooks')\n ? describe([\n [\n 'WEBHOOK_SECRET',\n 'The secret of the GitHub webhook that posts to `/api/webhooks/github`.',\n ],\n ])\n : {}),\n ...(hasExample(opts, 'checkout')\n ? describe([\n [\n 'STRIPE_SECRET_KEY',\n 'Your Stripe secret key, from the [API keys page](https://dashboard.stripe.com/test/apikeys). A test key (`sk_test_…`) takes test cards only.',\n ],\n [\n 'STRIPE_WEBHOOK_SECRET',\n '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`.',\n ],\n [\n 'RECEIPT_FROM',\n 'The From address of receipts, on a domain onboarded to Cloudflare Email Service. Leave it empty to send none.',\n ],\n ])\n : {}),\n ...(hasExample(opts, 'newsletter')\n ? describe([\n [\n 'NEWSLETTER_KEY',\n 'The key `/newsletter/send` asks for. Make a long random one: `openssl rand -hex 32`.',\n ],\n ['AWS_ACCESS_KEY_ID', 'An IAM user allowed `ses:SendEmail` and nothing else (README).'],\n ['AWS_SECRET_ACCESS_KEY', \"That IAM user's secret access key.\"],\n ['AWS_REGION', 'The SES region your sending domain is verified in, e.g. `eu-west-1`.'],\n ['NEWSLETTER_FROM', 'The From address of issues, on your SES-verified domain.'],\n [\n 'SNS_TOPIC_ARN',\n 'The SNS topic SES reports bounces and complaints to, subscribed to `https://<this app>/api/sns/ses`.',\n ],\n ])\n : {}),\n ...(oauthSignIn(opts)\n ? describe([\n [\n 'AUTH_SECRET',\n '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`.',\n ],\n [\n 'GITHUB_CLIENT_ID',\n '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.',\n ],\n ['GITHUB_CLIENT_SECRET', \"That OAuth App's client secret.\"],\n [\n 'GOOGLE_CLIENT_ID',\n '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.',\n ],\n ['GOOGLE_CLIENT_SECRET', \"That OAuth client's secret.\"],\n [\n 'LINKEDIN_CLIENT_ID',\n '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.',\n ],\n ['LINKEDIN_CLIENT_SECRET', \"That LinkedIn app's primary client secret.\"],\n ])\n : hasExample(opts, 'social')\n ? describe([\n [\n 'AUTH_SECRET',\n 'Seals the tokens of the accounts people connect. Make a random one: `openssl rand -base64 32`.',\n ],\n [\n 'LINKEDIN_CLIENT_ID',\n '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.',\n ],\n ['LINKEDIN_CLIENT_SECRET', \"That LinkedIn app's primary client secret.\"],\n ])\n : {}),\n ...(hasExample(opts, 'social')\n ? describe([\n [\n 'BLUESKY_PRIVATE_JWK',\n '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.',\n ],\n [\n 'BUFFER_CLIENT_ID',\n '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.',\n ],\n ['BUFFER_CLIENT_SECRET', \"That Buffer app client's secret (none for a public client).\"],\n [\n 'THREADS_APP_ID',\n '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.',\n ],\n ['THREADS_APP_SECRET', \"That Threads app's secret.\"],\n ])\n : {}),\n }\n}\n\n/**\n * The recipes (`packages/cli/recipes/<name>`) a cloudflare scaffold may add after its base, in\n * the order their pages appear in the side nav.\n */\nconst CLOUDFLARE_RECIPES = [\n 'agent',\n 'board',\n 'notes',\n 'import',\n 'files',\n 'export',\n 'usage',\n 'crud',\n 'live',\n 'voice',\n 'publish',\n 'publish-preview',\n 'webhooks',\n 'digest',\n 'search',\n 'checkout',\n 'billing',\n 'newsletter',\n 'social',\n 'accounts',\n 'auth-email',\n] as const\n\n/** Each example is its own recipe; the rest are what two choices bring together. */\nfunction includesRecipe(\n recipe: (typeof CLOUDFLARE_RECIPES)[number],\n opts: ScaffoldOptions,\n): boolean {\n switch (recipe) {\n case 'publish-preview':\n return hasExample(opts, 'publish') && hasExample(opts, 'export')\n case 'billing':\n return usesBilling(opts)\n case 'accounts':\n return hasAccounts(opts)\n case 'auth-email':\n return emailSignIn(opts)\n default:\n return hasExample(opts, recipe)\n }\n}\n\nfunction cloudflareRecipes(opts: ScaffoldOptions): string[] {\n return ['cloudflare', ...CLOUDFLARE_RECIPES.filter((recipe) => includesRecipe(recipe, opts))]\n}\n\nfunction buildCloudflareScaffold(opts: ScaffoldOptions, sections: Section[]): ScaffoldFile[] {\n const runtime = runtimeOf(opts)\n const recipes = cloudflareRecipes(opts)\n const recipeOutput = recipes.flatMap((recipe) => recipeFiles(recipe, recipeVars(opts)))\n const routeFiles = [\n ...sections.map((s, i) => ({\n file: cfSectionFile(s, i),\n contents: s.block\n ? blockPageTsx(s, 'export default function')\n : i === 0\n ? cfFirstRouteTsx(s)\n : cfRouteTsx(s, i),\n })),\n ...(hasAccounts(opts) ? [{ file: 'account.tsx', contents: cfAccountRouteTsx(opts) }] : []),\n ]\n const routes = [\n ...routeFiles.map((r) => r.file),\n ...recipeOutput\n .filter((f) => f.path.startsWith('src/routes/'))\n .map((f) => f.path.slice('src/routes/'.length)),\n ]\n return [\n { path: 'package.json', contents: cfPackageJson(opts) },\n { path: 'tsconfig.json', contents: cfTsconfig(opts) },\n ...(needsWorkerTypes(opts)\n ? [{ path: 'tsconfig.worker.json', contents: cfWorkerTsconfig() }]\n : []),\n { path: 'vite.config.ts', contents: cfViteConfig(runtime, opts) },\n { path: 'wrangler.jsonc', contents: wranglerJsonc(opts) },\n { path: 'index.html', contents: indexHtml(opts) },\n { path: 'eslint.config.js', contents: eslintConfig() },\n { path: '.prettierrc', contents: prettierrc() },\n { path: '.prettierignore', contents: cfPrettierIgnore() },\n { path: '.gitignore', contents: cfGitignore() },\n { path: 'README.md', contents: cfReadme(opts) },\n { path: 'AGENTS.md', contents: cfAgentsMd(opts) },\n { path: 'worker/index.ts', contents: cfWorkerTs(opts) },\n { path: 'src/api.ts', contents: cfApiTs(opts) },\n { path: 'src/vite-env.d.ts', contents: viteEnv() },\n { path: 'src/App.tsx', contents: cfAppTsx(sections, recipes, opts) },\n { path: 'src/Shell.tsx', contents: cfShellTsx(opts) },\n ...(hasExample(opts, 'webhooks') ||\n hasExample(opts, 'checkout') ||\n hasExample(opts, 'newsletter') ||\n hasExample(opts, 'social') ||\n oauthSignIn(opts)\n ? [\n { path: '.dev.vars', contents: cfDevVars(opts) },\n { path: '.dev.vars.example', contents: cfDevVarsExample(opts) },\n ]\n : []),\n ...recipeOutput,\n ...blockFiles(sections, opts),\n ...routeFiles.map(({ file, contents }) => ({ path: `src/routes/${file}`, contents })),\n // Written now so \\`tsc\\` passes before the first \\`vite\\` run; the plugin keeps it current.\n { path: 'src/routes.gen.ts', contents: generateRoutes(routes, './routes') },\n ]\n}\n\n/**\n * The app's blueprint, as `cascivo.app.json`: what it was generated from, in the vocabulary of\n * the flags, stamped with this CLI's version. `cascivo app` changes the app by changing this\n * file and merging what it generates.\n */\nfunction blueprintJson(opts: ScaffoldOptions, sections: Section[]): string {\n return formatJson({\n name: opts.name,\n framework: opts.framework ?? 'react-vite',\n theme: opts.theme,\n pages: sections.map((s) => ({ title: s.label, ...(s.block ? { block: s.block } : {}) })),\n ...(opts.runtime ? { runtime: opts.runtime } : {}),\n ...(opts.examples && opts.examples.length > 0 ? { examples: opts.examples } : {}),\n ...(opts.auth ? { auth: opts.auth } : {}),\n cascivo: CLI_VERSION,\n })\n}\n\nexport function buildScaffold(opts: ScaffoldOptions): ScaffoldFile[] {\n const sections = resolveSections(opts.sections, opts.blocks)\n const app = [\n ...buildFrameworkScaffold(opts, sections),\n { path: 'cascivo.app.json', contents: blueprintJson(opts, sections) },\n ...agentFiles(),\n ]\n if (!opts.workspace) return app\n return buildWorkspace({\n packageName: packageName(opts.name),\n app,\n firstLabel: sections[0]!.label,\n testable: (opts.framework ?? 'react-vite') === 'react-vite',\n reactVersion: V['@cascivo/react']!,\n })\n}\n\n/**\n * Wiring for a coding agent opened in the app. Claude Code reads CLAUDE.md, which imports the\n * AGENTS.md every other agent reads, so the instructions live in one file; `.mcp.json` is what\n * `cascivo mcp init` writes, so the agent can reach the registry without that extra step.\n */\nfunction agentFiles(): ScaffoldFile[] {\n const mcp = mergeMcpConfig(undefined, 'claude')\n if (mcp.kind !== 'added') throw new Error('cascivo: could not build .mcp.json')\n return [\n { path: 'CLAUDE.md', contents: '@AGENTS.md\\n' },\n { path: '.mcp.json', contents: formatJson(mcp.config) },\n ]\n}\n\nfunction buildFrameworkScaffold(opts: ScaffoldOptions, sections: Section[]): ScaffoldFile[] {\n if (opts.framework === 'astro') return buildAstroScaffold(opts, sections)\n if (opts.framework === 'cloudflare') {\n // The digest emails the report page the export example adds, so it brings that along.\n const examples =\n opts.examples?.includes('digest') && !opts.examples.includes('export')\n ? [...opts.examples, 'export' as const]\n : opts.examples\n // Social posts belong to a user: without --auth, it brings sign-in with providers.\n const auth = opts.auth ?? (examples?.includes('social') ? 'oauth' : undefined)\n return buildCloudflareScaffold(\n { ...opts, ...(examples ? { examples } : {}), ...(auth ? { auth } : {}) },\n sections,\n )\n }\n return [\n { path: 'package.json', contents: packageJson(opts) },\n { path: 'tsconfig.json', contents: tsconfig() },\n { path: 'vite.config.ts', contents: viteConfig() },\n { path: 'index.html', contents: indexHtml(opts) },\n // No `cascivo.config.ts`. It configures where `cascivo add` copies source, which a\n // prebuilt-path app never does — and its presence was how `doctor` decided a project\n // was copy-paste, so the scaffolder's own output failed `doctor --ci` and was told to\n // install the two packages the docs forbid. `cascivo add` writes the config itself the\n // first time it is used.\n { path: 'eslint.config.js', contents: eslintConfig() },\n { path: '.prettierrc', contents: prettierrc() },\n { path: '.prettierignore', contents: prettierIgnore() },\n { path: '.gitignore', contents: gitignore() },\n { path: 'README.md', contents: readme(opts) },\n { path: 'AGENTS.md', contents: agentsMd(opts) },\n { path: 'src/main.tsx', contents: mainTsx() },\n { path: 'src/vite-env.d.ts', contents: viteEnv() },\n { path: 'src/App.tsx', contents: appTsx(sections) },\n { path: 'src/Shell.tsx', contents: shellTsx(opts) },\n ...sections.map((s) => ({\n path: `src/sections/${s.component}.tsx`,\n contents: sectionTsx(s),\n })),\n ...blockFiles(sections, opts),\n ]\n}\n\nfunction buildAstroScaffold(opts: ScaffoldOptions, sections: Section[]): ScaffoldFile[] {\n return [\n { path: 'package.json', contents: astroPackageJson(opts) },\n { path: 'tsconfig.json', contents: astroTsconfig() },\n { path: 'astro.config.mjs', contents: astroConfig(opts) },\n { path: 'eslint.config.js', contents: eslintConfig() },\n { path: '.prettierrc', contents: prettierrc() },\n { path: '.prettierignore', contents: prettierIgnore() },\n { path: '.gitignore', contents: astroGitignore() },\n { path: 'README.md', contents: astroReadme(opts, sections) },\n { path: 'AGENTS.md', contents: agentsMd(opts) },\n { path: 'src/styles/layers.css', contents: astroLayersCss() },\n { path: 'src/layouts/Layout.astro', contents: astroLayout(opts) },\n { path: 'src/components/Shell.tsx', contents: astroShellTsx(opts, sections) },\n ...sections.map((s, i) => ({\n path: `src/pages/${sectionPageFile(s, i)}`,\n contents: astroPage(s, i),\n })),\n ...sections.map((s) => ({\n path: `src/components/${s.component}.tsx`,\n contents: astroSectionTsx(s),\n })),\n ]\n}\n\nconst DEFAULT_SECTIONS = ['Dashboard', 'Reports', 'Settings']\n\n/**\n * Combinations that cannot work, as the message to print, or `null`. Shared by the flags and\n * `--from <blueprint>`, so a blueprint is held to the same rules as a command line.\n */\nexport function optionsError(opts: Omit<ScaffoldOptions, 'pm'>): string | null {\n const examples = opts.examples ?? []\n if (examples.length > 0 && opts.framework !== 'cloudflare') {\n return '--example needs --framework cloudflare (it adds a Worker-backed page).'\n }\n if (examples.includes('social') && opts.auth === 'access') {\n return (\n '--example social needs accounts (posts belong to a user): use --auth email, oauth or ' +\n 'email,oauth, or leave --auth out to get oauth.'\n )\n }\n if (opts.auth && opts.framework !== 'cloudflare') {\n return '--auth needs --framework cloudflare (it guards the Worker).'\n }\n if (opts.workspace && opts.framework === 'astro') {\n return '--workspace needs --framework react-vite or cloudflare.'\n }\n if (examples.includes('agent') && opts.runtime === 'preact') {\n return (\n \"--example agent needs --runtime react: the Agents SDK's hooks call React 19's use(), \" +\n 'which Preact does not implement.'\n )\n }\n return null\n}\n\n/** Read and parse `--from <file>`, printing the problem and returning null when it is not one. */\nasync function readBlueprint(\n file: string,\n cwd: string,\n): Promise<Omit<ScaffoldOptions, 'pm'> | null> {\n const { readFileSync } = await import('node:fs')\n const { parseBlueprint, blueprintOptions } = await import('../scaffold/blueprint.js')\n try {\n const raw: unknown = JSON.parse(readFileSync(resolve(cwd, file), 'utf8'))\n return blueprintOptions(parseBlueprint(raw, file))\n } catch (e) {\n console.error(e instanceof Error ? e.message : String(e))\n return null\n }\n}\n\nexport async function create(args: string[], cwd: string = process.cwd()): Promise<void> {\n const yes = args.includes('--yes') || args.includes('-y')\n // Skip flag values (e.g. `bun` in `--pm bun`) so the project name is the first\n // real positional, not a flag's argument.\n const nameArg = positionalArgs(args, [\n 'pm',\n 'package-manager',\n 'theme',\n 'sections',\n 'template',\n 'framework',\n 'runtime',\n 'example',\n 'auth',\n 'from',\n ])[0]\n const themeArg = flagValue(args, 'theme')\n const sectionsArg = flagValue(args, 'sections')\n\n const frameworkArg = (flagValue(args, 'framework') ?? '').toLowerCase()\n if (frameworkArg && !(FRAMEWORKS as readonly string[]).includes(frameworkArg)) {\n console.error(`Unknown framework \"${frameworkArg}\". Expected one of: ${FRAMEWORKS.join(', ')}.`)\n process.exitCode = 1\n return\n }\n\n const runtimeArg = (flagValue(args, 'runtime') ?? '').toLowerCase()\n if (runtimeArg && !isRuntime(runtimeArg)) {\n console.error(`Unknown runtime \"${runtimeArg}\". Expected one of: ${RUNTIMES.join(', ')}.`)\n process.exitCode = 1\n return\n }\n\n const exampleArgs = (flagValue(args, 'example') ?? '')\n .split(',')\n .map((e) => e.trim().toLowerCase())\n .filter(Boolean)\n const badExample = exampleArgs.find((e) => !isExample(e))\n if (badExample) {\n console.error(`Unknown example \"${badExample}\". Expected one of: ${EXAMPLES.join(', ')}.`)\n process.exitCode = 1\n return\n }\n\n const authArg = parseAuth(flagValue(args, 'auth'))\n if (authArg === 'invalid') {\n console.error(\n `Unknown auth \"${flagValue(args, 'auth') ?? ''}\". Expected: access, email, oauth or email,oauth.`,\n )\n process.exitCode = 1\n return\n }\n\n const pmFlag = resolvePackageManagerFlag(args)\n if ('error' in pmFlag) {\n console.error(pmFlag.error)\n process.exitCode = 1\n return\n }\n // The new project has no lock file of its own, but the directory it lands IN usually does\n // — scaffolding into an existing workspace is the common case. `preferLockfileOverUserAgent`\n // makes that walk-up outrank `npm_config_user_agent`, which `npx` always reports as npm no\n // matter what the surrounding repo uses (2026-08-14 §11). With no lock file anywhere up the\n // tree, detection still falls back to the launcher.\n const pm = detectPackageManager(cwd, {\n preferLockfileOverUserAgent: true,\n ...(pmFlag.pm ? { override: pmFlag.pm } : {}),\n })\n\n const interactive = !yes && stdin.isTTY\n const rl = interactive ? createInterface({ input: stdin, output: stdout }) : null\n\n /** The options from flags and, on a terminal, prompts for the ones not given. */\n const prompted = async (): Promise<Omit<ScaffoldOptions, 'pm'>> => {\n let name = nameArg\n if (!name && rl) {\n name = (await rl.question('Project name? [my-cascivo-app]: ')).trim()\n }\n name = name || 'my-cascivo-app'\n\n let theme = (themeArg ?? '').toLowerCase()\n if (!(THEMES as readonly string[]).includes(theme) && rl) {\n theme = (await rl.question(`Theme? (${THEMES.join('/')}) [light]: `)).trim().toLowerCase()\n }\n const resolvedTheme: ThemeName = (THEMES as readonly string[]).includes(theme)\n ? (theme as ThemeName)\n : 'light'\n\n let sectionsInput = sectionsArg\n if (!sectionsInput && rl) {\n sectionsInput = (\n await rl.question(`Nav sections? (comma-separated) [${DEFAULT_SECTIONS.join(', ')}]: `)\n ).trim()\n }\n const sections = (sectionsInput ?? '')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n\n let framework = frameworkArg\n if (!framework && rl) {\n framework = (await rl.question(`Framework? (${FRAMEWORKS.join('/')}) [react-vite]: `))\n .trim()\n .toLowerCase()\n }\n const resolvedFramework: Framework = (FRAMEWORKS as readonly string[]).includes(framework)\n ? (framework as Framework)\n : 'react-vite'\n\n return {\n name,\n framework: resolvedFramework,\n theme: resolvedTheme,\n sections: sections.length > 0 ? sections : DEFAULT_SECTIONS,\n ...(isRuntime(runtimeArg) ? { runtime: runtimeArg } : {}),\n ...(exampleArgs.length > 0 ? { examples: exampleArgs.filter(isExample) } : {}),\n ...(authArg ? { auth: authArg } : {}),\n }\n }\n\n try {\n const fromArg = flagValue(args, 'from')\n const chosen = fromArg ? await readBlueprint(fromArg, cwd) : await prompted()\n if (!chosen) {\n process.exitCode = 1\n return\n }\n const workspace = args.includes('--workspace')\n const opts: ScaffoldOptions = {\n ...chosen,\n ...(fromArg && nameArg ? { name: nameArg } : {}),\n // A workspace is a pnpm workspace: its scripts and CI assume pnpm.\n pm: workspace ? 'pnpm' : pm,\n ...(workspace ? { workspace } : {}),\n }\n const problem = optionsError(opts)\n if (problem) {\n console.error(problem)\n process.exitCode = 1\n return\n }\n const name = opts.name\n const resolvedFramework = opts.framework ?? 'react-vite'\n const resolvedTheme = opts.theme\n\n const targetDir = join(cwd, name)\n if (existsSync(targetDir) && readdirSync(targetDir).length > 0) {\n console.error(`Target directory \"${name}\" already exists and is not empty.`)\n process.exitCode = 1\n return\n }\n\n const files = buildScaffold(opts)\n for (const file of files) {\n await writeFileSafe(join(targetDir, file.path), file.contents)\n }\n\n console.log(\n `\\nCreated ${name} (${resolvedFramework}) with the ${resolvedTheme} theme ` +\n `(${files.length} files).`,\n )\n\n const templateSpec = flagValue(args, 'template')\n if (templateSpec) {\n const { add } = await import('./add.js')\n const { loadConfig } = await import('../utils/config.js')\n console.log(`\\nInstalling template \"${templateSpec}\"…`)\n await add([templateSpec], await loadConfig(), { cwd: targetDir, pm })\n }\n\n console.log('\\nNext steps:')\n console.log(` cd ${name}`)\n console.log(` ${installAllCommand(pm)}`)\n console.log(` ${runScriptCommand(pm, 'dev')}`)\n // Two things the output used to leave the adopter to discover (2026-08-14 §11, §1).\n console.log('\\nGood to know:')\n console.log(' No cascivo.config.ts is written — this app uses the prebuilt @cascivo/react')\n console.log(' packages and never copies source. `cascivo add <component>` writes the')\n console.log(' config itself the first time you vendor a component.')\n if (resolvedFramework === 'cloudflare') {\n console.log('\\n worker/index.ts is the API (wrangler.jsonc routes /api/* to it); `dev`')\n console.log(' runs it in workerd. Deploy with `npx wrangler login` once, then the')\n console.log(` deploy script: ${runExplicitCommand(pm, 'deploy')}`)\n console.log('\\n No account yet? Share a 60-minute preview, claimable into a free account:')\n console.log(` ${runExplicitCommand(pm, 'deploy:preview')}`)\n } else if (resolvedFramework === 'astro') {\n console.log('\\n Pages are real Astro routes — no client router to add. Only src/')\n console.log(' components/Shell.tsx hydrates (client:load, for the mobile nav drawer);')\n console.log(' page content is server-rendered and ships no JS. See')\n console.log(' https://cascivo.com/docs/using-with-astro.md')\n } else {\n console.log('\\n Adding a router? Keep src/Shell.tsx, delete src/App.tsx + src/sections/,')\n console.log(' and register your Link once with setLinkComponent — see')\n console.log(' https://cascivo.com/docs/using-with-a-router.md')\n }\n } finally {\n rl?.close()\n }\n}\n"],"mappings":"igBAQA,MAAaS,EAA2C,CACtD,iBAAkB,SAClB,kBAAmB,QACnB,iBAAkB,SAClB,kBAAmB,SACnB,iBAAkB,QAClB,yBAA0B,QAC1B,eAAgB,SAChB,kBAAmB,SACnB,mBAAoB,SACpB,iBAAkB,OACpB,EAGaC,EAAe,UAMfC,EAAc,QC5B3B,SAASC,EAAc,EAAE,CAAC,IAAI,EAAE,EAAE,WAAW,GAAG,EAAE,EAAE,IAAI,IAAI,OAAO,EAAE,OAAO,EAAE,EAAE,QAAQ,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC,SAASC,EAAY,EAAE,CAAC,OAAO,EAAE,QAAQ,sBAAsB,MAAM,CAAC,CAAC,SAASC,EAAY,EAAE,CAAC,IAAI,EAA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BACA,wEACF,CACF,CAAC,EACD,CAAC,EACL,GAAI7F,EAAWnD,EAAM,UAAU,EAC3BgJ,EAAS,CACP,CACE,oBACA,8IACF,EACA,CACE,wBACA,mQACF,EACA,CACE,eACA,+GACF,CACF,CAAC,EACD,CAAC,EACL,GAAI7F,EAAWnD,EAAM,YAAY,EAC7BgJ,EAAS,CACP,CACE,iBACA,sFACF,EACA,CAAC,oBAAqB,gEAAgE,EACtF,CAAC,wBAAyB,oCAAoC,EAC9D,CAAC,aAAc,sEAAsE,EACrF,CAAC,kBAAmB,0DAA0D,EAC9E,CACE,gBACA,sGACF,CACF,CAAC,EACD,CAAC,EACL,GAAI/C,EAAYjG,CAAI,EAChBgJ,EAAS,CACP,CACE,cACA,4IACF,EACA,CACE,mBACA,qMACF,EACA,CAAC,uBAAwB,iCAAiC,EAC1D,CACE,mBACA,gLACF,EACA,CAAC,uBAAwB,6BAA6B,EACtD,CACE,qBACA,wNACF,EACA,CAAC,yBAA0B,4CAA4C,CACzE,CAAC,EACD7F,EAAWnD,EAAM,QAAQ,EACvBgJ,EAAS,CACP,CACE,cACA,gGACF,EACA,CACE,qBACA,wLACF,EACA,CAAC,yBAA0B,4CAA4C,CACzE,CAAC,EACD,CAAC,EACP,GAAI7F,EAAWnD,EAAM,QAAQ,EACzBgJ,EAAS,CACP,CACE,sBACA,2JACF,EACA,CACE,mBACA,wLACF,EACA,CAAC,uBAAwB,6DAA6D,EACtF,CACE,iBACA,mMACF,EACA,CAAC,qBAAsB,4BAA4B,CACrD,CAAC,EACD,CAAC,CACP,CACF,CAMA,MAAME,GAAqB,CACzB,QACA,QACA,QACA,SACA,QACA,SACA,QACA,OACA,OACA,QACA,UACA,kBACA,WACA,SACA,SACA,WACA,UACA,aACA,SACA,WACA,YACF,EAGA,SAASC,GACP,EACA,EACS,CACT,OAAQ7M,EAAR,CACE,IAAK,kBACH,OAAO6G,EAAWnD,EAAM,SAAS,GAAKmD,EAAWnD,EAAM,QAAQ,EACjE,IAAK,U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KG,EAAmBH,EAAI,gBAAgB,GAAG,GAClD0N,IAAsB,SAC/B,QAAQ,IAAI;mEAAsE,EAClF,QAAQ,IAAI,2EAA2E,EACvF,QAAQ,IAAI,wDAAwD,EACpE,QAAQ,IAAI,gDAAgD,IAE5D,QAAQ,IAAI;2EAA8E,EAC1F,QAAQ,IAAI,2DAA2D,EACvE,QAAQ,IAAI,mDAAmD,EAEnE,QAAU,CACRT,GAAI,MAAM,CACZ,CACF"}
|
|
1
|
+
{"version":3,"file":"create-BMqDBB8r.mjs","names":["t","e","detectPackageManager","THEMES","writeFileSafe","positionalArgs","resolvePackageManagerFlag","flagValue","mergeMcpConfig","CASCIVO_VERSIONS","SIGNALS_PEER","CLI_VERSION","normalizePath","escapeRegex","compilePath","compareSpecificity","f","fileToRoutePath","generateRoutes","i","a","e","n","t","specifier","r","o","s","HERE","dirname","fileURLToPath","recipesDir","candidate","join","existsSync","parseRecipe","raw","source","name","files","paths","file","isSafeRelativePath","nav","items","item","label","href","dependencies","d","cache","loadRecipe","cached","recipe","readFileSync","PLACEHOLDER","recipeFiles","dir","path","vars","key","blockNames","readdirSync","json","formatJson","parsePackageJson","contents","record","value","entry","ROOT_FILES","buildWorkspace","scope","input","ui","pkg","scripts","devDependencies","mcp","V","installAllCommand","pm","runScriptCommand","script","runExplicitCommand","FRAMEWORKS","RUNTIMES","EXAMPLES","isExample","isRuntime","slug","pascalCase","safe","p","brandName","words","w","kept","word","packageName","resolveSections","seenKeys","seenComponents","sections","index","labels","trimmed","component","block","blocks","packageJson","opts","blockDependencies","tsconfig","viteConfig","indexHtml","mainTsx","viteEnv","appTsx","sectionImports","oneLine","sectionType","navItems","renderedSections","shellTsx","appShellOpenTag","blockPageTsx","section","local","declaration","packages","version","blockFiles","recipeVars","usageDataset","sectionTsx","eslintConfig","header","line","prettierrc","prettierIgnore","gitignore","staticShareSection","COMPATIBILITY_DATE","readme","agentsMd","sectionPath","sectionPageFile","astroPackageJson","astroConfig","ASTRO_LAYER_ORDER","astroTsconfig","astroLayersCss","astroLayout","astroShellTsx","astroSectionTsx","astroPage","astroGitignore","astroReadme","routes","cfPackageJson","agent","hasExample","workerTypes","needsWorkerTypes","preact","runtimeOf","bindings","cfBindingDescriptions","cfTsconfig","cfg","cfWorkerTsconfig","cfViteConfig","ai","usesWorkersAi","plugin","runtime","call","clause","jsoncArray","indent","wranglerJsonc","publish","rooms","usesRooms","usesAgents","objects","comments","usesLimiter","emailSignIn","c","wranglerVars","SOCIAL_CRON","usesD1","hasAccounts","wranglerQueues","digest","social","checkout","newsletter","emailAuth","names","entries","comment","queues","newsletterQueue","q","usesBilling","oauthSignIn","parseAuth","parts","example","cfApiTs","imports","usage","crud","live","webhooks","search","billing","cfWorkerTs","exports","voice","d1","limiter","access","oauth","accounts","guards","custom","isAsync","serverRooms","signedPaths","readerPaths","openPaths","prefix","cfSectionPath","cfSectionFile","cfAppTsx","recipes","cfFirstRouteTsx","cfRouteTsx","cfAccountRouteTsx","email","lead","cfPrettierIgnore","cfGitignore","cfReadme","cfAgentsMd","cfShellTsx","shell","start","end","cfDevVars","cfDevVarsExample","describe","description","CLOUDFLARE_RECIPES","includesRecipe","cloudflareRecipes","buildCloudflareScaffold","recipeOutput","routeFiles","blueprintJson","buildScaffold","app","buildFrameworkScaffold","agentFiles","buildAstroScaffold","examples","auth","DEFAULT_SECTIONS","optionsError","readBlueprint","blueprintOptions","parseBlueprint","resolve","cwd","create","yes","args","nameArg","themeArg","sectionsArg","frameworkArg","runtimeArg","exampleArgs","badExample","authArg","pmFlag","rl","stdin","createInterface","stdout","prompted","theme","resolvedTheme","sectionsInput","framework","resolvedFramework","fromArg","chosen","workspace","problem","targetDir","templateSpec","add","loadConfig"],"sources":["../src/generated/versions.ts","../../app/dist/path-DJjeYL9s.js","../../app/dist/vite.js","../src/scaffold/recipes.ts","../src/scaffold/workspace.ts","../src/commands/create.ts"],"sourcesContent":["// GENERATED by scripts/registry/cli-versions.ts — do not edit by hand.\n/**\n * Exact published versions, baked in at build time.\n *\n * Scaffolded apps pin these rather than `\"latest\"`: the cascivo packages version\n * independently on 0.x, so a floating specifier can resolve a mutually incompatible set,\n * and GETTING-STARTED.md tells adopters to pin exactly. Regenerate with `pnpm regen`.\n */\nexport const CASCIVO_VERSIONS: Record<string, string> = {\n '@cascivo/react': '1.12.1',\n '@cascivo/themes': '1.0.3',\n '@cascivo/astro': '1.12.1',\n '@cascivo/charts': '1.12.1',\n '@cascivo/icons': '1.1.1',\n '@cascivo/eslint-config': '0.4.2',\n '@cascivo/app': '1.12.1',\n '@cascivo/render': '1.12.1',\n '@cascivo/storage': '1.12.1',\n '@cascivo/email': '0.6.1',\n}\n\n/** `@cascivo/core`'s declared `@preact/signals-react` peer range. */\nexport const SIGNALS_PEER = '>=3.0.0'\n\n/**\n * This CLI's own version, stamped into every scaffold's cascivo.app.json. `cascivo app`\n * regenerates an app's original files with exactly this version as its merge base.\n */\nexport const CLI_VERSION = '1.9.0'\n","function normalizePath(e){let t=e.startsWith(`/`)?e:`/${e}`;return t.length>1?t.replace(/\\/+$/,``)||`/`:t}function escapeRegex(e){return e.replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}function compilePath(e){let t=normalizePath(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+=`/${escapeRegex(a)}`}),{pattern:e,keys:n,regex:RegExp(`^${i||`/`}/?$`),score:r}}function matchPath(e,t){let n=e.regex.exec(normalizePath(t));if(!n)return null;let r={};try{e.keys.forEach((e,t)=>{let i=n[t+1]??``;r[e]=e===`*`?i.split(`/`).map(decodeURIComponent).join(`/`):decodeURIComponent(i)})}catch{return null}return r}function compareSpecificity(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}function buildPath(e,t){let n=t;return`/${normalizePath(e).split(`/`).filter(Boolean).map(t=>{if(t===`*`)return(n[`*`]??``).split(`/`).map(encodeURIComponent).join(`/`);if(t.startsWith(`:`)){let r=n[t.slice(1)];if(r===void 0)throw Error(`Missing param \"${t.slice(1)}\" for \"${e}\"`);return encodeURIComponent(r)}return t}).filter(e=>e!==``).join(`/`)}`}export{normalizePath as a,matchPath as i,compareSpecificity as n,compilePath as r,buildPath as t};","import{n as e,r as t}from\"./path-DJjeYL9s.js\";import{existsSync as n,readFileSync as r,readdirSync as i,statSync as a,writeFileSync as o}from\"node:fs\";import{dirname as s,join as c,relative as l,resolve as u,sep as d}from\"node:path\";var f=/\\.(tsx|jsx)$/;function fileToRoutePath(e){if(!f.test(e)||/\\.(test|spec)\\.[jt]sx$/.test(e))return;let t=e.replace(f,``).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 scanRoutes(e){if(!n(e))return[];let t=[],walk=n=>{for(let r of i(n).sort()){let i=c(n,r);a(i).isDirectory()?walk(i):t.push(l(e,i).split(d).join(`/`))}};return walk(e),t}function generateRoutes(n,r){let i=[],a=/* @__PURE__ */ new Map;for(let e of n){let t=fileToRoutePath(e);if(t===void 0)continue;let n=a.get(t);if(n)throw Error(`routes/${n} and routes/${e} both define ${t??`the 404 route`}`);a.set(t,e),i.push({file:e,path:t})}let specifier=e=>`${r}/${e.replace(f,``)}`,o=i.filter(e=>e.path!==null).map(e=>({...e,compiled:t(e.path)})).sort((t,n)=>e(t.compiled,n.compiled)||t.path.localeCompare(n.path)),s=i.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[] = [`,...o.map(e=>` lazyRoute('${e.path}', () => import('${specifier(e.file)}')),`),`]`,``,s?`export const notFound: Route | undefined = lazyRoute('*', () => import('${specifier(s.file)}'))`:`export const notFound: Route | undefined = undefined`,``,\"/** Every route pattern. Fill one with `buildPath` for a typed link. */\",`export type AppPath = ${o.length>0?o.map(e=>`'${e.path}'`).join(` | `):`never`}`,``].join(`\n`)}function cascivoRoutes(e={}){let t=process.cwd(),dir=()=>u(t,e.dir??`src/routes`),out=()=>u(t,e.out??`src/routes.gen.ts`);function write(){let e=l(s(out()),dir()).split(d).join(`/`);e.startsWith(`.`)||(e=`./${e}`);let t=generateRoutes(scanRoutes(dir()),e);(n(out())?r(out(),`utf8`):null)!==t&&o(out(),t)}return{name:`cascivo:routes`,enforce:`pre`,configResolved(e){t=e.root},buildStart(){write()},configureServer(e){e.watcher.add(dir());let onChange=e=>{u(e).startsWith(dir()+d)&&write()};e.watcher.on(`add`,onChange),e.watcher.on(`unlink`,onChange)}}}export{cascivoRoutes,fileToRoutePath,generateRoutes,scanRoutes};","import { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { isSafeRelativePath } from '@cascivo/registry'\n\n/**\n * A recipe is one feature of a scaffold as data: a directory under `packages/cli/recipes/`\n * holding a `recipe.json` and the files it adds, at the paths they take in the app. The files\n * are the app's real source rather than template literals, so composing a scaffold is choosing\n * recipes, not threading conditionals through one generator.\n */\nexport interface Recipe {\n name: string\n /** App-relative paths, each a file in the recipe's directory. */\n files: string[]\n /** Side-nav entries for the pages the recipe adds, in the order they appear. */\n nav: RecipeNavItem[]\n /** `@cascivo/*` packages the files import, added to the app at the CLI's pinned version. */\n dependencies: string[]\n}\n\nexport interface RecipeNavItem {\n label: string\n /** An app path, starting with `/`. */\n href: string\n}\n\n/** The values a recipe file may reference as `{{key}}`. Unknown keys are left as written. */\nexport interface RecipeVars {\n /** The app's display name, as `brandName` derives it. */\n brand: string\n /** The project name with quotes and backslashes removed, for a single-quoted string. */\n appName: string\n /** The Workers Analytics Engine dataset the `usage` recipe writes to. */\n usageDataset: string\n}\n\nconst HERE = dirname(fileURLToPath(import.meta.url))\n\n/** `recipes/` beside `dist/` in the published package, or beside `src/` in the repo. */\nfunction recipesDir(): string {\n for (const candidate of [join(HERE, '..', 'recipes'), join(HERE, '..', '..', 'recipes')]) {\n if (existsSync(join(candidate, 'cloudflare', 'recipe.json'))) return candidate\n }\n throw new Error(`cascivo: the scaffold recipes are missing (looked beside ${HERE}).`)\n}\n\n/** Parse a `recipe.json`. `source` names the file in errors. */\nexport function parseRecipe(raw: unknown, source: string): Recipe {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw new Error(`${source}: a recipe must be an object.`)\n }\n const { name, files, nav = [], dependencies = [] } = raw as Record<string, unknown>\n if (typeof name !== 'string' || !/^[a-z][a-z0-9-]*$/.test(name)) {\n throw new Error(`${source}: \"name\" must be a lower-case kebab-case string.`)\n }\n if (!Array.isArray(files) || files.length === 0) {\n throw new Error(`${source}: \"files\" must be a non-empty array of paths.`)\n }\n const paths: string[] = []\n for (const file of files) {\n if (!isSafeRelativePath(file)) {\n throw new Error(`${source}: \"${String(file)}\" is not a safe relative path.`)\n }\n paths.push(file)\n }\n if (!Array.isArray(nav)) throw new Error(`${source}: \"nav\" must be an array.`)\n const items: RecipeNavItem[] = []\n for (const item of nav) {\n const { label, href } = (typeof item === 'object' && item !== null ? item : {}) as Record<\n string,\n unknown\n >\n if (\n typeof label !== 'string' ||\n label === '' ||\n typeof href !== 'string' ||\n !href.startsWith('/')\n ) {\n throw new Error(\n `${source}: each \"nav\" entry needs a \"label\" and an \"href\" starting with \"/\".`,\n )\n }\n items.push({ label, href })\n }\n if (\n !Array.isArray(dependencies) ||\n !dependencies.every((d) => typeof d === 'string' && /^@cascivo\\/[a-z-]+$/.test(d))\n ) {\n throw new Error(`${source}: \"dependencies\" must be an array of @cascivo/* package names.`)\n }\n return { name, files: paths, nav: items, dependencies: dependencies.map(String) }\n}\n\nconst cache = new Map<string, Recipe>()\n\nexport function loadRecipe(name: string): Recipe {\n const cached = cache.get(name)\n if (cached) return cached\n const source = join(recipesDir(), name, 'recipe.json')\n const recipe = parseRecipe(JSON.parse(readFileSync(source, 'utf8')) as unknown, source)\n if (recipe.name !== name) throw new Error(`${source}: \"name\" must be \"${name}\".`)\n cache.set(name, recipe)\n return recipe\n}\n\nconst PLACEHOLDER = /\\{\\{(brand|appName|usageDataset)\\}\\}/g\n\n/** The files a recipe adds, with `{{key}}` placeholders filled from `vars`. */\nexport function recipeFiles(name: string, vars: RecipeVars): { path: string; contents: string }[] {\n const dir = join(recipesDir(), name)\n return loadRecipe(name).files.map((path) => ({\n path,\n contents: readFileSync(join(dir, path), 'utf8').replace(\n PLACEHOLDER,\n (_, key: keyof RecipeVars) => vars[key],\n ),\n }))\n}\n\n/** The registry blocks a blueprint page can render: each has a `block-<name>` recipe. */\nexport function blockNames(): string[] {\n return readdirSync(recipesDir())\n .filter((dir) => dir.startsWith('block-'))\n .map((dir) => dir.slice('block-'.length))\n .sort()\n}\n","import { formatJson } from '../commands/create.js'\nimport type { ScaffoldFile } from '../commands/create.js'\n\n/**\n * `cascivo create --workspace`: the app inside a pnpm monorepo with the tooling a team would set\n * up next anyway. The app itself is the ordinary scaffold, moved to `apps/web`, so everything\n * `cascivo app` does keeps working from that directory.\n *\n * - `packages/ui`: the team's own components, imported by the app. Copying cascivo source to\n * own it (`cascivo add`) happens here, so every app in the workspace shares one copy.\n * - Vite+ (`vp run`) runs each package's scripts across the workspace, in dependency order\n * and cached.\n * - CI runs the same scripts on every push.\n */\nexport interface WorkspaceInput {\n /** The npm package name of the app; the workspace packages are scoped under it. */\n packageName: string\n /** The scaffold's files, as `cascivo create` writes them for a single app. */\n app: ScaffoldFile[]\n /** The first nav label, which the smoke test looks for. */\n firstLabel: string\n /** React + Vite apps get a component test setup; the cloudflare app tests its Worker itself. */\n testable: boolean\n /** The `@cascivo/react` version the app pins, for packages/ui. */\n reactVersion: string\n}\n\n// As Prettier prints it, so the app's own `format:check` passes on what it was given.\nconst json = formatJson\n\n/** Keys of a package.json that JSON.parse returned, with `dependencies`-like maps narrowed. */\nfunction parsePackageJson(contents: string): Record<string, unknown> {\n const raw: unknown = JSON.parse(contents)\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw new Error('cascivo: the scaffold wrote a package.json that is not an object')\n }\n return { ...raw }\n}\n\nfunction record(value: unknown): Record<string, string> {\n if (typeof value !== 'object' || value === null) return {}\n return Object.fromEntries(\n Object.entries(value).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string',\n ),\n )\n}\n\nconst ROOT_FILES = new Set(['.mcp.json'])\n\nexport function buildWorkspace(input: WorkspaceInput): ScaffoldFile[] {\n const scope = `@${input.packageName}`\n const ui = `${scope}/ui`\n const files: ScaffoldFile[] = []\n\n for (const file of input.app) {\n if (ROOT_FILES.has(file.path)) continue\n if (file.path === 'package.json') {\n const pkg = parsePackageJson(file.contents)\n const scripts = record(pkg.scripts)\n const devDependencies = record(pkg.devDependencies)\n files.push({\n path: 'apps/web/package.json',\n contents: json({\n ...pkg,\n name: `${scope}/web`,\n scripts: input.testable ? { ...scripts, test: 'vitest run' } : scripts,\n dependencies: { [ui]: 'workspace:*', ...record(pkg.dependencies) },\n devDependencies: input.testable\n ? {\n ...devDependencies,\n '@testing-library/react': '^16.3.0',\n jsdom: '^30.0.0',\n vitest: '^5.0.0',\n }\n : devDependencies,\n }),\n })\n continue\n }\n files.push({ path: `apps/web/${file.path}`, contents: file.contents })\n }\n\n if (input.testable) {\n files.push(\n {\n path: 'apps/web/vitest.config.ts',\n contents: `import { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n test: { environment: 'jsdom' },\n})\n`,\n },\n {\n path: 'apps/web/src/App.test.tsx',\n contents: `import { render, screen } from '@testing-library/react'\nimport { expect, it } from 'vitest'\nimport App from './App'\n\nit('renders the app shell and its navigation', () => {\n render(<App />)\n expect(screen.getAllByText('${input.firstLabel.replace(/'/g, \"\\\\'\")}').length).toBeGreaterThan(0)\n})\n`,\n },\n )\n }\n\n files.push(\n {\n path: 'packages/ui/package.json',\n contents: json({\n name: ui,\n private: true,\n version: '0.0.0',\n type: 'module',\n exports: { '.': './src/index.ts' },\n scripts: { typecheck: 'tsc --noEmit' },\n dependencies: { '@cascivo/react': input.reactVersion },\n peerDependencies: { react: '>=18.0.0' },\n devDependencies: { '@types/react': '^19.0.0', typescript: '^5.7.0' },\n }),\n },\n {\n path: 'packages/ui/tsconfig.json',\n contents: json({\n compilerOptions: {\n target: 'ES2022',\n module: 'ESNext',\n moduleResolution: 'bundler',\n jsx: 'react-jsx',\n strict: true,\n noEmit: true,\n skipLibCheck: true,\n },\n include: ['src'],\n }),\n },\n {\n path: 'packages/ui/src/index.ts',\n contents: `// The team's own components, shared by every app in the workspace. Build them from\n// @cascivo/react, or copy a cascivo component here to own its source:\n// cd packages/ui && npx cascivo add <name>\n// then export it below and import it in an app as \\`import { … } from '${ui}'\\`.\nexport {}\n`,\n },\n {\n path: 'package.json',\n contents: json({\n name: input.packageName,\n private: true,\n type: 'module',\n scripts: {\n dev: 'pnpm --filter ./apps/web dev',\n build: 'vp run -r build',\n typecheck: 'vp run -r typecheck',\n lint: 'vp run -r lint',\n ...(input.testable ? { test: 'vp run -r test' } : {}),\n 'format:check': 'vp run -r format:check',\n },\n devDependencies: { 'vite-plus': '^1.1.0' },\n }),\n },\n {\n path: 'pnpm-workspace.yaml',\n contents: `packages:\n - apps/*\n - packages/*\n# Install scripts pnpm runs: esbuild fetches the binary Vite builds with, workerd is the\n# Workers runtime. allowBuilds is pnpm 11's form, onlyBuiltDependencies pnpm 10's.\nallowBuilds:\n esbuild: true\n workerd: true\nonlyBuiltDependencies:\n - esbuild\n - workerd\n`,\n },\n {\n path: 'vite.config.ts',\n contents: `// Vite+ configuration for the workspace: \\`vp run\\` caches each package's tasks.\nimport { defineConfig } from 'vite-plus'\n\nexport default defineConfig({\n run: { cache: true },\n})\n`,\n },\n {\n path: '.gitignore',\n contents: 'node_modules\\ndist\\n.vite\\n',\n },\n {\n path: '.github/workflows/ci.yml',\n contents: `name: CI\n\non:\n push:\n pull_request:\n\njobs:\n check:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: pnpm/action-setup@v4\n with:\n version: 10\n - uses: actions/setup-node@v4\n with:\n node-version: 22\n cache: pnpm\n - run: pnpm install --frozen-lockfile\n - run: pnpm typecheck\n - run: pnpm lint\n${input.testable ? ' - run: pnpm test\\n' : ''} - run: pnpm build\n`,\n },\n {\n path: 'AGENTS.md',\n contents: `# Agent instructions — workspace\n\nA pnpm workspace. Run every command from this directory unless a step says otherwise.\n\n- \\`apps/web\\` is the app. Read \\`apps/web/AGENTS.md\\` before changing it. Grow it with\n \\`npx cascivo app add page \"<title>\" --block <name>\\`, run in \\`apps/web\\`.\n- \\`packages/ui\\` (\\`${ui}\\`) holds the team's own components. Copy a cascivo component here to\n own its source (\\`cd packages/ui && npx cascivo add <name>\\`), and export it from\n \\`src/index.ts\\`.\n- Checks: \\`pnpm typecheck\\`, \\`pnpm lint\\`,${input.testable ? ' `pnpm test`,' : ''} \\`pnpm build\\`. CI runs the same.\n`,\n },\n { path: 'CLAUDE.md', contents: '@AGENTS.md\\n' },\n )\n const mcp = input.app.find((f) => f.path === '.mcp.json')\n if (mcp) files.push(mcp)\n return files\n}\n","import { existsSync, readdirSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { stdin, stdout } from 'node:process'\nimport { createInterface } from 'node:readline/promises'\nimport {\n detectPackageManager,\n THEMES,\n type PackageManager,\n type ThemeName,\n} from '../utils/config.js'\nimport { flagValue, positionalArgs, resolvePackageManagerFlag } from '../utils/args.js'\nimport { writeFileSafe } from '../utils/fs.js'\nimport { CASCIVO_VERSIONS, CLI_VERSION, SIGNALS_PEER } from '../generated/versions.js'\n// Bundled into the CLI (a devDependency): the scaffold writes the same routes.gen.ts the\n// app's own Vite plugin will, so the two cannot drift.\nimport { generateRoutes } from '@cascivo/app/vite'\nimport { loadRecipe, recipeFiles } from '../scaffold/recipes.js'\nimport { mergeMcpConfig } from './mcp.js'\nimport { buildWorkspace } from '../scaffold/workspace.js'\nimport type { RecipeVars } from '../scaffold/recipes.js'\n\n/**\n * Exact published versions, baked in at build time by `scripts/registry/cli-versions.ts`.\n *\n * This used to be the literal `'latest'` for every cascivo dependency — the loosest\n * possible specifier on a set of independently-versioned 0.x packages, and the direct\n * opposite of GETTING-STARTED.md's \"pin **exact** versions (no `^`)\". A scaffold that\n * contradicts the docs on the very first file an adopter opens undermines every other rule\n * those docs state, so the pins are generated rather than hand-written.\n */\nconst V = CASCIVO_VERSIONS\n\n/** Install-everything command for a package manager (`pnpm install`, `yarn`, …). */\nfunction installAllCommand(pm: PackageManager): string {\n return pm === 'yarn' ? 'yarn' : `${pm} install`\n}\n\n/** Run-a-script command for a package manager (`npm run dev` vs `pnpm dev`). */\nfunction runScriptCommand(pm: PackageManager, script: string): string {\n return pm === 'npm' ? `npm run ${script}` : `${pm} ${script}`\n}\n\n/**\n * Like `runScriptCommand`, but always through `run`. A script named after a built-in\n * command needs it: `pnpm deploy` is pnpm's own workspace deploy, not the `deploy` script.\n */\nfunction runExplicitCommand(pm: PackageManager, script: string): string {\n return `${pm} run ${script}`\n}\n\n/** Project shape `create` emits. */\nexport type Framework = 'react-vite' | 'astro' | 'cloudflare'\n\nexport const FRAMEWORKS = ['react-vite', 'astro', 'cloudflare'] as const\n\n/** Client runtime for `--framework cloudflare`. The source is identical for both. */\nexport type Runtime = 'preact' | 'react'\n\nexport const RUNTIMES = ['preact', 'react'] as const\n\n/** Optional demo pages for `--framework cloudflare`. */\nexport type Example =\n | 'board'\n | 'agent'\n | 'notes'\n | 'import'\n | 'files'\n | 'export'\n | 'usage'\n | 'crud'\n | 'live'\n | 'voice'\n | 'publish'\n | 'webhooks'\n | 'digest'\n | 'search'\n | 'checkout'\n | 'newsletter'\n | 'social'\n\nexport const EXAMPLES = [\n 'board',\n 'agent',\n 'notes',\n 'import',\n 'files',\n 'export',\n 'usage',\n 'crud',\n 'live',\n 'voice',\n 'publish',\n 'webhooks',\n 'digest',\n 'search',\n 'checkout',\n 'newsletter',\n 'social',\n] as const\n\nexport function isExample(value: string): value is Example {\n return (EXAMPLES as readonly string[]).includes(value)\n}\n\nexport function isRuntime(value: string): value is Runtime {\n return (RUNTIMES as readonly string[]).includes(value)\n}\n\nexport interface ScaffoldOptions {\n /** Project directory + package name. */\n name: string\n /** Project shape. Defaults to `react-vite`. */\n framework?: Framework\n /** Theme imported in the entry CSS and set on `<html data-theme>`. */\n theme: ThemeName\n /** Display labels for the side-nav sections (one section component each). */\n sections: string[]\n /** Package manager for the generated README's commands (default npm). */\n pm?: PackageManager\n /**\n * Client runtime for the `cloudflare` framework. Defaults to `preact`, or `react` with the\n * `agent` example, whose Agents SDK hooks need React (see {@link runtimeOf}).\n */\n runtime?: Runtime\n /** Extra demo pages for the `cloudflare` framework. */\n examples?: Example[]\n /**\n * `cloudflare` framework only. `access`: the Worker refuses every request Cloudflare Access\n * did not let through. `email`: accounts with emailed sign-in links; `oauth`: accounts with\n * GitHub, Google and LinkedIn sign-in; `email,oauth`: both on one page. With accounts, every API write\n * needs a signed-in user.\n */\n auth?: Auth\n /**\n * The registry block each section's page renders, aligned with `sections` (a blueprint's\n * `pages[].block`). `undefined` keeps the placeholder page.\n */\n blocks?: (string | undefined)[]\n /** Put the app in a pnpm workspace (`apps/web` + `packages/ui`, Vite+, CI). */\n workspace?: boolean\n}\n\nexport type Auth = 'access' | 'email' | 'oauth' | 'email,oauth'\n\nexport interface ScaffoldFile {\n /** Path relative to the project root. */\n path: string\n contents: string\n}\n\ninterface Section {\n /** Discriminant used in the section signal + conditional render. */\n key: string\n /** Human-readable label shown in the nav and section heading. */\n label: string\n /** PascalCase component + file name. */\n component: string\n /** The registry block the page renders, from a blueprint (`recipes/block-<block>`). */\n block?: string\n}\n\n/** Slug suitable for a union-member string literal: lower-kebab, alnum only. */\nfunction slug(label: string): string {\n return (\n label\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'section'\n )\n}\n\n/** PascalCase identifier derived from a free-text label. */\nfunction pascalCase(label: string): string {\n const parts = label\n .trim()\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean)\n const joined = parts.map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('')\n const safe = joined || 'Section'\n return /^[0-9]/.test(safe) ? `Section${safe}` : safe\n}\n\n/**\n * Short, human-readable brand for the shell header.\n *\n * The directory name is the wrong thing to render verbatim: a dated demo directory\n * (`vercel-dashboard-2026-07-30-take2`) produced a 45-character brand in the top-left of\n * every page. Take the leading words, title-case them, and stop — a brand is a label, not a\n * slug. Bare numbers and `v2`-style segments are dropped rather than counted.\n */\nexport function brandName(name: string): string {\n const words = name\n .trim()\n .split(/[^a-zA-Z0-9]+/)\n .filter((w) => w !== '' && !/^\\d+$/.test(w) && !/^v\\d+$/i.test(w))\n const kept: string[] = []\n for (const word of words) {\n if (kept.length >= 3) break\n if (kept.length > 0 && kept.join(' ').length + 1 + word.length > 24) break\n kept.push(word.charAt(0).toUpperCase() + word.slice(1))\n }\n return kept.join(' ') || 'App'\n}\n\n/** Normalize the project name into a valid npm package name. */\nfunction packageName(name: string): string {\n return (\n name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'cascivo-app'\n )\n}\n\n/** Turn raw section labels into unique keyed/component-named sections. */\nfunction resolveSections(labels: string[], blocks: (string | undefined)[] = []): Section[] {\n const seenKeys = new Set<string>()\n const seenComponents = new Set<string>()\n const sections: Section[] = []\n for (const [index, label] of labels.entries()) {\n const trimmed = label.trim()\n if (!trimmed) continue\n let key = slug(trimmed)\n let component = pascalCase(trimmed)\n let n = 2\n while (seenKeys.has(key) || seenComponents.has(component)) {\n key = `${slug(trimmed)}-${n}`\n component = `${pascalCase(trimmed)}${n}`\n n++\n }\n seenKeys.add(key)\n seenComponents.add(component)\n const block = blocks[index]\n sections.push({ key, label: trimmed, component, ...(block ? { block } : {}) })\n }\n return sections.length > 0 ? sections : [{ key: 'home', label: 'Home', component: 'Home' }]\n}\n\nfunction packageJson(opts: ScaffoldOptions): string {\n const pkg = {\n name: packageName(opts.name),\n private: true,\n version: '0.0.0',\n type: 'module',\n scripts: {\n dev: 'vite',\n build: 'tsc && vite build',\n preview: 'vite preview',\n typecheck: 'tsc --noEmit',\n lint: 'eslint .',\n format: 'prettier --write .',\n 'format:check': 'prettier --check .',\n },\n // Prebuilt path (Path B): `@cascivo/react` and `@cascivo/themes` only.\n //\n // `@cascivo/core` and `@cascivo/tokens` are deliberately absent. AI-RULES.md: \"**Never**\n // add `@cascivo/core` to a prebuilt-path app's package.json — it is only a transitive\n // dependency there, and everything is re-exported from `@cascivo/react`.\"\n // GETTING-STARTED.md says the same of `@cascivo/tokens`, which arrives with\n // `@cascivo/themes` as a direct dependency. The scaffold used to declare both and then\n // import from them, so it violated two documented rules and taught the pattern by example.\n //\n // `@preact/signals-react` IS declared: it is a required peer that the generated\n // `App.tsx` calls into via `useSignals()`. It used to be omitted entirely and survived\n // only by hoisting — a phantom dependency that breaks under pnpm's strict layout.\n dependencies: {\n ...blockDependencies(opts),\n '@cascivo/react': V['@cascivo/react']!,\n '@cascivo/themes': V['@cascivo/themes']!,\n '@preact/signals-react': SIGNALS_PEER,\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n },\n devDependencies: {\n '@cascivo/eslint-config': V['@cascivo/eslint-config']!,\n '@eslint/js': '^9.0.0',\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n '@vitejs/plugin-react': '^5.0.0',\n eslint: '^9.0.0',\n 'eslint-plugin-react-hooks': '^7.0.0',\n prettier: '^3.0.0',\n typescript: '^5.7.0',\n // Registers the TypeScript parser AND the `files` patterns that make ESLint look at\n // .ts/.tsx at all. Without it ESLint 9's default `files` is **/*.{js,cjs,mjs}, so\n // `lint` on a TypeScript-only app exits 0 having inspected zero files — a green check\n // that proves nothing (2026-08-08 report B).\n 'typescript-eslint': '^8.0.0',\n vite: '^7.0.0',\n },\n }\n return JSON.stringify(pkg, null, 2) + '\\n'\n}\n\n/**\n * JSON as Prettier prints it: an array of strings stays on one line. `JSON.stringify` breaks\n * every array across lines, so a fresh app failed its own `format:check` on tsconfig.json.\n */\nexport function formatJson(value: unknown): string {\n const json = JSON.stringify(value, null, 2).replace(\n /\\[\\n\\s+(\"[^\"\\n]*\"(?:,\\n\\s+\"[^\"\\n]*\")*)\\n\\s*\\]/g,\n (_, items: string) => `[${items.split(/,\\n\\s+/).join(', ')}]`,\n )\n return json + '\\n'\n}\n\nfunction tsconfig(): string {\n const cfg = {\n compilerOptions: {\n target: 'ES2022',\n useDefineForClassFields: true,\n lib: ['ES2022', 'DOM', 'DOM.Iterable'],\n module: 'ESNext',\n skipLibCheck: true,\n moduleResolution: 'bundler',\n allowImportingTsExtensions: true,\n resolveJsonModule: true,\n isolatedModules: true,\n moduleDetection: 'force',\n noEmit: true,\n jsx: 'react-jsx',\n strict: true,\n noUnusedLocals: true,\n noUnusedParameters: true,\n noFallthroughCasesInSwitch: true,\n },\n include: ['src'],\n }\n return formatJson(cfg)\n}\n\nfunction viteConfig(): string {\n return `import react from '@vitejs/plugin-react'\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n plugins: [react()],\n})\n`\n}\n\nfunction indexHtml(opts: ScaffoldOptions): string {\n return `<!doctype html>\n<html lang=\"en\" data-theme=\"${opts.theme}\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${brandName(opts.name)}</title>\n <style>\n @layer vendor, cascivo.reset, cascivo.base, cascivo.tokens, cascivo.component,\n cascivo.platform, cascivo.theme, cascivo.blocks, cascivo.example, cascivo.override;\n /* cascivo.example is this app's own slot — above the component/blocks layers so your\n styles win, below cascivo.override which stays free for one-off hotfixes. The\n generated AGENTS.md tells the agent to write there, and this statement is what makes\n that legal: a layer used but never declared falls to the end of the cascade and\n beats everything, which is the opposite of what the ordering is for. */\n /* Third-party CSS goes in the low-priority vendor layer so it can't beat cascivo:\n @import url('some-lib/styles.css') layer(vendor); — see docs/THIRD-PARTY-CSS.md */\n @layer cascivo.reset {\n *,\n *::before,\n *::after {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n }\n }\n @layer cascivo.base {\n html,\n body,\n #root {\n height: 100%;\n }\n }\n </style>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/src/main.tsx\"></script>\n </body>\n</html>\n`\n}\n\nfunction mainTsx(): string {\n return `import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\n\nconst root = document.getElementById('root')\nif (root) {\n ReactDOM.createRoot(root).render(\n <React.StrictMode>\n <App />\n </React.StrictMode>,\n )\n}\n`\n}\n\nfunction viteEnv(): string {\n return `/// <reference types=\"vite/client\" />\\n`\n}\n\n// No `opts`: the theme import and the brand moved to `Shell.tsx`, which owns the app chrome.\nfunction appTsx(sections: Section[]): string {\n const sectionImports = sections\n .map((s) => `import { ${s.component} } from './sections/${s.component}'`)\n .join('\\n')\n\n // As Prettier prints it (printWidth 100): one line while it fits, else one member per line.\n // A long section list otherwise fails the app's own `format:check`.\n const oneLine = `type Section = ${sections.map((s) => `'${s.key}'`).join(' | ')}`\n const sectionType =\n oneLine.length <= 100\n ? oneLine\n : `type Section =\\n${sections.map((s) => ` | '${s.key}'`).join('\\n')}`\n\n const navItems = sections\n .map(\n (s) => ` {\n label: '${s.label.replace(/'/g, \"\\\\'\")}',\n active: section.value === '${s.key}',\n onClick: (e) => {\n e.preventDefault()\n section.value = '${s.key}'\n },\n },`,\n )\n .join('\\n')\n\n const renderedSections = sections\n .map((s) => ` {section.value === '${s.key}' && <${s.component} />}`)\n .join('\\n')\n\n // Everything comes from `@cascivo/react` on the prebuilt path — it re-exports the\n // `@cascivo/core` primitives, so importing from `@cascivo/core` directly would make it a\n // phantom dependency (and AI-RULES.md forbids declaring it here). There is likewise no\n // `import '@cascivo/tokens'`: the tokens arrive with the theme stylesheet.\n return `'use client'\nimport { signal, useSignals, type SideNavItem } from '@cascivo/react'\nimport { Shell } from './Shell'\n${sectionImports}\n\n${sectionType}\n\nconst section = signal<Section>('${sections[0]!.key}')\n\nexport default function App() {\n useSignals()\n\n const navItems: SideNavItem[] = [\n${navItems}\n ]\n\n return (\n <Shell navItems={navItems}>\n${renderedSections}\n </Shell>\n )\n}\n`\n}\n\n/**\n * The app shell, as its own component with a `children` slot.\n *\n * Split out of `App.tsx` because the shell composition — AppShell + ShellHeader + SideNav —\n * is the valuable part of the scaffold, and it used to be welded to the signal-driven\n * section switcher. A 2026-08-14 adopter prompted for \"a dashboard with Vite and React\n * Router\", then deleted `App.tsx` and all of `src/sections/` — the majority of what `create`\n * generated — and re-derived this wiring by hand.\n *\n * Now adding a router means deleting `App.tsx` + `src/sections/` and rendering `<Shell>` from\n * the root route's layout, with `navItems` carrying `href` instead of `onClick`. Nothing in\n * here needs to change.\n */\nfunction shellTsx(opts: ScaffoldOptions): string {\n return `'use client'\nimport { AppShell, ShellHeader, SideNav, type SideNavItem } from '@cascivo/react'\nimport type { ReactNode } from 'react'\n\nimport '@cascivo/themes/${opts.theme}.css'\n// No '@cascivo/react/styles.css' here. On a bundler build each component imports its\n// own CSS, so you ship exactly what you use — this app emits well under 100 kB of entry\n// CSS instead of the ~273 kB aggregate sheet. Import the aggregate ONLY if you drop the\n// bundler (CDN / single-file setup). See https://cascivo.com/docs/getting-started.md\n// The theme import above is always required — themes are never automatic.\n\nexport interface ShellProps {\n /** Side-nav entries. Use \\`href\\` for a routed app, \\`onClick\\` for local state. */\n navItems: SideNavItem[]\n children: ReactNode\n}\n\n/**\n * App shell: header + side nav + a content slot.\n *\n * Adding a router? Keep this file. Delete \\`App.tsx\\` and \\`src/sections/\\`, render\n * \\`<Shell navItems={…}>\\` from your root route's layout with your \\`<Outlet />\\` as children,\n * and give each nav item an \\`href\\` instead of an \\`onClick\\`.\n *\n * For those hrefs to become real router links, call \\`setLinkComponent\\` ONCE at startup in\n * \\`main.tsx\\` — see the \"Adding a router\" section of README.md for the exact snippet, or\n * https://cascivo.com/docs/using-with-a-router.md for the full recipe.\n */\nexport function Shell({ navItems, children }: ShellProps) {\n return (\n${appShellOpenTag(opts, 'navItems')}\n {children}\n </AppShell>\n )\n}\n`\n}\n\n/**\n * A page that renders a registry block. The block's source is the app's own, in `src/blocks/`,\n * written there by its `block-<name>` recipe.\n */\nfunction blockPageTsx(\n section: Section,\n declaration: 'export function' | 'export default function',\n): string {\n const block = pascalCase(section.block!)\n const local = block === section.component ? `${block}Block` : block\n return `import { ${local === block ? block : `${block} as ${local}`} } from '../blocks/${section.block}'\n\n${declaration} ${section.component}() {\n return <${local} />\n}\n`\n}\n\n/** The packages the pages' blocks bring (`@cascivo/charts`), at the versions this CLI pins. */\nfunction blockDependencies(opts: ScaffoldOptions): Record<string, string> {\n const packages = new Set(\n (opts.blocks ?? []).flatMap((block) =>\n block ? loadRecipe(`block-${block}`).dependencies : [],\n ),\n )\n return Object.fromEntries(\n [...packages].sort().map((name) => {\n const version = V[name]\n if (!version) throw new Error(`cascivo: no pinned version for ${name}`)\n return [name, version]\n }),\n )\n}\n\n/** The recipe files for every block the pages render, each once. */\nfunction blockFiles(sections: Section[], opts: ScaffoldOptions): ScaffoldFile[] {\n const blocks = [...new Set(sections.flatMap((s) => (s.block ? [s.block] : [])))]\n return blocks.flatMap((block) => recipeFiles(`block-${block}`, recipeVars(opts)))\n}\n\nfunction recipeVars(opts: ScaffoldOptions): RecipeVars {\n return {\n brand: brandName(opts.name),\n appName: opts.name.replace(/[\\\\']/g, ''),\n usageDataset: usageDataset(opts),\n }\n}\n\nfunction sectionTsx(section: Section): string {\n if (section.block) return blockPageTsx(section, 'export function')\n // No inline styles: the generated AGENTS.md tells the agent not to write them, and a\n // scaffold that models the opposite teaches the opposite. The page inset comes from\n // AppShell's own \\`padding\\` prop, and the stacking from \\`Flex\\` — note \\`gap\\` takes a\n // NUMBER (a space-scale step), not a string.\n return `import { Card, CardContent, CardHeader, CardTitle, Flex, Heading, Text } from '@cascivo/react'\n\nexport function ${section.component}() {\n return (\n <Flex gap={6}>\n <Flex gap={2}>\n <Heading level={1}>${section.label}</Heading>\n <Text muted>\n Edit <code>src/sections/${section.component}.tsx</code> to build out this page.\n </Text>\n </Flex>\n\n <Card>\n <CardHeader>\n <CardTitle>Get started</CardTitle>\n </CardHeader>\n <CardContent>\n <Text>\n This page is wired into the app shell. Add components with{' '}\n <code>npx cascivo add <component></code>.\n </Text>\n </CardContent>\n </Card>\n </Flex>\n )\n}\n`\n}\n\n/**\n * ESLint flat config for the scaffold.\n *\n * `@cascivo/eslint-config` is wired in from the start because\n * `eslint-plugin-react-hooks@7`'s `recommended-latest` reports every `signal.value = next`\n * — the idiom AI-RULES.md mandates and the generated `App.tsx` below uses — as\n * `Error: This value cannot be modified`. Without this, `pnpm lint` on a freshly scaffolded\n * app errors on every piece of state it ships with.\n */\nfunction eslintConfig(): string {\n return `import js from '@eslint/js'\nimport tseslint from 'typescript-eslint'\nimport reactHooks from 'eslint-plugin-react-hooks'\nimport cascivo from '@cascivo/eslint-config'\n\nexport default [\n { ignores: ['dist/**'] },\n js.configs.recommended,\n // Registers the TypeScript parser and the .ts/.tsx \\`files\\` patterns. WITHOUT THIS ESLINT\n // LINTS NOTHING: its default \\`files\\` is **/*.{js,cjs,mjs}, so every file in this app is\n // skipped with \"File ignored because no matching configuration was supplied\" and the\n // \\`lint\\` script exits 0 having checked zero files.\n ...tseslint.configs.recommended,\n // NOTE the \\`.flat\\` — the plugin exports both \\`configs['recommended-latest']\\` (the legacy\n // eslintrc shape, which applies NOTHING here and reports no error) and this one.\n reactHooks.configs.flat['recommended-latest'],\n // Spread LAST — flat config is last-wins. This turns off \\`react-hooks/immutability\\`,\n // which reports cascivo's signal writes (\\`signal.value = next\\`) as errors. That rule\n // fires on the very first \\`signal.value = x\\` you write, so this is not optional wiring:\n // see https://cascivo.com/docs/using-with-strict-eslint.md\n ...cascivo,\n]\n`\n}\n\n/** Prettier config matching the style the scaffold's own generated source is written in. */\n/**\n * The shell's `<AppShell …>` opening tag, laid out as Prettier lays it out: on one line when it\n * fits in the 100-column print width (a short app name), split over its attributes otherwise.\n * Always writing the split form made a fresh app with a short name fail its own format:check.\n */\nfunction appShellOpenTag(opts: ScaffoldOptions, items: string): string {\n const header = `header={<ShellHeader brand={{ name: '${brandName(opts.name).replace(/'/g, \"\\\\'\")}' }} />}`\n const nav = `nav={<SideNav items={${items}} />}`\n const line = ` <AppShell ${header} ${nav}>`\n return line.length <= 100 ? line : ` <AppShell\\n ${header}\\n ${nav}\\n >`\n}\n\nfunction prettierrc(): string {\n return JSON.stringify({ semi: false, singleQuote: true, printWidth: 100 }, null, 2) + '\\n'\n}\n\nfunction prettierIgnore(): string {\n return `dist\nnode_modules\n# Vendored cascivo source is formatted upstream — reformatting it makes every\n# \\`cascivo add\\` update a merge conflict.\nsrc/components/ui/\n`\n}\n\nfunction gitignore(): string {\n return `node_modules\ndist\n*.local\n.DS_Store\n`\n}\n\n/**\n * \"Share a preview\" for a static build: Cloudflare Drop takes the folder with no account, and\n * `wrangler deploy --temporary --assets` is the same thing from a terminal (or an agent).\n */\nfunction staticShareSection(opts: ScaffoldOptions): string {\n const pm = opts.pm ?? 'npm'\n return `\n## Share a preview\n\nNo Cloudflare account needed. Run \\`${runScriptCommand(pm, 'build')}\\`, then either:\n\n- drag the \\`dist/\\` folder onto [Cloudflare Drop](https://www.cloudflare.com/drop/), or\n- from a terminal: \\`npx wrangler deploy --temporary --assets dist --name ${packageName(opts.name)} --compatibility-date ${COMPATIBILITY_DATE}\\`\n\nEither way you get a public URL that lasts 60 minutes. Sign in to Cloudflare within that hour\nto keep it.\n`\n}\n\nfunction readme(opts: ScaffoldOptions): string {\n const pm = opts.pm ?? 'npm'\n return `# ${opts.name}\n\nA [cascivo](https://cascivo.com) app — Vite + React + TypeScript, pre-wired with\nthe cascivo app shell, side navigation, and the \\`${opts.theme}\\` theme.\n\n## Develop\n\n\\`\\`\\`sh\n${installAllCommand(pm)}\n${runScriptCommand(pm, 'dev')}\n\\`\\`\\`\n\n## Structure\n\n- \\`src/Shell.tsx\\` — the app shell (header + side nav + content slot). Router-agnostic.\n- \\`src/App.tsx\\` — nav items and which section is showing\n- \\`src/sections/\\` — one component per nav item\n\nAdd more components with \\`npx cascivo add <component>\\`.\n\n## Adding a router\n\nThis app switches sections with a signal, not a router. To add one (React Router,\nTanStack Router, …):\n\n1. **Keep \\`src/Shell.tsx\\`.** Delete \\`src/App.tsx\\` and \\`src/sections/\\`.\n2. Render \\`<Shell navItems={…}>\\` from your root route's layout, with your \\`<Outlet />\\`\n as its children.\n3. Give each nav item an \\`href\\` instead of \\`onClick\\`.\n4. Register your router's Link **once** at startup, in \\`src/main.tsx\\`:\n\n\\`\\`\\`tsx\nimport { setLinkComponent } from '@cascivo/react'\nimport type { LinkComponentProps } from '@cascivo/react'\nimport { Link } from 'react-router'\n\nsetLinkComponent(({ href, ...rest }: LinkComponentProps) => <Link to={href ?? '#'} {...rest} />)\n\\`\\`\\`\n\nThat one call makes \\`SideNav\\`, \\`ShellHeader\\` and \\`Breadcrumb\\` render real router links.\nLinks you write in page content use \\`<Link asChild>\\` instead — two kinds of link, two\nmechanisms. Full recipe: https://cascivo.com/docs/using-with-a-router.md\n${staticShareSection(opts)}`\n}\n\nfunction agentsMd(opts: ScaffoldOptions): string {\n return `# Agent instructions — ${opts.name}\n\nThis is a [cascivo](https://cascivo.com) app. When generating or editing CSS, follow\nthe **layer contract** — cascivo styles live in cascade layers, and layer order beats\nselector specificity.\n\n## CSS layer contract\n\n1. Every declaration goes inside an \\`@layer\\` block. Unlayered CSS beats all layers\n regardless of specificity — never emit it.\n2. Never invent layer names. Write only: your app slot \\`cascivo.example\\` (declared in\n the order statement in \\`index.html\\`) for page styles, and\n \\`@layer cascivo.override { … }\\` for hotfixes / one-off overrides — it beats\n everything cascivo ships.\n3. Never nest layers deeper than the shipped \\`cascivo.blocks.<name>\\` pattern. For\n sub-elements, use native CSS nesting inside one layer block, not new sublayers.\n4. Third-party CSS: \\`@import url('lib/styles.css') layer(vendor);\\` with \\`vendor\\`\n declared before the cascivo layers. Don't import vendor CSS from JavaScript — route it\n through a CSS file, or use \\`@cascivo/vite-plugin\\` (\\`cascivoLayers\\`) to layer it.\n5. Style with \\`--cascivo-*\\` tokens, not raw values.\n\nThis app's declared layer order (in \\`index.html\\`):\n\n\\`\\`\\`css\n@layer vendor, cascivo.reset, cascivo.base, cascivo.tokens, cascivo.component,\n cascivo.platform, cascivo.theme, cascivo.blocks, cascivo.example, cascivo.override;\n\\`\\`\\`\n\n### Worked example — nesting, not new layers\n\n\\`\\`\\`css\n@layer cascivo.override {\n .projectCard {\n /* Sub-elements nest inside the one block — no cascivo.card.status sublayer. */\n .statusBadge {\n color: var(--cascivo-color-text-subtle);\n .pulseDot {\n background: var(--cascivo-color-success);\n }\n }\n }\n}\n\\`\\`\\`\n\n## Routing\n\nIf you add a router, keep \\`src/Shell.tsx\\` and delete \\`src/App.tsx\\` + \\`src/sections/\\`.\n\ncascivo links come in **two kinds**, wired two different ways. Do not intercept\n\\`onClick\\`, and do not hand-wrap nav items:\n\n1. **Config-driven navs** (\\`SideNav\\`, \\`ShellHeader\\`, \\`Breadcrumb\\`, \\`Switcher\\`) render\n through a module singleton. Register your router's Link once, in \\`src/main.tsx\\`:\n \\`setLinkComponent(({ href, ...rest }: LinkComponentProps) => <Link to={href ?? '#'} {...rest} />)\\`\n2. **Links in page content** use \\`asChild\\`:\n \\`<Link asChild><RouterLink to=\"/x\">x</RouterLink></Link>\\`\n\nFull recipe: https://cascivo.com/docs/using-with-a-router.md\n\n## Types\n\nThe vocabulary types are on a subpath: \\`import type { Tone } from '@cascivo/react/types'\\`\n(also \\`Progress\\`, \\`SpaceStep\\`). \\`Status.status\\` and \\`Badge.variant\\` use them, so a\n\\`Record<MyState, Tone>\\` is the supported way to map domain states onto tones. **Never**\nadd \\`@cascivo/core\\` to this app's dependencies — it is transitive here.\n\nMore: cascivo's machine-readable guide is at https://cascivo.com/llms.txt.\n`\n}\n\n/** Build the full set of files for a new cascivo app. Pure — no filesystem I/O. */\n/* ------------------------------------------------------------------------- *\n * Astro scaffold (`--framework astro`)\n *\n * Shaped around what Astro is actually for, rather than transliterating the Vite SPA:\n * pages are real routes (no router to add later), page CONTENT is cascivo components\n * rendered with no client directive at all — server HTML, zero JS — and the only island\n * is the shell, which needs JS for its mobile nav drawer.\n *\n * The `astro.config.mjs` this emits carries one non-obvious required line —\n * `vite.resolve.noExternal` — without which SSR'd islands render unstyled. Baking that in\n * is most of why this scaffold is worth having; see the comment on `astroConfig` and\n * docs/USING-WITH-ASTRO.md.\n * ------------------------------------------------------------------------- */\n\n/** Route for a section. The first section owns the index route. */\nfunction sectionPath(section: Section, index: number): string {\n return index === 0 ? '/' : `/${section.key}`\n}\n\n/** Page file for a section, relative to `src/pages/`. */\nfunction sectionPageFile(section: Section, index: number): string {\n return index === 0 ? 'index.astro' : `${section.key}.astro`\n}\n\nfunction astroPackageJson(opts: ScaffoldOptions): string {\n const pkg = {\n name: packageName(opts.name),\n private: true,\n version: '0.0.0',\n type: 'module',\n scripts: {\n dev: 'astro dev',\n build: 'astro build',\n preview: 'astro preview',\n typecheck: 'astro check',\n lint: 'eslint .',\n format: 'prettier --write .',\n 'format:check': 'prettier --check .',\n },\n // Same prebuilt-path rule as the Vite scaffold: `@cascivo/react` + `@cascivo/themes`\n // only. `@cascivo/core` and `@cascivo/tokens` are transitive and must not be declared.\n dependencies: {\n '@astrojs/react': '^7.1.0',\n '@cascivo/astro': V['@cascivo/astro']!,\n '@cascivo/react': V['@cascivo/react']!,\n '@cascivo/themes': V['@cascivo/themes']!,\n '@preact/signals-react': SIGNALS_PEER,\n astro: '^7.0.0',\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n },\n devDependencies: {\n // @astrojs/check 0.9 peers TypeScript ^5 || ^6 and refuses 7, so `typescript` below stays on 5.\n '@astrojs/check': '^0.9.0',\n '@cascivo/eslint-config': V['@cascivo/eslint-config']!,\n '@eslint/js': '^9.0.0',\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n eslint: '^9.0.0',\n 'eslint-plugin-react-hooks': '^7.0.0',\n prettier: '^3.0.0',\n typescript: '^5.7.0',\n 'typescript-eslint': '^8.0.0',\n },\n }\n return JSON.stringify(pkg, null, 2) + '\\n'\n}\n\nfunction astroConfig(opts: ScaffoldOptions): string {\n return `// @ts-check\nimport { defineConfig } from 'astro/config'\nimport react from '@astrojs/react'\nimport cascivo from '@cascivo/astro'\n\nexport default defineConfig({\n // @cascivo/astro injects, on every page and ahead of any other CSS, the layer order and then\n // the theme, and inlines a no-flash theme script that survives <ClientRouter /> swaps.\n // \\`layers\\` is the statement in src/styles/layers.css, this app's cascivo.example slot included.\n // Both theme options name the app's theme: the defaults (light-dark.css and the OS\n // preference) would repaint any other theme as plain light or dark.\n integrations: [\n react(),\n cascivo({\n layers:\n '${ASTRO_LAYER_ORDER}',\n theme: '@cascivo/themes/${opts.theme}.css',\n themeScript: { defaultTheme: '${opts.theme}' },\n }),\n ],\n vite: {\n resolve: {\n // Kept for @cascivo/react 1.9.0 and older; @cascivo/astro sets it too, and newer\n // versions do not need it (their package carries the \\`astro-component\\` keyword).\n //\n // Vite externalizes node_modules packages in its server build, so an externalized\n // @cascivo/react is imported by Node at runtime and its module graph is never walked\n // — and Astro collects a page's CSS by walking that graph. On those versions, without\n // it, SSR'd islands (client:load, client:visible) render with correct class names and no\n // rules anywhere in the output. Nothing warns; it reads as a theming problem.\n //\n // It must be \\`resolve.noExternal\\`, NOT \\`ssr.noExternal\\`: Astro prerenders static\n // routes in its own Vite environment, which \\`ssr.*\\` does not reach.\n // https://cascivo.com/docs/using-with-astro.md\n noExternal: [/^@cascivo\\\\//],\n },\n },\n})\n`\n}\n\nfunction astroTsconfig(): string {\n const cfg = {\n extends: 'astro/tsconfigs/strict',\n include: ['.astro/types.d.ts', '**/*'],\n exclude: ['dist'],\n compilerOptions: { jsx: 'react-jsx' },\n }\n return JSON.stringify(cfg, null, 2) + '\\n'\n}\n\n/**\n * The Astro scaffold's complete layer order: `vendor` lowest, the canonical cascivo layers,\n * and this app's `cascivo.example` slot just below `cascivo.override`. One constant, because\n * it is both passed to `@cascivo/astro` (which injects it first on every page) and repeated\n * in `src/styles/layers.css`; two copies would drift. One literal, not a concatenation:\n * scripts/checks/layer-order.test.ts scans this file for `@layer …;` statements, and a split\n * string would hide this one from it.\n */\nconst ASTRO_LAYER_ORDER =\n '@layer vendor, cascivo.reset, cascivo.base, cascivo.tokens, cascivo.component, cascivo.platform, cascivo.theme, cascivo.blocks, cascivo.example, cascivo.override;'\n\n/**\n * The reset and base rules, under the same order statement `@cascivo/astro` injects first.\n *\n * Layers take their order from first appearance, so the statement that counts is the\n * integration's, which lands before any cascivo CSS; a statement that only arrived after the\n * theme could reorder nothing, and `vendor` would win over every cascivo layer. Repeating the\n * identical statement here is idempotent and keeps the file readable on its own.\n */\nfunction astroLayersCss(): string {\n return `/* Cascade layer order. Later layers beat earlier ones regardless of specificity.\n @cascivo/astro injects this same statement first on every page (\\`layers\\` in\n astro.config.mjs); keep the two identical. Repeating it here is harmless.\n\n cascivo.example is this app's own slot: above the component and blocks layers so your\n page styles win, below cascivo.override which stays free for one-off hotfixes.\n Third-party CSS goes in vendor so it cannot beat cascivo:\n @import url('some-lib/styles.css') layer(vendor);\n See https://cascivo.com/docs/third-party-css.md */\n${ASTRO_LAYER_ORDER}\n\n@layer cascivo.reset {\n *,\n *::before,\n *::after {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n }\n}\n\n@layer cascivo.base {\n html,\n body {\n block-size: 100%;\n }\n}\n`\n}\n\nfunction astroLayout(opts: ScaffoldOptions): string {\n return `---\n// The layer order and the ${opts.theme} theme come from @cascivo/astro in astro.config.mjs,\n// injected ahead of this file on every page. This adds the reset and base rules.\nimport '../styles/layers.css'\n\n// No '@cascivo/react/styles.css'. Each component brings its own CSS through the module\n// graph, so you ship only what your pages use. Import the aggregate ONLY if you drop the\n// bundler entirely.\n\ninterface Props {\n title: string\n}\n\nconst { title } = Astro.props\n---\n\n<!doctype html>\n<html lang=\"en\" data-theme=\"${opts.theme}\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>{title} · ${brandName(opts.name)}</title>\n </head>\n <body>\n <slot />\n </body>\n</html>\n`\n}\n\n/**\n * The app shell — the ONLY island in the scaffold.\n *\n * It is hydrated because AppShell's nav drawer is interactive on small screens. Page\n * content is slotted in as children and stays server-rendered HTML, so a page costs the\n * shell's JS and nothing more.\n */\nfunction astroShellTsx(opts: ScaffoldOptions, sections: Section[]): string {\n const navItems = sections\n .map((s, i) => ` { label: '${s.label.replace(/'/g, \"\\\\'\")}', href: '${sectionPath(s, i)}' },`)\n .join('\\n')\n\n return `import { AppShell, ShellHeader, SideNav, type SideNavItem } from '@cascivo/react'\nimport type { ReactNode } from 'react'\n\nconst NAV: { label: string; href: string }[] = [\n${navItems}\n]\n\nexport interface ShellProps {\n /** Current route, e.g. \\`Astro.url.pathname\\`. Marks the matching nav item active. */\n activePath: string\n children: ReactNode\n}\n\n/**\n * Header + side nav + a content slot.\n *\n * Nav items carry \\`href\\`, so navigation is a real page load and Astro's router handles\n * it — there is no client router to register and no \\`setLinkComponent\\` call to make.\n */\nexport function Shell({ activePath, children }: ShellProps) {\n const items: SideNavItem[] = NAV.map((item) => ({\n ...item,\n active: item.href === activePath,\n }))\n\n return (\n${appShellOpenTag(opts, 'items')}\n {children}\n </AppShell>\n )\n}\n`\n}\n\n/**\n * A section's content as a plain React component with NO \\`'use client'\\`.\n *\n * Astro renders it on the server and ships no JavaScript for it. Add a client directive at\n * the call site in the page only when a section actually needs interactivity.\n */\nfunction astroSectionTsx(section: Section): string {\n return `import { Card, CardContent, CardHeader, CardTitle, Flex, Heading, Text } from '@cascivo/react'\n\nexport function ${section.component}() {\n return (\n <Flex gap={6}>\n <Flex gap={2}>\n <Heading level={1}>${section.label}</Heading>\n <Text muted>\n Edit <code>src/components/${section.component}.tsx</code> to build out this page.\n </Text>\n </Flex>\n\n <Card>\n <CardHeader>\n <CardTitle>Get started</CardTitle>\n </CardHeader>\n <CardContent>\n <Text>\n This page is server-rendered — no JavaScript ships for it. Add components with{' '}\n <code>npx cascivo add <component></code>.\n </Text>\n </CardContent>\n </Card>\n </Flex>\n )\n}\n`\n}\n\nfunction astroPage(section: Section, index: number): string {\n return `---\nimport Layout from '../layouts/Layout.astro'\nimport { Shell } from '../components/Shell'\nimport { ${section.component} } from '../components/${section.component}'\n---\n\n<Layout title=\"${section.label}\">\n {/* client:load hydrates the shell for its mobile nav drawer. The section below stays\n server-rendered HTML — it is slotted in as children and ships no JS. */}\n <Shell client:load activePath=\"${sectionPath(section, index)}\">\n <${section.component} />\n </Shell>\n</Layout>\n`\n}\n\nfunction astroGitignore(): string {\n return `node_modules\ndist\n.astro\n*.local\n.DS_Store\n`\n}\n\nfunction astroReadme(opts: ScaffoldOptions, sections: Section[]): string {\n const pm = opts.pm ?? 'npm'\n const routes = sections\n .map((s, i) => `- \\`${sectionPath(s, i)}\\` — \\`src/pages/${sectionPageFile(s, i)}\\``)\n .join('\\n')\n\n return `# ${opts.name}\n\nA [cascivo](https://cascivo.com) app — Astro + React islands + TypeScript, pre-wired with\nthe cascivo app shell, side navigation, and the \\`${opts.theme}\\` theme.\n\n## Develop\n\n\\`\\`\\`sh\n${installAllCommand(pm)}\n${runScriptCommand(pm, 'dev')}\n\\`\\`\\`\n\n## Routes\n\n${routes}\n\nAdd a page by dropping a new \\`.astro\\` file in \\`src/pages/\\` — Astro routes it by filename.\nAdd it to \\`NAV\\` in \\`src/components/Shell.tsx\\` to get a nav entry.\n\n## What hydrates, and what doesn't\n\nOnly \\`Shell\\` carries a client directive (\\`client:load\\`), because its nav drawer is\ninteractive on small screens. Everything inside it is slotted in as children and stays\nserver-rendered HTML, so a page ships the shell's JavaScript and nothing else.\n\nNeed a section to be interactive? Give it a directive at the call site in the page:\n\n\\`\\`\\`astro\n<${sections[0]!.component} client:visible />\n\\`\\`\\`\n\nA component that reads \\`signal.value\\` during render must also call \\`useSignals()\\` from\n\\`@cascivo/react\\` as its first statement — Astro applies no signals transform.\n\n## Styling\n\n\\`@cascivo/astro\\` (in \\`astro.config.mjs\\`) injects the cascade layer order, then the\n\\`${opts.theme}\\` theme, ahead of any other CSS on every page, and inlines a no-flash theme\nscript. Its \\`layers\\` option is the same statement as \\`src/styles/layers.css\\`, which adds\nthis app's own \\`cascivo.example\\` slot; keep the two identical. Layers take their position\nfrom first appearance, so a statement loaded after the theme cannot reorder anything.\n\nAdd more components with \\`npx cascivo add <component>\\`.\n${staticShareSection(opts)}`\n}\n\n/* ------------------------------------------------------------------------- *\n * Cloudflare scaffold (`--framework cloudflare`)\n *\n * A client-rendered app and its API, deployed as ONE Worker with static assets. No SSR:\n * the browser gets the SPA, `/api/*` reaches the Worker, and `@cloudflare/vite-plugin`\n * runs that Worker in workerd during `vite dev`, so dev and production execute the same\n * runtime. The shape comes from `apps/examples/chat` (its FINDINGS.md), not from a design\n * exercise: the source is typed against React and the runtime is picked in the bundler,\n * shared wire types live in one file both sides import, and streaming goes through\n * `@cascivo/data`.\n * ------------------------------------------------------------------------- */\n\n/** Workers runtime date the scaffold targets. Bump deliberately, never to \"today\". */\nconst COMPATIBILITY_DATE = '2026-09-01'\n\nfunction cfPackageJson(opts: ScaffoldOptions): string {\n const pm = opts.pm ?? 'npm'\n const agent = hasExample(opts, 'agent')\n const workerTypes = needsWorkerTypes(opts)\n const preact = runtimeOf(opts) === 'preact'\n const pkg = {\n name: packageName(opts.name),\n private: true,\n version: '0.0.0',\n type: 'module',\n scripts: {\n dev: 'vite',\n build: workerTypes ? 'tsc && tsc -p tsconfig.worker.json && vite build' : 'tsc && vite build',\n preview: 'vite preview',\n deploy: `${runScriptCommand(pm, 'build')} && wrangler deploy`,\n // No account: a temporary one, live for 60 minutes unless claimed (see README).\n 'deploy:preview': `${runScriptCommand(pm, 'build')} && wrangler deploy --temporary`,\n typecheck: workerTypes\n ? 'tsc --noEmit && tsc --noEmit -p tsconfig.worker.json'\n : 'tsc --noEmit',\n lint: 'eslint .',\n format: 'prettier --write .',\n 'format:check': 'prettier --check .',\n },\n // Same prebuilt-path rules as the Vite scaffold (see `packageJson`): no @cascivo/core,\n // no @cascivo/tokens. `@cascivo/app` is the router + typed API this app imports;\n // `@cascivo/data` arrives with it.\n dependencies: {\n '@cascivo/app': V['@cascivo/app']!,\n ...blockDependencies(opts),\n '@cascivo/react': V['@cascivo/react']!,\n '@cascivo/themes': V['@cascivo/themes']!,\n '@preact/signals-react': SIGNALS_PEER,\n ...(preact ? { preact: '^10.29.0' } : { react: '^19.0.0', 'react-dom': '^19.0.0' }),\n // The /usage and /ops pages' charts.\n ...(hasExample(opts, 'usage') || hasExample(opts, 'live')\n ? { '@cascivo/charts': V['@cascivo/charts']! }\n : {}),\n // The /report page's PDF/PNG export drives Browser Run through Cloudflare's puppeteer.\n ...(hasExample(opts, 'export') ? { '@cloudflare/puppeteer': '^1.4.0' } : {}),\n // The /notes page keeps its room in IndexedDB.\n ...(hasExample(opts, 'notes') ? { '@cascivo/storage': V['@cascivo/storage']! } : {}),\n // The /assistant page: Cloudflare's Agents SDK on the AI SDK, and @cascivo/render to\n // draw (and validate) the views the model builds.\n ...(agent\n ? {\n '@ai-sdk/react': '^4.0.0',\n '@cascivo/render': V['@cascivo/render']!,\n '@cloudflare/ai-chat': '^0.12.1',\n agents: '^0.26.0',\n ai: '^7.0.0',\n 'workers-ai-provider': '^4.0.0',\n zod: '^4.0.0',\n }\n : {}),\n // The /voice page: the Agents SDK's voice pipeline and its browser client.\n ...(hasExample(opts, 'voice') && !agent ? { agents: '^0.26.0' } : {}),\n // The /publish page and published pages render views with @cascivo/render.\n ...(hasExample(opts, 'publish') && !agent\n ? { '@cascivo/render': V['@cascivo/render']! }\n : {}),\n // The Worker renders receipts and newsletters with @cascivo/email (react-dom/server\n // underneath).\n ...(hasExample(opts, 'checkout') || hasExample(opts, 'newsletter')\n ? { '@cascivo/email': V['@cascivo/email']! }\n : {}),\n // The Worker server-renders published pages and emails; under Preact, react-dom/server\n // is preact/compat/server, which needs this.\n ...((hasExample(opts, 'publish') ||\n hasExample(opts, 'checkout') ||\n hasExample(opts, 'newsletter')) &&\n preact\n ? { 'preact-render-to-string': '^6.5.0' }\n : {}),\n },\n devDependencies: {\n '@cascivo/eslint-config': V['@cascivo/eslint-config']!,\n '@cloudflare/vite-plugin': '^1.62.0',\n // Types for worker/ (tsconfig.worker.json): the Agents SDK and Workflows extend runtime\n // classes only these declare. Kept out of the app's DOM-typed tsconfig.\n ...(workerTypes ? { '@cloudflare/workers-types': '^5.0.0' } : {}),\n '@eslint/js': '^9.0.0',\n // The source is typed against React even when Preact runs it (see vite.config.ts), so\n // React's types are always installed. Under Preact, `react`/`react-dom` are dev-only:\n // they satisfy cascivo's peer ranges and are aliased away at build time.\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n ...(preact\n ? {\n '@babel/core': '^7.0.0',\n '@preact/preset-vite': '^2.10.0',\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n }\n : { '@vitejs/plugin-react': '^6.0.0' }),\n eslint: '^9.0.0',\n 'eslint-plugin-react-hooks': '^7.0.0',\n prettier: '^3.0.0',\n typescript: '^5.7.0',\n 'typescript-eslint': '^8.0.0',\n vite: '^8.0.0',\n wrangler: '^4.143.0',\n },\n }\n const bindings = cfBindingDescriptions(opts)\n return (\n JSON.stringify(\n Object.keys(bindings).length > 0 ? { ...pkg, cloudflare: { bindings } } : pkg,\n null,\n 2,\n ) + '\\n'\n )\n}\n\nfunction cfTsconfig(opts: ScaffoldOptions): string {\n const cfg = JSON.parse(tsconfig()) as { include: string[] }\n // `worker/` is type-checked with the app: it imports `src/api.ts`, and a contract change\n // should fail `tsc` on whichever side was not updated. When the Worker needs Cloudflare's\n // runtime types (see needsWorkerTypes), which clash with the DOM's, it gets its own config\n // (tsconfig.worker.json) and both run in `typecheck`.\n cfg.include = needsWorkerTypes(opts) ? ['src'] : ['src', 'worker']\n return formatJson(cfg)\n}\n\nfunction cfWorkerTsconfig(): string {\n return formatJson({\n extends: './tsconfig.json',\n compilerOptions: {\n lib: ['ES2022'],\n types: ['@cloudflare/workers-types', 'vite/client'],\n },\n include: ['worker'],\n })\n}\n\nfunction cfViteConfig(runtime: Runtime, opts: ScaffoldOptions): string {\n const agent = hasExample(opts, 'agent')\n const ai = usesWorkersAi(opts)\n const plugin =\n runtime === 'preact'\n ? `import preact from '@preact/preset-vite'`\n : `import react from '@vitejs/plugin-react'`\n const call = runtime === 'preact' ? 'preact()' : 'react()'\n const note =\n runtime === 'preact'\n ? `// The source is written against React's types; @preact/preset-vite aliases react and\n// react-dom to preact/compat, so the bundle runs on Preact (about a third of React's JS in\n// this starter: ~27 KB gzip against ~85 KB). To run on React instead, swap this plugin\n// for @vitejs/plugin-react — no source changes.`\n : agent\n ? `// Runs on React: the /assistant page uses the Agents SDK's hooks, which call React 19's\n// use() — preact/compat does not implement it, so this app cannot switch to Preact.`\n : `// Runs on React. To ship Preact instead (about a third of the JS in this starter), swap\n// this plugin for @preact/preset-vite — it aliases react/react-dom to preact/compat; no\n// source changes.`\n return `${plugin}\nimport { cascivoRoutes } from '@cascivo/app/vite'\nimport { cloudflare } from '@cloudflare/vite-plugin'\nimport { defineConfig } from 'vite'\n\n${note}\n//\n// cascivoRoutes() writes src/routes.gen.ts from src/routes/ — one file per page.\n// cloudflare() runs worker/index.ts in workerd during \\`vite dev\\` and builds it with the\n// client, so dev and production execute the same runtime. Request routing is in wrangler.jsonc.${\n ai\n ? `\n//\n// Workers AI has no local mode: with remote bindings on, \\`vite dev\\` needs a Cloudflare login.\n// So they are off, ${\n hasExample(opts, 'search')\n ? `and:${[\n agent ? 'the assistant answers from worker/scripted-model.ts' : '',\n hasExample(opts, 'voice')\n ? 'the voice page uses the stand-ins in worker/scripted-voice.ts'\n : '',\n 'search runs by keyword, on SQLite full-text search (worker/search.ts)',\n ]\n .filter(Boolean)\n .map((clause) => `\\n// - ${clause}`)\n .join('')}`\n : agent && hasExample(opts, 'voice')\n ? `the assistant answers from worker/scripted-model.ts, and the voice\n// page uses the stand-ins in worker/scripted-voice.ts`\n : agent\n ? 'and the assistant answers from worker/scripted-model.ts'\n : 'and the voice page uses the stand-ins in worker/scripted-voice.ts'\n }. Run\n// \\`VITE_REAL_AI=1 vite dev\\` (after \\`wrangler login\\`) to use Workers AI.`\n : ''\n }\nexport default defineConfig({\n${\n ai\n ? ` plugins: [\n ${call},\n cascivoRoutes(),\n cloudflare({ remoteBindings: process.env['VITE_REAL_AI'] === '1' }),\n ],`\n : ` plugins: [${call}, cascivoRoutes(), cloudflare()],`\n}${\n hasExample(opts, 'publish')\n ? `\n // A published page's HTML links the stylesheets its route needs, found in this manifest\n // (worker/page-html.ts), so the page is styled for readers without JavaScript too.\n build: { manifest: 'asset-manifest.json' },`\n : ''\n }\n})\n`\n}\n\n/** A JSONC array property laid out as Prettier does: one line when it fits in 100 columns. */\nfunction jsoncArray(indent: string, key: string, items: string[]): string {\n const line = `${indent}\"${key}\": [${items.join(', ')}],`\n if (line.length <= 100) return line\n return `${indent}\"${key}\": [\\n${items.map((i) => `${indent} ${i},`).join('\\n')}\\n${indent}],`\n}\n\nfunction wranglerJsonc(opts: ScaffoldOptions): string {\n const publish = hasExample(opts, 'publish')\n const rooms = usesRooms(opts)\n const agent = hasExample(opts, 'agent')\n const ai = usesAgents(opts)\n // One Durable Object class per example; a fresh app declares them all in one migration.\n const objects = [\n ...(rooms ? [{ name: 'ROOMS', className: 'SyncRoom' }] : []),\n ...(agent ? [{ name: 'Assistant', className: 'Assistant' }] : []),\n ...(hasExample(opts, 'live') ? [{ name: 'LIVE', className: 'LiveRoom' }] : []),\n ...(hasExample(opts, 'voice') ? [{ name: 'Voice', className: 'Voice' }] : []),\n ]\n const comments = [\n ...(rooms ? ['// ROOMS: one SyncRoom per room (@cascivo/app/sync-server).'] : []),\n ...(agent\n ? ['// Assistant: one AIChatAgent per conversation; it stores the messages in SQLite.']\n : []),\n ...(hasExample(opts, 'live')\n ? [\"// LIVE: the /ops dashboard's per-second totals (@cascivo/app/live-server).\"]\n : []),\n ...(hasExample(opts, 'voice')\n ? ['// Voice: one voice agent per conversation (agents/voice); it stores the transcript.']\n : []),\n ]\n return `// Cloudflare deploy config. \\`${runExplicitCommand(opts.pm ?? 'npm', 'deploy')}\\` builds and ships the SPA and\n// the Worker together. https://developers.cloudflare.com/workers/wrangler/configuration/\n{\n \"name\": \"${packageName(opts.name)}\",\n \"main\": \"./worker/index.ts\",\n \"compatibility_date\": \"${COMPATIBILITY_DATE}\",\n \"assets\": {\n // Client-side app: an unknown path serves index.html, and the client renders it.\n \"not_found_handling\": \"single-page-application\",\n // ${\n publish\n ? 'Only the API and published pages reach the Worker; static assets are served\\n // without invoking it.'\n : 'Only the API reaches the Worker; static assets are served without invoking it.'\n }\n \"run_worker_first\": [${['\"/api/*\"', ...(ai ? ['\"/agents/*\"'] : []), ...(publish ? ['\"/p/*\"'] : [])].join(', ')}],${\n publish\n ? `\n // The Worker reads index.html through this to put a published page into it.\n \"binding\": \"ASSETS\",`\n : ''\n }\n },\n \"observability\": { \"enabled\": true },${\n objects.length > 0\n ? `\n ${comments.join('\\n ')}\n \"durable_objects\": {\n${jsoncArray(\n ' ',\n 'bindings',\n objects.map((o) => `{ \"name\": \"${o.name}\", \"class_name\": \"${o.className}\" }`),\n)}\n },\n${jsoncArray(' ', 'migrations', [`{ \"tag\": \"v1\", \"new_sqlite_classes\": [${objects.map((o) => `\"${o.className}\"`).join(', ')}] }`])}`\n : ''\n }${\n hasExample(opts, 'files') || hasExample(opts, 'social')\n ? `\n // ${[\n hasExample(opts, 'files')\n ? 'Uploaded files, and Cloudflare Images for their resized previews'\n : '',\n hasExample(opts, 'social') ? 'Images attached to social posts (worker/social.ts)' : '',\n ]\n .filter(Boolean)\n .join('; ')}.\n${jsoncArray(' ', 'r2_buckets', [\n ...(hasExample(opts, 'files')\n ? [`{ \"binding\": \"FILES\", \"bucket_name\": \"${packageName(opts.name)}-files\" }`]\n : []),\n ...(hasExample(opts, 'social')\n ? [`{ \"binding\": \"SOCIAL_MEDIA\", \"bucket_name\": \"${packageName(opts.name)}-social-media\" }`]\n : []),\n])}${hasExample(opts, 'files') ? '\\n \"images\": { \"binding\": \"IMAGES\" },' : ''}`\n : ''\n }${\n usesLimiter(opts)\n ? `\n // ${[\n hasExample(opts, 'files') ? 'Uploads' : '',\n hasExample(opts, 'export') ? 'exports' : '',\n hasExample(opts, 'publish') ? 'published pages' : '',\n hasExample(opts, 'digest') ? 'digests sent now' : '',\n hasExample(opts, 'search') ? 'search indexing' : '',\n hasExample(opts, 'checkout') ? 'checkouts started' : '',\n hasExample(opts, 'newsletter') ? 'newsletter sign-ups and composer requests' : '',\n hasExample(opts, 'social') ? 'connecting accounts, posts and image uploads' : '',\n emailSignIn(opts) ? 'sign-in emails' : '',\n ]\n .filter(Boolean)\n .join(', ')\n .replace(/^./, (c) => c.toUpperCase())} per caller: 20 a minute.\n // namespace_id is any number unique within your account:\n // https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/\n${jsoncArray(' ', 'ratelimits', ['{ \"name\": \"LIMITER\", \"namespace_id\": \"1001\", \"simple\": { \"limit\": 20, \"period\": 60 } }'])}`\n : ''\n }${wranglerVars(opts)}${\n hasExample(opts, 'digest') || hasExample(opts, 'social')\n ? `\n // ${[\n hasExample(opts, 'digest') ? 'The weekly digest: Mondays at 08:00 UTC (worker/digest.ts)' : '',\n hasExample(opts, 'social')\n ? 'Threads tokens renewed and reconnect reminders sent, daily at 04:17 UTC (worker/social.ts)'\n : '',\n ]\n .filter(Boolean)\n .join('; ')}.\n \"triggers\": { \"crons\": [${[\n hasExample(opts, 'digest') ? '\"0 8 * * 1\"' : '',\n hasExample(opts, 'social') ? `\"${SOCIAL_CRON}\"` : '',\n ]\n .filter(Boolean)\n .join(', ')}] },`\n : ''\n }${\n usesD1(opts)\n ? `\n // Tables for ${[\n hasExample(opts, 'crud') ? 'customers' : '',\n hasExample(opts, 'publish') ? 'published pages' : '',\n hasExample(opts, 'webhooks') ? 'webhook deliveries' : '',\n hasExample(opts, 'digest') ? 'digest runs' : '',\n hasExample(opts, 'search') ? 'help articles' : '',\n hasExample(opts, 'checkout') ? 'orders' : '',\n hasExample(opts, 'newsletter') ? 'newsletter subscribers and issues' : '',\n hasAccounts(opts) ? 'accounts' : '',\n ]\n .filter(Boolean)\n .join(', ')}.\n // No database_id: wrangler creates the database on first deploy, and the Worker applies its\n // own schema on its first query (\\`migrate\\`).\n${jsoncArray(' ', 'd1_databases', [`{ \"binding\": \"DB\", \"database_name\": \"${packageName(opts.name)}-db\" }`])}`\n : ''\n }${\n hasExample(opts, 'usage')\n ? `\n // Every API request is recorded here (worker/index.ts); /usage reads it back.\n \"analytics_engine_datasets\": [{ \"binding\": \"USAGE\", \"dataset\": \"${usageDataset(opts)}\" }],`\n : ''\n }${wranglerQueues(opts)}${\n hasExample(opts, 'import') || hasExample(opts, 'social')\n ? `\n // ${[\n hasExample(opts, 'import')\n ? 'The CSV import runs as a Workflow (worker/import-job.ts); its progress is a room.'\n : '',\n hasExample(opts, 'social')\n ? 'Each scheduled post is a Workflow that waits until it is due (worker/social-post.ts).'\n : '',\n ]\n .filter(Boolean)\n .join('\\n // ')}\n${jsoncArray(' ', 'workflows', [\n ...(hasExample(opts, 'import')\n ? ['{ \"name\": \"import-job\", \"binding\": \"IMPORT_JOB\", \"class_name\": \"ImportJob\" }']\n : []),\n ...(hasExample(opts, 'social')\n ? [\n `{ \"name\": \"${packageName(opts.name)}-social-post\", \"binding\": \"SOCIAL_POST\", \"class_name\": \"SocialPost\" }`,\n ]\n : []),\n])}`\n : ''\n }${\n usesWorkersAi(opts)\n ? `\n // Workers AI, which the ${[agent ? 'assistant' : '', hasExample(opts, 'voice') ? 'voice agent' : '', hasExample(opts, 'search') ? 'search page' : ''].filter(Boolean).join(' and ')} call${[agent, hasExample(opts, 'voice'), hasExample(opts, 'search')].filter(Boolean).length > 1 ? '' : 's'}.\n \"ai\": { \"binding\": \"AI\" },`\n : ''\n }${\n hasExample(opts, 'search')\n ? `\n // The help articles' embeddings (worker/search.ts). Create it once before deploying (README).\n${jsoncArray(' ', 'vectorize', [`{ \"binding\": \"ARTICLES_INDEX\", \"index_name\": \"${packageName(opts.name)}-articles\" }`])}`\n : ''\n }${\n hasExample(opts, 'export')\n ? `\n // Browser Run: renders pages to PDF/PNG for /api/export.\n \"browser\": { \"binding\": \"BROWSER\" },`\n : ''\n }${\n ai || hasExample(opts, 'export')\n ? `\n // ${[ai ? 'The Agents SDK' : '', hasExample(opts, 'export') ? \"Cloudflare's puppeteer\" : ''].filter(Boolean).join(' and ')} use${ai && hasExample(opts, 'export') ? '' : 's'} Node.js APIs.\n \"compatibility_flags\": [\"nodejs_compat\"],`\n : ''\n }\n // Add bindings here (KV, D1, R2, Durable Objects, Workers AI) and read them from the\n // \\`env\\` argument of the Worker's fetch handler.\n}\n`\n}\n\n/**\n * wrangler.jsonc's plain-text settings, in one `vars` object (a second one would replace the\n * first), and the Email Service binding when anything sends mail.\n */\nfunction wranglerVars(opts: ScaffoldOptions): string {\n const digest = hasExample(opts, 'digest')\n const social = hasExample(opts, 'social')\n const checkout = hasExample(opts, 'checkout')\n const newsletter = hasExample(opts, 'newsletter')\n const emailAuth = emailSignIn(opts)\n const comments = [\n ...(opts.auth === 'access'\n ? ['Cloudflare Access (README). Until both are set, the Worker refuses every request.']\n : []),\n ...(emailAuth\n ? [\n 'Sign-in links go out through Email Service (README). AUTH_FROM must be an address on a',\n 'domain you have onboarded; until it is set, sign-in fails with a clear error.',\n ]\n : []),\n ...(digest\n ? [\n \"The weekly digest (README): who gets it, who sends it, and the deployed app's URL,\",\n 'which the browser opens. Until they are set, each run is recorded as skipped.',\n ]\n : []),\n ...(social\n ? [\n 'Reminders to connect LinkedIn again go out through Email Service from REMINDER_FROM, an',\n `address on a domain you have onboarded, with links to APP_URL (README). Until both are`,\n 'set, no reminder is sent.',\n ]\n : []),\n ...(checkout\n ? [\n 'Receipts for paid orders go out through Email Service from RECEIPT_FROM, an address',\n 'on a domain you have onboarded (README). Until it is set, no receipt is sent.',\n ]\n : []),\n ...(newsletter\n ? [\n 'The newsletter sends through Amazon SES (README): the region your sending identity is',\n 'verified in, its From address, and the SNS topic SES reports bounces and complaints to.',\n ]\n : []),\n ]\n const names = [\n ...(opts.auth === 'access' ? ['ACCESS_TEAM_DOMAIN', 'ACCESS_AUD'] : []),\n ...(emailAuth ? ['AUTH_FROM'] : []),\n ...(digest ? ['DIGEST_TO', 'DIGEST_FROM', 'APP_URL'] : []),\n ...(social ? ['REMINDER_FROM', ...(digest ? [] : ['APP_URL'])] : []),\n ...(checkout ? ['RECEIPT_FROM'] : []),\n ...(newsletter ? ['AWS_REGION', 'NEWSLETTER_FROM', 'SNS_TOPIC_ARN'] : []),\n ]\n if (names.length === 0) return ''\n const entries = names.map((name) => `\"${name}\": \"\"`)\n const line = ` \"vars\": { ${entries.join(', ')} },`\n const vars =\n line.length <= 100\n ? line\n : ` \"vars\": {\\n${entries.map((entry) => ` ${entry},`).join('\\n')}\\n },`\n return `\n${comments.map((comment) => ` // ${comment}`).join('\\n')}${emailAuth || digest || checkout || social ? '\\n \"send_email\": [{ \"name\": \"EMAIL\" }],' : ''}\n${vars}`\n}\n\n/** One `queues` object for every example that has a queue (a second one would replace the first). */\nfunction wranglerQueues(opts: ScaffoldOptions): string {\n const queues = [\n ...(hasExample(opts, 'live')\n ? [\n {\n comment: [\n \"Events for /ops: POST /api/events sends them, and the Worker's queue handler takes them in\",\n 'batches of up to 100, or whatever arrived within a second.',\n ],\n binding: 'EVENTS',\n queue: `${packageName(opts.name)}-events`,\n consumer: ['\"max_batch_size\": 100', '\"max_batch_timeout\": 1'],\n },\n ]\n : []),\n ...(hasExample(opts, 'newsletter')\n ? [\n {\n comment: [\n 'Newsletter sends (worker/newsletter.ts): one message of 25 readers at a time, so SES',\n 'is called at a steady pace. A throttled message is retried after 30 seconds.',\n ],\n binding: 'NEWSLETTER',\n queue: newsletterQueue(opts),\n consumer: [\n '\"max_batch_size\": 1',\n '\"max_concurrency\": 1',\n '\"max_retries\": 10',\n '\"retry_delay\": 30',\n ],\n },\n ]\n : []),\n ]\n if (queues.length === 0) return ''\n return `\n${queues.flatMap((q) => q.comment.map((line) => ` // ${line}`)).join('\\n')}\n \"queues\": {\n${jsoncArray(\n ' ',\n 'producers',\n queues.map((q) => `{ \"binding\": \"${q.binding}\", \"queue\": \"${q.queue}\" }`),\n)}\n \"consumers\": [\n${queues\n .map(\n (q) => ` {\n \"queue\": \"${q.queue}\",\n${q.consumer.map((line) => ` ${line},`).join('\\n')}\n },`,\n )\n .join('\\n')}\n ],\n },`\n}\n\n/** A subscription plan needs an account to belong to: checkout with accounts bills one. */\nfunction usesBilling(opts: ScaffoldOptions): boolean {\n return hasExample(opts, 'checkout') && hasAccounts(opts)\n}\n\n/** Accounts of any kind: users, sessions, and API writes that need a signed-in user. */\nfunction hasAccounts(opts: ScaffoldOptions): boolean {\n return emailSignIn(opts) || oauthSignIn(opts)\n}\n\n/** Sign-in by an emailed one-time link (`handleAuth`). */\nfunction emailSignIn(opts: ScaffoldOptions): boolean {\n return opts.auth === 'email' || opts.auth === 'email,oauth'\n}\n\n/**\n * `--auth`: `access`, `email`, `oauth`, or `email,oauth` (either order); `null` when absent,\n * `'invalid'` for anything else, including `access` combined with a sign-in method.\n */\nexport function parseAuth(raw: string | undefined): Auth | null | 'invalid' {\n const parts = [\n ...new Set(\n (raw ?? '')\n .toLowerCase()\n .split(',')\n .map((p) => p.trim()),\n ),\n ].filter(Boolean)\n if (parts.length === 0) return null\n const key = parts.sort().join(',')\n return key === 'access' || key === 'email' || key === 'oauth' || key === 'email,oauth'\n ? key\n : 'invalid'\n}\n\n/** Sign-in with GitHub, Google and LinkedIn (`handleOAuth`). */\nfunction oauthSignIn(opts: ScaffoldOptions): boolean {\n return opts.auth === 'oauth' || opts.auth === 'email,oauth'\n}\n\n/** The newsletter's queue, named after the app like every other resource. */\nfunction newsletterQueue(opts: ScaffoldOptions): string {\n return `${packageName(opts.name)}-newsletter`\n}\n\nfunction hasExample(opts: ScaffoldOptions, example: Example): boolean {\n return opts.examples?.includes(example) ?? false\n}\n\n/**\n * Examples that live in `SyncRoom`s: the board and the notes (at /api/rooms/:name), and the\n * import's job progress (a read-only room at /api/jobs/:id).\n */\n/** The Analytics Engine dataset for `--example usage`: one per app, named after it. */\nfunction usageDataset(opts: ScaffoldOptions): string {\n return `${packageName(opts.name)\n .replace(/[^a-z0-9_]/g, '_')\n .replace(/^[^a-z_]/, '_$&')}_usage`\n}\n\n/**\n * Examples with requests that cost money (storage, a browser) or put content on the app's\n * origin (a published page): rate-limited per caller.\n */\nfunction usesLimiter(opts: ScaffoldOptions): boolean {\n return (\n hasExample(opts, 'files') ||\n hasExample(opts, 'export') ||\n hasExample(opts, 'publish') ||\n hasExample(opts, 'digest') ||\n hasExample(opts, 'search') ||\n hasExample(opts, 'checkout') ||\n hasExample(opts, 'newsletter') ||\n hasExample(opts, 'social') ||\n emailSignIn(opts)\n )\n}\n\n/** Examples that keep tables in D1, bound as DB. */\nfunction usesD1(opts: ScaffoldOptions): boolean {\n return (\n hasExample(opts, 'crud') ||\n hasExample(opts, 'publish') ||\n hasExample(opts, 'webhooks') ||\n hasExample(opts, 'digest') ||\n hasExample(opts, 'search') ||\n hasExample(opts, 'checkout') ||\n hasExample(opts, 'newsletter') ||\n hasAccounts(opts)\n )\n}\n\n/** Examples that call Workers AI: the Agents SDK ones, and search's embeddings. */\nfunction usesWorkersAi(opts: ScaffoldOptions): boolean {\n return usesAgents(opts) || hasExample(opts, 'search')\n}\n\n/** Examples on Cloudflare's Agents SDK: routed under /agents/*, calling Workers AI. */\nfunction usesAgents(opts: ScaffoldOptions): boolean {\n return hasExample(opts, 'agent') || hasExample(opts, 'voice')\n}\n\nfunction usesRooms(opts: ScaffoldOptions): boolean {\n return (\n hasExample(opts, 'board') ||\n hasExample(opts, 'notes') ||\n hasExample(opts, 'import') ||\n hasExample(opts, 'webhooks') ||\n hasExample(opts, 'checkout') ||\n hasExample(opts, 'newsletter')\n )\n}\n\n/**\n * Worker code that extends a runtime class (the Agents SDK's Durable Object, a Workflow)\n * needs Cloudflare's runtime types, which clash with the DOM's: those apps type-check\n * worker/ on its own (tsconfig.worker.json).\n */\nfunction needsWorkerTypes(opts: ScaffoldOptions): boolean {\n return usesAgents(opts) || hasExample(opts, 'import') || hasExample(opts, 'social')\n}\n\n/**\n * The client runtime. Preact by default; React with the `agent` example, because the Agents\n * SDK's hooks (`useAgent`, `useAgentChat`) call React 19's `use()`, which preact/compat\n * does not implement — the build fails on the missing export.\n */\nfunction runtimeOf(opts: ScaffoldOptions): Runtime {\n return opts.runtime ?? (hasExample(opts, 'agent') ? 'react' : 'preact')\n}\n\nfunction cfApiTs(opts: ScaffoldOptions): string {\n const imports = hasExample(opts, 'import')\n const files = hasExample(opts, 'files')\n const usage = hasExample(opts, 'usage')\n const crud = hasExample(opts, 'crud')\n const live = hasExample(opts, 'live')\n const publish = hasExample(opts, 'publish')\n const webhooks = hasExample(opts, 'webhooks')\n const digest = hasExample(opts, 'digest')\n const search = hasExample(opts, 'search')\n const checkout = hasExample(opts, 'checkout')\n const newsletter = hasExample(opts, 'newsletter')\n const billing = usesBilling(opts)\n const social = hasExample(opts, 'social')\n return `import { defineApi, ${imports || files || usage || crud || live || publish || webhooks || digest || search || checkout || newsletter || social ? 'endpoint, ' : ''}stream } from '@cascivo/app/api'\n${crud ? `import { parseTablePage, parseTableQuery } from '@cascivo/app/db'\\n` : ''}${files ? `import { parseStoredFile } from '@cascivo/app/uploads'\\n` : ''}${imports ? `import { parseImportRequest, parseStarted } from './import-job'\\n` : ''}${usage ? `import { parseUsageReport } from './usage'\\n` : ''}${crud ? `import { parseCustomer, parseCustomerInput, parseDeleted } from './customers'\\n` : ''}${live ? `import { ops, parseAccepted } from './ops'\\n` : ''}${publish ? `import { parsePage, parsePageInput, parsePageSummary } from './pages'\\n` : ''}${webhooks ? `import { parseDeliveries, parseTestResult } from './webhooks'\\n` : ''}${digest ? `import { parseDigestRun, parseDigestRuns } from './digest'\\n` : ''}${search ? `import { parseIndexed, parseSearchQuery, parseSearchResult } from './search'\\n` : ''}${billing ? `import { parseBilling, parseRedirect, parseSyncInput } from './billing'\\n` : ''}${checkout ? `import { parseCheckoutStarted, parseOrder } from './checkout'\\n` : ''}${\n newsletter\n ? `import {\n parseConfirmed,\n parseEmailInput,\n parseIssue,\n parseIssueInput,\n parseKeyInput,\n parseOverview,\n parsePreview,\n parseSubscribed,\n parseTokenInput,\n} from './newsletter'\\n`\n : ''\n }${social ? `import { parsePostInput, parseScheduledPost, parseSocial } from './social'\\n` : ''}\n/**\n * The contract between the browser and the Worker. Both import this file: the Worker serves\n * it with \\`createHandler\\`, the app calls it with \\`createClient\\`, and a change that breaks\n * either side is a type error. Add an endpoint here, then its handler in worker/index.ts.\n */\n\n/** How many ticks one stream sends before it ends. */\nexport const TICKS_PER_STREAM = 30\n\nexport interface Tick {\n n: number\n /** ISO timestamp, set by the Worker. */\n at: string\n}\n\n/**\n * Parses one streamed tick. It crosses the network, so it is checked rather than cast —\n * \\`JSON.parse\\` returns \\`any\\`, and \\`as Tick\\` would prove nothing.\n */\nexport function parseTick(raw: unknown): Tick {\n if (typeof raw === 'object' && raw !== null) {\n const { n, at } = raw as Record<string, unknown>\n if (typeof n === 'number' && typeof at === 'string') return { n, at }\n }\n throw new Error('Malformed tick')\n}\n\nexport const api = defineApi({\n ticks: stream({ method: 'GET', path: '/api/ticks', event: parseTick }),${\n imports\n ? `\n // Starts a CSV import; returns the job id to watch (src/import-page.ts).\n startImport: endpoint({\n method: 'POST',\n path: '/api/import',\n input: parseImportRequest,\n output: parseStarted,\n }),`\n : ''\n }${\n files\n ? `\n // The stored files (the uploads themselves are \\`handleUploads\\` in the Worker).\n listFiles: endpoint({\n method: 'GET',\n path: '/api/files',\n output: (raw) => {\n if (!Array.isArray(raw)) throw new Error('Expected a list of files')\n return raw.map(parseStoredFile)\n },\n }),`\n : ''\n }${\n usage\n ? `\n // The last 24 hours of API usage, read from Analytics Engine by the Worker.\n usage: endpoint({ method: 'GET', path: '/api/usage', output: parseUsageReport }),`\n : ''\n }${\n live\n ? `\n // Events for the /ops dashboard, at most 100 at a time, onto the EVENTS queue.\n sendEvents: endpoint({\n method: 'POST',\n path: '/api/events',\n input: ops.parseEvents,\n output: parseAccepted,\n }),`\n : ''\n }${\n publish\n ? `\n // Publishes a view as a page (checked against the manifests), and reads one back.\n publishPage: endpoint({\n method: 'POST',\n path: '/api/pages',\n input: parsePageInput,\n output: parsePageSummary,\n }),\n getPage: endpoint({ method: 'GET', path: '/api/pages/:slug', output: parsePage }),`\n : ''\n }${\n webhooks\n ? `\n // The last 50 webhook deliveries (they arrive at /api/webhooks/github, signed).\n listDeliveries: endpoint({ method: 'GET', path: '/api/webhooks', output: parseDeliveries }),\n // Signs a sample delivery with WEBHOOK_SECRET and runs it through the same path.\n sendTestDelivery: endpoint({\n method: 'POST',\n path: '/api/webhook-test',\n output: parseTestResult,\n }),`\n : ''\n }${\n digest\n ? `\n // The weekly digest's recent runs, and one run now (the Cron Trigger runs it on Mondays).\n digestRuns: endpoint({ method: 'GET', path: '/api/digest/runs', output: parseDigestRuns }),\n runDigest: endpoint({ method: 'POST', path: '/api/digest/run', output: parseDigestRun }),`\n : ''\n }${\n search\n ? `\n // Help articles by meaning (Vectorize), or by keyword in vite dev.\n search: endpoint({\n method: 'POST',\n path: '/api/search',\n input: parseSearchQuery,\n output: parseSearchResult,\n }),\n // Embeds every article into the Vectorize index.\n indexArticles: endpoint({ method: 'POST', path: '/api/search/index', output: parseIndexed }),`\n : ''\n }${\n checkout\n ? `\n // Opens a Stripe Checkout page for the product; the browser goes to its url.\n startCheckout: endpoint({ method: 'POST', path: '/api/checkout', output: parseCheckoutStarted }),\n // An order, checked with Stripe while it is pending (Stripe's webhook settles it too).\n getOrder: endpoint({ method: 'GET', path: '/api/orders/:id', output: parseOrder }),`\n : ''\n }${\n billing\n ? `\n // The signed-in user's subscription (worker/billing.ts), and the ways to change it.\n getBilling: endpoint({ method: 'GET', path: '/api/billing', output: parseBilling }),\n startSubscription: endpoint({\n method: 'POST',\n path: '/api/billing/subscribe',\n output: parseRedirect,\n }),\n syncBilling: endpoint({\n method: 'POST',\n path: '/api/billing/sync',\n input: parseSyncInput,\n output: parseBilling,\n }),\n openBillingPortal: endpoint({\n method: 'POST',\n path: '/api/billing/portal',\n output: parseRedirect,\n }),`\n : ''\n }${\n newsletter\n ? `\n // Signing up sends a confirmation link; only confirmed readers get issues.\n subscribe: endpoint({\n method: 'POST',\n path: '/api/newsletter/subscribe',\n input: parseEmailInput,\n output: parseSubscribed,\n }),\n confirmSubscription: endpoint({\n method: 'POST',\n path: '/api/newsletter/confirm',\n input: parseTokenInput,\n output: parseConfirmed,\n }),\n // The composer's calls, each carrying NEWSLETTER_KEY.\n newsletterOverview: endpoint({\n method: 'POST',\n path: '/api/newsletter/overview',\n input: parseKeyInput,\n output: parseOverview,\n }),\n previewIssue: endpoint({\n method: 'POST',\n path: '/api/newsletter/preview',\n input: parseIssueInput,\n output: parsePreview,\n }),\n sendIssue: endpoint({\n method: 'POST',\n path: '/api/newsletter/issues',\n input: parseIssueInput,\n output: parseIssue,\n }),`\n : ''\n }${\n crud\n ? `\n // One page of customers for DataTable's query (sort, search, filters, page).\n customers: endpoint({\n method: 'POST',\n path: '/api/customers/query',\n input: parseTableQuery,\n output: (raw) => parseTablePage(raw, parseCustomer),\n }),\n createCustomer: endpoint({\n method: 'POST',\n path: '/api/customers',\n input: parseCustomerInput,\n output: parseCustomer,\n }),\n updateCustomer: endpoint({\n method: 'PUT',\n path: '/api/customers/:id',\n input: parseCustomerInput,\n output: parseCustomer,\n }),\n deleteCustomer: endpoint({ method: 'DELETE', path: '/api/customers/:id', output: parseDeleted }),`\n : ''\n }${\n social\n ? `\n // The signed-in user's connected accounts and posts (worker/social.ts).\n getSocial: endpoint({ method: 'GET', path: '/api/social', output: parseSocial }),\n schedulePost: endpoint({\n method: 'POST',\n path: '/api/social/posts',\n input: parsePostInput,\n output: parseScheduledPost,\n }),\n cancelPost: endpoint({\n method: 'POST',\n path: '/api/social/posts/:id/cancel',\n output: parseScheduledPost,\n }),`\n : ''\n }\n})\n`\n}\n\nfunction cfWorkerTs(opts: ScaffoldOptions): string {\n const rooms = usesRooms(opts)\n const agent = hasExample(opts, 'agent')\n const imports = hasExample(opts, 'import')\n const files = hasExample(opts, 'files')\n const exports = hasExample(opts, 'export')\n const usage = hasExample(opts, 'usage')\n const crud = hasExample(opts, 'crud')\n const live = hasExample(opts, 'live')\n const voice = hasExample(opts, 'voice')\n const publish = hasExample(opts, 'publish')\n const webhooks = hasExample(opts, 'webhooks')\n const digest = hasExample(opts, 'digest')\n const search = hasExample(opts, 'search')\n const checkout = hasExample(opts, 'checkout')\n const newsletter = hasExample(opts, 'newsletter')\n const billing = usesBilling(opts)\n const d1 = usesD1(opts)\n const ai = usesAgents(opts)\n const limiter = usesLimiter(opts)\n const access = opts.auth === 'access'\n const emailAuth = emailSignIn(opts)\n const oauth = oauthSignIn(opts)\n const accounts = hasAccounts(opts)\n const social = hasExample(opts, 'social')\n const guards = [\n ...(access ? ['requireAccess'] : []),\n ...(limiter ? ['clientIp', 'rateLimit'] : []),\n ]\n const custom = rooms || ai || files || exports || access || live || limiter || publish || accounts\n const isAsync =\n ai ||\n files ||\n exports ||\n access ||\n limiter ||\n webhooks ||\n publish ||\n checkout ||\n newsletter ||\n accounts\n // Rooms the server writes: never opened through /api/rooms/:name, where clients may write.\n const serverRooms = [\n ...(imports ? ['job-'] : []),\n ...(webhooks ? ['webhooks$'] : []),\n ...(checkout ? ['order-'] : []),\n ...(newsletter ? ['issue-'] : []),\n ]\n // Writes that need no signed-in user even with accounts: webhooks carry a signature instead of a\n // session, and a newsletter's readers have no account.\n const signedPaths = [\n ...(webhooks ? ['/api/webhooks/'] : []),\n ...(checkout ? ['/api/stripe/'] : []),\n ...(newsletter ? ['/api/sns/'] : []),\n ]\n const readerPaths = newsletter\n ? ['/api/newsletter/subscribe', '/api/newsletter/confirm', '/api/newsletter/unsubscribe']\n : []\n const openPaths = [...signedPaths, ...readerPaths]\n return `${usage ? `import type { AnalyticsDataset } from '@cascivo/app/analytics'\\n` : ''}${d1 ? `import type { Database } from '@cascivo/app/db'\\n` : ''}${exports ? `import { handleExport } from '@cascivo/app/export'\\n` : ''}import { createHandler${publish ? ', HttpError' : ''} } from '@cascivo/app/api'\n${accounts ? `import { ${emailAuth ? 'handleAuth, ' : ''}requireUser } from '@cascivo/app/auth-server'\\n` : ''}${oauth ? `import { github, google, linkedin } from '@cascivo/app/oauth'\\nimport type { OAuthProvider } from '@cascivo/app/oauth'\\nimport { handleOAuth } from '@cascivo/app/oauth-server'\\n` : ''}${guards.length > 0 || webhooks || accounts ? `import { ${[...guards, 'guardResponse'].sort().join(', ')} } from '@cascivo/app/guard'\\n${limiter ? `import type { RateLimiter } from '@cascivo/app/guard'\\n` : ''}` : ''}${imports ? `import { jobReporter } from '@cascivo/app/jobs-server'\\n` : ''}${\n files\n ? `import { handleUploads, listUploads } from '@cascivo/app/uploads-server'\nimport type { ImageResizer, UploadBucket } from '@cascivo/app/uploads-server'\n`\n : ''\n }${\n live\n ? `import { recordLive } from '@cascivo/app/live-server'\nimport type { LiveBatch, LiveQueue } from '@cascivo/app/live-server'\n`\n : ''\n }${\n rooms || live\n ? `import { roomResponse } from '@cascivo/app/sync-server'\nimport type { RoomNamespace } from '@cascivo/app/sync-server'\n`\n : ''\n }${\n exports\n ? `import puppeteer from '@cloudflare/puppeteer'\nimport type { BrowserWorker } from '@cloudflare/puppeteer'\n`\n : ''\n }${ai ? `import { routeAgentRequest } from 'agents'\\n` : ''}import { api, TICKS_PER_STREAM } from '../src/api'\nimport type { Tick } from '../src/api'\n${imports ? `import { importJob } from '../src/import-job'\\n` : ''}${files ? `import { uploads } from '../src/upload-policy'\\n` : ''}${usage ? `import { usageMetrics } from '../src/usage'\\nimport { usageReport } from './usage'\\n` : ''}${live ? `import { OPS_ROOM, ops } from '../src/ops'\\n` : ''}${emailAuth ? `import { sendSignInLink } from './auth'\\nimport type { SignInSender } from './auth'\\n` : ''}${crud ? `import * as customerStore from './customers'\\n` : ''}${publish ? `import * as pageStore from './pages'\\nimport { renderPageHtml } from './page-html'\\nimport type { Assets } from './page-html'\\n${exports ? `import { pagePreview } from './page-preview'\\n` : ''}` : ''}${webhooks ? `import * as webhookStore from './webhooks'\\nimport { DELIVERIES_ROOM } from '../src/webhooks'\\n` : ''}${digest ? `import * as digestJob from './digest'\\nimport type { DigestSender } from './digest'\\n` : ''}${search ? `import * as articleSearch from './search'\\nimport type { ${ai ? '' : 'Embedder, '}VectorIndex } from './search'\\n` : ''}${billing ? `import * as billingStore from './billing'\\n` : ''}${social ? `import * as socialStore from './social'\\nimport type { ReminderSender, SocialMediaBucket, SocialPostParams } from './social'\\n` : ''}${checkout ? `import * as orderStore from './checkout'\\nimport type { ReceiptSender } from './checkout'\\nimport { ORDER_ID, orderRoom } from '../src/checkout'\\n` : ''}${newsletter ? `import * as newsletterStore from './newsletter'\\nimport type { NewsletterBatch, NewsletterQueue } from './newsletter'\\nimport { ISSUE_ID, issueRoom } from '../src/newsletter'\\n` : ''}${\n rooms\n ? `\n// The Durable Object class behind every room. wrangler.jsonc binds it as ROOMS, and it must be\n// exported from the Worker's main module.\nexport { SyncRoom } from '@cascivo/app/sync-server'\n`\n : ''\n }${\n agent\n ? `\n// The Durable Object behind /assistant: one per conversation (worker/assistant.ts).\nexport { Assistant } from './assistant'\n`\n : ''\n }${\n voice\n ? `\n// The Durable Object behind /voice: one per conversation (worker/voice.ts).\nexport { Voice } from './voice'\n`\n : ''\n }${\n live\n ? `\n// The Durable Object behind /ops: the last two minutes, per second (src/ops.ts).\nexport { LiveRoom } from '@cascivo/app/live-server'\n`\n : ''\n }${\n imports\n ? `\n// The Workflow behind /import (worker/import-job.ts), bound as IMPORT_JOB.\nexport { ImportJob } from './import-job'\n`\n : ''\n }${\n social\n ? `\n// The Workflow behind each scheduled post (worker/social-post.ts), bound as SOCIAL_POST.\nexport { SocialPost } from './social-post'\n`\n : ''\n }\n/**\n * Add bindings (KV, D1, R2, Durable Objects, Workers AI) in wrangler.jsonc and type them\n * here; every handler receives them as \\`env\\`.\n */\n${\n rooms ||\n ai ||\n files ||\n exports ||\n usage ||\n d1 ||\n access ||\n live ||\n accounts ||\n social ||\n webhooks ||\n digest ||\n search ||\n checkout ||\n newsletter\n ? `export interface Env {${ai ? '\\n /** Workers AI, bound in wrangler.jsonc. */\\n AI: Ai' : search ? '\\n /** Workers AI, bound in wrangler.jsonc. */\\n AI: Embedder' : ''}${search ? '\\n ARTICLES_INDEX: VectorIndex' : ''}${rooms ? '\\n ROOMS: RoomNamespace<unknown>' : ''}${imports ? '\\n IMPORT_JOB: Workflow<{ csv: string }>' : ''}${files ? '\\n FILES: UploadBucket\\n IMAGES: ImageResizer' : ''}${exports ? '\\n BROWSER: BrowserWorker' : ''}${usage ? '\\n USAGE: AnalyticsDataset\\n /** Secrets for reading Analytics Engine back (see README). */\\n CF_ACCOUNT_ID?: string\\n CF_API_TOKEN?: string' : ''}${d1 ? '\\n DB: Database' : ''}${publish ? '\\n ASSETS: Assets' : ''}${live ? '\\n LIVE: RoomNamespace<unknown>\\n EVENTS: LiveQueue' : ''}${limiter ? '\\n LIMITER: RateLimiter' : ''}${access ? '\\n /** Set in wrangler.jsonc (see README). */\\n ACCESS_TEAM_DOMAIN: string\\n ACCESS_AUD: string' : ''}${webhooks ? '\\n /** The webhook signing secret: `wrangler secret put WEBHOOK_SECRET` (.dev.vars locally). */\\n WEBHOOK_SECRET: string' : ''}${emailAuth || digest || checkout || social ? `\\n EMAIL: ${[emailAuth ? 'SignInSender' : '', digest ? 'DigestSender' : '', checkout ? 'ReceiptSender' : '', social ? 'ReminderSender' : ''].filter(Boolean).join(' & ')}` : ''}${emailAuth ? '\\n /** The From address of sign-in emails, set in wrangler.jsonc. */\\n AUTH_FROM: string' : ''}${oauth ? '\\n /** Sign-in with GitHub, Google and LinkedIn: `wrangler secret put` (.dev.vars locally). A provider is\\n * offered once both its id and secret are set; AUTH_SECRET seals the sign-in state. */\\n AUTH_SECRET?: string\\n GITHUB_CLIENT_ID?: string\\n GITHUB_CLIENT_SECRET?: string\\n GOOGLE_CLIENT_ID?: string\\n GOOGLE_CLIENT_SECRET?: string\\n LINKEDIN_CLIENT_ID?: string\\n LINKEDIN_CLIENT_SECRET?: string' : social ? \"\\n /** Seals connected accounts' tokens, and LinkedIn's app: `wrangler secret put` (.dev.vars\\n * locally). LinkedIn is offered once both its values are set. */\\n AUTH_SECRET?: string\\n LINKEDIN_CLIENT_ID?: string\\n LINKEDIN_CLIENT_SECRET?: string\" : ''}${social ? '\\n /** Bluesky: an ES256 private JWK (README); unset, the app is a public client. */\\n BLUESKY_PRIVATE_JWK?: string\\n /** A Buffer app client (README); Buffer is offered once its id is set. */\\n BUFFER_CLIENT_ID?: string\\n BUFFER_CLIENT_SECRET?: string\\n /** A Meta app with the Threads use case (README); Threads is offered once both are set. */\\n THREADS_APP_ID?: string\\n THREADS_APP_SECRET?: string\\n SOCIAL_POST: Workflow<SocialPostParams>\\n SOCIAL_MEDIA: SocialMediaBucket\\n /** Reconnect reminders (worker/social.ts), set in wrangler.jsonc. */\\n REMINDER_FROM: string' + (digest ? '' : '\\n APP_URL: string') : ''}${digest ? '\\n /** The weekly digest (worker/digest.ts), set in wrangler.jsonc. */\\n DIGEST_TO: string\\n DIGEST_FROM: string\\n APP_URL: string' : ''}${checkout ? '\\n /** The From address of receipts, set in wrangler.jsonc. */\\n RECEIPT_FROM: string\\n /** Stripe secrets: `wrangler secret put` (.dev.vars locally). Unset until you add them. */\\n STRIPE_SECRET_KEY?: string\\n STRIPE_WEBHOOK_SECRET?: string' : ''}${newsletter ? '\\n NEWSLETTER: NewsletterQueue\\n /** The newsletter (worker/newsletter.ts), set in wrangler.jsonc. */\\n AWS_REGION: string\\n NEWSLETTER_FROM: string\\n SNS_TOPIC_ARN: string\\n /** Secrets: `wrangler secret put` (.dev.vars locally). Unset until you add them. */\\n AWS_ACCESS_KEY_ID?: string\\n AWS_SECRET_ACCESS_KEY?: string\\n NEWSLETTER_KEY?: string' : ''}\n}`\n : `// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- bindings are added as members\nexport interface Env {}`\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n${\n oauth\n ? `\n/** The sign-in providers with both an id and a secret set; the others are not offered. */\nfunction oauthProviders(env: Env): OAuthProvider[] {\n const providers: OAuthProvider[] = []\n if (env.GITHUB_CLIENT_ID && env.GITHUB_CLIENT_SECRET) {\n providers.push(\n github({ clientId: env.GITHUB_CLIENT_ID, clientSecret: env.GITHUB_CLIENT_SECRET }),\n )\n }\n if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) {\n providers.push(\n google({ clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET }),\n )\n }\n if (env.LINKEDIN_CLIENT_ID && env.LINKEDIN_CLIENT_SECRET) {\n providers.push(\n linkedin({ clientId: env.LINKEDIN_CLIENT_ID, clientSecret: env.LINKEDIN_CLIENT_SECRET }),\n )\n }\n return providers\n}\n`\n : ''\n}${\n limiter\n ? `\n/**\n * Requests that each count against LIMITER:\n${[\n emailAuth ? 'a sign-in email' : '',\n digest ? 'a digest sent now (it starts a browser)' : '',\n search ? 'indexing the articles (it embeds every one)' : '',\n checkout ? 'a checkout started (it creates a Stripe session and an order)' : '',\n billing ? 'a subscription checkout or billing portal opened' : '',\n newsletter ? 'a newsletter sign-up (it sends an email), and each use of the newsletter key' : '',\n files ? 'a new upload (not each part of one)' : '',\n exports ? 'an export' : '',\n publish ? 'a published page' : '',\n social ? 'connecting an account (Mastodon registers the app with the server), or a post' : '',\n]\n .filter(Boolean)\n .map((item) => ` * - ${item}`)\n .join('\\n')}\n */\nfunction countsAgainstLimit(request: Request): boolean {\n const url = new URL(request.url)${\n search\n ? `\n if (url.pathname === '/api/search/index') return request.method === 'POST'`\n : ''\n }${\n digest\n ? `\n if (url.pathname === '/api/digest/run') return request.method === 'POST'`\n : ''\n }${\n checkout\n ? `\n if (url.pathname === '/api/checkout') return request.method === 'POST'`\n : ''\n }${\n billing\n ? `\n if (url.pathname === '/api/billing/subscribe' || url.pathname === '/api/billing/portal') {\n return request.method === 'POST'\n }`\n : ''\n }${\n newsletter\n ? `\n if (/^\\\\/api\\\\/newsletter\\\\/(subscribe|overview|preview|issues)$/.test(url.pathname)) {\n return request.method === 'POST'\n }`\n : ''\n }${\n emailAuth\n ? `\n if (url.pathname === '/api/auth/start') return request.method === 'POST'`\n : ''\n }${\n social\n ? `\n if (/^\\\\/api\\\\/connections\\\\/[a-z-]+$/.test(url.pathname)) return request.method === 'GET'\n if (url.pathname === '/api/social/posts') return request.method === 'POST'\n if (url.pathname.startsWith('/api/social/images')) return request.method !== 'GET'`\n : ''\n }${\n publish\n ? `\n if (url.pathname === '/api/pages') return request.method === 'POST'`\n : ''\n }${\n files\n ? `\n if (url.pathname === uploads.path) {\n const step = url.searchParams.get('multipart')\n return (request.method === 'PUT' && step === null) || step === 'start'\n }`\n : ''\n }\n return ${exports ? \"url.pathname === '/api/export'\" : 'false'}\n}\n`\n : ''\n }\n/**\n * One handler per endpoint in src/api.ts, typed from it. A stream handler is an async\n * generator: each \\`yield\\` is one server-sent event, and returning ends the stream. When the\n * client disconnects, \\`signal\\` aborts.\n */\nconst handleApi = createHandler<typeof api, Env>(api, {\n ticks: async function* ({ signal }) {\n for (let n = 1; n <= TICKS_PER_STREAM && !signal.aborted; n++) {\n const tick: Tick = { n, at: new Date().toISOString() }\n yield tick\n await sleep(1000)\n }\n },${\n imports\n ? `\n // The job's room exists (as \"queued\") before the Workflow starts, so the page has\n // something to show at once.\n startImport: async ({ body, env }) => {\n const id = crypto.randomUUID()\n await jobReporter(importJob, env.ROOMS, id).queued()\n await env.IMPORT_JOB.create({ id, params: { csv: body.csv } })\n return { id }\n },`\n : ''\n }${files ? `\\n listFiles: ({ env }) => listUploads(env.FILES),` : ''}${\n usage\n ? `\n usage: ({ env }) =>\n usageReport(\n env.CF_ACCOUNT_ID && env.CF_API_TOKEN\n ? { accountId: env.CF_ACCOUNT_ID, apiToken: env.CF_API_TOKEN }\n : null,\n ),`\n : ''\n }${\n crud\n ? `\n customers: ({ body, env }) => customerStore.listCustomers(env.DB, body),\n createCustomer: ({ body, env }) => customerStore.createCustomer(env.DB, body),\n updateCustomer: ({ params, body, env }) => customerStore.updateCustomer(env.DB, params.id, body),\n deleteCustomer: ({ params, env }) => customerStore.deleteCustomer(env.DB, params.id),`\n : ''\n }${\n publish\n ? `\n publishPage: ({ body, env }) => pageStore.publishPage(env.DB, body),\n getPage: ({ params, env }) => pageStore.getPage(env.DB, params.slug),`\n : ''\n }${\n webhooks\n ? `\n listDeliveries: ({ env }) => webhookStore.listDeliveries(env.DB),\n sendTestDelivery: ({ request, env }) => webhookStore.sendTestDelivery(request.url, env),`\n : ''\n }${\n search\n ? `\n search: ({ body, env }) => articleSearch.search(env, body.q),\n indexArticles: ({ env }) => articleSearch.indexArticles(env),`\n : ''\n }${\n checkout\n ? `\n startCheckout: ({ request, env }) => orderStore.startCheckout(env, new URL(request.url).origin),\n getOrder: ({ params, request, env }) =>\n orderStore.getOrder(env, params.id, new URL(request.url).origin),`\n : ''\n }${\n billing\n ? `\n getBilling: ({ request, env }) => billingStore.getBilling(env, request),\n startSubscription: ({ request, env }) =>\n billingStore.startSubscription(env, request, new URL(request.url).origin),\n syncBilling: ({ body, request, env }) => billingStore.syncBilling(env, request, body.sessionId),\n openBillingPortal: ({ request, env }) =>\n billingStore.openPortal(env, request, new URL(request.url).origin),`\n : ''\n }${\n newsletter\n ? `\n subscribe: ({ body, request, env }) =>\n newsletterStore.subscribe(env, body.email, new URL(request.url).origin),\n confirmSubscription: ({ body, env }) => newsletterStore.confirm(env, body.token),\n newsletterOverview: ({ body, env }) => newsletterStore.overview(env, body.key),\n previewIssue: ({ body, request, env }) =>\n newsletterStore.preview(env, body, new URL(request.url).origin),\n sendIssue: ({ body, request, env }) =>\n newsletterStore.sendIssue(env, body, new URL(request.url).origin),`\n : ''\n }${\n social\n ? `\n getSocial: ({ request, env }) => socialStore.getSocial(env, request),\n schedulePost: ({ body, request, env }) => socialStore.schedulePost(env, request, body),\n cancelPost: ({ params, request, env }) => socialStore.cancelPost(env, request, params.id),`\n : ''\n }${\n digest\n ? `\n digestRuns: ({ env }) => digestJob.listRuns(env.DB),\n runDigest: ({ request, env }) =>\n digestJob.runDigest(\n env,\n () => puppeteer.launch(env.BROWSER),\n 'manual',\n new URL(request.url).origin,\n ),`\n : ''\n }${\n live\n ? `\n // Each event is placed by the Worker's clock: a browser's is not trusted to say when.\n sendEvents: async ({ body, env }) => {\n const at = Date.now()\n if (body.length > 0) {\n await env.EVENTS.sendBatch(body.map((event) => ({ body: { at, values: event.values } })))\n }\n return { accepted: body.length }\n },`\n : ''\n }\n})\n${\n usage\n ? `\n/** Every API request, recorded in Analytics Engine; src/usage.ts names the columns. */\nasync function handleAndRecord(request: Request, env: Env): Promise<Response> {\n const started = Date.now()\n const response = await handleApi(request, env)\n usageMetrics.write(env.USAGE, {\n path: new URL(request.url).pathname,\n method: request.method,\n status: response.status,\n duration_ms: Date.now() - started,\n })\n return response\n}\n`\n : ''\n}\n// wrangler.jsonc routes only ${ai ? '/api/* and /agents/*' : '/api/*'} here; everything else is a static asset or index.html.\nexport default {\n${\n custom\n ? ` ${isAsync ? 'async ' : ''}fetch(request: Request, env: Env): Promise<Response>${isAsync ? '' : ' | Response'} {${\n access\n ? `\n // Cloudflare Access is in front of the app (README); this refuses a request that came\n // around it (straight to *.workers.dev, say). \\`vite dev\\` has no Access, so not there.\n if (!import.meta.env.DEV) {\n try {\n await requireAccess(request, {\n teamDomain: env.ACCESS_TEAM_DOMAIN,\n audience: env.ACCESS_AUD,\n })\n } catch (error) {\n return guardResponse(error)\n }\n }`\n : ''\n }${\n limiter\n ? `\n if (countsAgainstLimit(request)) {\n try {\n await rateLimit(env.LIMITER, clientIp(request))\n } catch (error) {\n return guardResponse(error)\n }\n }`\n : ''\n }${\n accounts\n ? `${\n emailAuth\n ? `\n // Sign-in links and sessions: /api/auth/* is answered here (worker/auth.ts sends mail).\n const signIn = await handleAuth(env.DB, {\n sendLink: (email, url) => sendSignInLink(env.EMAIL, env.AUTH_FROM, email, url),\n exposeLink: import.meta.env.DEV,\n })(request)\n if (signIn) return signIn`\n : ''\n }${\n oauth\n ? `\n // Sign-in with GitHub, Google and LinkedIn: /api/auth/oauth/* (and /me, /signout). A failed\n // sign-in lands on /account with ?error=.\n const signInWith = await handleOAuth(env.DB, {\n secret: env.AUTH_SECRET ?? '',\n providers: oauthProviders(env),\n errorPath: '/account',\n })(request)\n if (signInWith) return signInWith`\n : ''\n }\n // Every other API write needs a signed-in user; reads stay public.${signedPaths.length > 0 ? '\\n // Webhooks carry a signature instead of a session, and are checked by it.' : ''}${readerPaths.length > 0 ? '\\n // Newsletter readers sign up, confirm and unsubscribe without an account.' : ''}\n if (${\n openPaths.length > 0\n ? `\n request.method !== 'GET' &&\n request.method !== 'HEAD' &&${openPaths\n .map((prefix) => `\\n !new URL(request.url).pathname.startsWith('${prefix}')`)\n .join(' &&')}\n `\n : \"request.method !== 'GET' && request.method !== 'HEAD'\"\n }) {\n try {\n await requireUser(env.DB, request)\n } catch (error) {\n return guardResponse(error)\n }\n }${\n social\n ? `\n // The accounts a user connects to post with (worker/social.ts): /api/connections/*, and\n // the client metadata Bluesky's servers read.\n const blueskyClient = socialStore.blueskyClient(env, request)\n if (blueskyClient) return blueskyClient\n const connected = await socialStore.connections(env)(request)\n if (connected) return connected\n // Images for posts: the user's own uploads, and the signed links Threads and Buffer fetch.\n const image =\n (await socialStore.images(env, request)) ?? (await socialStore.media(env, request))\n if (image) return image`\n : ''\n }`\n : ''\n }${\n ai\n ? `\n // /agents/<agent>/<conversation>: the WebSocket ${[agent ? 'useAgent()' : '', voice ? 'VoiceClient' : ''].filter(Boolean).join(' or ')} opens.\n const agent = await routeAgentRequest(request, env)\n if (agent) return agent`\n : ''\n }${\n files\n ? `\n // Uploads into R2 and the files they stored.${access ? '' : ' Anyone can upload: see README.'}\n const upload = await handleUploads(uploads, env.FILES, { images: env.IMAGES })(request)\n if (upload) return upload`\n : ''\n }${\n exports\n ? `\n // /api/export?page=/report&format=pdf — each export starts a browser.\n const exported = await handleExport(request, { launch: () => puppeteer.launch(env.BROWSER) })\n if (exported) return exported`\n : ''\n }${\n live\n ? `\n // The /ops dashboard's room: browsers watch it, and only the queue handler writes to it.\n if (new URL(request.url).pathname === '/api/live') {\n return roomResponse(request, env.LIVE, OPS_ROOM, { readOnly: true })\n }`\n : ''\n }${\n publish\n ? `\n // A published page: its HTML carries the page's title, description and content, for link\n // previews and readers without JavaScript (worker/page-html.ts). An unknown slug gets the\n // app itself, which says so.\n const pagePath = new URL(request.url).pathname\n const published = /^\\\\/p\\\\/([a-z0-9]{10})$/.exec(pagePath)\n if (published && request.method === 'GET') {\n try {\n const page = await pageStore.getPage(env.DB, published[1]!)${\n exports\n ? `\n const image = new URL(\\`/api/pages/\\${page.slug}/preview.png\\`, request.url).href\n return await renderPageHtml(request, page, env.ASSETS, image)`\n : `\n return await renderPageHtml(request, page, env.ASSETS, null)`\n }\n } catch (error) {\n if (!(error instanceof HttpError)) throw error\n return env.ASSETS.fetch(request)\n }\n }${\n exports\n ? `\n // Its link-preview image, rendered once by Browser Run (worker/page-preview.ts).\n const preview = /^\\\\/api\\\\/pages\\\\/([a-z0-9]{10})\\\\/preview\\\\.png$/.exec(pagePath)\n if (preview && request.method === 'GET') {\n try {\n return await pagePreview(env.DB, preview[1]!, new URL(request.url).origin, () =>\n puppeteer.launch(env.BROWSER),\n )\n } catch (error) {\n return guardResponse(error)\n }\n }`\n : ''\n }`\n : ''\n }${\n webhooks\n ? `\n const path = new URL(request.url).pathname\n // Signed deliveries from GitHub (worker/webhooks.ts); a bad signature is a 401.\n if (path === webhookStore.GITHUB_WEBHOOK_PATH && request.method === 'POST') {\n try {\n return await webhookStore.receiveGithub(request, env)\n } catch (error) {\n return guardResponse(error)\n }\n }\n // New deliveries, pushed to the /webhooks page: it may watch, never write.\n if (path === '/api/webhooks/live') {\n return roomResponse(request, env.ROOMS, DELIVERIES_ROOM, { readOnly: true })\n }`\n : ''\n }${\n checkout\n ? `\n const checkoutPath = new URL(request.url).pathname\n // Stripe's webhook (worker/checkout.ts); a bad signature is a 401.\n if (checkoutPath === orderStore.STRIPE_WEBHOOK_PATH && request.method === 'POST') {\n try {\n return await orderStore.receiveStripe(request, env${\n billing ? ', billingStore.billingHooks(env)' : ''\n })\n } catch (error) {\n return guardResponse(error)\n }\n }\n // An order's page watches its room for what Stripe reports: it may watch, never write.\n const orderLive = /^\\\\/api\\\\/orders\\\\/([^/]+)\\\\/live$/.exec(checkoutPath)\n if (orderLive && ORDER_ID.test(orderLive[1]!)) {\n return roomResponse(request, env.ROOMS, orderRoom(orderLive[1]!), { readOnly: true })\n }`\n : ''\n }${\n newsletter\n ? `\n const newsletterPath = new URL(request.url).pathname\n // One-click unsubscribe (RFC 8058) and the unsubscribe page's button.\n if (newsletterPath === '/api/newsletter/unsubscribe' && request.method === 'POST') {\n return newsletterStore.unsubscribe(request, env)\n }\n // SES bounces and complaints, delivered by SNS (worker/newsletter.ts); verified by signature.\n if (newsletterPath === '/api/sns/ses' && request.method === 'POST') {\n try {\n return await newsletterStore.receiveFeedback(request, env)\n } catch (error) {\n return guardResponse(error)\n }\n }\n // An issue's sending progress, for the composer: it may watch, never write.\n const issueLive = /^\\\\/api\\\\/newsletter\\\\/issues\\\\/([^/]+)\\\\/live$/.exec(newsletterPath)\n if (issueLive && ISSUE_ID.test(issueLive[1]!)) {\n return roomResponse(request, env.ROOMS, issueRoom(issueLive[1]!), { readOnly: true })\n }`\n : ''\n }${\n hasExample(opts, 'board') || hasExample(opts, 'notes')\n ? `\n const room = /^\\\\/api\\\\/rooms\\\\/([^/]+)$/.exec(new URL(request.url).pathname)${\n serverRooms.length > 0\n ? `\n // Rooms only the server writes are watched read-only at their own routes, never opened\n // here: ${[imports ? \"a job's progress\" : '', webhooks ? 'webhook deliveries' : '', checkout ? 'orders' : '', newsletter ? 'newsletter issues' : ''].filter(Boolean).join(', ')}.\n if (room && !/^(${serverRooms.join('|')})/.test(room[1]!)) {\n return roomResponse(request, env.ROOMS, room[1]!)\n }`\n : `\n if (room) return roomResponse(request, env.ROOMS, room[1]!)`\n }`\n : ''\n }${\n imports\n ? `\n // A job's progress: the browser may watch its room, never write to it.\n const job = /^\\\\/api\\\\/jobs\\\\/([\\\\w-]{1,60})$/.exec(new URL(request.url).pathname)\n if (job) {\n return roomResponse(request, env.ROOMS, importJob.roomName(job[1]!), { readOnly: true })\n }`\n : ''\n }\n return ${usage ? 'handleAndRecord' : 'handleApi'}(request, env)\n },`\n : ` fetch: ${usage ? 'handleAndRecord' : 'handleApi'},`\n}${\n digest && social\n ? `\n // The Cron Triggers in wrangler.jsonc, told apart by their schedule.\n async scheduled(event: { cron: string }, env: Env): Promise<void> {\n // Threads tokens renewed, and reminders for those that cannot be (worker/social.ts).\n if (event.cron === '${SOCIAL_CRON}') {\n await socialStore.renewConnections(env)\n return socialStore.remindExpiring(env)\n }\n // The weekly digest, recorded whatever happens.\n await digestJob.runDigest(env, () => puppeteer.launch(env.BROWSER), 'cron')\n },`\n : digest\n ? `\n // The Cron Trigger in wrangler.jsonc: the weekly digest, recorded whatever happens.\n async scheduled(_event: unknown, env: Env): Promise<void> {\n await digestJob.runDigest(env, () => puppeteer.launch(env.BROWSER), 'cron')\n },`\n : social\n ? `\n // The Cron Trigger in wrangler.jsonc: Threads tokens renewed, then reminders for the ones\n // that cannot be (LinkedIn).\n async scheduled(_event: unknown, env: Env): Promise<void> {\n await socialStore.renewConnections(env)\n await socialStore.remindExpiring(env)\n },`\n : ''\n }${\n live && newsletter\n ? `\n // Two queues, one handler: each batch says which queue it came from. A throw retries it.\n async queue(batch: LiveBatch & NewsletterBatch & { queue: string }, env: Env): Promise<void> {\n // NEWSLETTER: one message of readers at a time, through SES (worker/newsletter.ts).\n if (batch.queue === '${newsletterQueue(opts)}') return newsletterStore.deliver(env, batch)\n // EVENTS: into the dashboard's room.\n await recordLive(\n ops,\n env.LIVE,\n OPS_ROOM,\n batch.messages.map((message) => message.body),\n )\n },`\n : live\n ? `\n // The EVENTS queue, a batch at a time, into the dashboard's room. A throw retries the batch.\n async queue(batch: LiveBatch, env: Env): Promise<void> {\n await recordLive(\n ops,\n env.LIVE,\n OPS_ROOM,\n batch.messages.map((message) => message.body),\n )\n },`\n : newsletter\n ? `\n // The NEWSLETTER queue: one message of readers at a time, through SES\n // (worker/newsletter.ts). A throw retries the message; readers already sent are skipped.\n async queue(batch: NewsletterBatch, env: Env): Promise<void> {\n await newsletterStore.deliver(env, batch)\n },`\n : ''\n }\n}\n`\n}\n\n/** Route pattern for a section: the first is `/`, the rest by key. */\nfunction cfSectionPath(section: Section, index: number): string {\n return index === 0 ? '/' : `/${section.key}`\n}\n\n/** Route file for a section, relative to `src/routes/`. */\nfunction cfSectionFile(section: Section, index: number): string {\n return index === 0 ? 'index.tsx' : `${section.key}.tsx`\n}\n\nfunction cfAppTsx(sections: Section[], recipes: string[], opts: ScaffoldOptions): string {\n const items = [\n ...sections.map((s, i) => ({ label: s.label, href: cfSectionPath(s, i) })),\n ...recipes.flatMap((recipe) => loadRecipe(recipe).nav),\n ]\n const navItems = items\n .map(\n (item) => ` {\n label: '${item.label.replace(/'/g, \"\\\\'\")}',\n href: '${item.href}',\n active: path === '${item.href}',\n },`,\n )\n .join('\\n')\n const exports = hasExample(opts, 'export')\n return `import { RouterView } from '@cascivo/app'\n${exports ? `import { isExporting } from '@cascivo/app/export'\\n` : ''}import { Spinner, useSignals, type SideNavItem } from '@cascivo/react'\nimport { router } from './router'\nimport { Shell } from './Shell'\n\nexport default function App() {\n useSignals()\n const path = router.pathname.value\n\n // \\`href\\`s, not click handlers: main.tsx registers the router's Link, so these navigate\n // client-side while middle-click and \"open in new tab\" still work.\n const navItems: SideNavItem[] = [\n${navItems}\n ]\n${\n exports\n ? `\n // Rendered by /api/export: the page alone, without the shell (which gave it its padding).\n if (isExporting()) {\n return (\n <div style={{ padding: 'var(--cascivo-space-8)' }}>\n <RouterView router={router} fallback={<Spinner label=\"Loading\" />} />\n </div>\n )\n }\n`\n : ''\n}\n return (\n <Shell navItems={navItems}>\n <RouterView router={router} fallback={<Spinner label=\"Loading\" />} />\n </Shell>\n )\n}\n`\n}\n\nfunction cfFirstRouteTsx(section: Section): string {\n return `import { Flex, Heading, Text } from '@cascivo/react'\nimport { LiveCard } from '../LiveCard'\n\nexport default function ${section.component}() {\n return (\n <Flex gap={6}>\n <Flex gap={2}>\n <Heading level={1}>${section.label}</Heading>\n <Text muted>\n Edit <code>src/routes/index.tsx</code> to build out this page.\n </Text>\n </Flex>\n <LiveCard />\n </Flex>\n )\n}\n`\n}\n\nfunction cfRouteTsx(section: Section, index: number): string {\n // The Vite scaffold's section, as a route file: a default export, at its own URL.\n return sectionTsx(section)\n .replace(\n `export function ${section.component}()`,\n `export default function ${section.component}()`,\n )\n .replace(`src/sections/${section.component}.tsx`, `src/routes/${cfSectionFile(section, index)}`)\n}\n\n/* --- `--example social`: scheduled posts to connected LinkedIn and Mastodon accounts --- */\n\n/** Daily, off the hour: renews Threads tokens in their last 30 days (\\`renewConnections\\`). */\nconst SOCIAL_CRON = '17 4 * * *'\n\nfunction cfAccountRouteTsx(opts: ScaffoldOptions): string {\n const email = emailSignIn(opts)\n const oauth = oauthSignIn(opts)\n const lead = email\n ? oauth\n ? 'Continue with GitHub, Google or LinkedIn, or get a one-time link by email. No password.'\n : 'No password: we email you a link that signs you in once.'\n : 'Continue with GitHub, Google or LinkedIn. No password.'\n return `import {\n Alert,\n Button,\n Card,\n CardContent,\n Flex,\n Heading,${email ? '\\n Input,\\n Link,' : ''}\n Spinner,\n Text,\n signal,\n useSignals,\n} from '@cascivo/react'\n${email ? \"import type { FormEvent } from 'react'\\n\" : ''}import { auth } from '../auth'${oauth ? \"\\nimport { router } from '../router'\" : ''}\n${\n email\n ? `\nconst sentTo = signal<string | null>(null)\n/** Set only in \\`vite dev\\`, where no email is sent: the link to open instead. */\nconst devLink = signal<string | null>(null)\nconst failure = signal<string | null>(null)\nconst sending = signal(false)\n\nasync function start(event: FormEvent<HTMLFormElement>): Promise<void> {\n event.preventDefault()\n const email = new FormData(event.currentTarget).get('email')\n if (typeof email !== 'string') return\n failure.value = null\n sending.value = true\n try {\n const { link } = await auth.start(email)\n sentTo.value = email\n devLink.value = link\n } catch (error) {\n failure.value = error instanceof Error ? error.message : 'Could not send the link'\n } finally {\n sending.value = false\n }\n}\n`\n : ''\n}${\n oauth\n ? `\nconst LABELS: Record<string, string> = { github: 'GitHub', google: 'Google', linkedin: 'LinkedIn' }\n\n/** The providers the Worker offers: those with an id and a secret set (README). */\nconst providers = signal<string[] | null>(null)\nauth.providers().then(\n (list) => {\n providers.value = list\n },\n () => {\n providers.value = []\n },\n)\n\n/** Why the last sign-in with a provider failed: the Worker sends it back as \\`?error=\\`. */\nconst REASONS: Record<string, string> = {\n denied: 'You did not allow access, so you are not signed in.',\n expired: 'The sign-in took too long, or started in another browser. Try again.',\n state_mismatch: 'That sign-in did not match the one this browser started. Try again.',\n provider_error: 'The provider did not confirm who you are. Try again, or use another way in.',\n identity_in_use: 'That account is already linked to another user here.',\n}\n`\n : ''\n }\nexport default function Account() {\n useSignals()\n const user = auth.user.value${\n oauth\n ? `\n const reason = new URLSearchParams(router.search.value).get('error')`\n : ''\n }\n\n if (user === undefined) return <Spinner label=\"Loading\" />\n if (user) {\n return (\n <Flex gap={4}>\n <Heading level={1}>Account</Heading>\n <Card>\n <CardContent>\n <Flex gap={3}>\n <Text>{user.email ? \\`Signed in as \\${user.email}\\` : 'Signed in'}</Text>\n <Flex direction=\"horizontal\">\n <Button variant=\"secondary\" onClick={() => void auth.signOut()}>\n Sign out\n </Button>\n </Flex>\n </Flex>\n </CardContent>\n </Card>\n </Flex>\n )\n }\n return (\n <Flex gap={4}>\n <Flex gap={1}>\n <Heading level={1}>Sign in</Heading>\n ${\n // Prettier's width: a lead too long for one line goes on its own.\n `<Text muted>${lead}</Text>`.length + 8 > 100\n ? `<Text muted>\\n ${lead}\\n </Text>`\n : `<Text muted>${lead}</Text>`\n }\n </Flex>${\n oauth\n ? `\n {reason ? (\n <Alert variant=\"destructive\" title=\"Not signed in\">\n {REASONS[reason] ?? 'Sign-in failed. Try again.'}\n </Alert>\n ) : null}\n {providers.value === null ? (\n <Spinner label=\"Loading\" />\n ) : providers.value.length === 0 ? (\n <Alert variant=\"info\" title=\"No provider is set up yet\">\n Set GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET, or the GOOGLE_ pair, in .dev.vars (README).\n </Alert>\n ) : (\n <Flex direction=\"horizontal\" gap={2} wrap>\n {providers.value.map((id) => (\n // A plain link: the Worker redirects to the provider, and back here afterwards.\n <Button key={id} asChild variant=\"secondary\">\n <a href={auth.signInUrl(id, '/account')}>Continue with {LABELS[id] ?? id}</a>\n </Button>\n ))}\n </Flex>\n )}`\n : ''\n }${\n email\n ? `\n {sentTo.value ? (\n <Alert variant=\"success\" title=\"Check your email\">\n We sent a sign-in link to {sentTo.value}. It works once, for 15 minutes.\n </Alert>\n ) : null}\n {devLink.value ? (\n <Alert variant=\"info\" title=\"vite dev sends no email\">\n <Link href={devLink.value}>Open the sign-in link</Link>\n </Alert>\n ) : null}\n {failure.value ? (\n <Alert variant=\"destructive\" title=\"Not sent\">\n {failure.value}\n </Alert>\n ) : null}\n <form onSubmit={(event) => void start(event)}>\n <Flex direction=\"horizontal\" align=\"end\" gap={2} wrap>\n <Input name=\"email\" type=\"email\" label=\"Email\" autoComplete=\"email\" required />\n <Button type=\"submit\" loading={sending.value}>\n Email me a link\n </Button>\n </Flex>\n </form>`\n : ''\n }\n </Flex>\n )\n}\n`\n}\n\nfunction cfPrettierIgnore(): string {\n return `${prettierIgnore()}# Rewritten by @cascivo/app/vite whenever a route file changes.\nsrc/routes.gen.ts\n`\n}\n\nfunction cfGitignore(): string {\n return `node_modules\ndist\n.wrangler\n.dev.vars*\n!.dev.vars.example\n*.local\n.DS_Store\n`\n}\n\nfunction cfReadme(opts: ScaffoldOptions): string {\n const pm = opts.pm ?? 'npm'\n const runtime = runtimeOf(opts)\n return `# ${opts.name}\n\nA [cascivo](https://cascivo.com) app on Cloudflare: a client-rendered\n${runtime === 'preact' ? 'Preact' : 'React'} app and its API, deployed as one Worker.\nThere is no server rendering; the browser gets the app, and \\`/api/*\\` reaches the Worker.\n\n## Develop\n\n\\`\\`\\`sh\n${installAllCommand(pm)}\n${runScriptCommand(pm, 'dev')}\n\\`\\`\\`\n\n\\`vite dev\\` runs \\`worker/index.ts\\` in workerd, the same runtime as production, via\n\\`@cloudflare/vite-plugin\\`.\n\n## Deploy\n\n\\`\\`\\`sh\nnpx wrangler login # once\n${runExplicitCommand(pm, 'deploy')}\n\\`\\`\\`\n\n## Share a preview (no account)\n\n\\`\\`\\`sh\n${runExplicitCommand(pm, 'deploy:preview')}\n\\`\\`\\`\n\nThis builds the app, then deploys it to a temporary Cloudflare account with\n\\`wrangler deploy --temporary\\`. You need no sign-up. It prints two URLs:\n\n- **A public \\`workers.dev\\` URL** for the app.\n- **A claim URL.** Open it and sign in within 60 minutes to keep the deployment; otherwise it is deleted.\n\nIt works only while wrangler is logged out. If you are logged in, use \\`deploy\\` instead.\nA temporary account supports Workers, static assets, KV, D1 and Durable Objects. It does not\nsupport Workers AI, R2, Workflows or Browser Run.${\n usesAgents(opts)\n ? ` So a preview serves the app, but its ${hasExample(opts, 'agent') ? 'assistant' : 'voice page'} cannot reach the model: deploy it\\nto your own account for that.`\n : ''\n }\n\n## Structure\n\n- \\`src/routes/\\` — one file per page. \\`index.tsx\\` is \\`/\\`, \\`settings.tsx\\` is\n \\`/settings\\`, \\`c/[id].tsx\\` is \\`/c/:id\\` (it receives \\`params.id\\`), \\`404.tsx\\` is\n everything else. \\`src/routes.gen.ts\\` is rewritten from this folder; do not edit it.\n- \\`src/api.ts\\` — the API contract both sides import: endpoints, their paths, and parsers\n for what crosses the network.\n- \\`worker/index.ts\\` — the API's handlers, typed from \\`src/api.ts\\`. Add bindings (KV,\n D1, R2, Durable Objects, Workers AI) in \\`wrangler.jsonc\\`; handlers receive them as \\`env\\`.\n- \\`src/live.ts\\` + \\`src/LiveCard.tsx\\` — a streaming endpoint read through the typed\n client into signals.\n- \\`src/App.tsx\\` — the nav (real \\`href\\`s) and the \\`RouterView\\`.\n- \\`src/Shell.tsx\\` — the app shell (header + side nav + content slot).\n\nPersist client state with \\`persistedSignal\\` from \\`@cascivo/storage\\` (localStorage or\nIndexedDB).${\n hasExample(opts, 'board')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'notes')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'import')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'files')\n ? `\n\n## Files (uploads)\n\n\\`/files\\` uploads into R2 through the Worker, with progress, and shows resized previews.\n\n- \\`src/upload-policy.ts\\` — what the app accepts (types, size), shared by both sides: the page\n checks a file before sending it, and the Worker enforces the same policy. SVG and HTML are\n refused by design; served from your origin they would run script.\n- \\`worker/index.ts\\` — \\`handleUploads\\` (\\`@cascivo/app/uploads-server\\`) stores uploads, in\n parts above 16 MiB, under keys the Worker chooses, and serves them back with headers that\n stop any file running script. \\`?w=320\\` returns a WebP preview from Cloudflare Images.\n- \\`src/files.ts\\` — \\`startUpload\\` gives each file progress and status signals.\n\nEach caller (by IP) may start 20 uploads a minute (\\`ratelimits\\` in \\`wrangler.jsonc\\`).${\n opts.auth\n ? ''\n : `\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.`\n } Create the bucket once before deploying:\n\\`npx wrangler r2 bucket create ${packageName(opts.name)}-files\\`. R2 and Images do not run on a\ntemporary account.`\n : ''\n }${\n hasExample(opts, 'export')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'live')\n ? `\n\n## Ops (live dashboard)\n\n\\`/ops\\` charts orders, revenue and errors per second, and every open copy of the page moves\ntogether as events arrive.\n\n- \\`src/ops.ts\\` — \\`defineLive\\` (\\`@cascivo/app/live\\`): the metrics, and two minutes of\n per-second history.\n- \\`worker/index.ts\\` — \\`POST /api/events\\` puts events on the \\`EVENTS\\` queue. The \\`queue\\`\n handler adds each batch into a \\`LiveRoom\\` Durable Object with \\`recordLive\\`, which keeps\n per-second totals and sends each change to the browsers watching \\`/api/live\\` (read-only).\n- \\`src/routes/ops.tsx\\` — \\`watchLive\\` gives the window as a signal; the page sends simulated\n traffic while its switch is on. Real producers are anything with the queue binding: another\n Worker, a cron, a webhook handler.\n\nA new viewer, or one back from a dropped connection, starts with the whole window. Delivery is\nat least once: a batch retried after a lost reply counts twice. \\`/api/events\\` has no auth, so\nanyone can move the numbers: check who is sending before real use (\\`--auth access\\` puts\nCloudflare Access in front of the Worker). Create the queue once before deploying:\n\\`npx wrangler queues create ${packageName(opts.name)}-events\\`.`\n : ''\n }${\n hasExample(opts, 'usage')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'search')\n ? `\n\n## Search (by meaning)\n\n\\`/search\\` finds help articles by what a question means: \"how do I get my money back\" finds\nRefunds, though they share no words. Each article is embedded with Workers AI\n(\\`@cf/baai/bge-base-en-v1.5\\`) into a Vectorize index; a question is embedded the same way\nand matched against it.\n\n- \\`worker/articles.ts\\` — the articles, seeded into D1. Replace them with your own content.\n- \\`worker/search.ts\\` — \\`search\\` and \\`indexArticles\\`. \"Index articles\" on the page embeds\n every article; Vectorize applies writes a few seconds later.\n\nCreate the index once before deploying, with the embedding model's dimensions:\n\\`npx wrangler vectorize create ${packageName(opts.name)}-articles --dimensions=768 --metric=cosine\\`.\nNeither Vectorize nor Workers AI runs locally, so \\`vite dev\\` searches by keyword with SQLite's\nfull-text search instead, and the page says so. \\`VITE_REAL_AI=1 ${runScriptCommand(pm, 'dev')}\\` uses the real ones\n(after \\`npx wrangler login\\`). Workers AI and Vectorize bill per use beyond their free\nallocations, and a temporary account has neither.`\n : ''\n }${\n hasExample(opts, 'digest')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'webhooks')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'checkout')\n ? `\n\n## Checkout (Stripe)\n\n\\`/checkout\\` sells one product on Stripe's hosted Checkout page: the card never touches this\napp. Stripe tells the Worker when the payment succeeds; the Worker marks the order paid, pushes\nit to the order page, and emails a receipt rendered with \\`@cascivo/email\\`.\n\n1. In the Stripe dashboard, in test mode, copy the secret key (\\`sk_test_…\\`) into \\`.dev.vars\\`\n as \\`STRIPE_SECRET_KEY\\`, then run the app and buy with the card \\`4242 4242 4242 4242\\`.\n The order page confirms the payment by reading the session back from Stripe, so this works\n before any webhook is set up.\n2. To receive the webhook locally, run\n \\`stripe listen --forward-to localhost:5173/api/stripe/webhook\\` (the Stripe CLI) and put the\n \\`whsec_…\\` secret it prints in \\`.dev.vars\\` as \\`STRIPE_WEBHOOK_SECRET\\`.\n3. Deployed: \\`npx wrangler secret put STRIPE_SECRET_KEY\\` and\n \\`npx wrangler secret put STRIPE_WEBHOOK_SECRET\\`. In the dashboard, add a webhook endpoint\n at \\`https://<your app>/api/stripe/webhook\\` for \\`checkout.session.completed\\`,\n \\`checkout.session.async_payment_succeeded\\`, \\`checkout.session.async_payment_failed\\`,\n \\`checkout.session.expired\\`, \\`charge.refunded\\`, \\`charge.dispute.created\\` and\n \\`charge.dispute.closed\\`; its signing secret is \\`STRIPE_WEBHOOK_SECRET\\`.\n4. Receipts: set \\`RECEIPT_FROM\\` in \\`wrangler.jsonc\\` to an address on a domain you have\n onboarded to Email Service. \\`vite dev\\` renders each receipt and logs it instead.\n\nWhat you sell is \\`PRODUCT\\` in \\`src/checkout.ts\\`. The Worker sends that price to Stripe, so a\nbrowser cannot change it.\n\n- \\`worker/checkout.ts\\` — \\`createStripe\\` (\\`@cascivo/app/stripe\\`) creates the session, with\n the order id as its idempotency key. The webhook is checked by \\`verifyWebhook\\` (scheme\n \\`stripe\\`: signature and a five-minute window) before \\`parseStripeEvent\\` reads it.\n- An order moves from \\`pending\\` to \\`paid\\`, \\`failed\\` or \\`expired\\` once. A retried event, or\n the page getting there before the webhook, changes nothing, so the receipt goes out once.\n Orders are found by Stripe's session id, never by \\`client_reference_id\\`, which a buyer can\n set on a Payment Link.\n- A bank debit completes the session as \\`unpaid\\`: the order stays pending until\n \\`async_payment_succeeded\\` or \\`async_payment_failed\\` arrives, possibly days later.\n- Refunds are made in the Stripe dashboard (or with \\`createRefund\\`); \\`charge.refunded\\` records\n the amount, and an order refunded in full becomes \\`refunded\\`. A chargeback makes it\n \\`disputed\\` until it is decided: answer it with evidence in the dashboard. Both find the\n order by the payment it stored when it was paid.\n- \\`src/routes/checkout/[order].tsx\\` — where Stripe sends the buyer back. It watches the\n order's read-only room, so it updates when the webhook arrives.\n\nEach caller (by IP) may start 20 checkouts a minute.${\n usesBilling(opts)\n ? `\n\n### Subscriptions (\\`/billing\\`)\n\nSigned-in users subscribe to \\`PLAN\\` (\\`src/billing.ts\\`) on Stripe's checkout and change,\npause or cancel it in Stripe's hosted billing portal, so the app has no billing screens to build.\n\n1. Add \\`customer.subscription.created\\`, \\`customer.subscription.updated\\`,\n \\`customer.subscription.deleted\\` and \\`invoice.payment_failed\\` to the webhook endpoint's\n events.\n2. In the Stripe dashboard, save the Customer Portal's settings once (test mode too): until\n then, Stripe refuses to open it.\n3. Gate a paid feature in the Worker with \\`await billingStore.requirePlan(env, request)\\` (402\n without the plan), never on what the page shows.\n\n- \\`worker/billing.ts\\` — the subscription names its user in its metadata, which only the\n Worker sets (\\`client_reference_id\\` can be set by a buyer on a Payment Link). Every\n subscription event is read back from Stripe before it is stored, because events arrive out of\n order, and a late event about an older subscription cannot end a live one.\n- Back from checkout, \\`/billing\\` reads the session and its subscription at once, so it is right\n before the webhook arrives, and only for the user the subscription names.\n- A renewal that cannot be charged leaves the plan on (\\`past_due\\`) while Stripe retries, and\n emails the customer once per attempt with Stripe's page to pay with another card. How long\n Stripe retries, and whether it then cancels, is set in the dashboard (Billing → Subscriptions\n and emails); turn off Stripe's own failed-payment emails there, or customers get two.`\n : `\n\nSubscriptions need an account to belong to: \\`cascivo create --framework cloudflare\n--example checkout --auth email\\` adds a \\`/billing\\` page with a monthly plan and Stripe's\nbilling portal.`\n }`\n : ''\n }${\n hasExample(opts, 'newsletter')\n ? `\n\n## Newsletter (Amazon SES)\n\n\\`/newsletter\\` signs readers up; \\`/newsletter/send\\` writes an issue in Markdown, previews it\nas the email it will be (rendered with \\`@cascivo/email\\`), and sends it to every confirmed\nreader through Amazon SES. It runs in \\`vite dev\\` with nothing set up: emails are logged instead\nof sent, and the sign-up page shows the confirmation link. The composer's key is in\n\\`.dev.vars\\` (\\`NEWSLETTER_KEY\\`).\n\nTo send for real:\n\n1. In SES, verify the domain you send from (SES gives DNS records for DKIM; add them in\n Cloudflare DNS, with an SPF and a DMARC record), and ask AWS to move the account out of the\n sandbox, where it can mail only verified addresses.\n2. Create an IAM user allowed \\`ses:SendEmail\\` and nothing else, and give its keys to the\n Worker: \\`npx wrangler secret put AWS_ACCESS_KEY_ID\\` and \\`AWS_SECRET_ACCESS_KEY\\` (in\n \\`.dev.vars\\` locally). Set \\`AWS_REGION\\` and \\`NEWSLETTER_FROM\\` in \\`wrangler.jsonc\\`, and\n \\`npx wrangler secret put NEWSLETTER_KEY\\` to a long random value.\n3. Bounces and complaints: create an SNS topic, set it as the SES identity's bounce and\n complaint notification topic, and subscribe \\`https://<your app>/api/sns/ses\\` to it (HTTPS).\n Put the topic's ARN in \\`SNS_TOPIC_ARN\\`. The Worker confirms the subscription itself.\n4. Create the queue once: \\`npx wrangler queues create ${newsletterQueue(opts)}\\`.\n\n- \\`worker/newsletter.ts\\` — double opt-in: a sign-up gets a confirmation link (valid a day,\n resent at most every ten minutes) and gets no issue until it is opened. Sending stores the\n issue and puts its readers on the \\`NEWSLETTER\\` queue, 25 per message; the consumer sends\n them one by one through \\`createSes\\` (\\`@cascivo/app/ses\\`), handed to \\`sendEmail\\` from\n \\`@cascivo/email\\`, which checks each message before it leaves, one message at a time. Each\n send is recorded, so a message retried after SES throttling skips whoever already has it.\n- Every issue carries \\`List-Unsubscribe\\` and \\`List-Unsubscribe-Post\\` (one-click\n unsubscribe, RFC 8058, which Gmail and Yahoo require of bulk senders) and a footer link to\n \\`/newsletter/unsubscribe\\`.\n- \\`handleSns\\` checks each SNS message's signature against SNS's certificate before\n \\`parseSesNotification\\` reads it. A permanent bounce or a complaint suppresses the address\n for good: mailing it again is what gets an SES account reviewed.\n- \\`worker/newsletter-email.ts\\` — the issue and confirmation emails. The body is Markdown drawn\n through the email primitives; raw HTML in it stays literal text.\n\nSign-ups and every use of the newsletter key count against the rate limit (20 a minute per\nIP). Sending reads every confirmed address into memory; past a few hundred thousand readers,\npage through them instead.`\n : ''\n }${\n hasExample(opts, 'social')\n ? `\n\n## Social posts\n\n\\`/social\\` connects Bluesky, Buffer, LinkedIn, Mastodon and Threads accounts and posts to them,\nnow or at a time you pick.\n\n- \\`worker/social.ts\\` — \\`handleConnections\\` (\\`@cascivo/app/oauth-server\\`) answers\n \\`/api/connections/*\\`: connect, list, remove. Tokens are sealed in D1 with \\`AUTH_SECRET\\`.\n Scheduling checks that each account is yours and connected, and that each network's\n publisher (\\`@cascivo/app/social\\`) accepts the post, before anything is stored.\n- \\`worker/social-post.ts\\` — \\`SocialPost\\`, a Workflow per post: it sleeps until the post\n is due, then posts to each account in its own step. Bluesky and Mastodon steps retry, safely:\n Mastodon takes an idempotency key, and a Bluesky post's record key is fixed by its time and\n id. Buffer, LinkedIn and Threads steps never do: they cannot deduplicate, so an interrupted\n post there is reported for you to check rather than sent twice.\n- \\`src/social.ts\\` — the shared types, and the publishers the page also runs, so what a\n network would refuse shows while you type.\n- Images: the composer uploads them into the \\`SOCIAL_MEDIA\\` R2 bucket through the Worker\n (\\`@cascivo/app/uploads\\`), each user under their own prefix; up to 4, JPEG or PNG, 1 MB each\n (Bluesky's limit), each with a description. Bluesky, LinkedIn and Mastodon get the bytes.\n Threads and Buffer fetch images by URL, so they get a link to \\`/api/social/media/…\\` signed\n with \\`AUTH_SECRET\\`. It is valid until a day after the post is due, and needs \\`APP_URL\\` set\n to the deployed app. Uploads stay in R2: add a lifecycle rule\n (\\`wrangler r2 bucket lifecycle add\\`) to expire old ones.\n\n**Bluesky** needs no set-up either: people type their handle. Bluesky's servers read this\napp's client metadata from \\`/api/bluesky/client-metadata.json\\`, so the deployed app must be\nreachable at its URL. In \\`vite dev\\` the app is Bluesky's development client, which may only\nreturn to \\`127.0.0.1\\`: open \\`http://127.0.0.1:5173\\`, not \\`localhost\\`. Without a key the app is a\npublic client and sessions end after two weeks; for sessions that last, make a key and set it\nas the \\`BLUESKY_PRIVATE_JWK\\` secret:\n\n\\`\\`\\`sh\nnode -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'})))\"\n\\`\\`\\`\n\n**Mastodon** needs no set-up: people type their server, and the app registers itself there\non first use.\n\n**Buffer** reaches the networks connected there (X, Instagram, TikTok, …): register an app\nclient at https://publish.buffer.com/settings/api with \\`…/api/connections/buffer/callback\\` as\nits redirect URL, and set \\`BUFFER_CLIENT_ID\\` (and \\`BUFFER_CLIENT_SECRET\\` for a confidential\nclient). Each channel in a connected Buffer is an account in the composer, checked against\nits network's limit. Buffer counts every request against your plan's budget (100 per 15\nminutes on every plan), for all your users together, so the channel list is kept for an hour.\nBuffer cannot deduplicate, so its posts are never retried, like LinkedIn's. **LinkedIn** needs an app at https://www.linkedin.com/developers/apps with the\n\"Share on LinkedIn\" product${oauthSignIn(opts) ? ' (the same app as sign-in works, with both products)' : ''}; add\n\\`…/api/connections/linkedin/callback\\` as a redirect URL and set \\`LINKEDIN_CLIENT_ID\\` and\n\\`LINKEDIN_CLIENT_SECRET\\`. LinkedIn tokens last 60 days and cannot be renewed: the page shows\n\"expires soon\" a week ahead, and connecting again renews the account in place. The daily Cron\nTrigger also emails the owner once, a week ahead, with a link to connect again\n(\\`remindExpiring\\`): set \\`REMINDER_FROM\\` in \\`wrangler.jsonc\\` to an address on a domain you\nhave onboarded to Email Service, and \\`APP_URL\\` to the deployed app. People whose provider shared\nno email see the page's notice only.\n\n**Threads** needs a Meta app with the \"Access the Threads API\" use case\n(https://developers.facebook.com/apps), the \\`threads_basic\\` and \\`threads_content_publish\\`\npermissions, and \\`…/api/connections/threads/callback\\` as a redirect callback URL; set\n\\`THREADS_APP_ID\\` and \\`THREADS_APP_SECRET\\` (the Threads app id and secret, not the Meta\napp's). Until Meta's App Review and business verification pass, only people added as testers\non the app can connect. A Threads token lasts 60 days and renews itself only while it still\nworks, so a daily Cron Trigger (\\`${SOCIAL_CRON}\\`, \\`renewConnections\\`) renews those in their last\n30 days; try it in \\`vite dev\\` at \\`/cdn-cgi/handler/scheduled\\`. Threads takes 500 characters,\ncounting an emoji as several, and cannot deduplicate either.\n\nConnecting an account and posting count against the rate limit (20 a minute per IP).\nWorkflows need a real Cloudflare account to deploy.`\n : ''\n }${\n hasAccounts(opts)\n ? `\n\n## Accounts (${emailSignIn(opts) ? (oauthSignIn(opts) ? 'email, GitHub, Google and LinkedIn sign-in' : 'email sign-in') : 'GitHub, Google and LinkedIn sign-in'})\n\n${\n emailSignIn(opts) && oauthSignIn(opts)\n ? 'Anyone can create an account by continuing with GitHub, Google or LinkedIn, or with their email address, on `/account`.'\n : oauthSignIn(opts)\n ? 'Anyone can create an account by continuing with GitHub, Google or LinkedIn on `/account`.'\n : '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.'\n} **Every API write needs a signed-in user; reads stay public.**\n\n- \\`worker/index.ts\\` — ${[emailSignIn(opts) ? '`handleAuth` (`@cascivo/app/auth-server`)' : '', oauthSignIn(opts) ? '`handleOAuth` (`@cascivo/app/oauth-server`)' : ''].filter(Boolean).join(' and ')} answer${emailSignIn(opts) && oauthSignIn(opts) ? '' : 's'} \\`/api/auth/*\\`, and\n \\`requireUser\\` refuses any other write without a session (401) or from another site (403).\n Call \\`requireUser(env.DB, request)\\` in a handler to know who is asking.${\n emailSignIn(opts)\n ? `\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.`\n : ''\n }\n- \\`src/auth.ts\\` — \\`auth.user\\`, a signal every page can read. \\`user.email\\` is \\`null\\` for\n someone whose provider shared no verified address.${\n emailSignIn(opts)\n ? `\n- \\`src/routes/signin/verify.tsx\\` — the page a link opens. It signs in on a button press,\n because mail scanners open every link in a message.`\n : ''\n }\n\nUsers${emailSignIn(opts) ? ', links' : ''} and sessions live in D1, stored as hashes. ${emailSignIn(opts) ? 'Links expire after 15 minutes and work once; sessions' : 'Sessions'} last 30 days.${emailSignIn(opts) ? ' 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\n(rooms, agents) are not covered by the write rule; check \\`currentUser\\` before forwarding them\nif they need a user.${\n oauthSignIn(opts)\n ? `\n\n### GitHub, Google and LinkedIn\n\n1. **GitHub**: create an OAuth App at https://github.com/settings/developers with the\n callback URL \\`http://localhost:5173/api/auth/oauth/github/callback\\` for \\`vite dev\\`\n (an OAuth App takes one callback URL, so make a second app for the deployed one).\n2. **Google**: in the Google Cloud console, create an OAuth client of type \"Web application\"\n with the redirect URIs \\`http://localhost:5173/api/auth/oauth/google/callback\\` and\n \\`https://<your app>/api/auth/oauth/google/callback\\`.\n3. **LinkedIn**: create an app at https://www.linkedin.com/developers/apps, add the product\n \"Sign In with LinkedIn using OpenID Connect\", and under Auth add both redirect URLs\n (\\`…/api/auth/oauth/linkedin/callback\\` on localhost and on your app).\n4. Put the ids and secrets in \\`.dev.vars\\`. Deployed: \\`npx wrangler secret put\\` each\n \\`*_CLIENT_ID\\` and \\`*_CLIENT_SECRET\\` you use, and \\`AUTH_SECRET\\` (a random one:\n \\`openssl rand -base64 32\\`). A provider is offered once both its values are set.\n\nPeople are matched by their account at the provider, not by email. A new sign-in joins an\nexisting account only through an email the provider has verified (GitHub's primary verified\naddress, Google's and LinkedIn's \\`email_verified\\`). A signed-in user who follows another provider's link\nadds it to their account.`\n : ''\n }`\n : ''\n }${\n opts.auth === 'access'\n ? `\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\\`.`\n : ''\n }${\n hasExample(opts, 'crud')\n ? `\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.`\n : ''\n }${\n hasExample(opts, 'agent')\n ? `\n\n## Assistant (generative UI)\n\n\\`/assistant\\` is a chat whose answers can be UI. The model calls a \\`show_view\\` tool with a view\nconfig; the Worker checks it against the component manifests (\\`validateView\\` from\n\\`@cascivo/render/validate\\`) and returns any errors to the model, which fixes them and calls\nagain. The page renders the result with \\`<CascivoView>\\`: real components, no generated code.\n\n- \\`worker/assistant.ts\\` — \\`Assistant\\`, an \\`AIChatAgent\\` (Cloudflare's Agents SDK): one\n Durable Object per conversation, which stores the messages and streams replies to every open\n tab. The system prompt, the \\`show_view\\` tool and the model (\\`MODEL\\`, any Workers AI model\n with tool calling) are here.\n- \\`src/assistant.ts\\` — \\`checkView\\`, the one check both sides run on a view.\n- \\`src/routes/assistant.tsx\\` — \\`useAgent\\` + \\`useAgentChat\\`; one conversation per browser.\n- \\`worker/scripted-model.ts\\` — \\`vite dev\\` answers from this scripted model, so the page works\n offline and without an account. \\`VITE_REAL_AI=1 ${runScriptCommand(pm, 'dev')}\\` uses Workers AI instead\n (after \\`npx wrangler login\\`); a deployed Worker always does.\n\nWorkers AI bills per use beyond its free daily allocation.`\n : ''\n }${\n hasExample(opts, 'publish')\n ? `\n\n## Publish (views as pages)\n\n\\`/publish\\` turns a view — the JSON that \\`<CascivoView>\\` renders, which an agent can write\ntoo — into a page at \\`/p/<slug>\\`, with no deploy. A view is data, not code: it can only\narrange this app's components with props their manifests allow, so a published page runs no\ncode of its author's and needs no sandbox.\n\n- \\`src/pages.ts\\` — \\`parsePageInput\\` checks a page with \\`validateView\\`\n (\\`@cascivo/render/validate\\`): known components and props, and no link or image URL that\n could run script. The Worker runs it before storing a page; \\`<CascivoView>\\` checks again\n before rendering one.\n- \\`worker/pages.ts\\` — pages in D1, under a random ten-character slug.\n- \\`src/routes/publish.tsx\\` — the editor, with a live preview.\n- \\`src/routes/p/[slug].tsx\\` — a published page.\n- \\`worker/page-html.ts\\` — the Worker answers \\`/p/<slug>\\` with index.html carrying the\n page's title, description and Open Graph tags, so a shared link previews properly, and the\n rendered page in a \\`<noscript>\\` for readers without JavaScript.${\n hasExample(opts, 'export')\n ? `\n- \\`worker/page-preview.ts\\` — the preview image (\\`og:image\\`, 1200 × 630): Browser Run\n renders the page once, and D1 keeps the PNG.`\n : ''\n }\n\n${\n opts.auth\n ? ''\n : `**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\\`. `\n}Each caller (by IP) may publish 20 pages a minute (\\`ratelimits\\` in\n\\`wrangler.jsonc\\`). D1 works on a temporary account.`\n : ''\n }${\n hasExample(opts, 'voice')\n ? `\n\n## Voice\n\n\\`/voice\\` is a voice assistant: press \"Start call\", talk, and it answers aloud. Talk over a\nreply to interrupt it. Typed messages work too.\n\n- \\`worker/voice.ts\\` — \\`Voice\\`, an Agent with the Agents SDK's voice pipeline\n (\\`withVoice\\` from \\`agents/voice\\`): Workers AI speech to text (Flux, which also decides when\n you have finished speaking), a text model (\\`MODEL\\`) and text to speech. One Durable Object\n per conversation stores the transcript, which the model gets as context.\n- \\`src/voice.ts\\` — \\`VoiceClient\\` (\\`agents/voice/client\\`) captures the microphone, streams\n it, and plays the replies; its events become signals the page reads.\n- \\`worker/scripted-voice.ts\\` — \\`vite dev\\` stand-ins, because Workers AI has no local mode:\n the transcriber \"hears\" a fixed question for every three seconds of sound, and the replies\n are text only. \\`VITE_REAL_AI=1 ${runScriptCommand(pm, 'dev')}\\` uses Workers AI instead (after\n \\`npx wrangler login\\`); a deployed Worker always does.\n\nBrowsers allow the microphone only on a secure origin: \\`localhost\\` or HTTPS. Workers AI\nbills per use beyond its free daily allocation, and a temporary account has no Workers AI.`\n : ''\n }\n\nAdd more components with \\`npx cascivo add <component>\\`.\n\n## ${runtime === 'preact' ? 'Preact or React' : 'React or Preact'}\n\n${\n hasExample(opts, 'agent')\n ? `This app runs on React. The Agents SDK's hooks call React 19's \\`use()\\`, which\nPreact's compat layer does not implement, so the assistant page needs React. (The other pages\nwould run on Preact unchanged: the source is typed against React either way.)`\n : `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).`\n}\n`\n}\n\nfunction cfAgentsMd(opts: ScaffoldOptions): string {\n return `${agentsMd(opts)}\n## Server\n\nThe API contract is \\`src/api.ts\\` (\\`defineApi\\` from \\`@cascivo/app/api\\`); its handlers are\n\\`worker/index.ts\\` (\\`createHandler\\`), and the app calls it through \\`createClient\\`. Add an\nendpoint to the contract first, with a parser for its input and output: parse every payload\nthat crosses the network, never cast it. A streaming endpoint's handler is an async\ngenerator. \\`wrangler.jsonc\\` routes only \\`/api/*\\` to the Worker.\n\n## Pages\n\nA page is a file in \\`src/routes/\\` with a default export: \\`c/[id].tsx\\` serves \\`/c/:id\\` and\nreceives \\`{ params }: RouteProps<'/c/:id'>\\`. Never edit \\`src/routes.gen.ts\\`. Link with\n\\`href\\`s (SideNav items, \\`router.Link\\`); navigate from code with \\`router.navigate(path)\\`,\nand build a path with \\`buildPath('/c/:id', { id })\\`, both from \\`@cascivo/app\\`.\n\n## Sharing\n\nTo show the user a running version, run \\`${runExplicitCommand(opts.pm ?? 'npm', 'deploy:preview')}\\`.\nIt needs no Cloudflare account. Give the user both URLs it prints: the live one, and the\nclaim URL. The deployment is public, and it is deleted after 60 minutes unless the user\nopens the claim URL and signs in.\n`\n}\n\nfunction cfShellTsx(opts: ScaffoldOptions): string {\n const shell = shellTsx(opts)\n const start = shell.indexOf(' * Adding a router?')\n const end = shell.indexOf(' */\\nexport function Shell')\n // This app already routes, so the Vite scaffold's \"adding a router\" advice does not apply.\n return (\n shell.slice(0, start) +\n ' * Routing lives in src/router.ts; nav items carry `href`s, and main.tsx registers the\\n' +\n \" * router's Link so they navigate client-side.\\n\" +\n shell.slice(end)\n )\n}\n\n/** Local secrets for `vite dev` (.gitignore'd); deployed, each is a `wrangler secret`. */\nfunction cfDevVars(opts: ScaffoldOptions): string {\n return [\n ...(hasExample(opts, 'webhooks')\n ? [\n '# The secret vite dev signs and checks test webhook deliveries with.',\n 'WEBHOOK_SECRET=dev-only-webhook-secret',\n ]\n : []),\n ...(hasExample(opts, 'checkout')\n ? [\n '# Stripe, in test mode (README): the secret key from the dashboard, and the signing',\n '# secret `stripe listen` prints.',\n 'STRIPE_SECRET_KEY=',\n 'STRIPE_WEBHOOK_SECRET=',\n ]\n : []),\n ...(hasExample(opts, 'newsletter')\n ? [\n '# The key /newsletter/send asks for. Deployed, choose a long random one.',\n 'NEWSLETTER_KEY=dev-only-newsletter-key',\n '# An IAM user allowed ses:SendEmail (README). Without them, vite dev logs each email.',\n 'AWS_ACCESS_KEY_ID=',\n 'AWS_SECRET_ACCESS_KEY=',\n ]\n : []),\n ...(oauthSignIn(opts)\n ? [\n '# Seals the sign-in state between the redirect and the callback. Deployed, a random one:',\n '# openssl rand -base64 32',\n 'AUTH_SECRET=dev-only-auth-secret-0123456789abcdef',\n '# A GitHub OAuth App, a Google OAuth client and a LinkedIn app (README).',\n '# Each provider is offered once both its id and secret are set.',\n 'GITHUB_CLIENT_ID=',\n 'GITHUB_CLIENT_SECRET=',\n 'GOOGLE_CLIENT_ID=',\n 'GOOGLE_CLIENT_SECRET=',\n 'LINKEDIN_CLIENT_ID=',\n 'LINKEDIN_CLIENT_SECRET=',\n ]\n : hasExample(opts, 'social')\n ? [\n \"# Seals connected accounts' tokens. Deployed, a random one: openssl rand -base64 32\",\n 'AUTH_SECRET=dev-only-auth-secret-0123456789abcdef',\n '# A LinkedIn app with \"Share on LinkedIn\" (README). Mastodon needs nothing.',\n 'LINKEDIN_CLIENT_ID=',\n 'LINKEDIN_CLIENT_SECRET=',\n ]\n : []),\n ...(hasExample(opts, 'social')\n ? [\n '# Optional: an ES256 private JWK with a kid, so Bluesky sessions last (README).',\n 'BLUESKY_PRIVATE_JWK=',\n '# Optional: a Buffer app client (publish.buffer.com/settings/api), to post to its channels.',\n 'BUFFER_CLIENT_ID=',\n 'BUFFER_CLIENT_SECRET=',\n '# Optional: a Meta app with the Threads use case (README), to post to Threads.',\n 'THREADS_APP_ID=',\n 'THREADS_APP_SECRET=',\n ]\n : []),\n ]\n .map((line) => `${line}\\n`)\n .join('')\n}\n\n/**\n * The secrets the app reads, with no values: committed, unlike .dev.vars. The \"Deploy to\n * Cloudflare\" button asks for each one it lists; `cp .dev.vars.example .dev.vars` starts a\n * fresh clone.\n */\nfunction cfDevVarsExample(opts: ScaffoldOptions): string {\n return cfDevVars(opts)\n .split('\\n')\n .map((line) => (line.startsWith('#') ? line : line.replace(/=.*$/, '=')))\n .join('\\n')\n}\n\n/**\n * What each setting is for, in package.json's \\`cloudflare.bindings\\`: the \"Deploy to Cloudflare\"\n * button shows it beside the field it asks the deployer to fill in.\n */\nfunction cfBindingDescriptions(opts: ScaffoldOptions): Record<string, { description: string }> {\n const describe = (entries: [string, string][]) =>\n Object.fromEntries(entries.map(([name, description]) => [name, { description }]))\n return {\n ...(hasExample(opts, 'webhooks')\n ? describe([\n [\n 'WEBHOOK_SECRET',\n 'The secret of the GitHub webhook that posts to `/api/webhooks/github`.',\n ],\n ])\n : {}),\n ...(hasExample(opts, 'checkout')\n ? describe([\n [\n 'STRIPE_SECRET_KEY',\n 'Your Stripe secret key, from the [API keys page](https://dashboard.stripe.com/test/apikeys). A test key (`sk_test_…`) takes test cards only.',\n ],\n [\n 'STRIPE_WEBHOOK_SECRET',\n '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`.',\n ],\n [\n 'RECEIPT_FROM',\n 'The From address of receipts, on a domain onboarded to Cloudflare Email Service. Leave it empty to send none.',\n ],\n ])\n : {}),\n ...(hasExample(opts, 'newsletter')\n ? describe([\n [\n 'NEWSLETTER_KEY',\n 'The key `/newsletter/send` asks for. Make a long random one: `openssl rand -hex 32`.',\n ],\n ['AWS_ACCESS_KEY_ID', 'An IAM user allowed `ses:SendEmail` and nothing else (README).'],\n ['AWS_SECRET_ACCESS_KEY', \"That IAM user's secret access key.\"],\n ['AWS_REGION', 'The SES region your sending domain is verified in, e.g. `eu-west-1`.'],\n ['NEWSLETTER_FROM', 'The From address of issues, on your SES-verified domain.'],\n [\n 'SNS_TOPIC_ARN',\n 'The SNS topic SES reports bounces and complaints to, subscribed to `https://<this app>/api/sns/ses`.',\n ],\n ])\n : {}),\n ...(oauthSignIn(opts)\n ? describe([\n [\n 'AUTH_SECRET',\n '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`.',\n ],\n [\n 'GITHUB_CLIENT_ID',\n '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.',\n ],\n ['GITHUB_CLIENT_SECRET', \"That OAuth App's client secret.\"],\n [\n 'GOOGLE_CLIENT_ID',\n '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.',\n ],\n ['GOOGLE_CLIENT_SECRET', \"That OAuth client's secret.\"],\n [\n 'LINKEDIN_CLIENT_ID',\n '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.',\n ],\n ['LINKEDIN_CLIENT_SECRET', \"That LinkedIn app's primary client secret.\"],\n ])\n : hasExample(opts, 'social')\n ? describe([\n [\n 'AUTH_SECRET',\n 'Seals the tokens of the accounts people connect. Make a random one: `openssl rand -base64 32`.',\n ],\n [\n 'LINKEDIN_CLIENT_ID',\n '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.',\n ],\n ['LINKEDIN_CLIENT_SECRET', \"That LinkedIn app's primary client secret.\"],\n ])\n : {}),\n ...(hasExample(opts, 'social')\n ? describe([\n [\n 'BLUESKY_PRIVATE_JWK',\n '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.',\n ],\n [\n 'BUFFER_CLIENT_ID',\n '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.',\n ],\n ['BUFFER_CLIENT_SECRET', \"That Buffer app client's secret (none for a public client).\"],\n [\n 'THREADS_APP_ID',\n '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.',\n ],\n ['THREADS_APP_SECRET', \"That Threads app's secret.\"],\n ])\n : {}),\n }\n}\n\n/**\n * The recipes (`packages/cli/recipes/<name>`) a cloudflare scaffold may add after its base, in\n * the order their pages appear in the side nav.\n */\nconst CLOUDFLARE_RECIPES = [\n 'agent',\n 'board',\n 'notes',\n 'import',\n 'files',\n 'export',\n 'usage',\n 'crud',\n 'live',\n 'voice',\n 'publish',\n 'publish-preview',\n 'webhooks',\n 'digest',\n 'search',\n 'checkout',\n 'billing',\n 'newsletter',\n 'social',\n 'accounts',\n 'auth-email',\n] as const\n\n/** Each example is its own recipe; the rest are what two choices bring together. */\nfunction includesRecipe(\n recipe: (typeof CLOUDFLARE_RECIPES)[number],\n opts: ScaffoldOptions,\n): boolean {\n switch (recipe) {\n case 'publish-preview':\n return hasExample(opts, 'publish') && hasExample(opts, 'export')\n case 'billing':\n return usesBilling(opts)\n case 'accounts':\n return hasAccounts(opts)\n case 'auth-email':\n return emailSignIn(opts)\n default:\n return hasExample(opts, recipe)\n }\n}\n\nfunction cloudflareRecipes(opts: ScaffoldOptions): string[] {\n return ['cloudflare', ...CLOUDFLARE_RECIPES.filter((recipe) => includesRecipe(recipe, opts))]\n}\n\nfunction buildCloudflareScaffold(opts: ScaffoldOptions, sections: Section[]): ScaffoldFile[] {\n const runtime = runtimeOf(opts)\n const recipes = cloudflareRecipes(opts)\n const recipeOutput = recipes.flatMap((recipe) => recipeFiles(recipe, recipeVars(opts)))\n const routeFiles = [\n ...sections.map((s, i) => ({\n file: cfSectionFile(s, i),\n contents: s.block\n ? blockPageTsx(s, 'export default function')\n : i === 0\n ? cfFirstRouteTsx(s)\n : cfRouteTsx(s, i),\n })),\n ...(hasAccounts(opts) ? [{ file: 'account.tsx', contents: cfAccountRouteTsx(opts) }] : []),\n ]\n const routes = [\n ...routeFiles.map((r) => r.file),\n ...recipeOutput\n .filter((f) => f.path.startsWith('src/routes/'))\n .map((f) => f.path.slice('src/routes/'.length)),\n ]\n return [\n { path: 'package.json', contents: cfPackageJson(opts) },\n { path: 'tsconfig.json', contents: cfTsconfig(opts) },\n ...(needsWorkerTypes(opts)\n ? [{ path: 'tsconfig.worker.json', contents: cfWorkerTsconfig() }]\n : []),\n { path: 'vite.config.ts', contents: cfViteConfig(runtime, opts) },\n { path: 'wrangler.jsonc', contents: wranglerJsonc(opts) },\n { path: 'index.html', contents: indexHtml(opts) },\n { path: 'eslint.config.js', contents: eslintConfig() },\n { path: '.prettierrc', contents: prettierrc() },\n { path: '.prettierignore', contents: cfPrettierIgnore() },\n { path: '.gitignore', contents: cfGitignore() },\n { path: 'README.md', contents: cfReadme(opts) },\n { path: 'AGENTS.md', contents: cfAgentsMd(opts) },\n { path: 'worker/index.ts', contents: cfWorkerTs(opts) },\n { path: 'src/api.ts', contents: cfApiTs(opts) },\n { path: 'src/vite-env.d.ts', contents: viteEnv() },\n { path: 'src/App.tsx', contents: cfAppTsx(sections, recipes, opts) },\n { path: 'src/Shell.tsx', contents: cfShellTsx(opts) },\n ...(hasExample(opts, 'webhooks') ||\n hasExample(opts, 'checkout') ||\n hasExample(opts, 'newsletter') ||\n hasExample(opts, 'social') ||\n oauthSignIn(opts)\n ? [\n { path: '.dev.vars', contents: cfDevVars(opts) },\n { path: '.dev.vars.example', contents: cfDevVarsExample(opts) },\n ]\n : []),\n ...recipeOutput,\n ...blockFiles(sections, opts),\n ...routeFiles.map(({ file, contents }) => ({ path: `src/routes/${file}`, contents })),\n // Written now so \\`tsc\\` passes before the first \\`vite\\` run; the plugin keeps it current.\n { path: 'src/routes.gen.ts', contents: generateRoutes(routes, './routes') },\n ]\n}\n\n/**\n * The app's blueprint, as `cascivo.app.json`: what it was generated from, in the vocabulary of\n * the flags, stamped with this CLI's version. `cascivo app` changes the app by changing this\n * file and merging what it generates.\n */\nfunction blueprintJson(opts: ScaffoldOptions, sections: Section[]): string {\n return formatJson({\n name: opts.name,\n framework: opts.framework ?? 'react-vite',\n theme: opts.theme,\n pages: sections.map((s) => ({ title: s.label, ...(s.block ? { block: s.block } : {}) })),\n ...(opts.runtime ? { runtime: opts.runtime } : {}),\n ...(opts.examples && opts.examples.length > 0 ? { examples: opts.examples } : {}),\n ...(opts.auth ? { auth: opts.auth } : {}),\n cascivo: CLI_VERSION,\n })\n}\n\nexport function buildScaffold(opts: ScaffoldOptions): ScaffoldFile[] {\n const sections = resolveSections(opts.sections, opts.blocks)\n const app = [\n ...buildFrameworkScaffold(opts, sections),\n { path: 'cascivo.app.json', contents: blueprintJson(opts, sections) },\n ...agentFiles(),\n ]\n if (!opts.workspace) return app\n return buildWorkspace({\n packageName: packageName(opts.name),\n app,\n firstLabel: sections[0]!.label,\n testable: (opts.framework ?? 'react-vite') === 'react-vite',\n reactVersion: V['@cascivo/react']!,\n })\n}\n\n/**\n * Wiring for a coding agent opened in the app. Claude Code reads CLAUDE.md, which imports the\n * AGENTS.md every other agent reads, so the instructions live in one file; `.mcp.json` is what\n * `cascivo mcp init` writes, so the agent can reach the registry without that extra step.\n */\nfunction agentFiles(): ScaffoldFile[] {\n const mcp = mergeMcpConfig(undefined, 'claude')\n if (mcp.kind !== 'added') throw new Error('cascivo: could not build .mcp.json')\n return [\n { path: 'CLAUDE.md', contents: '@AGENTS.md\\n' },\n { path: '.mcp.json', contents: formatJson(mcp.config) },\n ]\n}\n\nfunction buildFrameworkScaffold(opts: ScaffoldOptions, sections: Section[]): ScaffoldFile[] {\n if (opts.framework === 'astro') return buildAstroScaffold(opts, sections)\n if (opts.framework === 'cloudflare') {\n // The digest emails the report page the export example adds, so it brings that along.\n const examples =\n opts.examples?.includes('digest') && !opts.examples.includes('export')\n ? [...opts.examples, 'export' as const]\n : opts.examples\n // Social posts belong to a user: without --auth, it brings sign-in with providers.\n const auth = opts.auth ?? (examples?.includes('social') ? 'oauth' : undefined)\n return buildCloudflareScaffold(\n { ...opts, ...(examples ? { examples } : {}), ...(auth ? { auth } : {}) },\n sections,\n )\n }\n return [\n { path: 'package.json', contents: packageJson(opts) },\n { path: 'tsconfig.json', contents: tsconfig() },\n { path: 'vite.config.ts', contents: viteConfig() },\n { path: 'index.html', contents: indexHtml(opts) },\n // No `cascivo.config.ts`. It configures where `cascivo add` copies source, which a\n // prebuilt-path app never does — and its presence was how `doctor` decided a project\n // was copy-paste, so the scaffolder's own output failed `doctor --ci` and was told to\n // install the two packages the docs forbid. `cascivo add` writes the config itself the\n // first time it is used.\n { path: 'eslint.config.js', contents: eslintConfig() },\n { path: '.prettierrc', contents: prettierrc() },\n { path: '.prettierignore', contents: prettierIgnore() },\n { path: '.gitignore', contents: gitignore() },\n { path: 'README.md', contents: readme(opts) },\n { path: 'AGENTS.md', contents: agentsMd(opts) },\n { path: 'src/main.tsx', contents: mainTsx() },\n { path: 'src/vite-env.d.ts', contents: viteEnv() },\n { path: 'src/App.tsx', contents: appTsx(sections) },\n { path: 'src/Shell.tsx', contents: shellTsx(opts) },\n ...sections.map((s) => ({\n path: `src/sections/${s.component}.tsx`,\n contents: sectionTsx(s),\n })),\n ...blockFiles(sections, opts),\n ]\n}\n\nfunction buildAstroScaffold(opts: ScaffoldOptions, sections: Section[]): ScaffoldFile[] {\n return [\n { path: 'package.json', contents: astroPackageJson(opts) },\n { path: 'tsconfig.json', contents: astroTsconfig() },\n { path: 'astro.config.mjs', contents: astroConfig(opts) },\n { path: 'eslint.config.js', contents: eslintConfig() },\n { path: '.prettierrc', contents: prettierrc() },\n { path: '.prettierignore', contents: prettierIgnore() },\n { path: '.gitignore', contents: astroGitignore() },\n { path: 'README.md', contents: astroReadme(opts, sections) },\n { path: 'AGENTS.md', contents: agentsMd(opts) },\n { path: 'src/styles/layers.css', contents: astroLayersCss() },\n { path: 'src/layouts/Layout.astro', contents: astroLayout(opts) },\n { path: 'src/components/Shell.tsx', contents: astroShellTsx(opts, sections) },\n ...sections.map((s, i) => ({\n path: `src/pages/${sectionPageFile(s, i)}`,\n contents: astroPage(s, i),\n })),\n ...sections.map((s) => ({\n path: `src/components/${s.component}.tsx`,\n contents: astroSectionTsx(s),\n })),\n ]\n}\n\nconst DEFAULT_SECTIONS = ['Dashboard', 'Reports', 'Settings']\n\n/**\n * Combinations that cannot work, as the message to print, or `null`. Shared by the flags and\n * `--from <blueprint>`, so a blueprint is held to the same rules as a command line.\n */\nexport function optionsError(opts: Omit<ScaffoldOptions, 'pm'>): string | null {\n const examples = opts.examples ?? []\n if (examples.length > 0 && opts.framework !== 'cloudflare') {\n return '--example needs --framework cloudflare (it adds a Worker-backed page).'\n }\n if (examples.includes('social') && opts.auth === 'access') {\n return (\n '--example social needs accounts (posts belong to a user): use --auth email, oauth or ' +\n 'email,oauth, or leave --auth out to get oauth.'\n )\n }\n if (opts.auth && opts.framework !== 'cloudflare') {\n return '--auth needs --framework cloudflare (it guards the Worker).'\n }\n if (opts.workspace && opts.framework === 'astro') {\n return '--workspace needs --framework react-vite or cloudflare.'\n }\n if (examples.includes('agent') && opts.runtime === 'preact') {\n return (\n \"--example agent needs --runtime react: the Agents SDK's hooks call React 19's use(), \" +\n 'which Preact does not implement.'\n )\n }\n return null\n}\n\n/** Read and parse `--from <file>`, printing the problem and returning null when it is not one. */\nasync function readBlueprint(\n file: string,\n cwd: string,\n): Promise<Omit<ScaffoldOptions, 'pm'> | null> {\n const { readFileSync } = await import('node:fs')\n const { parseBlueprint, blueprintOptions } = await import('../scaffold/blueprint.js')\n try {\n const raw: unknown = JSON.parse(readFileSync(resolve(cwd, file), 'utf8'))\n return blueprintOptions(parseBlueprint(raw, file))\n } catch (e) {\n console.error(e instanceof Error ? e.message : String(e))\n return null\n }\n}\n\nexport async function create(args: string[], cwd: string = process.cwd()): Promise<void> {\n const yes = args.includes('--yes') || args.includes('-y')\n // Skip flag values (e.g. `bun` in `--pm bun`) so the project name is the first\n // real positional, not a flag's argument.\n const nameArg = positionalArgs(args, [\n 'pm',\n 'package-manager',\n 'theme',\n 'sections',\n 'template',\n 'framework',\n 'runtime',\n 'example',\n 'auth',\n 'from',\n ])[0]\n const themeArg = flagValue(args, 'theme')\n const sectionsArg = flagValue(args, 'sections')\n\n const frameworkArg = (flagValue(args, 'framework') ?? '').toLowerCase()\n if (frameworkArg && !(FRAMEWORKS as readonly string[]).includes(frameworkArg)) {\n console.error(`Unknown framework \"${frameworkArg}\". Expected one of: ${FRAMEWORKS.join(', ')}.`)\n process.exitCode = 1\n return\n }\n\n const runtimeArg = (flagValue(args, 'runtime') ?? '').toLowerCase()\n if (runtimeArg && !isRuntime(runtimeArg)) {\n console.error(`Unknown runtime \"${runtimeArg}\". Expected one of: ${RUNTIMES.join(', ')}.`)\n process.exitCode = 1\n return\n }\n\n const exampleArgs = (flagValue(args, 'example') ?? '')\n .split(',')\n .map((e) => e.trim().toLowerCase())\n .filter(Boolean)\n const badExample = exampleArgs.find((e) => !isExample(e))\n if (badExample) {\n console.error(`Unknown example \"${badExample}\". Expected one of: ${EXAMPLES.join(', ')}.`)\n process.exitCode = 1\n return\n }\n\n const authArg = parseAuth(flagValue(args, 'auth'))\n if (authArg === 'invalid') {\n console.error(\n `Unknown auth \"${flagValue(args, 'auth') ?? ''}\". Expected: access, email, oauth or email,oauth.`,\n )\n process.exitCode = 1\n return\n }\n\n const pmFlag = resolvePackageManagerFlag(args)\n if ('error' in pmFlag) {\n console.error(pmFlag.error)\n process.exitCode = 1\n return\n }\n // The new project has no lock file of its own, but the directory it lands IN usually does\n // — scaffolding into an existing workspace is the common case. `preferLockfileOverUserAgent`\n // makes that walk-up outrank `npm_config_user_agent`, which `npx` always reports as npm no\n // matter what the surrounding repo uses (2026-08-14 §11). With no lock file anywhere up the\n // tree, detection still falls back to the launcher.\n const pm = detectPackageManager(cwd, {\n preferLockfileOverUserAgent: true,\n ...(pmFlag.pm ? { override: pmFlag.pm } : {}),\n })\n\n const interactive = !yes && stdin.isTTY\n const rl = interactive ? createInterface({ input: stdin, output: stdout }) : null\n\n /** The options from flags and, on a terminal, prompts for the ones not given. */\n const prompted = async (): Promise<Omit<ScaffoldOptions, 'pm'>> => {\n let name = nameArg\n if (!name && rl) {\n name = (await rl.question('Project name? [my-cascivo-app]: ')).trim()\n }\n name = name || 'my-cascivo-app'\n\n let theme = (themeArg ?? '').toLowerCase()\n if (!(THEMES as readonly string[]).includes(theme) && rl) {\n theme = (await rl.question(`Theme? (${THEMES.join('/')}) [light]: `)).trim().toLowerCase()\n }\n const resolvedTheme: ThemeName = (THEMES as readonly string[]).includes(theme)\n ? (theme as ThemeName)\n : 'light'\n\n let sectionsInput = sectionsArg\n if (!sectionsInput && rl) {\n sectionsInput = (\n await rl.question(`Nav sections? (comma-separated) [${DEFAULT_SECTIONS.join(', ')}]: `)\n ).trim()\n }\n const sections = (sectionsInput ?? '')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n\n let framework = frameworkArg\n if (!framework && rl) {\n framework = (await rl.question(`Framework? (${FRAMEWORKS.join('/')}) [react-vite]: `))\n .trim()\n .toLowerCase()\n }\n const resolvedFramework: Framework = (FRAMEWORKS as readonly string[]).includes(framework)\n ? (framework as Framework)\n : 'react-vite'\n\n return {\n name,\n framework: resolvedFramework,\n theme: resolvedTheme,\n sections: sections.length > 0 ? sections : DEFAULT_SECTIONS,\n ...(isRuntime(runtimeArg) ? { runtime: runtimeArg } : {}),\n ...(exampleArgs.length > 0 ? { examples: exampleArgs.filter(isExample) } : {}),\n ...(authArg ? { auth: authArg } : {}),\n }\n }\n\n try {\n const fromArg = flagValue(args, 'from')\n const chosen = fromArg ? await readBlueprint(fromArg, cwd) : await prompted()\n if (!chosen) {\n process.exitCode = 1\n return\n }\n const workspace = args.includes('--workspace')\n const opts: ScaffoldOptions = {\n ...chosen,\n ...(fromArg && nameArg ? { name: nameArg } : {}),\n // A workspace is a pnpm workspace: its scripts and CI assume pnpm.\n pm: workspace ? 'pnpm' : pm,\n ...(workspace ? { workspace } : {}),\n }\n const problem = optionsError(opts)\n if (problem) {\n console.error(problem)\n process.exitCode = 1\n return\n }\n const name = opts.name\n const resolvedFramework = opts.framework ?? 'react-vite'\n const resolvedTheme = opts.theme\n\n const targetDir = join(cwd, name)\n if (existsSync(targetDir) && readdirSync(targetDir).length > 0) {\n console.error(`Target directory \"${name}\" already exists and is not empty.`)\n process.exitCode = 1\n return\n }\n\n const files = buildScaffold(opts)\n for (const file of files) {\n await writeFileSafe(join(targetDir, file.path), file.contents)\n }\n\n console.log(\n `\\nCreated ${name} (${resolvedFramework}) with the ${resolvedTheme} theme ` +\n `(${files.length} files).`,\n )\n\n const templateSpec = flagValue(args, 'template')\n if (templateSpec) {\n const { add } = await import('./add.js')\n const { loadConfig } = await import('../utils/config.js')\n console.log(`\\nInstalling template \"${templateSpec}\"…`)\n await add([templateSpec], await loadConfig(), { cwd: targetDir, pm })\n }\n\n console.log('\\nNext steps:')\n console.log(` cd ${name}`)\n console.log(` ${installAllCommand(pm)}`)\n console.log(` ${runScriptCommand(pm, 'dev')}`)\n // Two things the output used to leave the adopter to discover (2026-08-14 §11, §1).\n console.log('\\nGood to know:')\n console.log(' No cascivo.config.ts is written — this app uses the prebuilt @cascivo/react')\n console.log(' packages and never copies source. `cascivo add <component>` writes the')\n console.log(' config itself the first time you vendor a component.')\n if (resolvedFramework === 'cloudflare') {\n console.log('\\n worker/index.ts is the API (wrangler.jsonc routes /api/* to it); `dev`')\n console.log(' runs it in workerd. Deploy with `npx wrangler login` once, then the')\n console.log(` deploy script: ${runExplicitCommand(pm, 'deploy')}`)\n console.log('\\n No account yet? Share a 60-minute preview, claimable into a free account:')\n console.log(` ${runExplicitCommand(pm, 'deploy:preview')}`)\n } else if (resolvedFramework === 'astro') {\n console.log('\\n Pages are real Astro routes — no client router to add. Only src/')\n console.log(' components/Shell.tsx hydrates (client:load, for the mobile nav drawer);')\n console.log(' page content is server-rendered and ships no JS. See')\n console.log(' https://cascivo.com/docs/using-with-astro.md')\n } else {\n console.log('\\n Adding a router? Keep src/Shell.tsx, delete src/App.tsx + src/sections/,')\n console.log(' and register your Link once with setLinkComponent — see')\n console.log(' https://cascivo.com/docs/using-with-a-router.md')\n }\n } finally {\n rl?.close()\n }\n}\n"],"mappings":"igBAQA,MAAaS,EAA2C,CACtD,iBAAkB,SAClB,kBAAmB,QACnB,iBAAkB,SAClB,kBAAmB,SACnB,iBAAkB,QAClB,yBAA0B,QAC1B,eAAgB,SAChB,kBAAmB,SACnB,mBAAoB,SACpB,iBAAkB,OACpB,EAGaC,EAAe,UAMfC,EAAc,QC5B3B,SAASC,EAAc,EAAE,CAAC,IAAI,EAAE,EAAE,WAAW,GAAG,EAAE,EAAE,IAAI,IAAI,OAAO,EAAE,OAAO,EAAE,EAAE,QAAQ,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC,SAASC,EAAY,EAAE,CAAC,OAAO,EAAE,QAAQ,sBAAsB,MAAM,CAAC,CAAC,SAASC,EAAY,EAAE,CAAC,IAAI,EAAEF,EAAc,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,MAAM,MAAM,oDAAoD,EAAE,EAAE,EAAE,EAAE,KAAK,GAAG,EAAE,EAAE,KAAK,CAAC,EAAE,GAAG,YAAY,MAAM,GAAG,EAAE,WAAW,GAAG,EAAE,CAAC,IAAI,EAAE,EAAE,MAAM,CAAC,EAAE,GAAG,CAAC,qBAAqB,KAAK,CAAC,EAAE,MAAM,MAAM,uBAAuB,EAAE,qBAAqB,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,EAAE,GAAG,UAAU,MAAM,EAAE,KAAK,CAAC,EAAE,GAAG,IAAIC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