@ozguraltan/strapi-content-input 1.0.21 → 1.0.23

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 (29) hide show
  1. package/README.md +42 -13
  2. package/dist/admin/{AnalyticsHubPage-DsrcGI_Y.mjs → AnalyticsHubPage-Dvpx3KsP.mjs} +168 -55
  3. package/dist/admin/{AnalyticsHubPage-0p0Mx4AU.js → AnalyticsHubPage-K_trli5i.js} +186 -55
  4. package/dist/admin/{ContentInputField-CHXrzvE-.mjs → ContentInputField-C2kmtUwD.mjs} +328 -366
  5. package/dist/admin/{ContentInputField-7rWLSx_7.js → ContentInputField-CjxYYEps.js} +343 -381
  6. package/dist/admin/{SurveyWidgetEditor-BVN6X_3G.mjs → SurveyWidgetEditor-DMWOkHUt.mjs} +3271 -227
  7. package/dist/admin/{SurveyWidgetEditor-BmgYQaQS.js → SurveyWidgetEditor-DOYxWop9.js} +3247 -203
  8. package/dist/admin/{index-hFIuYqu5.mjs → index-AePRA0IB.mjs} +2 -2
  9. package/dist/admin/{index-CZAwXCFH.js → index-B9C8Qrfd.js} +2 -2
  10. package/dist/admin/index.js +1 -1
  11. package/dist/admin/index.mjs +1 -1
  12. package/dist/admin/src/components/common/CIImageSettingsControl.d.ts +17 -0
  13. package/dist/admin/src/components/widgets/CustomCardWidgetEditor.d.ts +1 -0
  14. package/dist/admin/src/components/widgets/HeroSliderStage.d.ts +3 -0
  15. package/dist/admin/src/components/widgets/SurveyLivePreviewPane.d.ts +9 -0
  16. package/dist/admin/src/components/widgets/SurveyWidgetEditor.d.ts +3 -1
  17. package/dist/admin/src/core/canvasClasses.d.ts +1 -0
  18. package/dist/admin/src/core/types.d.ts +12 -0
  19. package/dist/server/index.js +1359 -196
  20. package/dist/server/index.mjs +1341 -196
  21. package/dist/server/src/config/index.d.ts +4 -0
  22. package/dist/server/src/controllers/ci-image.d.ts +11 -2
  23. package/dist/server/src/controllers/index.d.ts +1 -0
  24. package/dist/server/src/index.d.ts +15 -1
  25. package/dist/server/src/services/ci-survey.d.ts +10 -1
  26. package/dist/server/src/services/index.d.ts +10 -1
  27. package/dist/server/src/utils/image-variants.d.ts +74 -0
  28. package/dist/server/src/utils/surveyEngine.d.ts +5 -0
  29. package/package.json +1 -1
@@ -3,6 +3,7 @@ import fs from "fs";
3
3
  import { createRequire } from "module";
4
4
  import os from "os";
5
5
  import path from "path";
6
+ import * as XLSXNs from "xlsx";
6
7
  const register = ({ strapi }) => {
7
8
  strapi.customFields.register({
8
9
  name: "content-input",
@@ -29,6 +30,878 @@ const register = ({ strapi }) => {
29
30
  });
30
31
  }
31
32
  };
