@mediamonks/canopy-cli 0.7.57 → 0.7.58

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.
@@ -10,6 +10,7 @@ import { join, relative, resolve } from "node:path";
10
10
  import { spawn } from "node:child_process";
11
11
  import * as p from "@clack/prompts";
12
12
  import * as esbuild from "esbuild";
13
+ import { createHash } from "node:crypto";
13
14
  //#region src/worker-bundle.ts
14
15
  /**
15
16
  * Bundle a project's `worker/` entry for deploy (G6).
@@ -149,6 +150,244 @@ const nodeBuiltins = {
149
150
  }
150
151
  };
151
152
  //#endregion
153
+ //#region src/media.ts
154
+ /**
155
+ * Site media for `canopy deploy` (OpenSpec site-media): folders of the build
156
+ * output, declared in canopy.json (`"media": ["mocks/"]`), that are stored once
157
+ * per project instead of in every version and served on the same URLs.
158
+ *
159
+ * Pure helpers here (rules, the split, suggestions, messages); the deploy
160
+ * command does the network part. The rules mirror the server's
161
+ * (apps/api/src/site-media.ts); the server stays authoritative.
162
+ */
163
+ /** Extensions site media may hold: data and media, never code. */
164
+ const MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
165
+ "json",
166
+ "csv",
167
+ "txt",
168
+ "png",
169
+ "jpg",
170
+ "jpeg",
171
+ "gif",
172
+ "webp",
173
+ "avif",
174
+ "ico",
175
+ "mp4",
176
+ "webm",
177
+ "mp3",
178
+ "wav",
179
+ "ogg",
180
+ "m4a",
181
+ "woff",
182
+ "woff2",
183
+ "glb",
184
+ "gltf",
185
+ "bin"
186
+ ]);
187
+ function isMediaFile(path) {
188
+ const file = path.split("/").at(-1) ?? "";
189
+ const dot = file.lastIndexOf(".");
190
+ return dot > 0 && MEDIA_EXTENSIONS.has(file.slice(dot + 1).toLowerCase());
191
+ }
192
+ /**
193
+ * Build output with a content hash in its name (Vite's `name-<8 chars>.ext`),
194
+ * same rule as the server's cache headers: such names change on every build,
195
+ * so they pile up in an additive store.
196
+ */
197
+ function looksHashed(path) {
198
+ const file = path.split("/").at(-1) ?? "";
199
+ const match = /-([A-Za-z0-9_-]{8})\.[A-Za-z0-9]+(?:\.map)?$/.exec(file);
200
+ return match !== null && /[0-9A-Z_-]/.test(match[1] ?? "");
201
+ }
202
+ /** canopy.json `media`, normalized like the server does it; throws on a bad entry. */
203
+ function normalizeMediaFolders(raw) {
204
+ if (raw === void 0 || raw === null) return [];
205
+ if (!Array.isArray(raw) || !raw.every((e) => typeof e === "string")) throw new Error("canopy.json \"media\" must be a list of folders, e.g. [\"mocks/\"].");
206
+ const cleaned = raw.map((entry) => {
207
+ const trimmed = entry.trim().replace(/^\.?\//, "").replace(/\/+$/, "");
208
+ if (trimmed === "" || trimmed.includes("\\") || trimmed.includes("\0") || trimmed.includes("//") || trimmed.split("/").some((seg) => seg === "" || seg === "." || seg === "..")) throw new Error(`canopy.json "media": "${entry}" is not a folder inside the build output (the root can't be media).`);
209
+ return `${trimmed}/`;
210
+ });
211
+ const unique = [...new Set(cleaned)].sort();
212
+ const folders = unique.filter((f) => !unique.some((g) => g !== f && f.startsWith(g)));
213
+ if (folders.length > 10) throw new Error(`canopy.json "media" lists ${folders.length} folders; the limit is 10.`);
214
+ return folders;
215
+ }
216
+ /** Version files and media files, by the declared folders. */
217
+ function splitMedia(files, folders) {
218
+ const bundle = [];
219
+ const media = [];
220
+ for (const file of files) (folders.some((f) => file.path.startsWith(f)) ? media : bundle).push(file);
221
+ return {
222
+ bundle,
223
+ media
224
+ };
225
+ }
226
+ const sha256Hex = (data) => createHash("sha256").update(data).digest("hex");
227
+ /**
228
+ * Folders that could be site media: the topmost folders (not the output root,
229
+ * not already declared) whose files are all data or media, at least 1 MB, and
230
+ * mostly not content-hashed build output. Largest first.
231
+ */
232
+ function mediaCandidates(files, declared = []) {
233
+ const stats = /* @__PURE__ */ new Map();
234
+ for (const file of files) {
235
+ const parts = file.path.split("/");
236
+ const ext = (parts.at(-1)?.split(".").at(-1) ?? "").toLowerCase();
237
+ for (let depth = 1; depth < parts.length; depth++) {
238
+ const folder = `${parts.slice(0, depth).join("/")}/`;
239
+ const s = stats.get(folder) ?? {
240
+ bytes: 0,
241
+ files: 0,
242
+ allMedia: true,
243
+ hashed: 0,
244
+ types: /* @__PURE__ */ new Set()
245
+ };
246
+ s.bytes += file.size;
247
+ s.files += 1;
248
+ s.allMedia &&= isMediaFile(file.path);
249
+ if (looksHashed(file.path)) s.hashed += 1;
250
+ s.types.add(ext);
251
+ stats.set(folder, s);
252
+ }
253
+ }
254
+ const qualifies = (folder) => {
255
+ const s = stats.get(folder);
256
+ return s !== void 0 && s.allMedia && s.bytes >= 1048576 && s.hashed * 2 < s.files && !declared.some((d) => folder.startsWith(d) || d.startsWith(folder));
257
+ };
258
+ const out = [];
259
+ for (const [folder, s] of stats) {
260
+ if (!qualifies(folder)) continue;
261
+ const parent = folder.slice(0, folder.slice(0, -1).lastIndexOf("/") + 1);
262
+ if (parent !== "" && qualifies(parent)) continue;
263
+ out.push({
264
+ folder,
265
+ bytes: s.bytes,
266
+ files: s.files,
267
+ types: [...s.types].sort()
268
+ });
269
+ }
270
+ return out.sort((a, b) => b.bytes - a.bytes || a.folder.localeCompare(b.folder));
271
+ }
272
+ /**
273
+ * The fewest of the largest candidates that bring the version under both
274
+ * limits, or null when even all of them are not enough.
275
+ */
276
+ function candidatesToFit(candidates, version, limits) {
277
+ const fits = (bytes, count) => (limits.maxTotalBytes === void 0 || bytes <= limits.maxTotalBytes) && (limits.maxFiles === void 0 || count <= limits.maxFiles);
278
+ let { bytes, files } = version;
279
+ const picked = [];
280
+ for (const candidate of candidates) {
281
+ if (fits(bytes, files)) break;
282
+ picked.push(candidate);
283
+ bytes -= candidate.bytes;
284
+ files -= candidate.files;
285
+ }
286
+ return fits(bytes, files) ? picked : null;
287
+ }
288
+ const formatSize = (bytes) => bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(1)} GB` : bytes >= 1024 ** 2 ? `${(bytes / 1024 ** 2).toFixed(1)} MB` : `${Math.max(0, Math.round(bytes / 1024))} kB`;
289
+ /** The sentence every media suggestion carries, so an agent weighs it. */
290
+ const NOT_VERSIONED = "Media is not versioned: rollbacks and pinned versions serve the current files.";
291
+ /** The `canopy.json` snippet that declares `folders` (plus any already declared). */
292
+ function mediaSnippet(folders, declared = []) {
293
+ return `"media": ${JSON.stringify([...declared, ...folders])}`;
294
+ }
295
+ /** Lines naming the candidates: folder, size, files, types. */
296
+ function describeCandidates(candidates) {
297
+ const width = Math.max(...candidates.map((c) => c.folder.length));
298
+ return candidates.map((c) => ` ${c.folder.padEnd(width)} ${formatSize(c.bytes).padStart(9)} ${String(c.files).padStart(5)} files ${c.types.join(", ")}`);
299
+ }
300
+ /**
301
+ * The soft hint: the version has reached SUGGEST_AT_SHARE of a limit and
302
+ * there are folders that could move out of it. Null otherwise.
303
+ */
304
+ function mediaHint(candidates, version, limits, declared = []) {
305
+ if (candidates.length === 0) return null;
306
+ const share = Math.max(limits.maxTotalBytes ? version.bytes / limits.maxTotalBytes : 0, limits.maxFiles ? version.files / limits.maxFiles : 0);
307
+ if (share < .3) return null;
308
+ return [
309
+ ` hint: this version is ${formatSize(version.bytes)} in ${version.files} files (${Math.round(share * 100)}% of the deploy limit).`,
310
+ " These folders could be site media (stored once, not part of every version):",
311
+ ...describeCandidates(candidates),
312
+ ` Add to canopy.json: ${mediaSnippet(candidates.map((c) => c.folder), declared)}`,
313
+ ` ${NOT_VERSIONED}`
314
+ ].join("\n");
315
+ }
316
+ /** Text added to the over-limit refusal: what to move, or why moving won't do. */
317
+ function overLimitAdvice(candidates, version, limits, declared = []) {
318
+ if (candidates.length === 0) return "Bundle/minify assets or drop what isn't served, then redeploy.";
319
+ const picked = candidatesToFit(candidates, version, limits);
320
+ if (!picked) return [
321
+ "Even moving every data and media folder to site media would not bring it under the limit:",
322
+ ...describeCandidates(candidates),
323
+ "Bundle/minify assets or drop what isn't served, then redeploy."
324
+ ].join("\n");
325
+ return [
326
+ "Move these folders to site media (stored once, not part of every version):",
327
+ ...describeCandidates(picked),
328
+ `Add to canopy.json: ${mediaSnippet(picked.map((c) => c.folder), declared)}`,
329
+ NOT_VERSIONED
330
+ ].join("\n");
331
+ }
332
+ /** What to upload and what it adds up to, against the stored manifest. */
333
+ function planMedia(local, manifest, opts) {
334
+ const stored = new Map(manifest.map((f) => [f.path, f]));
335
+ const localPaths = new Set(local.map((f) => f.path));
336
+ const upload = [];
337
+ const blocked = [];
338
+ let unchanged = 0;
339
+ for (const file of local) {
340
+ const sha256 = sha256Hex(file.data);
341
+ const remote = stored.get(file.path);
342
+ if (remote?.sha256 === sha256) unchanged++;
343
+ else if (remote && opts.createOnly) blocked.push(file.path);
344
+ else upload.push({
345
+ ...file,
346
+ sha256
347
+ });
348
+ }
349
+ const stale = manifest.filter((f) => !localPaths.has(f.path)).map((f) => f.path);
350
+ const prunes = opts.prune && !opts.createOnly;
351
+ let bytes = 0;
352
+ let files = 0;
353
+ for (const remote of manifest) {
354
+ if (prunes && !localPaths.has(remote.path)) continue;
355
+ const replacing = upload.find((u) => u.path === remote.path);
356
+ bytes += replacing ? replacing.data.byteLength : remote.size;
357
+ files += 1;
358
+ }
359
+ for (const u of upload) if (!stored.has(u.path)) {
360
+ bytes += u.data.byteLength;
361
+ files += 1;
362
+ }
363
+ return {
364
+ upload,
365
+ unchanged,
366
+ stale,
367
+ blocked,
368
+ projectedBytes: bytes,
369
+ projectedFiles: files
370
+ };
371
+ }
372
+ /** Why the media plan breaks the limits, or null. */
373
+ function mediaLimitError(plan, limits) {
374
+ const big = plan.upload.find((f) => f.data.byteLength > limits.maxFileBytes);
375
+ if (big) return `Site media file ${big.path} is ${formatSize(big.data.byteLength)}; one file may be at most ${formatSize(limits.maxFileBytes)} on this site.`;
376
+ if (plan.projectedFiles > limits.maxFiles) return `Site media would hold ${plan.projectedFiles} files; the limit is ${limits.maxFiles}. Drop files or run with --prune-media to remove stored ones that are gone locally.`;
377
+ if (plan.projectedBytes > limits.maxBytes) return `Site media would hold ${formatSize(plan.projectedBytes)}; this project's limit is ${formatSize(limits.maxBytes)}. Run with --prune-media to remove stored files that are gone locally, or ask a Canopy admin to raise it.`;
378
+ return null;
379
+ }
380
+ /** The lines a deploy prints about its media sync. */
381
+ function describeMediaSync(plan, pruned, opts) {
382
+ const kept = plan.projectedBytes;
383
+ const lines = [` media: ${plan.upload.length} uploaded, ${plan.unchanged} unchanged, ${formatSize(kept)} stored`];
384
+ if (plan.blocked.length > 0) lines.push(` ${plan.blocked.length} changed media files were not replaced: this token deploys only to staging, and media is shared with live:`, ...plan.blocked.slice(0, 10).map((path) => ` ${path}`));
385
+ if (pruned.length > 0) lines.push(` pruned ${pruned.length} stored media files no longer in the build:`, ...pruned.slice(0, 20).map((path) => ` ${path}`), ...pruned.length > 20 ? [` … and ${pruned.length - 20} more`] : []);
386
+ else if (!opts.prune && plan.stale.length > 0) lines.push(` ${plan.stale.length} stored media files are no longer in the build; --prune-media removes them.`);
387
+ else if (opts.prune && opts.createOnly && plan.stale.length > 0) lines.push(" --prune-media skipped: this token deploys only to staging and can't delete media.");
388
+ return lines;
389
+ }
390
+ //#endregion
152
391
  //#region src/deploy.ts
