@kidecms/core 0.18.0 → 0.19.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/admin/components/AssetsGrid.tsx +89 -15
- package/admin/components/DocumentActions.tsx +85 -25
- package/admin/components/DocumentsDataTable.tsx +8 -1
- package/admin/components/ImageBrowseDialog.tsx +9 -2
- package/admin/components/ImagePicker.tsx +14 -3
- package/admin/components/InternalLinkPicker.tsx +6 -2
- package/admin/components/TreeItemsEditor.tsx +2 -0
- package/admin/components/Untitled +1 -0
- package/admin/lib/utils.ts +12 -0
- package/admin/views/edit/ReverseReferencesList.astro +8 -3
- package/core/api.ts +5 -0
- package/core/asset-usage.ts +283 -0
- package/core/assets.ts +93 -1
- package/core/generator.ts +5 -1
- package/core/image.ts +11 -2
- package/core/index.ts +4 -2
- package/core/values.ts +2 -2
- package/internals/integration.ts +4 -0
- package/internals/push.ts +10 -1
- package/internals/virtual.d.ts +4 -0
- package/middleware/auth.ts +1 -1
- package/package.json +1 -1
- package/routes/admin/assets/[id].astro +62 -37
- package/routes/api/asset-usage.ts +53 -0
- package/routes/api/assets/[id].ts +25 -4
- package/routes/api/img/[...path].ts +1 -1
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { eq, or, sql, type SQL } from "drizzle-orm";
|
|
2
|
+
|
|
3
|
+
import { getLabelField, type CMSConfig, type CollectionConfig, type FieldConfig } from "./define";
|
|
4
|
+
import { getDb } from "./runtime";
|
|
5
|
+
import { getSchema } from "./schema";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Where an asset is used. Structurally identical to the admin's `ReverseRef`
|
|
9
|
+
* so the existing "Referenced by" list component renders it unchanged.
|
|
10
|
+
*/
|
|
11
|
+
export type AssetUsageRef = {
|
|
12
|
+
collectionSlug: string;
|
|
13
|
+
collectionLabel: string;
|
|
14
|
+
docs: Array<{ _id: string; label: string }>;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export type AssetUsageResult = {
|
|
18
|
+
refs: AssetUsageRef[];
|
|
19
|
+
/**
|
|
20
|
+
* Collections whose scan failed (missing table, schema drift). Their documents
|
|
21
|
+
* were not searched, so `refs` may under-report. Never treat a non-empty
|
|
22
|
+
* `incomplete` as "not used" — that is how a referenced asset gets deleted.
|
|
23
|
+
*/
|
|
24
|
+
incomplete: string[];
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** Matching rows pulled per collection before attribution. Generous — a match is already rare. */
|
|
28
|
+
const SCAN_CAP = 1000;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The config is registered by `createCms()` so `assets.delete()` can check usage
|
|
32
|
+
* without every caller threading the config through.
|
|
33
|
+
*/
|
|
34
|
+
let usageConfig: CMSConfig | null = null;
|
|
35
|
+
|
|
36
|
+
export const setUsageConfig = (config: CMSConfig) => {
|
|
37
|
+
usageConfig = config;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export const getUsageConfig = (): CMSConfig | null => usageConfig;
|
|
41
|
+
|
|
42
|
+
/** Field types serialized to JSON in a single text column — matched by substring. */
|
|
43
|
+
const JSON_FIELD_TYPES = new Set(["richText", "content", "array", "json", "blocks"]);
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Can this field hold a storagePath anywhere inside it? Keeps the query narrow —
|
|
47
|
+
* a `blocks` field whose block types declare no image never gets scanned.
|
|
48
|
+
*/
|
|
49
|
+
const fieldCanHoldAsset = (field: FieldConfig, depth = 0): boolean => {
|
|
50
|
+
if (depth > 6) return false;
|
|
51
|
+
switch (field.type) {
|
|
52
|
+
case "image":
|
|
53
|
+
return true;
|
|
54
|
+
// Rich text carries inline `{ type: "image", src }` nodes whatever the sub-fields say.
|
|
55
|
+
case "richText":
|
|
56
|
+
case "content":
|
|
57
|
+
return true;
|
|
58
|
+
case "array":
|
|
59
|
+
return fieldCanHoldAsset(field.of, depth + 1);
|
|
60
|
+
case "json":
|
|
61
|
+
// Freeform json has no declared shape — assume it might.
|
|
62
|
+
return field.itemFields ? Object.values(field.itemFields).some((f) => fieldCanHoldAsset(f, depth + 1)) : true;
|
|
63
|
+
case "blocks":
|
|
64
|
+
return Object.values(field.types).some((blockFields) =>
|
|
65
|
+
Object.values(blockFields).some((f) => fieldCanHoldAsset(f, depth + 1)),
|
|
66
|
+
);
|
|
67
|
+
default:
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
type UsageTargets = { exact: string[]; contains: string[] };
|
|
73
|
+
|
|
74
|
+
const getUsageTargets = (collection: CollectionConfig): UsageTargets => {
|
|
75
|
+
const exact: string[] = [];
|
|
76
|
+
const contains: string[] = [];
|
|
77
|
+
|
|
78
|
+
for (const [name, field] of Object.entries(collection.fields)) {
|
|
79
|
+
if (field.type === "image") exact.push(name);
|
|
80
|
+
else if (JSON_FIELD_TYPES.has(field.type) && fieldCanHoldAsset(field)) contains.push(name);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return { exact, contains };
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const hasUsageTargets = (targets: UsageTargets) => targets.exact.length > 0 || targets.contains.length > 0;
|
|
87
|
+
|
|
88
|
+
type ScanColumn = { key: string; column: any; exact: boolean };
|
|
89
|
+
|
|
90
|
+
const collectColumns = (table: Record<string, any>, targets: UsageTargets, includePublished: boolean): ScanColumn[] => {
|
|
91
|
+
const columns: ScanColumn[] = [];
|
|
92
|
+
|
|
93
|
+
for (const name of targets.exact) {
|
|
94
|
+
if (table[name]) columns.push({ key: `c${columns.length}`, column: table[name], exact: true });
|
|
95
|
+
}
|
|
96
|
+
for (const name of targets.contains) {
|
|
97
|
+
if (table[name]) columns.push({ key: `c${columns.length}`, column: table[name], exact: false });
|
|
98
|
+
}
|
|
99
|
+
// The published snapshot is what the live site serves while a doc has unpublished
|
|
100
|
+
// changes, so a path living only in there still renders — and still counts as used.
|
|
101
|
+
if (includePublished && table._published) {
|
|
102
|
+
columns.push({ key: `c${columns.length}`, column: table._published, exact: false });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return columns;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* `instr` is a literal substring search — no LIKE wildcards to escape, and the
|
|
110
|
+
* storagePath is a random nanoid so a substring hit is never a false positive.
|
|
111
|
+
*/
|
|
112
|
+
const matchExpression = (entry: ScanColumn, path: string): SQL =>
|
|
113
|
+
entry.exact ? eq(entry.column, path) : sql`instr(${entry.column}, ${path}) > 0`;
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Document ids per storagePath, per collection. One query per table — the DB does
|
|
117
|
+
* the filtering; JS only attributes each matched row back to the path(s) it matched.
|
|
118
|
+
*/
|
|
119
|
+
const scanUsage = async (
|
|
120
|
+
config: CMSConfig,
|
|
121
|
+
paths: string[],
|
|
122
|
+
): Promise<{ hits: Map<string, Array<{ collection: CollectionConfig; docId: string }>>; incomplete: string[] }> => {
|
|
123
|
+
const hits = new Map<string, Array<{ collection: CollectionConfig; docId: string }>>();
|
|
124
|
+
const incomplete: string[] = [];
|
|
125
|
+
for (const path of paths) hits.set(path, []);
|
|
126
|
+
if (paths.length === 0) return { hits, incomplete };
|
|
127
|
+
|
|
128
|
+
const db = await getDb();
|
|
129
|
+
const { cmsTables } = getSchema();
|
|
130
|
+
|
|
131
|
+
for (const collection of config.collections) {
|
|
132
|
+
const targets = getUsageTargets(collection);
|
|
133
|
+
if (!hasUsageTargets(targets)) continue;
|
|
134
|
+
|
|
135
|
+
const tables = cmsTables[collection.slug];
|
|
136
|
+
if (!tables?.main) continue;
|
|
137
|
+
|
|
138
|
+
const perPath = new Map<string, Set<string>>();
|
|
139
|
+
|
|
140
|
+
const scanTable = async (table: Record<string, any>, idColumn: any, includePublished: boolean) => {
|
|
141
|
+
const columns = collectColumns(table, targets, includePublished);
|
|
142
|
+
if (columns.length === 0) return;
|
|
143
|
+
|
|
144
|
+
const conditions = paths.flatMap((path) => columns.map((entry) => matchExpression(entry, path)));
|
|
145
|
+
const selection: Record<string, any> = { __id: idColumn };
|
|
146
|
+
for (const entry of columns) selection[entry.key] = entry.column;
|
|
147
|
+
|
|
148
|
+
const rows = await db
|
|
149
|
+
.select(selection)
|
|
150
|
+
.from(table)
|
|
151
|
+
.where(or(...conditions))
|
|
152
|
+
.limit(SCAN_CAP);
|
|
153
|
+
|
|
154
|
+
for (const row of rows as Array<Record<string, unknown>>) {
|
|
155
|
+
const docId = String(row.__id ?? "");
|
|
156
|
+
if (!docId) continue;
|
|
157
|
+
for (const path of paths) {
|
|
158
|
+
const matched = columns.some((entry) => {
|
|
159
|
+
const value = row[entry.key];
|
|
160
|
+
return typeof value === "string" && value.includes(path);
|
|
161
|
+
});
|
|
162
|
+
if (!matched) continue;
|
|
163
|
+
if (!perPath.has(path)) perPath.set(path, new Set());
|
|
164
|
+
perPath.get(path)!.add(docId);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
try {
|
|
170
|
+
await scanTable(tables.main, tables.main._id, !!collection.drafts);
|
|
171
|
+
if (tables.translations) await scanTable(tables.translations, tables.translations._entityId, false);
|
|
172
|
+
} catch (error) {
|
|
173
|
+
// A missing or mid-migration table must not break the whole check — but it must
|
|
174
|
+
// not pass as "no usage" either, so record it and let the caller refuse to
|
|
175
|
+
// conclude anything. Silence here is what deletes a referenced asset.
|
|
176
|
+
incomplete.push(collection.slug);
|
|
177
|
+
console.warn(`[cms] asset usage scan failed for collection "${collection.slug}":`, error);
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
for (const [path, docIds] of perPath) {
|
|
182
|
+
const bucket = hits.get(path);
|
|
183
|
+
if (!bucket) continue;
|
|
184
|
+
for (const docId of docIds) bucket.push({ collection, docId });
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return { hits, incomplete };
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
/** Resolves display labels for matched documents, one query per collection. */
|
|
192
|
+
const resolveLabels = async (
|
|
193
|
+
entries: Array<{ collection: CollectionConfig; docId: string }>,
|
|
194
|
+
): Promise<AssetUsageRef[]> => {
|
|
195
|
+
if (entries.length === 0) return [];
|
|
196
|
+
|
|
197
|
+
const db = await getDb();
|
|
198
|
+
const { cmsTables } = getSchema();
|
|
199
|
+
const bySlug = new Map<string, { collection: CollectionConfig; docIds: string[] }>();
|
|
200
|
+
|
|
201
|
+
for (const entry of entries) {
|
|
202
|
+
const existing = bySlug.get(entry.collection.slug);
|
|
203
|
+
if (existing) existing.docIds.push(entry.docId);
|
|
204
|
+
else bySlug.set(entry.collection.slug, { collection: entry.collection, docIds: [entry.docId] });
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const refs: AssetUsageRef[] = [];
|
|
208
|
+
|
|
209
|
+
for (const { collection, docIds } of bySlug.values()) {
|
|
210
|
+
const tables = cmsTables[collection.slug];
|
|
211
|
+
const labelField = getLabelField(collection);
|
|
212
|
+
const labels = new Map<string, string>();
|
|
213
|
+
|
|
214
|
+
if (tables?.main?.[labelField]) {
|
|
215
|
+
try {
|
|
216
|
+
const rows = await db
|
|
217
|
+
.select({ __id: tables.main._id, __label: tables.main[labelField] })
|
|
218
|
+
.from(tables.main)
|
|
219
|
+
.where(or(...docIds.map((id) => eq(tables.main._id, id))));
|
|
220
|
+
for (const row of rows as Array<Record<string, unknown>>) {
|
|
221
|
+
labels.set(String(row.__id), String(row.__label ?? "").trim());
|
|
222
|
+
}
|
|
223
|
+
} catch {
|
|
224
|
+
// fall through to id labels
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
refs.push({
|
|
229
|
+
collectionSlug: collection.slug,
|
|
230
|
+
collectionLabel: collection.singleton ? collection.labels.singular : collection.labels.plural,
|
|
231
|
+
docs: docIds.map((docId) => ({
|
|
232
|
+
_id: docId,
|
|
233
|
+
label: collection.singleton ? collection.labels.singular : labels.get(docId) || docId,
|
|
234
|
+
})),
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
return refs;
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
/** Every document that references this asset's storagePath. */
|
|
242
|
+
export const findAssetUsage = async (config: CMSConfig, storagePath: string): Promise<AssetUsageResult> => {
|
|
243
|
+
if (!storagePath) return { refs: [], incomplete: [] };
|
|
244
|
+
const { hits, incomplete } = await scanUsage(config, [storagePath]);
|
|
245
|
+
return { refs: await resolveLabels(hits.get(storagePath) ?? []), incomplete };
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
/** Usage counts for many assets at once — one pass per collection, not per asset. */
|
|
249
|
+
export const countAssetUsage = async (
|
|
250
|
+
config: CMSConfig,
|
|
251
|
+
storagePaths: string[],
|
|
252
|
+
): Promise<{ counts: Record<string, number>; incomplete: string[] }> => {
|
|
253
|
+
const unique = [...new Set(storagePaths.filter(Boolean))];
|
|
254
|
+
const counts: Record<string, number> = Object.fromEntries(unique.map((path) => [path, 0]));
|
|
255
|
+
if (unique.length === 0) return { counts, incomplete: [] };
|
|
256
|
+
|
|
257
|
+
const { hits, incomplete } = await scanUsage(config, unique);
|
|
258
|
+
for (const [path, entries] of hits) counts[path] = entries.length;
|
|
259
|
+
return { counts, incomplete };
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Raised by `assets.delete()` when the asset is still referenced — or when usage
|
|
264
|
+
* could not be established — and `force` was not set.
|
|
265
|
+
*/
|
|
266
|
+
export class AssetInUseError extends Error {
|
|
267
|
+
readonly usage: AssetUsageRef[];
|
|
268
|
+
readonly incomplete: string[];
|
|
269
|
+
readonly assetId: string;
|
|
270
|
+
|
|
271
|
+
constructor(assetId: string, usage: AssetUsageRef[], incomplete: string[] = []) {
|
|
272
|
+
const total = usage.reduce((sum, ref) => sum + ref.docs.length, 0);
|
|
273
|
+
super(
|
|
274
|
+
total > 0
|
|
275
|
+
? `Asset is used by ${total} document${total === 1 ? "" : "s"}.`
|
|
276
|
+
: `Could not verify where this asset is used (${incomplete.join(", ")} could not be searched).`,
|
|
277
|
+
);
|
|
278
|
+
this.name = "AssetInUseError";
|
|
279
|
+
this.assetId = assetId;
|
|
280
|
+
this.usage = usage;
|
|
281
|
+
this.incomplete = incomplete;
|
|
282
|
+
}
|
|
283
|
+
}
|
package/core/assets.ts
CHANGED
|
@@ -2,11 +2,23 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { and, desc, eq, isNull, like, or, sql } from "drizzle-orm";
|
|
3
3
|
import { nanoid } from "nanoid";
|
|
4
4
|
|
|
5
|
+
import { AssetInUseError, findAssetUsage, getUsageConfig } from "./asset-usage";
|
|
6
|
+
import type { CMSConfig } from "./define";
|
|
5
7
|
import { logAudit, type AuditActor } from "./audit";
|
|
6
8
|
import { getDb, getStorage } from "./runtime";
|
|
7
9
|
import { getSchema } from "./schema";
|
|
8
10
|
|
|
9
|
-
export type AssetContext = {
|
|
11
|
+
export type AssetContext = {
|
|
12
|
+
actor?: AuditActor;
|
|
13
|
+
/** Skip the in-use check. The admin sets this once the editor has confirmed the warning. */
|
|
14
|
+
force?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Config used for the in-use check. Pass it explicitly from any caller that
|
|
17
|
+
* deletes — relying on the copy `createCms()` registers makes the guard depend
|
|
18
|
+
* on whether something else in the process imported the generated API first.
|
|
19
|
+
*/
|
|
20
|
+
config?: CMSConfig;
|
|
21
|
+
};
|
|
10
22
|
|
|
11
23
|
export type AssetRecord = {
|
|
12
24
|
_id: string;
|
|
@@ -208,6 +220,25 @@ export const assets = {
|
|
|
208
220
|
const rows = await db.select().from(schema.cmsAssets).where(eq(schema.cmsAssets._id, id)).limit(1);
|
|
209
221
|
if (rows.length === 0) return;
|
|
210
222
|
const asset = rows[0] as any;
|
|
223
|
+
|
|
224
|
+
// Guarded here, not only in the admin — DELETE /api/cms/assets/:id is reachable
|
|
225
|
+
// directly. Never skip the check silently: with no config there is nothing to
|
|
226
|
+
// check against, and proceeding would delete a referenced asset without a word.
|
|
227
|
+
// Callers that genuinely want an unchecked delete pass `force`.
|
|
228
|
+
if (!context?.force) {
|
|
229
|
+
const config = context?.config ?? getUsageConfig();
|
|
230
|
+
if (!config) {
|
|
231
|
+
throw new Error(
|
|
232
|
+
"assets.delete() cannot check whether this asset is in use — pass `config` in the context " +
|
|
233
|
+
"(or `force: true` to delete without checking).",
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
const { refs, incomplete } = await findAssetUsage(config, asset.storagePath);
|
|
237
|
+
// A collection we could not search is not evidence of "unused" — refuse
|
|
238
|
+
// rather than delete something that may still be referenced.
|
|
239
|
+
if (refs.length > 0 || incomplete.length > 0) throw new AssetInUseError(id, refs, incomplete);
|
|
240
|
+
}
|
|
241
|
+
|
|
211
242
|
await storage.deleteFile(asset.storagePath);
|
|
212
243
|
await db.delete(schema.cmsAssets).where(eq(schema.cmsAssets._id, id));
|
|
213
244
|
|
|
@@ -334,3 +365,64 @@ export const folders = {
|
|
|
334
365
|
await db.delete(schema.cmsAssetFolders).where(eq(schema.cmsAssetFolders._id, id));
|
|
335
366
|
},
|
|
336
367
|
};
|
|
368
|
+
|
|
369
|
+
type RichTextLikeNode = { type?: string; src?: unknown; children?: unknown[]; [key: string]: unknown };
|
|
370
|
+
|
|
371
|
+
const collectLocalImageSrcs = (node: unknown, into: Set<string>): void => {
|
|
372
|
+
if (Array.isArray(node)) {
|
|
373
|
+
for (const child of node) collectLocalImageSrcs(child, into);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
if (!node || typeof node !== "object") return;
|
|
377
|
+
|
|
378
|
+
const candidate = node as RichTextLikeNode;
|
|
379
|
+
if (candidate.type === "image" && typeof candidate.src === "string" && candidate.src.startsWith("/uploads/")) {
|
|
380
|
+
into.add(candidate.src);
|
|
381
|
+
}
|
|
382
|
+
if (Array.isArray(candidate.children)) collectLocalImageSrcs(candidate.children, into);
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
const withoutMissingImages = <T>(node: T, missing: Set<string>): T => {
|
|
386
|
+
if (Array.isArray(node)) {
|
|
387
|
+
return node
|
|
388
|
+
.filter((child) => {
|
|
389
|
+
const candidate = child as RichTextLikeNode | null;
|
|
390
|
+
return !(
|
|
391
|
+
candidate &&
|
|
392
|
+
typeof candidate === "object" &&
|
|
393
|
+
candidate.type === "image" &&
|
|
394
|
+
typeof candidate.src === "string" &&
|
|
395
|
+
missing.has(candidate.src)
|
|
396
|
+
);
|
|
397
|
+
})
|
|
398
|
+
.map((child) => withoutMissingImages(child, missing)) as unknown as T;
|
|
399
|
+
}
|
|
400
|
+
if (!node || typeof node !== "object") return node;
|
|
401
|
+
|
|
402
|
+
const candidate = node as RichTextLikeNode;
|
|
403
|
+
if (!Array.isArray(candidate.children)) return node;
|
|
404
|
+
return { ...candidate, children: withoutMissingImages(candidate.children, missing) } as unknown as T;
|
|
405
|
+
};
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Drops `image` nodes whose upload no longer exists from a rich-text / content
|
|
409
|
+
* document. The renderers are synchronous string builders, so this is the async
|
|
410
|
+
* pass that keeps a deleted asset from emitting a <picture> of 404s.
|
|
411
|
+
*
|
|
412
|
+
* Returns the document unchanged when nothing is missing (the common case).
|
|
413
|
+
*/
|
|
414
|
+
export const stripMissingAssetImages = async <T>(document: T): Promise<T> => {
|
|
415
|
+
const srcs = new Set<string>();
|
|
416
|
+
collectLocalImageSrcs(document, srcs);
|
|
417
|
+
if (srcs.size === 0) return document;
|
|
418
|
+
|
|
419
|
+
const missing = new Set<string>();
|
|
420
|
+
await Promise.all(
|
|
421
|
+
[...srcs].map(async (src) => {
|
|
422
|
+
if (!(await assets.findByUrl(src))) missing.add(src);
|
|
423
|
+
}),
|
|
424
|
+
);
|
|
425
|
+
if (missing.size === 0) return document;
|
|
426
|
+
|
|
427
|
+
return withoutMissingImages(document, missing);
|
|
428
|
+
};
|
package/core/generator.ts
CHANGED
|
@@ -151,7 +151,11 @@ const generateSchemaFile = (config: CMSConfig): string => {
|
|
|
151
151
|
storagePath: text("storage_path").notNull(),
|
|
152
152
|
hash: text("hash"),
|
|
153
153
|
_createdAt: text("_created_at").notNull(),
|
|
154
|
-
})
|
|
154
|
+
}, (table) => ({
|
|
155
|
+
storagePathIdx: index("assets_storage_path_idx").on(table.storagePath),
|
|
156
|
+
hashIdx: index("assets_hash_idx").on(table.hash),
|
|
157
|
+
folderIdx: index("assets_folder_idx").on(table.folder),
|
|
158
|
+
}));`);
|
|
155
159
|
parts.push("");
|
|
156
160
|
parts.push(`export const cmsAssetFolders = sqliteTable("cms_asset_folders", {
|
|
157
161
|
_id: text("_id").primaryKey(),
|
package/core/image.ts
CHANGED
|
@@ -70,7 +70,16 @@ function isCloudflare(): boolean {
|
|
|
70
70
|
return typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
-
|
|
73
|
+
/**
|
|
74
|
+
* Builds a URL for one rendition. This is the low-level primitive — it cannot
|
|
75
|
+
* read the asset record, so it knows nothing about the stored focal point or the
|
|
76
|
+
* intrinsic dimensions, and it does not check that the upload still exists.
|
|
77
|
+
*
|
|
78
|
+
* To render an image, use `<CmsImage>`, which does all three. Reach for this only
|
|
79
|
+
* when you need a string rather than an element: og:image, CSS background-image,
|
|
80
|
+
* JSON-LD, email HTML.
|
|
81
|
+
*/
|
|
82
|
+
export function cmsImageUrl(src: string, width?: number, format: Format = "webp", crop?: CropOptions): string {
|
|
74
83
|
if (!src) return "";
|
|
75
84
|
|
|
76
85
|
const ratio = parseAspect(crop?.aspect);
|
|
@@ -110,7 +119,7 @@ export function cmsSrcset(
|
|
|
110
119
|
crop?: CropOptions,
|
|
111
120
|
): string {
|
|
112
121
|
if (!src) return "";
|
|
113
|
-
return widths.map((width) => `${
|
|
122
|
+
return widths.map((width) => `${cmsImageUrl(src, width, format, crop)} ${width}w`).join(", ");
|
|
114
123
|
}
|
|
115
124
|
|
|
116
125
|
export type TransformOptions = {
|
package/core/index.ts
CHANGED
|
@@ -140,8 +140,10 @@ export {
|
|
|
140
140
|
} from "./auth";
|
|
141
141
|
export type { SessionUser } from "./auth";
|
|
142
142
|
|
|
143
|
-
export { assets, folders } from "./assets";
|
|
143
|
+
export { assets, folders, stripMissingAssetImages } from "./assets";
|
|
144
144
|
export type { AssetRecord, FolderRecord } from "./assets";
|
|
145
|
+
export { AssetInUseError, countAssetUsage, findAssetUsage } from "./asset-usage";
|
|
146
|
+
export type { AssetUsageRef, AssetUsageResult } from "./asset-usage";
|
|
145
147
|
|
|
146
148
|
export { parseBlocks, parseList, cacheTags } from "./content";
|
|
147
149
|
export { renderRichText, createRichTextFromPlainText, richTextToPlainText, htmlToRichText } from "./richtext";
|
|
@@ -169,7 +171,7 @@ export {
|
|
|
169
171
|
contentToPlainText,
|
|
170
172
|
} from "./values";
|
|
171
173
|
export type { ContentSegment } from "./values";
|
|
172
|
-
export {
|
|
174
|
+
export { cmsImageUrl, cmsSrcset, transformImage, DEFAULT_PRESETS, resolveImagePreset } from "./image";
|
|
173
175
|
export type { CropOptions, TransformOptions } from "./image";
|
|
174
176
|
|
|
175
177
|
export {
|
package/core/values.ts
CHANGED
|
@@ -6,7 +6,7 @@ import type {
|
|
|
6
6
|
RichTextDocument,
|
|
7
7
|
RichTextNode,
|
|
8
8
|
} from "./define";
|
|
9
|
-
import {
|
|
9
|
+
import { cmsImageUrl, cmsSrcset } from "./image";
|
|
10
10
|
|
|
11
11
|
export const cloneValue = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
|
|
12
12
|
|
|
@@ -320,7 +320,7 @@ const renderNode = (node: RichTextNode): string => {
|
|
|
320
320
|
const sizes = "(max-width: 768px) 100vw, 768px";
|
|
321
321
|
const avif = escapeHtml(cmsSrcset(src, undefined, "avif"));
|
|
322
322
|
const webp = escapeHtml(cmsSrcset(src, undefined, "webp"));
|
|
323
|
-
const fallback = escapeHtml(
|
|
323
|
+
const fallback = escapeHtml(cmsImageUrl(src, 1024));
|
|
324
324
|
return `<picture><source type="image/avif" srcset="${avif}" sizes="${sizes}" /><source type="image/webp" srcset="${webp}" sizes="${sizes}" /><img src="${fallback}" alt="${alt}" loading="lazy" class="h-auto max-w-full rounded-lg" /></picture>`;
|
|
325
325
|
}
|
|
326
326
|
const safeSrc = safeUrl(src);
|
package/internals/integration.ts
CHANGED
|
@@ -309,6 +309,10 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
|
|
|
309
309
|
pattern: "/api/cms/assets",
|
|
310
310
|
entrypoint: new URL("../routes/api/assets/index.ts", import.meta.url),
|
|
311
311
|
});
|
|
312
|
+
injectRoute({
|
|
313
|
+
pattern: "/api/cms/asset-usage",
|
|
314
|
+
entrypoint: new URL("../routes/api/asset-usage.ts", import.meta.url),
|
|
315
|
+
});
|
|
312
316
|
injectRoute({
|
|
313
317
|
pattern: "/api/cms/collaboration",
|
|
314
318
|
entrypoint: new URL("../routes/api/collaboration/index.ts", import.meta.url),
|
package/internals/push.ts
CHANGED
|
@@ -122,7 +122,16 @@ async function main() {
|
|
|
122
122
|
// drizzle-kit's hasDataLoss misses plain DROP COLUMN — classify statement shapes too.
|
|
123
123
|
// (`__new_` is drizzle's table-recreate pattern: create copy, insert-select, drop old.)
|
|
124
124
|
const isDestructive = (stmt: string) => /\bDROP\s+TABLE\b|\bDROP\s+COLUMN\b|\bDELETE\s+FROM\b|__new_/i.test(stmt);
|
|
125
|
-
|
|
125
|
+
|
|
126
|
+
// `hasDataLoss` describes the whole diff, including the runtime FTS tables filtered
|
|
127
|
+
// out above — dropping those is not data loss (ensureSearchSchema rebuilds them), so
|
|
128
|
+
// the flag alone would block any additive change made while a search index exists.
|
|
129
|
+
// Judge what we are actually going to run, and only defer to drizzle's flag when
|
|
130
|
+
// something outside the search index could be behind it.
|
|
131
|
+
const droppedSearchIndex = statementsToExecute.some(isSearchIndexStatement);
|
|
132
|
+
const searchIndexIsTheOnlyLoss =
|
|
133
|
+
droppedSearchIndex && statementsToExecute.every((stmt) => isSearchIndexStatement(stmt) || !isDestructive(stmt));
|
|
134
|
+
const losesData = statements.some(isDestructive) || (hasDataLoss && !searchIndexIsTheOnlyLoss);
|
|
126
135
|
|
|
127
136
|
if (statements.length === 0) {
|
|
128
137
|
console.log("[cms:push] Schema already in sync.");
|
package/internals/virtual.d.ts
CHANGED
package/middleware/auth.ts
CHANGED
|
@@ -70,7 +70,7 @@ const handle = async (context: APIContext, next: MiddlewareNext) => {
|
|
|
70
70
|
const isInvitePage = pathname === "/admin/invite";
|
|
71
71
|
const isInviteApi = pathname === "/api/cms/auth/invite";
|
|
72
72
|
|
|
73
|
-
// Public despite the /api/cms prefix:
|
|
73
|
+
// Public despite the /api/cms prefix: cmsImageUrl() puts these URLs on public pages.
|
|
74
74
|
// Only reads files under public/, which are served unauthenticated anyway.
|
|
75
75
|
const isPublicImageApi = pathname.startsWith("/api/cms/img/");
|
|
76
76
|
|