33
+ const inFlightVariants = /* @__PURE__ */ new Map();
34
+ function getSharp() {
35
+ const req = typeof require !== "undefined" ? require : createRequire(path.join(process.cwd(), "package.json"));
36
+ return req("sharp");
37
+ }
38
+ function getVariantConfig(strapi) {
39
+ const pluginCfg = strapi?.config?.get?.("plugin::content-input") || {};
40
+ const envFolder = process.env.CI_IMAGE_VARIANT_FOLDER;
41
+ const rawFolder = envFolder !== void 0 && String(envFolder).trim() !== "" ? String(envFolder).trim() : pluginCfg.imageVariantFolder !== void 0 ? pluginCfg.imageVariantFolder : "ci-optimized";
42
+ let folder = "ci-optimized";
43
+ if (rawFolder === null || rawFolder === false || String(rawFolder).trim().toLowerCase() === "none" || String(rawFolder).trim() === "/") {
44
+ folder = null;
45
+ } else {
46
+ const cleaned = String(rawFolder).trim().replace(/^\/+|\/+$/g, "");
47
+ folder = cleaned || "ci-optimized";
48
+ }
49
+ const rawFmt = String(
50
+ process.env.CI_IMAGE_VARIANT_FORMAT || pluginCfg.imageVariantFormat || "webp"
51
+ ).trim().toLowerCase();
52
+ const defaultFormat = rawFmt === "auto" ? "auto" : "webp";
53
+ const envRedirect = process.env.CI_IMAGE_REDIRECT_CDN;
54
+ const redirectProxyToCdn = envRedirect !== void 0 ? envRedirect !== "0" && envRedirect.toLowerCase() !== "false" : pluginCfg.redirectProxyToCdn !== false;
55
+ const defaultQuality = Math.min(
56
+ 100,
57
+ Math.max(40, Number(pluginCfg.imageVariantQuality) || 85)
58
+ );
59
+ return {
60
+ folder,
61
+ defaultFormat,
62
+ redirectProxyToCdn,
63
+ defaultQuality
64
+ };
65
+ }
66
+ function isAbsoluteHttpUrl(url) {
67
+ return Boolean(url && /^https?:\/\//i.test(String(url).trim()));
68
+ }
69
+ function isOptimizableRasterImage(mime, urlOrName) {
70
+ const m = String(mime || "").trim().toLowerCase();
71
+ const u = String(urlOrName || "").split("?")[0].split("#")[0].trim().toLowerCase();
72
+ if (u.startsWith("data:") || u.startsWith("blob:")) return false;
73
+ if (m.includes("svg") || m.includes("gif") || m.startsWith("video/") || m.startsWith("audio/") || m.startsWith("application/") || m.startsWith("text/")) {
74
+ return false;
75
+ }
76
+ if (/\.(svg|gif|mp4|webm|mov|m4v|mp3|wav|ogg|pdf|docx?|xlsx?|pptx?|zip|rar)$/i.test(u)) {
77
+ return false;
78
+ }
79
+ if (m === "image/jpeg" || m === "image/jpg" || m === "image/png" || m === "image/webp" || m === "image/avif" || m === "image/tiff" || m === "image/bmp") {
80
+ return true;
81
+ }
82
+ if (/\.(jpe?g|png|webp|avif|tiff?|bmp)$/i.test(u)) {
83
+ return true;
84
+ }
85
+ if (m.startsWith("image/")) {
86
+ return true;
87
+ }
88
+ return false;
89
+ }
90
+ async function loadSourceBuffer(strapi, src) {
91
+ const publicDir = strapi?.dirs?.static?.public || path.join(process.cwd(), "public");
92
+ if (src.startsWith("/")) {
93
+ const cleanRel = decodeURIComponent(src.split("?")[0]).replace(/^\/+/, "");
94
+ const fullPath = path.resolve(publicDir, cleanRel);
95
+ const resolvedPublic = path.resolve(publicDir);
96
+ if (!fullPath.startsWith(resolvedPublic)) {
97
+ throw new Error("Invalid local file path");
98
+ }
99
+ if (!fs.existsSync(fullPath)) {
100
+ throw new Error(`File not found: ${src}`);
101
+ }
102
+ const buffer = await fs.promises.readFile(fullPath);
103
+ const ext = path.extname(fullPath).toLowerCase();
104
+ const mime = ext === ".png" ? "image/png" : ext === ".webp" ? "image/webp" : ext === ".avif" ? "image/avif" : ext === ".gif" ? "image/gif" : "image/jpeg";
105
+ return { buffer, mime };
106
+ }
107
+ if (/^https?:\/\//i.test(src)) {
108
+ const parsed = new URL(src);
109
+ if ((parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1") && parsed.pathname.startsWith("/uploads/")) {
110
+ const cleanRel = decodeURIComponent(parsed.pathname).replace(/^\/+/, "");
111
+ const fullPath = path.resolve(publicDir, cleanRel);
112
+ if (fs.existsSync(fullPath)) {
113
+ const buffer = await fs.promises.readFile(fullPath);
114
+ const ext = path.extname(fullPath).toLowerCase();
115
+ const mime = ext === ".png" ? "image/png" : ext === ".webp" ? "image/webp" : "image/jpeg";
116
+ return { buffer, mime };
117
+ }
118
+ }
119
+ const res = await fetch(src);
120
+ if (!res.ok) {
121
+ throw new Error(`Failed to fetch remote image (${res.status})`);
122
+ }
123
+ const contentType = res.headers.get("content-type") || "image/jpeg";
124
+ const arr = await res.arrayBuffer();
125
+ return { buffer: Buffer.from(arr), mime: contentType };
126
+ }
127
+ throw new Error("Unsupported image source URL");
128
+ }
129
+ function normalizeImageProcessSpec(imageSettings, defaultAutoMaxW = 1920) {
130
+ const safeMaxW = Math.min(3840, Math.max(64, Math.round(Number(defaultAutoMaxW) || 1920)));
131
+ const rawProc = String(imageSettings?.process ?? "").trim().toLowerCase();
132
+ const rotate = parseInt(String(imageSettings?.rotate || "0"), 10) || 0;
133
+ const q = Math.min(100, Math.max(30, parseInt(String(imageSettings?.quality || "85"), 10) || 85));
134
+ if (rawProc === "none" || rawProc === "no-process" || rawProc === "original") {
135
+ return {
136
+ processMode: "none",
137
+ w: 0,
138
+ h: 0,
139
+ maxW: safeMaxW,
140
+ q,
141
+ rotate: 0
142
+ };
143
+ }
144
+ if (rawProc === "fit") {
145
+ const w = Math.min(3840, Math.max(0, Math.round(Number(imageSettings?.cWidth) || 0)));
146
+ const h = Math.min(3840, Math.max(0, Math.round(Number(imageSettings?.cHeight) || 0)));
147
+ if (w > 0 && h > 0) {
148
+ return { processMode: "fit", w, h, maxW: safeMaxW, q, rotate };
149
+ }
150
+ }
151
+ if (rawProc === "widen") {
152
+ const w = Math.min(3840, Math.max(0, Math.round(Number(imageSettings?.cWidth) || 0)));
153
+ if (w > 0) {
154
+ return { processMode: "widen", w, h: 0, maxW: safeMaxW, q, rotate };
155
+ }
156
+ }
157
+ const customAutoW = Number(imageSettings?.maxWidth || imageSettings?.cWidth);
158
+ const autoW = rawProc === "auto" && customAutoW > 0 ? Math.min(3840, Math.max(64, Math.round(customAutoW))) : safeMaxW;
159
+ return {
160
+ processMode: "auto",
161
+ w: autoW,
162
+ h: 0,
163
+ maxW: autoW,
164
+ q,
165
+ rotate
166
+ };
167
+ }
168
+ function computeCiFormatKey(processMode, w, h, rotate = 0) {
169
+ const effH = processMode === "fit" ? h : 0;
170
+ const effW = w;
171
+ return `ci_${processMode}_${effW}x${effH}${rotate ? `_r${rotate}` : ""}`;
172
+ }
173
+ function compactAssetFormats(formats) {
174
+ if (!formats || typeof formats !== "object") return void 0;
175
+ const out = {};
176
+ const keepStandard = /* @__PURE__ */ new Set(["thumbnail", "small", "medium", "large"]);
177
+ for (const [key, val] of Object.entries(formats)) {
178
+ if (!val || typeof val !== "object" || typeof val.url !== "string" || !val.url) continue;
179
+ if (!keepStandard.has(key) && !key.startsWith("ci_")) continue;
180
+ out[key] = {
181
+ url: val.url,
182
+ ...val.width ? { width: Number(val.width) } : {},
183
+ ...val.height ? { height: Number(val.height) } : {},
184
+ ...val.mime ? { mime: String(val.mime) } : {},
185
+ ...val.size ? { size: Number(val.size) } : {}
186
+ };
187
+ }
188
+ return Object.keys(out).length > 0 ? out : void 0;
189
+ }
190
+ function stripVariantPrefixFromHash(baseNameNoExt) {
191
+ return baseNameNoExt.replace(/^ci_(?:fit|widen|auto)_\d+x\d+(?:_r-?\d+)?_/, "");
192
+ }
193
+ async function findUploadFileForAsset(strapi, assetOrUrl, cache) {
194
+ if (!assetOrUrl) return null;
195
+ const fileQuery = strapi.db.query("plugin::upload.file");
196
+ const isObj = typeof assetOrUrl === "object";
197
+ const rawId = isObj ? assetOrUrl.id : void 0;
198
+ const rawHash = isObj ? assetOrUrl.hash : void 0;
199
+ const rawUrl = isObj ? assetOrUrl.original_url || assetOrUrl.url || assetOrUrl.target_url || assetOrUrl.src || "" : String(assetOrUrl || "");
200
+ const cleanUrl = String(rawUrl || "").split("?")[0].split("#")[0].trim();
201
+ const cacheKey = rawId ? `id:${rawId}` : rawHash ? `hash:${rawHash}` : cleanUrl ? `url:${cleanUrl}` : "";
202
+ if (cache && cacheKey && cache.has(cacheKey)) {
203
+ return cache.get(cacheKey);
204
+ }
205
+ let found = null;
206
+ const remember = (record) => {
207
+ if (cache) {
208
+ if (cacheKey) cache.set(cacheKey, record);
209
+ if (record?.id) cache.set(`id:${record.id}`, record);
210
+ if (record?.hash) cache.set(`hash:${record.hash}`, record);
211
+ if (record?.url) cache.set(`url:${String(record.url).split("?")[0]}`, record);
212
+ }
213
+ return record;
214
+ };
215
+ if (rawId !== void 0 && rawId !== null && rawId !== "") {
216
+ const numId = Number(rawId);
217
+ if (!Number.isNaN(numId) && numId > 0) {
218
+ found = await fileQuery.findOne({ where: { id: numId } });
219
+ if (found) return remember(found);
220
+ }
221
+ }
222
+ if (rawHash && typeof rawHash === "string") {
223
+ const parentHash = stripVariantPrefixFromHash(rawHash.trim());
224
+ found = await fileQuery.findOne({ where: { hash: parentHash } });
225
+ if (found) return remember(found);
226
+ }
227
+ if (!cleanUrl) return remember(null);
228
+ found = await fileQuery.findOne({ where: { url: cleanUrl } });
229
+ if (found) return remember(found);
230
+ let pathnameStr = cleanUrl;
231
+ if (/^https?:\/\//i.test(cleanUrl)) {
232
+ try {
233
+ pathnameStr = decodeURIComponent(new URL(cleanUrl).pathname);
234
+ } catch {
235
+ pathnameStr = cleanUrl;
236
+ }
237
+ if (pathnameStr && pathnameStr !== cleanUrl) {
238
+ found = await fileQuery.findOne({ where: { url: pathnameStr } });
239
+ if (found) return remember(found);
240
+ }
241
+ }
242
+ const baseName = path.posix.basename(pathnameStr);
243
+ const ext = path.posix.extname(baseName);
244
+ const baseNoExt = ext ? baseName.slice(0, -ext.length) : baseName;
245
+ if (baseNoExt) {
246
+ const candidateHash = stripVariantPrefixFromHash(baseNoExt);
247
+ if (candidateHash) {
248
+ found = await fileQuery.findOne({ where: { hash: candidateHash } });
249
+ if (found) return remember(found);
250
+ }
251
+ }
252
+ return remember(null);
253
+ }
254
+ async function renderSharpVariantBuffer(sourceBuffer, sourceMime, opts) {
255
+ const sharp = getSharp();
256
+ let pipeline = sharp(sourceBuffer, { failOn: "none" }).rotate();
257
+ const rotate = opts.rotate || 0;
258
+ if (rotate && [90, 180, 270, -90].includes(rotate)) {
259
+ pipeline = pipeline.rotate(rotate);
260
+ }
261
+ const cw = opts.cw || 0;
262
+ const ch = opts.ch || 0;
263
+ if (cw > 0 && ch > 0) {
264
+ pipeline = pipeline.extract({
265
+ left: Math.max(0, opts.cx || 0),
266
+ top: Math.max(0, opts.cy || 0),
267
+ width: cw,
268
+ height: ch
269
+ });
270
+ }
271
+ const { processMode, w, h, q } = opts;
272
+ if (processMode === "fit" && w > 0 && h > 0) {
273
+ pipeline = pipeline.resize(w, h, {
274
+ fit: "cover",
275
+ position: "centre",
276
+ withoutEnlargement: false
277
+ });
278
+ } else if (processMode === "widen" && w > 0) {
279
+ pipeline = pipeline.resize(w, null, {
280
+ fit: "inside",
281
+ withoutEnlargement: false
282
+ });
283
+ } else if (processMode === "auto" && w > 0) {
284
+ pipeline = pipeline.resize(w, null, {
285
+ fit: "inside",
286
+ withoutEnlargement: true
287
+ });
288
+ } else if (w > 0 || h > 0) {
289
+ pipeline = pipeline.resize(w || null, h || null, {
290
+ fit: "inside",
291
+ withoutEnlargement: true
292
+ });
293
+ }
294
+ const reqFmt = String(opts.requestedFormat || "").trim().toLowerCase();
295
+ const preferWebp = reqFmt === "webp" || !reqFmt && (opts.defaultFormat || "webp") === "webp";
296
+ let contentType = sourceMime || "image/webp";
297
+ let ext = ".webp";
298
+ if (reqFmt === "avif") {
299
+ pipeline = pipeline.avif({ quality: q });
300
+ contentType = "image/avif";
301
+ ext = ".avif";
302
+ } else if (reqFmt === "png") {
303
+ pipeline = pipeline.png({ quality: q });
304
+ contentType = "image/png";
305
+ ext = ".png";
306
+ } else if (reqFmt === "jpg" || reqFmt === "jpeg") {
307
+ pipeline = pipeline.jpeg({ quality: q, mozjpeg: true });
308
+ contentType = "image/jpeg";
309
+ ext = ".jpg";
310
+ } else if (preferWebp || sourceMime === "image/webp") {
311
+ pipeline = pipeline.webp({ quality: q, alphaQuality: 100, effort: 4 });
312
+ contentType = "image/webp";
313
+ ext = ".webp";
314
+ } else if (sourceMime === "image/avif") {
315
+ pipeline = pipeline.avif({ quality: q });
316
+ contentType = "image/avif";
317
+ ext = ".avif";
318
+ } else if (sourceMime === "image/png") {
319
+ pipeline = pipeline.png({ quality: q });
320
+ contentType = "image/png";
321
+ ext = ".png";
322
+ } else {
323
+ pipeline = pipeline.jpeg({ quality: q, mozjpeg: true });
324
+ contentType = "image/jpeg";
325
+ ext = ".jpg";
326
+ }
327
+ const outputBuffer = await pipeline.toBuffer();
328
+ const outMeta = await sharp(outputBuffer).metadata();
329
+ return {
330
+ buffer: outputBuffer,
331
+ contentType,
332
+ ext,
333
+ width: outMeta.width || w || void 0,
334
+ height: outMeta.height || h || void 0
335
+ };
336
+ }
337
+ async function ensureMediaVariant(strapi, existingFile, spec) {
338
+ const formatKey = computeCiFormatKey(
339
+ spec.processMode,
340
+ spec.w,
341
+ spec.h,
342
+ spec.rotate || 0
343
+ );
344
+ if (!existingFile?.id || !existingFile?.url) {
345
+ return { formatKey, formatEntry: null, updatedFile: existingFile };
346
+ }
347
+ if (!isOptimizableRasterImage(existingFile.mime, existingFile.ext || existingFile.url)) {
348
+ return { formatKey, formatEntry: null, updatedFile: existingFile };
349
+ }
350
+ const already = existingFile.formats?.[formatKey];
351
+ if (already?.url) {
352
+ return { formatKey, formatEntry: already, updatedFile: existingFile };
353
+ }
354
+ const lockKey = `${existingFile.id}:${formatKey}`;
355
+ const activePromise = inFlightVariants.get(lockKey);
356
+ if (activePromise) {
357
+ return activePromise;
358
+ }
359
+ const task = (async () => {
360
+ const cfg = getVariantConfig(strapi);
361
+ const freshCheck = await strapi.db.query("plugin::upload.file").findOne({
362
+ where: { id: existingFile.id }
363
+ });
364
+ const baseRecord = freshCheck || existingFile;
365
+ if (baseRecord.formats?.[formatKey]?.url) {
366
+ return {
367
+ formatKey,
368
+ formatEntry: baseRecord.formats[formatKey],
369
+ updatedFile: baseRecord
370
+ };
371
+ }
372
+ const { buffer: sourceBuffer, mime: sourceMime } = await loadSourceBuffer(
373
+ strapi,
374
+ baseRecord.url
375
+ );
376
+ const rendered = await renderSharpVariantBuffer(
377
+ sourceBuffer,
378
+ baseRecord.mime || sourceMime,
379
+ {
380
+ processMode: spec.processMode,
381
+ w: spec.w,
382
+ h: spec.h,
383
+ q: spec.q || cfg.defaultQuality,
384
+ rotate: spec.rotate || 0,
385
+ requestedFormat: spec.requestedFormat,
386
+ defaultFormat: cfg.defaultFormat
387
+ }
388
+ );
389
+ const fallbackShortHash = crypto.createHash("sha1").update(String(baseRecord.url)).digest("hex").slice(0, 10);
390
+ const cleanBaseName = path.basename(
391
+ baseRecord.name || "image",
392
+ path.extname(baseRecord.name || "")
393
+ );
394
+ const variantHash = `${formatKey}_${baseRecord.hash || fallbackShortHash}`;
395
+ const variantName = `${formatKey}_${cleanBaseName}${rendered.ext}`;
396
+ const tmpVariantPath = path.join(
397
+ os.tmpdir(),
398
+ `${variantHash}_${Date.now()}_${Math.random().toString(36).slice(2, 6)}${rendered.ext}`
399
+ );
400
+ await fs.promises.writeFile(tmpVariantPath, rendered.buffer);
401
+ try {
402
+ const variantFile = {
403
+ name: variantName,
404
+ hash: variantHash,
405
+ ext: rendered.ext,
406
+ mime: rendered.contentType,
407
+ filepath: tmpVariantPath,
408
+ path: cfg.folder !== null ? cfg.folder : baseRecord.path || null,
409
+ getStream: () => fs.createReadStream(tmpVariantPath),
410
+ width: rendered.width,
411
+ height: rendered.height,
412
+ size: Math.round(rendered.buffer.length / 1e3 * 100) / 100,
413
+ sizeInBytes: rendered.buffer.length
414
+ };
415
+ const providerService = strapi.plugin("upload").service("provider");
416
+ if (!providerService || typeof providerService.upload !== "function") {
417
+ return { formatKey, formatEntry: null, updatedFile: baseRecord };
418
+ }
419
+ await providerService.upload(variantFile);
420
+ const { filepath: _fp, getStream: _gs, ...serializableFormat } = variantFile;
421
+ const latestRecord = await strapi.db.query("plugin::upload.file").findOne({
422
+ where: { id: baseRecord.id }
423
+ }) || baseRecord;
424
+ const nextFormats = {
425
+ ...latestRecord.formats || {},
426
+ [formatKey]: serializableFormat
427
+ };
428
+ const updatedFile = await strapi.db.query("plugin::upload.file").update({
429
+ where: { id: baseRecord.id },
430
+ data: { formats: nextFormats }
431
+ });
432
+ existingFile.formats = nextFormats;
433
+ return {
434
+ formatKey,
435
+ formatEntry: serializableFormat,
436
+ updatedFile: updatedFile || { ...latestRecord, formats: nextFormats }
437
+ };
438
+ } finally {
439
+ await fs.promises.rm(tmpVariantPath, { force: true }).catch(() => void 0);
440
+ }
441
+ })();
442
+ inFlightVariants.set(lockKey, task);
443
+ try {
444
+ return await task;
445
+ } finally {
446
+ inFlightVariants.delete(lockKey);
447
+ }
448
+ }
449
+ async function clearGeneratedCiVariantsForFile(strapi, fileRecord) {
450
+ if (!fileRecord?.id || !fileRecord?.formats || typeof fileRecord.formats !== "object") {
451
+ return;
452
+ }
453
+ const providerService = strapi.plugin("upload")?.service?.("provider");
454
+ const nextFormats = {};
455
+ const removedFormats = [];
456
+ for (const [k, fmt] of Object.entries(fileRecord.formats)) {
457
+ if (k.startsWith("ci_")) {
458
+ removedFormats.push(fmt);
459
+ } else {
460
+ nextFormats[k] = fmt;
461
+ }
462
+ }
463
+ if (removedFormats.length === 0) return;
464
+ if (providerService && typeof providerService.delete === "function") {
465
+ for (const fmt of removedFormats) {
466
+ try {
467
+ await providerService.delete(fmt);
468
+ } catch {
469
+ }
470
+ }
471
+ }
472
+ await strapi.db.query("plugin::upload.file").update({
473
+ where: { id: fileRecord.id },
474
+ data: { formats: nextFormats }
475
+ });
476
+ }
477
+ async function enrichMediaAssetNode(strapi, asset, opts = {}) {
478
+ if (!asset) return asset;
479
+ const isStringInput = typeof asset === "string";
480
+ const rawUrl = isStringInput ? asset : asset.original_url || asset.url || asset.target_url || asset.src || "";
481
+ if (!rawUrl || typeof rawUrl !== "string") return asset;
482
+ const fileRecord = await findUploadFileForAsset(strapi, asset, opts.fileCache);
483
+ if (!fileRecord) {
484
+ return asset;
485
+ }
486
+ const canonicalMasterUrl = fileRecord.url || rawUrl;
487
+ if (!isOptimizableRasterImage(fileRecord.mime, fileRecord.ext || canonicalMasterUrl)) {
488
+ if (isStringInput) return canonicalMasterUrl;
489
+ return {
490
+ ...asset,
491
+ id: fileRecord.id,
492
+ hash: fileRecord.hash,
493
+ original_url: canonicalMasterUrl,
494
+ url: canonicalMasterUrl,
495
+ target_url: canonicalMasterUrl
496
+ };
497
+ }
498
+ const spec = normalizeImageProcessSpec(
499
+ opts.imageSettings,
500
+ opts.defaultAutoMaxW || 1920
501
+ );
502
+ let latestFile = fileRecord;
503
+ let activeVariantUrl;
504
+ if (spec.processMode !== "none") {
505
+ try {
506
+ const primary = await ensureMediaVariant(strapi, latestFile, {
507
+ processMode: spec.processMode,
508
+ w: spec.w,
509
+ h: spec.h,
510
+ q: spec.q,
511
+ rotate: spec.rotate
512
+ });
513
+ latestFile = primary.updatedFile || latestFile;
514
+ if (primary.formatEntry?.url) {
515
+ activeVariantUrl = primary.formatEntry.url;
516
+ }
517
+ } catch (err) {
518
+ strapi.log?.warn?.(
519
+ `[content-input] Image variant generation skipped for "${canonicalMasterUrl}": ${err?.message || err}`
520
+ );
521
+ }
522
+ }
523
+ if (opts.alsoEnsureAutoMaxW && opts.alsoEnsureAutoMaxW > 0 && spec.processMode !== "none" && !(spec.processMode === "auto" && spec.w === opts.alsoEnsureAutoMaxW)) {
524
+ try {
525
+ const secondary = await ensureMediaVariant(strapi, latestFile, {
526
+ processMode: "auto",
527
+ w: opts.alsoEnsureAutoMaxW,
528
+ h: 0,
529
+ q: spec.q
530
+ });
531
+ latestFile = secondary.updatedFile || latestFile;
532
+ } catch {
533
+ }
534
+ }
535
+ if (opts.fileCache && latestFile?.id) {
536
+ opts.fileCache.set(`id:${latestFile.id}`, latestFile);
537
+ if (latestFile.hash) opts.fileCache.set(`hash:${latestFile.hash}`, latestFile);
538
+ if (latestFile.url) opts.fileCache.set(`url:${String(latestFile.url).split("?")[0]}`, latestFile);
539
+ }
540
+ const compactFormats = compactAssetFormats(latestFile.formats);
541
+ if (isStringInput) {
542
+ return activeVariantUrl || canonicalMasterUrl;
543
+ }
544
+ const nextAsset = {
545
+ ...asset,
546
+ id: latestFile.id,
547
+ hash: latestFile.hash,
548
+ original_url: canonicalMasterUrl,
549
+ url: canonicalMasterUrl,
550
+ target_url: canonicalMasterUrl,
551
+ filename: asset.filename || asset.name || latestFile.name || "image",
552
+ mime_type: asset.mime_type || latestFile.mime || "image/webp",
553
+ width: asset.width || latestFile.width || void 0,
554
+ height: asset.height || latestFile.height || void 0
555
+ };
556
+ if (spec.processMode === "none") {
557
+ delete nextAsset.optimized_url;
558
+ } else if (activeVariantUrl) {
559
+ nextAsset.optimized_url = activeVariantUrl;
560
+ }
561
+ if (compactFormats) {
562
+ nextAsset.formats = compactFormats;
563
+ }
564
+ return nextAsset;
565
+ }
566
+ async function runWithConcurrency(tasks, concurrency = 3) {
567
+ const results = new Array(tasks.length);
568
+ let cursor = 0;
569
+ async function worker() {
570
+ while (cursor < tasks.length) {
571
+ const idx = cursor++;
572
+ results[idx] = await tasks[idx]();
573
+ }
574
+ }
575
+ const poolSize = Math.min(Math.max(1, concurrency), tasks.length);
576
+ await Promise.all(Array.from({ length: poolSize }, () => worker()));
577
+ return results;
578
+ }
579
+ async function optimizeHtmlImgSources(strapi, html, fileCache) {
580
+ if (!html || typeof html !== "string" || !html.includes("<img")) return html;
581
+ const imgRegex = /(<img\b[^>]*?\bsrc=(["']))([^"']+)(\2[^>]*>)/gi;
582
+ const matches = Array.from(html.matchAll(imgRegex));
583
+ if (matches.length === 0) return html;
584
+ const replacements = /* @__PURE__ */ new Map();
585
+ const uniqueSrcs = Array.from(new Set(matches.map((m) => m[3]).filter(Boolean)));
586
+ await runWithConcurrency(
587
+ uniqueSrcs.map((srcUrl) => async () => {
588
+ if (!isOptimizableRasterImage(void 0, srcUrl)) return;
589
+ const fileRecord = await findUploadFileForAsset(strapi, srcUrl, fileCache);
590
+ if (!fileRecord) return;
591
+ if (!isOptimizableRasterImage(fileRecord.mime, fileRecord.ext || fileRecord.url)) return;
592
+ try {
593
+ const res = await ensureMediaVariant(strapi, fileRecord, {
594
+ processMode: "auto",
595
+ w: 1600,
596
+ h: 0
597
+ });
598
+ if (res.formatEntry?.url) {
599
+ replacements.set(srcUrl, res.formatEntry.url);
600
+ }
601
+ } catch {
602
+ }
603
+ }),
604
+ 3
605
+ );
606
+ if (replacements.size === 0) return html;
607
+ return html.replace(imgRegex, (full, prefix, _quote, srcVal, suffix) => {
608
+ const nextUrl = replacements.get(srcVal);
609
+ return nextUrl ? `${prefix}${nextUrl}${suffix}` : full;
610
+ });
611
+ }
612
+ async function syncContentInputTreeMedia(strapi, rawValue) {
613
+ if (!rawValue) return rawValue;
614
+ const wasString = typeof rawValue === "string";
615
+ let parsed = rawValue;
616
+ if (wasString) {
617
+ const trimmed = rawValue.trim();
618
+ if (!trimmed) return rawValue;
619
+ try {
620
+ parsed = JSON.parse(trimmed);
621
+ } catch {
622
+ return rawValue;
623
+ }
624
+ }
625
+ if (!Array.isArray(parsed)) {
626
+ return rawValue;
627
+ }
628
+ const rows = JSON.parse(JSON.stringify(parsed));
629
+ const fileCache = /* @__PURE__ */ new Map();
630
+ const jobs = [];
631
+ const scheduleAsset = (holder, key, opts) => {
632
+ const current = holder?.[key];
633
+ if (!current) return;
634
+ jobs.push(async () => {
635
+ holder[key] = await enrichMediaAssetNode(strapi, current, {
636
+ ...opts,
637
+ fileCache
638
+ });
639
+ });
640
+ };
641
+ const scheduleHtml = (holder, key) => {
642
+ const val = holder?.[key];
643
+ if (typeof val !== "string" || !val.includes("<img")) return;
644
+ jobs.push(async () => {
645
+ holder[key] = await optimizeHtmlImgSources(strapi, val, fileCache);
646
+ });
647
+ };
648
+ const walkRows = (rowList) => {
649
+ if (!Array.isArray(rowList)) return;
650
+ for (const row of rowList) {
651
+ if (!row || typeof row !== "object") continue;
652
+ if (row.bgImage) {
653
+ scheduleAsset(row, "bgImage", {
654
+ imageSettings: row.bgOptions?.imageSettings,
655
+ defaultAutoMaxW: 1920
656
+ });
657
+ }
658
+ const blocks = Array.isArray(row.blocks) ? row.blocks : [];
659
+ for (const block of blocks) {
660
+ if (!block || typeof block !== "object") continue;
661
+ if (block.bgImage) {
662
+ scheduleAsset(block, "bgImage", {
663
+ imageSettings: block.bgOptions?.imageSettings,
664
+ defaultAutoMaxW: 1920
665
+ });
666
+ }
667
+ const widgets = Array.isArray(block.widgets) ? block.widgets : [];
668
+ for (const widget of widgets) {
669
+ if (!widget || typeof widget !== "object") continue;
670
+ const wId = widget.id;
671
+ const wOpts = widget.options || {};
672
+ const wData = widget.data;
673
+ if (wId === "gallery") {
674
+ const list = Array.isArray(wData) ? wData : Array.isArray(wData?.images) ? wData.images : null;
675
+ if (list) {
676
+ const popupEnabled = wOpts.popup !== false;
677
+ for (let i = 0; i < list.length; i++) {
678
+ scheduleAsset(list, i, {
679
+ imageSettings: wOpts.imageSettings,
680
+ defaultAutoMaxW: 1600,
681
+ alsoEnsureAutoMaxW: popupEnabled ? 1920 : 0
682
+ });
683
+ }
684
+ }
685
+ } else if (wId === "singleImage" && wData && typeof wData === "object") {
686
+ if (wData.image) {
687
+ scheduleAsset(wData, "image", {
688
+ imageSettings: wOpts.imageSettings || wData.imageSettings,
689
+ defaultAutoMaxW: 1920
690
+ });
691
+ } else if (wData.url || wData.target_url) {
692
+ scheduleAsset(widget, "data", {
693
+ imageSettings: wOpts.imageSettings,
694
+ defaultAutoMaxW: 1920
695
+ });
696
+ }
697
+ } else if (wId === "banner" && wData && typeof wData === "object") {
698
+ if (wData.image) {
699
+ scheduleAsset(wData, "image", {
700
+ imageSettings: wOpts.imageSettings || wData.imageSettings,
701
+ defaultAutoMaxW: 1920
702
+ });
703
+ }
704
+ } else if (wId === "youtubeVideo") {
705
+ if (wOpts.thumbnailImage) {
706
+ scheduleAsset(wOpts, "thumbnailImage", {
707
+ imageSettings: wOpts.imageSettings,
708
+ defaultAutoMaxW: 1280
709
+ });
710
+ }
711
+ if (Array.isArray(wData)) {
712
+ for (const vid of wData) {
713
+ if (vid && typeof vid === "object" && vid.customThumbnail) {
714
+ scheduleAsset(vid, "customThumbnail", {
715
+ imageSettings: wOpts.imageSettings,
716
+ defaultAutoMaxW: 1280
717
+ });
718
+ }
719
+ }
720
+ } else if (wData && typeof wData === "object" && wData.customThumbnail) {
721
+ scheduleAsset(wData, "customThumbnail", {
722
+ imageSettings: wOpts.imageSettings,
723
+ defaultAutoMaxW: 1280
724
+ });
725
+ }
726
+ } else if (wId === "heroSlider" && wData && typeof wData === "object") {
727
+ const globalHeroImgSettings = wData.settings?.imageSettings || wOpts.imageSettings;
728
+ const slides = Array.isArray(wData.slides) ? wData.slides : [];
729
+ for (const slide of slides) {
730
+ if (!slide || typeof slide !== "object") continue;
731
+ if (slide.bgImage) {
732
+ scheduleAsset(slide, "bgImage", {
733
+ imageSettings: slide.imageSettings || globalHeroImgSettings,
734
+ defaultAutoMaxW: 1920
735
+ });
736
+ }
737
+ if (slide.mobileBgImage) {
738
+ scheduleAsset(slide, "mobileBgImage", {
739
+ imageSettings: slide.mobileImageSettings,
740
+ defaultAutoMaxW: 1080
741
+ });
742
+ }
743
+ const layers = Array.isArray(slide.layers) ? slide.layers : [];
744
+ for (const layer of layers) {
745
+ if (layer && typeof layer === "object" && layer.image) {
746
+ scheduleAsset(layer, "image", {
747
+ imageSettings: layer.imageSettings,
748
+ defaultAutoMaxW: 1200
749
+ });
750
+ }
751
+ }
752
+ }
753
+ } else if (wId === "customCard" && wData && typeof wData === "object") {
754
+ const cardImgSettings = wData.design?.imageSettings || wOpts.imageSettings;
755
+ const cards = Array.isArray(wData.cards) ? wData.cards : [];
756
+ for (const card of cards) {
757
+ if (!card || typeof card !== "object") continue;
758
+ if (card.image) {
759
+ scheduleAsset(card, "image", {
760
+ imageSettings: cardImgSettings,
761
+ defaultAutoMaxW: 960
762
+ });
763
+ }
764
+ if (card.authorAvatar) {
765
+ scheduleAsset(card, "authorAvatar", {
766
+ imageSettings: { process: "fit", cWidth: 240, cHeight: 240 },
767
+ defaultAutoMaxW: 240
768
+ });
769
+ }
770
+ }
771
+ } else if (wId === "entityCard" && wData && typeof wData === "object") {
772
+ const ecImgSettings = wOpts.imageSettings || wOpts.cardProps?.imageSettings;
773
+ if (wData.overrides?.image) {
774
+ scheduleAsset(wData.overrides, "image", {
775
+ imageSettings: ecImgSettings,
776
+ defaultAutoMaxW: 960
777
+ });
778
+ }
779
+ if (wData.entity?.image) {
780
+ scheduleAsset(wData.entity, "image", {
781
+ imageSettings: ecImgSettings,
782
+ defaultAutoMaxW: 960
783
+ });
784
+ }
785
+ if (Array.isArray(wData.items)) {
786
+ for (const item of wData.items) {
787
+ if (!item || typeof item !== "object") continue;
788
+ if (item.overrides?.image) {
789
+ scheduleAsset(item.overrides, "image", {
790
+ imageSettings: ecImgSettings,
791
+ defaultAutoMaxW: 960
792
+ });
793
+ }
794
+ if (item.entity?.image) {
795
+ scheduleAsset(item.entity, "image", {
796
+ imageSettings: ecImgSettings,
797
+ defaultAutoMaxW: 960
798
+ });
799
+ }
800
+ }
801
+ }
802
+ } else if (wId === "HtmlEditor") {
803
+ if (typeof wData === "string") {
804
+ scheduleHtml(widget, "data");
805
+ } else if (wData && typeof wData === "object" && typeof wData.content === "string") {
806
+ scheduleHtml(wData, "content");
807
+ }
808
+ } else if (wId === "tab" || wId === "accordion") {
809
+ const nodes = Array.isArray(wData) ? wData : Array.isArray(wData?.nodes) ? wData.nodes : Array.isArray(wData?.tabs) ? wData.tabs : [];
810
+ for (const node of nodes) {
811
+ if (!node || typeof node !== "object") continue;
812
+ if (Array.isArray(node.rows)) walkRows(node.rows);
813
+ if (Array.isArray(node.content)) walkRows(node.content);
814
+ if (Array.isArray(node.content?.data)) walkRows(node.content.data);
815
+ if (typeof node.html === "string") scheduleHtml(node, "html");
816
+ if (typeof node.content === "string") scheduleHtml(node, "content");
817
+ if (typeof node.content?.html === "string") scheduleHtml(node.content, "html");
818
+ }
819
+ } else if (wId === "survey" && wData && typeof wData === "object") {
820
+ const qLists = [wData.questions, wData.survey?.questions].filter(Array.isArray);
821
+ for (const qList of qLists) {
822
+ for (const q of qList) {
823
+ if (!q || typeof q !== "object" || !Array.isArray(q.options)) continue;
824
+ for (const opt of q.options) {
825
+ if (opt && typeof opt === "object" && opt.image) {
826
+ scheduleAsset(opt, "image", {
827
+ defaultAutoMaxW: 800
828
+ });
829
+ }
830
+ }
831
+ }
832
+ }
833
+ } else if (wId === "dataTable" && wData && typeof wData === "object") {
834
+ const cols = Array.isArray(wData.columns) ? wData.columns : [];
835
+ const imageColKeys = cols.filter((c) => c && c.type === "image" && c.key).map((c) => String(c.key));
836
+ const dtRows = Array.isArray(wData.rows) ? wData.rows : [];
837
+ if (imageColKeys.length > 0 && dtRows.length > 0) {
838
+ for (const dtRow of dtRows) {
839
+ if (!dtRow || typeof dtRow !== "object") continue;
840
+ for (const key of imageColKeys) {
841
+ if (dtRow[key]) {
842
+ scheduleAsset(dtRow, key, {
843
+ defaultAutoMaxW: 800
844
+ });
845
+ }
846
+ }
847
+ }
848
+ }
849
+ }
850
+ }
851
+ }
852
+ }
853
+ };
854
+ walkRows(rows);
855
+ if (jobs.length > 0) {
856
+ await runWithConcurrency(jobs, 3);
857
+ }
858
+ return wasString ? JSON.stringify(rows) : rows;
859
+ }
860
+ async function syncSurveyQuestionsMedia(strapi, questions) {
861
+ if (!Array.isArray(questions) || questions.length === 0) return questions;
862
+ const cloned = JSON.parse(JSON.stringify(questions));
863
+ const fileCache = /* @__PURE__ */ new Map();
864
+ const jobs = [];
865
+ for (const q of cloned) {
866
+ if (!q || typeof q !== "object" || !Array.isArray(q.options)) continue;
867
+ for (const opt of q.options) {
868
+ if (opt && typeof opt === "object" && opt.image) {
869
+ jobs.push(async () => {
870
+ opt.image = await enrichMediaAssetNode(strapi, opt.image, {
871
+ defaultAutoMaxW: 800,
872
+ fileCache
873
+ });
874
+ });
875
+ }
876
+ }
877
+ }
878
+ if (jobs.length > 0) {
879
+ await runWithConcurrency(jobs, 3);
880
+ }
881
+ return cloned;
882
+ }
883
+ function collectContentInputModelFields(strapi) {
884
+ const map = /* @__PURE__ */ new Map();
885
+ const inspectSchemas = (schemas) => {
886
+ if (!schemas || typeof schemas !== "object") return;
887
+ for (const [uid, schema] of Object.entries(schemas)) {
888
+ const attrs = schema?.attributes;
889
+ if (!attrs || typeof attrs !== "object") continue;
890
+ const matchingFields = [];
891
+ for (const [fieldName, attrDef] of Object.entries(attrs)) {
892
+ if (attrDef?.customField === "plugin::content-input.content-input") {
893
+ matchingFields.push(fieldName);
894
+ }
895
+ }
896
+ if (matchingFields.length > 0) {
897
+ map.set(uid, matchingFields);
898
+ }
899
+ }
900
+ };
901
+ inspectSchemas(strapi.contentTypes);
902
+ inspectSchemas(strapi.components);
903
+ return map;
904
+ }
32
905
  const bootstrap = async ({ strapi }) => {
33
906
  try {
34
907
  await strapi.plugin("content-input").service("ci-color").ensureSeeded();
@@ -37,12 +910,66 @@ const bootstrap = async ({ strapi }) => {
37
910
  } catch (err) {
38
911
  strapi.log.warn(`[content-input] Bootstrap seed skipped: ${err?.message || err}`);
39
912
  }
913
+ try {
914
+ const modelFieldMap = collectContentInputModelFields(strapi);
915
+ const surveyUid = "plugin::content-input.ci-survey";
916
+ const subscribedModels = Array.from(/* @__PURE__ */ new Set([...modelFieldMap.keys(), surveyUid]));
917
+ if (subscribedModels.length > 0 && strapi.db?.lifecycles?.subscribe) {
918
+ const processEventData = async (event) => {
919
+ const uid = event?.model?.uid;
920
+ const data = event?.params?.data;
921
+ if (!uid || !data || typeof data !== "object") return;
922
+ if (uid === surveyUid) {
923
+ if (Array.isArray(data.questions) && data.questions.length > 0) {
924
+ try {
925
+ data.questions = await syncSurveyQuestionsMedia(strapi, data.questions);
926
+ } catch (err) {
927
+ strapi.log.warn(
928
+ `[content-input] Survey media optimization warning: ${err?.message || err}`
929
+ );
930
+ }
931
+ }
932
+ return;
933
+ }
934
+ const fields = modelFieldMap.get(uid);
935
+ if (!fields || fields.length === 0) return;
936
+ for (const fieldName of fields) {
937
+ if (data[fieldName] !== void 0 && data[fieldName] !== null) {
938
+ try {
939
+ data[fieldName] = await syncContentInputTreeMedia(strapi, data[fieldName]);
940
+ } catch (err) {
941
+ strapi.log.warn(
942
+ `[content-input] Media sync warning on ${uid}.${fieldName}: ${err?.message || err}`
943
+ );
944
+ }
945
+ }
946
+ }
947
+ };
948
+ strapi.db.lifecycles.subscribe({
949
+ models: subscribedModels,
950
+ async beforeCreate(event) {
951
+ await processEventData(event);
952
+ },
953
+ async beforeUpdate(event) {
954
+ await processEventData(event);
955
+ }
956
+ });
957
+ }
958
+ } catch (err) {
959
+ strapi.log.warn(
960
+ `[content-input] Lifecycle registration skipped: ${err?.message || err}`
961
+ );
962
+ }
40
963
  };
41
964
  const destroy = ({ strapi }) => {
42
965
  };
43
966
  const config = {
44
967
  default: {
45
- previewUrl: "/ci-preview"
968
+ previewUrl: "/ci-preview",
969
+ imageVariantFolder: process.env.CI_IMAGE_VARIANT_FOLDER || "ci-optimized",
970
+ imageVariantFormat: process.env.CI_IMAGE_VARIANT_FORMAT || "webp",
971
+ imageVariantQuality: 85,
972
+ redirectProxyToCdn: true
46
973
  },
47
974
  validator() {
48
975
  }
@@ -293,10 +1220,6 @@ const ciMenuController = ({ strapi }) => ({
293
1220
  }
294
1221
  }
295
1222
  });
296
- function getSharp() {
297
- const req = typeof require !== "undefined" ? require : createRequire(path.join(process.cwd(), "package.json"));
298
- return req("sharp");
299
- }
300
1223
  function getCacheDir(strapi) {
301
1224
  const rootDir = strapi?.dirs?.app?.root || process.cwd();
302
1225
  const dir = path.join(rootDir, ".cache", "content-input-images");
@@ -305,47 +1228,12 @@ function getCacheDir(strapi) {
305
1228
  }
306
1229
  return dir;
307
1230
  }
308
- async function loadSourceBuffer(strapi, src) {
309
- const publicDir = strapi?.dirs?.static?.public || path.join(process.cwd(), "public");
310
- if (src.startsWith("/")) {
311
- const cleanRel = decodeURIComponent(src.split("?")[0]).replace(/^\/+/, "");
312
- const fullPath = path.resolve(publicDir, cleanRel);
313
- const resolvedPublic = path.resolve(publicDir);
314
- if (!fullPath.startsWith(resolvedPublic)) {
315
- throw new Error("Invalid local file path");
316
- }
317
- if (!fs.existsSync(fullPath)) {
318
- throw new Error(`File not found: ${src}`);
319
- }
320
- const buffer = await fs.promises.readFile(fullPath);
321
- const ext = path.extname(fullPath).toLowerCase();
322
- const mime = ext === ".png" ? "image/png" : ext === ".webp" ? "image/webp" : ext === ".avif" ? "image/avif" : ext === ".gif" ? "image/gif" : "image/jpeg";
323
- return { buffer, mime };
324
- }
325
- if (/^https?:\/\//i.test(src)) {
326
- const parsed = new URL(src);
327
- if ((parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1") && parsed.pathname.startsWith("/uploads/")) {
328
- const cleanRel = decodeURIComponent(parsed.pathname).replace(/^\/+/, "");
329
- const fullPath = path.resolve(publicDir, cleanRel);
330
- if (fs.existsSync(fullPath)) {
331
- const buffer = await fs.promises.readFile(fullPath);
332
- return { buffer, mime: "image/jpeg" };
333
- }
334
- }
335
- const res = await fetch(src);
336
- if (!res.ok) {
337
- throw new Error(`Failed to fetch remote image (${res.status})`);
338
- }
339
- const contentType = res.headers.get("content-type") || "image/jpeg";
340
- const arr = await res.arrayBuffer();
341
- return { buffer: Buffer.from(arr), mime: contentType };
342
- }
343
- throw new Error("Unsupported image source URL");
344
- }
345
1231
  const ciImageController = ({ strapi }) => ({
346
1232
  /**
347
1233
  * GET /api/content-input/image & GET /content-input/image
348
- * On-the-fly image scaling & cropping powered by sharp with disk + CDN HTTP caching.
1234
+ * Generates `ci-optimized` WebP variants via sharp, uploads to Strapi's Upload Provider (CDN),
1235
+ * persists in `plugin::upload.file.formats`, and issues a 302 redirect when a remote CDN URL is available
1236
+ * (with local byte-stream fallback in local-only environments).
349
1237
  */
350
1238
  async processImage(ctx) {
351
1239
  try {
@@ -354,16 +1242,96 @@ const ciImageController = ({ strapi }) => ({
354
1242
  if (!src) {
355
1243
  return ctx.badRequest("Missing src parameter");
356
1244
  }
357
- const processMode = String(query.process || "fit").toLowerCase();
358
- const w = Math.min(3840, Math.max(0, parseInt(String(query.w || query.cWidth || "0"), 10) || 0));
359
- const h = Math.min(3840, Math.max(0, parseInt(String(query.h || query.cHeight || "0"), 10) || 0));
1245
+ const rawProc = String(query.process || "auto").trim().toLowerCase();
1246
+ const processMode = rawProc === "fit" ? "fit" : rawProc === "widen" ? "widen" : "auto";
1247
+ const w = Math.min(
1248
+ 3840,
1249
+ Math.max(0, parseInt(String(query.w || query.cWidth || "0"), 10) || 0)
1250
+ );
1251
+ const h = Math.min(
1252
+ 3840,
1253
+ Math.max(0, parseInt(String(query.h || query.cHeight || "0"), 10) || 0)
1254
+ );
360
1255
  const q = Math.min(100, Math.max(20, parseInt(String(query.q || "85"), 10) || 85));
361
1256
  const rotate = parseInt(String(query.rotate || "0"), 10) || 0;
362
1257
  const cx = parseInt(String(query.x || "0"), 10) || 0;
363
1258
  const cy = parseInt(String(query.y || "0"), 10) || 0;
364
1259
  const cw = parseInt(String(query.cw || "0"), 10) || 0;
365
1260
  const ch = parseInt(String(query.ch || "0"), 10) || 0;
366
- const requestedFormat = String(query.format || "").toLowerCase();
1261
+ const requestedFormat = String(query.format || "").trim().toLowerCase();
1262
+ const acceptHeader = String(ctx.req?.headers?.accept || "");
1263
+ const wantsJson = query.json === "1" || query.json === "true" || acceptHeader.includes("application/json");
1264
+ const forceNoRedirect = query.redirect === "0" || query.redirect === "false" || query.proxy === "1" || query.proxy === "true";
1265
+ const forceRedirect = query.redirect === "1" || query.redirect === "true";
1266
+ const cfg = getVariantConfig(strapi);
1267
+ if (cw <= 0 && ch <= 0) {
1268
+ const existingFile = await findUploadFileForAsset(strapi, src);
1269
+ if (existingFile && existingFile.id) {
1270
+ if (!isOptimizableRasterImage(existingFile.mime, existingFile.ext || existingFile.url)) {
1271
+ const directUrl = existingFile.url;
1272
+ if (wantsJson) {
1273
+ ctx.body = { url: directUrl, formatKey: null };
1274
+ return;
1275
+ }
1276
+ if (!forceNoRedirect && directUrl && (cfg.redirectProxyToCdn && isAbsoluteHttpUrl(directUrl) || forceRedirect)) {
1277
+ ctx.set("Cache-Control", "public, max-age=86400");
1278
+ ctx.set("Access-Control-Allow-Origin", "*");
1279
+ ctx.status = 302;
1280
+ ctx.redirect(directUrl);
1281
+ return;
1282
+ }
1283
+ } else {
1284
+ const effW2 = w > 0 ? w : processMode === "auto" ? 1920 : 0;
1285
+ const effH2 = processMode === "fit" ? h : 0;
1286
+ if (effW2 > 0 || effH2 > 0) {
1287
+ const variantRes = await ensureMediaVariant(strapi, existingFile, {
1288
+ processMode,
1289
+ w: effW2,
1290
+ h: effH2,
1291
+ q,
1292
+ rotate,
1293
+ requestedFormat: requestedFormat || void 0
1294
+ });
1295
+ const providerUrl = variantRes.formatEntry?.url;
1296
+ if (providerUrl) {
1297
+ if (wantsJson) {
1298
+ ctx.body = {
1299
+ url: providerUrl,
1300
+ formatKey: variantRes.formatKey
1301
+ };
1302
+ return;
1303
+ }
1304
+ if (!forceNoRedirect && (cfg.redirectProxyToCdn && isAbsoluteHttpUrl(providerUrl) || forceRedirect)) {
1305
+ ctx.set("Cache-Control", "public, max-age=86400");
1306
+ ctx.set("Access-Control-Allow-Origin", "*");
1307
+ ctx.set("X-Content-Input-CDN-Url", providerUrl);
1308
+ ctx.status = 302;
1309
+ ctx.redirect(providerUrl);
1310
+ return;
1311
+ }
1312
+ try {
1313
+ const localVariant = await loadSourceBuffer(strapi, providerUrl);
1314
+ const etagLocal = `"ci-${variantRes.formatKey}-${existingFile.hash || existingFile.id}"`;
1315
+ if (ctx.req?.headers?.["if-none-match"] === etagLocal) {
1316
+ ctx.status = 304;
1317
+ return;
1318
+ }
1319
+ const resolvedMime = variantRes.formatEntry?.mime || localVariant.mime || "image/webp";
1320
+ ctx.body = localVariant.buffer;
1321
+ ctx.type = resolvedMime;
1322
+ ctx.set("Content-Type", resolvedMime);
1323
+ ctx.set("Cache-Control", "public, max-age=31536000, immutable");
1324
+ ctx.set("ETag", etagLocal);
1325
+ ctx.set("Access-Control-Allow-Origin", "*");
1326
+ ctx.set("X-Content-Input-CDN-Url", providerUrl);
1327
+ return;
1328
+ } catch {
1329
+ }
1330
+ }
1331
+ }
1332
+ }
1333
+ }
1334
+ }
367
1335
  const cacheKeyRaw = JSON.stringify({
368
1336
  src,
369
1337
  processMode,
@@ -375,11 +1343,11 @@ const ciImageController = ({ strapi }) => ({
375
1343
  cy,
376
1344
  cw,
377
1345
  ch,
378
- requestedFormat
1346
+ requestedFormat: requestedFormat || cfg.defaultFormat
379
1347
  });
380
1348
  const hash = crypto.createHash("sha1").update(cacheKeyRaw).digest("hex");
381
1349
  const etag = `"ci-${hash}"`;
382
- if (ctx.req.headers["if-none-match"] === etag) {
1350
+ if (!wantsJson && ctx.req?.headers?.["if-none-match"] === etag) {
383
1351
  ctx.status = 304;
384
1352
  return;
385
1353
  }
@@ -388,138 +1356,112 @@ const ciImageController = ({ strapi }) => ({
388
1356
  const binPath = path.join(cacheDir, `${hash}.bin`);
389
1357
  if (fs.existsSync(metaPath) && fs.existsSync(binPath)) {
390
1358
  const meta = JSON.parse(await fs.promises.readFile(metaPath, "utf8"));
1359
+ if (meta.providerUrl) {
1360
+ if (wantsJson) {
1361
+ ctx.body = { url: meta.providerUrl, formatKey: meta.formatKey || null };
1362
+ return;
1363
+ }
1364
+ if (!forceNoRedirect && (cfg.redirectProxyToCdn && isAbsoluteHttpUrl(meta.providerUrl) || forceRedirect)) {
1365
+ ctx.set("Cache-Control", "public, max-age=86400");
1366
+ ctx.set("Access-Control-Allow-Origin", "*");
1367
+ ctx.set("X-Content-Input-CDN-Url", meta.providerUrl);
1368
+ ctx.status = 302;
1369
+ ctx.redirect(meta.providerUrl);
1370
+ return;
1371
+ }
1372
+ }
391
1373
  const cachedBuffer = await fs.promises.readFile(binPath);
392
- ctx.set("Content-Type", meta.contentType || "image/jpeg");
1374
+ const cachedMime = meta.contentType || "image/webp";
1375
+ ctx.body = cachedBuffer;
1376
+ ctx.type = cachedMime;
1377
+ ctx.set("Content-Type", cachedMime);
393
1378
  ctx.set("Cache-Control", "public, max-age=31536000, immutable");
394
1379
  ctx.set("ETag", etag);
395
1380
  ctx.set("Access-Control-Allow-Origin", "*");
396
- ctx.body = cachedBuffer;
397
1381
  return;
398
1382
  }
399
1383
  const { buffer: sourceBuffer, mime: sourceMime } = await loadSourceBuffer(strapi, src);
400
- const sharp = getSharp();
401
- let pipeline = sharp(sourceBuffer, { failOn: "none" }).rotate();
402
- if (rotate && [90, 180, 270, -90].includes(rotate)) {
403
- pipeline = pipeline.rotate(rotate);
404
- }
405
- if (cw > 0 && ch > 0) {
406
- pipeline = pipeline.extract({
407
- left: Math.max(0, cx),
408
- top: Math.max(0, cy),
409
- width: cw,
410
- height: ch
411
- });
412
- }
413
- if (processMode === "fit" && w > 0 && h > 0) {
414
- pipeline = pipeline.resize(w, h, {
415
- fit: "cover",
416
- position: "centre",
417
- withoutEnlargement: false
418
- });
419
- } else if (processMode === "widen" && w > 0) {
420
- pipeline = pipeline.resize(w, null, {
421
- fit: "inside",
422
- withoutEnlargement: false
423
- });
424
- } else if (w > 0 || h > 0) {
425
- pipeline = pipeline.resize(w || null, h || null, {
426
- fit: "inside",
427
- withoutEnlargement: true
428
- });
429
- }
430
- let outContentType = sourceMime;
431
- if (requestedFormat === "webp" || sourceMime === "image/webp") {
432
- pipeline = pipeline.webp({ quality: q });
433
- outContentType = "image/webp";
434
- } else if (requestedFormat === "avif" || sourceMime === "image/avif") {
435
- pipeline = pipeline.avif({ quality: q });
436
- outContentType = "image/avif";
437
- } else if (requestedFormat === "png" || sourceMime === "image/png") {
438
- pipeline = pipeline.png({ quality: q });
439
- outContentType = "image/png";
440
- } else {
441
- pipeline = pipeline.jpeg({ quality: q, mozjpeg: true });
442
- outContentType = "image/jpeg";
443
- }
444
- const outputBuffer = await pipeline.toBuffer();
445
- let providerUrl;
446
- try {
447
- const cleanSrc = src.split("?")[0];
448
- const existingFile = await strapi.db.query("plugin::upload.file").findOne({
449
- where: { url: cleanSrc }
450
- });
451
- if (existingFile && existingFile.id) {
452
- const formatKey = `ci_${processMode}_${w}x${h}${rotate ? `_r${rotate}` : ""}`;
453
- const existingFormat = existingFile.formats?.[formatKey];
454
- if (existingFormat?.url) {
455
- providerUrl = existingFormat.url;
456
- } else {
457
- const outMeta = await sharp(outputBuffer).metadata();
458
- const ext = outContentType === "image/png" ? ".png" : outContentType === "image/webp" ? ".webp" : outContentType === "image/avif" ? ".avif" : ".jpg";
459
- const variantHash = `${formatKey}_${existingFile.hash || hash.slice(0, 10)}`;
460
- const variantName = `${formatKey}_${existingFile.name || "image"}`;
461
- const tmpVariantPath = path.join(os.tmpdir(), `${variantHash}${ext}`);
462
- await fs.promises.writeFile(tmpVariantPath, outputBuffer);
463
- try {
464
- const variantFile = {
465
- name: variantName,
466
- hash: variantHash,
467
- ext,
468
- mime: outContentType,
469
- filepath: tmpVariantPath,
470
- path: existingFile.path || null,
471
- getStream: () => fs.createReadStream(tmpVariantPath),
472
- width: outMeta.width || w || void 0,
473
- height: outMeta.height || h || void 0,
474
- size: Math.round(outputBuffer.length / 1e3 * 100) / 100,
475
- sizeInBytes: outputBuffer.length
476
- };
477
- const providerService = strapi.plugin("upload").service("provider");
478
- if (providerService && typeof providerService.upload === "function") {
479
- await providerService.upload(variantFile);
480
- providerUrl = variantFile.url;
481
- const { filepath: _fp, getStream: _gs, ...serializableFormat } = variantFile;
482
- const nextFormats = {
483
- ...existingFile.formats || {},
484
- [formatKey]: serializableFormat
485
- };
486
- await strapi.db.query("plugin::upload.file").update({
487
- where: { id: existingFile.id },
488
- data: { formats: nextFormats }
489
- });
490
- }
491
- } finally {
492
- await fs.promises.rm(tmpVariantPath, { force: true }).catch(() => void 0);
493
- }
494
- }
495
- }
496
- } catch {
497
- }
498
- await fs.promises.writeFile(binPath, outputBuffer);
1384
+ const effW = w > 0 ? w : processMode === "auto" ? 1920 : 0;
1385
+ const effH = processMode === "fit" ? h : 0;
1386
+ const rendered = await renderSharpVariantBuffer(sourceBuffer, sourceMime, {
1387
+ processMode,
1388
+ w: effW,
1389
+ h: effH,
1390
+ q,
1391
+ rotate,
1392
+ cx,
1393
+ cy,
1394
+ cw,
1395
+ ch,
1396
+ requestedFormat: requestedFormat || void 0,
1397
+ defaultFormat: cfg.defaultFormat
1398
+ });
1399
+ await fs.promises.writeFile(binPath, rendered.buffer);
499
1400
  await fs.promises.writeFile(
500
1401
  metaPath,
501
1402
  JSON.stringify({
502
- contentType: outContentType,
503
- size: outputBuffer.length,
504
- providerUrl
1403
+ contentType: rendered.contentType,
1404
+ size: rendered.buffer.length
505
1405
  })
506
1406
  );
507
- ctx.set("Content-Type", outContentType);
1407
+ if (wantsJson) {
1408
+ ctx.body = { url: src, formatKey: null };
1409
+ return;
1410
+ }
1411
+ ctx.body = rendered.buffer;
1412
+ ctx.type = rendered.contentType;
1413
+ ctx.set("Content-Type", rendered.contentType);
508
1414
  ctx.set("Cache-Control", "public, max-age=31536000, immutable");
509
1415
  ctx.set("ETag", etag);
510
1416
  ctx.set("Access-Control-Allow-Origin", "*");
511
- if (providerUrl) {
512
- ctx.set("X-Content-Input-CDN-Url", providerUrl);
513
- }
514
- ctx.body = outputBuffer;
515
1417
  } catch (err) {
516
1418
  ctx.throw(400, err?.message || "Image processing error");
517
1419
  }
518
1420
  },
1421
+ /**
1422
+ * POST /content-input/media/optimize
1423
+ * Eagerly optimizes one or multiple selected/uploaded Media Library assets into `ci-optimized/*.webp`
1424
+ * on the configured Upload Provider (CDN) and returns enriched CIMediaAsset object(s) with `formats` & `optimized_url`.
1425
+ */
1426
+ async optimizeMedia(ctx) {
1427
+ try {
1428
+ const body = ctx.request.body || {};
1429
+ const imageSettings = body.imageSettings || null;
1430
+ const defaultAutoMaxW = Number(body.defaultAutoMaxW) || 1920;
1431
+ const fileCache = /* @__PURE__ */ new Map();
1432
+ if (Array.isArray(body.assets)) {
1433
+ const enrichedList = [];
1434
+ for (const item of body.assets) {
1435
+ enrichedList.push(
1436
+ await enrichMediaAssetNode(strapi, item, {
1437
+ imageSettings,
1438
+ defaultAutoMaxW,
1439
+ fileCache
1440
+ })
1441
+ );
1442
+ }
1443
+ ctx.body = { data: enrichedList };
1444
+ return;
1445
+ }
1446
+ if (body.asset) {
1447
+ const enriched = await enrichMediaAssetNode(strapi, body.asset, {
1448
+ imageSettings,
1449
+ defaultAutoMaxW,
1450
+ fileCache
1451
+ });
1452
+ ctx.body = { data: enriched };
1453
+ return;
1454
+ }
1455
+ return ctx.badRequest("asset or assets is required");
1456
+ } catch (err) {
1457
+ ctx.throw(500, err?.message || "Failed to optimize media asset");
1458
+ }
1459
+ },
519
1460
  /**
520
1461
  * POST /content-input/media/crop
521
1462
  * Interactive crop & rotate using sharp on the backend (works seamlessly with local disk AND remote CDNs).
522
- * Supports mode: 'replace' (crops original asset in Media Library) or 'duplicate' (saves as new asset).
1463
+ * Supports mode: 'replace' (crops original asset in Media Library & refreshes ci-optimized variants)
1464
+ * or 'duplicate' (saves as new asset).
523
1465
  */
524
1466
  async cropMedia(ctx) {
525
1467
  const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "ci-crop-"));
@@ -575,7 +1517,7 @@ const ciImageController = ({ strapi }) => ({
575
1517
  if (ext === ".png" || mime === "image/png") {
576
1518
  pipeline = pipeline.png({ quality: 92 });
577
1519
  } else if (ext === ".webp" || mime === "image/webp") {
578
- pipeline = pipeline.webp({ quality: 90 });
1520
+ pipeline = pipeline.webp({ quality: 90, alphaQuality: 100 });
579
1521
  } else {
580
1522
  pipeline = pipeline.jpeg({ quality: 90, mozjpeg: true });
581
1523
  }
@@ -584,6 +1526,9 @@ const ciImageController = ({ strapi }) => ({
584
1526
  const targetFileName = mode === "duplicate" ? `${body.name || `${baseName}-cropped`}${ext.startsWith(".") ? ext : `.${ext}`}` : existingFile.name || `${baseName}${ext}`;
585
1527
  const tmpFilePath = path.join(tmpDir, targetFileName);
586
1528
  await fs.promises.writeFile(tmpFilePath, croppedBuffer);
1529
+ if (mode === "replace") {
1530
+ await clearGeneratedCiVariantsForFile(strapi, existingFile);
1531
+ }
587
1532
  const uploadService = strapi.plugin("upload").service("upload");
588
1533
  const fileInfo = {
589
1534
  name: targetFileName,
@@ -619,6 +1564,17 @@ const ciImageController = ({ strapi }) => ({
619
1564
  );
620
1565
  resultFile = Array.isArray(uploaded) ? uploaded[0] : uploaded;
621
1566
  }
1567
+ if (resultFile?.id) {
1568
+ try {
1569
+ const freshRes = await ensureMediaVariant(strapi, resultFile, {
1570
+ processMode: "auto",
1571
+ w: 1920,
1572
+ h: 0
1573
+ });
1574
+ resultFile = freshRes.updatedFile || resultFile;
1575
+ } catch {
1576
+ }
1577
+ }
622
1578
  ctx.body = { data: resultFile };
623
1579
  } catch (err) {
624
1580
  ctx.throw(500, err?.message || "Failed to crop media asset");
@@ -953,18 +1909,31 @@ const ciSurveyController = ({ strapi }) => ({
953
1909
  async exportResponses(ctx) {
954
1910
  try {
955
1911
  const { id } = ctx.params;
956
- const format = String(ctx.query?.format || "csv").toLowerCase() === "json" ? "json" : "csv";
1912
+ const rawFmt = String(ctx.query?.format || "xlsx").toLowerCase();
1913
+ const format = rawFmt === "json" ? "json" : rawFmt === "csv" ? "csv" : "xlsx";
957
1914
  const locale = String(ctx.query?.locale || "en").trim();
958
1915
  const from = ctx.query?.from ? String(ctx.query.from) : void 0;
959
1916
  const to = ctx.query?.to ? String(ctx.query.to) : void 0;
1917
+ const encoding = String(ctx.query?.encoding || "").toLowerCase();
960
1918
  const exported = await strapi.plugin("content-input").service("ci-survey").exportResponses(id, { format, locale, from, to });
961
1919
  if (!exported) {
962
1920
  return ctx.notFound("Survey not found");
963
1921
  }
1922
+ if (encoding === "base64") {
1923
+ const buf = Buffer.isBuffer(exported.body) ? exported.body : Buffer.from(String(exported.body), "utf8");
1924
+ ctx.status = 200;
1925
+ ctx.body = {
1926
+ filename: exported.filename,
1927
+ contentType: exported.contentType,
1928
+ base64: buf.toString("base64")
1929
+ };
1930
+ return;
1931
+ }
1932
+ ctx.body = exported.body;
1933
+ ctx.type = exported.contentType;
964
1934
  ctx.set("Content-Type", exported.contentType);
965
1935
  ctx.set("Content-Disposition", `attachment; filename="${exported.filename}"`);
966
1936
  ctx.status = 200;
967
- ctx.body = exported.body;
968
1937
  } catch (err) {
969
1938
  ctx.throw(500, err);
970
1939
  }
@@ -1345,6 +2314,14 @@ const routes = {
1345
2314
  policies: []
1346
2315
  }
1347
2316
  },
2317
+ {
2318
+ method: "POST",
2319
+ path: "/media/optimize",
2320
+ handler: "ci-image.optimizeMedia",
2321
+ config: {
2322
+ policies: []
2323
+ }
2324
+ },
1348
2325
  {
1349
2326
  method: "POST",
1350
2327
  path: "/media/crop",
@@ -4266,6 +5243,14 @@ const ciFormService = ({ strapi }) => ({
4266
5243
  }
4267
5244
  }
4268
5245
  }
5246
+ if (imageObj) {
5247
+ try {
5248
+ imageObj = await enrichMediaAssetNode(strapi, imageObj, {
5249
+ defaultAutoMaxW: 960
5250
+ });
5251
+ } catch {
5252
+ }
5253
+ }
4269
5254
  const pluralName = ct.info?.pluralName || "items";
4270
5255
  const slugField = ["slug", "path", "url", "permalink"].find(
4271
5256
  (k) => typeof entry[k] === "string" && entry[k].trim()
@@ -4296,6 +5281,7 @@ const ciFormService = ({ strapi }) => ({
4296
5281
  };
4297
5282
  }
4298
5283
  });
5284
+ const XLSX = XLSXNs?.utils ? XLSXNs : XLSXNs?.default || XLSXNs;
4299
5285
  function evalSingleRule(rule, answers) {
4300
5286
  const targetVal = answers ? answers[rule.questionKey] : void 0;
4301
5287
  const op = rule.operator;
@@ -4672,6 +5658,7 @@ function computeSurveyAnalytics(survey, rawResponses, filter = {}) {
4672
5658
  }
4673
5659
  const distribution = Object.keys(distMap).map(Number).sort((a, b) => a - b).map((value) => ({
4674
5660
  value,
5661
+ labels: q.scaleLabels ? q.scaleLabels[String(value)] : void 0,
4675
5662
  count: distMap[value] || 0,
4676
5663
  percentage: answeredCount > 0 ? Math.round((distMap[value] || 0) / answeredCount * 1e3) / 10 : 0
4677
5664
  }));
@@ -4682,6 +5669,7 @@ function computeSurveyAnalytics(survey, rawResponses, filter = {}) {
4682
5669
  max: maxVal,
4683
5670
  lowLabel: q.lowLabel,
4684
5671
  highLabel: q.highLabel,
5672
+ scaleLabels: q.scaleLabels,
4685
5673
  average: answeredCount > 0 ? Math.round(sum / answeredCount * 100) / 100 : 0,
4686
5674
  distribution,
4687
5675
  npsBreakdown: q.type === "nps" ? {
@@ -4870,6 +5858,7 @@ function computePublicSurveyResults(survey, rawResponses) {
4870
5858
  optionsBreakdown: qs.optionsBreakdown,
4871
5859
  average: qs.average,
4872
5860
  distribution: qs.distribution,
5861
+ scaleLabels: qs.scaleLabels,
4873
5862
  npsBreakdown: qs.npsBreakdown,
4874
5863
  rankingBreakdown: qs.rankingBreakdown
4875
5864
  }))
@@ -4882,9 +5871,17 @@ function escapeCsvCell(val) {
4882
5871
  }
4883
5872
  return str;
4884
5873
  }
4885
- function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
5874
+ function buildSurveyResponseExportAoA(survey, rawResponses, locale = "en") {
5875
+ const tr = String(locale || "").toLowerCase().startsWith("tr");
4886
5876
  const activeQuestions = (survey.questions || []).filter((q) => q && q.type !== "statement");
4887
- const headers = [
5877
+ const headers = tr ? [
5878
+ "Yanıt ID",
5879
+ "Gönderim Tarihi",
5880
+ "Dil",
5881
+ "Süre (sn)",
5882
+ "NPS Puanı",
5883
+ "NPS Kategorisi"
5884
+ ] : [
4888
5885
  "Response ID",
4889
5886
  "Submitted At",
4890
5887
  "Locale",
@@ -4902,18 +5899,18 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
4902
5899
  } else {
4903
5900
  headers.push(`${qTitle} (${q.key})`);
4904
5901
  if (q.allowOther) {
4905
- headers.push(`${qTitle} [Other Text]`);
5902
+ headers.push(`${qTitle} [${tr ? "Diğer Açıklama" : "Other Text"}]`);
4906
5903
  }
4907
5904
  }
4908
5905
  }
4909
- const lines = [headers.map(escapeCsvCell).join(",")];
5906
+ const rows = [];
4910
5907
  for (const r of rawResponses || []) {
4911
5908
  const rowCells = [
4912
5909
  String(r.id || r.documentId || ""),
4913
5910
  String(r.submittedAt || r.createdAt || ""),
4914
5911
  String(r.locale || ""),
4915
- String(r.durationSeconds ?? ""),
4916
- r.npsValue !== null && r.npsValue !== void 0 ? String(r.npsValue) : "",
5912
+ typeof r.durationSeconds === "number" ? r.durationSeconds : String(r.durationSeconds ?? ""),
5913
+ typeof r.npsValue === "number" ? r.npsValue : r.npsValue !== null && r.npsValue !== void 0 && r.npsValue !== "" ? Number(r.npsValue) : "",
4917
5914
  String(r.npsCategory || "")
4918
5915
  ];
4919
5916
  for (const q of activeQuestions) {
@@ -4930,7 +5927,7 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
4930
5927
  } else if (Array.isArray(q.options) && q.options.length > 0) {
4931
5928
  if (Array.isArray(ans)) {
4932
5929
  const mapped = ans.map((optId) => {
4933
- if (optId === "__other__") return locale === "tr" ? "Diğer" : "Other";
5930
+ if (optId === "__other__") return tr ? "Diğer" : "Other";
4934
5931
  const found = q.options.find((o) => o.id === optId);
4935
5932
  return found ? resolveLocalizedText(found.labels, locale, optId) : optId;
4936
5933
  });
@@ -4938,7 +5935,7 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
4938
5935
  } else if (ans !== void 0 && ans !== null && ans !== "") {
4939
5936
  const strAns = String(ans);
4940
5937
  if (strAns === "__other__") {
4941
- rowCells.push(locale === "tr" ? "Diğer" : "Other");
5938
+ rowCells.push(tr ? "Diğer" : "Other");
4942
5939
  } else {
4943
5940
  const found = q.options.find((o) => o.id === strAns);
4944
5941
  rowCells.push(found ? resolveLocalizedText(found.labels, locale, strAns) : strAns);
@@ -4950,16 +5947,131 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
4950
5947
  rowCells.push(String(r.otherTexts?.[q.key] || ""));
4951
5948
  }
4952
5949
  } else {
4953
- rowCells.push(ans === void 0 || ans === null ? "" : String(ans));
5950
+ if (q.type === "likert_scale" && q.scaleLabels && ans !== void 0 && ans !== null && ans !== "") {
5951
+ const ptLbl = resolveLocalizedText(q.scaleLabels[String(ans)], locale, "");
5952
+ rowCells.push(ptLbl ? `${ans} - ${ptLbl}` : Number.isNaN(Number(ans)) ? String(ans) : Number(ans));
5953
+ } else if ((q.type === "nps" || q.type === "star_rating" || q.type === "likert_scale") && ans !== void 0 && ans !== null && ans !== "" && !Number.isNaN(Number(ans))) {
5954
+ rowCells.push(Number(ans));
5955
+ } else {
5956
+ rowCells.push(ans === void 0 || ans === null ? "" : String(ans));
5957
+ }
4954
5958
  if (q.allowOther) {
4955
5959
  rowCells.push(String(r.otherTexts?.[q.key] || ""));
4956
5960
  }
4957
5961
  }
4958
5962
  }
4959
- lines.push(rowCells.map(escapeCsvCell).join(","));
5963
+ rows.push(rowCells);
5964
+ }
5965
+ return { headers, rows };
5966
+ }
5967
+ function computeAutoColWidths(aoa) {
5968
+ const colCount = aoa.reduce((m, r) => Math.max(m, r.length), 0);
5969
+ const widths = [];
5970
+ for (let c = 0; c < colCount; c++) {
5971
+ let maxLen = 12;
5972
+ for (let r = 0; r < Math.min(aoa.length, 300); r++) {
5973
+ const cell = aoa[r]?.[c];
5974
+ const str = cell === null || cell === void 0 ? "" : String(cell);
5975
+ if (str.length > maxLen) maxLen = str.length;
5976
+ }
5977
+ widths.push({ wch: Math.min(54, maxLen + 3) });
5978
+ }
5979
+ return widths;
5980
+ }
5981
+ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
5982
+ const { headers, rows } = buildSurveyResponseExportAoA(survey, rawResponses, locale);
5983
+ const lines = [headers.map(escapeCsvCell).join(",")];
5984
+ for (const r of rows) {
5985
+ lines.push(r.map(escapeCsvCell).join(","));
4960
5986
  }
4961
5987
  return `\uFEFF${lines.join("\r\n")}`;
4962
5988
  }
5989
+ function exportSurveyResponsesToXlsxBuffer(survey, rawResponses, locale = "en") {
5990
+ const tr = String(locale || "").toLowerCase().startsWith("tr");
5991
+ const { headers, rows } = buildSurveyResponseExportAoA(survey, rawResponses, locale);
5992
+ const responsesAoA = [headers, ...rows];
5993
+ const wb = XLSX.utils.book_new();
5994
+ const wsResponses = XLSX.utils.aoa_to_sheet(responsesAoA);
5995
+ wsResponses["!cols"] = computeAutoColWidths(responsesAoA);
5996
+ XLSX.utils.book_append_sheet(wb, wsResponses, tr ? "Yanitlar" : "Responses");
5997
+ const analytics = computeSurveyAnalytics(survey, rawResponses);
5998
+ const s = analytics.summary;
5999
+ const summaryAoA = [
6000
+ [tr ? "Anket Başlığı" : "Survey Title", resolveLocalizedText(survey.titleI18n, locale, survey.title)],
6001
+ ["Survey Slug", survey.slug],
6002
+ [tr ? "Dışa Aktarım Tarihi" : "Exported At", (/* @__PURE__ */ new Date()).toISOString()],
6003
+ [tr ? "Toplam Yanıt" : "Total Responses", s.totalResponses],
6004
+ [tr ? "Ortalama Süre (sn)" : "Average Duration (s)", s.avgDurationSeconds],
6005
+ [tr ? "Medyan Süre (sn)" : "Median Duration (s)", s.medianDurationSeconds]
6006
+ ];
6007
+ if (s.nps?.hasNps) {
6008
+ summaryAoA.push(
6009
+ ["Net Promoter Score (NPS)", s.nps.score ?? 0],
6010
+ [
6011
+ tr ? "NPS Dağılımı" : "NPS Breakdown",
6012
+ `Promoters: ${s.nps.promoters} (${s.nps.promotersPct}%) | Passives: ${s.nps.passives} (${s.nps.passivesPct}%) | Detractors: ${s.nps.detractors} (${s.nps.detractorsPct}%)`
6013
+ ]
6014
+ );
6015
+ }
6016
+ summaryAoA.push(
6017
+ [],
6018
+ tr ? ["Soru Anahtarı", "Soru Başlığı", "Tip", "Seçenek / Kriter", "Adet / Ort.", "Yüzde (%)"] : ["Question Key", "Question Title", "Type", "Option / Metric", "Count / Avg", "Share (%)"]
6019
+ );
6020
+ for (const qs of analytics.questionStats) {
6021
+ const qTitle = resolveLocalizedText(qs.title, locale, qs.key);
6022
+ if (Array.isArray(qs.optionsBreakdown)) {
6023
+ for (const opt of qs.optionsBreakdown) {
6024
+ const optLbl = opt.id === "__other__" ? tr ? "Diğer" : "Other" : resolveLocalizedText(opt.labels, locale, opt.id);
6025
+ summaryAoA.push([qs.key, qTitle, qs.type, optLbl, opt.count, opt.percentage]);
6026
+ }
6027
+ } else if (Array.isArray(qs.distribution)) {
6028
+ summaryAoA.push([
6029
+ qs.key,
6030
+ qTitle,
6031
+ qs.type,
6032
+ tr ? "Ortalama Puan" : "Average Score",
6033
+ qs.average,
6034
+ ""
6035
+ ]);
6036
+ for (const d of qs.distribution) {
6037
+ const ptLbl = d.labels ? resolveLocalizedText(d.labels, locale, "") : "";
6038
+ summaryAoA.push([
6039
+ qs.key,
6040
+ qTitle,
6041
+ qs.type,
6042
+ ptLbl ? `${d.value} - ${ptLbl}` : String(d.value),
6043
+ d.count,
6044
+ d.percentage
6045
+ ]);
6046
+ }
6047
+ } else if (Array.isArray(qs.rankingBreakdown)) {
6048
+ for (const rk of qs.rankingBreakdown) {
6049
+ summaryAoA.push([
6050
+ qs.key,
6051
+ qTitle,
6052
+ qs.type,
6053
+ resolveLocalizedText(rk.labels, locale, rk.id),
6054
+ rk.averageRank,
6055
+ rk.scorePercentage
6056
+ ]);
6057
+ }
6058
+ } else {
6059
+ summaryAoA.push([
6060
+ qs.key,
6061
+ qTitle,
6062
+ qs.type,
6063
+ tr ? "Toplam Yanıt" : "Answered Count",
6064
+ qs.answeredCount || 0,
6065
+ ""
6066
+ ]);
6067
+ }
6068
+ }
6069
+ const wsSummary = XLSX.utils.aoa_to_sheet(summaryAoA);
6070
+ wsSummary["!cols"] = computeAutoColWidths(summaryAoA);
6071
+ XLSX.utils.book_append_sheet(wb, wsSummary, tr ? "Ozet_Istatistik" : "Summary");
6072
+ const out = XLSX.write(wb, { type: "buffer", bookType: "xlsx" });
6073
+ return Buffer.isBuffer(out) ? out : Buffer.from(out);
6074
+ }
4963
6075
  const SURVEY_UID = "plugin::content-input.ci-survey";
4964
6076
  const SURVEY_RESPONSE_UID = "plugin::content-input.ci-survey-response";
4965
6077
  let activeSeedPromise = null;
@@ -5265,6 +6377,12 @@ const ciSurveyService = ({ strapi }) => ({
5265
6377
  settings: payload.settings ?? existing?.settings ?? {},
5266
6378
  version: existing ? Number(existing.version || 1) + 1 : 1
5267
6379
  };
6380
+ if (Array.isArray(recordData.questions) && recordData.questions.length > 0) {
6381
+ try {
6382
+ recordData.questions = await syncSurveyQuestionsMedia(strapi, recordData.questions);
6383
+ } catch {
6384
+ }
6385
+ }
5268
6386
  if (existing) {
5269
6387
  const updated = await strapi.db.query(SURVEY_UID).update({
5270
6388
  where: { id: existing.id },
@@ -5525,6 +6643,18 @@ const ciSurveyService = ({ strapi }) => ({
5525
6643
  return true;
5526
6644
  });
5527
6645
  }
6646
+ if (options2.format === "xlsx") {
6647
+ const xlsxBuf = exportSurveyResponsesToXlsxBuffer(
6648
+ survey,
6649
+ responses,
6650
+ options2.locale || "en"
6651
+ );
6652
+ return {
6653
+ filename: `${survey.slug}-responses.xlsx`,
6654
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
6655
+ body: xlsxBuf
6656
+ };
6657
+ }
5528
6658
  if (options2.format === "json") {
5529
6659
  return {
5530
6660
  filename: `${survey.slug}-responses.json`,
@@ -6068,33 +7198,48 @@ const ciColorService = ({ strapi }) => ({
6068
7198
  entries = [];
6069
7199
  }
6070
7200
  const collectionLabelText = ct.info?.displayName || uid;
6071
- const sanitizedRows = (entries || []).map((entry) => {
6072
- const row = {};
6073
- for (const f of allowedFields) {
6074
- if (f.key === "collectionLabel" && entry.collectionLabel === void 0) {
6075
- row.collectionLabel = collectionLabelText;
6076
- continue;
6077
- }
6078
- if (f.key === "url" && entry.url === void 0) {
6079
- const slugStr = entry.slug ? String(entry.slug).trim() : "";
6080
- row.url = slugStr ? slugStr === "home" ? "/" : `/${slugStr.replace(/^\/+/, "")}` : "";
6081
- continue;
6082
- }
6083
- const val = entry[f.key];
6084
- if (val !== null && val !== void 0 && typeof val === "object") {
6085
- if (Array.isArray(val)) {
6086
- row[f.key] = val[0]?.url || `${val.length} item`;
6087
- } else if (val.url) {
6088
- row[f.key] = val.url;
7201
+ const fileCache = /* @__PURE__ */ new Map();
7202
+ const sanitizedRows = await Promise.all(
7203
+ (entries || []).map(async (entry) => {
7204
+ const row = {};
7205
+ for (const f of allowedFields) {
7206
+ if (f.key === "collectionLabel" && entry.collectionLabel === void 0) {
7207
+ row.collectionLabel = collectionLabelText;
7208
+ continue;
7209
+ }
7210
+ if (f.key === "url" && entry.url === void 0) {
7211
+ const slugStr = entry.slug ? String(entry.slug).trim() : "";
7212
+ row.url = slugStr ? slugStr === "home" ? "/" : `/${slugStr.replace(/^\/+/, "")}` : "";
7213
+ continue;
7214
+ }
7215
+ const val = entry[f.key];
7216
+ if (val !== null && val !== void 0 && typeof val === "object") {
7217
+ if (Array.isArray(val)) {
7218
+ if (val[0]?.url) {
7219
+ const enriched = await enrichMediaAssetNode(strapi, val[0], {
7220
+ defaultAutoMaxW: 800,
7221
+ fileCache
7222
+ });
7223
+ row[f.key] = enriched?.optimized_url || enriched?.url || val[0].url;
7224
+ } else {
7225
+ row[f.key] = `${val.length} item`;
7226
+ }
7227
+ } else if (val.url) {
7228
+ const enriched = await enrichMediaAssetNode(strapi, val, {
7229
+ defaultAutoMaxW: 800,
7230
+ fileCache
7231
+ });
7232
+ row[f.key] = enriched?.optimized_url || enriched?.url || val.url;
7233
+ } else {
7234
+ row[f.key] = "";
7235
+ }
6089
7236
  } else {
6090
- row[f.key] = "";
7237
+ row[f.key] = val ?? "";
6091
7238
  }
6092
- } else {
6093
- row[f.key] = val ?? "";
6094
7239
  }
6095
- }
6096
- return row;
6097
- });
7240
+ return row;
7241
+ })
7242
+ );
6098
7243
  return {
6099
7244
  uid,
6100
7245
  displayName: ct.info?.displayName || uid,