153
392
  /**
154
393
  * canopy deploy — build (optional), then the signed-upload flow
@@ -226,6 +465,11 @@ const deployCommand = defineCommand({
226
465
  default: false,
227
466
  description: "Deploy to the project's staging channel (created on first use, database cloned from live)"
228
467
  },
468
+ "prune-media": {
469
+ type: "boolean",
470
+ default: false,
471
+ description: "Delete stored site media files that are no longer in the build (canopy.json media)"
472
+ },
229
473
  worker: {
230
474
  type: "boolean",
231
475
  default: true,
@@ -271,6 +515,25 @@ const deployCommand = defineCommand({
271
515
  data
272
516
  });
273
517
  }
518
+ const mediaFolders = normalizeMediaFolders(config.media);
519
+ const { bundle, media } = splitMedia(files, mediaFolders);
520
+ for (const folder of mediaFolders) if (!media.some((f) => f.path.startsWith(folder))) p.log.warn(`canopy.json "media": ${folder} is not in the build output; nothing to upload from it.`);
521
+ const notMedia = media.filter((f) => !isMediaFile(f.path)).map((f) => f.path);
522
+ if (notMedia.length > 0) throw new Error([
523
+ "Site media holds data and media files only (JSON, CSV, text, images, video, audio, fonts, 3D models). These can't be media:",
524
+ ...notMedia.slice(0, 20).map((path) => ` ${path}`),
525
+ ...notMedia.length > 20 ? [` … and ${notMedia.length - 20} more`] : [],
526
+ "Move them out of the media folders, or take the folder out of canopy.json \"media\"."
527
+ ].join("\n"));
528
+ for (const folder of mediaFolders) {
529
+ const inFolder = media.filter((f) => f.path.startsWith(folder));
530
+ if (inFolder.length > 0 && inFolder.filter((f) => looksHashed(f.path)).length * 2 >= inFolder.length) p.log.warn(`${folder} holds mostly content-hashed build output. Their names change on every build, and site media keeps old files until you deploy with --prune-media.`);
531
+ }
532
+ const bundleBytes = bundle.reduce((sum, f) => sum + f.data.byteLength, 0);
533
+ const candidates = mediaCandidates(bundle.map((f) => ({
534
+ path: f.path,
535
+ size: f.data.byteLength
536
+ })), mediaFolders);
274
537
  let workerBytes = null;
275
538
  if (config.worker && !args.worker) p.log.warn(`Skipping the backend (${config.worker}) — deploying the frontend only.`);
276
539
  if (config.worker && args.worker) {
@@ -289,24 +552,64 @@ const deployCommand = defineCommand({
289
552
  const spin = spinner$1();
290
553
  const workerNote = workerBytes ? " + worker" : "";
291
554
  const channelNote = channel === "staging" ? " [staging]" : "";
292
- spin.start(`Deploying ${files.length} files${workerNote} (${(total / 1024).toFixed(0)} kB) → ${slug}${channelNote}`);
555
+ const mediaNote = media.length > 0 ? ` + ${media.length} media files (${formatSize(total - bundleBytes - (workerBytes?.byteLength ?? 0))})` : "";
556
+ spin.start(`Deploying ${bundle.length} files${workerNote} (${(bundleBytes / 1024).toFixed(0)} kB)${mediaNote} → ${slug}${channelNote}`);
557
+ let mediaReport = [];
293
558
  let result;
294
559
  let migrateResult;
295
560
  let stagingCreated = false;
296
561
  let retentionHint = null;
562
+ let limitsSeen = {};
297
563
  try {
298
564
  const { upload, retention } = await withContext(apiRequest("POST", `/projects/${slug}/deploys`, {
299
565
  worker: workerBytes !== null,
300
- channel
566
+ channel,
567
+ ...mediaFolders.length > 0 && { media: mediaFolders }
301
568
  }, { headers: source }), { action: `deploy "${slug}"` });
302
569
  stagingCreated = upload.stagingCreated === true;
570
+ limitsSeen = {
571
+ maxTotalBytes: upload.maxTotalBytes,
572
+ maxFiles: upload.maxFiles
573
+ };
303
574
  retentionHint = retentionHintLine(retention);
304
- const overLimit = bundleLimitError(files, upload);
575
+ const overLimit = bundleLimitError(bundle, upload);
305
576
  if (overLimit) {
306
577
  spin.error("Deploy refused — nothing was uploaded.");
307
- throw new Error(overLimit);
578
+ throw new Error(`${overLimit}\n${overLimitAdvice(candidates, {
579
+ bytes: bundleBytes,
580
+ files: bundle.length
581
+ }, upload, mediaFolders)}`);
582
+ }
583
+ if (mediaFolders.length > 0 && !upload.media) {
584
+ spin.error("Deploy refused — nothing was uploaded.");
585
+ throw new Error("This site doesn't support site media yet. Take \"media\" out of canopy.json to deploy those folders as part of the version.");
308
586
  }
309
- const uploads = [...files, ...workerBytes ? [{
587
+ if (upload.media) {
588
+ spin.message(`Checking site media → ${slug}`);
589
+ const plan = planMedia(media, (await mediaManifest(upload.grant)).files, {
590
+ prune: args["prune-media"],
591
+ createOnly: upload.media.createOnly
592
+ });
593
+ const mediaError = mediaLimitError(plan, upload.media);
594
+ if (mediaError) {
595
+ spin.error("Deploy refused — nothing was uploaded.");
596
+ throw new Error(mediaError);
597
+ }
598
+ if (plan.upload.length > 0) {
599
+ spin.message(`Uploading ${plan.upload.length} site media files (${formatSize(plan.upload.reduce((n, f) => n + f.data.byteLength, 0))}) → ${slug}`);
600
+ await uploadMedia(upload.grant, plan.upload);
601
+ }
602
+ let pruned = [];
603
+ if (args["prune-media"] && plan.stale.length > 0 && !upload.media.createOnly) {
604
+ await deleteMedia(upload.grant, plan.stale);
605
+ pruned = plan.stale;
606
+ }
607
+ mediaReport = describeMediaSync(plan, pruned, {
608
+ prune: args["prune-media"],
609
+ createOnly: upload.media.createOnly
610
+ });
611
+ }
612
+ const uploads = [...bundle, ...workerBytes ? [{
310
613
  path: WORKER_BUNDLE_PATH,
311
614
  data: workerBytes
312
615
  }] : []];
@@ -335,6 +638,15 @@ const deployCommand = defineCommand({
335
638
  console.log(` happy with it? \`canopy promote\` makes v${result.version} live`);
336
639
  } else spin.stop(`Live: ${projectUrl(currentSlug(slug))} (v${result.version})${backend}`);
337
640
  if (migrateResult !== void 0) for (const line of describeMigrateResult(migrateResult)) console.log(` ${line}`);
641
+ for (const line of mediaReport) console.log(line);
642
+ const hint = mediaHint(candidates, {
643
+ bytes: bundleBytes,
644
+ files: bundle.length
645
+ }, {
646
+ maxTotalBytes: limitsSeen.maxTotalBytes,
647
+ maxFiles: limitsSeen.maxFiles
648
+ }, mediaFolders);
649
+ if (hint) console.log(`\n${hint}`);
338
650
  if (retentionHint) console.log(`\n${retentionHint}`);
339
651
  })
340
652
  });
@@ -406,11 +718,11 @@ const UPLOAD_CONCURRENCY = 8;
406
718
  * that states no limits isn't checked here; completion still enforces them.
407
719
  */
