clawnify 0.15.0 → 0.16.1
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/dist/{chunk-EYT3GVQW.js → chunk-2I4XJ52D.js} +5 -4
- package/dist/chunk-2I4XJ52D.js.map +1 -0
- package/dist/{cli-BOJXG2ZQ.js → cli-KOUOVFNL.js} +218 -12
- package/dist/cli-KOUOVFNL.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/{mcp-VXJ4TMMF.js → mcp-SPP4XMFV.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-EYT3GVQW.js.map +0 -1
- package/dist/cli-BOJXG2ZQ.js.map +0 -1
- /package/dist/{mcp-VXJ4TMMF.js.map → mcp-SPP4XMFV.js.map} +0 -0
|
@@ -573,13 +573,14 @@ async function pollUntilReady(resourceId, options = {}) {
|
|
|
573
573
|
const interval = options.interval ?? 3e3;
|
|
574
574
|
const timeout = options.timeout ?? 3e5;
|
|
575
575
|
const kind = options.kind ?? "app";
|
|
576
|
-
const
|
|
576
|
+
const authedBase = kind === "website" ? "/v1/websites" : "/v1/apps";
|
|
577
|
+
const basePath = options.anonToken ? kind === "website" ? "/v1/anon/websites" : "/v1/anon/apps" : authedBase;
|
|
577
578
|
const start = Date.now();
|
|
578
579
|
let frame = 0;
|
|
579
580
|
const isTTY = Boolean(process.stdout.isTTY);
|
|
580
581
|
let lastMessage = "";
|
|
581
582
|
while (Date.now() - start < timeout) {
|
|
582
|
-
const res = await api.get(`${basePath}/${resourceId}`, { orgId: options.orgId });
|
|
583
|
+
const res = options.anonToken ? await api.request("GET", `${basePath}/${resourceId}`, { token: options.anonToken }) : await api.get(`${basePath}/${resourceId}`, { orgId: options.orgId });
|
|
583
584
|
const data = await res.json();
|
|
584
585
|
const message = data.status_message || data.status;
|
|
585
586
|
if (isTTY) {
|
|
@@ -605,7 +606,7 @@ async function pollUntilReady(resourceId, options = {}) {
|
|
|
605
606
|
}
|
|
606
607
|
|
|
607
608
|
// src/version.ts
|
|
608
|
-
var VERSION = "0.
|
|
609
|
+
var VERSION = "0.16.1";
|
|
609
610
|
|
|
610
611
|
export {
|
|
611
612
|
OAUTH_CLIENT_ID,
|
|
@@ -629,4 +630,4 @@ export {
|
|
|
629
630
|
pollUntilReady,
|
|
630
631
|
VERSION
|
|
631
632
|
};
|
|
632
|
-
//# sourceMappingURL=chunk-
|
|
633
|
+
//# sourceMappingURL=chunk-2I4XJ52D.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/auth.ts","../src/lib/config.ts","../src/lib/api.ts","../src/lib/archive.ts","../src/lib/poll.ts","../src/version.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport crypto from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\n\nconst SUPABASE_URL = \"https://auth.clawnify.com\";\nconst SUPABASE_ANON_KEY =\n \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imh0a3l4Zm1pbXlkeG5iemd4aGZ6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzgzNDk5MjEsImV4cCI6MjA1MzkyNTkyMX0.wopxB_gQSbNMPuxLUNK0BrGXE_0JxJqzMYFPeXFV1GE\";\nexport const OAUTH_CLIENT_ID = \"3defc0e6-80de-4e7a-aa36-0b501c06b697\";\nexport const OAUTH_AUTHORIZE_URL = `${SUPABASE_URL}/auth/v1/oauth/authorize`;\nexport const OAUTH_TOKEN_URL = `${SUPABASE_URL}/auth/v1/oauth/token`;\n\nconst AUTH_DIR = path.join(homedir(), \".clawnify\");\nconst AUTH_FILE = path.join(AUTH_DIR, \"auth.json\");\nconst LOCK_FILE = path.join(AUTH_DIR, \"auth.lock\");\n\n// A refresh POST is a single network round-trip; anything holding the lock\n// longer than this has crashed, so the lock is stolen. The wait timeout is a\n// bit longer so a legitimately in-flight refresh is never pre-empted.\nconst LOCK_STALE_MS = 15_000;\nconst LOCK_WAIT_MS = 20_000;\n\n/**\n * Session credentials only. No org: a machine-global active org made one\n * mutable pointer shared by every shell, worktree and agent on the box, so one\n * session could silently redirect another's commands at a different tenant.\n * The org binding belongs to the folder — see resolveOrgContext.\n */\nexport interface AuthData {\n access_token: string;\n refresh_token: string;\n expires_at: number;\n}\n\nexport function loadAuth(): AuthData | null {\n try {\n const data = fs.readFileSync(AUTH_FILE, \"utf-8\");\n return JSON.parse(data) as AuthData;\n } catch {\n return null;\n }\n}\n\nexport function saveAuth(data: AuthData): void {\n fs.mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 });\n // Whitelist the fields rather than writing `data` wholesale: a legacy\n // org_id/org_slug parsed out of an existing file would otherwise ride along\n // on every token refresh and never drain. This migrates the file silently.\n const { access_token, refresh_token, expires_at } = data;\n fs.writeFileSync(\n AUTH_FILE,\n JSON.stringify({ access_token, refresh_token, expires_at }, null, 2),\n { mode: 0o600 },\n );\n}\n\nexport function clearAuth(): void {\n try {\n fs.unlinkSync(AUTH_FILE);\n } catch {\n // ignore if not exists\n }\n}\n\nexport async function getValidToken(): Promise<string | null> {\n // An env-provided token wins entirely — a headless agent / CI can't do the\n // browser OAuth. CLAWNIFY_TOKEN must be a Supabase access token (JWT), minted\n // by whatever runs the CLI; it is used as-is and never refreshed.\n if (process.env.CLAWNIFY_TOKEN) return process.env.CLAWNIFY_TOKEN;\n\n const auth = loadAuth();\n if (!auth) return null;\n\n const now = Math.floor(Date.now() / 1000);\n if (auth.expires_at - 60 > now) {\n return auth.access_token;\n }\n\n // Locally expired — refresh under a cross-process lock so parallel `clawnify`\n // invocations don't each present the same refresh token (Supabase rotates it\n // on every use and revokes the whole family on reuse).\n return refreshUnderLock(auth.access_token);\n}\n\n/**\n * Force a refresh after the server rejected a token that looked locally valid\n * (family revocation, clock skew, rotation race). Returns a usable access token\n * or null if the session is genuinely dead. Env-token callers can't refresh, so\n * they get null and the caller surfaces the real error.\n */\nexport async function refreshOnUnauthorized(\n rejectedToken: string,\n): Promise<string | null> {\n if (process.env.CLAWNIFY_TOKEN) return null;\n if (!loadAuth()) return null;\n return refreshUnderLock(rejectedToken);\n}\n\n/**\n * Serialize the refresh across processes with an exclusive lock file, then\n * double-check: another invocation may have already rotated the token while we\n * waited. Only the process that still sees the stale token performs the network\n * refresh; everyone else re-reads the freshly rotated token from disk. This is\n * what keeps concurrent invocations from triggering Supabase reuse detection.\n */\nasync function refreshUnderLock(staleToken: string): Promise<string | null> {\n const release = await acquireRefreshLock();\n try {\n const auth = loadAuth();\n if (!auth) return null;\n\n // Someone else refreshed while we waited for the lock — use their token.\n const now = Math.floor(Date.now() / 1000);\n if (auth.access_token !== staleToken && auth.expires_at - 60 > now) {\n return auth.access_token;\n }\n\n const res = await fetch(OAUTH_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: auth.refresh_token,\n client_id: OAUTH_CLIENT_ID,\n }),\n });\n\n if (!res.ok) {\n clearAuth();\n return null;\n }\n\n const tokens = (await res.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n\n const newAuth: AuthData = {\n ...auth,\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token,\n expires_at: Math.floor(Date.now() / 1000) + tokens.expires_in,\n };\n\n saveAuth(newAuth);\n return tokens.access_token;\n } finally {\n release();\n }\n}\n\n/**\n * Acquire an exclusive lock via atomic `O_EXCL` file creation. Waits for a\n * concurrent holder, steals a stale lock (holder crashed), and gives up after\n * LOCK_WAIT_MS to proceed best-effort rather than hang a command forever.\n */\nasync function acquireRefreshLock(): Promise<() => void> {\n fs.mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 });\n const start = Date.now();\n\n for (;;) {\n try {\n const fd = fs.openSync(LOCK_FILE, \"wx\", 0o600);\n fs.closeSync(fd);\n return () => {\n try {\n fs.unlinkSync(LOCK_FILE);\n } catch {\n // already released / stolen — nothing to do\n }\n };\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n\n // Held by another process — steal it if it's stale.\n try {\n const age = Date.now() - fs.statSync(LOCK_FILE).mtimeMs;\n if (age > LOCK_STALE_MS) {\n fs.unlinkSync(LOCK_FILE);\n continue;\n }\n } catch {\n // lock vanished between openSync and statSync — retry immediately\n continue;\n }\n\n if (Date.now() - start > LOCK_WAIT_MS) {\n // Couldn't get the lock in time; proceed unlocked rather than hang.\n return () => {};\n }\n await sleep(50 + Math.floor(Math.random() * 50));\n }\n }\n}\n\nexport async function requireAuth(): Promise<AuthData> {\n // Env override (headless / CI): synthesize AuthData from CLAWNIFY_TOKEN so\n // nothing is read from or written to disk. The org is not carried here —\n // CLAWNIFY_ORG_ID is read by resolveOrgContext like every other source.\n if (process.env.CLAWNIFY_TOKEN) {\n return {\n access_token: process.env.CLAWNIFY_TOKEN,\n refresh_token: \"\",\n expires_at: Number.MAX_SAFE_INTEGER,\n };\n }\n\n const token = await getValidToken();\n if (!token) {\n console.error(\n \"Not logged in. Run `clawnify login`, or set CLAWNIFY_TOKEN (a Supabase access token) for headless / CI use.\",\n );\n process.exit(1);\n }\n return loadAuth()!;\n}\n\n/** Parse email from Supabase JWT claims (base64url-decoded payload) */\nexport function getEmailFromToken(token: string): string | null {\n try {\n const payload = token.split(\".\")[1]!;\n const decoded = JSON.parse(\n Buffer.from(payload, \"base64url\").toString(\"utf-8\")\n );\n return decoded.email ?? null;\n } catch {\n return null;\n }\n}\n\n/** Generate PKCE code_verifier and code_challenge */\nexport function generatePkce(): {\n codeVerifier: string;\n codeChallenge: string;\n} {\n const codeVerifier = crypto.randomBytes(32).toString(\"base64url\");\n const codeChallenge = crypto\n .createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64url\");\n return { codeVerifier, codeChallenge };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface ClawnifyAppConfig {\n framework: string;\n database?: boolean;\n storage?: boolean;\n}\n\nexport interface ClawnifyWebsiteConfig {\n framework: string;\n}\n\n/**\n * An agent member (see `docs/internal/adr-company-monorepo.md` § Layer 1).\n * `harness` selects the runtime adapter — today only `openclaw`, whose\n * payload is `AGENT.md` + `skills/` + `flows/` + `openclaw.json`.\n */\nexport interface ClawnifyAgentConfig {\n harness: string;\n}\n\n/**\n * A workspace root is a monorepo that hosts an org's apps. It carries no\n * `app`/`website` block of its own — its `clawnify.json` declares only the\n * org every child app deploys to. See `docs/internal/adr-company-monorepo.md`.\n */\nexport interface ClawnifyWorkspaceConfig {\n /** Org slug or id this workspace (and every app under it) is bound to. */\n org: string;\n}\n\nexport interface ClawnifyManifest {\n name: string;\n description?: string;\n app?: ClawnifyAppConfig;\n website?: ClawnifyWebsiteConfig;\n /**\n * Overloaded (kept for back-compat with the published schema):\n * - OBJECT `{ harness }` → this project IS an agent (workspace member, #814).\n * - STRING → path to an app's agent-instructions file (schema default\n * \"agent.md\"); an app declares it alongside `app`, and the build reads\n * the file (`app-deployer.ts`). It is NOT a project kind.\n */\n agent?: ClawnifyAgentConfig | string;\n workspace?: ClawnifyWorkspaceConfig;\n}\n\nexport type ManifestKind = \"app\" | \"website\" | \"agent\";\n\n/** Anonymous-deploy context: the unclaimed org this folder deploys into.\n * deploy_token authorizes /v1/anon/* only and dies at claim or expiry. */\nexport interface AnonContext {\n org_id: string;\n deploy_token: string;\n claim_url: string;\n claim_expires_at: string;\n}\n\nexport interface ProjectConfig {\n kind?: ManifestKind;\n org_id?: string;\n org_slug?: string;\n app_id?: string;\n app_token?: string;\n website_id?: string;\n slug?: string;\n /** Agent link: the server + named agent this member deploys to. */\n server_id?: string;\n agent_name?: string;\n /** Present while this folder deploys anonymously (no login). */\n anon?: AnonContext;\n}\n\nexport function readManifest(dir: string = process.cwd()): ClawnifyManifest | null {\n try {\n const data = fs.readFileSync(path.join(dir, \"clawnify.json\"), \"utf-8\");\n const manifest = JSON.parse(data) as ClawnifyManifest;\n if (!manifest.name) return null;\n if (!manifest.app && !manifest.website && !manifest.agent) return null;\n return manifest;\n } catch {\n return null;\n }\n}\n\n/**\n * Returns the manifest kind, or throws with a clear message when neither or\n * both blocks are present. Callers should run this before dispatching deploy.\n */\nexport function manifestKind(manifest: ClawnifyManifest): ManifestKind {\n // `agent` is a project kind ONLY when it's an object ({ harness }). A string\n // value is an app's agent-instructions file path (schema default \"agent.md\"),\n // declared alongside `app` — it must not be counted as a second kind, or\n // every app that references its agent.md fails with a false \"more than one\n // kind\" error (open-crm, open-kitchen, …).\n const isAgentProject =\n typeof manifest.agent === \"object\" && manifest.agent !== null;\n const present: ManifestKind[] = [\n manifest.app ? \"app\" : null,\n manifest.website ? \"website\" : null,\n isAgentProject ? \"agent\" : null,\n ].filter((k): k is ManifestKind => k !== null);\n if (present.length > 1) {\n throw new Error(\n `clawnify.json declares more than one of \\`app\\`, \\`website\\`, \\`agent\\` (${present.join(\", \")}) — a project is exactly one kind.`,\n );\n }\n if (present.length === 0) {\n throw new Error(\n \"clawnify.json must declare an `app`, `website`, or `agent` block.\",\n );\n }\n return present[0]!;\n}\n\nexport function readProject(dir: string = process.cwd()): ProjectConfig | null {\n try {\n const data = fs.readFileSync(\n path.join(dir, \".clawnify\", \"project.json\"),\n \"utf-8\"\n );\n return JSON.parse(data) as ProjectConfig;\n } catch {\n return null;\n }\n}\n\n/**\n * The nearest `.clawnify/project.json` at or above `startDir`.\n *\n * Deliberately NOT folded into readProject(): that is used by paths which write\n * (`agents.ts` merges over it before saveProject) and by deploy, where \"which\n * folder am I in\" is the question being asked. Walking there would let a child\n * directory inherit — and then persist — a parent app's id and token.\n *\n * Org resolution is the opposite case: which org a command acts on shouldn't\n * change just because you cd'd into src/. Mirrors findWorkspaceRoot below, and\n * the way `supabase` resolves its project root from the nearest ancestor.\n */\nexport function findProjectRoot(\n startDir: string = process.cwd(),\n): ProjectConfig | null {\n let cur = path.resolve(startDir);\n for (;;) {\n const proj = readProject(cur);\n if (proj) return proj;\n const parent = path.dirname(cur);\n if (parent === cur) return null;\n cur = parent;\n }\n}\n\nexport function saveProject(dir: string, data: ProjectConfig): void {\n const projDir = path.join(dir, \".clawnify\");\n fs.mkdirSync(projDir, { recursive: true });\n fs.writeFileSync(\n path.join(projDir, \"project.json\"),\n JSON.stringify(data, null, 2)\n );\n}\n\nexport interface WorkspaceRoot {\n /** Absolute path to the workspace root directory. */\n dir: string;\n /** Org slug or id the workspace is bound to. */\n org: string;\n}\n\n/**\n * Read a workspace root's binding from `clawnify.json` at `dir`, or null if\n * that dir isn't a workspace root. A workspace is discriminated by the\n * presence of a `workspace.org` field (mirrors how app/website are detected).\n */\nexport function readWorkspaceConfig(dir: string): WorkspaceRoot | null {\n try {\n const data = fs.readFileSync(path.join(dir, \"clawnify.json\"), \"utf-8\");\n const manifest = JSON.parse(data) as ClawnifyManifest;\n if (manifest.workspace?.org) return { dir, org: manifest.workspace.org };\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * Walk up from `startDir` to the filesystem root, returning the nearest\n * enclosing workspace root, or null if there is none. Used so `init` drops\n * new apps under `apps/` and `deploy` inherits the org for a fresh app.\n */\nexport function findWorkspaceRoot(\n startDir: string = process.cwd(),\n): WorkspaceRoot | null {\n let cur = path.resolve(startDir);\n for (;;) {\n const ws = readWorkspaceConfig(cur);\n if (ws) return ws;\n const parent = path.dirname(cur);\n if (parent === cur) return null;\n cur = parent;\n }\n}\n","import {\n requireAuth,\n loadAuth,\n saveAuth,\n refreshOnUnauthorized,\n type AuthData,\n} from \"./auth.js\";\nimport { findProjectRoot, findWorkspaceRoot } from \"./config.js\";\nimport readline from \"node:readline\";\n\n// Overridable for CLI development against a local `wrangler dev` API.\nconst API_BASE = process.env.CLAWNIFY_API_BASE ?? \"https://provision.clawnify.com\";\n\nconst UUID_RE =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nasync function apiRequest(\n method: string,\n path: string,\n options?: {\n body?: unknown;\n formData?: FormData;\n token?: string;\n orgId?: string;\n }\n): Promise<Response> {\n const headers: Record<string, string> = {};\n\n if (options?.token) {\n headers[\"Authorization\"] = `Bearer ${options.token}`;\n }\n if (options?.orgId) {\n // The header carries a UUID and nothing else. A slug here does not fail\n // loudly — it fails as \"some other org\" — so an unresolved value must be\n // caught at the boundary that builds the request, not discovered later in\n // whichever org the server settled on. Callers pass ids from matchOrg() /\n // resolveOrgContext(); raw user input belongs in `orgFlag`, not here.\n if (!UUID_RE.test(options.orgId)) {\n throw new Error(\n `Internal: x-org-id must be an org UUID, got \"${options.orgId}\". ` +\n `Resolve it with resolveOrgContext({ orgFlag }) first.`,\n );\n }\n headers[\"x-org-id\"] = options.orgId;\n }\n\n let body: BodyInit | undefined;\n if (options?.formData) {\n body = options.formData;\n } else if (options?.body) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(options.body);\n }\n\n return fetch(`${API_BASE}${path}`, { method, headers, body });\n}\n\nasync function ensureOrg(auth: AuthData): Promise<string | undefined> {\n // Any `org_id` still sitting in auth.json is a legacy artifact from when\n // `org use` wrote machine-global state. Honouring it here would keep that\n // behaviour alive for everyone who already has the file, so it is ignored\n // and left to be dropped on the next login.\n\n // Fetch orgs and prompt\n const orgsRes = await apiRequest(\"GET\", \"/v1/orgs\", { token: auth.access_token });\n if (!orgsRes.ok) return undefined;\n\n const { orgs } = (await orgsRes.json()) as {\n orgs: Array<{ id: string; name: string; slug: string; role: string }>;\n };\n\n if (orgs.length === 0) return undefined;\n\n let orgId: string;\n if (orgs.length === 1) {\n orgId = orgs[0].id;\n } else if (!process.stdin.isTTY || process.env.CLAWNIFY_TOKEN) {\n // Non-interactive (headless agent / CI / env auth): can't prompt — default\n // to the first org and tell the caller how to pin one.\n console.error(\n `Multiple orgs — defaulting to \"${orgs[0].name}\". Pin with CLAWNIFY_ORG_ID or --org.`,\n );\n orgId = orgs[0].id;\n } else {\n console.log(\"\\nSelect an organization:\\n\");\n orgs.forEach((org, i) => {\n console.log(` ${i + 1}) ${org.name} (${org.role})`);\n });\n console.log();\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n const choice = await new Promise<string>((resolve) => {\n rl.question(\"Enter number: \", (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n\n const index = parseInt(choice, 10) - 1;\n orgId = (index >= 0 && index < orgs.length) ? orgs[index].id : orgs[0].id;\n console.log(`Selected: ${orgs[index >= 0 && index < orgs.length ? index : 0].name}\\n`);\n }\n\n // Deliberately NOT persisted. Writing the choice back to auth.json is what\n // created the machine-global active org in the first place. The durable\n // binding belongs to the folder (clawnify.json `workspace.org`, or\n // `.clawnify/project.json` via `clawnify link`), not to the machine.\n if (orgs.length > 1) {\n const chosen = orgs.find((o) => o.id === orgId);\n console.error(\n ` Using ${chosen?.name ?? orgId} for this command only.\\n` +\n ` Pin it so every command in this folder agrees: clawnify link <app> --org ${chosen?.slug ?? orgId}\\n` +\n ` (or set workspace.org in clawnify.json, or pass --org).`,\n );\n }\n return orgId;\n}\n\ntype OrgSource = \"flag\" | \"env\" | \"link\" | \"workspace\";\nlet orgCtxCache: string | undefined | null = null;\nlet orgEchoed = false;\n\n/** Print the org a command is acting on, once, to stderr (keeps stdout clean). */\nfunction echoOrg(label: string, source: OrgSource): void {\n if (orgEchoed) return;\n orgEchoed = true;\n process.stderr.write(`→ org: ${label} (${source})\\n`);\n}\n\nasync function matchOrg(ref: string): Promise<{ id: string; slug: string }> {\n const orgs = await listMyOrgs();\n const m = orgs.find((o) => o.id === ref || o.slug === ref);\n if (!m) {\n console.error(`No org matched \"${ref}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`);\n process.exit(1);\n }\n return { id: m.id, slug: m.slug };\n}\n\n/**\n * Resolve which org the current command targets, folder-first:\n * --org → CLAWNIFY_ORG_ID → .clawnify/project.json org_id → workspace.org\n *\n * There is deliberately no machine-global fallback. Org is a property of the\n * directory you are standing in, never of the machine, so a second shell,\n * worktree or agent cannot repoint what this command targets. Memoized and\n * echoed once; returns undefined when nothing resolves, leaving the decision to\n * ensureOrg (single org → use it, otherwise prompt).\n */\nexport async function resolveOrgContext(\n opts?: { orgFlag?: string; dir?: string },\n): Promise<string | undefined> {\n if (orgCtxCache !== null) return orgCtxCache;\n const dir = opts?.dir ?? process.cwd();\n\n if (opts?.orgFlag) {\n const m = await matchOrg(opts.orgFlag);\n const proj = findProjectRoot(dir);\n if (proj?.org_id && proj.org_id !== m.id) {\n console.error(\n `This folder is linked to a different org (${proj.org_slug ?? proj.org_id}).\\n` +\n ` --org ${opts.orgFlag} resolves to ${m.slug}. Re-link, or run from another directory.`,\n );\n process.exit(1);\n }\n orgCtxCache = m.id;\n echoOrg(m.slug, \"flag\");\n return m.id;\n }\n\n const env = process.env.CLAWNIFY_ORG_ID;\n if (env) {\n // Accepts a slug as well as a UUID, like --org. A slug used to be passed\n // through untouched and land as \"some other org\" server-side; resolving it\n // here keeps CI configs honest. UUIDs skip the lookup — the common case\n // shouldn't pay for a network round-trip.\n const id = UUID_RE.test(env) ? env : (await matchOrg(env)).id;\n orgCtxCache = id;\n echoOrg(env, \"env\");\n return id;\n }\n\n const proj = findProjectRoot(dir);\n if (proj?.org_id) {\n orgCtxCache = proj.org_id;\n echoOrg(proj.org_slug ?? proj.org_id, \"link\");\n return proj.org_id;\n }\n\n const ws = findWorkspaceRoot(dir);\n if (ws?.org) {\n const m = await matchOrg(ws.org);\n orgCtxCache = m.id;\n echoOrg(m.slug, \"workspace\");\n return m.id;\n }\n\n // NO machine-global fallback. `~/.clawnify/auth.json` is an auth artifact and\n // must not carry a project binding: it is one mutable pointer shared by every\n // shell, worktree and agent on the box, so one session repointing it silently\n // redirected another session's commands at a different tenant. Falling through\n // to undefined hands the decision to ensureOrg, which resolves an unambiguous\n // single org and otherwise prompts — a better answer than a stale global.\n orgCtxCache = undefined;\n return undefined;\n}\n\nasync function authedRequest(\n method: string,\n path: string,\n options?: { body?: unknown; formData?: FormData; orgId?: string }\n): Promise<Response> {\n let auth = await requireAuth();\n let orgId = options?.orgId;\n if (!orgId) {\n orgId = await resolveOrgContext();\n if (!orgId) {\n orgId = await ensureOrg(auth);\n }\n }\n\n const res = await apiRequest(method, path, {\n ...options,\n token: auth.access_token,\n orgId,\n });\n\n if (res.status !== 401) return res;\n\n // A 401 is not necessarily an expired session: the token may have been\n // rotated by a concurrent invocation, revoked, or the route itself may be\n // rejecting an otherwise-valid token. Attempt exactly one silent refresh and\n // retry before deciding it's a login problem.\n const fresh = await refreshOnUnauthorized(auth.access_token);\n if (!fresh) {\n if (process.env.CLAWNIFY_TOKEN) {\n console.error(\"CLAWNIFY_TOKEN was rejected (401). Provide a valid Supabase access token.\");\n } else {\n console.error(\"Session expired. Run `clawnify login` again.\");\n }\n process.exit(1);\n }\n\n // Retry once with the refreshed token. If it still 401s, this isn't a session\n // problem — return the response so the caller surfaces the real error instead\n // of masquerading it as a login failure.\n return apiRequest(method, path, {\n ...options,\n token: fresh,\n orgId,\n });\n}\n\nexport interface Org {\n id: string;\n name: string;\n slug: string;\n role: string;\n}\n\n/** List every org the authenticated user belongs to, bypassing org selection. */\nexport async function listMyOrgs(): Promise<Org[]> {\n const auth = await requireAuth();\n const res = await apiRequest(\"GET\", \"/v1/orgs\", { token: auth.access_token });\n if (!res.ok) return [];\n const { orgs } = (await res.json()) as { orgs: Org[] };\n return orgs ?? [];\n}\n\nexport const api = {\n get: (path: string, opts?: { orgId?: string }) =>\n authedRequest(\"GET\", path, opts),\n post: (path: string, body?: unknown, opts?: { orgId?: string }) =>\n authedRequest(\"POST\", path, { body, ...opts }),\n postForm: (path: string, formData: FormData, opts?: { orgId?: string }) =>\n authedRequest(\"POST\", path, { formData, ...opts }),\n del: (path: string, opts?: { orgId?: string }) =>\n authedRequest(\"DELETE\", path, opts),\n // Generic authed request for the `clawnify api` escape hatch (any method).\n call: (method: string, path: string, opts?: { body?: unknown; orgId?: string }) =>\n authedRequest(method, path, opts),\n request: apiRequest,\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport { gzipSync } from \"node:zlib\";\n\nconst EXCLUDE_DIRS = new Set([\n \"node_modules\",\n \".git\",\n \"dist\",\n \".next\",\n \".clawnify\",\n \"build\",\n]);\n\nconst MAX_SIZE = 20 * 1024 * 1024; // 20MB\n\nfunction runGit(args: string[], dir: string): string | null {\n try {\n return execSync(`git ${args.join(\" \")}`, {\n cwd: dir,\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // execSync's default maxBuffer is 1MB. `ls-files --others` enumerates\n // every file under an unignored node_modules, which easily exceeds that —\n // the throw was caught below and untracked files silently vanished from\n // the archive (new assets never deployed).\n maxBuffer: 64 * 1024 * 1024,\n });\n } catch {\n return null;\n }\n}\n\n/**\n * Collect every file `git add .` would stage: tracked files plus untracked\n * files that aren't ignored. Returns null if the directory isn't a git repo,\n * so the caller falls back to walkDir.\n *\n * The previous implementation used only `git ls-files`, which silently\n * excluded brand-new untracked files — a common foot-gun when an agent\n * (or human) creates a file but forgets to `git add` it.\n */\nfunction getGitFiles(dir: string): string[] | null {\n const tracked = runGit([\"ls-files\", \"-z\"], dir);\n if (tracked === null) return null;\n const untrackedResult = runGit([\"ls-files\", \"-z\", \"--others\", \"--exclude-standard\"], dir);\n if (untrackedResult === null) {\n // Never fail silently here: proceeding without untracked files means a\n // brand-new asset quietly missing from the deployed site.\n console.warn(\n \" warning: could not list untracked files (git ls-files --others failed); \" +\n \"newly created files that aren't committed may be missing from this deploy.\",\n );\n }\n const untracked = untrackedResult ?? \"\";\n const merged = new Set<string>();\n for (const f of tracked.split(\"\\0\")) if (f) merged.add(f);\n for (const f of untracked.split(\"\\0\")) if (f) merged.add(f);\n return [...merged];\n}\n\nfunction walkDir(dir: string, base: string = \"\"): string[] {\n const files: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (EXCLUDE_DIRS.has(entry.name)) continue;\n const rel = base ? `${base}/${entry.name}` : entry.name;\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...walkDir(full, rel));\n } else if (entry.isFile()) {\n files.push(rel);\n }\n }\n return files;\n}\n\n/**\n * A repo-root `manifest.json` is not part of the clawnify contract\n * (clawnify.json is). Some templates leave a Preact-style manifest behind;\n * users see \"manifest\" and assume it controls something. Warn so they know\n * it's being uploaded as a dumb file.\n */\nfunction warnOnStaleManifest(dir: string, files: string[]) {\n if (!files.includes(\"manifest.json\")) return;\n try {\n const raw = fs.readFileSync(path.join(dir, \"manifest.json\"), \"utf-8\");\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n if (parsed && typeof parsed === \"object\" && \"framework\" in parsed && \"files\" in parsed) {\n console.warn(\n ` warning: manifest.json looks like a stale auto-generated file. ` +\n `Clawnify uses clawnify.json — manifest.json is ignored.`,\n );\n }\n } catch {\n // not JSON, not our concern\n }\n}\n\n/**\n * EXCLUDE_DIRS must hold on BOTH listing paths. The git path lists whatever\n * git would stage — which includes `.clawnify/` (app_token!) or `.env` when\n * the surrounding repo's .gitignore doesn't cover them (e.g. a cloned\n * template). Those must never be uploaded regardless of git status.\n */\nfunction isExcludedPath(rel: string): boolean {\n const parts = rel.split(\"/\");\n return parts.some((p) => EXCLUDE_DIRS.has(p)) || parts[parts.length - 1] === \".env\";\n}\n\nfunction listFiles(dir: string): string[] {\n const fromGit = getGitFiles(dir);\n const files = (fromGit ?? walkDir(dir)).filter((f) => !isExcludedPath(f));\n warnOnStaleManifest(dir, files);\n return files;\n}\n\n/** Public helper for `clawnify deploy --dry-run`. */\nexport function listArchiveFiles(dir: string): string[] {\n return listFiles(dir);\n}\n\nfunction createTarHeader(filename: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(filename, 0, Math.min(filename.length, 100), \"utf-8\");\n header.write(\"0000644\\0\", 100, 8, \"utf-8\");\n header.write(\"0000000\\0\", 108, 8, \"utf-8\");\n header.write(\"0000000\\0\", 116, 8, \"utf-8\");\n header.write(size.toString(8).padStart(11, \"0\") + \"\\0\", 124, 12, \"utf-8\");\n const mtime = Math.floor(Date.now() / 1000);\n header.write(mtime.toString(8).padStart(11, \"0\") + \"\\0\", 136, 12, \"utf-8\");\n header.write(\"0\", 156, 1, \"utf-8\");\n header.write(\"ustar\\0\", 257, 6, \"utf-8\");\n header.write(\"00\", 263, 2, \"utf-8\");\n header.write(\" \", 148, 8, \"utf-8\");\n let checksum = 0;\n for (let i = 0; i < 512; i++) {\n checksum += header[i]!;\n }\n header.write(checksum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, 8, \"utf-8\");\n return header;\n}\n\n/**\n * Drizzle migrations live under `.clawnify/drizzle/<NNNN>_<name>.sql`\n * locally (gitignored, regenerated by the CLI on dev/deploy). The\n * deploy pipeline (PR #444) scans R2's `drizzle/` prefix on each\n * deploy. We remap on upload — the user's repo stays clean, the\n * pipeline contract is unchanged.\n *\n * Only top-level `*.sql` files come along; drizzle's `meta/` snapshot\n * dir is local-only state.\n */\nfunction collectDrizzleMigrations(\n dir: string,\n): { src: string; tarName: string }[] {\n const drizzleDir = path.join(dir, \".clawnify\", \"drizzle\");\n if (!fs.existsSync(drizzleDir)) return [];\n try {\n return fs\n .readdirSync(drizzleDir)\n .filter((name) => name.endsWith(\".sql\"))\n .sort()\n .map((name) => ({\n src: path.join(drizzleDir, name),\n tarName: `drizzle/${name}`,\n }));\n } catch {\n return [];\n }\n}\n\nexport function createArchive(dir: string): { archive: Buffer; files: string[] } {\n const files = listFiles(dir);\n const parts: Buffer[] = [];\n const includedFiles: string[] = [];\n\n function addEntry(absPath: string, tarName: string): void {\n let stat: fs.Stats;\n try {\n stat = fs.statSync(absPath);\n } catch {\n return;\n }\n if (!stat.isFile()) return;\n\n const content = fs.readFileSync(absPath);\n const header = createTarHeader(tarName, content.length);\n parts.push(header);\n parts.push(content);\n includedFiles.push(tarName);\n\n const remainder = content.length % 512;\n if (remainder > 0) {\n parts.push(Buffer.alloc(512 - remainder));\n }\n }\n\n for (const file of files) {\n addEntry(path.join(dir, file), file);\n }\n\n for (const m of collectDrizzleMigrations(dir)) {\n addEntry(m.src, m.tarName);\n }\n\n parts.push(Buffer.alloc(1024));\n\n const tar = Buffer.concat(parts);\n const gzipped = gzipSync(tar);\n\n if (gzipped.length > MAX_SIZE) {\n throw new Error(\n `Archive too large (${(gzipped.length / 1024 / 1024).toFixed(1)}MB). Maximum is 20MB.`,\n );\n }\n\n return { archive: gzipped, files: includedFiles };\n}\n","import { api } from \"./api.js\";\n\nconst SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\n\nexport interface AppStatus {\n status: string;\n status_message?: string;\n url?: string;\n error?: string;\n}\n\n// Status values that mean we're done — apps use \"live\"/\"error\", websites\n// use \"live\"/\"failed\". Pollers stop on any of these.\nconst TERMINAL_STATUSES = new Set([\"live\", \"ready\", \"error\", \"failed\"]);\nconst FAILURE_STATUSES = new Set([\"error\", \"failed\"]);\n// Draft-first: a CLI website deploy builds to the draft tier and parks at\n// \"preview\" (publishing to live is an explicit, separate action from the\n// dashboard). So \"preview\" is a terminal SUCCESS for websites — without this\n// the poller would spin until it times out on a perfectly good deploy.\nconst WEBSITE_TERMINAL_SUCCESS = new Set([\"preview\"]);\n\nexport async function pollUntilReady(\n resourceId: string,\n options: {\n interval?: number;\n timeout?: number;\n kind?: \"app\" | \"website\";\n orgId?: string;\n /** Anonymous deploy token — polls /v1/anon/* instead of the authed surface. */\n anonToken?: string;\n } = {},\n): Promise<AppStatus> {\n const interval = options.interval ?? 3000;\n const timeout = options.timeout ?? 300000;\n const kind = options.kind ?? \"app\";\n const authedBase = kind === \"website\" ? \"/v1/websites\" : \"/v1/apps\";\n const basePath = options.anonToken\n ? (kind === \"website\" ? \"/v1/anon/websites\" : \"/v1/anon/apps\")\n : authedBase;\n const start = Date.now();\n let frame = 0;\n const isTTY = Boolean(process.stdout.isTTY);\n let lastMessage = \"\";\n\n while (Date.now() - start < timeout) {\n const res = options.anonToken\n ? await api.request(\"GET\", `${basePath}/${resourceId}`, { token: options.anonToken })\n : await api.get(`${basePath}/${resourceId}`, { orgId: options.orgId });\n const data = (await res.json()) as AppStatus;\n const message = data.status_message || data.status;\n\n if (isTTY) {\n const spinner = SPINNER_FRAMES[frame % SPINNER_FRAMES.length];\n process.stdout.write(`\\r${spinner} ${message}`);\n } else if (message !== lastMessage) {\n // Non-TTY (CI logs, background tasks): write whole lines so the\n // output survives in pipes and files instead of being mangled by\n // cursor escapes from the spinner.\n console.log(`status: ${message}`);\n lastMessage = message;\n }\n frame++;\n\n const terminal =\n TERMINAL_STATUSES.has(data.status) ||\n (kind === \"website\" && WEBSITE_TERMINAL_SUCCESS.has(data.status));\n if (terminal) {\n if (isTTY) process.stdout.write(\"\\r\\x1b[K\");\n // Normalize \"failed\" to \"error\" so downstream callers only branch\n // on one terminal-failure value.\n if (FAILURE_STATUSES.has(data.status)) {\n return { ...data, status: \"error\" };\n }\n return data;\n }\n\n await new Promise((r) => setTimeout(r, interval));\n }\n\n if (isTTY) process.stdout.write(\"\\r\\x1b[K\");\n throw new Error(\"Timed out waiting for deployment\");\n}\n","/**\n * The CLI's real version, injected at build time from package.json by\n * tsup.config.ts. package.json stays the single source of truth — bumping it\n * IS the release (see .github/workflows/publish-cli.yml), and this makes\n * `clawnify --version` say the same thing.\n *\n * It used to be a hardcoded \"0.1.0\" in cli.ts and mcp.ts, which meant every\n * build ever published reported the same string. That made \"are you on the\n * fixed CLI?\" unanswerable — a stale global install (npm installs into the\n * ACTIVE nvm node version, so one per node version is easy to end up with)\n * was indistinguishable from a current one.\n */\ndeclare const __CLI_VERSION__: string;\n\nexport const VERSION = __CLI_VERSION__;\n"],"mappings":";;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,YAAY;AACnB,SAAS,eAAe;AACxB,SAAS,cAAc,aAAa;AAEpC,IAAM,eAAe;AAGd,I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AQ,eAAe,MAAM;AAC5D,cAAQ,OAAO,MAAM,KAAK,OAAO,IAAI,OAAO,EAAE;AAAA,IAChD,WAAW,YAAY,aAAa;AAIlC,cAAQ,IAAI,WAAW,OAAO,EAAE;AAChC,oBAAc;AAAA,IAChB;AACA;AAEA,UAAM,WACJ,kBAAkB,IAAI,KAAK,MAAM,KAChC,SAAS,aAAa,yBAAyB,IAAI,KAAK,MAAM;AACjE,QAAI,UAAU;AACZ,UAAI,MAAO,SAAQ,OAAO,MAAM,UAAU;AAG1C,UAAI,iBAAiB,IAAI,KAAK,MAAM,GAAG;AACrC,eAAO,EAAE,GAAG,MAAM,QAAQ,QAAQ;AAAA,MACpC;AACA,aAAO;AAAA,IACT;AAEA,UAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,QAAQ,CAAC;AAAA,EAClD;AAEA,MAAI,MAAO,SAAQ,OAAO,MAAM,UAAU;AAC1C,QAAM,IAAI,MAAM,kCAAkC;AACpD;;;ACnEO,IAAM,UAAU;","names":["fs","path","path","proj","fs","path","path","fs"]}
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
resolveOrgContext,
|
|
21
21
|
saveAuth,
|
|
22
22
|
saveProject
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-2I4XJ52D.js";
|
|
24
24
|
|
|
25
25
|
// src/cli.ts
|
|
26
26
|
import { Command, Option } from "commander";
|
|
@@ -180,6 +180,90 @@ import path2 from "path";
|
|
|
180
180
|
import readline2 from "readline";
|
|
181
181
|
import { spawn } from "child_process";
|
|
182
182
|
|
|
183
|
+
// src/lib/anon.ts
|
|
184
|
+
function isLoggedOut() {
|
|
185
|
+
return !process.env.CLAWNIFY_TOKEN && !loadAuth();
|
|
186
|
+
}
|
|
187
|
+
function anonExpired(ctx) {
|
|
188
|
+
return new Date(ctx.claim_expires_at).getTime() <= Date.now();
|
|
189
|
+
}
|
|
190
|
+
function saveAnon(dir, ctx, extra = {}) {
|
|
191
|
+
const existing = readProject(dir) ?? {};
|
|
192
|
+
saveProject(dir, { ...existing, ...extra, org_id: ctx.org_id, anon: ctx });
|
|
193
|
+
}
|
|
194
|
+
function clearAnon(dir) {
|
|
195
|
+
const existing = readProject(dir);
|
|
196
|
+
if (!existing?.anon) return;
|
|
197
|
+
const {
|
|
198
|
+
anon: _anon,
|
|
199
|
+
app_id: _a,
|
|
200
|
+
website_id: _w,
|
|
201
|
+
slug: _s,
|
|
202
|
+
org_id: _o,
|
|
203
|
+
app_token: _t,
|
|
204
|
+
...rest
|
|
205
|
+
} = existing;
|
|
206
|
+
saveProject(dir, rest);
|
|
207
|
+
}
|
|
208
|
+
async function getOrCreateAnonContext(dir, name) {
|
|
209
|
+
const existing = readProject(dir)?.anon;
|
|
210
|
+
if (existing && !anonExpired(existing)) {
|
|
211
|
+
return { ctx: existing, created: false };
|
|
212
|
+
}
|
|
213
|
+
if (existing) clearAnon(dir);
|
|
214
|
+
const res = await api.request("POST", "/claims/orgs", { body: { name } });
|
|
215
|
+
if (!res.ok) {
|
|
216
|
+
const err = await res.json().catch(() => ({}));
|
|
217
|
+
console.error(
|
|
218
|
+
`Could not start an anonymous deploy: ${err.error || res.statusText}
|
|
219
|
+
You can always deploy signed in: clawnify login`
|
|
220
|
+
);
|
|
221
|
+
process.exit(1);
|
|
222
|
+
}
|
|
223
|
+
const data = await res.json();
|
|
224
|
+
const ctx = {
|
|
225
|
+
org_id: data.org_id,
|
|
226
|
+
deploy_token: data.deploy_token,
|
|
227
|
+
claim_url: data.claim_url,
|
|
228
|
+
claim_expires_at: data.claim_expires_at
|
|
229
|
+
};
|
|
230
|
+
saveAnon(dir, ctx);
|
|
231
|
+
return { ctx, created: true };
|
|
232
|
+
}
|
|
233
|
+
async function anonPostForm(path10, formData, ctx) {
|
|
234
|
+
return api.request("POST", path10, { formData, token: ctx.deploy_token });
|
|
235
|
+
}
|
|
236
|
+
function explainAnonUnauthorized(dir) {
|
|
237
|
+
clearAnon(dir);
|
|
238
|
+
console.error(
|
|
239
|
+
"This temporary workspace is no longer writable (claimed or expired).\n Run `clawnify deploy` again to start a fresh one, or sign in: clawnify login"
|
|
240
|
+
);
|
|
241
|
+
process.exit(1);
|
|
242
|
+
}
|
|
243
|
+
async function healStaleAnonLink(dir, ctx) {
|
|
244
|
+
console.log("\nThis folder was linked to a temporary workspace this account can't access.");
|
|
245
|
+
if (new Date(ctx.claim_expires_at).getTime() > Date.now()) {
|
|
246
|
+
console.log("If nobody claimed it yet, it is still claimable:");
|
|
247
|
+
printClaimBlock(ctx);
|
|
248
|
+
}
|
|
249
|
+
clearAnon(dir);
|
|
250
|
+
const orgId = await resolveOrgContext({ dir });
|
|
251
|
+
console.log("Deploying into your own workspace instead...\n");
|
|
252
|
+
return orgId;
|
|
253
|
+
}
|
|
254
|
+
function printClaimBlock(ctx) {
|
|
255
|
+
const hoursLeft = Math.max(
|
|
256
|
+
1,
|
|
257
|
+
Math.round((new Date(ctx.claim_expires_at).getTime() - Date.now()) / 36e5)
|
|
258
|
+
);
|
|
259
|
+
console.log(
|
|
260
|
+
` Keep it: ${ctx.claim_url}
|
|
261
|
+
Sign in with Google there to make this workspace yours.
|
|
262
|
+
Unclaimed workspaces are deleted after ~${hoursLeft}h.
|
|
263
|
+
`
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
|
|
183
267
|
// src/lib/sync-schema.ts
|
|
184
268
|
import fs from "fs/promises";
|
|
185
269
|
import path from "path";
|
|
@@ -527,6 +611,54 @@ async function deployWebsite(dir, options) {
|
|
|
527
611
|
const baseName = options.name || manifest?.name || path2.basename(resolvedDir);
|
|
528
612
|
const linkedProject = readProject(resolvedDir);
|
|
529
613
|
const { archive, files } = createArchive(resolvedDir);
|
|
614
|
+
if (isLoggedOut() && !options.org) {
|
|
615
|
+
if (options.dryRun) {
|
|
616
|
+
const sizeKB = (archive.length / 1024).toFixed(1);
|
|
617
|
+
console.log(`
|
|
618
|
+
Dry run \u2014 would deploy website '${baseName}' anonymously (astro)`);
|
|
619
|
+
console.log(` Archive: ${files.length} files, ${sizeKB}KB gzipped
|
|
620
|
+
`);
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
const { ctx, created } = await getOrCreateAnonContext(resolvedDir, baseName);
|
|
624
|
+
console.log(
|
|
625
|
+
created ? `No account detected \u2014 deploying ${baseName} to a temporary workspace...` : `Updating ${baseName} (temporary workspace)...`
|
|
626
|
+
);
|
|
627
|
+
const formData = new FormData();
|
|
628
|
+
formData.append("source", new Blob([archive]), "source.tar.gz");
|
|
629
|
+
formData.append("name", baseName);
|
|
630
|
+
const res = await anonPostForm("/v1/anon/websites/deploy", formData, ctx);
|
|
631
|
+
if (res.status === 401) explainAnonUnauthorized(resolvedDir);
|
|
632
|
+
if (!res.ok) {
|
|
633
|
+
const err = await res.json().catch(() => ({}));
|
|
634
|
+
console.error(`Deploy failed: ${err.error || res.statusText}`);
|
|
635
|
+
process.exit(1);
|
|
636
|
+
}
|
|
637
|
+
const data = await res.json();
|
|
638
|
+
saveProject(resolvedDir, {
|
|
639
|
+
...readProject(resolvedDir) ?? {},
|
|
640
|
+
kind: "website",
|
|
641
|
+
org_id: ctx.org_id,
|
|
642
|
+
website_id: data.website_id,
|
|
643
|
+
slug: data.slug,
|
|
644
|
+
anon: ctx
|
|
645
|
+
});
|
|
646
|
+
const polled2 = await pollUntilReady(data.website_id, {
|
|
647
|
+
kind: "website",
|
|
648
|
+
anonToken: ctx.deploy_token
|
|
649
|
+
});
|
|
650
|
+
if (polled2.status === "error" || polled2.status === "failed") {
|
|
651
|
+
console.error(`
|
|
652
|
+
Deploy failed: ${polled2.error || "Unknown error"}
|
|
653
|
+
`);
|
|
654
|
+
process.exit(1);
|
|
655
|
+
}
|
|
656
|
+
console.log(`
|
|
657
|
+
\u2713 Deployed to a private draft.
|
|
658
|
+
`);
|
|
659
|
+
printClaimBlock(ctx);
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
530
662
|
let orgId;
|
|
531
663
|
if (options.org) {
|
|
532
664
|
const orgs = await listMyOrgs();
|
|
@@ -565,7 +697,11 @@ async function deployWebsite(dir, options) {
|
|
|
565
697
|
return;
|
|
566
698
|
}
|
|
567
699
|
console.log(linkedProject?.website_id ? `Updating ${baseName}...` : `Deploying ${baseName}...`);
|
|
568
|
-
|
|
700
|
+
let result = await uploadWebsiteDeploy(archive, baseName, orgId);
|
|
701
|
+
if (!result.ok && result.error === "org_not_accessible" && linkedProject?.anon) {
|
|
702
|
+
orgId = await healStaleAnonLink(resolvedDir, linkedProject.anon);
|
|
703
|
+
result = await uploadWebsiteDeploy(archive, baseName, orgId);
|
|
704
|
+
}
|
|
569
705
|
if (!result.ok) {
|
|
570
706
|
console.error(`Deploy failed: ${result.error}`);
|
|
571
707
|
process.exit(1);
|
|
@@ -716,6 +852,12 @@ async function deployCommand(dir, options = {}) {
|
|
|
716
852
|
process.exit(EXIT_USAGE);
|
|
717
853
|
}
|
|
718
854
|
}
|
|
855
|
+
if (!manifest && (fs2.existsSync(path2.join(resolvedDir, "astro.config.mjs")) || fs2.existsSync(path2.join(resolvedDir, "astro.config.ts"))) && fs2.existsSync(path2.join(resolvedDir, "src", "tree"))) {
|
|
856
|
+
console.error(
|
|
857
|
+
'This looks like a Clawnify website, but it has no clawnify.json so it\ncannot be told apart from an app \u2014 deploying it as one creates a broken app.\n\n Add a clawnify.json here:\n { "version": 1, "name": "website", "website": { "framework": "astro" } }\n\n Or push to the synced workspace repo, which rebuilds the site for you.'
|
|
858
|
+
);
|
|
859
|
+
process.exit(EXIT_USAGE);
|
|
860
|
+
}
|
|
719
861
|
}
|
|
720
862
|
let appId;
|
|
721
863
|
let slug;
|
|
@@ -725,16 +867,18 @@ async function deployCommand(dir, options = {}) {
|
|
|
725
867
|
if (options.from) {
|
|
726
868
|
const repo = options.from.replace(/^github:/, "");
|
|
727
869
|
const subdir = options.path?.trim().replace(/^\/+|\/+$/g, "") || void 0;
|
|
870
|
+
const fromDir = process.cwd();
|
|
871
|
+
const orgId = await resolveOrgId(options, readProject(fromDir), fromDir);
|
|
728
872
|
if (options.dryRun) {
|
|
729
873
|
console.log(
|
|
730
874
|
`
|
|
731
875
|
Dry run \u2014 would deploy from GitHub repo '${repo}' (branch: main${subdir ? `, path: ${subdir}` : ""}${options.name ? `, name: ${options.name}` : ""})
|
|
876
|
+
Target org: ${orgId ?? "(unresolved \u2014 would use your default org)"}
|
|
732
877
|
`
|
|
733
878
|
);
|
|
734
879
|
return;
|
|
735
880
|
}
|
|
736
881
|
console.log(`Deploying from ${repo}${subdir ? `/${subdir}` : ""}...`);
|
|
737
|
-
const orgId = options.org ? await resolveOrgId(options, null) : void 0;
|
|
738
882
|
let result2 = await repoDeploy({ repo, subdir, name: options.name, orgId });
|
|
739
883
|
if (!result2.ok && "conflict" in result2) {
|
|
740
884
|
const decision = await resolveConflictDecision(options, result2.conflict);
|
|
@@ -778,7 +922,54 @@ async function deployCommand(dir, options = {}) {
|
|
|
778
922
|
await regenerateDrizzleMigrations(resolvedDir);
|
|
779
923
|
assertDatabaseDdlPresent(resolvedDir, manifest);
|
|
780
924
|
const { archive, files } = createArchive(resolvedDir);
|
|
781
|
-
|
|
925
|
+
if (isLoggedOut() && !options.org) {
|
|
926
|
+
if (options.dryRun) {
|
|
927
|
+
summarizeArchive(archive, files, framework, baseName);
|
|
928
|
+
console.log(` Would deploy anonymously into a temporary workspace
|
|
929
|
+
`);
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
const { ctx, created } = await getOrCreateAnonContext(resolvedDir, baseName);
|
|
933
|
+
const isUpdate = Boolean(linkedProject?.app_id && linkedProject?.anon);
|
|
934
|
+
console.log(
|
|
935
|
+
created ? `No account detected \u2014 deploying ${baseName} to a temporary workspace...` : isUpdate ? `Updating ${baseName} (temporary workspace)...` : `Deploying ${baseName} (temporary workspace)...`
|
|
936
|
+
);
|
|
937
|
+
const formData = new FormData();
|
|
938
|
+
formData.append("source", new Blob([archive]), "source.tar.gz");
|
|
939
|
+
formData.append("name", baseName);
|
|
940
|
+
formData.append("framework", framework);
|
|
941
|
+
const anonPath = isUpdate ? `/v1/anon/apps/${linkedProject.app_id}/redeploy` : "/v1/anon/apps/deploy";
|
|
942
|
+
const res = await anonPostForm(anonPath, formData, ctx);
|
|
943
|
+
if (res.status === 401) explainAnonUnauthorized(resolvedDir);
|
|
944
|
+
if (!res.ok) {
|
|
945
|
+
const err = await res.json().catch(() => ({}));
|
|
946
|
+
console.error(`Deploy failed: ${err.error || res.statusText}`);
|
|
947
|
+
process.exit(1);
|
|
948
|
+
}
|
|
949
|
+
const data = await res.json();
|
|
950
|
+
saveProject(resolvedDir, {
|
|
951
|
+
...readProject(resolvedDir) ?? {},
|
|
952
|
+
org_id: ctx.org_id,
|
|
953
|
+
app_id: data.app_id,
|
|
954
|
+
slug: data.slug,
|
|
955
|
+
app_token: data.app_token,
|
|
956
|
+
anon: ctx
|
|
957
|
+
});
|
|
958
|
+
const polled = await pollUntilReady(data.app_id, { anonToken: ctx.deploy_token });
|
|
959
|
+
if (polled.status === "error") {
|
|
960
|
+
console.error(`
|
|
961
|
+
Deploy failed: ${polled.error || "Unknown error"}
|
|
962
|
+
`);
|
|
963
|
+
process.exit(1);
|
|
964
|
+
}
|
|
965
|
+
console.log(`
|
|
966
|
+
\u2713 Deployed (private link):`);
|
|
967
|
+
console.log(` https://${data.slug}.apps.clawnify.com?token=${data.app_token}
|
|
968
|
+
`);
|
|
969
|
+
printClaimBlock(ctx);
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
let orgId = await resolveOrgId(options, linkedProject, resolvedDir);
|
|
782
973
|
if (options.dryRun) {
|
|
783
974
|
summarizeArchive(archive, files, framework, baseName);
|
|
784
975
|
if (linkedProject?.app_id) {
|
|
@@ -790,20 +981,30 @@ async function deployCommand(dir, options = {}) {
|
|
|
790
981
|
}
|
|
791
982
|
return;
|
|
792
983
|
}
|
|
984
|
+
let needsCreate = !linkedProject?.app_id;
|
|
793
985
|
if (linkedProject?.app_id) {
|
|
794
986
|
console.log(`Updating ${baseName} (${linkedProject.slug ?? linkedProject.app_id})...`);
|
|
795
987
|
const result2 = await uploadRedeploy(linkedProject.app_id, archive, orgId);
|
|
796
|
-
if (
|
|
988
|
+
if (result2.ok) {
|
|
989
|
+
appId = result2.data.app_id;
|
|
990
|
+
slug = result2.data.slug;
|
|
991
|
+
appToken = result2.data.app_token;
|
|
992
|
+
saveProject(resolvedDir, { org_id: orgId, app_id: appId, slug, app_token: appToken });
|
|
993
|
+
} else if (result2.error === "org_not_accessible" && linkedProject.anon) {
|
|
994
|
+
orgId = await healStaleAnonLink(resolvedDir, linkedProject.anon);
|
|
995
|
+
needsCreate = true;
|
|
996
|
+
} else {
|
|
797
997
|
console.error(`Deploy failed: ${result2.error}`);
|
|
798
998
|
process.exit(1);
|
|
799
999
|
}
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
appToken = result2.data.app_token;
|
|
803
|
-
saveProject(resolvedDir, { org_id: orgId, app_id: appId, slug, app_token: appToken });
|
|
804
|
-
} else {
|
|
1000
|
+
}
|
|
1001
|
+
if (needsCreate) {
|
|
805
1002
|
console.log(`Deploying ${baseName}...`);
|
|
806
1003
|
let result2 = await uploadDeploy(archive, baseName, framework, orgId);
|
|
1004
|
+
if (!result2.ok && !("conflict" in result2) && result2.error === "org_not_accessible" && linkedProject?.anon) {
|
|
1005
|
+
orgId = await healStaleAnonLink(resolvedDir, linkedProject.anon);
|
|
1006
|
+
result2 = await uploadDeploy(archive, baseName, framework, orgId);
|
|
1007
|
+
}
|
|
807
1008
|
if (!result2.ok && "conflict" in result2) {
|
|
808
1009
|
const decision = await resolveConflictDecision(options, result2.conflict);
|
|
809
1010
|
if (decision === "update") {
|
|
@@ -1456,13 +1657,18 @@ function agentByName(name) {
|
|
|
1456
1657
|
var ALL_AGENTS = DETECTORS.map((d) => d.agent);
|
|
1457
1658
|
|
|
1458
1659
|
// src/lib/skills/content.gen.ts
|
|
1459
|
-
var CLI_VERSION = "0.
|
|
1660
|
+
var CLI_VERSION = "0.16.1";
|
|
1460
1661
|
var BUNDLED_SKILLS = [
|
|
1461
1662
|
{
|
|
1462
1663
|
name: "build-a-clawnify-app",
|
|
1463
1664
|
description: "Author a Clawnify app end-to-end \u2014 the canonical Hono + React + Vite + @hono/zod-openapi + @clawnify/db (Drizzle) stack, schema.ts (typed queries) kept in sync with schema.sql (the DDL the deploy applies), OpenAPIHono routes (createRoute) that auto-generate an OpenAPI spec, and platform-injected identity via user()/orgId()/caller(). Use when building or modifying an app that deploys to the Clawnify platform.",
|
|
1464
1665
|
content: '# Build a Clawnify app\n\nCanonical skill: how to author a Clawnify app end-to-end. Same content\nfor humans reading the docs and for AI coding agents injecting this as\ninstructions during an app build.\n\nIf you\'re an agent: this document is enough context to produce a\nworking app from scratch. Follow it literally. The patterns here\nare exactly what `clawnify init` scaffolds and what the platform\nexpects.\n\n## TL;DR\n\n- **One stack.** Hono + React + Vite + `@hono/zod-openapi` +\n `@clawnify/db` (Drizzle) + `@clawnify/app` (entry, routing,\n identity) + Tailwind v4. Nothing else.\n- **Schema lives in two files kept in sync** \u2014 `schema.ts` (Drizzle\n DSL, the typed view your queries use) and `schema.sql` (the DDL the\n deploy applies to your app\'s D1). Change one, change the other.\n- **Queries through `getDB`** \u2014 `import { getDB, eq } from\n "@clawnify/db"`. JSON columns auto-serialize.\n- **API routes are `OpenAPIHono` + `createRoute`** \u2014 Zod-validated\n request/response.\n- **`createApp()`** (from `@clawnify/app`) builds the entry \u2014 it returns an\n `OpenAPIHono` with API discovery already mounted (`/api/openapi.json` +\n `/llms.txt`, generated from your live routes). That descriptor *is* the\n tool surface agents discover. Never hand-write those routes.\n- **One import.** `@clawnify/app` re-exports `createRoute`, `z` and\n `OpenAPIHono`, and adds `user` / `orgId` / `caller`. Import from it, not\n from `@clawnify/routes` directly.\n- **`clawnify.json`** declares framework, env, and public routes.\n There is no `api.tools[]` \u2014 the agent discovers and calls your\n endpoints via `/llms.txt` (and the OpenAPI spec).\n- **Identity is injected by the platform** \u2014 read it with `user(c)` /\n `orgId(c)` / `caller(c)` from `@clawnify/app`. Your app never\n authenticates anyone.\n\n## Stack rationale\n\nOne template, one set of decisions. Don\'t deviate unless the user has\nexplicitly asked. `clawnify init` (type `app`) scaffolds either a\n`blank` template (one GET route + a page) or a `crud` template (a\ntable with list/create/update/delete + a form). Both share the exact\nsame stack below.\n\n## File layout\n\n```\nmy-app/\n clawnify.json \u2190 Manifest (validated against /schema/v1/clawnify.json)\n package.json\n tsconfig.json\n vite.config.ts \u2190 @vitejs/plugin-react + @tailwindcss/vite; proxies /api \u2192 :8787\n index.html\n .gitignore\n .clawnify/ \u2190 CLI cache (gitignored)\n wrangler.toml \u2190 Generated per-dev wrangler config\n src/\n server/\n index.ts \u2190 OpenAPIHono entry \u2014 mounts routes, serves /api/openapi.json\n routes.ts \u2190 OpenAPIHono + createRoute definitions \u2014 the API surface\n schema.ts \u2190 Drizzle table definitions (typed view for queries)\n schema.sql \u2190 canonical DDL the deploy applies \u2014 keep in sync with schema.ts\n worker-env.d.ts \u2190 Cloudflare Workers types reference\n uploads.ts \u2190 R2 helpers (only when storage is enabled)\n client/\n main.tsx \u2190 React mount point\n app.tsx \u2190 Root component (plain fetch against /api/*)\n index.css \u2190 @import "tailwindcss"\n```\n\n## Schema \u2014 `schema.ts` + `schema.sql`, kept in sync\n\nTwo files describe the same tables. `schema.ts` (Drizzle DSL) is the\ntyped view your queries compile against; `schema.sql` is the DDL the\ndeploy applies to your app\'s D1. **When you change one, update the\nother** \u2014 they must describe the same tables.\n\nThe scaffold\'s starter table (blank template):\n\n```ts\n// src/server/schema.ts\nimport { sqliteTable, text, integer } from "@clawnify/db";\n\nexport const items = sqliteTable("items", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n name: text("name").notNull(),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n});\n```\n\nReal apps are multi-tenant. Every user-facing table carries an\n`org_id`, every query filters by it. JSON columns and indexes use the\nDrizzle DSL re-exported from `@clawnify/db`:\n\n```ts\nimport { sqliteTable, text, integer, index } from "@clawnify/db";\n\nexport const notes = sqliteTable(\n "notes",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n orgId: text("org_id").notNull(), // ALWAYS filter by this in queries\n title: text("title").notNull(),\n body: text("body").notNull().default(""),\n tags: text("tags", { mode: "json" }).$type<string[]>().notNull().default([]),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n },\n (t) => ({\n byOrg: index("notes_by_org").on(t.orgId, t.createdAt),\n }),\n);\n```\n\nRules:\n- JSON columns: `text(col, { mode: "json" }).$type<T>()` \u2014 Drizzle\n serializes on write and parses on read.\n- Multi-tenancy: every user-facing table has `org_id`. Every query\n filters by it. No exceptions.\n- Identifiers: snake_case in SQL, camelCase in TS (Drizzle bridges).\n\n## `schema.sql` \u2014 the DDL the deploy applies\n\nAlongside `schema.ts`, keep a `schema.sql` describing the same tables.\nThis is the DDL applied to your app\'s database on deploy.\n\n```sql\n-- src/server/schema.sql (mirror of the schema.ts tables)\nCREATE TABLE IF NOT EXISTS notes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n org_id TEXT NOT NULL,\n title TEXT NOT NULL,\n body TEXT NOT NULL DEFAULT \'\',\n tags TEXT NOT NULL DEFAULT \'[]\', -- JSON column\n created_at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS notes_by_org ON notes(org_id, created_at);\n```\n\nRules:\n- Always `CREATE TABLE IF NOT EXISTS` \u2014 the apply is additive and\n re-run-safe.\n- Add a new column with `ALTER TABLE <t> ADD COLUMN \u2026` at the **end** of\n `schema.sql`, and reflect it in `schema.ts`. The deploy adds it.\n- Deploys are **additive**: new tables and columns are added\n automatically. Destructive changes (dropping or retyping a column) are\n not applied automatically \u2014 do those deliberately, and never drop a\n table with user data unless explicitly asked.\n- **Never let `schema.ts` and `schema.sql` drift.** Change one, change\n the other \u2014 they must describe the same tables.\n\n## `src/server/index.ts` \u2014 the entry\n\n```ts\nimport { createApp } from "@clawnify/app";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database } };\n\n// db:false \u2014 this app reads the database per request via getDB(c.env),\n// which needs no init middleware.\nconst app = createApp<Env>({ title: "My app", version: "1.0.0", db: false });\n\napp.route("/", api);\n\nexport default app;\n```\n\nThe entry is thin: `createApp()` then mount your routes. `createApp`\nreturns an `OpenAPIHono` with **API discovery already mounted** \u2014 it\nserves both `/api/openapi.json` (generated from your `createRoute`\ndefinitions, with schemas) **and** `/llms.txt` (the same, agent-readable).\nAny `/api/*` route written as a plain `app.get` with no `createRoute` is\nstill listed from the live route table, so the endpoint inventory is\nalways complete. **Never hand-write a `/openapi.json` or `/llms.txt`\nhandler** \u2014 and don\'t call `mountDiscovery` yourself; `createApp` did it.\n\nWhen storage (file uploads) is enabled, the entry also wires the R2\nbucket in a middleware before mounting routes:\n\n```ts\nimport { createApp } from "@clawnify/app";\nimport { initUploads } from "./uploads";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database; UPLOADS: R2Bucket } };\n\nconst app = createApp<Env>({ title: "My app", version: "1.0.0", db: false });\n\napp.use("*", async (c, next) => {\n initUploads(c.env.UPLOADS);\n await next();\n});\n\napp.route("/", api);\n\nexport default app;\n```\n\n## `src/server/routes.ts` \u2014 routes with `createRoute`\n\nEach endpoint is a `createRoute({ method, path, summary, request, responses })`\ndefinition paired with a handler via `api.openapi(route, handler)`.\nRequest bodies and params are Zod-validated (`c.req.valid("json")`,\n`c.req.valid("param")`); response shapes are declared with\n`.openapi("Name")` Zod schemas so they land in the generated spec.\n\nBlank template \u2014 one read route:\n\n```ts\nimport { OpenAPIHono, createRoute, z } from "@clawnify/app";\nimport { getDB, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n name: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\nexport default api;\n```\n\nCRUD template \u2014 the full list/create/update/delete surface:\n\n```ts\nimport { OpenAPIHono, createRoute, z } from "@clawnify/app";\nimport { getDB, eq, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n title: z.string(),\n status: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\nconst CreateItemSchema = z.object({ title: z.string().min(1) }).openapi("CreateItem");\nconst UpdateItemSchema = z.object({\n title: z.string().min(1).optional(),\n status: z.string().optional(),\n}).openapi("UpdateItem");\nconst IdParamSchema = z.object({ id: z.string() });\nconst OkSchema = z.object({ ok: z.boolean() }).openapi("Ok");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\napi.openapi(\n createRoute({\n method: "post",\n path: "/api/items",\n summary: "Create item",\n request: { body: { content: { "application/json": { schema: CreateItemSchema } } } },\n responses: {\n 201: {\n description: "Created item",\n content: { "application/json": { schema: ItemSchema } },\n },\n },\n }),\n async (c) => {\n const { title } = c.req.valid("json");\n const db = getDB(c.env, { schema });\n const [row] = await db\n .insert(schema.items)\n .values({ title: title.trim() })\n .returning();\n return c.json(row, 201);\n },\n);\n\napi.openapi(\n createRoute({\n method: "patch",\n path: "/api/items/:id",\n summary: "Update item",\n request: {\n params: IdParamSchema,\n body: { content: { "application/json": { schema: UpdateItemSchema } } },\n },\n responses: {\n 200: { description: "Updated", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const body = c.req.valid("json");\n const patch: Partial<typeof schema.items.$inferInsert> = {};\n if (body.title !== undefined) patch.title = body.title;\n if (body.status !== undefined) patch.status = body.status;\n if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);\n const db = getDB(c.env, { schema });\n await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\napi.openapi(\n createRoute({\n method: "delete",\n path: "/api/items/:id",\n summary: "Delete item",\n request: { params: IdParamSchema },\n responses: {\n 200: { description: "Deleted", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const db = getDB(c.env, { schema });\n await db.delete(schema.items).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\nexport default api;\n```\n\nPatterns to follow:\n- **Give every route a clear `summary`/`description`.** The generated\n OpenAPI spec is what the agent reads to decide which endpoint to\n call \u2014 a vague summary makes your endpoint invisible in practice.\n- **Validate input with Zod** via `request.body` / `request.params`\n and read it with `c.req.valid("json")` / `c.req.valid("param")`.\n Never parse `c.req.raw` by hand.\n- **Declare response shapes** with `.openapi("Name")` schemas \u2014 they\n become the documented return type in the spec.\n- **Filter by the org** on every user-facing query (see "who is\n calling" below). No exceptions.\n\n## `src/server` \u2014 who is calling\n\nThe platform authenticates every caller at its perimeter and injects a\nverified identity onto the request (it strips any client-supplied\nversion first, so it can\'t be spoofed). Your app never authenticates\nanyone: no `Authorization`, no cookies, no JWT, no login screen.\n\nRead it with the helpers from `@clawnify/app` \u2014 don\'t parse headers\nyourself:\n\n```ts\nimport { user, orgId, caller } from "@clawnify/app";\n\napp.get("/api/notes", async (c) => {\n const org = orgId(c);\n if (!org) return c.json({ error: "unauthorized" }, 401);\n\n const db = getDB(c.env, { schema });\n return c.json(\n await db.select().from(schema.notes).where(eq(schema.notes.orgId, org)),\n );\n});\n```\n\n| Helper | Returns |\n|--------|---------|\n| `orgId(c)` | Organization UUID \u2014 the tenant key. Filter every user-facing query by it. |\n| `user(c)` | `{ id, email, name, avatarUrl, firstName, lastName }` \u2014 or **`null`** when the caller isn\'t a person. |\n| `caller(c)` | `user`, `api`, `agent`, `agent-browser`, `public`, `bypass`, `system`, or `app`. |\n\nTwo rules that catch people out:\n\n- **`user(c)` is null for five of the eight caller kinds**\n (`agent-browser`, `public`, `bypass`, `system`, `app`). Always handle\n the null case \u2014 don\'t assume a person is present just because a\n request arrived. For per-user rows, store `user(c).id` in a `user_id`\n column and filter on it, exactly as you filter on `org_id`.\n- **`firstName` / `lastName` are a heuristic** split of a single stored\n full name (first word / the rest). Fine for a greeting; never persist\n them or treat them as someone\'s legal name \u2014 store `name`.\n\nDon\'t build app-level users, roles, or permissions. Authorization\nalready happened at the perimeter.\n\n## `src/client` \u2014 React + plain fetch\n\nThe client mounts React and talks to the API with plain `fetch`\nagainst the `/api/*` routes. No data-layer library is scaffolded.\n\n```tsx\n// src/client/main.tsx\nimport { StrictMode } from "react";\nimport { createRoot } from "react-dom/client";\nimport { App } from "./app";\nimport "./index.css";\n\ncreateRoot(document.getElementById("app")!).render(\n <StrictMode>\n <App />\n </StrictMode>\n);\n```\n\n```tsx\n// src/client/app.tsx (CRUD template shape)\nimport { useState, useEffect } from "react";\n\ninterface Item {\n id: number;\n title: string;\n status: string;\n createdAt: string;\n}\n\nexport function App() {\n const [items, setItems] = useState<Item[]>([]);\n const [title, setTitle] = useState("");\n\n async function load() {\n const res = await fetch("/api/items");\n setItems(await res.json());\n }\n\n useEffect(() => { load(); }, []);\n\n async function addItem(e: React.FormEvent) {\n e.preventDefault();\n if (!title.trim()) return;\n await fetch("/api/items", {\n method: "POST",\n headers: { "Content-Type": "application/json" },\n body: JSON.stringify({ title }),\n });\n setTitle("");\n load();\n }\n\n // ...toggleStatus / deleteItem call PATCH/DELETE the same way.\n\n return (\n <div className="max-w-xl mx-auto mt-10 px-4">\n {/* form + list */}\n </div>\n );\n}\n```\n\nIn local dev, Vite proxies `/api` to the Worker on `:8787` (see\n`vite.config.ts`), so the same relative fetch paths work in dev and\nin production. The API is the one contract: the UI calls it over\n`fetch`, and the agent calls it over the OpenAPI spec.\n\n## Design\n\nIf the project contains a `DESIGN.md`, it is the single source of\ntruth for visuals \u2014 follow its tokens, don\'t restyle around it. The\nscaffold ships Tailwind v4 (via `@tailwindcss/vite`, imported with\n`@import "tailwindcss";` in `index.css`) and nothing else \u2014 no\ncomponent library. The rules every Clawnify app follows:\n\n- **Neutral chrome.** White canvas and surfaces, one text ramp\n (foreground \u2192 muted \u2192 faint), hairline borders. Color is for\n meaning, not decoration.\n- **One primary CTA per screen.** Blue is reserved for links and\n focus rings; never a second accent.\n- **Status colors are muted pairs** \u2014 never pure-saturated fills.\n- **Style with Tailwind utilities.** Don\'t install another component\n library or write a bespoke CSS system unless the user asks.\n- **Sizes in rem**, so browser zoom and font settings are respected.\n\n## `clawnify.json` \u2014 the manifest\n\n```json\n{\n "$schema": "https://app.clawnify.com/schema/v1/clawnify.json",\n "version": 1,\n "name": "Notes",\n "description": "Take and organize notes. Searchable by tag.",\n "app": {\n "framework": "react+hono",\n "database": true,\n "storage": false\n },\n "env": {\n "optional": ["OPENROUTER_API_KEY"]\n },\n "api": {\n "public_routes": [\n { "path": "/api/feed", "methods": ["GET"] }\n ]\n }\n}\n```\n\n`clawnify init` writes the minimal form:\n`{ app: { framework: "react+hono", database: true, storage } }`. Add\nthe rest as needed.\n\nIf the app talks to third-party services the user has connected\n(ads platforms, CRMs, messaging), declare them:\n\n```json\n{ "app": { "credentials": ["metaads", "googleads"] } }\n```\n\nGet the ids and names from `clawnify connections list` \u2014 see the\nnaming rule below.\n\n`env` supports `required` (deploy warns if missing), `optional`\n(injected when available), and `oneOf` (at least one per group).\n\nRules:\n- **There is no `api.tools[]`.** The manifest\'s `api` object only\n accepts `public_routes` and `automation_bypass`. Your API surface\n is discovered from the generated OpenAPI spec, not a hand-authored\n tools list (see the next section).\n- **Public routes are the exception**, not the default. Every route\n is behind the Clawnify perimeter (auth-required) unless you\n explicitly add a matching path to `api.public_routes`. Use only for\n webhooks, RSS, embedded feeds.\n- **`framework: "react+hono"`** for new apps. Never `preact+hono` or\n `vite-preact` \u2014 those are legacy.\n- **`database: true`** if the app uses a DB. Ship both `schema.ts`\n (typed) and `schema.sql` (the applied DDL), kept in sync.\n\n## How the agent reaches your API (no `api.tools[]`)\n\nThe old tRPC stack emitted an `api.tools[]` array from procedure meta.\nThat mechanism is gone. Today the flow is:\n\n1. Your `createRoute` definitions auto-generate a live OpenAPI 3.0 spec\n plus a lean `/llms.txt` index, both served for you \u2014 never hand-write\n or route them yourself. **These are the agent\'s discovery channel:**\n it calls `call_app_api` with `GET /llms.txt` (index of every\n endpoint) or `GET /api/openapi.json` (full request/response schemas).\n Because both are generated from the live route table, they cannot\n drift from the code.\n2. The agent then drives your endpoints with `call_app_api` (a `method`\n + `path` on the live app). No per-app MCP registration and no\n manifest tools array. Use source reading to *modify* code, not to\n discover endpoints.\n\nSo you make an endpoint "agent-callable" by defining it with\n`createRoute()` + `app.openapi()` and giving it a clear\n`summary`/`description` with Zod-typed request/response. The clearer\nthose are, the more reliably the agent uses it.\n\n### `agent.md` \u2014 lead with the procedure, not the endpoint list\n\n`agent.md` is extracted into `agent_instructions` on every build. Since\ndiscovery is already covered by the generated surfaces above, **`agent.md`\nis not an API reference** \u2014 re-listing every payload there just creates a\nsecond source of truth that goes stale the first time a route changes.\nIt is the one place for what generation can\'t produce: **judgment**.\n\nWrite it in this order:\n\n1. **Division of labour, first and short.** What the agent should do\n itself vs. what it must delegate to the app \u2014 and say the wrong move\n out loud (*"never look up contact details yourself; post the records\n and let the app resolve them"*). This one block prevents more misuse\n than the rest of the file combined.\n2. **The procedure** \u2014 numbered steps for the app\'s main job, written so\n the agent can follow them on a request it has never seen.\n3. **Pages**, flagging the screenshot-friendly ones.\n4. **API anchors, not API docs** \u2014 method, path, and *when to reach for\n it*, plus the one or two request shapes the agent writes most often.\n For anything else, let it read `/llms.txt`.\n5. **How to read failures**, and any **cost discipline** \u2014 which calls\n spend the user\'s money and which are free.\n\n**Don\'t ship a per-app skill.** A skill\'s frontmatter stays resident in\nagent context, so one skill per app grows the agent\'s context floor as\nthe app count grows; `agent_instructions` and `/llms.txt` are pulled on\ndemand instead. Skills are for **cross-app** procedures \u2014 if one earns\nreuse across more than one app, promote that single procedure\n(parameterized) to the shared skills library rather than copying it into\nevery app.\n\n## Connections & secrets \u2014 `@clawnify/connections`\n\n**The naming rule \u2014 never invent an identifier.** Before declaring\n`credentials` or env names, run `clawnify connections list`: it shows\nthe org\'s canonical integration ids (`googleads`, never `google_ads`),\nthe fixed provider-key names (`OPENROUTER_API_KEY`, never\n`OPENROUTER_KEY`), and custom env vars already defined \u2014 each with\nconnected/set state. Reuse those exact identifiers; a misspelled one\ndoesn\'t fail the build, it silently resolves to nothing at runtime. If\nyou need a custom secret that isn\'t listed, pick a clear name and tell\nthe user to set it in the dashboard.\n\nIf the app needs a third-party service or a provider API key, use\nthe `@clawnify/connections` SDK. Never read credential bindings\ndirectly, never paste API keys, never hardcode a token or endpoint.\n\n```ts\nimport { connect, secret, describe, searchActions } from "@clawnify/connections";\n\n// A connected integration:\nconst meta = connect("metaads", env);\nconst accounts = await meta.adAccounts("name,currency");\n\n// A provider key the user supplied (null if absent):\nconst key = secret("OPENROUTER_API_KEY", env);\n\n// What\'s wired vs missing \u2014 drive your setup/empty state from this:\nconst status = await describe(env, undefined, REQUIRES);\n```\n\nHow to call a connected service \u2014 the mistake that silently breaks\nintegration apps, so get it right:\n\n- **Prefer the typed client\'s semantic methods** where they exist\n (`meta.adAccounts(...)`, `googleads.query(gaql)`).\n- **For anything else, discover and run an action:**\n ```ts\n const [best] = await searchActions("list google ads campaigns", env);\n const data = await connect(best.service, env).run(best.slug, body);\n ```\n- Some integrations also expose a raw REST client\n (`connect("bird", env).get("/path")`) \u2014 but if `.get()`/`.post()`\n throws for a service, that service only supports semantic methods\n and `run()`. When unsure, use `run()`.\n- **Need exact paths/arguments for a raw-REST provider?** Some carry\n a `spec_url` (the provider\'s published OpenAPI spec) \u2014\n `clawnify connections list --json` shows it. Download and query it \u2014\n `curl -s <spec_url> -o spec.json && jq \'.paths | keys\' spec.json` \u2014\n never read a whole spec into context (they run to 10+ MB).\n- **Never fall back to raw `fetch`** against a provider API, and\n never invent endpoints or guess tokens.\n\n**The one exception \u2014 a service we don\'t support at all.** If a\nprovider isn\'t in the connections registry (nothing to `connect()`\nto, and `clawnify connections list` doesn\'t show it), the sanctioned\npath *is* a raw call with a user-supplied key: declare the key(s) it\nneeds in `clawnify.json` `env` (`required`/`optional`/`oneOf`), tell\nthe user to set them in the dashboard, read them with\n`secret("THAT_KEY", env)`, and `fetch` the provider\'s documented\nendpoints directly. This is the escape hatch for the long tail of\nintegrations we don\'t model yet \u2014 it does **not** apply to a service\nwe *do* support (use `connect()` / `run()` for those, always). Keep\nthe endpoint and token server-side, never in the client bundle.\n\nBuild a `describe()`-driven setup state instead of assuming\nconnections exist \u2014 show the user what\'s missing and where to\nconnect it.\n\n## Scheduling & deferred work \u2014 the managed queue\n\nA deployed app **cannot bind Cloudflare Queues, Durable Objects, or cron\ntriggers** (the platform builds every app with a fixed binding set: `DB` +\n`ASSETS` + `UPLOADS`). To run work later \u2014 a scheduled publish, a reminder, a\nretry, a "do this in 10 minutes" \u2014 use the **Clawnify managed queue service**\nover HTTP. It owns the clock, retries, and at-least-once delivery, then calls an\nendpoint on *your own app* back at the scheduled time.\n\nIt\'s a thin seam over a platform primitive, same shape as `@clawnify/db` /\n`@clawnify/connections` (a `@clawnify/queue` package is coming; inline the seam\nuntil then). Auth is the build-injected `env.CLAWNIFY_TOKEN`; with no token\n(local dev) the seam degrades to a no-op.\n\n**Enqueue** a deferred call to your own endpoint:\n\n```ts\n// POST https://services.clawnify.com/queue/enqueue (Bearer CLAWNIFY_TOKEN)\nconst res = await fetch("https://services.clawnify.com/queue/enqueue", {\n method: "POST",\n headers: { Authorization: `Bearer ${env.CLAWNIFY_TOKEN}`, "Content-Type": "application/json" },\n body: JSON.stringify({\n target_url: `${origin}/api/internal/publish`, // an endpoint on THIS app\n payload: { post_id: id }, // echoed back to you on fire\n run_at: new Date(whenMs).toISOString(),\n idempotency_key: `post:${id}:${whenMs}`, // same key dedupes; new time = new job\n }),\n});\nconst { job_id } = await res.json(); // store it to cancel/reschedule\n```\n\nPersist `job_id` on the row (e.g. `posts.queue_job_id`). **Cancel / reschedule**:\n`DELETE https://services.clawnify.com/queue/jobs/{job_id}` (Bearer token);\nreschedule = cancel + a fresh enqueue.\n\n**The callback endpoint is a public, signature-verified route.** The queue calls\n`target_url` from outside the perimeter, so the endpoint must be declared in\n`clawnify.json` `public_routes` **and** verify the delivery signature itself \u2014\nthe signature *is* its auth (never trust an unsigned call):\n\n```jsonc\n// clawnify.json\n"api": { "public_routes": [ { "path": "/api/internal/publish", "methods": ["POST"] } ] }\n```\n\nDeliveries are signed with the platform\'s **ECDSA P-256 (ES256)** key,\nStripe-style over `${timestamp}.${rawBody}`, verified against\n`https://services.clawnify.com/.well-known/jwks.json` (public key \u2014 nothing\nbreaks on token rotation). Read the raw body, check the signature + a timestamp\ntolerance (~5 min) before doing anything:\n\n```ts\napp.post("/api/internal/publish", async (c) => {\n const raw = await c.req.text();\n const ok = await verifyDelivery(raw, {\n signature: c.req.header("x-clawnify-signature"),\n timestamp: c.req.header("x-clawnify-timestamp"),\n keyId: c.req.header("x-clawnify-key-id"),\n });\n if (!ok) return c.json({ error: "bad signature" }, 401);\n const { post_id } = JSON.parse(raw);\n // \u2026do the deferred work (short: it\'s one normal Worker invocation)\u2026\n return c.json({ ok: true });\n});\n```\n\nEach fire is a normal Worker request \u2014 size the work to one invocation (publish a\npost, send a digest). For long compute *now* (not deferred), hold the request\nopen and return when done; don\'t fire-and-forget past the response.\n\n## Migrations\n\nKeep `schema.ts` and `schema.sql` in sync by hand. The workflow is:\n\n1. Edit `src/server/schema.ts` for the new shape (types + queries).\n2. Make the matching edit in `src/server/schema.sql` \u2014 a new\n `CREATE TABLE IF NOT EXISTS`, or `ALTER TABLE \u2026 ADD COLUMN \u2026` at the\n **end** of the file for a new column.\n3. Run `clawnify dev` locally, then `clawnify deploy`.\n\nOn deploy your schema changes are applied to the app\'s database \u2014 new\ntables and columns are added automatically.\n\nDestructive changes (drop column, rename) are not applied automatically;\ndo them deliberately, and only when the user explicitly asks. Renames\nare risky on production data \u2014 prefer "add new column, backfill, switch\nqueries, drop old column" over a single-step rename.\n\n## What the agent must NOT do\n\n- Author a `/openapi.json` handler by hand. `app.doc("/api/openapi.json", \u2026)`\n generates it from your `createRoute` definitions.\n- Let `schema.ts` and `schema.sql` drift. They describe the same\n tables \u2014 change both, every time.\n- Hand-author migration SQL files. Make schema changes in `schema.sql`\n (and mirror them in `schema.ts`); the deploy applies them.\n- Invent an `api.tools[]` array in the manifest. It isn\'t a valid\n field \u2014 the OpenAPI spec is the tool surface.\n- Use `JSON.stringify` on query params. JSON columns auto-serialize\n via Drizzle. The raw SQL API has `json()` as a helper.\n- Skip the `org_id` filter on a user-facing query. Multi-tenant\n leak is the worst-class bug we can ship.\n- Read auth from `Authorization` / cookies / `Bearer` tokens, or\n hand-parse `X-Clawnify-*` headers. Use `user(c)` / `orgId(c)` /\n `caller(c)` from `@clawnify/app`.\n- Call third-party APIs with raw `fetch` or hardcoded tokens. Go\n through `@clawnify/connections` (`connect` / `secret` / `run`).\n- Install `drizzle-orm` as a separate top-level dependency.\n `@clawnify/db@^0.4.1` pulls it in transitively; only add it if you\n need to pin a specific version (rare).\n\n## What the agent SHOULD do\n\n- Import everything from `@clawnify/db` where possible\n (`getDB`, `eq`, `and`, `desc`, `sql`, `sqliteTable`, `text`,\n `integer`, `index`, etc. are all re-exported there). Drop to\n `drizzle-orm` directly only for things not re-exported.\n- Give every route a clear `summary`/`description` and Zod-typed\n request/response so the agent can discover and call it via the\n OpenAPI spec.\n- Test on the draft URL (`<slug>.draft.clawnify.com`) before\n publishing \u2014 the preview tier catches schema drift and type errors\n at build time.\n- When unsure about a Drizzle pattern, check the `@clawnify/db`\n README for the current API + version notes.\n\n## Schema-as-data exception\n\nApps that let END users define data shapes at runtime (CMS, no-code\ntable editor) can\'t model their schema in `schema.ts` \u2014 the table\ndefinitions live in rows. Those apps fall back to the raw SQL API\nfrom `@clawnify/db` (`query`, `get`, `run`, `json`). Open-cms is\nthe canonical example.\n\nIf you\'re building this kind of app, you still use Drizzle\'s\n`schema.ts` for the **registry** tables (content types, field\ndefinitions). Only the dynamically-spawned per-collection tables\nneed raw SQL. See open-cms\'s `src/server/schema-sync.ts` for the\nruntime DDL pattern.\n'
|
|
1465
1666
|
},
|
|
1667
|
+
{
|
|
1668
|
+
name: "build-a-clawnify-website",
|
|
1669
|
+
description: "Build and ship a Clawnify website \u2014 Astro on Cloudflare Workers, the built-in form system (never hand-roll a form), images and assets, and the draft-then-publish deploy flow. Use when creating or editing a Clawnify website, or when a site needs a contact/waitlist/signup form.",
|
|
1670
|
+
content: "# Build a Clawnify website\n\nA Clawnify website is an **Astro** project deployed to Cloudflare Workers. One\nsite per organization. You write pages; the platform owns hosting, forms and\nthe publish flow.\n\n```bash\nclawnify init --type website --name \"My Site\" website\ncd website && pnpm install && pnpm dev # http://localhost:4321\n```\n\n```\nwebsite/\n src/pages/ # one .astro file per route (index.astro \u2192 /)\n src/layouts/ # shared shell: nav, footer, <head>\n src/blocks/ # platform blocks you've adopted (see Forms below)\n public/ # images, favicons \u2014 served as-is from /\n```\n\n## Forms: use the built-in system. Do not build your own.\n\n**This is the single most common mistake.** A site needs a contact or waitlist\nform, and the obvious move is to write a `<form>` and POST it somewhere \u2014 your\nown endpoint, a third-party form service, or the platform's submit URL with the\nwebsite id pasted in. All three are wrong, and the last one looks right enough\nto survive review.\n\nClawnify has a form system. It captures submissions, stores them, can email you,\nand can hand each one to an agent or a flow. You get all of it by using the\n**Forms block** rather than writing a form yourself.\n\n### How it works\n\n- The submit target is **computed at render time** from `WEBSITE_ID` \u2014 a\n variable the platform bakes into your site's Worker \u2014 plus the form's id:\n\n ```astro\n const env = (Astro.locals as { runtime?: { env?: Record<string, string> } })?.runtime?.env;\n const websiteId = env?.WEBSITE_ID ?? \"\";\n const action = websiteId ? `https://provision.clawnify.com/forms/submit/${websiteId}/${formId}` : \"\";\n ```\n\n **Never hardcode the website id.** It is baked per Worker so a site can only\n ever submit to itself \u2014 hardcoding throws that away, and the literal goes\n stale the moment the site is recreated. An empty `action` in local `astro dev`\n is expected: there are no Worker vars locally, so the form simply no-ops.\n\n- The submit script POSTs JSON with `Content-Type: text/plain;charset=UTF-8`.\n That is not a typo \u2014 `text/plain` is CORS-safelisted, so the request needs no\n preflight, which matters because the platform can't know your site's origin in\n advance. The route parses the text body as JSON.\n\n- **Keep the Turnstile widget.** The ingest rejects a submission with no token,\n so a form without the widget fails every time with \"Verification required\".\n The sitekey shipped in the block is public and pairs with the platform's\n secret; the widget will not validate on `localhost`, only on a real hostname.\n\n### Getting the block\n\nSites are seeded with the platform's block library at creation. If yours has\n`src/blocks/Forms/Contact.astro`, import it and go. If it doesn't \u2014 an older\nsite, or one scaffolded bare by the CLI \u2014 copy it in from the website template\nand adapt it.\n\n**The design is yours; the plumbing is not.** Restyle the markup, labels and\nclasses freely. Preserve, exactly:\n\n- the computed `action` (never a prop, never a literal),\n- the Turnstile widget,\n- the `data-clawnify-form` attribute and its submit script,\n- `export const schema`,\n- destructuring only known props \u2014 never splat leftover props onto `<form>`,\n or an injected `action` becomes a way to point your form at someone else.\n\n### Fields\n\nThe stock block collects **name, email and message**. Two ways to go beyond\nthat, and the right one depends on whether your form is registered:\n\n- **Registered forms** (a tree node named `Forms/Contact`) are schema-locked:\n the ingest 422s any field it doesn't expect. Give extra inputs **no `name`\n attribute** and have the submit script fold them into `message`.\n- **Unregistered forms** \u2014 hand-built pages like this one \u2014 are not locked, so\n extra fields post as themselves and are stored verbatim in the payload. Better\n data, but if the site later moves onto the tree renderer, registration will\n start rejecting them. Leave a comment saying so.\n\n### PDF attachments\n\nThe Contact block can collect one PDF per submission (job applications, RFQs).\nOff by default \u2014 enable it with the block's `attachment` prop (and optionally\n`attachmentLabel`), then **publish**: the file field is registered at publish\ntime, and the ingest rejects files on forms that haven't registered one. Rules\nthe platform enforces server-side (don't fight them client-side): PDF only,\nverified by content not by extension, max 10 MB. The submission's payload\ncarries the filename and a download link that only the site's own organization\ncan open \u2014 the file is never on a public URL. When a file is attached the\nsubmit script posts `multipart/form-data` instead of JSON; both are\npreflight-free, and the block already handles the switch.\n\n### Where submissions go\n\nEvery submission is stored and visible in the dashboard. From there it can\nnotify an email address, or fan out to an agent or a flow \u2014 which is how a\nsignup becomes a CRM record or a WhatsApp message without you writing a backend.\nSet the notification address in the dashboard, not in the site.\n\n## Images and assets\n\nPut them in `public/` and reference them with an absolute path (`/img/hero.jpg`).\nThey're served as static files. Pull in real assets at real resolution rather\nthan linking someone else's CDN from your markup.\n\n## Deploying: draft first, then publish\n\n```bash\nclawnify deploy # \u2192 the DRAFT site, visible only to your org\n```\n\nDeploying **never** changes the live site. Going live is a separate, explicit\nstep: review the draft, then **Publish to live** in the dashboard. Tell the user\nthis \u2014 a deploy that \"worked\" but didn't appear on the live site is almost\nalways someone expecting deploy to publish.\n\n## Pinning the org\n\nEvery command resolves which organization it targets, folder-first. In a linked\nfolder you get it for free; otherwise pass `--org`. If you work across several\norganizations, pass `--org` explicitly on anything that writes \u2014 the global\nactive org is shared machine-wide and another session can change it under you.\n"
|
|
1671
|
+
},
|
|
1466
1672
|
{
|
|
1467
1673
|
name: "use-the-clawnify-cli",
|
|
1468
1674
|
description: "Use the Clawnify CLI end-to-end \u2014 authenticate, scaffold, run locally, deploy apps and websites, link projects, manage orgs, and inspect deployed apps. Use when deploying to Clawnify from a terminal or wiring the CLI into scripts and coding agents.",
|
|
@@ -4124,4 +4330,4 @@ async function runCli() {
|
|
|
4124
4330
|
export {
|
|
4125
4331
|
runCli
|
|
4126
4332
|
};
|
|
4127
|
-
//# sourceMappingURL=cli-
|
|
4333
|
+
//# sourceMappingURL=cli-KOUOVFNL.js.map
|