@mainsoft/agent-cms 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +91 -2
  3. package/TODO.md +6 -6
  4. package/UPGRADE-0.11.md +43 -0
  5. package/dist/agent.d.cts +1 -1
  6. package/dist/agent.d.ts +1 -1
  7. package/dist/agent.js +7 -7
  8. package/dist/bin.js +236 -23
  9. package/dist/{chunk-IU2SMWAM.js → chunk-42PW3HQ3.js} +15 -1
  10. package/dist/{chunk-6PB4ZCHH.js → chunk-CIMW73L3.js} +58 -1
  11. package/dist/{chunk-7Y6TU2UA.js → chunk-HY4ED7LT.js} +2 -2
  12. package/dist/{chunk-DSJETZT4.js → chunk-I3DF6DMI.js} +15 -10
  13. package/dist/{chunk-KAO3Z3CF.js → chunk-I5UHTAAW.js} +3 -1
  14. package/dist/{chunk-7SCYDG2G.js → chunk-J25IKU7C.js} +164 -28
  15. package/dist/{chunk-BFVBHIHV.js → chunk-J5DW3RFQ.js} +4 -1
  16. package/dist/{chunk-7WJIIJCI.js → chunk-LELPCGDX.js} +8 -5
  17. package/dist/{chunk-5ODZ2ZJF.js → chunk-NO6S7KOL.js} +1 -1
  18. package/dist/{chunk-5FMVVBDR.js → chunk-OLHLSSTD.js} +3 -3
  19. package/dist/{chunk-3OPKTBEI.js → chunk-SV3ZA6XP.js} +1 -1
  20. package/dist/{chunk-PEQY4N73.js → chunk-TKKTEGHL.js} +1 -0
  21. package/dist/{chunk-PGV2QPIL.js → chunk-WWG7XDIZ.js} +2 -0
  22. package/dist/cli.cjs +236 -23
  23. package/dist/cli.d.cts +2 -2
  24. package/dist/cli.d.ts +2 -2
  25. package/dist/cli.js +18 -16
  26. package/dist/client.cjs +4 -1
  27. package/dist/client.d.cts +14 -2
  28. package/dist/client.d.ts +14 -2
  29. package/dist/client.js +1 -1
  30. package/dist/{cms-pqJyowu1.d.ts → cms-A9tmLmTP.d.ts} +100 -5
  31. package/dist/{cms-C_vkAxYV.d.cts → cms-CaB81PPX.d.cts} +100 -5
  32. package/dist/config.d.cts +1 -1
  33. package/dist/config.d.ts +1 -1
  34. package/dist/{drizzle-repo-DWLD0rWe.d.ts → drizzle-repo-BXV-hFkE.d.ts} +1 -1
  35. package/dist/{drizzle-repo-CviH3EX7.d.cts → drizzle-repo-CblPVYnK.d.cts} +1 -1
  36. package/dist/errors.cjs +4 -0
  37. package/dist/errors.d.cts +3 -1
  38. package/dist/errors.d.ts +3 -1
  39. package/dist/errors.js +2 -2
  40. package/dist/frontmatter.d.cts +1 -1
  41. package/dist/frontmatter.d.ts +1 -1
  42. package/dist/http.cjs +17 -7
  43. package/dist/http.d.cts +2 -2
  44. package/dist/http.d.ts +2 -2
  45. package/dist/http.js +16 -15
  46. package/dist/image-sharp.cjs +104 -0
  47. package/dist/image-sharp.d.cts +47 -0
  48. package/dist/image-sharp.d.ts +47 -0
  49. package/dist/image-sharp.js +70 -0
  50. package/dist/index.cjs +244 -27
  51. package/dist/index.d.cts +3 -3
  52. package/dist/index.d.ts +3 -3
  53. package/dist/index.js +21 -21
  54. package/dist/mcp.cjs +9 -4
  55. package/dist/mcp.d.cts +1 -1
  56. package/dist/mcp.d.ts +1 -1
  57. package/dist/mcp.js +11 -11
  58. package/dist/messages/en.cjs +2 -0
  59. package/dist/messages/en.js +1 -1
  60. package/dist/messages/ko.cjs +2 -0
  61. package/dist/messages/ko.js +2 -0
  62. package/dist/registry/cms-doc-editor.json +6 -1
  63. package/dist/registry/cms-lib.json +2 -2
  64. package/dist/registry/cms-media-picker.json +2 -2
  65. package/dist/registry/cms-media.json +1 -1
  66. package/dist/registry/registry.json +4 -0
  67. package/dist/storage-vercel-blob.cjs +199 -0
  68. package/dist/storage-vercel-blob.d.cts +98 -0
  69. package/dist/storage-vercel-blob.d.ts +98 -0
  70. package/dist/storage-vercel-blob.js +165 -0
  71. package/dist/storage.cjs +63 -3
  72. package/dist/storage.d.cts +27 -2
  73. package/dist/storage.d.ts +27 -2
  74. package/dist/storage.js +9 -3
  75. package/dist/tables.cjs +15 -1
  76. package/dist/tables.d.cts +160 -7
  77. package/dist/tables.d.ts +160 -7
  78. package/dist/tables.js +2 -2
  79. package/dist/tools.cjs +8 -3
  80. package/dist/tools.d.cts +1 -1
  81. package/dist/tools.d.ts +1 -1
  82. package/dist/tools.js +9 -9
  83. package/dist/types.cjs +5 -0
  84. package/dist/types.d.cts +6 -1
  85. package/dist/types.d.ts +6 -1
  86. package/dist/types.js +3 -3
  87. package/package.json +36 -2
package/dist/cli.cjs CHANGED
@@ -492,6 +492,60 @@ var DEFAULT_MAX_FILE_SIZE = 5 * 1024 ** 3;
492
492
  var PART_SIZE = 16 * 1024 * 1024;
493
493
  var THUMB_PREFIX = "_cms/thumbs/";
494
494
  var RESERVED_FOLDER = "_cms";
