@mediamonks/canopy-cli 0.7.58 → 0.7.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/{ai-00f2Mgqh.mjs → ai-4Mr9FbLU.mjs} +2 -2
  2. package/dist/{api-fmc8CEMT.mjs → api-CpG-9WSe.mjs} +13 -1
  3. package/dist/{audience-ByM1jUH3.mjs → audience-BXXdvGC_.mjs} +3 -3
  4. package/dist/{browse-CxwKuka0.mjs → browse-BegddW9V.mjs} +2 -2
  5. package/dist/{calls-DsbRjCcy.mjs → calls-NFUccBaQ.mjs} +3 -3
  6. package/dist/{db-BU-ni9fj.mjs → db-DIxujtt1.mjs} +13 -6
  7. package/dist/{deploy-k2DzsLxO.mjs → deploy-Bp5DMp_U.mjs} +4 -4
  8. package/dist/{dev-qp1VRNM_.mjs → dev-AkM6kLVb.mjs} +9 -9
  9. package/dist/dev-pj6lLjMR.mjs +2 -0
  10. package/dist/{dev-worker-7tqL9UFi.mjs → dev-worker-DEK8fOgz.mjs} +18 -1
  11. package/dist/docs/cli-dev.md +1 -1
  12. package/dist/docs/data.md +18 -0
  13. package/dist/docs/migrations.md +22 -0
  14. package/dist/docs/sdk-database.md +51 -0
  15. package/dist/{docs-ZBBQi3uK.mjs → docs-F0GxdMrn.mjs} +4 -4
  16. package/dist/{egress-Bzn2VKDe.mjs → egress-Dwq-d6cB.mjs} +3 -3
  17. package/dist/{feedback-B0-6QTSh.mjs → feedback-ClCjUP3z.mjs} +4 -4
  18. package/dist/{files-CBbAtHIK.mjs → files-CUPtGcuZ.mjs} +3 -3
  19. package/dist/index.mjs +39 -39
  20. package/dist/{local-C1i2uhAf.mjs → local-CFxKguzg.mjs} +54 -19
  21. package/dist/{login-Baso-JE0.mjs → login-CP1fO_AH.mjs} +3 -3
  22. package/dist/{logs-c76jVOhb.mjs → logs-BwqG7lYU.mjs} +3 -3
  23. package/dist/{mcp-DmcjX8Kn.mjs → mcp-CnTfFA0U.mjs} +3 -3
  24. package/dist/{migrations-ChafLorm.mjs → migrations-DJrRnU7X.mjs} +2 -2
  25. package/dist/{open-Doat726T.mjs → open-5JLHiz_J.mjs} +2 -2
  26. package/dist/{package-BzvVsyRl.mjs → package-tnyqU_dN.mjs} +1 -1
  27. package/dist/{project-template-BnX47DpF.mjs → project-template-CsTOpPto.mjs} +3 -3
  28. package/dist/project-template-xNjGs9ty.mjs +2 -0
  29. package/dist/{projects-DOqpkUVT.mjs → projects-DCFn4zcq.mjs} +6 -6
  30. package/dist/{rename-RA_oYbRT.mjs → rename-OeOI97da.mjs} +3 -3
  31. package/dist/repo-BW7dDQZL.mjs +2 -0
  32. package/dist/{repo-DD3eK1P_.mjs → repo-CIEG53hP.mjs} +3 -3
  33. package/dist/{roles-tqf4sYDM.mjs → roles-2Pkqiwrx.mjs} +1 -1
  34. package/dist/{roles-BS8-Gvv-.mjs → roles-BCJWHeGq.mjs} +3 -3
  35. package/dist/{schedule-D8AQ8MVF.mjs → schedule-Cy-7IFy5.mjs} +3 -3
  36. package/dist/{secrets-Bi7BYCla.mjs → secrets-Cgte8mvq.mjs} +3 -3
  37. package/dist/{site-BcZ0LOvm.mjs → site-Bz-fEyKS.mjs} +1 -1
  38. package/dist/{skill-k3HLr7rK.mjs → skill-CoPNcCaM.mjs} +2 -2
  39. package/dist/{src-DpjA-a59.mjs → src-Dlg7aeRj.mjs} +250 -23
  40. package/dist/{staging-BxG3Cffd.mjs → staging-D6-Ojy39.mjs} +3 -3
  41. package/dist/{token-bHdy_IoX.mjs → token-yAj7pF78.mjs} +3 -3
  42. package/dist/{ui-9f_lF2Ak.mjs → ui-BUeiY_zZ.mjs} +1 -1
  43. package/dist/{upgrade-DkjbsYNs.mjs → upgrade-CLFrKuJS.mjs} +2 -2
  44. package/dist/{usage-DFs2TERV.mjs → usage-BXPm04tk.mjs} +3 -3
  45. package/dist/{versions-Cgw7sB3h.mjs → versions-C204ivt9.mjs} +3 -3
  46. package/package.json +1 -1
  47. package/dist/dev-BtacZ4HE.mjs +0 -2
  48. package/dist/project-template--mESzwea.mjs +0 -2
  49. package/dist/repo-DayXVvyj.mjs +0 -2
@@ -1,5 +1,5 @@
1
- import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
2
- import { i as reportErrors } from "./ui-9f_lF2Ak.mjs";
1
+ import { a as apiRequest, m as withContext } from "./api-CpG-9WSe.mjs";
2
+ import { i as reportErrors } from "./ui-BUeiY_zZ.mjs";
3
3
  import { defineCommand } from "citty";
4
4
  //#region src/ai.ts
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { h as tryReadCanopyJson, p as rewriteCanopyJsonSlug, r as siteConfig, t as projectDir } from "./site-BcZ0LOvm.mjs";
1
+ import { h as tryReadCanopyJson, p as rewriteCanopyJsonSlug, r as siteConfig, t as projectDir } from "./site-Bz-fEyKS.mjs";
2
2
  //#region src/api.ts
