@cardinali-studio/adminkit 2.2.20 → 2.2.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/api.d.ts +38 -2
  2. package/dist/api.js +13 -0
  3. package/dist/app/App.d.ts +1 -0
  4. package/dist/app/App.js +36 -15
  5. package/dist/app/NextAdminApp.d.ts +8 -0
  6. package/dist/app/NextAdminApp.js +3 -0
  7. package/dist/app/lib/admin-interface.d.ts +11 -0
  8. package/dist/app/lib/admin-interface.js +45 -0
  9. package/dist/app/next.css +826 -0
  10. package/dist/app/routes/AdminInterfaceSettings.d.ts +12 -0
  11. package/dist/app/routes/AdminInterfaceSettings.js +14 -0
  12. package/dist/app/routes/Deliveries.js +1 -1
  13. package/dist/app/routes/GallerySectionsEditor.d.ts +1 -1
  14. package/dist/app/routes/GallerySectionsEditor.js +14 -2
  15. package/dist/app/routes/HomeEditor.js +2 -2
  16. package/dist/app/routes/Overview.js +4 -4
  17. package/dist/app/routes/PageEditor.js +12 -5
  18. package/dist/app/routes/PortfolioWorksEditor.d.ts +1 -1
  19. package/dist/app/routes/PortfolioWorksEditor.js +11 -3
  20. package/dist/app/routes/Requests.js +2 -2
  21. package/dist/app/routes/SiteSettingsEditor.d.ts +4 -1
  22. package/dist/app/routes/SiteSettingsEditor.js +3 -2
  23. package/dist/app/ui/MediaSlot.js +1 -1
  24. package/dist/app/ui/OpenCard.js +22 -1
  25. package/dist/app/ui/icons.js +5 -2
  26. package/dist/form/fields/index.js +2 -1
  27. package/dist/form/media/Lightbox.js +33 -3
  28. package/dist/form/media/MediaGrid.js +9 -6
  29. package/dist/form/media/media-model.d.ts +2 -0
  30. package/dist/form/media/media-model.js +8 -0
  31. package/dist/form/media/useMediaLibrary.d.ts +11 -2
  32. package/dist/form/media/useMediaLibrary.js +89 -24
  33. package/dist/functions/_shared/d1-media.js +105 -91
  34. package/dist/functions/_shared/media-alt.js +61 -0
  35. package/dist/functions/api/assets/delete.js +20 -3
  36. package/dist/functions/api/assets/media.js +57 -2
  37. package/dist/functions/api/assets/move.js +5 -1
  38. package/dist/functions/api/assets/upload.js +3 -1
  39. package/dist/functions/api/assets.js +5 -2
  40. package/dist/gallery.d.ts +2 -0
  41. package/dist/media.d.ts +19 -0
  42. package/dist/media.js +132 -0
  43. package/dist/normalize.d.ts +1 -0
  44. package/dist/normalize.js +2 -1
  45. package/dist/persistence.d.ts +8 -0
  46. package/dist/persistence.js +78 -6
  47. package/dist/theme.css +42 -0
  48. package/package.json +2 -2
@@ -5,15 +5,11 @@ import {
5
5
  canonicalChecksum, canonicalJson, contentSaveRequestChecksum, D1ContentRepository,
6
6
  } from "../../persistence.js";
7
7
  import {
8
- D1MediaOperationRepository, prepareMediaCopy,
8
+ D1MediaOperationRepository, mediaPublicUrl, prepareMediaCopy, rewriteMediaValue,
9
9
  } from "../../media.js";
10
10
  import { validateContentDocument } from "../site.js";
11
11
  import { isKey, moveToTrash, sanitizeName } from "./assets.js";
12
12
 