495
+ var DERIVED_PREFIX = "_cms/derived/";
496
+ var REPLACE_PREFIX = "_cms/replace/";
497
+ function stripJpegMetadata(b) {
498
+ if (b.length < 4 || b[0] !== 255 || b[1] !== 216) return b;
499
+ const keep = [];
500
+ let orientation = 1;
501
+ let dropped = false;
502
+ let i = 2;
503
+ while (i + 4 <= b.length && b[i] === 255) {
504
+ const m = b[i + 1];
505
+ if (m === 218 || m === 217) break;
506
+ if (m === 255) {
507
+ i++;
508
+ continue;
509
+ }
510
+ if (m >= 208 && m <= 215 || m === 1) {
511
+ keep.push([i, i + 2]);
512
+ i += 2;
513
+ continue;
514
+ }
515
+ const end = i + 2 + (b[i + 2] << 8 | b[i + 3]);
516
+ if (end < i + 4 || end > b.length) return b;
517
+ if (m === 225 || m === 237 || m === 254) {
518
+ dropped = true;
519
+ if (m === 225 && end - i >= 18 && b[i + 4] === 69 && b[i + 5] === 120 && b[i + 6] === 105 && b[i + 7] === 102) orientation = exifOrientation(b.subarray(i + 10, end)) ?? orientation;
520
+ } else keep.push([i, end]);
521
+ i = end;
522
+ }
523
+ if (!dropped) return b;
524
+ const turn = orientation >= 2 && orientation <= 8 ? Uint8Array.of(255, 225, 0, 34, 69, 120, 105, 102, 0, 0, 77, 77, 0, 42, 0, 0, 0, 8, 0, 1, 1, 18, 0, 3, 0, 0, 0, 1, 0, orientation, 0, 0, 0, 0, 0, 0) : new Uint8Array();
525
+ const out = new Uint8Array(2 + turn.length + keep.reduce((n, [a, z2]) => n + z2 - a, 0) + b.length - i);
526
+ out.set(b.subarray(0, 2));
527
+ out.set(turn, 2);
528
+ let at = 2 + turn.length;
529
+ for (const [a, z2] of keep) {
530
+ out.set(b.subarray(a, z2), at);
531
+ at += z2 - a;
532
+ }
533
+ out.set(b.subarray(i), at);
534
+ return out;
535
+ }
536
+ function exifOrientation(t) {
537
+ if (t.length < 14) return null;
538
+ const le = t[0] === 73;
539
+ const u16 = (o) => le ? t[o] | t[o + 1] << 8 : t[o] << 8 | t[o + 1];
540
+ const ifd = le ? t[4] | t[5] << 8 | t[6] << 16 | t[7] << 24 : (t[4] << 24 | t[5] << 16 | t[6] << 8 | t[7]) >>> 0;
541
+ if (ifd < 8 || ifd + 2 > t.length) return null;
542
+ const n = u16(ifd);
543
+ for (let k = 0; k < n && ifd + 2 + (k + 1) * 12 <= t.length; k++) {
544
+ const e = ifd + 2 + k * 12;
545
+ if (u16(e) === 274) return u16(e + 8);
546
+ }
547
+ return null;
548
+ }
495
549
  var extOf = (name) => {
496
550
  const m = /\.([a-z0-9]{1,10})$/i.exec(name);
497
551
  return m ? m[1].toLowerCase() : "";
@@ -632,6 +686,16 @@ var ASSET_ID_RE = /^[a-z0-9]{12}$/;
632
686
  var SIGN_SECONDS = 3600;
633
687
  var MAX_THUMB_BYTES = 512 * 1024;
634
688
  var TAG_MAX = 30;
689
+ var IMAGE_EXT = { webp: "webp", avif: "avif", jpeg: "jpg", png: "png" };
690
+ var FOREVER = "public, max-age=31536000, immutable";
691
+ function stamp(v) {
692
+ let h = 2166136261;
693
+ for (const c of JSON.stringify(v)) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
694
+ return (h >>> 0).toString(36);
695
+ }
696
+ var withRev = (url, rev) => rev > 0 ? `${url}${url.includes("?") ? "&" : "?"}v=${rev}` : url;
697
+ var focalOf = (a) => a.focalX !== null && a.focalY !== null ? { x: a.focalX, y: a.focalY } : null;
698
+ var resizable = (a) => a.kind === "image" && a.mime !== "image/svg+xml" && a.mime !== "image/gif";
635
699
  function humanSize(bytes) {
636
700
  const units = ["B", "KB", "MB", "GB", "TB"];
637
701
  let n = bytes;
@@ -652,6 +716,7 @@ function createAssets(ctx) {
652
716
  const names2 = Object.keys(media?.stores ?? {});
653
717
  const filesUrl = (media?.filesUrl ?? "/api/cms/files").replace(/\/+$/, "");
654
718
  const ttl = media?.linkTtlSeconds ?? 300;
719
+ const transforms = media?.transforms ?? null;
655
720
  for (const n of names2) {
656
721
  const s = media.stores[n];
657
722
  const rules = s.accept ?? media.accept ?? DEFAULT_ACCEPT;
@@ -684,11 +749,12 @@ function createAssets(ctx) {
684
749
  function view(a) {
685
750
  const cfg = media?.stores[a.store];
686
751
  const href = `${filesUrl}/${a.id}/${encodeURIComponent(a.name)}`;
687
- return { ...a, visibility: cfg?.visibility ?? "private", href, publicUrl: cfg?.visibility === "public" ? cfg.adapter.publicUrl(a.key) : null, thumbHref: a.thumbKey ? `${href}?thumb=1` : null };
752
+ const direct = cfg?.visibility === "public" ? cfg.adapter.publicUrl(a.key) : null;
753
+ return { ...a, visibility: cfg?.visibility ?? "private", href, publicUrl: direct ? withRev(direct, a.rev) : null, thumbHref: a.thumbKey ? `${href}?thumb=1${a.rev ? `&v=${a.rev}` : ""}` : null };
688
754
  }
689
755
  const info = (a) => {
690
756
  const v = view(a);
691
- return { id: a.id, name: a.name, kind: a.kind, mime: a.mime, size: a.size, width: a.width, height: a.height, duration: a.duration, alt: a.alt, url: v.publicUrl ?? v.href, visibility: v.visibility };
757
+ return { id: a.id, name: a.name, kind: a.kind, mime: a.mime, size: a.size, width: a.width, height: a.height, duration: a.duration, alt: a.alt, url: v.publicUrl ?? v.href, visibility: v.visibility, focal: focalOf(a) };
692
758
  };
693
759
  async function load(id, o = {}) {
694
760
  const a = ASSET_ID_RE.test(id) ? await repo.findAsset(id) : null;
@@ -731,23 +797,25 @@ function createAssets(ctx) {
731
797
  }
732
798
  async function requestUpload(actor, input) {
733
799
  await ctx.ready();
734
- const store = storeOf(input.store);
800
+ const target = input.replace ? await replaceable(actor, input.replace, input) : null;
801
+ const store = storeOf(target ? target.store : input.store);
735
802
  need(actor, store.name, "write");
736
- const a = admit(store, input);
737
- const free = await freeKey(store, a.folder, a.name);
803
+ const a = target ? admit(store, { name: target.name, mime: target.mime, size: input.size, folder: target.folder }) : admit(store, input);
804
+ const id = newAssetId();
805
+ const free = target ? { key: `${REPLACE_PREFIX}${target.id}/${id}${extOf(target.name) ? `.${extOf(target.name)}` : ""}`, name: target.name } : await freeKey(store, a.folder, a.name);
738
806
  const put2 = { mime: a.mime, disposition: dispositionFor(free.name, a.mime) };
739
807
  const who = ctx.actorRef(actor);
740
808
  let upload;
741
809
  let uploadId = null;
742
- if (input.size <= PART_SIZE) {
743
- const signed = await store.cfg.adapter.presignPut(free.key, { ...put2, expires: SIGN_SECONDS });
810
+ if (input.size <= PART_SIZE || store.cfg.adapter.multipart === false) {
811
+ const signed = await store.cfg.adapter.presignPut(free.key, { ...put2, expires: SIGN_SECONDS, size: input.size });
744
812
  upload = { kind: "single", url: signed.url, headers: signed.headers };
745
813
  } else {
746
814
  uploadId = await store.cfg.adapter.createMultipart(free.key, put2);
747
815
  upload = { kind: "multipart", partSize: PART_SIZE, partCount: Math.ceil(input.size / PART_SIZE) };
748
816
  }
749
817
  const row = await repo.insertAsset({
750
- id: newAssetId(),
818
+ id,
751
819
  store: store.name,
752
820
  key: free.key,
753
821
  folder: a.folder,
@@ -795,9 +863,107 @@ function createAssets(ctx) {
795
863
  });
796
864
  if (a.thumbKey) await adapter.delete(a.thumbKey).catch(() => {
797
865
  });
866
+ await dropDerived(a);
798
867
  }
799
868
  await repo.deleteAsset(a.id);
800
869
  }
870
+ async function replaceable(actor, id, input) {
871
+ const t = await load(id);
872
+ need(actor, t.store, "delete");
873
+ if (t.kind === "folder" || mimeOf(cleanName(input.name), input.mime) !== t.mime) throw fail("asset_replace_type", { name: input.name, mime: t.mime });
874
+ return t;
875
+ }
876
+ async function replaced(actor, t, now) {
877
+ const adapter = storeOf(t.store).cfg.adapter;
878
+ if (t.thumbKey) await adapter.delete(t.thumbKey).catch(() => {
879
+ });
880
+ await dropDerived(t);
881
+ const row = await repo.updateAsset(t.id, { ...now, thumbKey: null, rev: t.rev + 1, updatedAt: ctx.nowIso() });
882
+ ctx.audit(actor, "asset.replace", { detail: { id: t.id, store: t.store, key: t.key, size: now.size, was: t.size } });
883
+ return row;
884
+ }
885
+ async function replace(actor, id, input) {
886
+ await ctx.ready();
887
+ const t = await replaceable(actor, id, { name: (await load(id)).name, mime: input.mime });
888
+ const store = storeOf(t.store);
889
+ const bytes = media?.stripMetadata && t.mime === "image/jpeg" ? stripJpegMetadata(input.bytes) : input.bytes;
890
+ admit(store, { name: t.name, mime: t.mime, size: bytes.length, folder: t.folder });
891
+ if (!contentMatches(t.mime, bytes.subarray(0, 4096))) throw fail("asset_type_mismatch", { name: t.name, mime: t.mime });
892
+ await scanned(actor, { store: t.store, key: t.key, name: t.name, mime: t.mime, size: bytes.length, bytes }, null);
893
+ await store.cfg.adapter.put(t.key, bytes, { mime: t.mime, disposition: dispositionFor(t.name, t.mime) });
894
+ const given = dims(input);
895
+ const read = t.kind === "image" && !given.width ? imageSize(bytes) : null;
896
+ return view(await serverThumb(await replaced(actor, t, { size: bytes.length, width: given.width ?? read?.width ?? null, height: given.height ?? read?.height ?? null, duration: given.duration }), bytes));
897
+ }
898
+ const made = /* @__PURE__ */ new Set();
899
+ const making = /* @__PURE__ */ new Map();
900
+ const waiting = [];
901
+ let active = 0;
902
+ const jobOf = (a, p) => ({ width: p.width ?? null, height: p.height ?? null, fit: p.fit ?? "inside", format: p.format ?? transforms.format, quality: p.quality ?? null, focal: focalOf(a) });
903
+ async function sized(a, size) {
904
+ const preset = transforms?.presets[size];
905
+ if (!transforms || !preset) throw fail("unknown_image_size", { size });
906
+ if (!resizable(a) || a.size > (transforms.maxInputBytes ?? 40 * 1024 * 1024)) return null;
907
+ const job = jobOf(a, preset);
908
+ const key = `${DERIVED_PREFIX}${a.id}/${size}-${stamp([a.rev, a.size, job])}.${IMAGE_EXT[job.format]}`;
909
+ if (made.has(key)) return key;
910
+ let work = making.get(key);
911
+ if (!work) {
912
+ work = (async () => {
913
+ const adapter = storeOf(a.store).cfg.adapter;
914
+ if (await adapter.head(key)) return key;
915
+ if (active >= (transforms.concurrency ?? 4)) await new Promise((go) => waiting.push(go));
916
+ else active++;
917
+ try {
918
+ const bytes = await adapter.readStart(a.key, a.size);
919
+ if (!bytes) return null;
920
+ const out = await transforms.make(bytes, job);
921
+ await adapter.put(key, out.bytes, { mime: `image/${job.format}`, cacheControl: FOREVER });
922
+ return key;
923
+ } finally {
924
+ const next = waiting.shift();
925
+ if (next) next();
926
+ else active--;
927
+ }
928
+ })().then((k) => (k && made.add(k), k)).catch((e) => (ctx.warn(`image-size-${a.id}-${size}`, `could not make size "${size}" of ${a.key}: ${e instanceof Error ? e.message : String(e)}`), null)).finally(() => making.delete(key));
929
+ making.set(key, work);
930
+ }
931
+ let timer;
932
+ const late = new Promise((r) => timer = setTimeout(() => r(null), transforms.timeoutMs ?? 1e4));
933
+ try {
934
+ return await Promise.race([work, late]);
935
+ } finally {
936
+ clearTimeout(timer);
937
+ }
938
+ }
939
+ async function dropDerived(a) {
940
+ const adapter = media?.stores[a.store]?.adapter;
941
+ if (!adapter || !transforms) return;
942
+ try {
943
+ let cursor = null;
944
+ do {
945
+ const page = await adapter.list({ prefix: `${DERIVED_PREFIX}${a.id}/`, cursor, limit: 200 });
946
+ for (const o of page.objects) {
947
+ await adapter.delete(o.key).catch(() => {
948
+ });
949
+ made.delete(o.key);
950
+ }
951
+ cursor = page.cursor;
952
+ } while (cursor);
953
+ } catch {
954
+ }
955
+ }
956
+ async function serverThumb(row, bytes) {
957
+ if (!transforms || !resizable(row) || bytes.length > (transforms.maxInputBytes ?? 40 * 1024 * 1024)) return row;
958
+ try {
959
+ const out = await transforms.make(bytes, { width: 480, height: 480, fit: "inside", format: "webp", quality: null, focal: null });
960
+ const key = `${THUMB_PREFIX}${row.id}.webp`;
961
+ await storeOf(row.store).cfg.adapter.put(key, out.bytes, { mime: "image/webp", cacheControl: FOREVER });
962
+ return await repo.updateAsset(row.id, { thumbKey: key }) ?? row;
963
+ } catch {
964
+ return row;
965
+ }
966
+ }
801
967
  const dims = (o) => {
802
968
  const int = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 && v < 1e5 ? Math.round(v) : null;
803
969
  return { width: int(o.width), height: int(o.height), duration: typeof o.duration === "number" && Number.isFinite(o.duration) && o.duration >= 0 ? o.duration : null };
@@ -832,6 +998,19 @@ function createAssets(ctx) {
832
998
  });
833
999
  const given = dims(meta);
834
1000
  const read = a.kind === "image" && !given.width ? imageSize(start) : null;
1001
+ const settle = (key, name) => adapter.settle?.(key, { mime: a.mime, disposition: dispositionFor(name, a.mime) });
1002
+ if (a.key.startsWith(REPLACE_PREFIX)) {
1003
+ const t = await repo.findAsset(a.key.slice(REPLACE_PREFIX.length).split("/")[0]);
1004
+ if (!t || t.status !== "ready" || !canAsset(actor, t.store, "delete")) {
1005
+ await discard({ ...a, uploadId: null });
1006
+ throw fail("asset_not_found", { id });
1007
+ }
1008
+ await adapter.copy(a.key, t.key);
1009
+ await settle(t.key, t.name);
1010
+ await discard({ ...a, uploadId: null });
1011
+ return view(await replaced(actor, t, { size: head.size, width: given.width ?? read?.width ?? null, height: given.height ?? read?.height ?? null, duration: given.duration }));
1012
+ }
1013
+ await settle(a.key, a.name);
835
1014
  const row = await repo.updateAsset(a.id, { status: "ready", uploadId: null, width: given.width ?? read?.width ?? null, height: given.height ?? read?.height ?? null, duration: given.duration, updatedAt: ctx.nowIso() });
836
1015
  ctx.audit(actor, "asset.upload", { detail: { id: a.id, store: a.store, key: a.key, size: a.size } });
837
1016
  return view(row);
@@ -857,6 +1036,7 @@ function createAssets(ctx) {
857
1036
  await ctx.ready();
858
1037
  const store = storeOf(input.store);
859
1038
  need(actor, store.name, "write");
1039
+ if (media?.stripMetadata && mimeOf(cleanName(input.name), input.mime) === "image/jpeg") input = { ...input, bytes: stripJpegMetadata(input.bytes) };
860
1040
  const a = admit(store, { ...input, size: input.bytes.length });
861
1041
  if (!contentMatches(a.mime, input.bytes.subarray(0, 4096))) throw fail("asset_type_mismatch", { name: a.name, mime: a.mime });
862
1042
  const free = await freeKey(store, a.folder, a.name);
@@ -890,7 +1070,7 @@ function createAssets(ctx) {
890
1070
  updatedAt: ctx.nowIso()
891
1071
  });
892
1072
  ctx.audit(actor, "asset.upload", { detail: { id: row.id, store: row.store, key: row.key, size: row.size } });
893
- return view(row);
1073
+ return view(await serverThumb(row, input.bytes));
894
1074
  }
895
1075
  async function importFromUrl(actor, input) {
896
1076
  const store = storeOf(input.store);
@@ -1001,7 +1181,10 @@ function createAssets(ctx) {
1001
1181
  async function update(actor, id, patch) {
1002
1182
  const a = await load(id);
1003
1183
  need(actor, a.store, "write");
1004
- const row = await repo.updateAsset(a.id, { ...patch.alt !== void 0 ? { alt: String(patch.alt).trim().slice(0, 500) } : {}, ...patch.tags !== void 0 ? { tags: cleanTags(patch.tags) } : {}, updatedAt: ctx.nowIso() });
1184
+ const unit = (v) => Math.round(Math.min(1, Math.max(0, Number(v) || 0)) * 1e3) / 1e3;
1185
+ const focal = patch.focal === void 0 ? {} : patch.focal === null || a.kind !== "image" ? { focalX: null, focalY: null } : { focalX: unit(patch.focal.x), focalY: unit(patch.focal.y) };
1186
+ const row = await repo.updateAsset(a.id, { ...patch.alt !== void 0 ? { alt: String(patch.alt).trim().slice(0, 500) } : {}, ...patch.tags !== void 0 ? { tags: cleanTags(patch.tags) } : {}, ...focal, updatedAt: ctx.nowIso() });
1187
+ if ("focalX" in focal && (focal.focalX !== a.focalX || focal.focalY !== a.focalY)) await dropDerived(a);
1005
1188
  return view(row);
1006
1189
  }
1007
1190
  async function move(actor, id, to) {
@@ -1071,8 +1254,9 @@ function createAssets(ctx) {
1071
1254
  const a = await load(id);
1072
1255
  const store = storeOf(a.store);
1073
1256
  if (store.cfg.visibility === "private" || store.cfg.access?.read) need(actor, a.store, "read");
1074
- const key = o.thumb && a.thumbKey ? a.thumbKey : a.key;
1075
- const direct = store.cfg.visibility === "public" && !o.download ? store.cfg.adapter.publicUrl(key) : null;
1257
+ const key = o.thumb && a.thumbKey ? a.thumbKey : o.size && !o.thumb ? await sized(a, o.size) ?? a.key : a.key;
1258
+ const plain = store.cfg.visibility === "public" && !o.download ? store.cfg.adapter.publicUrl(key) : null;
1259
+ const direct = plain && !key.startsWith(DERIVED_PREFIX) ? withRev(plain, a.rev) : plain;
1076
1260
  return { url: direct ?? await store.cfg.adapter.presignGet(key, { expires: ttl, download: o.download ? a.name : null }), visibility: store.cfg.visibility, ttl };
1077
1261
  }
1078
1262
  async function cleanup(o = {}) {
@@ -1152,7 +1336,9 @@ function createAssets(ctx) {
1152
1336
  return Object.fromEntries(rows.filter((a) => a.status === "ready" && media.stores[a.store]).map((a) => [a.id, info(a)]));
1153
1337
  }
1154
1338
  function imageUrl(asset, o) {
1155
- return media?.imageUrl && asset.kind === "image" && asset.mime !== "image/svg+xml" ? media.imageUrl({ url: asset.url, width: o.width, asset }) : asset.url;
1339
+ if (asset.kind !== "image" || asset.mime === "image/svg+xml") return asset.url;
1340
+ if (o.size && transforms?.presets[o.size] && asset.mime !== "image/gif") return `${filesUrl}/${asset.id}/${encodeURIComponent(asset.name)}?size=${encodeURIComponent(o.size)}`;
1341
+ return media?.imageUrl && o.width ? media.imageUrl({ url: asset.url, width: o.width, asset }) : asset.url;
1156
1342
  }
1157
1343
  async function scanned(actor, f, adapter) {
1158
1344
  if (!media?.scan) return;
@@ -1363,9 +1549,9 @@ function createAssets(ctx) {
1363
1549
  if (!media) return null;
1364
1550
  const stores = names2.filter((n) => canAsset(actor, n, "read")).map((n) => {
1365
1551
  const cfg = media.stores[n];
1366
- return { name: n, label: cfg.label ?? n, visibility: cfg.visibility, ...rulesOf(cfg), can: { write: canAsset(actor, n, "write"), delete: canAsset(actor, n, "delete"), browse: canBrowse(actor, n) } };
1552
+ return { name: n, label: cfg.label ?? n, visibility: cfg.visibility, ...rulesOf(cfg), parts: cfg.adapter.multipart !== false, can: { write: canAsset(actor, n, "write"), delete: canAsset(actor, n, "delete"), browse: canBrowse(actor, n) } };
1367
1553
  });
1368
- return stores.length ? { stores, partSize: PART_SIZE } : null;
1554
+ return stores.length ? { stores, partSize: PART_SIZE, stripMetadata: !!media.stripMetadata, sizes: Object.keys(transforms?.presets ?? {}) } : null;
1369
1555
  }
1370
1556
  return {
1371
1557
  enabled: !!media && names2.length > 0,
@@ -1379,6 +1565,7 @@ function createAssets(ctx) {
1379
1565
  abortUpload,
1380
1566
  setThumb,
1381
1567
  put,
1568
+ replace,
1382
1569
  import: importFromUrl,
1383
1570
  list,
1384
1571
  folders,
@@ -1628,7 +1815,10 @@ function createRestClient(opts) {
1628
1815
  /** Address of a file by its key (files the CMS has no row for). */
1629
1816
  storeFileUrl: (store, key, o = {}) => `${base}/stores/${enc(store)}/files/_open?key=${enc(key)}${o.download ? "&download=1" : ""}`,
1630
1817
  /** Address of a file through the CMS route (`thumb`: its small picture). */
1631
- fileUrl: (a, o = {}) => `${base}/files/${enc(a.id)}/${enc(a.name)}${o.thumb ? "?thumb=1" : o.download ? "?download=1" : ""}`,
1818
+ fileUrl: (a, o = {}) => {
1819
+ const query = [o.thumb ? "thumb=1" : o.download ? "download=1" : o.size ? `size=${enc(o.size)}` : "", a.rev ? `v=${a.rev}` : ""].filter(Boolean).join("&");
1820
+ return `${base}/files/${enc(a.id)}/${enc(a.name)}${query ? `?${query}` : ""}`;
1821
+ },
1632
1822
  audit: (q = {}) => req("GET", "/audit", { query: q })
1633
1823
  };
1634
1824
  }
@@ -1690,6 +1880,8 @@ var en = {
1690
1880
  import_blocked: "That address cannot be fetched",
1691
1881
  import_failed: "Could not fetch the file ({reason})",
1692
1882
  asset_rejected: "This file did not pass the check",
1883
+ asset_replace_type: "A file can only be replaced by one of the same type ({mime})",
1884
+ unknown_image_size: "There is no image size named \u201C{size}\u201D",
1693
1885
  asset_missing: "The file {id} does not exist",
1694
1886
  asset_wrong_kind: "The file {id} is not a kind this field takes",
1695
1887
  asset_alt_missing: "The image on line {line} has no alt text",
@@ -1779,6 +1971,8 @@ var ERROR_CODES = {
1779
1971
  import_blocked: "invalid",
1780
1972
  import_failed: "invalid",
1781
1973
  asset_rejected: "invalid",
1974
+ asset_replace_type: "invalid",
1975
+ unknown_image_size: "not_found",
1782
1976
  asset_missing: "invalid",
1783
1977
  asset_wrong_kind: "invalid",
1784
1978
  asset_alt_missing: "invalid",
@@ -2623,7 +2817,7 @@ function displayPrefix(raw) {
2623
2817
  }
2624
2818
 
2625
2819
  // src/schema-version.ts
2626
- var SCHEMA_VERSION = 4;
2820
+ var SCHEMA_VERSION = 5;
2627
2821
 
2628
2822
  // src/search.ts
2629
2823
  var HANGUL = /[\uac00-\ud7a3]/;
@@ -3662,17 +3856,17 @@ ${h.added.join("\n")}`).digest("hex").slice(0, 12);
3662
3856
  const t = Date.now();
3663
3857
  if (index2.built && !index2.dirty && t - index2.checkedAt > refreshMs) {
3664
3858
  index2.checkedAt = t;
3665
- const stamp = await repo.changeStamp().catch(() => index2.stamp);
3666
- if (stamp !== index2.stamp) index2.dirty = true;
3859
+ const stamp2 = await repo.changeStamp().catch(() => index2.stamp);
3860
+ if (stamp2 !== index2.stamp) index2.dirty = true;
3667
3861
  }
3668
3862
  if (index2.built && !index2.dirty) return index2.built;
3669
3863
  if (!index2.building) {
3670
3864
  index2.dirty = false;
3671
3865
  index2.building = (async () => {
3672
- const stamp = await repo.changeStamp();
3866
+ const stamp2 = await repo.changeStamp();
3673
3867
  const built = await buildIndex();
3674
3868
  index2.built = built;
3675
- index2.stamp = stamp;
3869
+ index2.stamp = stamp2;
3676
3870
  index2.checkedAt = Date.now();
3677
3871
  return built;
3678
3872
  })().catch((err) => {
@@ -4090,6 +4284,9 @@ function cmsTables(o = {}) {
4090
4284
  alt: (0, import_pg_core.text)("alt").notNull().default(""),
4091
4285
  tags: (0, import_pg_core.jsonb)("tags").$type().notNull().default([]),
4092
4286
  thumbKey: (0, import_pg_core.text)("thumb_key"),
4287
+ focalX: (0, import_pg_core.real)("focal_x"),
4288
+ focalY: (0, import_pg_core.real)("focal_y"),
4289
+ rev: (0, import_pg_core.integer)("rev").notNull().default(0),
4093
4290
  status: (0, import_pg_core.text)("status").notNull().default("pending"),
4094
4291
  uploadId: (0, import_pg_core.text)("upload_id"),
4095
4292
  createdBy: (0, import_pg_core.text)("created_by"),
@@ -4266,6 +4463,9 @@ CREATE TABLE IF NOT EXISTS ${tbl("assets")} (
4266
4463
  "alt" text NOT NULL DEFAULT '',
4267
4464
  "tags" jsonb NOT NULL DEFAULT '[]'::jsonb,
4268
4465
  "thumb_key" text,
4466
+ "focal_x" real,
4467
+ "focal_y" real,
4468
+ "rev" integer NOT NULL DEFAULT 0,
4269
4469
  "status" text NOT NULL DEFAULT 'pending',
4270
4470
  "upload_id" text,
4271
4471
  "created_by" text,
@@ -4355,6 +4555,14 @@ CREATE TABLE IF NOT EXISTS ${tbl("presence")} (
4355
4555
  PRIMARY KEY ("document_id", "actor_id")
4356
4556
  );
4357
4557
  CREATE INDEX IF NOT EXISTS ${idx("presence_seen_idx")} ON ${tbl("presence")} ("seen_at");`.trim()
4558
+ },
4559
+ {
4560
+ version: 5,
4561
+ name: "agent-cms 0.11.0: an image's focal point, replacing a file at the same address",
4562
+ sql: `
4563
+ ALTER TABLE ${tbl("assets")} ADD COLUMN IF NOT EXISTS "focal_x" real;
4564
+ ALTER TABLE ${tbl("assets")} ADD COLUMN IF NOT EXISTS "focal_y" real;
4565
+ ALTER TABLE ${tbl("assets")} ADD COLUMN IF NOT EXISTS "rev" integer NOT NULL DEFAULT 0;`.trim()
4358
4566
  }
4359
4567
  ];
4360
4568
  }
@@ -4587,6 +4795,9 @@ var DrizzleRepo = class _DrizzleRepo {
4587
4795
  alt: r.alt,
4588
4796
  tags: r.tags ?? [],
4589
4797
  thumbKey: r.thumbKey,
4798
+ focalX: r.focalX ?? null,
4799
+ focalY: r.focalY ?? null,
4800
+ rev: r.rev ?? 0,
4590
4801
  status: r.status,
4591
4802
  uploadId: r.uploadId,
4592
4803
  createdBy: r.createdBy,
@@ -5097,7 +5308,7 @@ var import_node_path = require("path");
5097
5308
  var import_node_url = require("url");
5098
5309
 
5099
5310
  // src/version.ts
5100
- var VERSION = "0.10.2";
5311
+ var VERSION = "0.11.0";
5101
5312
 
5102
5313
  // src/registry.ts
5103
5314
  var sha = (s) => (0, import_node_crypto3.createHash)("sha256").update(s).digest("hex");
@@ -5584,7 +5795,8 @@ async function storageCheck(media, origin, io) {
5584
5795
  expect(res.ok, `PUT answered ${res.status}`);
5585
5796
  expect((await a.head(`${run}/b.txt`))?.size === text2.length, "the file did not arrive");
5586
5797
  });
5587
- await step("large files in parts", async () => {
5798
+ if (a.multipart === false) io.out("skip large files in parts: not supported on this store (a file goes up in one request, and a failed upload starts again)");
5799
+ else await step("large files in parts", async () => {
5588
5800
  const id = await a.createMultipart(`${run}/c.bin`, { mime: "application/octet-stream" });
5589
5801
  const sizes = [5 * 1024 * 1024, 1024];
5590
5802
  for (const n of [1, 2]) {
@@ -5637,6 +5849,7 @@ async function storageCheck(media, origin, io) {
5637
5849
  for (const k of ["a.txt", "b.txt", "c.bin", "d.txt"]) await a.delete(`${run}/${k}`).catch(() => {
5638
5850
  });
5639
5851
  }
5852
+ if (Object.values(media.stores).every((s) => s.adapter.multipart === false)) return bad ? 1 : 0;
5640
5853
  io.out("");
5641
5854
  io.out("CORS rule the bucket needs (replace the origin with your site):");
5642
5855
  io.out(JSON.stringify([{ AllowedOrigins: [origin ?? "https://your-site.example"], AllowedMethods: ["GET", "HEAD", "PUT"], AllowedHeaders: ["*"], ExposeHeaders: ["ETag"], MaxAgeSeconds: 3600 }], null, 2));
package/dist/cli.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MediaOptions } from './cms-C_vkAxYV.cjs';
2
- import { D as DoctorReport } from './drizzle-repo-CviH3EX7.cjs';
1
+ import { M as MediaOptions } from './cms-CaB81PPX.cjs';
2
+ import { D as DoctorReport } from './drizzle-repo-CblPVYnK.cjs';
3
3
  import { cmsTables } from './tables.cjs';
4
4
  import './storage.cjs';
5
5
  import './types.cjs';
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MediaOptions } from './cms-pqJyowu1.js';
2
- import { D as DoctorReport } from './drizzle-repo-DWLD0rWe.js';
1
+ import { M as MediaOptions } from './cms-A9tmLmTP.js';
2
+ import { D as DoctorReport } from './drizzle-repo-BXV-hFkE.js';
3
3
  import { cmsTables } from './tables.js';
4
4
  import './storage.js';
5
5
  import './types.js';
package/dist/cli.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-T66ZKBHF.js";
4
4
  import {
5
5
  DrizzleRepo
6
- } from "./chunk-7WJIIJCI.js";
6
+ } from "./chunk-LELPCGDX.js";
7
7
  import {
8
8
  docFromMarkdown
9
9
  } from "./chunk-DD56PTZ4.js";
@@ -13,35 +13,35 @@ import {
13
13
  schemaVersionSql,
14
14
  splitSql,
15
15
  upgradeSteps
16
- } from "./chunk-IU2SMWAM.js";
16
+ } from "./chunk-42PW3HQ3.js";
17
17
  import {
18
18
  VERSION
19
- } from "./chunk-5ODZ2ZJF.js";
20
- import {
21
- CmsRemoteError,
22
- createCmsClient,
23
- createRestClient,
24
- isCmsRemoteError
25
- } from "./chunk-BFVBHIHV.js";
19
+ } from "./chunk-NO6S7KOL.js";
26
20
  import {
27
21
  createCmsCore,
28
22
  humanSize,
29
23
  imageSize
30
- } from "./chunk-7SCYDG2G.js";
24
+ } from "./chunk-J25IKU7C.js";
31
25
  import "./chunk-MA6VKJ3F.js";
32
- import "./chunk-PEQY4N73.js";
26
+ import "./chunk-TKKTEGHL.js";
27
+ import "./chunk-I5UHTAAW.js";
28
+ import "./chunk-WWG7XDIZ.js";
33
29
  import {
34
30
  SCHEMA_VERSION
35
- } from "./chunk-3OPKTBEI.js";
31
+ } from "./chunk-SV3ZA6XP.js";
36
32
  import {
37
33
  unifiedDiff
38
34
  } from "./chunk-AKN7SUXU.js";
39
- import "./chunk-KAO3Z3CF.js";
40
- import "./chunk-PGV2QPIL.js";
35
+ import {
36
+ CmsRemoteError,
37
+ createCmsClient,
38
+ createRestClient,
39
+ isCmsRemoteError
40
+ } from "./chunk-J5DW3RFQ.js";
41
41
  import {
42
42
  DEFAULT_ACCEPT,
43
43
  DEFAULT_MAX_FILE_SIZE
44
- } from "./chunk-6PB4ZCHH.js";
44
+ } from "./chunk-CIMW73L3.js";
45
45
  import {
46
46
  __dirname
47
47
  } from "./chunk-2NTK7H4W.js";
@@ -540,7 +540,8 @@ async function storageCheck(media, origin, io) {
540
540
  expect(res.ok, `PUT answered ${res.status}`);
541
541
  expect((await a.head(`${run}/b.txt`))?.size === text.length, "the file did not arrive");
542
542
  });
543
- await step("large files in parts", async () => {
543
+ if (a.multipart === false) io.out("skip large files in parts: not supported on this store (a file goes up in one request, and a failed upload starts again)");
544
+ else await step("large files in parts", async () => {
544
545
  const id = await a.createMultipart(`${run}/c.bin`, { mime: "application/octet-stream" });
545
546
  const sizes = [5 * 1024 * 1024, 1024];
546
547
  for (const n of [1, 2]) {
@@ -593,6 +594,7 @@ async function storageCheck(media, origin, io) {
593
594
  for (const k of ["a.txt", "b.txt", "c.bin", "d.txt"]) await a.delete(`${run}/${k}`).catch(() => {
594
595
  });
595
596
  }
597
+ if (Object.values(media.stores).every((s) => s.adapter.multipart === false)) return bad ? 1 : 0;
596
598
  io.out("");
597
599
  io.out("CORS rule the bucket needs (replace the origin with your site):");
598
600
  io.out(JSON.stringify([{ AllowedOrigins: [origin ?? "https://your-site.example"], AllowedMethods: ["GET", "HEAD", "PUT"], AllowedHeaders: ["*"], ExposeHeaders: ["ETag"], MaxAgeSeconds: 3600 }], null, 2));
package/dist/client.cjs CHANGED
@@ -243,7 +243,10 @@ function createRestClient(opts) {
243
243
  /** Address of a file by its key (files the CMS has no row for). */
244
244
  storeFileUrl: (store, key, o = {}) => `${base}/stores/${enc(store)}/files/_open?key=${enc(key)}${o.download ? "&download=1" : ""}`,
245
245
  /** Address of a file through the CMS route (`thumb`: its small picture). */
246
- fileUrl: (a, o = {}) => `${base}/files/${enc(a.id)}/${enc(a.name)}${o.thumb ? "?thumb=1" : o.download ? "?download=1" : ""}`,
246
+ fileUrl: (a, o = {}) => {
247
+ const query = [o.thumb ? "thumb=1" : o.download ? "download=1" : o.size ? `size=${enc(o.size)}` : "", a.rev ? `v=${a.rev}` : ""].filter(Boolean).join("&");
248
+ return `${base}/files/${enc(a.id)}/${enc(a.name)}${query ? `?${query}` : ""}`;
249
+ },
247
250
  audit: (q = {}) => req("GET", "/audit", { query: q })
248
251
  };
249
252
  }
package/dist/client.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { g as AssetView, f as AssetUsage, E as PatchOp, i as BulkAction, j as BulkResult, D as DocDiff, A as AgentChange, I as PreviewTtl, G as PreviewLink, af as CommentThread, ag as TrashRef, ah as TrashItem, ai as ReleaseView, c as AssetListOptions, W as UploadRequest, V as UploadInstructions } from './cms-C_vkAxYV.cjs';
2
- export { aj as BlockedItem, ak as ScheduledRun } from './cms-C_vkAxYV.cjs';
1
+ import { i as AssetView, h as AssetUsage, H as PatchOp, k as BulkAction, l as BulkResult, D as DocDiff, A as AgentChange, Q as PreviewTtl, J as PreviewLink, ai as CommentThread, aj as TrashRef, ak as TrashItem, al as ReleaseView, e as AssetListOptions, Z as UploadRequest, Y as UploadInstructions } from './cms-CaB81PPX.cjs';
2
+ export { am as BlockedItem, an as ScheduledRun } from './cms-CaB81PPX.cjs';
3
3
  import { ErrorParams, Diagnostic } from './errors.cjs';
4
4
  import { Block, TocItem } from './markdown.cjs';
5
5
  import { CmsRelease, DocSummary, DocCounts, CmsDoc, AutosaveState, VersionSummary, CmsVersion, CmsComment, Presence, SavedFilter, CmsKey, KeyScope, AuditEntry } from './types.cjs';
@@ -141,6 +141,8 @@ interface MediaStoreInfo {
141
141
  /** File types the store takes (MIME types, `image/*` groups, `.ext`). */
142
142
  accept: readonly string[];
143
143
  maxFileSize: number;
144
+ /** `false`: the store takes a file in one request, so a failed upload starts again instead of carrying on. */
145
+ parts?: boolean;
144
146
  can: {
145
147
  write: boolean;
146
148
  delete: boolean;
@@ -150,6 +152,10 @@ interface MediaStoreInfo {
150
152
  interface MediaInfo {
151
153
  stores: MediaStoreInfo[];
152
154
  partSize: number;
155
+ /** Photos lose their camera data (location, time, device) in the browser before they are sent. */
156
+ stripMetadata?: boolean;
157
+ /** Names of the image sizes the server makes (`?size=`). */
158
+ sizes?: string[];
153
159
  }
154
160
  interface FolderTree {
155
161
  store: string;
@@ -420,6 +426,10 @@ declare function createRestClient(opts: RestClientOptions): {
420
426
  updateAsset: (id: string, patch: {
421
427
  alt?: string;
422
428
  tags?: string[];
429
+ focal?: {
430
+ x: number;
431
+ y: number;
432
+ } | null;
423
433
  }) => Promise<AssetView>;
424
434
  moveAsset: (id: string, to: {
425
435
  folder?: string | null;
@@ -510,9 +520,11 @@ declare function createRestClient(opts: RestClientOptions): {
510
520
  fileUrl: (a: {
511
521
  id: string;
512
522
  name: string;
523
+ rev?: number;
513
524
  }, o?: {
514
525
  thumb?: boolean;
515
526
  download?: boolean;
527
+ size?: string;
516
528
  }) => string;
517
529
  audit: (q?: {
518
530
  cursor?: string | null;