3
3
  /**
4
4
  * Authenticated requests to the Canopy control plane. Credentials, in order:
@@ -226,6 +226,18 @@ const ERROR_COPY = {
226
226
  why: "branches are full git refs, and the staging branch must differ from the live one",
227
227
  fix: "Pass e.g. `--ref refs/heads/main --staging-ref refs/heads/develop`."
228
228
  },
229
+ export_unsupported: {
230
+ why: "the database holds a table that exports and snapshots can't include",
231
+ fix: "The detail names the table. Remove it if you can, or report it with `canopy feedback report`."
232
+ },
233
+ snapshot_failed: {
234
+ why: "the platform could not export the database to take the snapshot",
235
+ fix: "Retry once. If it fails the same way, it isn't temporary: report it with `canopy feedback report` and include the request id."
236
+ },
237
+ export_failed: {
238
+ why: "the platform could not export the database",
239
+ fix: "Retry once. If it fails the same way, it isn't temporary: report it with `canopy feedback report` and include the request id."
240
+ },
229
241
  version_expired: {
230
242
  why: "version retention expired that version: its files are gone, so it can no longer be made live, staged, pinned or downloaded",
231
243
  fix: "Pick a version that is still kept (`canopy versions` shows how many are), or rebuild it from source and deploy."
@@ -1,6 +1,6 @@
1
- import { f as resolveProject, l as projectDirArgs, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
3
- import { i as reportErrors } from "./ui-9f_lF2Ak.mjs";
1
+ import { f as resolveProject, l as projectDirArgs, u as projectFlagArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-CpG-9WSe.mjs";
3
+ import { i as reportErrors } from "./ui-BUeiY_zZ.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  import * as p from "@clack/prompts";
6
6
  //#region src/audience.ts
@@ -1,5 +1,5 @@
1
- import { g as tryResolveProject, r as siteConfig } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, t as ApiError } from "./api-fmc8CEMT.mjs";
1
+ import { g as tryResolveProject, r as siteConfig } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, t as ApiError } from "./api-CpG-9WSe.mjs";
3
3
  import { defineCommand } from "citty";
4
4
  //#region src/browse.ts
5
5
  /**
@@ -1,6 +1,6 @@
1
- import { f as resolveProject, l as projectDirArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
3
- import { i as reportErrors, n as formatDateTime } from "./ui-9f_lF2Ak.mjs";
1
+ import { f as resolveProject, l as projectDirArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-CpG-9WSe.mjs";
3
+ import { i as reportErrors, n as formatDateTime } from "./ui-BUeiY_zZ.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  //#region src/calls.ts
6
6
  /**
@@ -1,7 +1,7 @@
1
- import { f as resolveProject, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext, r as apiDataRequest } from "./api-fmc8CEMT.mjs";
3
- import { a as requireTty, i as reportErrors, o as spinner$1, s as unwrap, t as confirmTypedSlug } from "./ui-9f_lF2Ak.mjs";
4
- import { n as migrateProject, r as readMigrationFiles, t as describeMigrateResult } from "./migrations-ChafLorm.mjs";
1
+ import { f as resolveProject, u as projectFlagArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, m as withContext, r as apiDataRequest } from "./api-CpG-9WSe.mjs";
3
+ import { a as requireTty, i as reportErrors, o as spinner$1, s as unwrap, t as confirmTypedSlug } from "./ui-BUeiY_zZ.mjs";
4
+ import { n as migrateProject, r as readMigrationFiles, t as describeMigrateResult } from "./migrations-DJrRnU7X.mjs";
5
5
  import { defineCommand } from "citty";
6
6
  import { readFileSync, writeFileSync } from "node:fs";
7
7
  import * as p from "@clack/prompts";
@@ -29,6 +29,10 @@ const stagingFlagArgs = { staging: {
29
29
  } };
30
30
  const channelOf = (args) => args.staging ? "staging" : "live";
31
31
  const channelNote = (args) => args.staging ? " [staging]" : "";
32
+ /** The notes an export or snapshot came back with, one printable line each. */
33
+ function exportNoteLines(notes) {
34
+ return (notes ?? []).map((note) => `Note: ${note}`);
35
+ }
32
36
  const formatSize = (bytes) => bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} kB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`;
33
37
  const pullCommand = defineCommand({
34
38
  meta: {
@@ -49,12 +53,13 @@ const pullCommand = defineCommand({
49
53
  const spin = spinner$1();
50
54
  spin.start(`Exporting ${slug}${channelNote(args)}…`);
51
55
  try {
52
- const { url } = await apiDataRequest("POST", "/db/export", slug, void 0, { channel: channelOf(args) });
56
+ const { url, notes } = await apiDataRequest("POST", "/db/export", slug, void 0, { channel: channelOf(args) });
53
57
  const download = await fetch(url);
54
58
  if (!download.ok) throw new Error(`Download failed (HTTP ${download.status}).`);
55
59
  const sql = Buffer.from(await download.arrayBuffer());
56
60
  writeFileSync(out, sql);
57
61
  spin.stop(`Wrote ${out} (${formatSize(sql.byteLength)}).`);
62
+ for (const line of exportNoteLines(notes)) console.log(line);
58
63
  } catch (err) {
59
64
  spin.error("Export failed.");
60
65
  throw err;
@@ -75,13 +80,15 @@ const snapshotCommand = defineCommand({
75
80
  const spin = spinner$1();
76
81
  spin.start(`Snapshotting ${slug}${channelNote(args)}…`);
77
82
  let created;
83
+ let notes;
78
84
  try {
79
- ({snapshot: created} = await apiDataRequest("POST", "/db/snapshots", slug, void 0, { channel: channelOf(args) }));
85
+ ({snapshot: created, notes} = await apiDataRequest("POST", "/db/snapshots", slug, void 0, { channel: channelOf(args) }));
80
86
  } catch (err) {
81
87
  spin.error("Snapshot failed.");
82
88
  throw err;
83
89
  }
84
90
  spin.stop(`Stored ${created.key} (${formatSize(created.size)}).`);
91
+ for (const line of exportNoteLines(notes)) console.log(line);
85
92
  console.log(`Restore anytime with \`canopy db restore --snapshot ${created.key}\`.`);
