@mainsoft/agent-cms 0.10.1 → 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.
- package/CHANGELOG.md +21 -0
- package/README.md +98 -2
- package/TODO.md +6 -6
- package/UPGRADE-0.11.md +43 -0
- package/dist/agent.d.cts +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +7 -7
- package/dist/bin.js +236 -23
- package/dist/{chunk-IU2SMWAM.js → chunk-42PW3HQ3.js} +15 -1
- package/dist/{chunk-6PB4ZCHH.js → chunk-CIMW73L3.js} +58 -1
- package/dist/{chunk-7Y6TU2UA.js → chunk-HY4ED7LT.js} +2 -2
- package/dist/{chunk-DSJETZT4.js → chunk-I3DF6DMI.js} +15 -10
- package/dist/{chunk-KAO3Z3CF.js → chunk-I5UHTAAW.js} +3 -1
- package/dist/{chunk-7SCYDG2G.js → chunk-J25IKU7C.js} +164 -28
- package/dist/{chunk-BFVBHIHV.js → chunk-J5DW3RFQ.js} +4 -1
- package/dist/{chunk-7WJIIJCI.js → chunk-LELPCGDX.js} +8 -5
- package/dist/{chunk-QMPSOLLH.js → chunk-NO6S7KOL.js} +1 -1
- package/dist/{chunk-ZCUJ4MPT.js → chunk-OLHLSSTD.js} +3 -3
- package/dist/{chunk-3OPKTBEI.js → chunk-SV3ZA6XP.js} +1 -1
- package/dist/{chunk-PEQY4N73.js → chunk-TKKTEGHL.js} +1 -0
- package/dist/{chunk-PGV2QPIL.js → chunk-WWG7XDIZ.js} +2 -0
- package/dist/cli.cjs +236 -23
- package/dist/cli.d.cts +2 -2
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +18 -16
- package/dist/client.cjs +4 -1
- package/dist/client.d.cts +14 -2
- package/dist/client.d.ts +14 -2
- package/dist/client.js +1 -1
- package/dist/{cms-pqJyowu1.d.ts → cms-A9tmLmTP.d.ts} +100 -5
- package/dist/{cms-C_vkAxYV.d.cts → cms-CaB81PPX.d.cts} +100 -5
- package/dist/config.d.cts +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/{drizzle-repo-DWLD0rWe.d.ts → drizzle-repo-BXV-hFkE.d.ts} +1 -1
- package/dist/{drizzle-repo-CviH3EX7.d.cts → drizzle-repo-CblPVYnK.d.cts} +1 -1
- package/dist/errors.cjs +4 -0
- package/dist/errors.d.cts +3 -1
- package/dist/errors.d.ts +3 -1
- package/dist/errors.js +2 -2
- package/dist/frontmatter.d.cts +1 -1
- package/dist/frontmatter.d.ts +1 -1
- package/dist/http.cjs +32 -12
- package/dist/http.d.cts +18 -4
- package/dist/http.d.ts +18 -4
- package/dist/http.js +30 -20
- package/dist/image-sharp.cjs +104 -0
- package/dist/image-sharp.d.cts +47 -0
- package/dist/image-sharp.d.ts +47 -0
- package/dist/image-sharp.js +70 -0
- package/dist/index.cjs +244 -27
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +21 -21
- package/dist/mcp.cjs +9 -4
- package/dist/mcp.d.cts +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +11 -11
- package/dist/messages/en.cjs +2 -0
- package/dist/messages/en.js +1 -1
- package/dist/messages/ko.cjs +2 -0
- package/dist/messages/ko.js +2 -0
- package/dist/registry/cms-doc-editor.json +6 -1
- package/dist/registry/cms-lib.json +2 -2
- package/dist/registry/cms-media-picker.json +2 -2
- package/dist/registry/cms-media.json +1 -1
- package/dist/registry/registry.json +4 -0
- package/dist/storage-vercel-blob.cjs +199 -0
- package/dist/storage-vercel-blob.d.cts +98 -0
- package/dist/storage-vercel-blob.d.ts +98 -0
- package/dist/storage-vercel-blob.js +165 -0
- package/dist/storage.cjs +63 -3
- package/dist/storage.d.cts +27 -2
- package/dist/storage.d.ts +27 -2
- package/dist/storage.js +9 -3
- package/dist/tables.cjs +15 -1
- package/dist/tables.d.cts +154 -1
- package/dist/tables.d.ts +154 -1
- package/dist/tables.js +2 -2
- package/dist/tools.cjs +8 -3
- package/dist/tools.d.cts +1 -1
- package/dist/tools.d.ts +1 -1
- package/dist/tools.js +9 -9
- package/dist/types.cjs +5 -0
- package/dist/types.d.cts +6 -1
- package/dist/types.d.ts +6 -1
- package/dist/types.js +3 -3
- package/package.json +36 -2
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
{
|
|
23
23
|
"path": "registry/cms/cms-media.tsx",
|
|
24
24
|
"type": "registry:component",
|
|
25
|
-
"content": "// agent-cms registry: cms-media (0.8.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// The media library: stores and folders on the left, files as a grid or a\n// list, a panel with one file's details (alt text, tags, where it is used),\n// uploads straight to the storage, and delete with a look at the documents\n// that use the file.\n\"use client\";\n\nimport * as React from \"react\";\nimport { Copy, Download, Folder, FolderPlus, LayoutGrid, Link as LinkIcon, List, Pencil, Search, Trash2, X } from \"lucide-react\";\nimport type { AssetDetail, AssetView, FolderTree } from \"@mainsoft/agent-cms/client\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@/components/ui/table\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport { AssetGrid, AssetThumb, folderOptions, kindName, kindTabs, SELECT_CLASS, storeLabel, UploadButton, UploadPanel, useAssetList, useUploads, type KindTab } from \"./cms-media-picker\";\nimport { errorMessage } from \"./cms-messages\";\nimport { ConfirmDialog, copyText, PageHeader, Segmented, StateBadge, StatusText, Who } from \"./cms-parts\";\nimport { fileSize } from \"./cms-upload\";\nimport { forgetAsset, useAsync, useCms, useDebounced, useIsMobile, useLocalStorage } from \"./use-cms\";\n\nexport interface CmsMediaProps {\n /** Where the admin screens live, for links to the documents that use a file. Default \"/admin\". */\n basePath?: string;\n docHref?: (collection: string, slug: string) => string;\n className?: string;\n}\n\nexport function CmsMedia({ basePath = \"/admin\", docHref, className }: CmsMediaProps) {\n const { client, t, me, locale } = useCms();\n const stores = me?.media?.stores ?? [];\n const tree = useAsync<FolderTree[]>(() => client.assetFolders(), [client]);\n const [where, setWhere] = React.useState<{ store: string | null; folder: string | null }>({ store: null, folder: null });\n const [kind, setKind] = React.useState<KindTab>(\"all\");\n const [text, setText] = React.useState(\"\");\n const [q, setQ] = React.useState(\"\");\n const [tag, setTag] = React.useState<string | null>(null);\n const [view, setView] = useLocalStorage<\"grid\" | \"list\">(\"cms-media-view\", \"grid\");\n const [openId, setOpenId] = React.useState<string | null>(null);\n const [newFolder, setNewFolder] = React.useState(false);\n const [importing, setImporting] = React.useState(false);\n const [dragging, setDragging] = React.useState(false);\n const applyQ = useDebounced(setQ, 250);\n const store = where.store ?? stores[0]?.name ?? null;\n const info = stores.find((s) => s.name === store);\n const list = useAssetList({ store, folder: where.folder, kind, q, tag }, !!me?.media);\n const refresh = () => {\n list.reload();\n tree.reload();\n };\n const uploads = useUploads(refresh);\n const options = folderOptions(tree.data ?? [], t);\n const tags = React.useMemo(() => [...new Set([...(tag ? [tag] : []), ...list.assets.flatMap((a) => a.tags)])].sort(), [list.assets, tag]);\n const total = list.counts ? (kind === \"all\" ? list.counts.all : kind === \"document\" ? list.counts.document + list.counts.other : list.counts[kind]) : 0;\n const upload = (files: File[]) => uploads.add(files, { store, folder: where.folder });\n const go = (s: string, folder: string | null) => {\n setWhere({ store: s, folder });\n setOpenId(null);\n };\n\n if (me && !me.media) return <StatusText className=\"p-6\">{t(\"media_empty\")}</StatusText>;\n\n return (\n <div className={cn(\"flex min-h-full flex-col\", className)}>\n <PageHeader title={t(\"nav_media\")}>\n {info?.can.write ? (\n <>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" aria-label={t(\"media_import\")} onClick={() => setImporting(true)}>\n <LinkIcon aria-hidden className=\"h-4 w-4\" />\n <span className=\"hidden lg:inline\">{t(\"media_import\")}</span>\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => setNewFolder(true)}>\n <FolderPlus aria-hidden className=\"h-4 w-4\" />\n {t(\"media_new_folder\")}\n </Button>\n <UploadButton size=\"sm\" accept={info.accept} onFiles={upload} />\n </>\n ) : null}\n </PageHeader>\n <div className=\"flex min-h-0 flex-1\">\n <nav aria-label={t(\"media_folders\")} className=\"hidden w-52 shrink-0 border-r p-3 md:block\">\n {(tree.data ?? []).map((s) => (\n <div key={s.store} className=\"mb-4\">\n <h2 className=\"px-2 pb-1 text-xs font-medium text-muted-foreground\">{storeLabel(s, t)}</h2>\n <ul className=\"flex flex-col gap-0.5\">\n {[{ path: null as string | null, count: s.total }, ...s.folders].map((f) => {\n const on = store === s.store && where.folder === f.path;\n const depth = f.path ? f.path.split(\"/\").length - 1 : 0;\n return (\n <li key={f.path ?? \"\"}>\n <button\n type=\"button\"\n aria-current={on ? \"true\" : undefined}\n onClick={() => go(s.store, f.path)}\n style={{ paddingLeft: 8 + depth * 14 }}\n className={cn(\"flex h-8 w-full items-center gap-2 rounded-md pr-2 text-left text-sm outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring\", on && \"bg-accent font-medium\")}\n >\n <Folder aria-hidden className=\"h-4 w-4 shrink-0 text-muted-foreground\" />\n <span className=\"flex-1 truncate\">{f.path ? f.path.split(\"/\").pop() : t(\"all\")}</span>\n <span className=\"text-xs tabular-nums text-muted-foreground\">{f.count}</span>\n </button>\n </li>\n );\n })}\n </ul>\n </div>\n ))}\n </nav>\n <section\n className={cn(\"flex min-w-0 flex-1 flex-col\", dragging && \"bg-accent/40\")}\n onDragOver={(e) => {\n if (!info?.can.write || !e.dataTransfer.types.includes(\"Files\")) return;\n e.preventDefault();\n setDragging(true);\n }}\n onDragLeave={() => setDragging(false)}\n onDrop={(e) => {\n setDragging(false);\n if (!info?.can.write || !e.dataTransfer.files.length) return;\n e.preventDefault();\n upload(Array.from(e.dataTransfer.files));\n }}\n >\n <div className=\"flex flex-wrap items-center gap-2 border-b px-4 py-3 md:px-5\">\n {options.length > 1 ? (\n <select\n aria-label={t(\"media_folder\")}\n className={cn(SELECT_CLASS, \"w-full md:hidden\")}\n value={`${store ?? \"\"}:${where.folder ?? \"\"}`}\n onChange={(e) => {\n const o = options.find((x) => x.value === e.target.value);\n if (o) go(o.store, o.folder);\n }}\n >\n {options.map((o) => (\n <option key={o.value} value={o.value}>\n {o.label}\n </option>\n ))}\n </select>\n ) : null}\n <div className=\"relative min-w-[160px] flex-1 md:max-w-[260px]\">\n <Search aria-hidden className=\"pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground\" />\n <Input\n aria-label={t(\"media_search\")}\n placeholder={t(\"media_search\")}\n className=\"pl-8\"\n value={text}\n onChange={(e) => {\n setText(e.target.value);\n applyQ(e.target.value.trim());\n }}\n />\n </div>\n <Segmented label={t(\"media_kind\")} value={kind} onChange={setKind} options={kindTabs(list.counts, t)} className=\"max-w-full overflow-x-auto\" />\n <div className=\"ml-auto hidden items-center gap-2 md:flex\">\n {tags.length ? (\n <select aria-label={t(\"media_tag\")} className={cn(SELECT_CLASS, \"max-w-[140px]\")} value={tag ?? \"\"} onChange={(e) => setTag(e.target.value || null)}>\n <option value=\"\">{t(\"media_tag\")}</option>\n {tags.map((x) => (\n <option key={x} value={x}>\n {x}\n </option>\n ))}\n </select>\n ) : null}\n <Segmented\n label={t(\"media_view\")}\n value={view}\n onChange={setView}\n options={[\n { value: \"grid\", label: <LayoutGrid aria-label={t(\"media_view_grid\")} className=\"h-4 w-4\" /> },\n { value: \"list\", label: <List aria-label={t(\"media_view_list\")} className=\"h-4 w-4\" /> },\n ]}\n />\n </div>\n </div>\n <div className=\"flex-1 px-2.5 py-3 md:px-3.5\">\n {list.error ? <StatusText tone=\"error\">{errorMessage(list.error, t)}</StatusText> : null}\n {!list.loading && !list.assets.length && !list.error ? <p className=\"py-16 text-center text-sm text-muted-foreground\">{t(\"media_empty\")}</p> : null}\n {view === \"list\" && list.assets.length ? (\n <Table>\n <TableHeader>\n <TableRow>\n <TableHead>{t(\"media_col_name\")}</TableHead>\n <TableHead className=\"w-36\">{t(\"media_col_kind\")}</TableHead>\n <TableHead className=\"w-24 text-right\">{t(\"media_col_size\")}</TableHead>\n <TableHead className=\"w-32\">{t(\"media_col_updated\")}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {list.assets.map((a) => (\n <TableRow key={a.id} data-state={a.id === openId ? \"selected\" : undefined}>\n <TableCell className=\"max-w-0\">\n <button type=\"button\" aria-pressed={a.id === openId} onClick={() => setOpenId(a.id)} className=\"flex w-full items-center gap-2.5 rounded text-left outline-none focus-visible:ring-2 focus-visible:ring-ring\">\n <AssetThumb asset={a} className=\"aspect-square w-8 shrink-0 rounded [&>span]:hidden [&_svg]:h-4 [&_svg]:w-4\" />\n <span className=\"truncate font-medium\">{a.name}</span>\n </button>\n </TableCell>\n <TableCell className=\"text-muted-foreground\">{kindName(a, t)}</TableCell>\n <TableCell className=\"text-right tabular-nums\">{fileSize(a.size)}</TableCell>\n <TableCell className=\"tabular-nums text-muted-foreground\">{new Date(a.updatedAt).toLocaleDateString(locale)}</TableCell>\n </TableRow>\n ))}\n </TableBody>\n </Table>\n ) : (\n <AssetGrid assets={list.assets} selected={openId} onSelect={(a) => setOpenId(a.id === openId ? null : a.id)} className={openId ? \"xl:grid-cols-3\" : undefined} />\n )}\n </div>\n {list.assets.length ? (\n <footer className=\"flex items-center gap-3 border-t px-4 py-2.5 text-sm text-muted-foreground md:px-5\">\n <span className=\"tabular-nums\" role=\"status\">\n {t(\"media_count\", { total, shown: list.assets.length })}\n </span>\n {list.cursor ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => void list.more()}>\n {t(\"load_more\")}\n </Button>\n ) : null}\n </footer>\n ) : null}\n </section>\n {openId ? (\n <AssetPanel\n key={openId}\n id={openId}\n basePath={basePath}\n docHref={docHref}\n onClose={() => setOpenId(null)}\n onChanged={(a) => list.setState((s) => ({ ...s, assets: s.assets.map((x) => (x.id === a.id ? { ...x, ...a } : x)) }))}\n onDeleted={() => {\n setOpenId(null);\n refresh();\n }}\n />\n ) : null}\n </div>\n <ImportDialog\n open={importing}\n onOpenChange={setImporting}\n onImport={async (url) => {\n const a = await client.importAsset({ url, store, folder: where.folder });\n refresh();\n setOpenId(a.id);\n }}\n />\n <NewFolderDialog\n open={newFolder}\n onOpenChange={setNewFolder}\n onCreate={async (name) => {\n const path = `${where.folder ? `${where.folder}/` : \"\"}${name}`;\n await client.createAssetFolder(path, store);\n tree.reload();\n setWhere({ store, folder: path });\n }}\n />\n <UploadPanel items={uploads.items} onRetry={uploads.retry} onRemove={uploads.remove} onClose={uploads.clear} />\n </div>\n );\n}\n\nexport function NewFolderDialog({ open, onOpenChange, onCreate }: { open: boolean; onOpenChange: (o: boolean) => void; onCreate: (name: string) => Promise<void> }) {\n const { t } = useCms();\n const [name, setName] = React.useState(\"\");\n const [error, setError] = React.useState<unknown>(null);\n const [busy, setBusy] = React.useState(false);\n React.useEffect(() => {\n if (open) (setName(\"\"), setError(null));\n }, [open]);\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[400px]\">\n <form\n className=\"grid gap-4\"\n onSubmit={(e) => {\n e.preventDefault();\n if (!name.trim()) return;\n setBusy(true);\n onCreate(name.trim()).then(\n () => (setBusy(false), onOpenChange(false)),\n (err) => (setBusy(false), setError(err))\n );\n }}\n >\n <DialogHeader>\n <DialogTitle>{t(\"media_new_folder\")}</DialogTitle>\n </DialogHeader>\n <div className=\"grid gap-1.5\">\n <Label htmlFor=\"cms-folder-name\">{t(\"media_folder_name\")}</Label>\n <Input id=\"cms-folder-name\" autoFocus value={name} onChange={(e) => setName(e.target.value)} aria-invalid={error ? true : undefined} />\n {error ? <StatusText tone=\"error\">{errorMessage(error, t)}</StatusText> : null}\n </div>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => onOpenChange(false)}>\n {t(\"cancel\")}\n </Button>\n <Button type=\"submit\" disabled={busy || !name.trim()}>\n {t(\"create\")}\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n}\n\n/** Fetch a file from a public https address into the folder that is open. The server refuses addresses inside the network. */\nfunction ImportDialog({ open, onOpenChange, onImport }: { open: boolean; onOpenChange: (o: boolean) => void; onImport: (url: string) => Promise<void> }) {\n const { t } = useCms();\n const [url, setUrl] = React.useState(\"\");\n const [error, setError] = React.useState<unknown>(null);\n const [busy, setBusy] = React.useState(false);\n React.useEffect(() => {\n if (open) (setUrl(\"\"), setError(null));\n }, [open]);\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[440px]\">\n <form\n className=\"grid gap-4\"\n onSubmit={(e) => {\n e.preventDefault();\n if (!url.trim()) return;\n setBusy(true);\n onImport(url.trim()).then(\n () => (setBusy(false), onOpenChange(false)),\n (err) => (setBusy(false), setError(err))\n );\n }}\n >\n <DialogHeader>\n <DialogTitle>{t(\"media_import\")}</DialogTitle>\n </DialogHeader>\n <div className=\"grid gap-1.5\">\n <Label htmlFor=\"cms-import-url\">{t(\"media_import_url\")}</Label>\n <Input id=\"cms-import-url\" type=\"url\" inputMode=\"url\" placeholder=\"https://\" autoFocus value={url} onChange={(e) => setUrl(e.target.value)} aria-invalid={error ? true : undefined} />\n {error ? <StatusText tone=\"error\">{errorMessage(error, t)}</StatusText> : null}\n </div>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => onOpenChange(false)}>\n {t(\"cancel\")}\n </Button>\n <Button type=\"submit\" disabled={busy || !url.trim()}>\n {t(\"media_import_go\")}\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n}\n\n// ── one file ─────────────────────────────────────────────────────────────────\n\nexport function AssetPanel({ id, basePath, docHref, onClose, onChanged, onDeleted }: { id: string; basePath: string; docHref?: CmsMediaProps[\"docHref\"]; onClose: () => void; onChanged: (a: AssetView) => void; onDeleted: () => void }) {\n const { client, t, me, appUrl, slots, locale } = useCms();\n const mobile = useIsMobile();\n const { data: asset, error, setData } = useAsync<AssetDetail>(() => client.asset(id), [client, id]);\n const [alt, setAlt] = React.useState<string | null>(null);\n const [tagText, setTagText] = React.useState(\"\");\n const [saveError, setSaveError] = React.useState<unknown>(null);\n const [asking, setAsking] = React.useState(false);\n const [busy, setBusy] = React.useState(false);\n /** The name being typed while renaming (null: not renaming). */\n const [naming, setNaming] = React.useState<string | null>(null);\n const rename = async () => {\n const name = naming?.trim();\n setNaming(null);\n if (!name || !asset || name === asset.name) return;\n try {\n // The server keeps the extension, so the file's type cannot change by renaming.\n const next = await client.moveAsset(id, { name });\n forgetAsset(client, id);\n setData((d) => (d ? { ...d, ...next } : d));\n onChanged(next);\n setSaveError(null);\n } catch (e) {\n setSaveError(e);\n }\n };\n const store = me?.media?.stores.find((s) => s.name === asset?.store);\n const can = store?.can;\n const save = async (patch: { alt?: string; tags?: string[] }) => {\n try {\n const next = await client.updateAsset(id, patch);\n forgetAsset(client, id);\n setData((d) => (d ? { ...d, ...next } : d));\n onChanged(next);\n setSaveError(null);\n } catch (e) {\n setSaveError(e);\n }\n };\n const body = !asset ? (\n <StatusText tone={error ? \"error\" : \"muted\"}>{error ? errorMessage(error, t) : t(\"loading\")}</StatusText>\n ) : (\n <>\n <div className=\"flex items-center gap-2\">\n <div className=\"min-w-0 flex-1\">\n {naming !== null ? (\n <Input\n aria-label={t(\"media_rename\")}\n autoFocus\n className=\"h-8\"\n value={naming}\n onChange={(e) => setNaming(e.target.value)}\n onBlur={() => void rename()}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") void rename();\n if (e.key === \"Escape\") (e.stopPropagation(), setNaming(null));\n }}\n />\n ) : (\n <h2 className=\"truncate font-semibold\">{asset.name}</h2>\n )}\n <p className=\"truncate text-xs text-muted-foreground\">\n {store ? storeLabel(store, t) : asset.store}\n {asset.folder ? ` / ${asset.folder}` : \"\"}\n </p>\n </div>\n {can?.delete && naming === null ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-8 w-8\" aria-label={t(\"media_rename\")} onClick={() => setNaming(asset.name)}>\n <Pencil aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : null}\n {mobile ? null : (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-8 w-8\" aria-label={t(\"close\")} onClick={onClose}>\n <X aria-hidden className=\"h-4 w-4\" />\n </Button>\n )}\n </div>\n {asset.kind === \"video\" ? (\n <video controls preload=\"metadata\" src={client.fileUrl(asset)} poster={asset.thumbKey ? client.fileUrl(asset, { thumb: true }) : undefined} className=\"aspect-video w-full rounded-md border bg-black\" />\n ) : asset.kind === \"audio\" ? (\n <audio controls preload=\"metadata\" src={client.fileUrl(asset)} className=\"w-full\" />\n ) : asset.kind === \"image\" ? (\n <img src={client.fileUrl(asset)} alt={asset.alt} className=\"max-h-64 w-full rounded-md border bg-muted object-contain\" />\n ) : (\n <AssetThumb asset={asset} className=\"aspect-video w-full\" />\n )}\n <div className=\"flex flex-wrap items-center gap-1.5\">\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-8 px-2.5\" onClick={() => void copyText(asset.publicUrl ?? (/^https?:/.test(asset.href) ? asset.href : `${appUrl}${asset.href}`))}>\n <Copy aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"media_copy_url\")}\n </Button>\n {/* A plain link with the button's look: `asChild` exists only in the Radix flavour of shadcn/ui. */}\n <a href={client.fileUrl(asset, { download: true })} className={buttonVariants({ variant: \"outline\", size: \"sm\", className: \"h-8 px-2.5\" })}>\n <Download aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"media_download\")}\n </a>\n <span className=\"flex-1\" />\n {can?.delete ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-8 px-2.5 text-destructive hover:text-destructive\" onClick={() => setAsking(true)}>\n <Trash2 aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"action_delete\")}\n </Button>\n ) : null}\n </div>\n <div className=\"grid gap-1.5\">\n <div className=\"flex min-h-6 items-center\">\n <Label htmlFor=\"cms-asset-alt\" className=\"flex-1\">\n {t(\"media_alt\")}\n </Label>\n {can?.write ? slots.assetAlt?.(asset, { setAlt }) : null}\n </div>\n <Textarea\n id=\"cms-asset-alt\"\n rows={2}\n readOnly={!can?.write}\n value={alt ?? asset.alt}\n onChange={(e) => setAlt(e.target.value)}\n onBlur={() => {\n if (alt !== null && alt.trim() !== asset.alt) void save({ alt: alt.trim() });\n }}\n />\n </div>\n <div className=\"grid gap-1.5\">\n <Label htmlFor=\"cms-asset-tag\">{t(\"media_tags\")}</Label>\n <div className=\"flex min-h-9 flex-wrap items-center gap-1 rounded-md border border-input px-2 py-1 focus-within:ring-2 focus-within:ring-ring\">\n {asset.tags.map((x) => (\n <span key={x} className=\"inline-flex h-6 items-center gap-1 rounded bg-muted pl-2 pr-1 text-xs\">\n {x}\n {can?.write ? (\n <button type=\"button\" aria-label={t(\"media_tag_remove\", { tag: x })} className=\"rounded outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring\" onClick={() => void save({ tags: asset.tags.filter((y) => y !== x) })}>\n <X aria-hidden className=\"h-3 w-3 text-muted-foreground\" />\n </button>\n ) : null}\n </span>\n ))}\n {can?.write ? (\n <input\n id=\"cms-asset-tag\"\n aria-label={t(\"media_tag_add\")}\n value={tagText}\n onChange={(e) => setTagText(e.target.value)}\n onKeyDown={(e) => {\n const v = tagText.trim().replace(/,$/, \"\");\n if ((e.key === \"Enter\" || e.key === \",\") && v) {\n e.preventDefault();\n setTagText(\"\");\n if (!asset.tags.includes(v)) void save({ tags: [...asset.tags, v] });\n }\n }}\n className=\"h-6 min-w-[60px] flex-1 bg-transparent text-sm outline-none\"\n />\n ) : null}\n </div>\n </div>\n {saveError ? <StatusText tone=\"error\">{errorMessage(saveError, t)}</StatusText> : null}\n <dl className=\"grid grid-cols-[84px_1fr] gap-y-2 text-sm\">\n <dt className=\"text-muted-foreground\">{t(\"media_kind\")}</dt>\n <dd>{kindName(asset, t)}</dd>\n <dt className=\"text-muted-foreground\">{t(\"media_size\")}</dt>\n <dd className=\"tabular-nums\">{`${fileSize(asset.size)}${asset.width && asset.height ? `, ${asset.width}×${asset.height}` : \"\"}`}</dd>\n <dt className=\"text-muted-foreground\">{t(\"media_by\")}</dt>\n <dd className=\"min-w-0\">\n <Who kind={asset.createdByKind} label={asset.createdBy} agent={asset.createdByAgent} />\n </dd>\n <dt className=\"text-muted-foreground\">{t(\"media_at\")}</dt>\n <dd className=\"tabular-nums\">{new Date(asset.createdAt).toLocaleDateString(locale)}</dd>\n </dl>\n <div className=\"grid gap-1.5\">\n <h3 className=\"text-sm font-medium\">\n {t(\"media_usage\")} <span className=\"font-normal tabular-nums text-muted-foreground\">{asset.usage.length + asset.usageHidden}</span>\n </h3>\n {asset.usage.length ? <UsageList asset={asset} basePath={basePath} docHref={docHref} /> : asset.usageHidden ? null : <p className=\"text-sm text-muted-foreground\">{t(\"none\")}</p>}\n {asset.usageHidden ? <p className=\"text-xs text-muted-foreground\">{t(\"media_usage_hidden\", { n: asset.usageHidden })}</p> : null}\n </div>\n <ConfirmDialog\n open={asking}\n onOpenChange={setAsking}\n title={t(\"media_delete_title\", { n: 1 })}\n description={t(\"media_delete_gone\")}\n confirmLabel={t(\"action_delete\")}\n destructive\n busy={busy}\n error={saveError && asking ? errorMessage(saveError, t) : undefined}\n onConfirm={async () => {\n setBusy(true);\n try {\n await client.removeAsset(id, { confirm: asset.usage.length + asset.usageHidden > 0 });\n forgetAsset(client, id);\n setAsking(false);\n onDeleted();\n } catch (e) {\n setSaveError(e);\n } finally {\n setBusy(false);\n }\n }}\n >\n {asset.usage.length + asset.usageHidden ? (\n <div className=\"grid gap-1.5\">\n <p className=\"text-sm font-medium\">{t(\"media_delete_used\", { n: asset.usage.length + asset.usageHidden })}</p>\n <UsageList asset={asset} basePath={basePath} docHref={docHref} />\n </div>\n ) : null}\n </ConfirmDialog>\n </>\n );\n if (mobile)\n return (\n <Dialog open onOpenChange={(o) => !o && onClose()}>\n <DialogContent className=\"max-h-[92dvh] overflow-y-auto\">\n <DialogTitle className=\"sr-only\">{asset?.name ?? t(\"nav_media\")}</DialogTitle>\n <div className=\"grid gap-4\">{body}</div>\n </DialogContent>\n </Dialog>\n );\n return (\n <aside aria-label={asset?.name ?? t(\"nav_media\")} className=\"grid w-80 shrink-0 content-start gap-4 border-l p-4\">\n {body}\n </aside>\n );\n}\n\nexport function UsageList({ asset, basePath, docHref }: { asset: Pick<AssetDetail, \"usage\">; basePath: string; docHref?: CmsMediaProps[\"docHref\"] }) {\n const { me } = useCms();\n return (\n <ul className=\"divide-y rounded-md border text-sm\">\n {asset.usage.map((u) => (\n <li key={`${u.collection}/${u.slug}`} className=\"flex h-10 items-center gap-2 px-2.5\">\n <a href={docHref?.(u.collection, u.slug) ?? `${basePath}/${encodeURIComponent(u.collection)}/${encodeURIComponent(u.slug)}`} className=\"min-w-0 flex-1 truncate font-medium underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring\">\n {u.title}\n </a>\n <span className=\"text-xs text-muted-foreground\">{me?.collections.find((c) => c.slug === u.collection)?.label ?? u.collection}</span>\n <StateBadge state={u.status} />\n </li>\n ))}\n </ul>\n );\n}\n"
|
|
25
|
+
"content": "// agent-cms registry: cms-media (0.11.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// The media library: stores and folders on the left, files as a grid or a\n// list, a panel with one file's details (alt text, tags, where it is used),\n// uploads straight to the storage, and delete with a look at the documents\n// that use the file.\n\"use client\";\n\nimport * as React from \"react\";\nimport { Copy, Crosshair, Download, Folder, FolderPlus, LayoutGrid, Link as LinkIcon, List, Pencil, Replace, Search, Trash2, X } from \"lucide-react\";\nimport type { AssetDetail, AssetView, FolderTree } from \"@mainsoft/agent-cms/client\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@/components/ui/table\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport { AssetGrid, AssetThumb, folderOptions, kindName, kindTabs, SELECT_CLASS, storeLabel, UploadButton, UploadPanel, useAssetList, useUploads, type KindTab } from \"./cms-media-picker\";\nimport { errorMessage } from \"./cms-messages\";\nimport { ConfirmDialog, copyText, PageHeader, Segmented, StateBadge, StatusText, Who } from \"./cms-parts\";\nimport { fileSize } from \"./cms-upload\";\nimport { forgetAsset, useAsync, useCms, useDebounced, useIsMobile, useLocalStorage } from \"./use-cms\";\n\nexport interface CmsMediaProps {\n /** Where the admin screens live, for links to the documents that use a file. Default \"/admin\". */\n basePath?: string;\n docHref?: (collection: string, slug: string) => string;\n className?: string;\n}\n\nexport function CmsMedia({ basePath = \"/admin\", docHref, className }: CmsMediaProps) {\n const { client, t, me, locale } = useCms();\n const stores = me?.media?.stores ?? [];\n const tree = useAsync<FolderTree[]>(() => client.assetFolders(), [client]);\n const [where, setWhere] = React.useState<{ store: string | null; folder: string | null }>({ store: null, folder: null });\n const [kind, setKind] = React.useState<KindTab>(\"all\");\n const [text, setText] = React.useState(\"\");\n const [q, setQ] = React.useState(\"\");\n const [tag, setTag] = React.useState<string | null>(null);\n const [view, setView] = useLocalStorage<\"grid\" | \"list\">(\"cms-media-view\", \"grid\");\n const [openId, setOpenId] = React.useState<string | null>(null);\n const [newFolder, setNewFolder] = React.useState(false);\n const [importing, setImporting] = React.useState(false);\n const [dragging, setDragging] = React.useState(false);\n const applyQ = useDebounced(setQ, 250);\n const store = where.store ?? stores[0]?.name ?? null;\n const info = stores.find((s) => s.name === store);\n const list = useAssetList({ store, folder: where.folder, kind, q, tag }, !!me?.media);\n const refresh = () => {\n list.reload();\n tree.reload();\n };\n /** Bumped when the open file's content was replaced, so its panel loads it again. */\n const [stamp, setStamp] = React.useState(0);\n const uploads = useUploads((a) => {\n refresh();\n if (a.rev) (forgetAsset(client, a.id), setStamp((n) => n + 1));\n });\n const options = folderOptions(tree.data ?? [], t);\n const tags = React.useMemo(() => [...new Set([...(tag ? [tag] : []), ...list.assets.flatMap((a) => a.tags)])].sort(), [list.assets, tag]);\n const total = list.counts ? (kind === \"all\" ? list.counts.all : kind === \"document\" ? list.counts.document + list.counts.other : list.counts[kind]) : 0;\n const upload = (files: File[]) => uploads.add(files, { store, folder: where.folder });\n const go = (s: string, folder: string | null) => {\n setWhere({ store: s, folder });\n setOpenId(null);\n };\n\n if (me && !me.media) return <StatusText className=\"p-6\">{t(\"media_empty\")}</StatusText>;\n\n return (\n <div className={cn(\"flex min-h-full flex-col\", className)}>\n <PageHeader title={t(\"nav_media\")}>\n {info?.can.write ? (\n <>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" aria-label={t(\"media_import\")} onClick={() => setImporting(true)}>\n <LinkIcon aria-hidden className=\"h-4 w-4\" />\n <span className=\"hidden lg:inline\">{t(\"media_import\")}</span>\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => setNewFolder(true)}>\n <FolderPlus aria-hidden className=\"h-4 w-4\" />\n {t(\"media_new_folder\")}\n </Button>\n <UploadButton size=\"sm\" accept={info.accept} onFiles={upload} />\n </>\n ) : null}\n </PageHeader>\n <div className=\"flex min-h-0 flex-1\">\n <nav aria-label={t(\"media_folders\")} className=\"hidden w-52 shrink-0 border-r p-3 md:block\">\n {(tree.data ?? []).map((s) => (\n <div key={s.store} className=\"mb-4\">\n <h2 className=\"px-2 pb-1 text-xs font-medium text-muted-foreground\">{storeLabel(s, t)}</h2>\n <ul className=\"flex flex-col gap-0.5\">\n {[{ path: null as string | null, count: s.total }, ...s.folders].map((f) => {\n const on = store === s.store && where.folder === f.path;\n const depth = f.path ? f.path.split(\"/\").length - 1 : 0;\n return (\n <li key={f.path ?? \"\"}>\n <button\n type=\"button\"\n aria-current={on ? \"true\" : undefined}\n onClick={() => go(s.store, f.path)}\n style={{ paddingLeft: 8 + depth * 14 }}\n className={cn(\"flex h-8 w-full items-center gap-2 rounded-md pr-2 text-left text-sm outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring\", on && \"bg-accent font-medium\")}\n >\n <Folder aria-hidden className=\"h-4 w-4 shrink-0 text-muted-foreground\" />\n <span className=\"flex-1 truncate\">{f.path ? f.path.split(\"/\").pop() : t(\"all\")}</span>\n <span className=\"text-xs tabular-nums text-muted-foreground\">{f.count}</span>\n </button>\n </li>\n );\n })}\n </ul>\n </div>\n ))}\n </nav>\n <section\n className={cn(\"flex min-w-0 flex-1 flex-col\", dragging && \"bg-accent/40\")}\n onDragOver={(e) => {\n if (!info?.can.write || !e.dataTransfer.types.includes(\"Files\")) return;\n e.preventDefault();\n setDragging(true);\n }}\n onDragLeave={() => setDragging(false)}\n onDrop={(e) => {\n setDragging(false);\n if (!info?.can.write || !e.dataTransfer.files.length) return;\n e.preventDefault();\n upload(Array.from(e.dataTransfer.files));\n }}\n >\n <div className=\"flex flex-wrap items-center gap-2 border-b px-4 py-3 md:px-5\">\n {options.length > 1 ? (\n <select\n aria-label={t(\"media_folder\")}\n className={cn(SELECT_CLASS, \"w-full md:hidden\")}\n value={`${store ?? \"\"}:${where.folder ?? \"\"}`}\n onChange={(e) => {\n const o = options.find((x) => x.value === e.target.value);\n if (o) go(o.store, o.folder);\n }}\n >\n {options.map((o) => (\n <option key={o.value} value={o.value}>\n {o.label}\n </option>\n ))}\n </select>\n ) : null}\n <div className=\"relative min-w-[160px] flex-1 md:max-w-[260px]\">\n <Search aria-hidden className=\"pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground\" />\n <Input\n aria-label={t(\"media_search\")}\n placeholder={t(\"media_search\")}\n className=\"pl-8\"\n value={text}\n onChange={(e) => {\n setText(e.target.value);\n applyQ(e.target.value.trim());\n }}\n />\n </div>\n <Segmented label={t(\"media_kind\")} value={kind} onChange={setKind} options={kindTabs(list.counts, t)} className=\"max-w-full overflow-x-auto\" />\n <div className=\"ml-auto hidden items-center gap-2 md:flex\">\n {tags.length ? (\n <select aria-label={t(\"media_tag\")} className={cn(SELECT_CLASS, \"max-w-[140px]\")} value={tag ?? \"\"} onChange={(e) => setTag(e.target.value || null)}>\n <option value=\"\">{t(\"media_tag\")}</option>\n {tags.map((x) => (\n <option key={x} value={x}>\n {x}\n </option>\n ))}\n </select>\n ) : null}\n <Segmented\n label={t(\"media_view\")}\n value={view}\n onChange={setView}\n options={[\n { value: \"grid\", label: <LayoutGrid aria-label={t(\"media_view_grid\")} className=\"h-4 w-4\" /> },\n { value: \"list\", label: <List aria-label={t(\"media_view_list\")} className=\"h-4 w-4\" /> },\n ]}\n />\n </div>\n </div>\n <div className=\"flex-1 px-2.5 py-3 md:px-3.5\">\n {list.error ? <StatusText tone=\"error\">{errorMessage(list.error, t)}</StatusText> : null}\n {!list.loading && !list.assets.length && !list.error ? <p className=\"py-16 text-center text-sm text-muted-foreground\">{t(\"media_empty\")}</p> : null}\n {view === \"list\" && list.assets.length ? (\n <Table>\n <TableHeader>\n <TableRow>\n <TableHead>{t(\"media_col_name\")}</TableHead>\n <TableHead className=\"w-36\">{t(\"media_col_kind\")}</TableHead>\n <TableHead className=\"w-24 text-right\">{t(\"media_col_size\")}</TableHead>\n <TableHead className=\"w-32\">{t(\"media_col_updated\")}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {list.assets.map((a) => (\n <TableRow key={a.id} data-state={a.id === openId ? \"selected\" : undefined}>\n <TableCell className=\"max-w-0\">\n <button type=\"button\" aria-pressed={a.id === openId} onClick={() => setOpenId(a.id)} className=\"flex w-full items-center gap-2.5 rounded text-left outline-none focus-visible:ring-2 focus-visible:ring-ring\">\n <AssetThumb asset={a} className=\"aspect-square w-8 shrink-0 rounded [&>span]:hidden [&_svg]:h-4 [&_svg]:w-4\" />\n <span className=\"truncate font-medium\">{a.name}</span>\n </button>\n </TableCell>\n <TableCell className=\"text-muted-foreground\">{kindName(a, t)}</TableCell>\n <TableCell className=\"text-right tabular-nums\">{fileSize(a.size)}</TableCell>\n <TableCell className=\"tabular-nums text-muted-foreground\">{new Date(a.updatedAt).toLocaleDateString(locale)}</TableCell>\n </TableRow>\n ))}\n </TableBody>\n </Table>\n ) : (\n <AssetGrid assets={list.assets} selected={openId} onSelect={(a) => setOpenId(a.id === openId ? null : a.id)} className={openId ? \"xl:grid-cols-3\" : undefined} />\n )}\n </div>\n {list.assets.length ? (\n <footer className=\"flex items-center gap-3 border-t px-4 py-2.5 text-sm text-muted-foreground md:px-5\">\n <span className=\"tabular-nums\" role=\"status\">\n {t(\"media_count\", { total, shown: list.assets.length })}\n </span>\n {list.cursor ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => void list.more()}>\n {t(\"load_more\")}\n </Button>\n ) : null}\n </footer>\n ) : null}\n </section>\n {openId ? (\n <AssetPanel\n key={openId}\n id={openId}\n basePath={basePath}\n docHref={docHref}\n stamp={stamp}\n onReplace={(file) => uploads.add([file], { replace: openId })}\n onClose={() => setOpenId(null)}\n onChanged={(a) => list.setState((s) => ({ ...s, assets: s.assets.map((x) => (x.id === a.id ? { ...x, ...a } : x)) }))}\n onDeleted={() => {\n setOpenId(null);\n refresh();\n }}\n />\n ) : null}\n </div>\n <ImportDialog\n open={importing}\n onOpenChange={setImporting}\n onImport={async (url) => {\n const a = await client.importAsset({ url, store, folder: where.folder });\n refresh();\n setOpenId(a.id);\n }}\n />\n <NewFolderDialog\n open={newFolder}\n onOpenChange={setNewFolder}\n onCreate={async (name) => {\n const path = `${where.folder ? `${where.folder}/` : \"\"}${name}`;\n await client.createAssetFolder(path, store);\n tree.reload();\n setWhere({ store, folder: path });\n }}\n />\n <UploadPanel items={uploads.items} onRetry={uploads.retry} onRemove={uploads.remove} onClose={uploads.clear} />\n </div>\n );\n}\n\nexport function NewFolderDialog({ open, onOpenChange, onCreate }: { open: boolean; onOpenChange: (o: boolean) => void; onCreate: (name: string) => Promise<void> }) {\n const { t } = useCms();\n const [name, setName] = React.useState(\"\");\n const [error, setError] = React.useState<unknown>(null);\n const [busy, setBusy] = React.useState(false);\n React.useEffect(() => {\n if (open) (setName(\"\"), setError(null));\n }, [open]);\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[400px]\">\n <form\n className=\"grid gap-4\"\n onSubmit={(e) => {\n e.preventDefault();\n if (!name.trim()) return;\n setBusy(true);\n onCreate(name.trim()).then(\n () => (setBusy(false), onOpenChange(false)),\n (err) => (setBusy(false), setError(err))\n );\n }}\n >\n <DialogHeader>\n <DialogTitle>{t(\"media_new_folder\")}</DialogTitle>\n </DialogHeader>\n <div className=\"grid gap-1.5\">\n <Label htmlFor=\"cms-folder-name\">{t(\"media_folder_name\")}</Label>\n <Input id=\"cms-folder-name\" autoFocus value={name} onChange={(e) => setName(e.target.value)} aria-invalid={error ? true : undefined} />\n {error ? <StatusText tone=\"error\">{errorMessage(error, t)}</StatusText> : null}\n </div>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => onOpenChange(false)}>\n {t(\"cancel\")}\n </Button>\n <Button type=\"submit\" disabled={busy || !name.trim()}>\n {t(\"create\")}\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n}\n\n/** Fetch a file from a public https address into the folder that is open. The server refuses addresses inside the network. */\nfunction ImportDialog({ open, onOpenChange, onImport }: { open: boolean; onOpenChange: (o: boolean) => void; onImport: (url: string) => Promise<void> }) {\n const { t } = useCms();\n const [url, setUrl] = React.useState(\"\");\n const [error, setError] = React.useState<unknown>(null);\n const [busy, setBusy] = React.useState(false);\n React.useEffect(() => {\n if (open) (setUrl(\"\"), setError(null));\n }, [open]);\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[440px]\">\n <form\n className=\"grid gap-4\"\n onSubmit={(e) => {\n e.preventDefault();\n if (!url.trim()) return;\n setBusy(true);\n onImport(url.trim()).then(\n () => (setBusy(false), onOpenChange(false)),\n (err) => (setBusy(false), setError(err))\n );\n }}\n >\n <DialogHeader>\n <DialogTitle>{t(\"media_import\")}</DialogTitle>\n </DialogHeader>\n <div className=\"grid gap-1.5\">\n <Label htmlFor=\"cms-import-url\">{t(\"media_import_url\")}</Label>\n <Input id=\"cms-import-url\" type=\"url\" inputMode=\"url\" placeholder=\"https://\" autoFocus value={url} onChange={(e) => setUrl(e.target.value)} aria-invalid={error ? true : undefined} />\n {error ? <StatusText tone=\"error\">{errorMessage(error, t)}</StatusText> : null}\n </div>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => onOpenChange(false)}>\n {t(\"cancel\")}\n </Button>\n <Button type=\"submit\" disabled={busy || !url.trim()}>\n {t(\"media_import_go\")}\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n}\n\n// ── one file ─────────────────────────────────────────────────────────────────\n\nexport interface AssetPanelProps {\n id: string;\n basePath: string;\n docHref?: CmsMediaProps[\"docHref\"];\n onClose: () => void;\n onChanged: (a: AssetView) => void;\n onDeleted: () => void;\n /** Send this file as the new content of the open one. Without it there is no \"Replace\" button. */\n onReplace?: (file: File) => void;\n /** Change it to load the file again (its content was replaced). */\n stamp?: number;\n}\n\n/** Arrow keys move the focal point by this much (Shift: five times). */\nconst FOCAL_STEP = 0.02;\n\nexport function AssetPanel({ id, basePath, docHref, onClose, onChanged, onDeleted, onReplace, stamp = 0 }: AssetPanelProps) {\n const { client, t, me, appUrl, slots, locale } = useCms();\n const mobile = useIsMobile();\n const { data: asset, error, setData } = useAsync<AssetDetail>(() => client.asset(id), [client, id, stamp]);\n /** The file chosen as new content, waiting for a yes. */\n const [incoming, setIncoming] = React.useState<File | null>(null);\n const replaceInput = React.useRef<HTMLInputElement>(null);\n /** Setting the focal point (the picture takes clicks). */\n const [aiming, setAiming] = React.useState(false);\n const [alt, setAlt] = React.useState<string | null>(null);\n const [tagText, setTagText] = React.useState(\"\");\n const [saveError, setSaveError] = React.useState<unknown>(null);\n const [asking, setAsking] = React.useState(false);\n const [busy, setBusy] = React.useState(false);\n /** The name being typed while renaming (null: not renaming). */\n const [naming, setNaming] = React.useState<string | null>(null);\n const rename = async () => {\n const name = naming?.trim();\n setNaming(null);\n if (!name || !asset || name === asset.name) return;\n try {\n // The server keeps the extension, so the file's type cannot change by renaming.\n const next = await client.moveAsset(id, { name });\n forgetAsset(client, id);\n setData((d) => (d ? { ...d, ...next } : d));\n onChanged(next);\n setSaveError(null);\n } catch (e) {\n setSaveError(e);\n }\n };\n const store = me?.media?.stores.find((s) => s.name === asset?.store);\n const can = store?.can;\n const save = async (patch: { alt?: string; tags?: string[]; focal?: { x: number; y: number } | null }) => {\n try {\n const next = await client.updateAsset(id, patch);\n forgetAsset(client, id);\n setData((d) => (d ? { ...d, ...next } : d));\n onChanged(next);\n setSaveError(null);\n } catch (e) {\n setSaveError(e);\n }\n };\n const focal = asset && asset.focalX !== null && asset.focalY !== null ? { x: asset.focalX, y: asset.focalY } : null;\n const point = focal ?? { x: 0.5, y: 0.5 };\n const body = !asset ? (\n <StatusText tone={error ? \"error\" : \"muted\"}>{error ? errorMessage(error, t) : t(\"loading\")}</StatusText>\n ) : (\n <>\n <div className=\"flex items-center gap-2\">\n <div className=\"min-w-0 flex-1\">\n {naming !== null ? (\n <Input\n aria-label={t(\"media_rename\")}\n autoFocus\n className=\"h-8\"\n value={naming}\n onChange={(e) => setNaming(e.target.value)}\n onBlur={() => void rename()}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") void rename();\n if (e.key === \"Escape\") (e.stopPropagation(), setNaming(null));\n }}\n />\n ) : (\n <h2 className=\"truncate font-semibold\">{asset.name}</h2>\n )}\n <p className=\"truncate text-xs text-muted-foreground\">\n {store ? storeLabel(store, t) : asset.store}\n {asset.folder ? ` / ${asset.folder}` : \"\"}\n </p>\n </div>\n {can?.delete && naming === null ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-8 w-8\" aria-label={t(\"media_rename\")} onClick={() => setNaming(asset.name)}>\n <Pencil aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : null}\n {mobile ? null : (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-8 w-8\" aria-label={t(\"close\")} onClick={onClose}>\n <X aria-hidden className=\"h-4 w-4\" />\n </Button>\n )}\n </div>\n {asset.kind === \"video\" ? (\n <video controls preload=\"metadata\" src={client.fileUrl(asset)} poster={asset.thumbKey ? client.fileUrl(asset, { thumb: true }) : undefined} className=\"aspect-video w-full rounded-md border bg-black\" />\n ) : asset.kind === \"audio\" ? (\n <audio controls preload=\"metadata\" src={client.fileUrl(asset)} className=\"w-full\" />\n ) : asset.kind === \"image\" ? (\n <div className=\"grid gap-1.5\">\n <div className=\"flex justify-center overflow-hidden rounded-md border bg-muted\">\n {/* The box is exactly the picture, so a place in the box is a place in the picture. */}\n <div className=\"relative\">\n {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions -- the point itself is a button that takes the arrow keys */}\n <img\n src={client.fileUrl(asset)}\n alt={asset.alt}\n className={cn(\"block max-h-64 max-w-full\", aiming && \"cursor-crosshair\")}\n onClick={\n aiming\n ? (e) => {\n const box = e.currentTarget.getBoundingClientRect();\n if (box.width && box.height) void save({ focal: { x: (e.clientX - box.left) / box.width, y: (e.clientY - box.top) / box.height } });\n }\n : undefined\n }\n />\n {aiming || focal ? (\n <button\n type=\"button\"\n disabled={!aiming}\n aria-label={t(\"media_focal_at\", { x: Math.round(point.x * 100), y: Math.round(point.y * 100) })}\n className={cn(\n \"absolute h-5 w-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-primary/80 shadow outline-none ring-1 ring-black/40 focus-visible:ring-2 focus-visible:ring-ring\",\n !aiming && \"pointer-events-none h-3 w-3\",\n aiming && !focal && \"border-dashed bg-primary/40\"\n )}\n style={{ left: `${point.x * 100}%`, top: `${point.y * 100}%` }}\n onKeyDown={(e) => {\n const d = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[e.key];\n if (!d) return;\n e.preventDefault();\n const k = FOCAL_STEP * (e.shiftKey ? 5 : 1);\n void save({ focal: { x: Math.min(1, Math.max(0, point.x + d[0] * k)), y: Math.min(1, Math.max(0, point.y + d[1] * k)) } });\n }}\n />\n ) : null}\n </div>\n </div>\n {aiming ? (\n <p className=\"flex items-start gap-2 text-xs text-muted-foreground\">\n <span className=\"flex-1\">{t(\"media_focal_help\")}</span>\n {focal ? (\n <button type=\"button\" className=\"shrink-0 rounded-sm underline underline-offset-2 outline-none focus-visible:ring-2 focus-visible:ring-ring\" onClick={() => void save({ focal: null })}>\n {t(\"media_focal_clear\")}\n </button>\n ) : null}\n </p>\n ) : null}\n </div>\n ) : (\n <AssetThumb asset={asset} className=\"aspect-video w-full\" />\n )}\n <div className=\"flex flex-wrap items-center gap-1.5\">\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-8 px-2.5\" onClick={() => void copyText(asset.publicUrl ?? (/^https?:/.test(asset.href) ? asset.href : `${appUrl}${asset.href}`))}>\n <Copy aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"media_copy_url\")}\n </Button>\n {/* A plain link with the button's look: `asChild` exists only in the Radix flavour of shadcn/ui. */}\n <a href={client.fileUrl(asset, { download: true })} className={buttonVariants({ variant: \"outline\", size: \"sm\", className: \"h-8 px-2.5\" })}>\n <Download aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"media_download\")}\n </a>\n {can?.write && asset.kind === \"image\" && asset.mime !== \"image/svg+xml\" ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" aria-pressed={aiming} className={cn(\"h-8 px-2.5\", aiming && \"bg-muted\")} onClick={() => setAiming((v) => !v)}>\n <Crosshair aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"media_focal\")}\n </Button>\n ) : null}\n {can?.delete && onReplace ? (\n <>\n <input\n ref={replaceInput}\n type=\"file\"\n hidden\n // The address keeps its ending, so only the same kind of file is offered.\n accept={/\\.[a-z0-9]+$/i.exec(asset.name)?.[0] ?? asset.mime}\n onChange={(e) => {\n setIncoming(e.target.files?.[0] ?? null);\n e.target.value = \"\";\n }}\n />\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-8 px-2.5\" onClick={() => replaceInput.current?.click()}>\n <Replace aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"media_replace\")}\n </Button>\n </>\n ) : null}\n <span className=\"flex-1\" />\n {can?.delete ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-8 px-2.5 text-destructive hover:text-destructive\" onClick={() => setAsking(true)}>\n <Trash2 aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"action_delete\")}\n </Button>\n ) : null}\n </div>\n <div className=\"grid gap-1.5\">\n <div className=\"flex min-h-6 items-center\">\n <Label htmlFor=\"cms-asset-alt\" className=\"flex-1\">\n {t(\"media_alt\")}\n </Label>\n {can?.write ? slots.assetAlt?.(asset, { setAlt }) : null}\n </div>\n <Textarea\n id=\"cms-asset-alt\"\n rows={2}\n readOnly={!can?.write}\n value={alt ?? asset.alt}\n onChange={(e) => setAlt(e.target.value)}\n onBlur={() => {\n if (alt !== null && alt.trim() !== asset.alt) void save({ alt: alt.trim() });\n }}\n />\n </div>\n <div className=\"grid gap-1.5\">\n <Label htmlFor=\"cms-asset-tag\">{t(\"media_tags\")}</Label>\n <div className=\"flex min-h-9 flex-wrap items-center gap-1 rounded-md border border-input px-2 py-1 focus-within:ring-2 focus-within:ring-ring\">\n {asset.tags.map((x) => (\n <span key={x} className=\"inline-flex h-6 items-center gap-1 rounded bg-muted pl-2 pr-1 text-xs\">\n {x}\n {can?.write ? (\n <button type=\"button\" aria-label={t(\"media_tag_remove\", { tag: x })} className=\"rounded outline-none hover:bg-background focus-visible:ring-2 focus-visible:ring-ring\" onClick={() => void save({ tags: asset.tags.filter((y) => y !== x) })}>\n <X aria-hidden className=\"h-3 w-3 text-muted-foreground\" />\n </button>\n ) : null}\n </span>\n ))}\n {can?.write ? (\n <input\n id=\"cms-asset-tag\"\n aria-label={t(\"media_tag_add\")}\n value={tagText}\n onChange={(e) => setTagText(e.target.value)}\n onKeyDown={(e) => {\n const v = tagText.trim().replace(/,$/, \"\");\n if ((e.key === \"Enter\" || e.key === \",\") && v) {\n e.preventDefault();\n setTagText(\"\");\n if (!asset.tags.includes(v)) void save({ tags: [...asset.tags, v] });\n }\n }}\n className=\"h-6 min-w-[60px] flex-1 bg-transparent text-sm outline-none\"\n />\n ) : null}\n </div>\n </div>\n {saveError ? <StatusText tone=\"error\">{errorMessage(saveError, t)}</StatusText> : null}\n <dl className=\"grid grid-cols-[84px_1fr] gap-y-2 text-sm\">\n <dt className=\"text-muted-foreground\">{t(\"media_kind\")}</dt>\n <dd>{kindName(asset, t)}</dd>\n <dt className=\"text-muted-foreground\">{t(\"media_size\")}</dt>\n <dd className=\"tabular-nums\">{`${fileSize(asset.size)}${asset.width && asset.height ? `, ${asset.width}×${asset.height}` : \"\"}`}</dd>\n <dt className=\"text-muted-foreground\">{t(\"media_by\")}</dt>\n <dd className=\"min-w-0\">\n <Who kind={asset.createdByKind} label={asset.createdBy} agent={asset.createdByAgent} />\n </dd>\n <dt className=\"text-muted-foreground\">{t(\"media_at\")}</dt>\n <dd className=\"tabular-nums\">{new Date(asset.createdAt).toLocaleDateString(locale)}</dd>\n </dl>\n <div className=\"grid gap-1.5\">\n <h3 className=\"text-sm font-medium\">\n {t(\"media_usage\")} <span className=\"font-normal tabular-nums text-muted-foreground\">{asset.usage.length + asset.usageHidden}</span>\n </h3>\n {asset.usage.length ? <UsageList asset={asset} basePath={basePath} docHref={docHref} /> : asset.usageHidden ? null : <p className=\"text-sm text-muted-foreground\">{t(\"none\")}</p>}\n {asset.usageHidden ? <p className=\"text-xs text-muted-foreground\">{t(\"media_usage_hidden\", { n: asset.usageHidden })}</p> : null}\n </div>\n <ConfirmDialog\n open={!!incoming}\n onOpenChange={(o) => !o && setIncoming(null)}\n title={t(\"media_replace_title\", { name: asset.name })}\n description={t(\"media_replace_text\")}\n confirmLabel={t(\"media_replace\")}\n onConfirm={() => {\n if (incoming) onReplace?.(incoming);\n setIncoming(null);\n }}\n >\n {incoming ? (\n <div className=\"grid gap-1.5 text-sm\">\n <p className=\"truncate\">\n <span className=\"text-muted-foreground\">{t(\"media_replace_with\")}</span> {incoming.name} <span className=\"tabular-nums text-muted-foreground\">({fileSize(incoming.size)})</span>\n </p>\n {asset.usage.length + asset.usageHidden ? <p className=\"font-medium\">{t(\"media_replace_used\", { n: asset.usage.length + asset.usageHidden })}</p> : null}\n </div>\n ) : null}\n </ConfirmDialog>\n <ConfirmDialog\n open={asking}\n onOpenChange={setAsking}\n title={t(\"media_delete_title\", { n: 1 })}\n description={t(\"media_delete_gone\")}\n confirmLabel={t(\"action_delete\")}\n destructive\n busy={busy}\n error={saveError && asking ? errorMessage(saveError, t) : undefined}\n onConfirm={async () => {\n setBusy(true);\n try {\n await client.removeAsset(id, { confirm: asset.usage.length + asset.usageHidden > 0 });\n forgetAsset(client, id);\n setAsking(false);\n onDeleted();\n } catch (e) {\n setSaveError(e);\n } finally {\n setBusy(false);\n }\n }}\n >\n {asset.usage.length + asset.usageHidden ? (\n <div className=\"grid gap-1.5\">\n <p className=\"text-sm font-medium\">{t(\"media_delete_used\", { n: asset.usage.length + asset.usageHidden })}</p>\n <UsageList asset={asset} basePath={basePath} docHref={docHref} />\n </div>\n ) : null}\n </ConfirmDialog>\n </>\n );\n if (mobile)\n return (\n <Dialog open onOpenChange={(o) => !o && onClose()}>\n <DialogContent className=\"max-h-[92dvh] overflow-y-auto\">\n <DialogTitle className=\"sr-only\">{asset?.name ?? t(\"nav_media\")}</DialogTitle>\n <div className=\"grid gap-4\">{body}</div>\n </DialogContent>\n </Dialog>\n );\n return (\n <aside aria-label={asset?.name ?? t(\"nav_media\")} className=\"grid w-80 shrink-0 content-start gap-4 border-l p-4\">\n {body}\n </aside>\n );\n}\n\nexport function UsageList({ asset, basePath, docHref }: { asset: Pick<AssetDetail, \"usage\">; basePath: string; docHref?: CmsMediaProps[\"docHref\"] }) {\n const { me } = useCms();\n return (\n <ul className=\"divide-y rounded-md border text-sm\">\n {asset.usage.map((u) => (\n <li key={`${u.collection}/${u.slug}`} className=\"flex h-10 items-center gap-2 px-2.5\">\n <a href={docHref?.(u.collection, u.slug) ?? `${basePath}/${encodeURIComponent(u.collection)}/${encodeURIComponent(u.slug)}`} className=\"min-w-0 flex-1 truncate font-medium underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring\">\n {u.title}\n </a>\n <span className=\"text-xs text-muted-foreground\">{me?.collections.find((c) => c.slug === u.collection)?.label ?? u.collection}</span>\n <StateBadge state={u.status} />\n </li>\n ))}\n </ul>\n );\n}\n"
|
|
26
26
|
}
|
|
27
27
|
]
|
|
28
28
|
}
|
|
@@ -186,6 +186,10 @@
|
|
|
186
186
|
"path": "registry/cms/cms-flow.tsx",
|
|
187
187
|
"type": "registry:component"
|
|
188
188
|
},
|
|
189
|
+
{
|
|
190
|
+
"path": "registry/cms/cms-body-tools.tsx",
|
|
191
|
+
"type": "registry:component"
|
|
192
|
+
},
|
|
189
193
|
{
|
|
190
194
|
"path": "registry/cms/cms-paste.ts",
|
|
191
195
|
"type": "registry:lib"
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/storage-vercel-blob.ts
|
|
31
|
+
var storage_vercel_blob_exports = {};
|
|
32
|
+
__export(storage_vercel_blob_exports, {
|
|
33
|
+
VercelBlobError: () => VercelBlobError,
|
|
34
|
+
vercelBlobStorage: () => vercelBlobStorage
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(storage_vercel_blob_exports);
|
|
37
|
+
var VercelBlobError = class extends Error {
|
|
38
|
+
constructor(op, message, options) {
|
|
39
|
+
super(`Vercel Blob ${op} failed: ${message}`, options);
|
|
40
|
+
this.op = op;
|
|
41
|
+
this.name = "VercelBlobError";
|
|
42
|
+
}
|
|
43
|
+
op;
|
|
44
|
+
};
|
|
45
|
+
var MAX_LINK_MS = 7 * 24 * 3600 * 1e3 - 6e4;
|
|
46
|
+
var TOKEN_LIFE_MS = 2 * 3600 * 1e3;
|
|
47
|
+
var NO_PARTS = "Vercel Blob takes a file in one request; uploads in parts are not supported on this store";
|
|
48
|
+
var notFound = (e, b) => !!e && typeof e === "object" && (!!b?.BlobNotFoundError && e instanceof b.BlobNotFoundError || e.name === "BlobNotFoundError" || e.constructor?.name === "BlobNotFoundError");
|
|
49
|
+
var Missing = class extends Error {
|
|
50
|
+
};
|
|
51
|
+
var text = (e) => e instanceof Error ? e.message : String(e);
|
|
52
|
+
var iso = (d) => d ? new Date(d).toISOString() : null;
|
|
53
|
+
var hasExt = (key) => /\.[A-Za-z0-9]{1,10}$/.test(key.split("/").pop() ?? "");
|
|
54
|
+
var maxAge = (cacheControl) => {
|
|
55
|
+
const m = /max-age=(\d+)/.exec(cacheControl ?? "");
|
|
56
|
+
return m ? { cacheControlMaxAge: Number(m[1]) } : {};
|
|
57
|
+
};
|
|
58
|
+
function vercelBlobStorage(o) {
|
|
59
|
+
if (o.access !== "public" && o.access !== "private") throw new Error('agent-cms: vercelBlobStorage({ access }) must be "public" or "private", the way the Blob store was created');
|
|
60
|
+
const storeId = /^vercel_blob_rw_([A-Za-z0-9]+)_/.exec(o.token ?? "")?.[1];
|
|
61
|
+
if (!storeId) throw new Error("agent-cms: vercelBlobStorage({ token }) needs the store's read-write token (BLOB_READ_WRITE_TOKEN, it starts with vercel_blob_rw_)");
|
|
62
|
+
const { token, access } = o;
|
|
63
|
+
const prefix = o.prefix ? `${o.prefix.replace(/^\/+|\/+$/g, "")}/` : "";
|
|
64
|
+
const doFetch = o.fetch ?? fetch;
|
|
65
|
+
const full = (key) => prefix + key;
|
|
66
|
+
const strip = (k) => k.startsWith(prefix) ? k.slice(prefix.length) : k;
|
|
67
|
+
const fixed = { access, token, addRandomSuffix: false, allowOverwrite: true };
|
|
68
|
+
let lib = o.blob ? Promise.resolve(o.blob) : null;
|
|
69
|
+
const load = () => lib ??= import("@vercel/blob").then(
|
|
70
|
+
(m) => m,
|
|
71
|
+
(e) => {
|
|
72
|
+
lib = null;
|
|
73
|
+
throw new Error(`agent-cms: vercelBlobStorage() could not load "@vercel/blob" (npm install @vercel/blob): ${text(e)}`);
|
|
74
|
+
}
|
|
75
|
+
);
|
|
76
|
+
async function call(op, fn) {
|
|
77
|
+
const b = await load();
|
|
78
|
+
try {
|
|
79
|
+
return await fn(b);
|
|
80
|
+
} catch (e) {
|
|
81
|
+
if (notFound(e, b)) throw new Missing(text(e));
|
|
82
|
+
throw new VercelBlobError(op, text(e), { cause: e });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const signers = /* @__PURE__ */ new Map();
|
|
86
|
+
async function signer(operation, needMs) {
|
|
87
|
+
const cached = await signers.get(operation)?.catch(() => null);
|
|
88
|
+
if (cached && cached.validUntil - Date.now() >= needMs + 3e4) return cached;
|
|
89
|
+
const made = call("sign", (b) => b.issueSignedToken({ token, operations: [operation], validUntil: Date.now() + Math.min(MAX_LINK_MS + 3e4, Math.max(needMs + 6e5, TOKEN_LIFE_MS)) }));
|
|
90
|
+
signers.set(operation, made);
|
|
91
|
+
return made;
|
|
92
|
+
}
|
|
93
|
+
async function presign(operation, key, expires, more = {}) {
|
|
94
|
+
const ms = Math.min(Math.max(1, expires) * 1e3, MAX_LINK_MS);
|
|
95
|
+
const t = await signer(operation, ms);
|
|
96
|
+
return (await call("sign", (b) => b.presignUrl(t, { operation, pathname: full(key), access, validUntil: Date.now() + ms, ...more }))).presignedUrl;
|
|
97
|
+
}
|
|
98
|
+
async function head(key) {
|
|
99
|
+
try {
|
|
100
|
+
const h = await call("head", (b) => b.head(full(key), { token }));
|
|
101
|
+
return { key, size: h.size, mime: h.contentType ?? null, etag: h.etag ?? null, lastModified: iso(h.uploadedAt) };
|
|
102
|
+
} catch (e) {
|
|
103
|
+
if (e instanceof Missing) return null;
|
|
104
|
+
throw e;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
async function copy(from, to, mime) {
|
|
108
|
+
const contentType = mime ?? (hasExt(to) ? void 0 : (await head(from))?.mime ?? void 0);
|
|
109
|
+
await call("copy", (b) => b.copy(full(from), full(to), { ...fixed, ...contentType ? { contentType } : {} }));
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
options: o,
|
|
113
|
+
multipart: false,
|
|
114
|
+
async presignPut(key, p) {
|
|
115
|
+
const url = await presign("put", key, p.expires, { addRandomSuffix: false, allowOverwrite: true, ...p.size ? { maximumSizeInBytes: p.size } : {}, ...maxAge(p.cacheControl) });
|
|
116
|
+
return { url, headers: { "content-type": p.mime } };
|
|
117
|
+
},
|
|
118
|
+
async put(key, body, p) {
|
|
119
|
+
if (key.endsWith("/")) {
|
|
120
|
+
await call("createFolder", (b) => b.createFolder(full(key).replace(/\/+$/, ""), { token, access })).catch(async (e) => {
|
|
121
|
+
if (!await head(key)) throw e;
|
|
122
|
+
});
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (!body.length) {
|
|
126
|
+
const signed = await this.presignPut(key, { ...p, expires: 300 });
|
|
127
|
+
const res = await doFetch(signed.url, { method: "PUT", headers: signed.headers, body });
|
|
128
|
+
if (!res.ok) throw new VercelBlobError("put", `${res.status} ${(await res.text().catch(() => "")).slice(0, 200)}`);
|
|
129
|
+
await res.arrayBuffer().catch(() => {
|
|
130
|
+
});
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
await call("put", (b) => b.put(full(key), new Blob([body]), { ...fixed, contentType: p.mime, ...maxAge(p.cacheControl) }));
|
|
134
|
+
},
|
|
135
|
+
async createMultipart() {
|
|
136
|
+
throw new VercelBlobError("createMultipart", NO_PARTS);
|
|
137
|
+
},
|
|
138
|
+
async presignPart() {
|
|
139
|
+
throw new VercelBlobError("presignPart", NO_PARTS);
|
|
140
|
+
},
|
|
141
|
+
async listParts() {
|
|
142
|
+
return [];
|
|
143
|
+
},
|
|
144
|
+
async completeMultipart() {
|
|
145
|
+
throw new VercelBlobError("completeMultipart", NO_PARTS);
|
|
146
|
+
},
|
|
147
|
+
async abortMultipart() {
|
|
148
|
+
},
|
|
149
|
+
head,
|
|
150
|
+
async readStart(key, bytes) {
|
|
151
|
+
if (bytes <= 0) return new Uint8Array();
|
|
152
|
+
try {
|
|
153
|
+
const got = await call("read", (b) => b.get(full(key), { access, token, headers: { range: `bytes=0-${bytes - 1}` } }));
|
|
154
|
+
if (!got) return null;
|
|
155
|
+
if (!got.stream) return new Uint8Array();
|
|
156
|
+
return new Uint8Array(await new Response(got.stream).arrayBuffer()).slice(0, bytes);
|
|
157
|
+
} catch (e) {
|
|
158
|
+
if (e instanceof Missing) return null;
|
|
159
|
+
const h = await head(key);
|
|
160
|
+
if (!h) return null;
|
|
161
|
+
if (h.size === 0) return new Uint8Array();
|
|
162
|
+
throw e;
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
async presignGet(key, g) {
|
|
166
|
+
const url = await presign("get", key, g.expires);
|
|
167
|
+
return g.download ? `${url}&download=1` : url;
|
|
168
|
+
},
|
|
169
|
+
publicUrl(key) {
|
|
170
|
+
return access === "public" ? `https://${storeId.toLowerCase()}.public.blob.vercel-storage.com/${full(key).split("/").map(encodeURIComponent).join("/")}` : null;
|
|
171
|
+
},
|
|
172
|
+
copy: (from, to) => copy(from, to),
|
|
173
|
+
/**
|
|
174
|
+
* A file a browser sent is stored as a download. Copying it onto itself
|
|
175
|
+
* from the server makes Blob apply its usual rule (pictures, PDF, video
|
|
176
|
+
* and sound open in the browser), in about a second even for large files.
|
|
177
|
+
*/
|
|
178
|
+
async settle(key, p) {
|
|
179
|
+
if (p.disposition?.startsWith("attachment")) return;
|
|
180
|
+
await copy(key, key, p.mime);
|
|
181
|
+
},
|
|
182
|
+
async delete(key) {
|
|
183
|
+
await call("delete", (b) => b.del(full(key), { token }));
|
|
184
|
+
},
|
|
185
|
+
async list(l = {}) {
|
|
186
|
+
const r = await call("list", (b) => b.list({ token, prefix: prefix + (l.prefix ?? ""), mode: l.delimiter ? "folded" : "expanded", limit: l.limit ?? 1e3, ...l.cursor ? { cursor: l.cursor } : {} }));
|
|
187
|
+
return {
|
|
188
|
+
objects: r.blobs.map((x) => ({ key: strip(x.pathname), size: x.size, mime: null, etag: x.etag ?? null, lastModified: iso(x.uploadedAt) })),
|
|
189
|
+
prefixes: (r.folders ?? []).map(strip),
|
|
190
|
+
cursor: r.hasMore && r.cursor ? r.cursor : null
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
196
|
+
0 && (module.exports = {
|
|
197
|
+
VercelBlobError,
|
|
198
|
+
vercelBlobStorage
|
|
199
|
+
});
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { StorageAdapter } from './storage.cjs';
|
|
2
|
+
import './types.cjs';
|
|
3
|
+
import 'zod';
|
|
4
|
+
import './errors.cjs';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Vercel Blob as a `StorageAdapter` (`npm install @vercel/blob`).
|
|
8
|
+
*
|
|
9
|
+
* import { vercelBlobStorage } from "@mainsoft/agent-cms/storage-vercel-blob";
|
|
10
|
+
*
|
|
11
|
+
* createCms({
|
|
12
|
+
* media: {
|
|
13
|
+
* stores: {
|
|
14
|
+
* public: { visibility: "public", adapter: vercelBlobStorage({ token: process.env.BLOB_READ_WRITE_TOKEN!, access: "public" }) },
|
|
15
|
+
* },
|
|
16
|
+
* },
|
|
17
|
+
* });
|
|
18
|
+
*
|
|
19
|
+
* `access` is how the Blob store was created (public or private); a private
|
|
20
|
+
* store is read through signed links only.
|
|
21
|
+
*
|
|
22
|
+
* How it differs from S3-compatible storage:
|
|
23
|
+
* - A file goes up in ONE request, whatever its size (`multipart: false`).
|
|
24
|
+
* There are no parts to retry one by one and nothing to carry on after a
|
|
25
|
+
* reload: a failed upload starts again.
|
|
26
|
+
* - Blob decides the stored type from the file's extension and decides
|
|
27
|
+
* itself whether a file opens in the browser or downloads; `disposition`
|
|
28
|
+
* is not ours to set.
|
|
29
|
+
* - No CORS rule to configure: Blob answers browsers on any origin.
|
|
30
|
+
*
|
|
31
|
+
* Checked against real public and private Blob stores with @vercel/blob 2.9.0
|
|
32
|
+
* (2026-11-20). Only the package's documented calls are used.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/** The parts of `@vercel/blob` this adapter calls. */
|
|
36
|
+
interface VercelBlobApi {
|
|
37
|
+
put(pathname: string, body: unknown, o: Record<string, unknown>): Promise<{
|
|
38
|
+
pathname: string;
|
|
39
|
+
}>;
|
|
40
|
+
head(pathname: string, o: {
|
|
41
|
+
token: string;
|
|
42
|
+
}): Promise<{
|
|
43
|
+
size: number;
|
|
44
|
+
uploadedAt: Date | string;
|
|
45
|
+
pathname: string;
|
|
46
|
+
contentType?: string | null;
|
|
47
|
+
etag?: string | null;
|
|
48
|
+
}>;
|
|
49
|
+
get(pathname: string, o: Record<string, unknown>): Promise<{
|
|
50
|
+
statusCode: number;
|
|
51
|
+
stream: ReadableStream<Uint8Array> | null;
|
|
52
|
+
} | null>;
|
|
53
|
+
copy(from: string, to: string, o: Record<string, unknown>): Promise<unknown>;
|
|
54
|
+
del(pathname: string | string[], o: {
|
|
55
|
+
token: string;
|
|
56
|
+
}): Promise<void>;
|
|
57
|
+
list(o: Record<string, unknown>): Promise<{
|
|
58
|
+
blobs: {
|
|
59
|
+
pathname: string;
|
|
60
|
+
size: number;
|
|
61
|
+
uploadedAt: Date | string;
|
|
62
|
+
etag?: string | null;
|
|
63
|
+
}[];
|
|
64
|
+
folders?: string[];
|
|
65
|
+
cursor?: string;
|
|
66
|
+
hasMore: boolean;
|
|
67
|
+
}>;
|
|
68
|
+
createFolder(pathname: string, o: Record<string, unknown>): Promise<unknown>;
|
|
69
|
+
issueSignedToken(o: Record<string, unknown>): Promise<{
|
|
70
|
+
validUntil: number;
|
|
71
|
+
} & Record<string, unknown>>;
|
|
72
|
+
presignUrl(token: unknown, o: Record<string, unknown>): Promise<{
|
|
73
|
+
presignedUrl: string;
|
|
74
|
+
}>;
|
|
75
|
+
BlobNotFoundError?: abstract new (...args: never[]) => Error;
|
|
76
|
+
}
|
|
77
|
+
interface VercelBlobStorageOptions {
|
|
78
|
+
/** The store's read-write token (`BLOB_READ_WRITE_TOKEN`). Server only. */
|
|
79
|
+
token: string;
|
|
80
|
+
/** How the Blob store was created. */
|
|
81
|
+
access: "public" | "private";
|
|
82
|
+
/** Put every key under this folder of the store. */
|
|
83
|
+
prefix?: string;
|
|
84
|
+
fetch?: typeof fetch;
|
|
85
|
+
/** A stand-in for the `@vercel/blob` module (tests). */
|
|
86
|
+
blob?: VercelBlobApi;
|
|
87
|
+
}
|
|
88
|
+
declare class VercelBlobError extends Error {
|
|
89
|
+
readonly op: string;
|
|
90
|
+
constructor(op: string, message: string, options?: {
|
|
91
|
+
cause?: unknown;
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
declare function vercelBlobStorage(o: VercelBlobStorageOptions): StorageAdapter & {
|
|
95
|
+
readonly options: Readonly<VercelBlobStorageOptions>;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
export { type VercelBlobApi, VercelBlobError, type VercelBlobStorageOptions, vercelBlobStorage };
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { StorageAdapter } from './storage.js';
|
|
2
|
+
import './types.js';
|
|
3
|
+
import 'zod';
|
|
4
|
+
import './errors.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Vercel Blob as a `StorageAdapter` (`npm install @vercel/blob`).
|
|
8
|
+
*
|
|
9
|
+
* import { vercelBlobStorage } from "@mainsoft/agent-cms/storage-vercel-blob";
|
|
10
|
+
*
|
|
11
|
+
* createCms({
|
|
12
|
+
* media: {
|
|
13
|
+
* stores: {
|
|
14
|
+
* public: { visibility: "public", adapter: vercelBlobStorage({ token: process.env.BLOB_READ_WRITE_TOKEN!, access: "public" }) },
|
|
15
|
+
* },
|
|
16
|
+
* },
|
|
17
|
+
* });
|
|
18
|
+
*
|
|
19
|
+
* `access` is how the Blob store was created (public or private); a private
|
|
20
|
+
* store is read through signed links only.
|
|
21
|
+
*
|
|
22
|
+
* How it differs from S3-compatible storage:
|
|
23
|
+
* - A file goes up in ONE request, whatever its size (`multipart: false`).
|
|
24
|
+
* There are no parts to retry one by one and nothing to carry on after a
|
|
25
|
+
* reload: a failed upload starts again.
|
|
26
|
+
* - Blob decides the stored type from the file's extension and decides
|
|
27
|
+
* itself whether a file opens in the browser or downloads; `disposition`
|
|
28
|
+
* is not ours to set.
|
|
29
|
+
* - No CORS rule to configure: Blob answers browsers on any origin.
|
|
30
|
+
*
|
|
31
|
+
* Checked against real public and private Blob stores with @vercel/blob 2.9.0
|
|
32
|
+
* (2026-11-20). Only the package's documented calls are used.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/** The parts of `@vercel/blob` this adapter calls. */
|
|
36
|
+
interface VercelBlobApi {
|
|
37
|
+
put(pathname: string, body: unknown, o: Record<string, unknown>): Promise<{
|
|
38
|
+
pathname: string;
|
|
39
|
+
}>;
|
|
40
|
+
head(pathname: string, o: {
|
|
41
|
+
token: string;
|
|
42
|
+
}): Promise<{
|
|
43
|
+
size: number;
|
|
44
|
+
uploadedAt: Date | string;
|
|
45
|
+
pathname: string;
|
|
46
|
+
contentType?: string | null;
|
|
47
|
+
etag?: string | null;
|
|
48
|
+
}>;
|
|
49
|
+
get(pathname: string, o: Record<string, unknown>): Promise<{
|
|
50
|
+
statusCode: number;
|
|
51
|
+
stream: ReadableStream<Uint8Array> | null;
|
|
52
|
+
} | null>;
|
|
53
|
+
copy(from: string, to: string, o: Record<string, unknown>): Promise<unknown>;
|
|
54
|
+
del(pathname: string | string[], o: {
|
|
55
|
+
token: string;
|
|
56
|
+
}): Promise<void>;
|
|
57
|
+
list(o: Record<string, unknown>): Promise<{
|
|
58
|
+
blobs: {
|
|
59
|
+
pathname: string;
|
|
60
|
+
size: number;
|
|
61
|
+
uploadedAt: Date | string;
|
|
62
|
+
etag?: string | null;
|
|
63
|
+
}[];
|
|
64
|
+
folders?: string[];
|
|
65
|
+
cursor?: string;
|
|
66
|
+
hasMore: boolean;
|
|
67
|
+
}>;
|
|
68
|
+
createFolder(pathname: string, o: Record<string, unknown>): Promise<unknown>;
|
|
69
|
+
issueSignedToken(o: Record<string, unknown>): Promise<{
|
|
70
|
+
validUntil: number;
|
|
71
|
+
} & Record<string, unknown>>;
|
|
72
|
+
presignUrl(token: unknown, o: Record<string, unknown>): Promise<{
|
|
73
|
+
presignedUrl: string;
|
|
74
|
+
}>;
|
|
75
|
+
BlobNotFoundError?: abstract new (...args: never[]) => Error;
|
|
76
|
+
}
|
|
77
|
+
interface VercelBlobStorageOptions {
|
|
78
|
+
/** The store's read-write token (`BLOB_READ_WRITE_TOKEN`). Server only. */
|
|
79
|
+
token: string;
|
|
80
|
+
/** How the Blob store was created. */
|
|
81
|
+
access: "public" | "private";
|
|
82
|
+
/** Put every key under this folder of the store. */
|
|
83
|
+
prefix?: string;
|
|
84
|
+
fetch?: typeof fetch;
|
|
85
|
+
/** A stand-in for the `@vercel/blob` module (tests). */
|
|
86
|
+
blob?: VercelBlobApi;
|
|
87
|
+
}
|
|
88
|
+
declare class VercelBlobError extends Error {
|
|
89
|
+
readonly op: string;
|
|
90
|
+
constructor(op: string, message: string, options?: {
|
|
91
|
+
cause?: unknown;
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
declare function vercelBlobStorage(o: VercelBlobStorageOptions): StorageAdapter & {
|
|
95
|
+
readonly options: Readonly<VercelBlobStorageOptions>;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
export { type VercelBlobApi, VercelBlobError, type VercelBlobStorageOptions, vercelBlobStorage };
|