408
720
  function bundleLimitError(files, limits) {
409
- if (limits.maxFiles !== void 0 && files.length > limits.maxFiles) return `This deploy has ${files.length} files; the limit is ${limits.maxFiles}. Bundle/minify assets or drop what isn't served, then redeploy.`;
721
+ if (limits.maxFiles !== void 0 && files.length > limits.maxFiles) return `This deploy has ${files.length} files; the limit is ${limits.maxFiles}.`;
410
722
  const bytes = files.reduce((sum, f) => sum + f.data.byteLength, 0);
411
723
  if (limits.maxTotalBytes !== void 0 && bytes > limits.maxTotalBytes) {
412
724
  const mb = (n) => `${(n / 1024 / 1024).toFixed(1)} MB`;
413
- return `This deploy is ${mb(bytes)}; the limit is ${mb(limits.maxTotalBytes)}. Move large images or fonts to file storage, then redeploy.`;
725
+ return `This deploy is ${mb(bytes)}; the limit is ${mb(limits.maxTotalBytes)}.`;
414
726
  }
415
727
  return null;
416
728
  }
@@ -451,17 +763,36 @@ function skipMessage(code, slug) {
451
763
  const host = server ? new URL(server).host : void 0;
452
764
  return `"${slug}" is not linked to this repository, so this run deployed nothing. The project owner can link it with \`canopy repo link ${repo ? `${host && host !== "github.com" ? `${host}/` : ""}${repo}` : "<owner/name>"}\`, or set a CANOPY_DEPLOY_TOKEN secret.`;
453
765
  }