86
93
  })
87
94
  });
@@ -1,7 +1,7 @@
1
- import { d as projectUrl, f as resolveProject, h as tryReadCanopyJson, l as projectDirArgs, m as stagingUrl, r as siteConfig, s as parseVersionArg, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, d as githubActionsCredentials, i as apiDownload, l as currentSlug, m as withContext, p as onGithubActions, r as apiDataRequest, t as ApiError } from "./api-fmc8CEMT.mjs";
3
- import { i as reportErrors, n as formatDateTime, o as spinner$1, s as unwrap } from "./ui-9f_lF2Ak.mjs";
4
- import { n as migrateProject, r as readMigrationFiles, t as describeMigrateResult } from "./migrations-ChafLorm.mjs";
1
+ import { d as projectUrl, f as resolveProject, h as tryReadCanopyJson, l as projectDirArgs, m as stagingUrl, r as siteConfig, s as parseVersionArg, u as projectFlagArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, d as githubActionsCredentials, i as apiDownload, l as currentSlug, m as withContext, p as onGithubActions, r as apiDataRequest, t as ApiError } from "./api-CpG-9WSe.mjs";
3
+ import { i as reportErrors, n as formatDateTime, o as spinner$1, s as unwrap } from "./ui-BUeiY_zZ.mjs";
4
+ import { n as migrateProject, r as readMigrationFiles, t as describeMigrateResult } from "./migrations-DJrRnU7X.mjs";
5
5
  import { builtinModules } from "node:module";
6
6
  import { defineCommand } from "citty";
7
7
  import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -1,9 +1,9 @@
1
- import { c as projectDialect, f as resolveProject, h as tryReadCanopyJson, l as projectDirArgs, r as siteConfig } from "./site-BcZ0LOvm.mjs";
2
- import { r as stampWorkerHeaders, t as WORKER_ATTEST_HEADER } from "./src-DpjA-a59.mjs";
3
- import { a as apiRequest, m as withContext, t as ApiError } from "./api-fmc8CEMT.mjs";
4
- import { i as reportErrors, n as formatDateTime } from "./ui-9f_lF2Ak.mjs";
5
- import { r as readMigrationFiles } from "./migrations-ChafLorm.mjs";
6
- import { s as parseAppRoleFlag } from "./roles-BS8-Gvv-.mjs";
1
+ import { c as projectDialect, f as resolveProject, h as tryReadCanopyJson, l as projectDirArgs, r as siteConfig } from "./site-Bz-fEyKS.mjs";
2
+ import { r as stampWorkerHeaders, t as WORKER_ATTEST_HEADER } from "./src-Dlg7aeRj.mjs";
3
+ import { a as apiRequest, m as withContext, t as ApiError } from "./api-CpG-9WSe.mjs";
4
+ import { i as reportErrors, n as formatDateTime } from "./ui-BUeiY_zZ.mjs";
5
+ import { r as readMigrationFiles } from "./migrations-DJrRnU7X.mjs";
6
+ import { s as parseAppRoleFlag } from "./roles-BCJWHeGq.mjs";
7
7
  import { n as writeDevServerRecord } from "./dev-server-file-Dk9pk4AR.mjs";
8
8
  import { createRequire } from "node:module";
9
9
  import { defineCommand } from "citty";
@@ -107,7 +107,7 @@ async function workerPlugin(flags, slug, workerAttest, remoteUser, roles) {
107
107
  console.log(`note: canopy.json points "worker" at ${entry}, which does not exist — skipping.`);
108
108
  return;
109
109
  }
110
- const { missingSecretNames, readDevVars, workerDevPlugin } = await import("./dev-worker-7tqL9UFi.mjs");
110
+ const { missingSecretNames, readDevVars, workerDevPlugin } = await import("./dev-worker-DEK8fOgz.mjs");
111
111
  const secrets = readDevVars(flags.dir);
112
112
  const email = siteConfig().email;