13
- const MEDIA_PREFIX = "/media/";
14
-
15
- function mediaUrl(key) { return MEDIA_PREFIX + key.split("/").map(encodeURIComponent).join("/"); }
16
-
17
13
  function editor(data) {
18
14
  const payload = data?.cloudflareAccess?.JWT?.payload;
19
15
  if (!payload?.sub) throw new Error("unauthenticated");
@@ -26,67 +22,7 @@ function operationId(value) {
26
22
  return value;
27
23
  }
28
24
 
29
- function replaceBoundedUrl(value, from, to) {
30
- let cursor = 0;
31
- let next = "";
32
- while (cursor < value.length) {
33
- const found = value.indexOf(from, cursor);
34
- if (found < 0) return next + value.slice(cursor);
35
- const after = value[found + from.length];
36
- /* A media key is a path, not a string prefix. Query/fragment suffixes and
37
- * further URL/path characters belong to a different reference and must
38
- * not be rewritten accidentally. */
39
- if (after && /[A-Za-z0-9._~%!$&'()*+,;=:@/?#-]/.test(after)) {
40
- next += value.slice(cursor, found + from.length);
41
- cursor = found + from.length;
42
- continue;
43
- }
44
- next += value.slice(cursor, found) + to;
45
- cursor = found + from.length;
46
- }
47
- return next;
48
- }
49
-
50
- function replaceText(value, replacements, removals) {
51
- let next = value;
52
- for (const [from, to] of Object.entries(replacements)) next = replaceBoundedUrl(next, from, to);
53
- for (const from of removals) next = replaceBoundedUrl(next, from, "");
54
- return next;
55
- }
56
-
57
- /** JSON Media values are intentionally rewritten only as complete public URLs
58
- * (or a URL embedded in Markdown). Arrays lose an exact removed URL; scalar
59
- * slots become empty strings and are then validated by the site's schema. */
60
- function rewriteValue(value, replacements, removals, inArray = false) {
61
- if (typeof value === "string") {
62
- if (removals.has(value) && inArray) return { changed: true, removed: true };
63
- const next = replaceText(value, replacements, removals);
64
- return { changed: next !== value, value: next };
65
- }
66
- if (Array.isArray(value)) {
67
- let changed = false;
68
- const next = [];
69
- for (const item of value) {
70
- const result = rewriteValue(item, replacements, removals, true);
71
- changed ||= result.changed;
72
- if (!result.removed) next.push(result.value);
73
- }
74
- return { changed, value: next };
75
- }
76
- if (value && typeof value === "object") {
77
- let changed = false;
78
- const next = {};
79
- for (const [key, item] of Object.entries(value)) {
80
- const result = rewriteValue(item, replacements, removals, false);
81
- changed ||= result.changed;
82
- if (!result.removed) next[key] = result.value;
83
- }
84
- return { changed, value: next };
85
- }
86
- return { changed: false, value };
87
- }
88
-
89
- async function effectiveDocuments(db) {
25
+ async function mediaDocuments(db) {
90
26
  return ((await db.prepare(`SELECT document.document_id AS documentId, document.kind, document.locale,
91
27
  document.draft_revision_id AS draftRevisionId, published.revision_id AS publishedRevisionId,
92
28
  draft.payload_json AS draftPayload, draft.is_tombstone AS draftTombstone,
@@ -101,16 +37,33 @@ async function effectiveDocuments(db) {
101
37
  }
102
38
 
103
39
  async function rewriteDocuments({ db, data, replacements = {}, removals = [] }) {
104
- const replacementUrls = Object.fromEntries(Object.entries(replacements).map(([from, to]) => [mediaUrl(from), mediaUrl(to)]));
105
- const removalUrls = new Set(removals.map(mediaUrl));
106
40
  const commands = [];
107
- for (const row of await effectiveDocuments(db)) {
108
- const useDraft = row.draftRevisionId !== null;
109
- const raw = useDraft ? row.draftPayload : row.publishedPayload;
110
- if (!raw || (useDraft ? row.draftTombstone : row.publishedTombstone)) continue;
111
- let payload;
112
- try { payload = JSON.parse(raw); } catch { throw new Error("invalid_document"); }
113
- const rewritten = rewriteValue(payload, replacementUrls, removalUrls);
41
+ const publishedDocuments = [];
42
+ for (const row of await mediaDocuments(db)) {
43
+ /* Validate the exact published patch now, before the operation can become
44
+ * ready. Publication later starts from this same immutable release side,
45
+ * never from an unrelated editorial draft. */
46
+ if (row.publishedPayload && !row.publishedTombstone) {
47
+ let publishedPayload;
48
+ try { publishedPayload = JSON.parse(row.publishedPayload); } catch { throw new Error("invalid_document"); }
49
+ const published = rewriteMediaValue(publishedPayload, { replacements, removals });
50
+ if (published.changed) {
51
+ validateContentDocument({
52
+ documentId: row.documentId, kind: row.kind, locale: row.locale, schemaVersion: row.schemaVersion,
53
+ tombstone: false, payload: published.value,
54
+ });
55
+ publishedDocuments.push({ documentId: row.documentId, kind: row.kind });
56
+ }
57
+ }
58
+
59
+ /* Existing drafts keep every unrelated edit but must not be able to
60
+ * reintroduce a source after the isolated Media release. No draft is
61
+ * manufactured when none existed: the detached published patch owns that
62
+ * side of the operation. */
63
+ if (row.draftRevisionId === null || !row.draftPayload || row.draftTombstone) continue;
64
+ let draftPayload;
65
+ try { draftPayload = JSON.parse(row.draftPayload); } catch { throw new Error("invalid_document"); }
66
+ const rewritten = rewriteMediaValue(draftPayload, { replacements, removals });
114
67
  if (!rewritten.changed) continue;
115
68
  const normalized = validateContentDocument({
116
69
  documentId: row.documentId, kind: row.kind, locale: row.locale, schemaVersion: row.schemaVersion,
@@ -118,14 +71,14 @@ async function rewriteDocuments({ db, data, replacements = {}, removals = [] })
118
71
  });
119
72
  commands.push({
120
73
  revisionId: crypto.randomUUID(), documentId: row.documentId,
121
- baseRevisionId: useDraft ? row.draftRevisionId : row.publishedRevisionId,
74
+ baseRevisionId: row.draftRevisionId,
122
75
  expectedDraftRevisionId: row.draftRevisionId, kind: row.kind, locale: row.locale,
123
76
  schemaVersion: row.schemaVersion, tombstone: false, payload: normalized.payload,
124
77
  });
125
78
  }
126
79
  /* Nessun riferimento è un esito valido: l'operazione Media deve proseguire
127
80
  * senza costruire una transazione editoriale vuota, che `saveMany` rifiuta. */
128
- if (!commands.length) return { documents: [] };
81
+ if (!commands.length) return { documents: [], publishedDocuments };
129
82
  const who = editor(data);
130
83
  const repository = new D1ContentRepository(db);
131
84
  /* Every command was fully parsed and site-validated before the first write.
@@ -136,7 +89,10 @@ async function rewriteDocuments({ db, data, replacements = {}, removals = [] })
136
89
  ...command, payloadChecksum: await canonicalChecksum(command.payload), requestChecksum: await contentSaveRequestChecksum(command),
137
90
  now, authorSubject: who.subject, authorLabel: who.label,
138
91
  }))));
139
- return { documents: commands.map((command) => ({ documentId: command.documentId, kind: command.kind })) };
92
+ return {
93
+ documents: commands.map((command) => ({ documentId: command.documentId, kind: command.kind })),
94
+ publishedDocuments,
95
+ };
140
96
  }
141
97
 
142
98
  function keys(input) {
@@ -205,14 +161,22 @@ export async function d1MoveMedia({ env, data, body }) {
205
161
  const stored = await journal.entries(id);
206
162
  return {
207
163
  operationId: id, repeated: true, moved: stored.length,
208
- urlMap: Object.fromEntries(stored.filter((entry) => entry.destinationKey).map((entry) => [mediaUrl(entry.sourceKey), mediaUrl(entry.destinationKey)])),
209
- documents: [],
164
+ urlMap: Object.fromEntries(stored.filter((entry) => entry.destinationKey).map((entry) => [mediaPublicUrl(entry.sourceKey), mediaPublicUrl(entry.destinationKey)])),
165
+ documents: [], publishedDocuments: [], requiresPublication: true,
210
166
  };
211
167
  }
212
168
  try {
213
169
  for (const entry of entries) await prepareMediaCopy({ bucket: env.MEDIA, journal, operationId: id, entryId: entry.entryId, sourceKey: entry.sourceKey, destinationKey: entry.destinationKey, now: Date.now() });
214
170
  const rewritten = await rewriteDocuments({ db: env.CONTENT_DB, data, replacements: Object.fromEntries(entries.map((entry) => [entry.sourceKey, entry.destinationKey])) });
215
- return { operationId: id, repeated: false, moved: entries.length, urlMap: Object.fromEntries(entries.map((entry) => [mediaUrl(entry.sourceKey), mediaUrl(entry.destinationKey)])), documents: rewritten.documents };
171
+ const immediate = rewritten.publishedDocuments.length
172
+ ? { requiresPublication: true }
173
+ : await finalizeUnpublishedD1MediaOperation({ env, operationId: id });
174
+ return {
175
+ operationId: id, repeated: false, moved: entries.length,
176
+ urlMap: Object.fromEntries(entries.map((entry) => [mediaPublicUrl(entry.sourceKey), mediaPublicUrl(entry.destinationKey)])),
177
+ documents: rewritten.documents, publishedDocuments: rewritten.publishedDocuments,
178
+ ...immediate,
179
+ };
216
180
  } catch (error) {
217
181
  await journal.cancel(id, Date.now()).catch(() => null);
218
182
  throw error;
@@ -225,12 +189,22 @@ export async function d1DeleteMedia({ env, data, body }) {
225
189
  const id = operationId(body.operationId);
226
190
  const entries = sourceKeys.map((sourceKey) => ({ entryId: crypto.randomUUID(), sourceKey }));
227
191
  const { journal, created } = await createOperation({ db: env.CONTENT_DB, data, type: "delete", id, entries, clientChecksum: body.requestChecksum });
228
- if (created === "repeated") return { operationId: id, repeated: true, trashed: (await journal.entries(id)).length, documents: [] };
192
+ if (created === "repeated") return {
193
+ operationId: id, repeated: true, trashed: (await journal.entries(id)).length,
194
+ documents: [], publishedDocuments: [], requiresPublication: true,
195
+ };
229
196
  try {
230
197
  const inspected = await Promise.all(entries.map((entry) => inspectSource(env.MEDIA, entry)));
231
198
  const rewritten = await rewriteDocuments({ db: env.CONTENT_DB, data, removals: sourceKeys });
232
199
  for (const entry of inspected) await journal.readyDeleteEntry({ ...entry, operationId: id, now: Date.now() });
233
- return { operationId: id, repeated: false, trashed: entries.length, documents: rewritten.documents };
200
+ const immediate = rewritten.publishedDocuments.length
201
+ ? { requiresPublication: true }
202
+ : await finalizeUnpublishedD1MediaOperation({ env, operationId: id });
203
+ return {
204
+ operationId: id, repeated: false, trashed: entries.length,
205
+ documents: rewritten.documents, publishedDocuments: rewritten.publishedDocuments,
206
+ ...immediate,
207
+ };
234
208
  } catch (error) {
235
209
  await journal.cancel(id, Date.now()).catch(() => null);
236
210
  throw error;
@@ -246,28 +220,42 @@ export async function d1PendingSourceKeys(db) {
246
220
  export async function d1MediaUsage(db, sourceKeys) {
247
221
  const keys = [...new Set(sourceKeys.filter(isKey))];
248
222
  if (!keys.length) return { usage: {}, pages: [], count: 0, selectedCount: 0, blockers: [] };
249
- const rows = (await db.prepare(`SELECT document.kind, document.document_id AS documentId, revision.payload_json AS payload
223
+ const rows = (await db.prepare(`SELECT document.kind, document.document_id AS documentId,
224
+ revision.payload_json AS payload, 0 AS locationRank
250
225
  FROM content_documents document
251
226
  JOIN content_revisions revision ON revision.document_id = document.document_id AND revision.revision_id = document.draft_revision_id
252
227
  UNION
253
- SELECT document.kind, document.document_id AS documentId, revision.payload_json AS payload
228
+ SELECT document.kind, document.document_id AS documentId,
229
+ revision.payload_json AS payload, 1 AS locationRank
254
230
  FROM content_site_state state
255
231
  JOIN content_release_entries entry ON entry.release_id = state.current_release_id
256
232
  JOIN content_documents document ON document.document_id = entry.document_id
257
233
  JOIN content_revisions revision ON revision.document_id = entry.document_id AND revision.revision_id = entry.revision_id
258
234
  UNION
259
- SELECT document.kind, document.document_id AS documentId, revision.payload_json AS payload
235
+ SELECT document.kind, document.document_id AS documentId,
236
+ revision.payload_json AS payload, 2 AS locationRank
260
237
  FROM content_releases release
261
238
  JOIN content_release_entries entry ON entry.release_id = release.release_id
262
239
  JOIN content_documents document ON document.document_id = entry.document_id
263
240
  JOIN content_revisions revision ON revision.document_id = entry.document_id AND revision.revision_id = entry.revision_id
264
- WHERE release.status = 'publishing'`).all()).results ?? [];
241
+ WHERE release.status = 'publishing'
242
+ ORDER BY locationRank, documentId`).all()).results ?? [];
265
243
  const usage = {};
266
244
  const pages = new Set();
267
245
  for (const key of keys) {
268
- const url = mediaUrl(key);
269
- const locations = [...new Set(rows.filter((row) => typeof row.payload === "string" && row.payload.includes(url))
270
- .map((row) => `${row.kind} · ${row.documentId}`))];
246
+ const url = mediaPublicUrl(key);
247
+ const documents = new Map();
248
+ for (const row of rows) {
249
+ if (documents.has(row.documentId) || typeof row.payload !== "string" || !row.payload.includes(url)) continue;
250
+ let payload;
251
+ try { payload = JSON.parse(row.payload); } catch { payload = null; }
252
+ const candidate = payload && typeof payload === "object" && !Array.isArray(payload)
253
+ ? [payload.title, payload.name, payload.label, payload.slug]
254
+ .find((value) => typeof value === "string" && value.trim())
255
+ : null;
256
+ documents.set(row.documentId, candidate ? String(candidate).trim().slice(0, 200) : `${row.kind} · ${row.documentId}`);
257
+ }
258
+ const locations = [...documents.values()];
271
259
  if (locations.length) { usage[key] = locations; locations.forEach((location) => pages.add(location)); }
272
260
  }
273
261
  return { usage, pages: [...pages], count: Object.keys(usage).length, selectedCount: keys.length, blockers: [] };
@@ -302,10 +290,36 @@ export async function finalizeD1MediaRelease({ env, releaseId, now = Date.now()
302
290
  return { completed, failed };
303
291
  }
304
292
 
293
+ async function finalizeUnpublishedD1MediaOperation({ env, operationId: id, now = Date.now(), resume = false }) {
294
+ if (!env.CONTENT_DB || !env.MEDIA) throw new Error("content_unavailable");
295
+ const journal = new D1MediaOperationRepository(env.CONTENT_DB);
296
+ if (resume) await journal.resumeUnboundFinalization(id, now);
297
+ else if (!await journal.beginUnpublishedFinalization(id, now)) return { requiresPublication: true, completed: 0, failed: 0 };
298
+ const entries = await journal.unboundFinalizationWork(id);
299
+ let completed = 0;
300
+ let failed = 0;
301
+ for (const entry of entries) {
302
+ try {
303
+ if (entry.type === "delete") await moveToTrash(env.MEDIA, entry.sourceKey);
304
+ else await env.MEDIA.delete(entry.sourceKey);
305
+ await journal.recordFinalizedEntry({ operationId: id, entryId: entry.entryId, now, outcome: "completed" });
306
+ completed += 1;
307
+ } catch {
308
+ await journal.recordFinalizedEntry({
309
+ operationId: id, entryId: entry.entryId, now, outcome: "failed",
310
+ safeError: "La pulizia del Media verrà ritentata.",
311
+ });
312
+ failed += 1;
313
+ }
314
+ }
315
+ return { requiresPublication: false, completed, failed };
316
+ }
317
+
305
318
  export async function resumeD1MediaOperation({ env, data, operationId: id, releaseId }) {
306
319
  if (!env.CONTENT_DB || !env.MEDIA) throw new Error("content_unavailable");
307
320
  editor(data);
308
- if (typeof id !== "string" || typeof releaseId !== "string") throw new Error("invalid_media_operation");
321
+ if (typeof id !== "string" || !(releaseId === null || releaseId === undefined || typeof releaseId === "string")) throw new Error("invalid_media_operation");
322
+ if (!releaseId) return finalizeUnpublishedD1MediaOperation({ env, operationId: id, now: Date.now(), resume: true });
309
323
  const journal = new D1MediaOperationRepository(env.CONTENT_DB);
310
324
  await journal.resumeFinalization(id, releaseId, Date.now());
311
325
  return finalizeD1MediaRelease({ env, releaseId, now: Date.now() });
@@ -0,0 +1,61 @@
1
+ /* Testi alternativi associati al file Media.
2
+ *
3
+ * Vivono nei custom metadata dell'oggetto R2: in questo modo seguono già le copie usate da
4
+ * spostamento, cestino e ripristino, senza una seconda tabella da tenere sincronizzata con le
5
+ * chiavi del bucket. Il valore è JSON perché R2 accetta solo stringhe nei custom metadata.
6
+ */
7
+
8
+ export const MEDIA_ALT_METADATA_KEY = "adminkitAlt";
9
+ export const MEDIA_UPLOADED_METADATA_KEY = "adminkitUploadedAt";
10
+
11
+ const EMPTY = Object.freeze({ decorative: false, texts: Object.freeze({}) });
12
+
13
+ export function altLocales(languageConfig) {
14
+ return languageConfig?.available?.length ? [...languageConfig.available] : ["default"];
15
+ }
16
+
17
+ /** Legge in modo difensivo anche metadati scritti da una versione futura o incompleta. */
18
+ export function mediaAltFromMetadata(customMetadata, locales = null) {
19
+ const raw = customMetadata?.[MEDIA_ALT_METADATA_KEY];
20
+ if (!raw) return EMPTY;
21
+ let value;
22
+ try { value = JSON.parse(raw); } catch { return EMPTY; }
23
+ if (!value || typeof value !== "object" || Array.isArray(value)) return EMPTY;
24
+ const allowed = locales ? new Set(locales) : null;
25
+ const texts = {};
26
+ if (value.texts && typeof value.texts === "object" && !Array.isArray(value.texts)) {
27
+ for (const [locale, text] of Object.entries(value.texts)) {
28
+ if ((!allowed || allowed.has(locale)) && typeof text === "string" && text.trim()) {
29
+ texts[locale] = text.trim();
30
+ }
31
+ }
32
+ }
33
+ return { decorative: value.decorative === true, texts };
34
+ }
35
+
36
+ /** Valida il comando editoriale. Il limite è solo tecnico (dimensione dei metadata R2), non
37
+ * una falsa regola SEO: l'interfaccia non impone un maxlength al testo. */
38
+ export function normalizeMediaAlt(value, locales) {
39
+ if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.decorative !== "boolean") {
40
+ throw new Error("invalid_media_alt");
41
+ }
42
+ if (!value.texts || typeof value.texts !== "object" || Array.isArray(value.texts)) {
43
+ throw new Error("invalid_media_alt");
44
+ }
45
+ const allowed = new Set(locales);
46
+ const texts = {};
47
+ for (const [locale, text] of Object.entries(value.texts)) {
48
+ if (!allowed.has(locale) || typeof text !== "string") throw new Error("invalid_media_alt");
49
+ const normalized = text.trim();
50
+ if (normalized) texts[locale] = normalized;
51
+ }
52
+ const result = { decorative: value.decorative, texts: value.decorative ? {} : texts };
53
+ if (new TextEncoder().encode(JSON.stringify(result)).byteLength > 1600) {
54
+ throw new Error("media_alt_too_large");
55
+ }
56
+ return result;
57
+ }
58
+
59
+ export function mediaAltMetadataValue(value) {
60
+ return value.decorative || Object.keys(value.texts).length ? JSON.stringify(value) : null;
61
+ }
@@ -126,10 +126,27 @@ export async function onRequestPost({ request, env, data }) {
126
126
  const operable = keyList.filter((key) => !pending.has(key));
127
127
  const result = operable.length ? await d1DeleteMedia({ env, data, body: { ...body, keys: operable } }) : null;
128
128
  for (const keepKey of keepKeys) await env.MEDIA.delete(keepKey);
129
- return json({ ok: true, trashed: result?.trashed ?? keyList.length, operationId: result?.operationId, pagesUpdated: result?.documents.map((document) => document.kind) ?? [], deferred: Boolean(result), d1: true, warning: result ? "I file resteranno disponibili fino alla pubblicazione." : undefined });
129
+ return json({
130
+ ok: true,
131
+ trashed: result?.trashed ?? keyList.length,
132
+ operationId: result?.operationId,
133
+ pagesUpdated: result?.publishedDocuments?.map((document) => document.kind) ?? [],
134
+ requiresPublication: result?.requiresPublication === true,
135
+ deferred: result?.requiresPublication === true || Number(result?.failed ?? 0) > 0,
136
+ completed: result ? Number(result.completed ?? 0) : keyList.length,
137
+ failed: Number(result?.failed ?? 0),
138
+ d1: true,
139
+ warning: result?.requiresPublication ? "Le pagine verranno pubblicate senza questi Media prima di spostarli nel cestino." : undefined,
140
+ });
130
141
  } catch (error) {
131
- const code = error?.message === "unauthenticated" ? "unauthenticated" : error?.message === "media_source_busy" ? "media_source_busy" : "media_operation_unavailable";
132
- return json({ ok: false, code, error: code === "media_source_busy" ? "Questo Media è già in un'operazione in corso." : "Non riesco a registrare l'operazione Media D1." }, code === "unauthenticated" ? 401 : 409);
142
+ const code = error?.message === "unauthenticated" ? "unauthenticated"
143
+ : error?.message === "media_source_busy" ? "media_source_busy"
144
+ : error?.message === "invalid_document" ? "media_replacement_required"
145
+ : "media_operation_unavailable";
146
+ const message = code === "media_source_busy" ? "Questo Media è già in un'operazione in corso."
147
+ : code === "media_replacement_required" ? "Una pagina richiede questa immagine: sostituiscila prima di eliminarla."
148
+ : "Non riesco a registrare l'operazione Media D1.";
149
+ return json({ ok: false, code, error: message }, code === "unauthenticated" ? 401 : code === "media_replacement_required" ? 422 : 409);
133
150
  }
134
151
  }
135
152
 
@@ -1,9 +1,13 @@
1
1
  /* D1 Media operation status and bounded recovery. These routes exist only
2
2
  * after D1 cutover; Git-mode Media keeps its established pending-marker flow. */
3
- import { json } from "../../_shared/assets.js";
3
+ import { guessMime, isKey, json } from "../../_shared/assets.js";
4
4
  import { D1MediaOperationRepository } from "../../../media.js";
5
- import { contentPersistenceMode } from "../../site.js";
5
+ import { contentPersistenceMode, languages } from "../../site.js";
6
6
  import { cancelD1MediaOperation, resumeD1MediaOperation } from "../../_shared/d1-media.js";
7
+ import {
8
+ altLocales, mediaAltMetadataValue, normalizeMediaAlt,
9
+ MEDIA_ALT_METADATA_KEY, MEDIA_UPLOADED_METADATA_KEY,
10
+ } from "../../_shared/media-alt.js";
7
11
 
8
12
  function unavailable() { return json({ ok: false, code: "feature_inactive", error: "Journal Media D1 non attivo." }, 404); }
9
13
  function failure(error) {
@@ -11,6 +15,57 @@ function failure(error) {
11
15
  return json({ ok: false, code, error: code === "unauthenticated" ? "Sessione non valida: ricarica la pagina per rientrare." : "L'operazione Media non può essere completata." }, code === "unauthenticated" ? 401 : 409);
12
16
  }
13
17
 
18
+ /** Aggiorna solo i metadata editoriali del file. R2 richiede di riscrivere l'oggetto per
19
+ * cambiare customMetadata: conserviamo quindi esplicitamente la data originaria, oltre a tutti
20
+ * i metadata HTTP/EXIF già presenti. */
21
+ export async function onRequestPatch({ request, env }) {
22
+ if (!env.MEDIA) return json({ ok: false, error: "Binding MEDIA non configurato" }, 500);
23
+ let body;
24
+ try { body = await request.json(); } catch { return json({ ok: false, code: "media_alt_invalid", error: "JSON non valido." }, 400); }
25
+ const key = typeof body?.key === "string" ? body.key : "";
26
+ if (!isKey(key) || key.startsWith("_trash/") || key.startsWith("_adminkit/")) {
27
+ return json({ ok: false, code: "media_alt_invalid", error: "File Media non valido." }, 400);
28
+ }
29
+ const object = await env.MEDIA.get(key);
30
+ if (!object) return json({ ok: false, code: "media_not_found", error: "Il file non esiste più." }, 404);
31
+ const type = object.httpMetadata?.contentType || guessMime(key);
32
+ if (!type.startsWith("image/")) {
33
+ return json({ ok: false, code: "media_alt_not_applicable", error: "Il testo alternativo si applica alle immagini." }, 422);
34
+ }
35
+ let alt;
36
+ try { alt = normalizeMediaAlt(body.alt, altLocales(languages())); }
37
+ catch (error) {
38
+ const tooLarge = error?.message === "media_alt_too_large";
39
+ return json({
40
+ ok: false,
41
+ code: tooLarge ? "media_alt_too_large" : "media_alt_invalid",
42
+ error: tooLarge ? "I testi alternativi sono troppo estesi per i metadati del file." : "Testo alternativo non valido.",
43
+ }, 400);
44
+ }
45
+ const customMetadata = { ...(object.customMetadata || {}) };
46
+ const encoded = mediaAltMetadataValue(alt);
47
+ if (encoded) customMetadata[MEDIA_ALT_METADATA_KEY] = encoded;
48
+ else delete customMetadata[MEDIA_ALT_METADATA_KEY];
49
+ if (!customMetadata[MEDIA_UPLOADED_METADATA_KEY]) {
50
+ customMetadata[MEDIA_UPLOADED_METADATA_KEY] = object.uploaded instanceof Date
51
+ ? object.uploaded.toISOString()
52
+ : new Date().toISOString();
53
+ }
54
+ const saved = await env.MEDIA.put(key, object.body, {
55
+ httpMetadata: object.httpMetadata || {},
56
+ customMetadata,
57
+ ...(object.etag ? { onlyIf: { etagMatches: object.etag } } : {}),
58
+ });
59
+ if (object.etag && saved === null) {
60
+ return json({
61
+ ok: false,
62
+ code: "media_alt_conflict",
63
+ error: "Il file è cambiato durante il salvataggio. Riaprilo e riprova.",
64
+ }, 409);
65
+ }
66
+ return json({ ok: true, key, alt });
67
+ }
68
+
14
69
  export async function onRequestGet({ env }) {
15
70
  if (contentPersistenceMode() !== "d1") return unavailable();
16
71
  if (!env.CONTENT_DB) return json({ ok: false, code: "content_unavailable", error: "Persistenza contenuti non disponibile." }, 503);
@@ -145,7 +145,11 @@ export async function onRequestPost({ request, env, data }) {
145
145
  if (Object.hasOwn(body, "applyRefs")) return json({ ok: true, moved: 0, pagesUpdated: [], failed: [], d1: true });
146
146
  try {
147
147
  const result = await d1MoveMedia({ env, data, body });
148
- return json({ ok: true, ...result, pagesUpdated: result.documents.map((document) => document.kind), failed: [], warning: "Le sorgenti restano disponibili fino alla pubblicazione." });
148
+ return json({
149
+ ok: true, ...result,
150
+ pagesUpdated: result.publishedDocuments.map((document) => document.kind), failed: [],
151
+ warning: result.requiresPublication ? "Le pagine verranno pubblicate con i nuovi indirizzi prima di rimuovere le sorgenti." : undefined,
152
+ });
149
153
  } catch (error) {
150
154
  const code = error?.message === "unauthenticated" ? "unauthenticated" : error?.message === "media_source_busy" ? "media_source_busy" : "media_operation_unavailable";
151
155
  return json({ ok: false, code, error: code === "media_source_busy" ? "Questo Media è già in un'operazione in corso." : "Non riesco a registrare l'operazione Media D1." }, code === "unauthenticated" ? 401 : 409);
@@ -5,6 +5,7 @@
5
5
  import { isPrefix, json, guessMime, uniqueKey } from "../../_shared/assets.js";
6
6
  import { extractCapturedAt } from "../../_shared/exif.js";
7
7
  import { sizeFromBuffer } from "../../_shared/imagesize.js";
8
+ import { MEDIA_UPLOADED_METADATA_KEY } from "../../_shared/media-alt.js";
8
9
 
9
10
  export async function onRequestPost({ request, env }) {
10
11
  if (!env.MEDIA) return json({ ok: false, error: "Binding MEDIA non configurato" }, 500);
@@ -21,7 +22,7 @@ export async function onRequestPost({ request, env }) {
21
22
  if (!ctype || ctype === "application/octet-stream") ctype = guessMime(key);
22
23
 
23
24
  // data di scatto (EXIF) per l'ordinamento "Data scatto"
24
- const custom = {};
25
+ const custom = { [MEDIA_UPLOADED_METADATA_KEY]: new Date().toISOString() };
25
26
  const suppliedCapturedAt = request.headers.get("X-Captured-At") || "";
26
27
  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(suppliedCapturedAt)) {
27
28
  custom.capturedAt = suppliedCapturedAt;
@@ -52,6 +53,7 @@ export async function onRequestPost({ request, env }) {
52
53
  capturedAt: custom.capturedAt || null,
53
54
  w: wh ? wh[0] : null,
54
55
  h: wh ? wh[1] : null,
56
+ alt: { decorative: false, texts: {} },
55
57
  url: "/media/" + key.split("/").map(encodeURIComponent).join("/"),
56
58
  });
57
59
  }
@@ -4,8 +4,9 @@
4
4
  import { isPrefix, json, listKeysUnder } from "../_shared/assets.js";
5
5
  import { sizeFromBucket } from "../_shared/imagesize.js";
6
6
  import { pendingSourceKeys } from "../_shared/pending-media.js";
7
- import { contentPersistenceMode } from "../site.js";
7
+ import { contentPersistenceMode, languages } from "../site.js";
8
8
  import { d1PendingSourceKeys } from "../_shared/d1-media.js";
9
+ import { altLocales, mediaAltFromMetadata, MEDIA_UPLOADED_METADATA_KEY } from "../_shared/media-alt.js";
9
10
 
10
11
  const IMG = /\.(webp|jpe?g|png|avif|gif)$/i;
11
12
 
@@ -15,6 +16,7 @@ export async function onRequestGet({ request, env }) {
15
16
  let prefix = (url.searchParams.get("prefix") || "").trim();
16
17
  if (!isPrefix(prefix)) return json({ ok: false, error: `prefisso non valido: ${prefix}` }, 400);
17
18
  const pending = contentPersistenceMode() === "d1" ? await d1PendingSourceKeys(env.CONTENT_DB) : await pendingSourceKeys(env.MEDIA);
19
+ const locales = altLocales(languages());
18
20
 
19
21
  /* `recursive=1` guarda TUTTO quello che c'è sotto, a qualunque profondità: serve a chi deve
20
22
  * spostare o cancellare una cartella intera, che altrimenti si porterebbe dietro solo il primo
@@ -82,11 +84,12 @@ export async function onRequestGet({ request, env }) {
82
84
  name: o.key.slice(prefix.length),
83
85
  size: o.size,
84
86
  url: "/media/" + o.key.split("/").map(encodeURIComponent).join("/"),
85
- uploaded: o.uploaded,
87
+ uploaded: cm[MEDIA_UPLOADED_METADATA_KEY] || o.uploaded,
86
88
  capturedAt: cm.capturedAt || null,
87
89
  type: (o.httpMetadata && o.httpMetadata.contentType) || "",
88
90
  w: w > 0 ? w : null,
89
91
  h: h > 0 ? h : null,
92
+ alt: mediaAltFromMetadata(cm, locales),
90
93
  };
91
94
  }));
92
95
 
package/dist/gallery.d.ts CHANGED
@@ -3,6 +3,8 @@ export type GalleryImage = {
3
3
  w?: number | null;
4
4
  h?: number | null;
5
5
  hidden?: boolean;
6
+ /** Copia iniziale del default Media, modificabile nel contesto della singola gallery. */
7
+ alt?: string;
6
8
  };
7
9
  export type SectionType = "header" | "text" | "image" | "gallery";
8
10
  /** Una sezione della pagina gallery. Ha TUTTI i campi qualunque sia il tipo: Zod e React vogliono
package/dist/media.d.ts CHANGED
@@ -1,4 +1,16 @@
1
1
  import type { D1DatabaseLike } from "./persistence.js";
2
+ export declare function mediaPublicUrl(key: string): string;
3
+ /** Rewrites exactly the Media references owned by one operation. Exact array
4
+ * values are removed as array items; scalar slots become an empty string and
5
+ * are then accepted or rejected by the site's complete schema validator. */
6
+ export declare function rewriteMediaValue(value: unknown, input: {
7
+ replacements?: Readonly<Record<string, string>>;
8
+ removals?: readonly string[];
9
+ }): {
10
+ changed: boolean;
11
+ value?: unknown;
12
+ removed?: boolean;
13
+ };
2
14
  export declare const mediaOperationStates: readonly ["preparing", "ready", "blocked_in_use", "bound", "finalizing", "completed", "completed_with_warning", "cancelled", "failed"];
3
15
  export type MediaOperationState = typeof mediaOperationStates[number];
4
16
  export type MediaOperationType = "move" | "delete";
@@ -95,6 +107,11 @@ export declare class D1MediaOperationRepository {
95
107
  metadataJson: string | null;
96
108
  }): Promise<"pending" | "ready">;
97
109
  beginFinalization(operationId: string, releaseId: string, now: number): Promise<void>;
110
+ /** An operation whose sources occur in neither the public manifest nor any
111
+ * current draft needs no content release. The same guarded transition closes
112
+ * the last race before R2 cleanup; a concurrent reference makes it stay
113
+ * ready for the isolated-publication path instead. */
114
+ beginUnpublishedFinalization(operationId: string, now: number): Promise<boolean>;
98
115
  /** Individual cleanup writes are retryable. A single failed entry reaches
99
116
  * `completed_with_warning` only after every entry has a terminal result;
100
117
  * the already-live release is never rolled back. */
@@ -124,9 +141,11 @@ export declare class D1MediaOperationRepository {
124
141
  /** Work is named by its immutable release binding: there is intentionally no
125
142
  * "latest operation" cleanup path. */
126
143
  finalizationWork(releaseId: string): Promise<readonly BoundMediaEntry[]>;
144
+ unboundFinalizationWork(operationId: string): Promise<readonly BoundMediaEntry[]>;
127
145
  /** A warning is a live release with incomplete housekeeping. Retrying resets
128
146
  * only failed effects, never an already-completed entry. */
129
147
  resumeFinalization(operationId: string, releaseId: string, now: number): Promise<void>;
148
+ resumeUnboundFinalization(operationId: string, now: number): Promise<void>;
130
149
  readyDeleteEntry(input: {
131
150
  operationId: string;
132
151
  entryId: string;