766
+ const PUT_ATTEMPTS = 3;
767
+ /**
768
+ * One upload PUT, tried again when the connection drops. Node's fetch speaks
769
+ * HTTP/2 to the edge, and with several uploads in flight a stream is now and
770
+ * then reset (ERR_HTTP2_STREAM_ERROR) on a different file each time. An HTTP
771
+ * answer, refusal or not, is returned as is: only network failures retry.
772
+ * Re-sending is safe: an upload replaces the same key with the same bytes.
773
+ */
774
+ async function putWithRetry(url, headers, data, what) {
775
+ for (let attempt = 1;; attempt++) try {
776
+ return await fetch(url, {
777
+ method: "PUT",
778
+ headers,
779
+ body: Buffer.from(data)
780
+ });
781
+ } catch (err) {
782
+ if (attempt >= PUT_ATTEMPTS) {
783
+ const cause = err.cause;
784
+ throw new Error(`${what} failed after ${PUT_ATTEMPTS} tries: ${cause?.code ?? cause?.message ?? err.message}.`);
785
+ }
786
+ await new Promise((resolve) => setTimeout(resolve, 500 * attempt));
787
+ }
788
+ }
454
789
  /** PUT each file to /data/v1/uploads/<grant> — the grant is the credential. */
455
790
  async function uploadFiles(grant, files) {
456
791
  const { apiUrl } = siteConfig();
457
792
  const queue = [...files];
458
793
  async function worker() {
459
794
  for (let file = queue.shift(); file; file = queue.shift()) {
460
- const url = `${apiUrl}/data/v1/uploads/${encodeURIComponent(grant)}?path=${encodeURIComponent(file.path)}`;
461
- const res = await fetch(url, {
462
- method: "PUT",
463
- body: Buffer.from(file.data)
464
- });
795
+ const res = await putWithRetry(`${apiUrl}/data/v1/uploads/${encodeURIComponent(grant)}?path=${encodeURIComponent(file.path)}`, {}, file.data, `Upload of ${file.path}`);
465
796
  if (!res.ok) {
466
797
  const payload = await res.json().catch(() => ({}));
467
798
  throw new Error(`Upload of ${file.path} failed (HTTP ${res.status}${payload.error ? `, ${payload.error}` : ""}).`);
@@ -470,6 +801,40 @@ async function uploadFiles(grant, files) {
470
801
  }
471
802
  await Promise.all(Array.from({ length: UPLOAD_CONCURRENCY }, worker));
472
803
  }
804
+ /** The project's stored media, under the deploy's grant. */
805
+ async function mediaManifest(grant) {
806
+ const { apiUrl } = siteConfig();
807
+ const res = await fetch(`${apiUrl}/data/v1/media/${encodeURIComponent(grant)}/manifest`);
808
+ if (!res.ok) throw new Error(`Reading the site media manifest failed (HTTP ${res.status}).`);
809
+ return await res.json();
810
+ }
811
+ /** PUT each new or changed media file with its hash; the store refuses a mismatch. */
812
+ async function uploadMedia(grant, files) {
813
+ const { apiUrl } = siteConfig();
814
+ const queue = [...files];
815
+ async function worker() {
816
+ for (let file = queue.shift(); file; file = queue.shift()) {
817
+ const res = await putWithRetry(`${apiUrl}/data/v1/media/${encodeURIComponent(grant)}?path=${encodeURIComponent(file.path)}`, { "x-canopy-sha256": file.sha256 }, file.data, `Site media upload of ${file.path} (${formatSize(file.data.byteLength)})`);
818
+ if (!res.ok) {
819
+ const payload = await res.json().catch(() => ({}));
820
+ throw new Error(`Site media upload of ${file.path} failed (HTTP ${res.status}${payload.error ? `, ${payload.error}` : ""})${payload.detail ? `: ${payload.detail}` : "."}`);
821
+ }
822
+ }
823
+ }
824
+ await Promise.all(Array.from({ length: UPLOAD_CONCURRENCY }, worker));
825
+ }
826
+ /** --prune-media: delete stored media that's gone from the build, 1000 per call. */
827
+ async function deleteMedia(grant, paths) {
828
+ const { apiUrl } = siteConfig();
829
+ for (let i = 0; i < paths.length; i += 1e3) {
830
+ const res = await fetch(`${apiUrl}/data/v1/media/${encodeURIComponent(grant)}/delete`, {
831
+ method: "POST",
832
+ headers: { "content-type": "application/json" },
833
+ body: JSON.stringify({ paths: paths.slice(i, i + 1e3) })
834
+ });
835
+ if (!res.ok) throw new Error(`Pruning site media failed (HTTP ${res.status}).`);
836
+ }
837
+ }
473
838
  /** Show the deploy history and ask which version to act on. */
474
839
  async function pickVersion(deploys, live, message, initial) {
475
840
  return unwrap(await p.select({
@@ -20,6 +20,7 @@ canopy deploy --project my-app ./out
20
20
  - `--build` / `--no-build` — run the `canopy.json` build command first (default on). Use `--no-build` when the output is already built, e.g. a CI step that built earlier.
21
21
  - `--migrate` / `--no-migrate` — apply pending schema migrations before the new version goes live (default on; only does anything when `canopy.json` configures a `"migrations"` directory — see the [migrations guide](https://docs.canopy.website/guides/migrations)).
22
22
  - `--staging` — deploy to the project's [staging channel](https://docs.canopy.website/guides/staging) instead of live: created on first use with a copy of the live database, served at `staging-dot-<slug>`, promoted with [canopy promote](https://docs.canopy.website/cli/promote). Pending migrations apply to the _staging_ database (the rehearsal). Not to be confused with `--profile staging`, which picks a whole different site.
23
+ - `--prune-media` — delete stored [site media](https://docs.canopy.website/guides/static-serving#site-media) files that are no longer in the build, including folders you took out of `canopy.json`. Without it, site media only grows. The CLI prints how many it removed and which.
23
24
  - `--profile <site>` / `CANOPY_PROFILE` — which site to deploy to (`main`, `staging`, …). Always pass it explicitly when the target matters; a `canopy.json` profile pin is the fallback.
24
25
 
25
26
  ## How it works
@@ -27,12 +28,28 @@ canopy deploy --project my-app ./out
27
28
  1. **Build.** If `canopy.json` has a `build` command and you didn't pass `--no-build`, it runs in the project directory with your shell; a non-zero exit aborts the deploy.
28
29
  2. **Collect files.** Everything under the `dist` directory from `canopy.json` (default: the project directory itself) is gathered, skipping `canopy.json`, `README.md`, `AGENTS.md`, `CLAUDE.md`, `.gitignore`, `.DS_Store`, and any dot-directories plus `.git`, `node_modules`, and `.claude`. An empty or missing output directory is an error.
29
30
  3. **Bundle the backend (if any).** When `canopy.json` names a `worker` entry, that backend code is bundled into a single file (dependencies included) and ships in the same version as the static files — frontend and backend always move together.
30
- 4. **Upload.** The files upload in parallel; the new version is staged alongside the old one, so the live site keeps serving until everything has arrived.
31
- 5. **Migrate (if configured).** With a `"migrations"` directory in `canopy.json`, pending schema migrations apply now — after the bundle is staged, before the version flips — so the incoming code never runs against the old schema. The platform stores an automatic pre-migrate snapshot first. If a migration fails, the deploy aborts and the live version is unchanged; the error names the snapshot to restore if needed.
32
- 6. **Go live.** The platform validates the staged version and switches the site over to it in one step. The upload must contain an `index.html` at the top level — the deploy is rejected otherwise — so double-check `dist` points at the folder that actually holds `index.html`. On success the CLI prints the live URL and version number (plus the backend service URL for worker projects).
31
+ 4. **Site media (if declared).** Folders listed in `canopy.json` `"media"` don't go into the version. The CLI compares them with what the project already stores and uploads only new and changed files; unchanged ones cost nothing. They are live as soon as they are uploaded. One line reports what happened, e.g. `media: 3 uploaded, 3,255 unchanged, 175 MB stored`.
32
+ 5. **Upload.** The files upload in parallel; the new version is staged alongside the old one, so the live site keeps serving until everything has arrived.
33
+ 6. **Migrate (if configured).** With a `"migrations"` directory in `canopy.json`, pending schema migrations apply now — after the bundle is staged, before the version flips — so the incoming code never runs against the old schema. The platform stores an automatic pre-migrate snapshot first. If a migration fails, the deploy aborts and the live version is unchanged; the error names the snapshot to restore if needed.
34
+ 7. **Go live.** The platform validates the staged version and switches the site over to it in one step. The upload must contain an `index.html` at the top level — the deploy is rejected otherwise — so double-check `dist` points at the folder that actually holds `index.html`. On success the CLI prints the live URL and version number (plus the backend service URL for worker projects).
33
35
 
34
36
  Deploys are versioned and immutable: nothing overwrites an old version, so [canopy rollback](https://docs.canopy.website/cli/rollback) can always take you back.
35
37
 
38
+ ## Site media
39
+
40
+ A folder of large data or media that rarely changes, such as Storybook mock data or demo video, can be stored once per project instead of in every version:
41
+
42
+ ```json
43
+ {
44
+ "dist": "storybook-static",
45
+ "media": ["mocks/", "demo-assets/"]
46
+ }
47
+ ```
48
+
49
+ The folders are paths inside the build output. Their files keep their URLs (`/mocks/users.json`), and don't count toward the deploy limit. They may hold data and media only: JSON, CSV, text, images, video, audio, fonts and 3D models. A folder with HTML, JavaScript, CSS or SVG in it is refused before anything uploads. **Media is not versioned:** a rollback or a pinned version serves the current files, and it is shared with the staging channel.
50
+
51
+ The CLI suggests folders for you. When the version reaches 30% of the deploy limit, the deploy ends with a hint naming the folders that could move and the exact `"media"` line to add. When it is over the limit, the refusal names the folders that would bring it under. The CLI never edits `canopy.json` itself. See [Site media](https://docs.canopy.website/guides/static-serving#site-media) for limits and details.
52
+
36
53
  **CI.** In GitHub Actions, `canopy deploy` needs no secret and no `canopy login`: with `permissions: id-token: write` in the workflow, it proves which repository and branch the run comes from and deploys a project [linked](https://docs.canopy.website/cli/repo) to that repository. A run on the project's staging branch deploys to staging without `--staging`. An unlinked project, or one whose CI deploys are off, skips the deploy with a warning instead of failing. Elsewhere, set `CANOPY_DEPLOY_TOKEN` to a project-scoped deploy token (from [canopy token create](https://docs.canopy.website/cli/token)); it wins over the linked repository when both are there. Deploys from GitHub Actions are tagged with their source in the deploy history. See [CI deploys](https://docs.canopy.website/guides/ci).
37
54
 
38
55
  ## Examples
@@ -54,6 +54,9 @@ You can also "roll forward": after reverting to v3, making v5 live again is
54
54
  the same one-step operation. Any version in the history can be live, as long
55
55
  as it hasn't expired (see below).
56
56
 
57
+ Folders you declared as [site media](https://docs.canopy.website/guides/static-serving#site-media) are
58
+ not part of a version: a rollback keeps serving the current media files.
59
+
57
60
  ## Version retention
58
61
 
59
62
  Old versions take up storage, and after a while nobody rolls back to them.
@@ -43,6 +43,13 @@ One file can be up to 200 MB on `main` and `staging` (100 MB when a browser
43
43
  uploads it) and up to 25 MB on `gcp-pilot`. See
44
44
  [how big a file can be](https://docs.canopy.website/sdk/files#how-big-a-file-can-be).
45
45
 
46
+ ## Site media on the Files tab
47
+
48
+ The Files tab also shows a project's [site media](https://docs.canopy.website/guides/static-serving#site-media)
49
+ when it has any: how much it stores against its limit, how many files, and
50
+ which folders the live version serves from it. Site media isn't file storage.
51
+ Your app's code can't list or change it; only `canopy deploy` writes it.
52
+
46
53
  ## Snapshots and restores
47
54
 
48
55
  The Data tab's **Data safety** card is your undo button for data:
@@ -75,8 +75,40 @@ without deploying anything.
75
75
 
76
76
  `canopy deploy` checks both limits before it uploads anything. If you're over
77
77
  the file count, it's almost always un-bundled assets that a build
78
- step would combine; over the size limit, it's usually images or fonts that
79
- belong in [file storage](https://docs.canopy.website/sdk/files) instead of the bundle.
78
+ step would combine. Over the size limit, it's usually data or media that
79
+ belongs in [site media](#site-media) instead of every version.
80
+
81
+ ## Site media
82
+
83
+ Some sites carry a lot of data or media that rarely changes, such as Storybook
84
+ mock data, demo images and video. Copying that into every version makes every
85
+ deploy slow and heavy. Name those folders in `canopy.json`, and Canopy stores
86
+ them once for the whole project:
87
+
88
+ ```json
89
+ { "dist": "storybook-static", "media": ["mocks/", "demo-assets/"] }
90
+ ```
91
+
92
+ - **Same URLs.** `/mocks/users.json` stays `/mocks/users.json`. Your app and
93
+ `canopy dev` need no changes.
94
+ - **Only changes upload.** Each deploy sends new and changed files only.
95
+ - **Not versioned.** Rolling back, or opening a pinned version, serves the
96
+ current files. The staging channel shares them with live. A changed file goes
97
+ live as soon as it's uploaded, before the rest of the deploy.
98
+ - **Data, not code.** JSON, CSV, text, images, video, audio, fonts and 3D
99
+ models. HTML, JavaScript, CSS and SVG must stay in the version.
100
+ - **Adds up, until you prune.** A file you delete locally stays stored until
101
+ you deploy with `canopy deploy --prune-media`.
102
+ - **Limits.** 1 GB and 10,000 files per project, and per file the same limit
103
+ as [file storage](https://docs.canopy.website/sdk/files). A Canopy admin can raise the total.
104
+ - **Video plays.** Byte ranges are served, so video seeks and plays in every
105
+ browser, from site media or from the version itself.
106
+ - A path in a media folder that isn't stored answers 404, never your
107
+ `index.html`.
108
+
109
+ `canopy deploy` suggests folders when a version grows past 30% of the limit.
110
+ See [canopy deploy](https://docs.canopy.website/cli/deploy#site-media). The Files tab in the dashboard
111
+ shows how much site media a project holds.
80
112
 
81
113
  ## What this rules out
82
114
 
@@ -1,4 +1,4 @@
1
- import { t as version } from "./package-BpOFa8Qi.mjs";
1
+ import { t as version } from "./package-BzvVsyRl.mjs";
2
2
  import { r as siteConfig } from "./site-BcZ0LOvm.mjs";
3
3
  import { i as latestKnownVersion, r as compareSemver } from "./version-check-CcsA1QjI.mjs";
4
4
  import { n as agentHeaders } from "./api-fmc8CEMT.mjs";
@@ -1,4 +1,4 @@
1
- import { t as version } from "./package-BpOFa8Qi.mjs";
1
+ import { t as version } from "./package-BzvVsyRl.mjs";
2
2
  import { f as resolveProject, g as tryResolveProject, h as tryReadCanopyJson, l as projectDirArgs, r as siteConfig } from "./site-BcZ0LOvm.mjs";
3
3
  import { a as apiRequest, c as credentials, i as apiDownload, o as apiUpload, s as commonHeaders } from "./api-fmc8CEMT.mjs";
4
4
  import { i as reportErrors, n as formatDateTime } from "./ui-9f_lF2Ak.mjs";
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as version } from "./package-BpOFa8Qi.mjs";
2
+ import { t as version } from "./package-BzvVsyRl.mjs";
3
3
  import { i as siteHeaderLine, n as setInvocationProfile } from "./site-BcZ0LOvm.mjs";
4
4
  import { a as notifyOfUpdate, o as runRefresh } from "./version-check-CcsA1QjI.mjs";
5
5
  import { defineCommand, runMain } from "citty";
@@ -60,11 +60,11 @@ const main = defineCommand({
60
60
  delete: () => import("./projects-DOqpkUVT.mjs").then((m) => m.deleteCommand),
61
61
  rename: () => import("./rename-RA_oYbRT.mjs").then((m) => m.renameCommand),
62
62
  dev: () => import("./dev-BtacZ4HE.mjs").then((m) => m.devCommand),
63
- deploy: () => import("./deploy-7tgGJZUK.mjs").then((m) => m.deployCommand),
64
- promote: () => import("./deploy-7tgGJZUK.mjs").then((m) => m.promoteCommand),
63
+ deploy: () => import("./deploy-k2DzsLxO.mjs").then((m) => m.deployCommand),
64
+ promote: () => import("./deploy-k2DzsLxO.mjs").then((m) => m.promoteCommand),
65
65
  staging: () => import("./staging-BxG3Cffd.mjs").then((m) => m.stagingCommand),
66
- rollback: () => import("./deploy-7tgGJZUK.mjs").then((m) => m.rollbackCommand),
67
- download: () => import("./deploy-7tgGJZUK.mjs").then((m) => m.downloadCommand),
66
+ rollback: () => import("./deploy-k2DzsLxO.mjs").then((m) => m.rollbackCommand),
67
+ download: () => import("./deploy-k2DzsLxO.mjs").then((m) => m.downloadCommand),
68
68
  versions: () => import("./versions-Cgw7sB3h.mjs").then((m) => m.versionsCommand),
69
69
  token: () => import("./token-bHdy_IoX.mjs").then((m) => m.tokenCommand),
70
70
  egress: () => import("./egress-Bzn2VKDe.mjs").then((m) => m.egressCommand),
@@ -73,18 +73,18 @@ const main = defineCommand({
73
73
  roles: () => import("./roles-tqf4sYDM.mjs").then((m) => m.rolesCommand),
74
74
  members: () => import("./roles-tqf4sYDM.mjs").then((m) => m.membersCommand),
75
75
  schedule: () => import("./schedule-D8AQ8MVF.mjs").then((m) => m.scheduleCommand),
76
- feedback: () => import("./feedback-COujxFBV.mjs").then((m) => m.feedbackCommand),
76
+ feedback: () => import("./feedback-B0-6QTSh.mjs").then((m) => m.feedbackCommand),
77
77
  db: () => import("./db-BU-ni9fj.mjs").then((m) => m.dbCommand),
78
78
  files: () => import("./files-CBbAtHIK.mjs").then((m) => m.filesCommand),
79
79
  usage: () => import("./usage-DFs2TERV.mjs").then((m) => m.usageCommand),
80
80
  ai: () => import("./ai-00f2Mgqh.mjs").then((m) => m.aiCommand),
81
81
  open: () => import("./open-Doat726T.mjs").then((m) => m.openCommand),
82
82
  browse: () => import("./browse-CxwKuka0.mjs").then((m) => m.browseCommand),
83
- docs: () => import("./docs-hcHwEc6n.mjs").then((m) => m.docsCommand),
84
- skill: () => import("./skill-984KseKb.mjs").then((m) => m.skillCommand),
85
- upgrade: () => import("./upgrade-DhK_PlAN.mjs").then((m) => m.upgradeCommand),
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
86
  logs: () => import("./logs-c76jVOhb.mjs").then((m) => m.logsCommand),
87
- mcp: () => import("./mcp-aWskwkXw.mjs").then((m) => m.mcpCommand),
87
+ mcp: () => import("./mcp-DmcjX8Kn.mjs").then((m) => m.mcpCommand),
88
88
  repo: () => import("./repo-DayXVvyj.mjs").then((m) => m.repoCommand),
89
89
  template: () => import("./project-template--mESzwea.mjs").then((m) => m.templateCommand),
90
90
  audience: () => import("./audience-ByM1jUH3.mjs").then((m) => m.audienceCommand)
@@ -1,4 +1,4 @@
1
- import { t as version } from "./package-BpOFa8Qi.mjs";
1
+ import { t as version } from "./package-BzvVsyRl.mjs";
2
2
  import { d as projectUrl, g as tryResolveProject, m as stagingUrl, r as siteConfig } from "./site-BcZ0LOvm.mjs";
3
3
  import { a as apiRequest, f as noticeRenamesOnly, l as currentSlug, t as ApiError } from "./api-fmc8CEMT.mjs";
4
4
  import { t as liveDevServer } from "./dev-server-file-Dk9pk4AR.mjs";
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.7.57";
2
+ var version = "0.7.58";
3
3
  //#endregion
4
4
  export { version as t };
@@ -221,6 +221,9 @@ Non-interactive: `canopy create "My App" --template spa`. **When unsure between
221
221
  restores.
222
222
  - **Deploys are public.** `canopy deploy` makes a version live. Confirm before
223
223
  deploying unless the user clearly asked you to.
224
+ - **Site media isn't versioned.** When a deploy suggests moving a folder to
225
+ `canopy.json` `"media"`, do it only for data or media that rarely changes,
226
+ or when the user agrees: a rollback keeps serving the current media.
224
227
  - **Version retention deletes old versions.** When a deploy prints a retention
225
228
  hint, pass it on to the user and ask before running
226
229
  `canopy versions retention on`: expired versions can no longer be rolled
@@ -1,4 +1,4 @@
1
- import { t as version } from "./package-BpOFa8Qi.mjs";
1
+ import { t as version } from "./package-BzvVsyRl.mjs";
2
2
  import { i as reportErrors } from "./ui-9f_lF2Ak.mjs";
3
3
  import { defineCommand } from "citty";
4
4
  import { cpSync, existsSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
@@ -112,7 +112,7 @@ const upgradeCommand = defineCommand({
112
112
  const spec = `${PACKAGE_NAME}@${args.version ?? "latest"}`;
113
113
  const command = pmCommand(pm);
114
114
  const cmd = installArgs(pm, spec);
115
- const { skillInstalled } = await import("./skill-984KseKb.mjs");
115
+ const { skillInstalled } = await import("./skill-k3HLr7rK.mjs");
116
116
  const { homedir } = await import("node:os");
117
117
  const refreshGlobal = skillInstalled(homedir());
118
118
  const refreshRepo = process.cwd() !== homedir() && skillInstalled(process.cwd());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mediamonks/canopy-cli",
3
- "version": "0.7.57",
3
+ "version": "0.7.58",
4
4
  "description": "Canopy CLI — create, develop and deploy Canopy projects.",
5
5
  "bin": {
6
6
  "canopy": "./dist/index.mjs"