113
113
  const found = await remoteUser?.() ?? (email ? {
@@ -326,7 +326,7 @@ async function devRemote(flags, slug) {
326
326
  async function devLocal(flags, slug) {
327
327
  let dump;
328
328
  if (flags.pull) {
329
- const { fetchProjectDump } = await import("./local-C1i2uhAf.mjs");
329
+ const { fetchProjectDump } = await import("./local-CFxKguzg.mjs");
330
330
  console.log(`Pulling a fresh export of ${slug}${flags.staging ? " [staging]" : ""}…`);
331
331
  dump = await fetchProjectDump(slug, flags.staging ? "staging" : "live");
332
332
  }
@@ -343,7 +343,7 @@ async function devLocal(flags, slug) {
343
343
  }
344
344
  const workerAttest = randomBytes(24).toString("base64url");
345
345
  const devRoles = await resolveDevRoles(slug, flags.asRoles);
346
- const { createSandbox } = await import("./local-C1i2uhAf.mjs");
346
+ const { createSandbox } = await import("./local-CFxKguzg.mjs");
347
347
  const sandbox = await createSandbox({
348
348
  slug,
349
349
  persistDir: join(flags.dir, ".canopy", "local"),
@@ -0,0 +1,2 @@
1
+ import { n as devCommand } from "./dev-AkM6kLVb.mjs";
2
+ export { devCommand };
@@ -1,4 +1,4 @@
1
- import { a as readPersonCaller, i as CALLER_HEADER, n as redactCanopyCredentials, o as readUser, r as stampWorkerHeaders, t as WORKER_ATTEST_HEADER } from "./src-DpjA-a59.mjs";
1
+ import { a as readPersonCaller, i as CALLER_HEADER, n as redactCanopyCredentials, o as readUser, r as stampWorkerHeaders, t as WORKER_ATTEST_HEADER } from "./src-Dlg7aeRj.mjs";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { relative, resolve, sep } from "node:path";
4
4
  //#region src/dev-worker.ts
@@ -148,6 +148,23 @@ function createDevDb(canopyFetch, dialect) {
148
148
  rows,
149
149
  rowCount: rows.length
150
150
  };
151
+ },
152
+ batch: async (statements) => {
153
+ const response = await canopyFetch("/data/v1/db/sql/batch", {
154
+ method: "POST",
155
+ headers: { "content-type": "application/json" },
156
+ body: JSON.stringify({ statements })
157
+ });
158
+ if (!response.ok) {
159
+ const text = await response.text();
160
+ let detail = text.slice(0, 300);
161
+ try {
162
+ const body = JSON.parse(text);
163
+ detail = body.detail ?? body.error ?? detail;
164
+ } catch {}
165
+ throw new Error(`env.DB batch failed (HTTP ${response.status}): ${detail}`);
166
+ }
167
+ return (await response.json()).results;
151
168
  }
152
169
  };
153
170
  }
@@ -40,7 +40,7 @@ With the lock in place, `--local` runs on an embedded SQLite engine instead —
40
40
 
41
41
  **Your backend worker.** If `canopy.json` names a `worker` entry (the worker scaffold does), `canopy dev` serves it too: requests to `/api/*` go to your worker, everything else to the SPA — the same split the platform makes once you deploy. There's no build step; save the file and the next request runs the new code.
42
42
 
43
- Your worker gets the same `env` it gets in production: `env.CANOPY.fetch` for the SDK, `env.DB` and `env.BLOB` for raw database and file access, `env.CALLER` and `env.USER` for whoever is calling, `env.PROJECT_SLUG`, and `env.CANOPY_CHANNEL` (`"staging"` with `--staging`, otherwise `"live"`). They all follow the mode you're in — live project data by default, your sandbox under `--local`. Three differences worth knowing: `env.CALLER` and `env.USER` are you (the account you logged in with), since there's no company login in front of a local server; there's no [access token](https://docs.canopy.website/guides/access-tokens) check, so `env.CALLER.token` is always `null` and `requireScope` lets every request through; and a write through `env.DB` reports no row count locally.
43
+ Your worker gets the same `env` it gets in production: `env.CANOPY.fetch` for the SDK, `env.DB` (with [`batch()`](https://docs.canopy.website/sdk/database#in-your-worker), still all or nothing) and `env.BLOB` for raw database and file access, `env.CALLER` and `env.USER` for whoever is calling, `env.PROJECT_SLUG`, and `env.CANOPY_CHANNEL` (`"staging"` with `--staging`, otherwise `"live"`). They all follow the mode you're in — live project data by default, your sandbox under `--local`. Three differences worth knowing: `env.CALLER` and `env.USER` are you (the account you logged in with), since there's no company login in front of a local server; there's no [access token](https://docs.canopy.website/guides/access-tokens) check, so `env.CALLER.token` is always `null` and `requireScope` lets every request through; and a write through `env.DB.query()` reports no row count locally (`env.DB.batch()` does).
44
44
 
45
45
  To tick a schedule by hand, post its name to the same path the platform uses:
46
46
 
package/dist/docs/data.md CHANGED
@@ -72,6 +72,24 @@ canopy db snapshots delete <key> # delete one for
72
72
  The same settings are on the dashboard's Data tab. See
73
73
  [`canopy db`](https://docs.canopy.website/cli/db#canopy-db-snapshots-settings) for every option.
74
74
 
75
+ ### Your own full-text search tables
76
+
77
+ On sqlite, a project can create its own full-text search tables in a
78
+ [migration](https://docs.canopy.website/guides/migrations) (`CREATE VIRTUAL TABLE … USING fts5(…)`).
79
+ Dumps, snapshots and restores include them:
80
+
81
+ - A table that stores its own text comes back with all its rows.
82
+ - A table that indexes another of your tables (`content='posts'`) is rebuilt from
83
+ that table on restore.
84
+ - A **contentless** table (`content=''`) only keeps an index, which can't be
85
+ exported, so it comes back **empty**. `canopy db pull` and `canopy db snapshot`
86
+ print a note naming it. After a restore, rebuild it from your own data.
87
+ - Settings you changed with FTS5's configuration commands, such as a custom
88
+ `rank`, aren't carried over. Set them again after a restore.
89
+
90
+ Other kinds of virtual tables can't be exported; `canopy db snapshot` names the
91
+ table and stops (`export_unsupported`).
92
+
75
93
  ## Restore — destructive
76
94
 
77
95
  > **Warning:** Restoring **replaces ALL project data**. Take a snapshot first — a snapshot taken seconds earlier
@@ -135,6 +135,28 @@ export default {
135
135
  };
136
136
  ```
137
137
 
138
+ On a sqlite site the backend proxy can also take a second callback for
139
+ `db.batch([...])`. Hand it to [`env.DB.batch()`](https://docs.canopy.website/sdk/database#in-your-worker)
140
+ and Drizzle's batches run in one round trip, all or nothing:
141
+
142
+ ```ts title="worker/index.ts"
143
+ const db = drizzle(
144
+ async (sql, params, method) => {
145
+ /* as above */
146
+ },
147
+ async (queries) => {
148
+ const results = await env.DB.batch(queries.map(({ sql, params }) => ({ sql, params })));
149
+ return results.map(({ rows }, i) => {
150
+ const values = rows.map((row) => Object.values(row));
151
+ return { rows: queries[i]?.method === "get" ? (values[0] ?? []) : values };
152
+ });
153
+ },
154
+ );
155
+ ```
156
+
157
+ Drizzle's `pg-proxy` driver has no batch callback; on a postgres site, call
158
+ `env.DB.batch()` directly with the SQL you need.
159
+
138
160
  **In the browser (or anywhere the SDK runs)**, wrap `canopy.db.sql()` the same
139
161
  way:
140
162
 
@@ -122,6 +122,57 @@ per SDK instance, so calling it often is free.
122
122
  > `db.sql()` only when you genuinely need SQL (aggregates, joins, bulk updates), and branch on
123
123
  > `db.dialect()` whenever the syntax differs.
124
124
 
125
+ ## In your worker
126
+
127
+ Your [backend](https://docs.canopy.website/developers/architecture) also gets the database directly, as
128
+ `env.DB`. It speaks the same SQL as `db.sql()` — your site's own dialect — and
129
+ has no connection string to manage:
130
+
131
+ ```ts title="worker/index.ts"
132
+ // What env.DB looks like; declare it in your worker's Env type.
133
+ interface ProjectDb {
134
+ dialect: "sqlite" | "postgres";
135
+ query(
136
+ sql: string,
137
+ params?: unknown[],
138
+ ): Promise<{ rows: Record<string, unknown>[]; rowCount: number | null }>;
139
+ batch(
140
+ statements: { sql: string; params?: unknown[] }[],
141
+ ): Promise<{ rows: Record<string, unknown>[]; rowCount: number | null }[]>;
142
+ }
143
+ ```
144
+
145
+ - **`dialect`** — `"sqlite"` or `"postgres"`, so your code can pick the right
146
+ placeholders (`?1` versus `$1`).
147
+ - **`query(sql, params?)`** — one statement. `rows` holds what it returned;
148
+ `rowCount` is the number of rows returned, or for a write the number of rows
149
+ it changed.
150
+ - **`batch(statements)`** — several statements in one call, each with its own
151
+ parameters. You get one `{ rows, rowCount }` back per statement, in order.
152
+
153
+ Every `query()` is a round trip to the database. When you write many rows — an
154
+ import, a sync — send them as a batch instead:
155
+
156
+ ```ts title="worker/index.ts"
157
+ const insert = "INSERT INTO texts (key, value) VALUES (?1, ?2)";
158
+ for (let i = 0; i < texts.length; i += 500) {
159
+ await env.DB.batch(
160
+ texts.slice(i, i + 500).map((t) => ({ sql: insert, params: [t.key, t.value] })),
161
+ );
162
+ }
163
+ ```
164
+
165
+ A batch is **all or nothing**. If any statement fails, none of the batch's
166
+ changes are kept and the call throws with the database's own message. That
167
+ also makes a batch the way to change several tables together: `BEGIN` and
168
+ `COMMIT` through `query()` do not hold a transaction.
169
+
170
+ A batch holds at most 1,000 statements. Each statement keeps the database's
171
+ own limits, such as 100 bound parameters per statement on a SQLite site. A
172
+ statement cannot use an earlier one's result as a parameter; use a subquery or
173
+ `RETURNING` in SQL for that. `canopy dev` gives your worker the same `env.DB`,
174
+ batches included.
175
+
125
176
  ## Who can call this from the browser
126
177
 
127
178
  Everything above works from a page as well as from your worker — that is the
@@ -1,8 +1,8 @@
1
- import { t as version } from "./package-BzvVsyRl.mjs";
2
- import { r as siteConfig } from "./site-BcZ0LOvm.mjs";
1
+ import { t as version } from "./package-tnyqU_dN.mjs";
2
+ import { r as siteConfig } from "./site-Bz-fEyKS.mjs";
3
3
  import { i as latestKnownVersion, r as compareSemver } from "./version-check-CcsA1QjI.mjs";
4
- import { n as agentHeaders } from "./api-fmc8CEMT.mjs";
5
- import { i as reportErrors } from "./ui-9f_lF2Ak.mjs";
4
+ import { n as agentHeaders } from "./api-CpG-9WSe.mjs";
5
+ import { i as reportErrors } from "./ui-BUeiY_zZ.mjs";
6
6
  import { defineCommand } from "citty";
7
7
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
8
8
  import { homedir } from "node:os";
@@ -1,6 +1,6 @@
1
- import { f as resolveProject, l as projectDirArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
3
- import { i as reportErrors, n as formatDateTime, s as unwrap, t as confirmTypedSlug } from "./ui-9f_lF2Ak.mjs";
1
+ import { f as resolveProject, l as projectDirArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-CpG-9WSe.mjs";
3
+ import { i as reportErrors, n as formatDateTime, s as unwrap, t as confirmTypedSlug } from "./ui-BUeiY_zZ.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  import * as p from "@clack/prompts";
6
6
  //#region src/egress.ts
@@ -1,7 +1,7 @@
1
- import { t as version } from "./package-BzvVsyRl.mjs";
2
- import { f as resolveProject, g as tryResolveProject, h as tryReadCanopyJson, l as projectDirArgs, r as siteConfig } from "./site-BcZ0LOvm.mjs";
3
- import { a as apiRequest, c as credentials, i as apiDownload, o as apiUpload, s as commonHeaders } from "./api-fmc8CEMT.mjs";
4
- import { i as reportErrors, n as formatDateTime } from "./ui-9f_lF2Ak.mjs";
1
+ import { t as version } from "./package-tnyqU_dN.mjs";
2
+ import { f as resolveProject, g as tryResolveProject, h as tryReadCanopyJson, l as projectDirArgs, r as siteConfig } from "./site-Bz-fEyKS.mjs";
3
+ import { a as apiRequest, c as credentials, i as apiDownload, o as apiUpload, s as commonHeaders } from "./api-CpG-9WSe.mjs";
4
+ import { i as reportErrors, n as formatDateTime } from "./ui-BUeiY_zZ.mjs";
5
5
  import { defineCommand } from "citty";
6
6
  import { basename, extname, join } from "node:path";
7
7
  import { readFile, writeFile } from "node:fs/promises";
@@ -1,6 +1,6 @@
1
- import { f as resolveProject, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest } from "./api-fmc8CEMT.mjs";
3
- import { i as reportErrors } from "./ui-9f_lF2Ak.mjs";
1
+ import { f as resolveProject, u as projectFlagArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest } from "./api-CpG-9WSe.mjs";
3
+ import { i as reportErrors } from "./ui-BUeiY_zZ.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  //#region src/files.ts
6
6
  /**
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as version } from "./package-BzvVsyRl.mjs";
3
- import { i as siteHeaderLine, n as setInvocationProfile } from "./site-BcZ0LOvm.mjs";
2
+ import { t as version } from "./package-tnyqU_dN.mjs";
3
+ import { i as siteHeaderLine, n as setInvocationProfile } from "./site-Bz-fEyKS.mjs";
4
4
  import { a as notifyOfUpdate, o as runRefresh } from "./version-check-CcsA1QjI.mjs";
5
5
  import { defineCommand, runMain } from "citty";
6
6
  //#region src/index.ts
@@ -51,43 +51,43 @@ const main = defineCommand({
51
51
  description: "canopy — create and deploy vibecoded projects"
52
52
  },
53
53
  subCommands: {
54
- login: () => import("./login-Baso-JE0.mjs").then((m) => m.loginCommand),
55
- whoami: () => import("./login-Baso-JE0.mjs").then((m) => m.whoamiCommand),
56
- logout: () => import("./login-Baso-JE0.mjs").then((m) => m.logoutCommand),
57
- create: () => import("./projects-DOqpkUVT.mjs").then((m) => m.createCommand),
58
- init: () => import("./projects-DOqpkUVT.mjs").then((m) => m.initCommand),
59
- projects: () => import("./projects-DOqpkUVT.mjs").then((m) => m.projectsCommand),
60
- delete: () => import("./projects-DOqpkUVT.mjs").then((m) => m.deleteCommand),
61
- rename: () => import("./rename-RA_oYbRT.mjs").then((m) => m.renameCommand),
62
- dev: () => import("./dev-BtacZ4HE.mjs").then((m) => m.devCommand),
63
- deploy: () => import("./deploy-k2DzsLxO.mjs").then((m) => m.deployCommand),
64
- promote: () => import("./deploy-k2DzsLxO.mjs").then((m) => m.promoteCommand),
65
- staging: () => import("./staging-BxG3Cffd.mjs").then((m) => m.stagingCommand),
66
- rollback: () => import("./deploy-k2DzsLxO.mjs").then((m) => m.rollbackCommand),
67
- download: () => import("./deploy-k2DzsLxO.mjs").then((m) => m.downloadCommand),
68
- versions: () => import("./versions-Cgw7sB3h.mjs").then((m) => m.versionsCommand),
69
- token: () => import("./token-bHdy_IoX.mjs").then((m) => m.tokenCommand),
70
- egress: () => import("./egress-Bzn2VKDe.mjs").then((m) => m.egressCommand),
71
- calls: () => import("./calls-DsbRjCcy.mjs").then((m) => m.callsCommand),
72
- secrets: () => import("./secrets-Bi7BYCla.mjs").then((m) => m.secretsCommand),
73
- roles: () => import("./roles-tqf4sYDM.mjs").then((m) => m.rolesCommand),
74
- members: () => import("./roles-tqf4sYDM.mjs").then((m) => m.membersCommand),
75
- schedule: () => import("./schedule-D8AQ8MVF.mjs").then((m) => m.scheduleCommand),
76
- feedback: () => import("./feedback-B0-6QTSh.mjs").then((m) => m.feedbackCommand),
77
- db: () => import("./db-BU-ni9fj.mjs").then((m) => m.dbCommand),
78
- files: () => import("./files-CBbAtHIK.mjs").then((m) => m.filesCommand),
79
- usage: () => import("./usage-DFs2TERV.mjs").then((m) => m.usageCommand),
80
- ai: () => import("./ai-00f2Mgqh.mjs").then((m) => m.aiCommand),
81
- open: () => import("./open-Doat726T.mjs").then((m) => m.openCommand),
82
- browse: () => import("./browse-CxwKuka0.mjs").then((m) => m.browseCommand),
83
- docs: () => import("./docs-ZBBQi3uK.mjs").then((m) => m.docsCommand),
84
- skill: () => import("./skill-k3HLr7rK.mjs").then((m) => m.skillCommand),
85
- upgrade: () => import("./upgrade-DkjbsYNs.mjs").then((m) => m.upgradeCommand),
86
- logs: () => import("./logs-c76jVOhb.mjs").then((m) => m.logsCommand),
87
- mcp: () => import("./mcp-DmcjX8Kn.mjs").then((m) => m.mcpCommand),
88
- repo: () => import("./repo-DayXVvyj.mjs").then((m) => m.repoCommand),
89
- template: () => import("./project-template--mESzwea.mjs").then((m) => m.templateCommand),
90
- audience: () => import("./audience-ByM1jUH3.mjs").then((m) => m.audienceCommand)
54
+ login: () => import("./login-CP1fO_AH.mjs").then((m) => m.loginCommand),
55
+ whoami: () => import("./login-CP1fO_AH.mjs").then((m) => m.whoamiCommand),
56
+ logout: () => import("./login-CP1fO_AH.mjs").then((m) => m.logoutCommand),
57
+ create: () => import("./projects-DCFn4zcq.mjs").then((m) => m.createCommand),
58
+ init: () => import("./projects-DCFn4zcq.mjs").then((m) => m.initCommand),
59
+ projects: () => import("./projects-DCFn4zcq.mjs").then((m) => m.projectsCommand),
60
+ delete: () => import("./projects-DCFn4zcq.mjs").then((m) => m.deleteCommand),
61
+ rename: () => import("./rename-OeOI97da.mjs").then((m) => m.renameCommand),
62
+ dev: () => import("./dev-pj6lLjMR.mjs").then((m) => m.devCommand),
63
+ deploy: () => import("./deploy-Bp5DMp_U.mjs").then((m) => m.deployCommand),
64
+ promote: () => import("./deploy-Bp5DMp_U.mjs").then((m) => m.promoteCommand),
65
+ staging: () => import("./staging-D6-Ojy39.mjs").then((m) => m.stagingCommand),
66
+ rollback: () => import("./deploy-Bp5DMp_U.mjs").then((m) => m.rollbackCommand),
67
+ download: () => import("./deploy-Bp5DMp_U.mjs").then((m) => m.downloadCommand),
68
+ versions: () => import("./versions-C204ivt9.mjs").then((m) => m.versionsCommand),
69
+ token: () => import("./token-yAj7pF78.mjs").then((m) => m.tokenCommand),
70
+ egress: () => import("./egress-Dwq-d6cB.mjs").then((m) => m.egressCommand),
71
+ calls: () => import("./calls-NFUccBaQ.mjs").then((m) => m.callsCommand),
72
+ secrets: () => import("./secrets-Cgte8mvq.mjs").then((m) => m.secretsCommand),
73
+ roles: () => import("./roles-2Pkqiwrx.mjs").then((m) => m.rolesCommand),
74
+ members: () => import("./roles-2Pkqiwrx.mjs").then((m) => m.membersCommand),
75
+ schedule: () => import("./schedule-Cy-7IFy5.mjs").then((m) => m.scheduleCommand),
76
+ feedback: () => import("./feedback-ClCjUP3z.mjs").then((m) => m.feedbackCommand),
77
+ db: () => import("./db-DIxujtt1.mjs").then((m) => m.dbCommand),
78
+ files: () => import("./files-CUPtGcuZ.mjs").then((m) => m.filesCommand),
79
+ usage: () => import("./usage-BXPm04tk.mjs").then((m) => m.usageCommand),
80
+ ai: () => import("./ai-4Mr9FbLU.mjs").then((m) => m.aiCommand),
81
+ open: () => import("./open-5JLHiz_J.mjs").then((m) => m.openCommand),
82
+ browse: () => import("./browse-BegddW9V.mjs").then((m) => m.browseCommand),
83
+ docs: () => import("./docs-F0GxdMrn.mjs").then((m) => m.docsCommand),
84
+ skill: () => import("./skill-CoPNcCaM.mjs").then((m) => m.skillCommand),
85
+ upgrade: () => import("./upgrade-CLFrKuJS.mjs").then((m) => m.upgradeCommand),
86
+ logs: () => import("./logs-BwqG7lYU.mjs").then((m) => m.logsCommand),
87
+ mcp: () => import("./mcp-CnTfFA0U.mjs").then((m) => m.mcpCommand),
88
+ repo: () => import("./repo-BW7dDQZL.mjs").then((m) => m.repoCommand),
89
+ template: () => import("./project-template-xNjGs9ty.mjs").then((m) => m.templateCommand),
90
+ audience: () => import("./audience-BXXdvGC_.mjs").then((m) => m.audienceCommand)
91
91
  }
92
92
  });
93
93
  const quiet = process.argv[2] === "mcp" && process.argv[3] === "serve" || process.argv[2] === "repo" && process.argv[3] === "credential";
@@ -1,6 +1,6 @@
1
- import { c as dbRouter, h as isCreateOnly, l as hasPrivateNames, m as blobRouter, p as STREAMED_BLOB_BYTES, s as realtimeRouter, t as WORKER_ATTEST_HEADER, u as META_COLUMNS } from "./src-DpjA-a59.mjs";
2
- import { r as apiDataRequest } from "./api-fmc8CEMT.mjs";
3
- import { a as rewriteApiPath } from "./dev-qp1VRNM_.mjs";
1
+ import { c as dbRouter, h as isCreateOnly, l as hasPrivateNames, m as blobRouter, p as STREAMED_BLOB_BYTES, s as realtimeRouter, t as WORKER_ATTEST_HEADER, u as META_COLUMNS } from "./src-Dlg7aeRj.mjs";
2
+ import { r as apiDataRequest } from "./api-CpG-9WSe.mjs";
3
+ import { a as rewriteApiPath } from "./dev-AkM6kLVb.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
6
6
  import { dirname, join, relative, sep } from "node:path";
@@ -818,13 +818,28 @@ async function createPgliteDb(persistDir) {
818
818
  const db = dataDir ? new PGlite(dataDir) : new PGlite();
819
819
  await db.waitReady;
820
820
  return {
821
- store: { query: async (sql, params = []) => {
822
- const result = await db.query(sql, params);
823
- return {
824
- results: result.rows,
825
- meta: { changes: Number(result.affectedRows ?? 0) }
826
- };
827
- } },
821
+ store: {
822
+ query: async (sql, params = []) => {
823
+ const result = await db.query(sql, params);
824
+ return {
825
+ results: result.rows,
826
+ meta: { changes: Number(result.affectedRows ?? 0) }
827
+ };
828
+ },
829
+ batch: (statements) => db.transaction(async (tx) => {
830
+ const out = [];
831
+ for (const [i, s] of statements.entries()) {
832
+ const result = await tx.query(s.sql, s.params).catch((err) => {
833
+ throw new Error(`statement ${i}: ${err instanceof Error ? err.message : String(err)}`);
834
+ });
835
+ out.push({
836
+ results: result.rows,
837
+ meta: { changes: Number(result.affectedRows ?? 0) }
838
+ });
839
+ }
840
+ return out;
841
+ })
842
+ },
828
843
  exec: async (sql) => {
829
844
  await db.exec(sql);
830
845
  },
@@ -849,16 +864,36 @@ async function createSqliteDb(persistDir) {
849
864
  if (persistDir) mkdirSync(persistDir, { recursive: true });
850
865
  const db = new DatabaseSync(persistDir ? join(persistDir, "sqlite.db") : ":memory:");
851
866
  const listTables = (where) => db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND ${where}`).all().map((row) => row.name);
867
+ const run = (sql, params) => {
868
+ const bound = params.map((p) => typeof p === "boolean" ? p ? 1 : 0 : p);
869
+ const results = db.prepare(sql).all(...bound);
870
+ const { c } = db.prepare("SELECT changes() AS c").get();
871
+ return {
872
+ results,
873
+ meta: { changes: Number(c) }
874
+ };
875
+ };
852
876
  return {
853
- store: { query: async (sql, params = []) => {
854
- const bound = params.map((p) => typeof p === "boolean" ? p ? 1 : 0 : p);
855
- const results = db.prepare(sql).all(...bound);
856
- const { c } = db.prepare("SELECT changes() AS c").get();
857
- return {
858
- results,
859
- meta: { changes: Number(c) }
860
- };
861
- } },
877
+ store: {
878
+ query: async (sql, params = []) => run(sql, params),
879
+ batch: async (statements) => {
880
+ db.exec("BEGIN");
881
+ try {
882
+ const out = statements.map((s, i) => {
883
+ try {
884
+ return run(s.sql, s.params);
885
+ } catch (err) {
886
+ throw new Error(`statement ${i}: ${err instanceof Error ? err.message : String(err)}`);
887
+ }
888
+ });
889
+ db.exec("COMMIT");
890
+ return out;
891
+ } catch (err) {
892
+ db.exec("ROLLBACK");
893
+ throw err;
894
+ }
895
+ }
896
+ },
862
897
  exec: async (sql) => {
863
898
  db.exec(sql);
864
899
  },
@@ -1,6 +1,6 @@
1
- import { C as upsertProfileAuth, E as isProfileId, S as setActiveProfile, T as getBakedProfile, b as listBakedProfiles, r as siteConfig, w as writeConfigFile, x as readConfigFile, y as clearAllProfileTokens } from "./site-BcZ0LOvm.mjs";
2
- import { n as agentHeaders } from "./api-fmc8CEMT.mjs";
3
- import { i as reportErrors, o as spinner$1, r as openBrowser } from "./ui-9f_lF2Ak.mjs";
1
+ import { C as upsertProfileAuth, E as isProfileId, S as setActiveProfile, T as getBakedProfile, b as listBakedProfiles, r as siteConfig, w as writeConfigFile, x as readConfigFile, y as clearAllProfileTokens } from "./site-Bz-fEyKS.mjs";
2
+ import { n as agentHeaders } from "./api-CpG-9WSe.mjs";
3
+ import { i as reportErrors, o as spinner$1, r as openBrowser } from "./ui-BUeiY_zZ.mjs";
4
4
  import { n as clearRepoTokenCache } from "./repo-credential-CNDRM-tG.mjs";
5
5
  import { defineCommand } from "citty";
6
6
  import { hostname } from "node:os";
@@ -1,6 +1,6 @@
1
- import { f as resolveProject, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
3
- import { i as reportErrors } from "./ui-9f_lF2Ak.mjs";
1
+ import { f as resolveProject, u as projectFlagArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-CpG-9WSe.mjs";
3
+ import { i as reportErrors } from "./ui-BUeiY_zZ.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  //#region src/logs.ts
6
6
  /**
@@ -1,6 +1,6 @@
1
- import { t as version } from "./package-BzvVsyRl.mjs";
2
- import { d as projectUrl, g as tryResolveProject, m as stagingUrl, r as siteConfig } from "./site-BcZ0LOvm.mjs";
3
- import { a as apiRequest, f as noticeRenamesOnly, l as currentSlug, t as ApiError } from "./api-fmc8CEMT.mjs";
1
+ import { t as version } from "./package-tnyqU_dN.mjs";
2
+ import { d as projectUrl, g as tryResolveProject, m as stagingUrl, r as siteConfig } from "./site-Bz-fEyKS.mjs";
3
+ import { a as apiRequest, f as noticeRenamesOnly, l as currentSlug, t as ApiError } from "./api-CpG-9WSe.mjs";
4
4
  import { t as liveDevServer } from "./dev-server-file-Dk9pk4AR.mjs";
5
5
  import { defineCommand } from "citty";
6
6
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
@@ -1,5 +1,5 @@
1
- import { h as tryReadCanopyJson } from "./site-BcZ0LOvm.mjs";
2
- import { r as apiDataRequest } from "./api-fmc8CEMT.mjs";
1
+ import { h as tryReadCanopyJson } from "./site-Bz-fEyKS.mjs";
2
+ import { r as apiDataRequest } from "./api-CpG-9WSe.mjs";
3
3
  import { readFileSync, readdirSync } from "node:fs";
4
4
  import { join, resolve } from "node:path";
5
5
  //#region src/migrations.ts