@datawheel/bespoke 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/dist/index.css +0 -5
  2. package/dist/index.js +11486 -3731
  3. package/dist/server.js +1300 -411
  4. package/package.json +15 -5
package/dist/server.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { initAuth0 } from '@auth0/nextjs-auth0';
2
2
  import auth0 from 'auth0';
3
3
  import * as pg from 'pg';
4
- import { Sequelize, Error as Error$1, fn, col, Op, DataTypes, QueryTypes, Model } from 'sequelize';
4
+ import { Sequelize, Error as Error$1, Op, fn, col, DataTypes, QueryTypes, Model } from 'sequelize';
5
5
  import yn2 from 'yn';
6
6
  import * as d3Array from 'd3-array';
7
7
  import * as d3Collection from 'd3-collection';
@@ -28,6 +28,7 @@ import imageType from 'image-type';
28
28
  import formidable from 'formidable';
29
29
  import puppeteer from 'puppeteer';
30
30
  import DomParser from 'dom-parser';
31
+ import path from 'path';
31
32
  import axiosRetry from 'axios-retry';
32
33
  import toposort from 'toposort';
33
34
  import { csvParse } from 'd3-dsv';
@@ -97,6 +98,10 @@ function resultWrapper(method) {
97
98
  return (param) => method(param).then(successResult, failureResult);
98
99
  }
99
100
  function pickMethod(api, operation, entity) {
101
+ if (operation === "createBulk" || operation === "updateBulk") {
102
+ const name2 = `${operation}${capitalize(entity)}`;
103
+ return api[name2];
104
+ }
100
105
  const name = `${operation}${capitalize(entity)}`;
101
106
  return api[name];
102
107
  }
@@ -116,10 +121,10 @@ var CMS_ROLES_TYPES = {
116
121
  };
117
122
  var addRoleTypes = (roles) => {
118
123
  const systemRoles = Object.values(CMS_ROLES);
119
- return roles ? roles.map((r) => {
124
+ return roles ? roles.map((r2) => {
120
125
  return {
121
- ...r,
122
- type: systemRoles.includes(r.name) ? CMS_ROLES_TYPES.APP : CMS_ROLES_TYPES.USER
126
+ ...r2,
127
+ type: systemRoles.includes(r2.name) ? CMS_ROLES_TYPES.APP : CMS_ROLES_TYPES.USER
123
128
  };
124
129
  }) : [];
125
130
  };
@@ -204,12 +209,15 @@ function dbUpdateUser() {
204
209
  try {
205
210
  if (user.user_id) {
206
211
  if (user.app_metadata) {
207
- await updateUserMetadata(user.user_id, user.app_metadata);
212
+ await updateAppMetadata(user.user_id, user.app_metadata);
213
+ }
214
+ if (user.user_metadata) {
215
+ await updateUserMetadata(user.user_id, user.user_metadata);
208
216
  }
209
217
  if (user.roles) {
210
218
  const currentRoles = await managementClient.users.getRoles({ id: user.user_id });
211
- const oldRoles = currentRoles.map((r) => r.id);
212
- const newRoles = user.roles.map((r) => r.id);
219
+ const oldRoles = currentRoles.map((r2) => r2.id);
220
+ const newRoles = user.roles.map((r2) => r2.id);
213
221
  const rolesToAssign = newRoles.filter((role) => !oldRoles.includes(role));
214
222
  const rolesToDelete = oldRoles.filter((role) => !newRoles.includes(role));
215
223
  if (rolesToAssign.length > 0) {
@@ -219,7 +227,10 @@ function dbUpdateUser() {
219
227
  await managementClient.users.removeRoles({ id: user.user_id }, { roles: rolesToDelete });
220
228
  }
221
229
  }
222
- return "User updated!";
230
+ return {
231
+ status: "success",
232
+ message: "User updated!"
233
+ };
223
234
  } else {
224
235
  throw new BackendError(404, "user_id is required");
225
236
  }
@@ -229,7 +240,7 @@ function dbUpdateUser() {
229
240
  }
230
241
  };
231
242
  }
232
- function dbAddNewReportToCurrentUser() {
243
+ function dbUpdateMyData() {
233
244
  return async (params) => {
234
245
  try {
235
246
  return "NOT USED SERVICE";
@@ -239,20 +250,23 @@ function dbAddNewReportToCurrentUser() {
239
250
  }
240
251
  };
241
252
  }
242
- async function updateUserMetadata(userId, newMetadata) {
253
+ async function updateAppMetadata(userId, newMetadata) {
243
254
  return await managementClient.users.updateAppMetadata({ id: userId }, newMetadata);
244
255
  }
256
+ async function updateUserMetadata(userId, newMetadata) {
257
+ return await managementClient.users.updateUserMetadata({ id: userId }, newMetadata);
258
+ }
245
259
  async function searchUsersByMetadata(key, value) {
246
260
  try {
247
261
  const users = await managementClient.getUsers({
248
262
  search_engine: "v3",
249
- q: `app_metadata.${key}:"${value}"`
263
+ q: `user_metadata.${key}:"${value}"`
250
264
  });
251
265
  for (let index = 0; index < users.length; index++) {
252
- const u = users[index];
253
- u.bespoke_app_metadata = u.app_metadata || {};
254
- delete u.app_metadata;
255
- u.bespoke_roles = (await managementClient.users.getRoles({ id: u.user_id })).map((r) => r.name);
266
+ const u2 = users[index];
267
+ u2.bespoke_user_metadata = u2.user_metadata || {};
268
+ delete u2.user_metadata;
269
+ u2.bespoke_roles = (await managementClient.users.getRoles({ id: u2.user_id })).map((r2) => r2.name);
256
270
  }
257
271
  return users;
258
272
  } catch (error) {
@@ -260,8 +274,8 @@ async function searchUsersByMetadata(key, value) {
260
274
  }
261
275
  }
262
276
 
263
- // api/auth/updateCurrentUserMetadata.tsx
264
- var updateCurrentUserMetadata = (req, res, newMetadata) => {
277
+ // api/auth/updateCurrentUserAppMetadata.tsx
278
+ var updateCurrentUserAppMetadata = (req, res, newMetadata) => {
265
279
  return new Promise((resolve, reject) => {
266
280
  const updateMetadata = async () => {
267
281
  try {
@@ -275,7 +289,7 @@ var updateCurrentUserMetadata = (req, res, newMetadata) => {
275
289
  ...oldMetadata,
276
290
  ...newMetadata
277
291
  };
278
- await updateUserMetadata(session.user.sub, latestMetadata);
292
+ await updateAppMetadata(session.user.sub, latestMetadata);
279
293
  await getAuth_default.updateSession(req, res, {
280
294
  ...session,
281
295
  user: {
@@ -285,7 +299,47 @@ var updateCurrentUserMetadata = (req, res, newMetadata) => {
285
299
  });
286
300
  resolve({
287
301
  error: "",
288
- description: `Settings updated for user ${session.user.email}`
302
+ description: `App metadata updated for user ${session.user.email}`
303
+ });
304
+ }
305
+ } catch (error) {
306
+ reject({
307
+ error: error.message,
308
+ description: "The user does not have an active session or is not authenticated"
309
+ });
310
+ }
311
+ };
312
+ updateMetadata();
313
+ });
314
+ };
315
+ var updateCurrentUserAppMetadata_default = updateCurrentUserAppMetadata;
316
+
317
+ // api/auth/updateCurrentUserMetadata.ts
318
+ var updateCurrentUserMetadata = (req, res, newMetadata) => {
319
+ return new Promise((resolve, reject) => {
320
+ const updateMetadata = async () => {
321
+ try {
322
+ const session = await getAuth_default.getSession(req, res);
323
+ if (!session || !session.user) {
324
+ throw new Error("not_authenticated");
325
+ } else {
326
+ const { user } = session;
327
+ const oldMetadata = session.user.bespoke_user_metadata || {};
328
+ const latestMetadata = {
329
+ ...oldMetadata,
330
+ ...newMetadata
331
+ };
332
+ await updateUserMetadata(session.user.sub, latestMetadata);
333
+ await getAuth_default.updateSession(req, res, {
334
+ ...session,
335
+ user: {
336
+ ...user,
337
+ bespoke_user_metadata: latestMetadata
338
+ }
339
+ });
340
+ resolve({
341
+ error: "",
342
+ description: `App metadata updated for user ${session.user.email}`
289
343
  });
290
344
  }
291
345
  } catch (error) {
@@ -301,12 +355,12 @@ var updateCurrentUserMetadata = (req, res, newMetadata) => {
301
355
  var updateCurrentUserMetadata_default = updateCurrentUserMetadata;
302
356
 
303
357
  // libs/js/arrayUtils.ts
304
- var keyDiver = (obj, str) => !str ? obj : typeof str === "string" ? str.split(".").reduce((o, i) => o[i], obj) : obj;
358
+ var keyDiver = (obj, str) => !str ? obj : typeof str === "string" ? str.split(".").reduce((o2, i2) => o2[i2], obj) : obj;
305
359
  function arrContainsAnyItem(arr1, arr2) {
306
360
  return arr1.some((item) => arr2.includes(item));
307
361
  }
308
362
 
309
- // api/auth/withApiRoleAuthRequired.tsx
363
+ // api/auth/withApiRoleAuthRequired.ts
310
364
  var withApiRoleAuthRequired = (apiRoute, allowedRoles) => {
311
365
  return async function(req, res) {
312
366
  const session = await getAuth_default.getSession(req, res);
@@ -330,7 +384,7 @@ var withApiRoleAuthRequired = (apiRoute, allowedRoles) => {
330
384
  };
331
385
  var withApiRoleAuthRequired_default = withApiRoleAuthRequired;
332
386
 
333
- // api/auth/searchUsersByMetadata.tsx
387
+ // api/auth/searchUsersByMetadata.ts
334
388
  var searchUsersByMetadata2 = (key, value) => {
335
389
  return new Promise((resolve, reject) => {
336
390
  const searchUsers = async () => {
@@ -502,25 +556,25 @@ function initModel3(sequelize) {
502
556
  var block_input_default = initModel3;
503
557
 
504
558
  // libs/stats.js
505
- function logGamma(Z) {
506
- const S = 1 + 76.18009173 / Z - 86.50532033 / (Z + 1) + 24.01409822 / (Z + 2) - 1.231739516 / (Z + 3) + 0.00120858003 / (Z + 4) - 536382e-11 / (Z + 5);
507
- return (Z - 0.5) * Math.log(Z + 4.5) - (Z + 4.5) + Math.log(S * 2.50662827465);
559
+ function logGamma(Z2) {
560
+ const S2 = 1 + 76.18009173 / Z2 - 86.50532033 / (Z2 + 1) + 24.01409822 / (Z2 + 2) - 1.231739516 / (Z2 + 3) + 0.00120858003 / (Z2 + 4) - 536382e-11 / (Z2 + 5);
561
+ return (Z2 - 0.5) * Math.log(Z2 + 4.5) - (Z2 + 4.5) + Math.log(S2 * 2.50662827465);
508
562
  }
509
- function betinc(X, A, B) {
563
+ function betinc(X2, A2, B2) {
510
564
  let A0 = 0;
511
565
  let B0 = 1;
512
566
  let A1 = 1;
513
567
  let B1 = 1;
514
568
  let M9 = 0;
515
- let A2 = 0;
569
+ let A22 = 0;
516
570
  let C9;
517
- while (Math.abs((A1 - A2) / A1) > 1e-5) {
518
- A2 = A1;
519
- C9 = -(A + M9) * (A + B + M9) * X / (A + 2 * M9) / (A + 2 * M9 + 1);
571
+ while (Math.abs((A1 - A22) / A1) > 1e-5) {
572
+ A22 = A1;
573
+ C9 = -(A2 + M9) * (A2 + B2 + M9) * X2 / (A2 + 2 * M9) / (A2 + 2 * M9 + 1);
520
574
  A0 = A1 + C9 * A0;
521
575
  B0 = B1 + C9 * B0;
522
576
  M9 += 1;
523
- C9 = M9 * (B - M9) * X / (A + 2 * M9 - 1) / (A + 2 * M9);
577
+ C9 = M9 * (B2 - M9) * X2 / (A2 + 2 * M9 - 1) / (A2 + 2 * M9);
524
578
  A1 = A0 + C9 * A1;
525
579
  B1 = B0 + C9 * B1;
526
580
  A0 /= B1;
@@ -528,26 +582,26 @@ function betinc(X, A, B) {
528
582
  A1 /= B1;
529
583
  B1 = 1;
530
584
  }
531
- return A1 / A;
585
+ return A1 / A2;
532
586
  }
533
- function binomialCdf(X, N, P) {
587
+ function binomialCdf(X2, N2, P2) {
534
588
  let betacdf;
535
589
  let bincdf;
536
- if (X < 0)
590
+ if (X2 < 0)
537
591
  bincdf = 0;
538
- else if (X >= N)
592
+ else if (X2 >= N2)
539
593
  bincdf = 1;
540
594
  else {
541
- X = Math.floor(X);
542
- const Z = P;
543
- const A = X + 1;
544
- const B = N - X;
545
- const S = A + B;
546
- const BT = Math.exp(logGamma(S) - logGamma(B) - logGamma(A) + A * Math.log(Z) + B * Math.log(1 - Z));
547
- if (Z < (A + 1) / (S + 2)) {
548
- betacdf = BT * betinc(Z, A, B);
595
+ X2 = Math.floor(X2);
596
+ const Z2 = P2;
597
+ const A2 = X2 + 1;
598
+ const B2 = N2 - X2;
599
+ const S2 = A2 + B2;
600
+ const BT = Math.exp(logGamma(S2) - logGamma(B2) - logGamma(A2) + A2 * Math.log(Z2) + B2 * Math.log(1 - Z2));
601
+ if (Z2 < (A2 + 1) / (S2 + 2)) {
602
+ betacdf = BT * betinc(Z2, A2, B2);
549
603
  } else {
550
- betacdf = 1 - BT * betinc(1 - Z, B, A);
604
+ betacdf = 1 - BT * betinc(1 - Z2, B2, A2);
551
605
  }
552
606
  bincdf = 1 - betacdf;
553
607
  }
@@ -562,26 +616,26 @@ function criticalValue(confLevel) {
562
616
  };
563
617
  return critMap[confLevel];
564
618
  }
565
- function binP(N, p, x1, x2) {
566
- const q = p / (1 - p);
567
- let k = 0;
568
- let v = 1;
569
- let s = 0;
619
+ function binP(N2, p2, x1, x2) {
620
+ const q2 = p2 / (1 - p2);
621
+ let k2 = 0;
622
+ let v2 = 1;
623
+ let s2 = 0;
570
624
  let tot = 0;
571
- while (k <= N) {
572
- tot += v;
573
- if (k >= x1 & k <= x2) {
574
- s += v;
625
+ while (k2 <= N2) {
626
+ tot += v2;
627
+ if (k2 >= x1 & k2 <= x2) {
628
+ s2 += v2;
575
629
  }
576
630
  if (tot > 1e30) {
577
- s /= 1e30;
631
+ s2 /= 1e30;
578
632
  tot /= 1e30;
579
- v /= 1e30;
633
+ v2 /= 1e30;
580
634
  }
581
- k += 1;
582
- v = v * q * (N + 1 - k) / k;
635
+ k2 += 1;
636
+ v2 = v2 * q2 * (N2 + 1 - k2) / k2;
583
637
  }
584
- return s / tot;
638
+ return s2 / tot;
585
639
  }
586
640
  function computeMidP(vx, vN, confLevel) {
587
641
  const vP = vx / vN;
@@ -592,38 +646,38 @@ function computeMidP(vx, vN, confLevel) {
592
646
  if (vx === 0) {
593
647
  T1 = 0;
594
648
  } else {
595
- let v = vP / 2;
649
+ let v2 = vP / 2;
596
650
  let vsL = 0;
597
651
  let vsH = vP;
598
- const p = vTL / 100;
652
+ const p2 = vTL / 100;
599
653
  while (vsH - vsL > 1e-5) {
600
- if (binP(vN, v, vx, vx) * 0.5 + binP(vN, v, vx + 1, vN) > p) {
601
- vsH = v;
602
- v = (vsL + v) / 2;
654
+ if (binP(vN, v2, vx, vx) * 0.5 + binP(vN, v2, vx + 1, vN) > p2) {
655
+ vsH = v2;
656
+ v2 = (vsL + v2) / 2;
603
657
  } else {
604
- vsL = v;
605
- v = (vsH + v) / 2;
658
+ vsL = v2;
659
+ v2 = (vsH + v2) / 2;
606
660
  }
607
661
  }
608
- T1 = v;
662
+ T1 = v2;
609
663
  }
610
664
  if (vx === vN) {
611
665
  T2 = 0;
612
666
  } else {
613
- let v = (1 + vP) / 2;
667
+ let v2 = (1 + vP) / 2;
614
668
  let vsL = vP;
615
669
  let vsH = 1;
616
- const p = vTL / 100;
670
+ const p2 = vTL / 100;
617
671
  while (vsH - vsL > 1e-5) {
618
- if (binP(vN, v, vx, vx) * 0.5 + binP(vN, v, 0, vx - 1) < p) {
619
- vsH = v;
620
- v = (vsL + v) / 2;
672
+ if (binP(vN, v2, vx, vx) * 0.5 + binP(vN, v2, 0, vx - 1) < p2) {
673
+ vsH = v2;
674
+ v2 = (vsL + v2) / 2;
621
675
  } else {
622
- vsL = v;
623
- v = (vsH + v) / 2;
676
+ vsL = v2;
677
+ v2 = (vsH + v2) / 2;
624
678
  }
625
679
  }
626
- T2 = v;
680
+ T2 = v2;
627
681
  }
628
682
  return { lci: T1, uci: T2 };
629
683
  }
@@ -633,54 +687,54 @@ function smr(observedVal, expectedVal) {
633
687
  const Obs = vx;
634
688
  const Exp = vN;
635
689
  const ci = 95;
636
- let v = 0.5;
690
+ let v2 = 0.5;
637
691
  let dv = 0.5;
638
692
  const vTL = (100 - ci) / 2;
639
- let p = vTL / 100;
693
+ let p2 = vTL / 100;
640
694
  const vZ = Obs;
641
695
  while (dv > 1e-5) {
642
696
  dv /= 2;
643
- if (poisP((1 + vZ) * v / (1 - v), vZ + 1, 1e10) + 0.5 * poisP((1 + vZ) * v / (1 - v), vZ, vZ) > p) {
644
- v -= dv;
697
+ if (poisP((1 + vZ) * v2 / (1 - v2), vZ + 1, 1e10) + 0.5 * poisP((1 + vZ) * v2 / (1 - v2), vZ, vZ) > p2) {
698
+ v2 -= dv;
645
699
  } else {
646
- v += dv;
700
+ v2 += dv;
647
701
  }
648
702
  }
649
- const QL = (1 + vZ) * v / (1 - v) / Exp;
650
- v = 0.5;
703
+ const QL = (1 + vZ) * v2 / (1 - v2) / Exp;
704
+ v2 = 0.5;
651
705
  dv = 0.5;
652
706
  const vTU = (100 - ci) / 2;
653
- p = vTU / 100;
707
+ p2 = vTU / 100;
654
708
  while (dv > 1e-5) {
655
709
  dv /= 2;
656
- if (poisP((1 + vZ) * v / (1 - v), 0, vZ - 1) + 0.5 * poisP((1 + vZ) * v / (1 - v), vZ, vZ) < p) {
657
- v -= dv;
710
+ if (poisP((1 + vZ) * v2 / (1 - v2), 0, vZ - 1) + 0.5 * poisP((1 + vZ) * v2 / (1 - v2), vZ, vZ) < p2) {
711
+ v2 -= dv;
658
712
  } else {
659
- v += dv;
713
+ v2 += dv;
660
714
  }
661
715
  }
662
- const QU = (1 + vZ) * v / (1 - v) / Exp;
716
+ const QU = (1 + vZ) * v2 / (1 - v2) / Exp;
663
717
  return { lci: QL, uci: QU };
664
718
  }
665
- function poisP(Z, x1, x2) {
666
- let q = 1;
719
+ function poisP(Z2, x1, x2) {
720
+ let q2 = 1;
667
721
  let tot = 0;
668
- let s = 0;
669
- let k = 0;
670
- while (k < Z || q > tot * 1e-10) {
671
- tot += q;
672
- if (k >= x1 & k <= x2) {
673
- s += q;
722
+ let s2 = 0;
723
+ let k2 = 0;
724
+ while (k2 < Z2 || q2 > tot * 1e-10) {
725
+ tot += q2;
726
+ if (k2 >= x1 & k2 <= x2) {
727
+ s2 += q2;
674
728
  }
675
729
  if (tot > 1e30) {
676
- s /= 1e30;
730
+ s2 /= 1e30;
677
731
  tot /= 1e30;
678
- q /= 1e30;
732
+ q2 /= 1e30;
679
733
  }
680
- k += 1;
681
- q = q * Z / k;
734
+ k2 += 1;
735
+ q2 = q2 * Z2 / k2;
682
736
  }
683
- return s / tot;
737
+ return s2 / tot;
684
738
  }
685
739
  var stats_default = {
686
740
  binomialCdf,
@@ -1346,7 +1400,7 @@ var getLocales_default = () => {
1346
1400
  };
1347
1401
 
1348
1402
  // libs/js/stripHTML.ts
1349
- function stripHTML(n) {
1403
+ function stripHTML(n2) {
1350
1404
  const entities = {
1351
1405
  "&amp;": "&",
1352
1406
  "&lt;": "<",
@@ -1359,13 +1413,13 @@ function stripHTML(n) {
1359
1413
  const source = `(?:${Object.keys(entities).join("|")})`;
1360
1414
  const testRegexp = RegExp(source);
1361
1415
  const replaceRegexp = RegExp(source, "g");
1362
- const s = String(n).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
1363
- return testRegexp.test(s) ? s.replace(replaceRegexp, (match) => entities[match]) : s;
1416
+ const s2 = String(n2).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
1417
+ return testRegexp.test(s2) ? s2.replace(replaceRegexp, (match) => entities[match]) : s2;
1364
1418
  }
1365
1419
 
1366
1420
  // libs/js/stripEntities.ts
1367
- function stripEntities(n) {
1368
- return typeof n === "string" ? String(n).replace(/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});/ig, " ") : n;
1421
+ function stripEntities(n2) {
1422
+ return typeof n2 === "string" ? String(n2).replace(/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});/ig, " ") : n2;
1369
1423
  }
1370
1424
 
1371
1425
  // libs/js/slugify.ts
@@ -1412,13 +1466,13 @@ function ingestMembersFactory(db) {
1412
1466
  const { overrideNames, overrideAttributes } = getVariantSettingsDefaults(settings);
1413
1467
  const {
1414
1468
  accessor,
1415
- path,
1469
+ path: path2,
1416
1470
  idKey,
1417
1471
  labelKey
1418
1472
  } = config[localeDefault];
1419
- if (!path || !idKey || !labelKey)
1473
+ if (!path2 || !idKey || !labelKey)
1420
1474
  return;
1421
- const memberFetch = await axios6.get(path).catch((e) => ({ data: [], error: e }));
1475
+ const memberFetch = await axios6.get(path2).catch((e) => ({ data: [], error: e }));
1422
1476
  const members = keyDiver(memberFetch.data, accessor);
1423
1477
  let toUpdateContent = [];
1424
1478
  try {
@@ -1438,15 +1492,15 @@ function ingestMembersFactory(db) {
1438
1492
  ));
1439
1493
  const ingestions = Object.entries(config).map(async ([locale, config2]) => {
1440
1494
  const {
1441
- path: path2,
1495
+ path: path3,
1442
1496
  accessor: accessor2,
1443
1497
  idKey: idKey2,
1444
1498
  labelKey: labelKey2,
1445
1499
  attributes = []
1446
1500
  } = config2;
1447
- if (!path2 || !idKey2 || !labelKey2)
1501
+ if (!path3 || !idKey2 || !labelKey2)
1448
1502
  return;
1449
- const memberFetch2 = await axios6.get(path2).catch((e) => ({ data: [], error: e }));
1503
+ const memberFetch2 = await axios6.get(path3).catch((e) => ({ data: [], error: e }));
1450
1504
  const members2 = keyDiver(memberFetch2.data, accessor2);
1451
1505
  const oldIngestedContents = await SearchContent.findAll({
1452
1506
  // attributes: ["id", "zvalue", "slug"],
@@ -1454,13 +1508,13 @@ function ingestMembersFactory(db) {
1454
1508
  }).then((arr) => Object.fromEntries(arr.map((item) => {
1455
1509
  return [item.id, item.toJSON()];
1456
1510
  })));
1457
- const contentMembers = members2.filter((member) => member[idKey2] && member[idKey2] !== "" && member[labelKey2] && member[labelKey2] !== "").map((d) => {
1458
- const searchElement = contentHash[d[idKey2]];
1511
+ const contentMembers = members2.filter((member) => member[idKey2] && member[idKey2] !== "" && member[labelKey2] && member[labelKey2] !== "").map((d2) => {
1512
+ const searchElement = contentHash[d2[idKey2]];
1459
1513
  let contentMember;
1460
1514
  const calculatedAttributes = Object.fromEntries(
1461
1515
  attributes.map((attr) => [
1462
1516
  attr.name,
1463
- attr.type === "constant" ? attr.value : d[attr.value] || ""
1517
+ attr.type === "constant" ? attr.value : d2[attr.value] || ""
1464
1518
  ])
1465
1519
  );
1466
1520
  if (searchElement.needsUpdate && oldIngestedContents[searchElement.content_id]) {
@@ -1468,7 +1522,7 @@ function ingestMembersFactory(db) {
1468
1522
  ...oldIngestedContents[searchElement.content_id]
1469
1523
  };
1470
1524
  if (overrideNames) {
1471
- contentMember.name = d[labelKey2];
1525
+ contentMember.name = d2[labelKey2];
1472
1526
  }
1473
1527
  if (overrideAttributes) {
1474
1528
  contentMember.attributes = calculatedAttributes;
@@ -1477,7 +1531,7 @@ function ingestMembersFactory(db) {
1477
1531
  contentMember = {
1478
1532
  id: searchElement.content_id,
1479
1533
  locale,
1480
- name: d[labelKey2],
1534
+ name: d2[labelKey2],
1481
1535
  attributes: calculatedAttributes
1482
1536
  };
1483
1537
  }
@@ -1743,7 +1797,7 @@ function readMemberFactory(db) {
1743
1797
  throw new BackendError(404, "One or more members were not found.");
1744
1798
  }
1745
1799
  memberSearchResults.sort(
1746
- (a, b) => whereClause.content_id.indexOf(a.content_id) - whereClause.content_id.indexOf(b.content_id)
1800
+ (a2, b2) => whereClause.content_id.indexOf(a2.content_id) - whereClause.content_id.indexOf(b2.content_id)
1747
1801
  );
1748
1802
  const normalizedResults = memberSearchResults.map((item) => {
1749
1803
  let finalResult;
@@ -1862,7 +1916,7 @@ var whitelist = [
1862
1916
  ];
1863
1917
  var verbose2 = getLogging_default();
1864
1918
  var { locales } = getLocales_default();
1865
- var enabledLocales = locales.filter((d) => whitelist.includes(d));
1919
+ var enabledLocales = locales.filter((d2) => whitelist.includes(d2));
1866
1920
  var initializing = false;
1867
1921
  var getSearchIndexByLocale = async (db, forceRegenerate = false) => {
1868
1922
  if (forceRegenerate) {
@@ -1921,7 +1975,7 @@ async function newSearchIndex(db) {
1921
1975
  this.pipeline.reset();
1922
1976
  this.searchPipeline.reset();
1923
1977
  results.forEach((result) => {
1924
- const content = result.contentByLocale.find((d) => d.locale === locale);
1978
+ const content = result.contentByLocale.find((d2) => d2.locale === locale);
1925
1979
  if (content) {
1926
1980
  const searchTerms = sanitizeQuery_default(content.name);
1927
1981
  const payload = {
@@ -1954,10 +2008,11 @@ function dbSearchMemberFactory(db) {
1954
2008
  async function searchMember2(params) {
1955
2009
  const searchIndexByLocale = await search_default2(db);
1956
2010
  let resultsIds = [];
1957
- let resultsScores = [];
2011
+ const resultsScores = {};
1958
2012
  const {
1959
2013
  query,
1960
2014
  locale,
2015
+ preferredLocale,
1961
2016
  limit,
1962
2017
  format,
1963
2018
  visible,
@@ -1973,8 +2028,26 @@ function dbSearchMemberFactory(db) {
1973
2028
  if (query && query !== "" && searchIndexByLocale[locale]) {
1974
2029
  const terms = sanitizeQuery_default(query).replace(/([A-z]{2,})/g, (txt) => `+${txt}`).replace(/(.)$/g, (txt) => `${txt}*`);
1975
2030
  const lunrResults = searchIndexByLocale[locale].index.search(terms);
1976
- resultsIds = lunrResults.map((d) => parseInt(d.ref, 10));
1977
- resultsScores = lunrResults.reduce((obj, d) => (obj[d.ref] = d.score, obj), {});
2031
+ resultsIds = lunrResults.map((d2) => parseInt(d2.ref, 10));
2032
+ lunrResults.forEach((d2) => {
2033
+ resultsScores[d2.ref] = d2.score;
2034
+ });
2035
+ if (preferredLocale && searchIndexByLocale[preferredLocale]) {
2036
+ const lunrResults2 = searchIndexByLocale[preferredLocale].index.search(terms);
2037
+ resultsIds = Array.from(/* @__PURE__ */ new Set(
2038
+ [
2039
+ ...resultsIds,
2040
+ ...lunrResults2.map((d2) => parseInt(d2.ref, 10))
2041
+ ]
2042
+ ));
2043
+ lunrResults2.forEach((d2) => {
2044
+ if (resultsScores[d2.ref]) {
2045
+ resultsScores[d2.ref] = Math.max(resultsScores[d2.ref], d2.score);
2046
+ } else {
2047
+ resultsScores[d2.ref] = d2.score;
2048
+ }
2049
+ });
2050
+ }
1978
2051
  }
1979
2052
  const whereClause = {
1980
2053
  ...visible ? { visible } : {},
@@ -1998,7 +2071,7 @@ function dbSearchMemberFactory(db) {
1998
2071
  WHERE t.rank <= ${calculatedLimit}
1999
2072
  ORDER BY t.variant_id, t.zvalue DESC;
2000
2073
  `, { type: QueryTypes.SELECT });
2001
- resultsIds = rank.map((d) => d.content_id);
2074
+ resultsIds = rank.map((d2) => d2.content_id);
2002
2075
  }
2003
2076
  whereClause.content_id = resultsIds;
2004
2077
  const includeClause = [{
@@ -2029,9 +2102,9 @@ function dbSearchMemberFactory(db) {
2029
2102
  });
2030
2103
  if (sort === "name") {
2031
2104
  const sortDirection = direction.toUpperCase() === "ASC" ? 1 : -1;
2032
- results.sort((a, b) => {
2033
- const aValue = a.getContent(localeDefault2);
2034
- const bValue = b.getContent(localeDefault2);
2105
+ results.sort((a2, b2) => {
2106
+ const aValue = a2.getContent(localeDefault2);
2107
+ const bValue = b2.getContent(localeDefault2);
2035
2108
  if (aValue && bValue) {
2036
2109
  return aValue.name > bValue.name ? 1 * sortDirection : -1 * sortDirection;
2037
2110
  }
@@ -2041,15 +2114,15 @@ function dbSearchMemberFactory(db) {
2041
2114
  const resultFormatter = format === "nested" ? nestedFormatter : plainFormatter;
2042
2115
  const formattedResults = results.map(resultFormatter);
2043
2116
  if (format !== "nested") {
2044
- formattedResults.forEach((d) => {
2045
- const { name, keywords, score = 0, zvalue } = d;
2117
+ formattedResults.forEach((d2) => {
2118
+ const { name, keywords, score = 0, zvalue } = d2;
2046
2119
  if (name) {
2047
2120
  const cleanName = sanitizeQuery_default(name);
2048
2121
  let scoreMod = score;
2049
2122
  const diffMod = query.length / cleanName.length;
2050
- const matchingStartChars = cleanName.split("").reduce((str, c, i) => {
2051
- if (str === query.slice(0, i), query.charAt(i) === c)
2052
- str += c;
2123
+ const matchingStartChars = cleanName.split("").reduce((str, c2, i2) => {
2124
+ if (str === query.slice(0, i2), query.charAt(i2) === c2)
2125
+ str += c2;
2053
2126
  return str;
2054
2127
  }, "").length;
2055
2128
  if (cleanName === query || keywords && keywords.includes(query))
@@ -2058,7 +2131,7 @@ function dbSearchMemberFactory(db) {
2058
2131
  scoreMod *= 20 * diffMod;
2059
2132
  else if (matchingStartChars)
2060
2133
  scoreMod *= matchingStartChars * diffMod;
2061
- d.zvalue = scoreMod * 2 + zvalue;
2134
+ d2.zvalue = scoreMod * 2 + zvalue;
2062
2135
  }
2063
2136
  });
2064
2137
  }
@@ -2165,24 +2238,19 @@ function dbMemberFactory(db) {
2165
2238
  var blockQuery = {
2166
2239
  include: [
2167
2240
  { association: "contentByLocale", separate: true },
2168
- { association: "inputs", include: [
2169
- { association: "contentByLocale", separate: true }
2170
- ] },
2171
- { association: "consumers", include: [
2172
- { association: "contentByLocale", separate: true }
2173
- ] }
2241
+ { association: "inputs", include: [{ association: "contentByLocale", separate: true }] },
2242
+ {
2243
+ association: "consumers",
2244
+ include: [{ association: "contentByLocale", separate: true }]
2245
+ }
2174
2246
  ]
2175
2247
  };
2176
2248
  var dimensionQuery = {
2177
- include: [
2178
- { association: "variants", separate: true }
2179
- ],
2249
+ include: [{ association: "variants", separate: true }],
2180
2250
  order: [["ordering", "ASC"]]
2181
2251
  };
2182
2252
  var sectionQuery = {
2183
- include: [
2184
- { association: "blocks", separate: true, ...blockQuery }
2185
- ]
2253
+ include: [{ association: "blocks", separate: true, ...blockQuery }]
2186
2254
  };
2187
2255
  var reportQuery = {
2188
2256
  include: [
@@ -2196,9 +2264,7 @@ var imageQueryThumbOnly = [
2196
2264
  attributes: {
2197
2265
  exclude: ["splash"]
2198
2266
  },
2199
- include: [
2200
- { association: "contentByLocale" }
2201
- ]
2267
+ include: [{ association: "contentByLocale" }]
2202
2268
  },
2203
2269
  { association: "contentByLocale" }
2204
2270
  ];
@@ -2210,19 +2276,40 @@ function dbBlockFactory(db) {
2210
2276
  createBlock,
2211
2277
  readBlock,
2212
2278
  updateBlock,
2213
- deleteBlock
2279
+ deleteBlock,
2280
+ createBulkBlock,
2281
+ updateBulkBlock
2214
2282
  };
2215
2283
  async function createBlock(data) {
2216
2284
  const { locales: locales10, ...blockData } = data;
2217
- const entity = await Block.create({
2218
- ...blockData,
2219
- consumers: [],
2220
- inputs: [],
2221
- contentByLocale: locales10.map((locale) => ({ locale }))
2222
- }, {
2285
+ const entity = await Block.create(
2286
+ {
2287
+ ...blockData,
2288
+ consumers: [],
2289
+ inputs: [],
2290
+ contentByLocale: locales10.map((locale) => ({ locale }))
2291
+ },
2292
+ {
2293
+ include: blockQuery.include
2294
+ }
2295
+ );
2296
+ return entity.toJSON();
2297
+ }
2298
+ async function createBulkBlock(data) {
2299
+ const blocks = data.map((data2) => {
2300
+ const { locales: locales10, ...blockData } = data2;
2301
+ const block = {
2302
+ ...blockData,
2303
+ consumers: [],
2304
+ inputs: [],
2305
+ contentByLocale: locales10.map((locale) => ({ locale }))
2306
+ };
2307
+ return block;
2308
+ });
2309
+ const entities = await Block.bulkCreate(blocks, {
2223
2310
  include: blockQuery.include
2224
2311
  });
2225
- return entity.toJSON();
2312
+ return entities.map((b2) => b2.toJSON());
2226
2313
  }
2227
2314
  async function readBlock({ id, include } = {}) {
2228
2315
  const idList = id == null ? [] : [].concat(id);
@@ -2239,7 +2326,7 @@ function dbBlockFactory(db) {
2239
2326
  }
2240
2327
  async function updateBlock(data) {
2241
2328
  const {
2242
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
2329
+ //eslint-disable-next-line @typescript-eslint/no-unused-vars
2243
2330
  id,
2244
2331
  contentByLocale,
2245
2332
  consumers,
@@ -2269,6 +2356,54 @@ function dbBlockFactory(db) {
2269
2356
  await entity.reload();
2270
2357
  return entity.toJSON();
2271
2358
  }
2359
+ async function updateBulkBlock(data) {
2360
+ const blocks = data.map((data2) => {
2361
+ const {
2362
+ //eslint-disable-next-line @typescript-eslint/no-unused-vars
2363
+ id,
2364
+ contentByLocale,
2365
+ consumers,
2366
+ inputs,
2367
+ inputAction,
2368
+ ...blockData
2369
+ } = data2;
2370
+ return { id, contentByLocale, inputAction, ...blockData };
2371
+ });
2372
+ const entities = await Block.findAll({
2373
+ where: {
2374
+ id: {
2375
+ [Op.or]: blocks.map((b2) => b2.id)
2376
+ }
2377
+ },
2378
+ include: blockQuery.include
2379
+ });
2380
+ const result = [];
2381
+ for (const e of entities) {
2382
+ const updates = blocks.filter((b2) => b2.id === e.id);
2383
+ for (let i2 = 0; i2 < updates.length; i2++) {
2384
+ const update = updates[i2];
2385
+ const { id, contentByLocale, inputAction, ...blockData } = update;
2386
+ if (inputAction) {
2387
+ if (inputAction.operation === "create") {
2388
+ await BlockInput.create(inputAction.input);
2389
+ } else {
2390
+ await BlockInput.destroy({ where: inputAction.input });
2391
+ }
2392
+ }
2393
+ if (contentByLocale) {
2394
+ const contentList = Object.values(contentByLocale);
2395
+ await BlockContent.bulkCreate(contentList, {
2396
+ updateOnDuplicate: ["content"]
2397
+ });
2398
+ }
2399
+ e.set(blockData);
2400
+ await e.save();
2401
+ await e.reload();
2402
+ result.push(e.toJSON());
2403
+ }
2404
+ }
2405
+ return result;
2406
+ }
2272
2407
  async function deleteBlock(id) {
2273
2408
  const entity = await Block.findByPk(id, { rejectOnEmpty: true });
2274
2409
  await entity.destroy();
@@ -2374,13 +2509,16 @@ function dbReportFactory(db) {
2374
2509
  deleteReport
2375
2510
  };
2376
2511
  async function createReport(data) {
2377
- const entity = await Report.create({
2378
- name: data.name,
2379
- sections: [],
2380
- dimensions: []
2381
- }, {
2382
- include: reportQuery.include
2383
- });
2512
+ const entity = await Report.create(
2513
+ {
2514
+ name: data.name,
2515
+ sections: [],
2516
+ dimensions: []
2517
+ },
2518
+ {
2519
+ include: reportQuery.include
2520
+ }
2521
+ );
2384
2522
  return entity.toJSON();
2385
2523
  }
2386
2524
  async function readReport({
@@ -2389,12 +2527,15 @@ function dbReportFactory(db) {
2389
2527
  locales: locales10 = reportLocales
2390
2528
  } = {}) {
2391
2529
  const allIdsList = id == null ? [] : [].concat(id);
2392
- const idList = allIdsList.reduce((uniques, currentValue) => {
2393
- if (!uniques.includes(currentValue)) {
2394
- uniques.push(currentValue);
2395
- }
2396
- return uniques;
2397
- }, []);
2530
+ const idList = allIdsList.reduce(
2531
+ (uniques, currentValue) => {
2532
+ if (!uniques.includes(currentValue)) {
2533
+ uniques.push(currentValue);
2534
+ }
2535
+ return uniques;
2536
+ },
2537
+ []
2538
+ );
2398
2539
  const entities = await Report.findAll({
2399
2540
  where: idList.length > 0 ? { id: idList } : void 0,
2400
2541
  include: include ? reportQuery.include : void 0
@@ -2408,10 +2549,13 @@ function dbReportFactory(db) {
2408
2549
  ...section,
2409
2550
  blocks: section.blocks.map((block) => ({
2410
2551
  ...block,
2411
- contentByLocale: Object.keys(block.contentByLocale).reduce((filteredContent, locale) => ({
2412
- ...filteredContent,
2413
- ...[...locales10, "logic"].includes(locale) ? { [locale]: block.contentByLocale[locale] } : {}
2414
- }), {})
2552
+ contentByLocale: Object.keys(block.contentByLocale).reduce(
2553
+ (filteredContent, locale) => ({
2554
+ ...filteredContent,
2555
+ ...[...locales10, "logic"].includes(locale) ? { [locale]: block.contentByLocale[locale] } : {}
2556
+ }),
2557
+ {}
2558
+ )
2415
2559
  }))
2416
2560
  }))
2417
2561
  };
@@ -2422,12 +2566,8 @@ function dbReportFactory(db) {
2422
2566
  throw new BackendError(404, `Report(id=${missing}) does not exist.`);
2423
2567
  }
2424
2568
  async function updateReport(data) {
2425
- const {
2426
- id,
2427
- dimensions,
2428
- sections,
2429
- ...reportData
2430
- } = data;
2569
+ const { id, dimensions, sections, ...reportData } = data;
2570
+ console.log(data, "CON DATA");
2431
2571
  const entity = await Report.findByPk(id, {
2432
2572
  include: reportQuery.include,
2433
2573
  rejectOnEmpty: true
@@ -2615,6 +2755,8 @@ function dbEntityFactory(dbModels) {
2615
2755
  deleteBlock: resultWrapper(crud.deleteBlock),
2616
2756
  readBlock: resultWrapper(crud.readBlock),
2617
2757
  updateBlock: resultWrapper(crud.updateBlock),
2758
+ createBulkBlock: resultWrapper(crud.createBulkBlock),
2759
+ updateBulkBlock: resultWrapper(crud.updateBulkBlock),
2618
2760
  readMember: resultWrapper(crud.readMember),
2619
2761
  searchMember: resultWrapper(crud.searchMember),
2620
2762
  updateMember: resultWrapper(crud.updateMember),
@@ -2666,9 +2808,9 @@ async function searchFlickrProvider(_db, params) {
2666
2808
  console.log("Flickr is not initialized. Check the credentials");
2667
2809
  throw new Error("Flickr is not initialized. Check the credentials");
2668
2810
  }
2669
- const q = searchParams.prompt;
2811
+ const q2 = searchParams.prompt;
2670
2812
  const result = await flickr.photos.search({
2671
- text: q,
2813
+ text: q2,
2672
2814
  license: validLicensesString,
2673
2815
  sort: "relevance",
2674
2816
  per_page: imagesPageSize,
@@ -2678,15 +2820,15 @@ async function searchFlickrProvider(_db, params) {
2678
2820
  }).then((resp) => resp.body);
2679
2821
  const photos = result.photos.photo;
2680
2822
  const fetches = photos.reduce(
2681
- (acc, d) => acc.concat(flickr.photos.getSizes({ photo_id: d.id })),
2823
+ (acc, d2) => acc.concat(flickr.photos.getSizes({ photo_id: d2.id })),
2682
2824
  []
2683
2825
  );
2684
2826
  const results = await Promise.all(fetches).then((results2) => results2);
2685
- const imagesResults = results.reduce((acc, d, i) => {
2686
- const small = d.body.sizes.size.find((s) => s.label === "Small 320");
2827
+ const imagesResults = results.reduce((acc, d2, i2) => {
2828
+ const small = d2.body.sizes.size.find((s2) => s2.label === "Small 320");
2687
2829
  if (small) {
2688
2830
  acc.push({
2689
- id: photos[i].id,
2831
+ id: photos[i2].id,
2690
2832
  source: small.source
2691
2833
  });
2692
2834
  }
@@ -2728,24 +2870,24 @@ async function saveFlickrProvider(db, params) {
2728
2870
  } else {
2729
2871
  const sizeObj = await flickr.photos.getSizes({ photo_id: image_id }).then((resp) => resp.body);
2730
2872
  let image = sizeObj.sizes.size.find(
2731
- (d) => parseInt(d.width, 10) >= 1600
2873
+ (d2) => parseInt(d2.width, 10) >= 1600
2732
2874
  );
2733
2875
  if (!image) {
2734
2876
  image = sizeObj.sizes.size.find(
2735
- (d) => parseInt(d.width, 10) >= 1e3
2877
+ (d2) => parseInt(d2.width, 10) >= 1e3
2736
2878
  );
2737
2879
  }
2738
2880
  if (!image) {
2739
2881
  image = sizeObj.sizes.size.find(
2740
- (d) => parseInt(d.width, 10) >= 500
2882
+ (d2) => parseInt(d2.width, 10) >= 500
2741
2883
  );
2742
2884
  }
2743
2885
  if (!image || !image.source) {
2744
2886
  throw new Error("Flickr Source Error, try another image.");
2745
2887
  }
2746
- const imageData = await axios6.get(image.source, { responseType: "arraybuffer" }).then((d) => d.data);
2888
+ const imageData = await axios6.get(image.source, { responseType: "arraybuffer" }).then((d2) => d2.data);
2747
2889
  const allLicenses = await flickr.photos.licenses.getInfo().then((resp) => resp.body.licenses.license);
2748
- const currentPhotoLicense = allLicenses.find((l) => l.id === parseInt(info.photo.license, 10));
2890
+ const currentPhotoLicense = allLicenses.find((l2) => l2.id === parseInt(info.photo.license, 10));
2749
2891
  const payload = {
2750
2892
  url,
2751
2893
  author: info.photo.owner.realname || info.photo.owner.username,
@@ -2792,8 +2934,8 @@ async function saveFlickrProvider(db, params) {
2792
2934
  }
2793
2935
 
2794
2936
  // api/endpoints/lib.ts
2795
- function endpoint(method, path, handler, roleRequired) {
2796
- return { method, path, handler, roleRequired };
2937
+ function endpoint(method, path2, handler, roleRequired) {
2938
+ return { method, path: path2, handler, roleRequired };
2797
2939
  }
2798
2940
  function parseFiniteNumber(value) {
2799
2941
  const num = Number.parseInt(`${value || ""}`, 10);
@@ -2957,6 +3099,7 @@ function parseSearchMemberParams(query) {
2957
3099
  return {
2958
3100
  query: normalizeList(query.query || query.q)[0] || "",
2959
3101
  locale: localeIsAll ? localeDefault3 : locale,
3102
+ preferredLocale: normalizeList(query.preferredLocale)[0],
2960
3103
  limit: normalizeList(query.limit).map(parseFiniteNumber)[0] ?? 5,
2961
3104
  format: formatIsNested ? "nested" : "plain",
2962
3105
  includes: yn2(query.includes, { default: true }),
@@ -3039,9 +3182,9 @@ async function searchUnsplashProvider(_db, params) {
3039
3182
  if (!unsplash) {
3040
3183
  throw new Error("Unsplash API Key not configured");
3041
3184
  }
3042
- const q = searchParams.prompt;
3185
+ const q2 = searchParams.prompt;
3043
3186
  const result = await unsplash.search.getPhotos({
3044
- query: q,
3187
+ query: q2,
3045
3188
  perPage: imagesPageSize,
3046
3189
  page: searchParams.page,
3047
3190
  orientation: "landscape"
@@ -3084,7 +3227,7 @@ async function saveUnsplashProvider(db, params) {
3084
3227
  if (imageRow) {
3085
3228
  await db.search.update({ image_id: imageRow.id }, { where: { content_id } });
3086
3229
  } else {
3087
- const imageData = await axios6.get(info.urls.full, { responseType: "arraybuffer" }).then((d) => d.data);
3230
+ const imageData = await axios6.get(info.urls.full, { responseType: "arraybuffer" }).then((d2) => d2.data);
3088
3231
  const payload = {
3089
3232
  url,
3090
3233
  author: info.user.name || info.user.username,
@@ -3269,7 +3412,7 @@ async function saveAdobeProvider(db, params) {
3269
3412
  if (imageRow) {
3270
3413
  await db.search.update({ image_id: imageRow.id }, { where: { content_id } });
3271
3414
  } else {
3272
- const imageData = await axios6.get(info.thumbnail_1000_url, { responseType: "arraybuffer" }).then((d) => d.data);
3415
+ const imageData = await axios6.get(info.thumbnail_1000_url, { responseType: "arraybuffer" }).then((d2) => d2.data);
3273
3416
  const payload = {
3274
3417
  url,
3275
3418
  author: info.creator_name,
@@ -3415,7 +3558,7 @@ var addProfilesData = (items, metadata) => {
3415
3558
  } else if (report.mode === REPORT_MODES.MULTILATERAL) ;
3416
3559
  }
3417
3560
  });
3418
- return profileResults.sort((a, b) => a.confidence < b.confidence ? 1 : -1);
3561
+ return profileResults.sort((a2, b2) => a2.confidence < b2.confidence ? 1 : -1);
3419
3562
  };
3420
3563
  var formatNested = (items, metadata) => {
3421
3564
  if (!items)
@@ -3424,9 +3567,9 @@ var formatNested = (items, metadata) => {
3424
3567
  let dimension;
3425
3568
  let variant;
3426
3569
  return items.map((item) => {
3427
- report = { ...metadata.find((r) => r.id === item.report_id) };
3428
- dimension = { ...report.dimensions.find((d) => d.id === item.dimension_id) };
3429
- variant = { ...dimension.variants.find((v) => v.id === item.variant_id) };
3570
+ report = { ...metadata.find((r2) => r2.id === item.report_id) };
3571
+ dimension = { ...report.dimensions.find((d2) => d2.id === item.dimension_id) };
3572
+ variant = { ...dimension.variants.find((v2) => v2.id === item.variant_id) };
3430
3573
  delete report.dimensions;
3431
3574
  delete dimension.variants;
3432
3575
  return {
@@ -3601,8 +3744,8 @@ function dbReadPrivateBlocksFactory(db) {
3601
3744
  return report.sections.reduce((acc, section) => {
3602
3745
  const nestedBlocks = section.blocks.map((entity) => {
3603
3746
  const normalized = entity.toJSON();
3604
- normalized.inputs = normalized.inputs.map((b) => b.id);
3605
- normalized.consumers = normalized.consumers.map((b) => b.id);
3747
+ normalized.inputs = normalized.inputs.map((b2) => b2.id);
3748
+ normalized.consumers = normalized.consumers.map((b2) => b2.id);
3606
3749
  return normalized;
3607
3750
  });
3608
3751
  return acc.concat(nestedBlocks);
@@ -3664,7 +3807,7 @@ function dbReadIconFactory(provider) {
3664
3807
  }
3665
3808
 
3666
3809
  // api/db/index.ts
3667
- function useDatabaseApi(_, __, api) {
3810
+ function useDatabaseApi(_2, __, api) {
3668
3811
  return getDB().then((dbModels) => {
3669
3812
  Object.assign(api, apiFactory(dbModels));
3670
3813
  });
@@ -3689,7 +3832,7 @@ function apiFactory(dbModels) {
3689
3832
  searchUser: resultWrapper(dbSearchUser()),
3690
3833
  readUser: resultWrapper(dbReadUser()),
3691
3834
  updateUser: resultWrapper(dbUpdateUser()),
3692
- addNewReportToCurrentUser: resultWrapper(dbAddNewReportToCurrentUser()),
3835
+ updateMyData: resultWrapper(dbUpdateMyData()),
3693
3836
  revalidateReport: resultWrapper(dbRevalidateReportFactory(dbModels)),
3694
3837
  revalidateUrl: resultWrapper(dbRevalidateUrlFactory()),
3695
3838
  readPrivateBlocks: resultWrapper(dbReadPrivateBlocksFactory(dbModels)),
@@ -3725,35 +3868,79 @@ function endpointCRUDFactory(api, entity) {
3725
3868
  const crudRead = pickMethod(api, "read", entity);
3726
3869
  const crudUpdate = pickMethod(api, "update", entity);
3727
3870
  const crudDelete = pickMethod(api, "delete", entity);
3871
+ const crudUpdateBulk = pickMethod(api, "updateBulk", entity);
3872
+ const crudCreateBulk = pickMethod(api, "createBulk", entity);
3728
3873
  return [
3729
- endpoint("POST", `create/${entity}`, (req) => {
3730
- const { body } = req;
3731
- return crudCreate(body);
3732
- }, [CMS_ROLES.EDITOR]),
3874
+ endpoint(
3875
+ "POST",
3876
+ `create/bulk/${entity}`,
3877
+ (req) => {
3878
+ const { body } = req;
3879
+ const { files, ...rest } = body;
3880
+ const blocks = Object.keys(rest).map((key) => rest[key]);
3881
+ return crudCreateBulk(blocks);
3882
+ },
3883
+ [CMS_ROLES.EDITOR]
3884
+ ),
3885
+ endpoint(
3886
+ "POST",
3887
+ `create/${entity}`,
3888
+ (req) => {
3889
+ const { body } = req;
3890
+ return crudCreate(body);
3891
+ },
3892
+ [CMS_ROLES.EDITOR]
3893
+ ),
3733
3894
  endpoint("GET", `read/${entity}`, (req) => {
3734
3895
  const params = req.query;
3735
3896
  const id = normalizeList(params.id).map(parseFiniteNumber);
3736
3897
  return crudRead({ id, include: yn2(params.include) });
3737
3898
  }),
3738
- endpoint("POST", `update/${entity}`, (req) => {
3739
- const { body } = req;
3740
- return crudUpdate(body);
3741
- }, [CMS_ROLES.EDITOR]),
3742
- endpoint("DELETE", `delete/${entity}`, (req) => {
3743
- const id = parseFiniteNumber(req.query.id);
3744
- return crudDelete(id);
3745
- }, [CMS_ROLES.EDITOR])
3899
+ endpoint(
3900
+ "POST",
3901
+ `update/${entity}`,
3902
+ (req) => {
3903
+ const { body } = req;
3904
+ return crudUpdate(body);
3905
+ },
3906
+ [CMS_ROLES.EDITOR]
3907
+ ),
3908
+ endpoint(
3909
+ "POST",
3910
+ `update/bulk/${entity}`,
3911
+ (req) => {
3912
+ const { body } = req;
3913
+ const { files, ...rest } = body;
3914
+ const blocks = Object.keys(rest).map((key) => rest[key]);
3915
+ return crudUpdateBulk(blocks);
3916
+ },
3917
+ [CMS_ROLES.EDITOR]
3918
+ ),
3919
+ endpoint(
3920
+ "DELETE",
3921
+ `delete/${entity}`,
3922
+ (req) => {
3923
+ const id = parseFiniteNumber(req.query.id);
3924
+ return crudDelete(id);
3925
+ },
3926
+ [CMS_ROLES.EDITOR]
3927
+ )
3746
3928
  ];
3747
3929
  }
3748
3930
  function endpointVariantCRUDFactory(api) {
3749
3931
  const { validateVariantSlug } = api;
3750
3932
  return [
3751
3933
  ...endpointCRUDFactory(api, "variant"),
3752
- endpoint("GET", "validate/variant", (req) => {
3753
- const params = req.query;
3754
- const dimension = parseFiniteNumber(params.dimension);
3755
- return validateVariantSlug({ dimension, slug: slugify_default(params.slug) });
3756
- }, [CMS_ROLES.EDITOR])
3934
+ endpoint(
3935
+ "GET",
3936
+ "validate/variant",
3937
+ (req) => {
3938
+ const params = req.query;
3939
+ const dimension = parseFiniteNumber(params.dimension);
3940
+ return validateVariantSlug({ dimension, slug: slugify_default(params.slug) });
3941
+ },
3942
+ [CMS_ROLES.EDITOR]
3943
+ )
3757
3944
  ];
3758
3945
  }
3759
3946
 
@@ -3839,16 +4026,16 @@ function endpointRevalidateReportFactory(operations) {
3839
4026
  }
3840
4027
  try {
3841
4028
  const reportIdInt = parseInt(`${reportId}`, 10);
3842
- const profilePrefixClean = `${profilePrefix}`.split("/").filter((p) => p !== "").join("/");
4029
+ const profilePrefixClean = `${profilePrefix}`.split("/").filter((p2) => p2 !== "").join("/");
3843
4030
  const variantPaths = [];
3844
- const report = await readMetadata2({}).then((metadata) => metadata.ok ? metadata.data.data.find((r) => r.id === reportIdInt) : []);
4031
+ const report = await readMetadata2({}).then((metadata) => metadata.ok ? metadata.data.data.find((r2) => r2.id === reportIdInt) : []);
3845
4032
  if (report && report.mode === REPORT_MODES.UNILATERAL) {
3846
- report.dimensions.forEach((d) => {
3847
- d.variants.forEach((v) => {
4033
+ report.dimensions.forEach((d2) => {
4034
+ d2.variants.forEach((v2) => {
3848
4035
  variantPaths.push({
3849
4036
  prefix: profilePrefixClean,
3850
- variantId: v.id,
3851
- variantSlug: v.slug
4037
+ variantId: v2.id,
4038
+ variantSlug: v2.slug
3852
4039
  });
3853
4040
  });
3854
4041
  });
@@ -3865,12 +4052,12 @@ function endpointRevalidateReportFactory(operations) {
3865
4052
  if (urlsToRevalidate.ok) {
3866
4053
  qty = urlsToRevalidate.data.paths.length;
3867
4054
  samples = urlsToRevalidate.data.paths.slice(0, 5);
3868
- Promise.all(urlsToRevalidate.data.paths.map((path) => {
4055
+ Promise.all(urlsToRevalidate.data.paths.map((path2) => {
3869
4056
  let rev;
3870
4057
  try {
3871
- rev = res.revalidate(path, { unstable_onlyGenerated: true });
4058
+ rev = res.revalidate(path2, { unstable_onlyGenerated: true });
3872
4059
  } catch (error) {
3873
- console.log("error", path, error);
4060
+ console.log("error", path2, error);
3874
4061
  }
3875
4062
  return rev;
3876
4063
  }));
@@ -3965,7 +4152,8 @@ function endpointUpdateUserDataFactory(operations) {
3965
4152
  user: {
3966
4153
  ...session.user,
3967
4154
  bespoke_app_metadata: latestUserData.data.app_metadata,
3968
- bespoke_roles: latestUserData.data.roles.map((r) => r.name)
4155
+ bespoke_user_metadata: latestUserData.data.user_metadata,
4156
+ bespoke_roles: latestUserData.data.roles.map((r2) => r2.name)
3969
4157
  }
3970
4158
  });
3971
4159
  }
@@ -3973,17 +4161,17 @@ function endpointUpdateUserDataFactory(operations) {
3973
4161
  return response;
3974
4162
  }, [CMS_ROLES.ADMIN]);
3975
4163
  }
3976
- function endpointAddNewReportToCurrentUserFactory(operations) {
4164
+ function endpointUpdateMyDataFactory(operations) {
3977
4165
  const { updateUser: updateUser2, readUser: readUser2 } = operations;
3978
4166
  return endpoint("POST", "auth/update/me", async (req, res, session) => {
3979
- const reportId = req.body.report_id;
4167
+ const { report_id: reportId, user_metadata } = req.body;
4168
+ const updateObject = {
4169
+ user_id: session.user.sub,
4170
+ user_metadata: {}
4171
+ };
3980
4172
  try {
3981
- if (session && session.user && reportId) {
3982
- const updateObject = {
3983
- user_id: session.user.sub,
3984
- app_metadata: {}
3985
- };
3986
- const { user } = session;
4173
+ const { user } = session;
4174
+ if (session && user && reportId) {
3987
4175
  if (user.bespoke_app_metadata && user.bespoke_app_metadata.reports && Array.isArray(user.bespoke_app_metadata.reports)) {
3988
4176
  updateObject.app_metadata = {
3989
4177
  ...user.bespoke_app_metadata
@@ -3994,22 +4182,32 @@ function endpointAddNewReportToCurrentUserFactory(operations) {
3994
4182
  updateObject.app_metadata.reports.push({
3995
4183
  reportId
3996
4184
  });
3997
- await updateUser2(updateObject);
3998
- const latestUserData = await readUser2(updateObject.user_id);
3999
- if (latestUserData.ok) {
4000
- await getAuth_default.updateSession(req, res, {
4001
- ...session,
4002
- user: {
4003
- ...user,
4004
- bespoke_app_metadata: latestUserData.data.app_metadata
4005
- }
4006
- });
4007
- }
4185
+ }
4186
+ if (user_metadata) {
4187
+ updateObject.user_metadata = {
4188
+ ...user.bespoke_app_metadata,
4189
+ ...user_metadata
4190
+ };
4191
+ }
4192
+ await updateUser2(updateObject);
4193
+ const latestUserData = await readUser2(updateObject.user_id);
4194
+ if (latestUserData.ok) {
4195
+ await getAuth_default.updateSession(req, res, {
4196
+ ...session,
4197
+ user: {
4198
+ ...user,
4199
+ bespoke_app_metadata: latestUserData.data.app_metadata,
4200
+ bespoke_user_metadata: latestUserData.data.user_metadata
4201
+ }
4202
+ });
4008
4203
  }
4009
4204
  return {
4010
4205
  ok: true,
4011
4206
  status: 200,
4012
- data: "User & session updated"
4207
+ data: {
4208
+ ok: true,
4209
+ message: "User & session updated"
4210
+ }
4013
4211
  };
4014
4212
  } catch (error) {
4015
4213
  return {
@@ -4018,9 +4216,9 @@ function endpointAddNewReportToCurrentUserFactory(operations) {
4018
4216
  error: error.message
4019
4217
  };
4020
4218
  }
4021
- }, [CMS_ROLES.EDITOR]);
4219
+ }, []);
4022
4220
  }
4023
- async function generatePDF(path) {
4221
+ async function generatePDF(path2) {
4024
4222
  const width = 1920;
4025
4223
  const height = 1080;
4026
4224
  const maxTimeoutPerPage = 0;
@@ -4034,7 +4232,7 @@ async function generatePDF(path) {
4034
4232
  headless: "new",
4035
4233
  ignoreHTTPSErrors: true
4036
4234
  });
4037
- const url = new URL(path);
4235
+ const url = new URL(path2);
4038
4236
  const searchParams = new URLSearchParams(url.search);
4039
4237
  searchParams.set("print", "true");
4040
4238
  url.search = searchParams.toString();
@@ -4114,11 +4312,11 @@ async function generatePDF(path) {
4114
4312
  }
4115
4313
  function endpointDownloadReport() {
4116
4314
  return endpoint("POST", "pdf", async (req, res) => {
4117
- const { slugs, path } = req.body;
4118
- if (!slugs || !path) {
4315
+ const { slugs, path: path2 } = req.body;
4316
+ if (!slugs || !path2) {
4119
4317
  throw new BackendError(400, "Missing path parameter in request.");
4120
4318
  } else {
4121
- const url = new URL(path, req.headers["origin"]);
4319
+ const url = new URL(path2, req.headers["origin"]);
4122
4320
  const pdf = await generatePDF(url);
4123
4321
  return {
4124
4322
  ok: true,
@@ -4185,8 +4383,8 @@ function endpointReportVariables() {
4185
4383
 
4186
4384
  // api/endpoints/index.ts
4187
4385
  var verbose3 = getLogging_default();
4188
- function endpointKey(method, path) {
4189
- return `${method.toUpperCase()} ${path.toLowerCase()}`;
4386
+ function endpointKey(method, path2) {
4387
+ return `${method.toUpperCase()} ${path2.toLowerCase()}`;
4190
4388
  }
4191
4389
  function getEndpointMap(db) {
4192
4390
  const api = apiFactory(db);
@@ -4215,7 +4413,7 @@ function getEndpointMap(db) {
4215
4413
  endpointGetUsersFactory(api),
4216
4414
  endpointGetUserDataFactory(api),
4217
4415
  endpointUpdateUserDataFactory(api),
4218
- endpointAddNewReportToCurrentUserFactory(api),
4416
+ endpointUpdateMyDataFactory(api),
4219
4417
  endpointRevalidateReportFactory(api),
4220
4418
  endpointRevalidateUrlFactory(),
4221
4419
  endpointReadPrivateBlocksFactory(api),
@@ -4223,7 +4421,7 @@ function getEndpointMap(db) {
4223
4421
  endpointListIconsFactory(api, "tabler"),
4224
4422
  endpointReadIconFactory(api, "tabler"),
4225
4423
  endpointReportVariables()
4226
- ].map(({ handler, method, path, roleRequired }) => [endpointKey(method, path), { handler, roleRequired }]));
4424
+ ].map(({ handler, method, path: path2, roleRequired }) => [endpointKey(method, path2), { handler, roleRequired }]));
4227
4425
  }
4228
4426
  var endpointMap = getDB().then(getEndpointMap);
4229
4427
  async function endpointNextJsHandlerFactory(req, res) {
@@ -4232,10 +4430,10 @@ async function endpointNextJsHandlerFactory(req, res) {
4232
4430
  origin: "*"
4233
4431
  });
4234
4432
  const { query: queryParams, method } = req;
4235
- const { path, ...query } = queryParams;
4236
- if (path && method) {
4433
+ const { path: path2, ...query } = queryParams;
4434
+ if (path2 && method) {
4237
4435
  const handlerObj = await endpointMap.then((map) => {
4238
- const pathString = [].concat(path).join("/");
4436
+ const pathString = [].concat(path2).join("/");
4239
4437
  const key = endpointKey(method, pathString);
4240
4438
  return map[key];
4241
4439
  });
@@ -4284,10 +4482,10 @@ async function endpointNextJsHandlerFactory(req, res) {
4284
4482
  });
4285
4483
  }
4286
4484
  }
4287
- } else if (!path) {
4485
+ } else if (!path2) {
4288
4486
  await endpointMap.then(console.log);
4289
4487
  }
4290
- return res.status(404).json({ error: "No matching route", path, query });
4488
+ return res.status(404).json({ error: "No matching route", path: path2, query });
4291
4489
  }
4292
4490
 
4293
4491
  // api/crosswalk/index.ts
@@ -4304,7 +4502,7 @@ var crosswalk_default = reportsCrosswalkEntrypointFn;
4304
4502
  var actions_exports = {};
4305
4503
  __export(actions_exports, {
4306
4504
  addBlockToState: () => addBlockToState,
4307
- addNewReportToCurrentUser: () => addNewReportToCurrentUser,
4505
+ cloneEntity: () => cloneEntity,
4308
4506
  createEntity: () => createEntity,
4309
4507
  deleteEntity: () => deleteEntity,
4310
4508
  deleteQueryParam: () => deleteQueryParam,
@@ -4324,11 +4522,13 @@ __export(actions_exports, {
4324
4522
  searchRole: () => searchRole,
4325
4523
  searchUser: () => searchUser,
4326
4524
  setCurrentLocale: () => setCurrentLocale,
4525
+ setPreferredLocale: () => setPreferredLocale,
4327
4526
  setPreviews: () => setPreviews,
4328
4527
  setQueryParam: () => setQueryParam,
4329
4528
  setSectionState: () => setSectionState,
4330
4529
  setStatus: () => setStatus,
4331
4530
  updateEntity: () => updateEntity,
4531
+ updateMyData: () => updateMyData,
4332
4532
  updateUser: () => updateUser,
4333
4533
  urlProxy: () => urlProxy2,
4334
4534
  variantValidateSlug: () => variantValidateSlug
@@ -4416,9 +4616,7 @@ var transformDeletePayload = (id) => {
4416
4616
  };
4417
4617
  var transformReadMembers = (params) => {
4418
4618
  if (params.mode === "slugs") {
4419
- const slugs = params.slugs.map(
4420
- (slug) => [slug.variantSlug, slug.memberSlug].join("/")
4421
- ).join(",");
4619
+ const slugs = params.slugs.map((slug) => [slug.variantSlug, slug.memberSlug].join("/")).join(",");
4422
4620
  return { ...params, slugs };
4423
4621
  }
4424
4622
  if (params.mode === "related") {
@@ -4429,6 +4627,7 @@ var transformReadMembers = (params) => {
4429
4627
  function apiFactory2(baseURL) {
4430
4628
  const axios7 = axios6.create({ baseURL });
4431
4629
  return {
4630
+ createBulkBlock: httpPOST(axios7, "create/bulk/block"),
4432
4631
  createBlock: httpPOST(axios7, "create/block"),
4433
4632
  createDimension: httpPOST(axios7, "create/dimension"),
4434
4633
  createFormatter: httpPOST(axios7, "create/formatter"),
@@ -4447,6 +4646,7 @@ function apiFactory2(baseURL) {
4447
4646
  readReport: httpGET(axios7, "read/report"),
4448
4647
  readSection: httpGET(axios7, "read/section"),
4449
4648
  readVariant: httpGET(axios7, "read/variant"),
4649
+ updateBulkBlock: httpPOST(axios7, "update/bulk/block"),
4450
4650
  updateBlock: httpPOST(axios7, "update/block"),
4451
4651
  updateDimension: httpPOST(axios7, "update/dimension"),
4452
4652
  updateFormatter: httpPOST(axios7, "update/formatter"),
@@ -4478,7 +4678,7 @@ function apiFactory2(baseURL) {
4478
4678
  searchUser: httpGET(axios7, "auth/search/users"),
4479
4679
  readUser: httpGET(axios7, "auth/read/user"),
4480
4680
  updateUser: httpPOST(axios7, "auth/update/user"),
4481
- addNewReportToCurrentUser: httpPOST(axios7, "auth/update/me"),
4681
+ updateMyData: httpPOST(axios7, "auth/update/me"),
4482
4682
  revalidateReport: httpGET(axios7, "revalidate/report"),
4483
4683
  revalidateUrl: httpGET(axios7, "revalidate/url"),
4484
4684
  readPrivateBlocks: httpPOST(axios7, "read/blocks/private"),
@@ -4518,11 +4718,11 @@ function mortarEval(varInnerName, varOuterValue, logic, formatterFunctions, attr
4518
4718
  });
4519
4719
  let output;
4520
4720
  if (attributes) {
4521
- const fn3 = new Function(varInnerName, "console", "libs", "formatters", "locale", "variables", logic);
4522
- output = fn3(varOuterValue, pConsole, libraries, formatterFunctions, locale, attributes);
4721
+ const fn4 = new Function(varInnerName, "console", "libs", "formatters", "locale", "variables", logic);
4722
+ output = fn4(varOuterValue, pConsole, libraries, formatterFunctions, locale, attributes);
4523
4723
  } else {
4524
- const fn3 = new Function(varInnerName, "console", "libs", "formatters", "locale", logic);
4525
- output = fn3(varOuterValue, pConsole, libraries, formatterFunctions, locale);
4724
+ const fn4 = new Function(varInnerName, "console", "libs", "formatters", "locale", logic);
4725
+ output = fn4(varOuterValue, pConsole, libraries, formatterFunctions, locale);
4526
4726
  }
4527
4727
  if (typeof output === "object" && Object.keys(output).length > 0) {
4528
4728
  Object.assign(vars, output);
@@ -4539,13 +4739,13 @@ function isInSet(value, ...args) {
4539
4739
  }
4540
4740
 
4541
4741
  // libs/js/list.ts
4542
- function list(n) {
4543
- return n.reduce((str, item, i) => {
4544
- if (!i)
4742
+ function list(n2) {
4743
+ return n2.reduce((str, item, i2) => {
4744
+ if (!i2)
4545
4745
  str += item;
4546
- else if (i === n.length - 1 && i === 1)
4746
+ else if (i2 === n2.length - 1 && i2 === 1)
4547
4747
  str += ` and ${item}`;
4548
- else if (i === n.length - 1)
4748
+ else if (i2 === n2.length - 1)
4549
4749
  str += `, and ${item}`;
4550
4750
  else
4551
4751
  str += `, ${item}`;
@@ -4561,13 +4761,13 @@ function varSwap(sourceString, formatterFunctions, blockContext, passive = false
4561
4761
  return sourceString;
4562
4762
  const match = /([A-z0-9]*)\{\{([^\}]+)\}\}/g;
4563
4763
  const resultString = sourceString.replace(match, (match2, g1, keyMatch) => {
4564
- let formatter = (d) => d;
4764
+ let formatter = (d2) => d2;
4565
4765
  if (g1) {
4566
4766
  const formatTitle = g1.replace(/^\w/g, (chr) => chr.toLowerCase());
4567
4767
  if (formatTitle in formatterFunctions) {
4568
4768
  formatter = formatterFunctions[formatTitle];
4569
4769
  } else {
4570
- formatter = (d) => `${g1}${d}`;
4770
+ formatter = (d2) => `${g1}${d2}`;
4571
4771
  }
4572
4772
  }
4573
4773
  const value = Array.isArray(variables[keyMatch]) ? list(variables[keyMatch]) : variables[keyMatch];
@@ -4597,14 +4797,14 @@ var varSwapRecursive = (sourceObj, formatterFunctions, blockContext) => {
4597
4797
  if (typeof obj[skey] === "string") {
4598
4798
  obj[skey] = varSwap_default(obj[skey], formatterFunctions, blockContext);
4599
4799
  } else if (Array.isArray(obj[skey])) {
4600
- obj[skey] = obj[skey].filter(allowed).map((o) => {
4601
- if (typeof o === "object") {
4602
- return varSwapRecursive(o, formatterFunctions, blockContext);
4800
+ obj[skey] = obj[skey].filter(allowed).map((o2) => {
4801
+ if (typeof o2 === "object") {
4802
+ return varSwapRecursive(o2, formatterFunctions, blockContext);
4603
4803
  }
4604
- if (typeof o === "string") {
4605
- return varSwap_default(o, formatterFunctions, blockContext);
4804
+ if (typeof o2 === "string") {
4805
+ return varSwap_default(o2, formatterFunctions, blockContext);
4606
4806
  }
4607
- return o;
4807
+ return o2;
4608
4808
  });
4609
4809
  } else if (typeof obj[skey] === "object" && obj[skey] !== null && !(obj[skey] instanceof Date)) {
4610
4810
  obj[skey] = varSwapRecursive(obj[skey], formatterFunctions, blockContext);
@@ -4618,7 +4818,7 @@ var varSwapRecursive_default = varSwapRecursive;
4618
4818
  var scaffoldDynamic_default = (optionsArray) => {
4619
4819
  if (!Array.isArray(optionsArray))
4620
4820
  return [];
4621
- return optionsArray.map((d) => typeof d === "string" ? { allowed: "always", label: d, id: d } : { allowed: "always", label: d.id, ...d });
4821
+ return optionsArray.map((d2) => typeof d2 === "string" ? { allowed: "always", label: d2, id: d2 } : { allowed: "always", label: d2.id, ...d2 });
4622
4822
  };
4623
4823
 
4624
4824
  // libs/selectors/valueInOptions.ts
@@ -4629,7 +4829,7 @@ var valueInOptions_default = (type, value, options) => {
4629
4829
  return options.find((obj) => obj.id === value);
4630
4830
  }
4631
4831
  const multiValue = Array.isArray(value) ? value : value.split(",");
4632
- return Array.isArray(multiValue) && multiValue.every((d) => options.map((o) => o.id).includes(d));
4832
+ return Array.isArray(multiValue) && multiValue.every((d2) => options.map((o2) => o2.id).includes(d2));
4633
4833
  };
4634
4834
 
4635
4835
  // libs/selectors/runSelector.js
@@ -4655,7 +4855,7 @@ function runSelector(id, logic, formatterFunctions, blockContext, replaceQuery =
4655
4855
  const fallbackValue = options && options[0] && options[0].id || options[0] || "";
4656
4856
  defaultValue = maybeFixForMulti(fallbackValue);
4657
4857
  }
4658
- if (replaceQuery) {
4858
+ if (replaceQuery && typeof window !== "undefined") {
4659
4859
  const accesor = `selector${id}id`;
4660
4860
  const searchParams = new URLSearchParams(window.location.search);
4661
4861
  const query = Object.fromEntries(searchParams);
@@ -4682,14 +4882,14 @@ var selectorQueryToVariable = (id, query, config) => {
4682
4882
  const queryObject = new URLSearchParams(query);
4683
4883
  if (config.type === SELECTOR_TYPES.MULTI) {
4684
4884
  const queryIds = queryObject.get(accessor) ? queryObject.get(accessor).split(",") : config.defaultValue;
4685
- const options = config.options.filter((d) => queryIds.includes(d.id));
4885
+ const options = config.options.filter((d2) => queryIds.includes(d2.id));
4686
4886
  return {
4687
4887
  [`selector${id}id`]: queryIds,
4688
- [`selector${id}label`]: (options || []).map((d) => d.label)
4888
+ [`selector${id}label`]: (options || []).map((d2) => d2.label)
4689
4889
  };
4690
4890
  }
4691
- const queryId = queryObject.get(accessor) && config.options.find((d) => d.id === queryObject.get(accessor)) ? queryObject.get(accessor) : config.defaultValue;
4692
- const option = config.options.find((d) => d.id === queryId);
4891
+ const queryId = queryObject.get(accessor) && config.options.find((d2) => d2.id === queryObject.get(accessor)) ? queryObject.get(accessor) : config.defaultValue;
4892
+ const option = config.options.find((d2) => d2.id === queryId);
4693
4893
  return {
4694
4894
  [`selector${id}id`]: queryId,
4695
4895
  [`selector${id}label`]: option && option.label || void 0
@@ -4736,9 +4936,9 @@ axios6.interceptors.request.use((config) => ({
4736
4936
  ...config,
4737
4937
  requestStart: Date.now()
4738
4938
  }));
4739
- axios6.interceptors.response.use((d) => ({
4740
- ...d,
4741
- requestDuration: (/* @__PURE__ */ new Date()).getTime() - d.config.requestStart
4939
+ axios6.interceptors.response.use((d2) => ({
4940
+ ...d2,
4941
+ requestDuration: (/* @__PURE__ */ new Date()).getTime() - d2.config.requestStart
4742
4942
  }), (e) => Promise.reject(e));
4743
4943
  var swapAPI = (api, formatterFunctions, blockContext) => {
4744
4944
  let url = varSwap_default(api, formatterFunctions, blockContext);
@@ -4903,8 +5103,8 @@ async function runSingleBlock(block, formatterFunctions, blockContext, readMembe
4903
5103
  };
4904
5104
  }
4905
5105
  }
4906
- resp = apiResponses.length === 1 ? apiResponses[0].data : apiResponses.map((r) => r.data);
4907
- responseSize = apiResponses.reduce((acc, r) => acc + JSON.stringify(r.data).length / 1024, 0);
5106
+ resp = apiResponses.length === 1 ? apiResponses[0].data : apiResponses.map((r2) => r2.data);
5107
+ responseSize = apiResponses.reduce((acc, r2) => acc + JSON.stringify(r2.data).length / 1024, 0);
4908
5108
  duration = Math.max(...apiResponses.map((ar) => ar.requestDuration));
4909
5109
  }
4910
5110
  if (block.type === BLOCK_TYPES.SELECTOR) {
@@ -5030,7 +5230,7 @@ async function runSingleBlock(block, formatterFunctions, blockContext, readMembe
5030
5230
  }
5031
5231
  };
5032
5232
  }
5033
- const nsVars = Object.keys(vars).reduce((acc, d) => ({ ...acc, [`${block.type}${block.id}${d}`]: vars[d] }), {});
5233
+ const nsVars = Object.keys(vars).reduce((acc, d2) => ({ ...acc, [`${block.type}${block.id}${d2}`]: vars[d2] }), {});
5034
5234
  return {
5035
5235
  renderVariables: vars,
5036
5236
  outputVariables: block.type === BLOCK_TYPES.GENERATOR ? vars : nsVars,
@@ -5131,7 +5331,7 @@ var runConsumersV2 = async (blocks, sections, bid, formatterFunctions, blockCont
5131
5331
  block.inputs.filter((iid) => executionOrder.includes(String(iid))).map((iid) => runningBlocks.get(Number(iid)))
5132
5332
  );
5133
5333
  const runningTask = dependenciesDone.then(async () => {
5134
- const variables = block.inputs.reduce((acc, d) => ({ ...acc, ...variablesById[d] }), attributes);
5334
+ const variables = block.inputs.reduce((acc, d2) => ({ ...acc, ...variablesById[d2] }), attributes);
5135
5335
  const inputNotAllowed = block.inputs.find(
5136
5336
  (iid) => {
5137
5337
  const ignoreInputs = block.settings?.ignoreCascade ? block.settings?.ignoreCascade : [];
@@ -5217,18 +5417,18 @@ var runConsumersV2 = async (blocks, sections, bid, formatterFunctions, blockCont
5217
5417
  function previewsToAttributes(previews = []) {
5218
5418
  return previews.reduce((attributes, preview, index) => {
5219
5419
  if (preview) {
5220
- const i = index + 1;
5221
- attributes[`id${i}`] = preview.id;
5222
- attributes[`name${i}`] = preview.name;
5420
+ const i2 = index + 1;
5421
+ attributes[`id${i2}`] = preview.id;
5422
+ attributes[`name${i2}`] = preview.name;
5223
5423
  if ("attributes" in preview) {
5224
5424
  Object.keys(preview.attributes).forEach((key) => {
5225
- attributes[`attr_${key}${i}`] = preview.attributes[key];
5425
+ attributes[`attr_${key}${i2}`] = preview.attributes[key];
5226
5426
  });
5227
5427
  }
5228
- attributes[`variant_id${i}`] = preview.variant_id;
5229
- attributes[`variant_name${i}`] = preview.variant_name;
5230
- attributes[`dimension_id${i}`] = preview.dimension_id;
5231
- attributes[`dimension_name${i}`] = preview.dimension_name;
5428
+ attributes[`variant_id${i2}`] = preview.variant_id;
5429
+ attributes[`variant_name${i2}`] = preview.variant_name;
5430
+ attributes[`dimension_id${i2}`] = preview.dimension_id;
5431
+ attributes[`dimension_name${i2}`] = preview.dimension_name;
5232
5432
  attributes["report_id"] = preview.report_id;
5233
5433
  attributes["report_name"] = preview.report_name;
5234
5434
  }
@@ -5250,13 +5450,13 @@ var publicEnvVarsToAttributes_default = publicEnvVarsToAttributes;
5250
5450
  function comparePositions(firstPos, secondPos) {
5251
5451
  return +(firstPos < secondPos) - +(firstPos > secondPos);
5252
5452
  }
5253
- function orderSort(a, b, accessor = "ordering") {
5254
- return comparePositions(b[accessor], a[accessor]);
5453
+ function orderSort(a2, b2, accessor = "ordering") {
5454
+ return comparePositions(b2[accessor], a2[accessor]);
5255
5455
  }
5256
5456
  var parse = (config, formatters = {}, locale = "en", actions = {}, extraGlobals = {}) => {
5257
5457
  const globals = {
5258
- setVariables: actions.onSetVariables ? actions.onSetVariables : (d) => d,
5259
- openModal: actions.onOpenModal ? actions.onOpenModal : (d) => d,
5458
+ setVariables: actions.onSetVariables ? actions.onSetVariables : (d2) => d2,
5459
+ openModal: actions.onOpenModal ? actions.onOpenModal : (d2) => d2,
5260
5460
  formatters,
5261
5461
  libs: libraries,
5262
5462
  locale,
@@ -5271,10 +5471,10 @@ var parse = (config, formatters = {}, locale = "en", actions = {}, extraGlobals
5271
5471
  }
5272
5472
  for (const key in obj) {
5273
5473
  if (Array.isArray(obj[key])) {
5274
- obj[key] = obj[key].map((d) => {
5275
- if (isObject(d))
5276
- return makeFunctions(d);
5277
- return d;
5474
+ obj[key] = obj[key].map((d2) => {
5475
+ if (isObject(d2))
5476
+ return makeFunctions(d2);
5477
+ return d2;
5278
5478
  });
5279
5479
  } else if (isObject(obj[key]))
5280
5480
  obj[key] = makeFunctions(obj[key]);
@@ -5287,12 +5487,12 @@ var parse = (config, formatters = {}, locale = "en", actions = {}, extraGlobals
5287
5487
  // store/lib.ts
5288
5488
  var { localeDefault: localeDefault8 } = getLocales_default();
5289
5489
  var blockSchema = new schema.Entity("block" /* BLOCKS */, {}, {
5290
- mergeStrategy(a, b) {
5291
- if (b.block_input)
5292
- return a || {};
5490
+ mergeStrategy(a2, b2) {
5491
+ if (b2.block_input)
5492
+ return a2 || {};
5293
5493
  return {
5294
- ...a,
5295
- ...b
5494
+ ...a2,
5495
+ ...b2
5296
5496
  };
5297
5497
  }
5298
5498
  });
@@ -5384,9 +5584,9 @@ var parseVariableUpdateParams = (status, params = void 0) => {
5384
5584
  statusPayload
5385
5585
  };
5386
5586
  };
5387
- var funcifyFormattersByLocale = (formatters = [], locale = localeDefault8) => formatters.reduce((acc, f) => {
5388
- const formatterFn = parse({ vars: ["n"], logic: f.content.logic }, {}, locale, {});
5389
- acc[f.name] = formatterFn;
5587
+ var funcifyFormattersByLocale = (formatters = [], locale = localeDefault8) => formatters.reduce((acc, f2) => {
5588
+ const formatterFn = parse({ vars: ["n"], logic: f2.content.logic }, {}, locale, {});
5589
+ acc[f2.name] = formatterFn;
5390
5590
  return acc;
5391
5591
  }, {});
5392
5592
 
@@ -5401,6 +5601,7 @@ var initialState = {
5401
5601
  localeDefault: localeDefault9,
5402
5602
  locales: locales8,
5403
5603
  currentLocale: localeDefault9,
5604
+ preferredLocale: localeDefault9,
5404
5605
  showToolbar: false,
5405
5606
  activeSection: null,
5406
5607
  previews: [],
@@ -5430,6 +5631,9 @@ var statusSlice = createSlice({
5430
5631
  setCurrentLocale(state, action) {
5431
5632
  state.currentLocale = action.payload;
5432
5633
  },
5634
+ setPreferredLocale(state, action) {
5635
+ state.preferredLocale = action.payload;
5636
+ },
5433
5637
  setSectionState(state, action) {
5434
5638
  state.sectionState = { ...state.sectionState, ...action.payload };
5435
5639
  },
@@ -5548,7 +5752,8 @@ var recordsSlice = createSlice({
5548
5752
  const req = action.payload;
5549
5753
  state.requests[req.type][req.key] = req;
5550
5754
  if (req.status === "SUCCESS" /* SUCCESS */) {
5551
- const newEntities = normalizeEntity(req.type, [req.data]);
5755
+ const entities = Array.isArray(req.data) ? req.data : [req.data];
5756
+ const newEntities = normalizeEntity(req.type, entities);
5552
5757
  const nextEntities = combineRecords(state.entities, newEntities);
5553
5758
  state.entities = nextEntities;
5554
5759
  if (req.type === "report") {
@@ -5568,7 +5773,7 @@ var recordsSlice = createSlice({
5568
5773
  } else if (req.type === "variant") {
5569
5774
  const item = req.data;
5570
5775
  state.entities.dimension[item.dimension_id].variants.push(item.id);
5571
- } else if (req.type === "section") {
5776
+ } else if (req.type === "section" && !Array.isArray(req.data)) {
5572
5777
  const item = req.data;
5573
5778
  state.entities.report[item.report_id].sections.push(item.id);
5574
5779
  state.entities.report[item.report_id].sections = recalculateOrder(
@@ -5576,8 +5781,15 @@ var recordsSlice = createSlice({
5576
5781
  nextEntities.section
5577
5782
  );
5578
5783
  } else if (req.type === "block") {
5579
- const item = req.data;
5580
- state.entities.section[item.section_id].blocks.push(item.id);
5784
+ if (Array.isArray(req.data)) {
5785
+ const items = req.data;
5786
+ const item = items[0];
5787
+ const ids = items.map((item2) => item2.id);
5788
+ state.entities.section[item.section_id].blocks.concat(ids);
5789
+ } else {
5790
+ const item = req.data;
5791
+ state.entities.section[item.section_id].blocks.push(item.id);
5792
+ }
5581
5793
  }
5582
5794
  }
5583
5795
  },
@@ -5602,21 +5814,23 @@ var recordsSlice = createSlice({
5602
5814
  * Besides saving the new elements:
5603
5815
  * - Updates the order of the reference IDs in the parent's array
5604
5816
  */
5817
+ // UPDATE THIS ONE TO SUPPORT MULTIPLE UPDATES
5605
5818
  setUpdateRequest(state, action) {
5606
5819
  const req = action.payload;
5607
5820
  state.requests[req.type][req.key] = req;
5608
5821
  if (req.status === "SUCCESS" /* SUCCESS */) {
5609
- const currEntities = normalizeEntity(req.type, [req.data]);
5822
+ const entities = Array.isArray(req.data) ? req.data : [req.data];
5823
+ const currEntities = normalizeEntity(req.type, entities);
5610
5824
  let isInputUpdate;
5611
5825
  let targetId;
5612
5826
  let isDeletion;
5613
- if (req.type === "block") {
5827
+ if (req.type === "block" && !Array.isArray(req.data)) {
5614
5828
  const oldInputs = state.entities.block[req.data.id].inputs;
5615
5829
  const newInputs = currEntities.block[req.data.id].inputs;
5616
5830
  isInputUpdate = oldInputs.length !== newInputs.length;
5617
5831
  if (isInputUpdate) {
5618
5832
  isDeletion = oldInputs.length > newInputs.length;
5619
- targetId = isDeletion ? oldInputs.filter((d) => !newInputs.includes(d))[0] : newInputs.filter((d) => !oldInputs.includes(d))[0];
5833
+ targetId = isDeletion ? oldInputs.filter((d2) => !newInputs.includes(d2))[0] : newInputs.filter((d2) => !oldInputs.includes(d2))[0];
5620
5834
  }
5621
5835
  Object.values(currEntities.block).forEach((block) => {
5622
5836
  if (block.block_input) {
@@ -5632,17 +5846,17 @@ var recordsSlice = createSlice({
5632
5846
  nextEntities.report[item.report_id].dimensions,
5633
5847
  nextEntities.dimension
5634
5848
  );
5635
- } else if (req.type === "section") {
5849
+ } else if (req.type === "section" && !Array.isArray(req.data)) {
5636
5850
  const item = req.data;
5637
5851
  state.entities.report[item.report_id].sections = recalculateOrder(
5638
5852
  nextEntities.report[item.report_id].sections,
5639
5853
  nextEntities.section
5640
5854
  );
5641
- } else if (req.type === "block") {
5855
+ } else if (req.type === "block" && !Array.isArray(req.data)) {
5642
5856
  const item = req.data;
5643
5857
  if (isInputUpdate) {
5644
5858
  if (isDeletion) {
5645
- state.entities.block[targetId].consumers = state.entities.block[targetId].consumers.filter((d) => d !== item.id);
5859
+ state.entities.block[targetId].consumers = state.entities.block[targetId].consumers.filter((d2) => d2 !== item.id);
5646
5860
  } else {
5647
5861
  state.entities.block[targetId].consumers.push(item.id);
5648
5862
  }
@@ -5739,6 +5953,392 @@ function arrayRemove(list2, item) {
5739
5953
  list2.splice(index, 1);
5740
5954
  }
5741
5955
  }
5956
+
5957
+ // ../../node_modules/immer/dist/immer.esm.mjs
5958
+ function n(n2) {
5959
+ for (var r2 = arguments.length, t2 = Array(r2 > 1 ? r2 - 1 : 0), e = 1; e < r2; e++)
5960
+ t2[e - 1] = arguments[e];
5961
+ if ("production" !== process.env.NODE_ENV) {
5962
+ var i2 = Y[n2], o2 = i2 ? "function" == typeof i2 ? i2.apply(null, t2) : i2 : "unknown error nr: " + n2;
5963
+ throw Error("[Immer] " + o2);
5964
+ }
5965
+ throw Error("[Immer] minified error nr: " + n2 + (t2.length ? " " + t2.map(function(n3) {
5966
+ return "'" + n3 + "'";
5967
+ }).join(",") : "") + ". Find the full error at: https://bit.ly/3cXEKWf");
5968
+ }
5969
+ function r(n2) {
5970
+ return !!n2 && !!n2[Q];
5971
+ }
5972
+ function t(n2) {
5973
+ var r2;
5974
+ return !!n2 && (function(n3) {
5975
+ if (!n3 || "object" != typeof n3)
5976
+ return false;
5977
+ var r3 = Object.getPrototypeOf(n3);
5978
+ if (null === r3)
5979
+ return true;
5980
+ var t2 = Object.hasOwnProperty.call(r3, "constructor") && r3.constructor;
5981
+ return t2 === Object || "function" == typeof t2 && Function.toString.call(t2) === Z;
5982
+ }(n2) || Array.isArray(n2) || !!n2[L] || !!(null === (r2 = n2.constructor) || void 0 === r2 ? void 0 : r2[L]) || s(n2) || v(n2));
5983
+ }
5984
+ function i(n2, r2, t2) {
5985
+ void 0 === t2 && (t2 = false), 0 === o(n2) ? (t2 ? Object.keys : nn)(n2).forEach(function(e) {
5986
+ t2 && "symbol" == typeof e || r2(e, n2[e], n2);
5987
+ }) : n2.forEach(function(t3, e) {
5988
+ return r2(e, t3, n2);
5989
+ });
5990
+ }
5991
+ function o(n2) {
5992
+ var r2 = n2[Q];
5993
+ return r2 ? r2.i > 3 ? r2.i - 4 : r2.i : Array.isArray(n2) ? 1 : s(n2) ? 2 : v(n2) ? 3 : 0;
5994
+ }
5995
+ function u(n2, r2) {
5996
+ return 2 === o(n2) ? n2.has(r2) : Object.prototype.hasOwnProperty.call(n2, r2);
5997
+ }
5998
+ function a(n2, r2) {
5999
+ return 2 === o(n2) ? n2.get(r2) : n2[r2];
6000
+ }
6001
+ function f(n2, r2, t2) {
6002
+ var e = o(n2);
6003
+ 2 === e ? n2.set(r2, t2) : 3 === e ? n2.add(t2) : n2[r2] = t2;
6004
+ }
6005
+ function c(n2, r2) {
6006
+ return n2 === r2 ? 0 !== n2 || 1 / n2 == 1 / r2 : n2 != n2 && r2 != r2;
6007
+ }
6008
+ function s(n2) {
6009
+ return X && n2 instanceof Map;
6010
+ }
6011
+ function v(n2) {
6012
+ return q && n2 instanceof Set;
6013
+ }
6014
+ function p(n2) {
6015
+ return n2.o || n2.t;
6016
+ }
6017
+ function l(n2) {
6018
+ if (Array.isArray(n2))
6019
+ return Array.prototype.slice.call(n2);
6020
+ var r2 = rn(n2);
6021
+ delete r2[Q];
6022
+ for (var t2 = nn(r2), e = 0; e < t2.length; e++) {
6023
+ var i2 = t2[e], o2 = r2[i2];
6024
+ false === o2.writable && (o2.writable = true, o2.configurable = true), (o2.get || o2.set) && (r2[i2] = { configurable: true, writable: true, enumerable: o2.enumerable, value: n2[i2] });
6025
+ }
6026
+ return Object.create(Object.getPrototypeOf(n2), r2);
6027
+ }
6028
+ function d(n2, e) {
6029
+ return void 0 === e && (e = false), y(n2) || r(n2) || !t(n2) || (o(n2) > 1 && (n2.set = n2.add = n2.clear = n2.delete = h), Object.freeze(n2), e && i(n2, function(n3, r2) {
6030
+ return d(r2, true);
6031
+ }, true)), n2;
6032
+ }
6033
+ function h() {
6034
+ n(2);
6035
+ }
6036
+ function y(n2) {
6037
+ return null == n2 || "object" != typeof n2 || Object.isFrozen(n2);
6038
+ }
6039
+ function b(r2) {
6040
+ var t2 = tn[r2];
6041
+ return t2 || n(18, r2), t2;
6042
+ }
6043
+ function _() {
6044
+ return "production" === process.env.NODE_ENV || U || n(0), U;
6045
+ }
6046
+ function j(n2, r2) {
6047
+ r2 && (b("Patches"), n2.u = [], n2.s = [], n2.v = r2);
6048
+ }
6049
+ function g(n2) {
6050
+ O(n2), n2.p.forEach(S), n2.p = null;
6051
+ }
6052
+ function O(n2) {
6053
+ n2 === U && (U = n2.l);
6054
+ }
6055
+ function w(n2) {
6056
+ return U = { p: [], l: U, h: n2, m: true, _: 0 };
6057
+ }
6058
+ function S(n2) {
6059
+ var r2 = n2[Q];
6060
+ 0 === r2.i || 1 === r2.i ? r2.j() : r2.g = true;
6061
+ }
6062
+ function P(r2, e) {
6063
+ e._ = e.p.length;
6064
+ var i2 = e.p[0], o2 = void 0 !== r2 && r2 !== i2;
6065
+ return e.h.O || b("ES5").S(e, r2, o2), o2 ? (i2[Q].P && (g(e), n(4)), t(r2) && (r2 = M(e, r2), e.l || x(e, r2)), e.u && b("Patches").M(i2[Q].t, r2, e.u, e.s)) : r2 = M(e, i2, []), g(e), e.u && e.v(e.u, e.s), r2 !== H ? r2 : void 0;
6066
+ }
6067
+ function M(n2, r2, t2) {
6068
+ if (y(r2))
6069
+ return r2;
6070
+ var e = r2[Q];
6071
+ if (!e)
6072
+ return i(r2, function(i2, o3) {
6073
+ return A(n2, e, r2, i2, o3, t2);
6074
+ }, true), r2;
6075
+ if (e.A !== n2)
6076
+ return r2;
6077
+ if (!e.P)
6078
+ return x(n2, e.t, true), e.t;
6079
+ if (!e.I) {
6080
+ e.I = true, e.A._--;
6081
+ var o2 = 4 === e.i || 5 === e.i ? e.o = l(e.k) : e.o, u2 = o2, a2 = false;
6082
+ 3 === e.i && (u2 = new Set(o2), o2.clear(), a2 = true), i(u2, function(r3, i2) {
6083
+ return A(n2, e, o2, r3, i2, t2, a2);
6084
+ }), x(n2, o2, false), t2 && n2.u && b("Patches").N(e, t2, n2.u, n2.s);
6085
+ }
6086
+ return e.o;
6087
+ }
6088
+ function A(e, i2, o2, a2, c2, s2, v2) {
6089
+ if ("production" !== process.env.NODE_ENV && c2 === o2 && n(5), r(c2)) {
6090
+ var p2 = M(e, c2, s2 && i2 && 3 !== i2.i && !u(i2.R, a2) ? s2.concat(a2) : void 0);
6091
+ if (f(o2, a2, p2), !r(p2))
6092
+ return;
6093
+ e.m = false;
6094
+ } else
6095
+ v2 && o2.add(c2);
6096
+ if (t(c2) && !y(c2)) {
6097
+ if (!e.h.D && e._ < 1)
6098
+ return;
6099
+ M(e, c2), i2 && i2.A.l || x(e, c2);
6100
+ }
6101
+ }
6102
+ function x(n2, r2, t2) {
6103
+ void 0 === t2 && (t2 = false), !n2.l && n2.h.D && n2.m && d(r2, t2);
6104
+ }
6105
+ function z(n2, r2) {
6106
+ var t2 = n2[Q];
6107
+ return (t2 ? p(t2) : n2)[r2];
6108
+ }
6109
+ function I(n2, r2) {
6110
+ if (r2 in n2)
6111
+ for (var t2 = Object.getPrototypeOf(n2); t2; ) {
6112
+ var e = Object.getOwnPropertyDescriptor(t2, r2);
6113
+ if (e)
6114
+ return e;
6115
+ t2 = Object.getPrototypeOf(t2);
6116
+ }
6117
+ }
6118
+ function k(n2) {
6119
+ n2.P || (n2.P = true, n2.l && k(n2.l));
6120
+ }
6121
+ function E(n2) {
6122
+ n2.o || (n2.o = l(n2.t));
6123
+ }
6124
+ function N(n2, r2, t2) {
6125
+ var e = s(r2) ? b("MapSet").F(r2, t2) : v(r2) ? b("MapSet").T(r2, t2) : n2.O ? function(n3, r3) {
6126
+ var t3 = Array.isArray(n3), e2 = { i: t3 ? 1 : 0, A: r3 ? r3.A : _(), P: false, I: false, R: {}, l: r3, t: n3, k: null, o: null, j: null, C: false }, i2 = e2, o2 = en;
6127
+ t3 && (i2 = [e2], o2 = on);
6128
+ var u2 = Proxy.revocable(i2, o2), a2 = u2.revoke, f2 = u2.proxy;
6129
+ return e2.k = f2, e2.j = a2, f2;
6130
+ }(r2, t2) : b("ES5").J(r2, t2);
6131
+ return (t2 ? t2.A : _()).p.push(e), e;
6132
+ }
6133
+ function R(e) {
6134
+ return r(e) || n(22, e), function n2(r2) {
6135
+ if (!t(r2))
6136
+ return r2;
6137
+ var e2, u2 = r2[Q], c2 = o(r2);
6138
+ if (u2) {
6139
+ if (!u2.P && (u2.i < 4 || !b("ES5").K(u2)))
6140
+ return u2.t;
6141
+ u2.I = true, e2 = D(r2, c2), u2.I = false;
6142
+ } else
6143
+ e2 = D(r2, c2);
6144
+ return i(e2, function(r3, t2) {
6145
+ u2 && a(u2.t, r3) === t2 || f(e2, r3, n2(t2));
6146
+ }), 3 === c2 ? new Set(e2) : e2;
6147
+ }(e);
6148
+ }
6149
+ function D(n2, r2) {
6150
+ switch (r2) {
6151
+ case 2:
6152
+ return new Map(n2);
6153
+ case 3:
6154
+ return Array.from(n2);
6155
+ }
6156
+ return l(n2);
6157
+ }
6158
+ var G;
6159
+ var U;
6160
+ var W = "undefined" != typeof Symbol && "symbol" == typeof Symbol("x");
6161
+ var X = "undefined" != typeof Map;
6162
+ var q = "undefined" != typeof Set;
6163
+ var B = "undefined" != typeof Proxy && void 0 !== Proxy.revocable && "undefined" != typeof Reflect;
6164
+ var H = W ? Symbol.for("immer-nothing") : ((G = {})["immer-nothing"] = true, G);
6165
+ var L = W ? Symbol.for("immer-draftable") : "__$immer_draftable";
6166
+ var Q = W ? Symbol.for("immer-state") : "__$immer_state";
6167
+ var Y = { 0: "Illegal state", 1: "Immer drafts cannot have computed properties", 2: "This object has been frozen and should not be mutated", 3: function(n2) {
6168
+ return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + n2;
6169
+ }, 4: "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.", 5: "Immer forbids circular references", 6: "The first or second argument to `produce` must be a function", 7: "The third argument to `produce` must be a function or undefined", 8: "First argument to `createDraft` must be a plain object, an array, or an immerable object", 9: "First argument to `finishDraft` must be a draft returned by `createDraft`", 10: "The given draft is already finalized", 11: "Object.defineProperty() cannot be used on an Immer draft", 12: "Object.setPrototypeOf() cannot be used on an Immer draft", 13: "Immer only supports deleting array indices", 14: "Immer only supports setting array indices and the 'length' property", 15: function(n2) {
6170
+ return "Cannot apply patch, path doesn't resolve: " + n2;
6171
+ }, 16: 'Sets cannot have "replace" patches.', 17: function(n2) {
6172
+ return "Unsupported patch operation: " + n2;
6173
+ }, 18: function(n2) {
6174
+ return "The plugin for '" + n2 + "' has not been loaded into Immer. To enable the plugin, import and call `enable" + n2 + "()` when initializing your application.";
6175
+ }, 20: "Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available", 21: function(n2) {
6176
+ return "produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '" + n2 + "'";
6177
+ }, 22: function(n2) {
6178
+ return "'current' expects a draft, got: " + n2;
6179
+ }, 23: function(n2) {
6180
+ return "'original' expects a draft, got: " + n2;
6181
+ }, 24: "Patching reserved attributes like __proto__, prototype and constructor is not allowed" };
6182
+ var Z = "" + Object.prototype.constructor;
6183
+ var nn = "undefined" != typeof Reflect && Reflect.ownKeys ? Reflect.ownKeys : void 0 !== Object.getOwnPropertySymbols ? function(n2) {
6184
+ return Object.getOwnPropertyNames(n2).concat(Object.getOwnPropertySymbols(n2));
6185
+ } : Object.getOwnPropertyNames;
6186
+ var rn = Object.getOwnPropertyDescriptors || function(n2) {
6187
+ var r2 = {};
6188
+ return nn(n2).forEach(function(t2) {
6189
+ r2[t2] = Object.getOwnPropertyDescriptor(n2, t2);
6190
+ }), r2;
6191
+ };
6192
+ var tn = {};
6193
+ var en = { get: function(n2, r2) {
6194
+ if (r2 === Q)
6195
+ return n2;
6196
+ var e = p(n2);
6197
+ if (!u(e, r2))
6198
+ return function(n3, r3, t2) {
6199
+ var e2, i3 = I(r3, t2);
6200
+ return i3 ? "value" in i3 ? i3.value : null === (e2 = i3.get) || void 0 === e2 ? void 0 : e2.call(n3.k) : void 0;
6201
+ }(n2, e, r2);
6202
+ var i2 = e[r2];
6203
+ return n2.I || !t(i2) ? i2 : i2 === z(n2.t, r2) ? (E(n2), n2.o[r2] = N(n2.A.h, i2, n2)) : i2;
6204
+ }, has: function(n2, r2) {
6205
+ return r2 in p(n2);
6206
+ }, ownKeys: function(n2) {
6207
+ return Reflect.ownKeys(p(n2));
6208
+ }, set: function(n2, r2, t2) {
6209
+ var e = I(p(n2), r2);
6210
+ if (null == e ? void 0 : e.set)
6211
+ return e.set.call(n2.k, t2), true;
6212
+ if (!n2.P) {
6213
+ var i2 = z(p(n2), r2), o2 = null == i2 ? void 0 : i2[Q];
6214
+ if (o2 && o2.t === t2)
6215
+ return n2.o[r2] = t2, n2.R[r2] = false, true;
6216
+ if (c(t2, i2) && (void 0 !== t2 || u(n2.t, r2)))
6217
+ return true;
6218
+ E(n2), k(n2);
6219
+ }
6220
+ return n2.o[r2] === t2 && (void 0 !== t2 || r2 in n2.o) || Number.isNaN(t2) && Number.isNaN(n2.o[r2]) || (n2.o[r2] = t2, n2.R[r2] = true), true;
6221
+ }, deleteProperty: function(n2, r2) {
6222
+ return void 0 !== z(n2.t, r2) || r2 in n2.t ? (n2.R[r2] = false, E(n2), k(n2)) : delete n2.R[r2], n2.o && delete n2.o[r2], true;
6223
+ }, getOwnPropertyDescriptor: function(n2, r2) {
6224
+ var t2 = p(n2), e = Reflect.getOwnPropertyDescriptor(t2, r2);
6225
+ return e ? { writable: true, configurable: 1 !== n2.i || "length" !== r2, enumerable: e.enumerable, value: t2[r2] } : e;
6226
+ }, defineProperty: function() {
6227
+ n(11);
6228
+ }, getPrototypeOf: function(n2) {
6229
+ return Object.getPrototypeOf(n2.t);
6230
+ }, setPrototypeOf: function() {
6231
+ n(12);
6232
+ } };
6233
+ var on = {};
6234
+ i(en, function(n2, r2) {
6235
+ on[n2] = function() {
6236
+ return arguments[0] = arguments[0][0], r2.apply(this, arguments);
6237
+ };
6238
+ }), on.deleteProperty = function(r2, t2) {
6239
+ return "production" !== process.env.NODE_ENV && isNaN(parseInt(t2)) && n(13), on.set.call(this, r2, t2, void 0);
6240
+ }, on.set = function(r2, t2, e) {
6241
+ return "production" !== process.env.NODE_ENV && "length" !== t2 && isNaN(parseInt(t2)) && n(14), en.set.call(this, r2[0], t2, e, r2[0]);
6242
+ };
6243
+ var un = function() {
6244
+ function e(r2) {
6245
+ var e2 = this;
6246
+ this.O = B, this.D = true, this.produce = function(r3, i3, o2) {
6247
+ if ("function" == typeof r3 && "function" != typeof i3) {
6248
+ var u2 = i3;
6249
+ i3 = r3;
6250
+ var a2 = e2;
6251
+ return function(n2) {
6252
+ var r4 = this;
6253
+ void 0 === n2 && (n2 = u2);
6254
+ for (var t2 = arguments.length, e3 = Array(t2 > 1 ? t2 - 1 : 0), o3 = 1; o3 < t2; o3++)
6255
+ e3[o3 - 1] = arguments[o3];
6256
+ return a2.produce(n2, function(n3) {
6257
+ var t3;
6258
+ return (t3 = i3).call.apply(t3, [r4, n3].concat(e3));
6259
+ });
6260
+ };
6261
+ }
6262
+ var f2;
6263
+ if ("function" != typeof i3 && n(6), void 0 !== o2 && "function" != typeof o2 && n(7), t(r3)) {
6264
+ var c2 = w(e2), s2 = N(e2, r3, void 0), v2 = true;
6265
+ try {
6266
+ f2 = i3(s2), v2 = false;
6267
+ } finally {
6268
+ v2 ? g(c2) : O(c2);
6269
+ }
6270
+ return "undefined" != typeof Promise && f2 instanceof Promise ? f2.then(function(n2) {
6271
+ return j(c2, o2), P(n2, c2);
6272
+ }, function(n2) {
6273
+ throw g(c2), n2;
6274
+ }) : (j(c2, o2), P(f2, c2));
6275
+ }
6276
+ if (!r3 || "object" != typeof r3) {
6277
+ if (void 0 === (f2 = i3(r3)) && (f2 = r3), f2 === H && (f2 = void 0), e2.D && d(f2, true), o2) {
6278
+ var p2 = [], l2 = [];
6279
+ b("Patches").M(r3, f2, p2, l2), o2(p2, l2);
6280
+ }
6281
+ return f2;
6282
+ }
6283
+ n(21, r3);
6284
+ }, this.produceWithPatches = function(n2, r3) {
6285
+ if ("function" == typeof n2)
6286
+ return function(r4) {
6287
+ for (var t3 = arguments.length, i4 = Array(t3 > 1 ? t3 - 1 : 0), o3 = 1; o3 < t3; o3++)
6288
+ i4[o3 - 1] = arguments[o3];
6289
+ return e2.produceWithPatches(r4, function(r5) {
6290
+ return n2.apply(void 0, [r5].concat(i4));
6291
+ });
6292
+ };
6293
+ var t2, i3, o2 = e2.produce(n2, r3, function(n3, r4) {
6294
+ t2 = n3, i3 = r4;
6295
+ });
6296
+ return "undefined" != typeof Promise && o2 instanceof Promise ? o2.then(function(n3) {
6297
+ return [n3, t2, i3];
6298
+ }) : [o2, t2, i3];
6299
+ }, "boolean" == typeof (null == r2 ? void 0 : r2.useProxies) && this.setUseProxies(r2.useProxies), "boolean" == typeof (null == r2 ? void 0 : r2.autoFreeze) && this.setAutoFreeze(r2.autoFreeze);
6300
+ }
6301
+ var i2 = e.prototype;
6302
+ return i2.createDraft = function(e2) {
6303
+ t(e2) || n(8), r(e2) && (e2 = R(e2));
6304
+ var i3 = w(this), o2 = N(this, e2, void 0);
6305
+ return o2[Q].C = true, O(i3), o2;
6306
+ }, i2.finishDraft = function(r2, t2) {
6307
+ var e2 = r2 && r2[Q];
6308
+ "production" !== process.env.NODE_ENV && (e2 && e2.C || n(9), e2.I && n(10));
6309
+ var i3 = e2.A;
6310
+ return j(i3, t2), P(void 0, i3);
6311
+ }, i2.setAutoFreeze = function(n2) {
6312
+ this.D = n2;
6313
+ }, i2.setUseProxies = function(r2) {
6314
+ r2 && !B && n(20), this.O = r2;
6315
+ }, i2.applyPatches = function(n2, t2) {
6316
+ var e2;
6317
+ for (e2 = t2.length - 1; e2 >= 0; e2--) {
6318
+ var i3 = t2[e2];
6319
+ if (0 === i3.path.length && "replace" === i3.op) {
6320
+ n2 = i3.value;
6321
+ break;
6322
+ }
6323
+ }
6324
+ e2 > -1 && (t2 = t2.slice(e2 + 1));
6325
+ var o2 = b("Patches").$;
6326
+ return r(n2) ? o2(n2, t2) : this.produce(n2, function(n3) {
6327
+ return o2(n3, t2);
6328
+ });
6329
+ }, e;
6330
+ }();
6331
+ var an = new un();
6332
+ var fn3 = an.produce;
6333
+ an.produceWithPatches.bind(an);
6334
+ an.setAutoFreeze.bind(an);
6335
+ an.setUseProxies.bind(an);
6336
+ an.applyPatches.bind(an);
6337
+ an.createDraft.bind(an);
6338
+ an.finishDraft.bind(an);
6339
+ var immer_esm_default = fn3;
6340
+
6341
+ // store/recordsActions.ts
5742
6342
  var recordsActions = recordsSlice.actions;
5743
6343
  var createEntity = entityActionFactory({
5744
6344
  block: createHandlerFactory("block"),
@@ -5772,13 +6372,15 @@ var deleteEntity = entityActionFactory({
5772
6372
  section: deleteHandlerFactory("section"),
5773
6373
  variant: deleteHandlerFactory("variant")
5774
6374
  });
6375
+ var cloneEntity = entityActionFactory({
6376
+ block: cloneHandlerFactory("block"),
6377
+ section: cloneHandlerFactory("section")
6378
+ });
5775
6379
  function entityActionFactory(entitySet) {
5776
6380
  return (type, payload) => {
5777
6381
  const action = entitySet[type];
5778
6382
  if (!action) {
5779
- throw new Error(
5780
- `Attempting to dispatch action for invalid entity type '${type}'`
5781
- );
6383
+ throw new Error(`Attempting to dispatch action for invalid entity type '${type}'`);
5782
6384
  }
5783
6385
  return action(payload);
5784
6386
  };
@@ -5802,29 +6404,58 @@ function rpcFailure(entity, key, code, message) {
5802
6404
  title: "Error"
5803
6405
  });
5804
6406
  }
5805
- dispatch(recordsActions.setRequest({
5806
- key,
5807
- type: entity,
5808
- status: "FAILURE" /* FAILURE */,
5809
- error: { code, message }
5810
- }));
6407
+ dispatch(
6408
+ recordsActions.setRequest({
6409
+ key,
6410
+ type: entity,
6411
+ status: "FAILURE" /* FAILURE */,
6412
+ error: { code, message }
6413
+ })
6414
+ );
5811
6415
  };
5812
6416
  }
5813
6417
  function createHandlerFactory(entity) {
5814
6418
  return (payload) => {
5815
6419
  const key = keyMakerCreate(entity, payload);
5816
- return (dispatch, _, api) => {
6420
+ return (dispatch, _2, api) => {
5817
6421
  dispatch(rpcAnnounce(entity, key));
5818
6422
  const rpc = pickMethod(api, "create", entity);
5819
6423
  return rpc(payload).then((result) => {
5820
6424
  if (result.ok === true) {
5821
- dispatch(recordsActions.setCreateRequest({
5822
- key,
5823
- operation: "create",
5824
- status: "SUCCESS" /* SUCCESS */,
5825
- type: entity,
5826
- data: result.data
5827
- }));
6425
+ dispatch(
6426
+ recordsActions.setCreateRequest({
6427
+ key,
6428
+ operation: "create",
6429
+ status: "SUCCESS" /* SUCCESS */,
6430
+ type: entity,
6431
+ data: result.data
6432
+ })
6433
+ );
6434
+ } else {
6435
+ dispatch(rpcFailure(entity, key, result.status, result.error));
6436
+ }
6437
+ return result;
6438
+ });
6439
+ };
6440
+ };
6441
+ }
6442
+ function createBulkEntities(entity) {
6443
+ return (payload) => {
6444
+ const key = keyMakerCreate(entity, payload[0]);
6445
+ return (dispatch, _2, api) => {
6446
+ dispatch(rpcAnnounce(entity, key));
6447
+ const rpc = pickMethod(api, "createBulk", entity);
6448
+ return rpc(payload).then((result) => {
6449
+ if (result.ok === true) {
6450
+ dispatch(
6451
+ recordsActions.setCreateRequest({
6452
+ key,
6453
+ operation: "createBulk",
6454
+ status: "SUCCESS" /* SUCCESS */,
6455
+ type: entity,
6456
+ data: result.data
6457
+ })
6458
+ );
5828
6459
  } else {
5829
6460
  dispatch(rpcFailure(entity, key, result.status, result.error));
5830
6461
  }
@@ -5833,24 +6464,233 @@ function createHandlerFactory(entity) {
5833
6464
  };
5834
6465
  };
5835
6466
  }
6467
+ function replaceAll(search, replacement, target) {
6468
+ return target.replace(new RegExp(search, "g"), replacement);
6469
+ }
6470
+ function isBlock(entity) {
6471
+ return entity.section_id !== void 0;
6472
+ }
6473
+ function isSection(entity) {
6474
+ return entity.report_id !== void 0;
6475
+ }
6476
+ function cloneHandlerFactory(entity) {
6477
+ return (payload) => {
6478
+ const { create } = payload;
6479
+ return (dispatch, _2, api) => {
6480
+ const createPromise = createHandlerFactory(entity)(create)(dispatch, _2, api);
6481
+ return createPromise.then(async (result) => {
6482
+ if (result.ok) {
6483
+ const { data } = result;
6484
+ const { id } = data;
6485
+ const { update } = payload;
6486
+ const key = keyMakerClone(entity, { id });
6487
+ dispatch(rpcAnnounce(entity, `${key}`));
6488
+ if (entity === "block" && isBlock(create)) {
6489
+ let updateData = immer_esm_default(update, (draft) => {
6490
+ draft.id = id;
6491
+ });
6492
+ const { contentByLocale } = updateData;
6493
+ if (contentByLocale) {
6494
+ updateData = immer_esm_default(updateData, (draft) => {
6495
+ draft.id = id;
6496
+ draft.contentByLocale = Object.keys(contentByLocale).reduce(
6497
+ (prev, curr) => {
6498
+ const obj = contentByLocale ? contentByLocale[curr] : {};
6499
+ prev[curr] = { ...obj, id };
6500
+ return prev;
6501
+ },
6502
+ {}
6503
+ );
6504
+ });
6505
+ }
6506
+ const inputs = updateData.inputs;
6507
+ const updateInputs = inputs?.map((b2) => ({
6508
+ type: b2.type,
6509
+ id: b2.id,
6510
+ inputAction: {
6511
+ operation: "create",
6512
+ input: {
6513
+ input_id: b2.id,
6514
+ block_id: updateData.id
6515
+ }
6516
+ }
6517
+ }));
6518
+ if (updateInputs && updateInputs.length > 0) {
6519
+ updateBulkEntities(entity)([updateData, ...updateInputs])(
6520
+ dispatch,
6521
+ _2,
6522
+ api
6523
+ ).then(
6524
+ () => readHandlerFactory("section")({
6525
+ id: updateData.section_id,
6526
+ include: true
6527
+ })(dispatch, _2, api).then((result2) => {
6528
+ if (result2.ok) {
6529
+ dispatch(
6530
+ recordsActions.setRequest({
6531
+ key,
6532
+ type: entity,
6533
+ status: "SUCCESS" /* SUCCESS */,
6534
+ data: result2.data
6535
+ })
6536
+ );
6537
+ }
6538
+ return result2;
6539
+ })
6540
+ );
6541
+ }
6542
+ return updateHandlerFactory(entity)(updateData)(dispatch, _2, api).then(
6543
+ (result2) => {
6544
+ if (result2.ok) {
6545
+ dispatch(
6546
+ recordsActions.setRequest({
6547
+ key,
6548
+ type: entity,
6549
+ status: "SUCCESS" /* SUCCESS */,
6550
+ data: result2.data
6551
+ })
6552
+ );
6553
+ }
6554
+ return result2;
6555
+ }
6556
+ );
6557
+ }
6558
+ if (entity === "section" && isSection(create)) {
6559
+ const { id: section_id } = data;
6560
+ const updateSectionData = immer_esm_default(update, (draft) => {
6561
+ draft.id = section_id;
6562
+ });
6563
+ const { blocks } = updateSectionData;
6564
+ const mapblocks = blocks?.map((b2) => ({
6565
+ type: b2.type,
6566
+ blockcol: b2.blockcol,
6567
+ blockrow: b2.blockrow,
6568
+ section_id,
6569
+ locales: Object.keys(b2.contentByLocale).map((locale) => locale)
6570
+ }));
6571
+ if (mapblocks && blocks) {
6572
+ await createBulkEntities("block")(mapblocks)(dispatch, _2, api).then(
6573
+ (newBlocksBulk) => {
6574
+ if (newBlocksBulk.ok) {
6575
+ const newBlocksBulkData = newBlocksBulk.data;
6576
+ const nestedInputUpdates = [];
6577
+ const blocksUpdateData = newBlocksBulkData.map((b2, i2) => {
6578
+ const newBlock = b2;
6579
+ const copyBlock = { ...newBlock };
6580
+ const parentBlockId = copyBlock.id;
6581
+ const block = blocks[i2];
6582
+ if (block.contentByLocale) {
6583
+ copyBlock.contentByLocale = Object.keys(
6584
+ block.contentByLocale
6585
+ ).reduce((prev, curr) => {
6586
+ const o2 = block.contentByLocale[curr];
6587
+ prev[curr] = { ...o2, content: { ...o2.content }, id: copyBlock.id };
6588
+ return prev;
6589
+ }, {});
6590
+ }
6591
+ const { settings } = block;
6592
+ const { contentByLocale, id: id2 } = copyBlock;
6593
+ copyBlock.settings = settings;
6594
+ const updateBlock = {
6595
+ id: id2,
6596
+ contentByLocale,
6597
+ settings
6598
+ };
6599
+ const blockinputsids = block.inputs.map((b3) => b3.id);
6600
+ const blockinputsidxs = blockinputsids.reduce((prev, curr) => {
6601
+ const index = blocks.findIndex((el) => el.id === curr);
6602
+ return [...prev, index];
6603
+ }, []);
6604
+ const nestedInputs = blockinputsidxs.map((index) => {
6605
+ return {
6606
+ ...newBlocksBulkData[index],
6607
+ originalBlock: blocks[index]
6608
+ };
6609
+ });
6610
+ nestedInputs.forEach((input) => {
6611
+ const { id: id3, type, originalBlock } = input;
6612
+ if (["selector", "visualization"].includes(type)) {
6613
+ if (updateBlock.contentByLocale?.logic?.content?.api) {
6614
+ const api2 = updateBlock.contentByLocale?.logic.content.api;
6615
+ updateBlock.contentByLocale.logic.content.api = replaceAll(
6616
+ `(selector${originalBlock.id}id)`,
6617
+ `selector${id3}id`,
6618
+ api2
6619
+ );
6620
+ }
6621
+ if (updateBlock.contentByLocale?.logic?.content?.logic) {
6622
+ const logic = updateBlock.contentByLocale.logic.content.logic;
6623
+ updateBlock.contentByLocale.logic.content.logic = replaceAll(
6624
+ `(selector${originalBlock.id}id)`,
6625
+ `selector${id3}id`,
6626
+ logic
6627
+ );
6628
+ }
6629
+ }
6630
+ nestedInputUpdates.push({
6631
+ id: id3,
6632
+ inputAction: {
6633
+ operation: "create",
6634
+ input: {
6635
+ input_id: id3,
6636
+ block_id: parentBlockId
6637
+ }
6638
+ }
6639
+ });
6640
+ });
6641
+ return updateBlock;
6642
+ });
6643
+ return updateBulkEntities("block")([
6644
+ ...blocksUpdateData,
6645
+ ...nestedInputUpdates
6646
+ ])(dispatch, _2, api);
6647
+ }
6648
+ }
6649
+ );
6650
+ }
6651
+ return updateHandlerFactory(entity)(updateSectionData)(dispatch, _2, api).then(
6652
+ (result2) => {
6653
+ if (result2.ok) {
6654
+ dispatch(
6655
+ recordsActions.setRequest({
6656
+ key,
6657
+ type: entity,
6658
+ status: "SUCCESS" /* SUCCESS */,
6659
+ data: result2.data
6660
+ })
6661
+ );
6662
+ }
6663
+ return result2;
6664
+ }
6665
+ );
6666
+ }
6667
+ return updateHandlerFactory(entity)({ ...update, id: data.id })(dispatch, _2, api);
6668
+ }
6669
+ });
6670
+ };
6671
+ };
6672
+ }
5836
6673
  function readHandlerFactory(entity) {
5837
6674
  return (payload) => {
5838
6675
  const key = keyMakerRead(entity, payload);
5839
- return (dispatch, _, api) => {
6676
+ return (dispatch, _2, api) => {
5840
6677
  dispatch(rpcAnnounce(entity, key));
5841
6678
  const rpc = pickMethod(api, "read", entity);
5842
6679
  return rpc(payload).then((result) => {
5843
6680
  if (result.ok === true) {
5844
- dispatch(recordsActions.setReadRequest({
5845
- key,
5846
- operation: "read",
5847
- status: "SUCCESS" /* SUCCESS */,
5848
- type: entity,
5849
- data: result.data
5850
- }));
6681
+ dispatch(
6682
+ recordsActions.setReadRequest({
6683
+ key,
6684
+ operation: "read",
6685
+ status: "SUCCESS" /* SUCCESS */,
6686
+ type: entity,
6687
+ data: result.data
6688
+ })
6689
+ );
5851
6690
  } else {
5852
6691
  dispatch(rpcFailure(entity, key, result.status, result.error));
5853
6692
  }
6693
+ return result;
5854
6694
  });
5855
6695
  };
5856
6696
  };
@@ -5858,21 +6698,49 @@ function readHandlerFactory(entity) {
5858
6698
  function updateHandlerFactory(entity) {
5859
6699
  return (payload) => {
5860
6700
  const key = keyMakerUpdate(entity, payload);
5861
- return (dispatch, _, api) => {
6701
+ return (dispatch, _2, api) => {
5862
6702
  dispatch(rpcAnnounce(entity, key));
5863
6703
  const rpc = pickMethod(api, "update", entity);
5864
6704
  return rpc(payload).then((result) => {
5865
6705
  if (result.ok === true) {
5866
- dispatch(recordsActions.setUpdateRequest({
5867
- key,
5868
- operation: "update",
5869
- status: "SUCCESS" /* SUCCESS */,
5870
- type: entity,
5871
- data: result.data
5872
- }));
6706
+ dispatch(
6707
+ recordsActions.setUpdateRequest({
6708
+ key,
6709
+ operation: "update",
6710
+ status: "SUCCESS" /* SUCCESS */,
6711
+ type: entity,
6712
+ data: result.data
6713
+ })
6714
+ );
6715
+ } else {
6716
+ dispatch(rpcFailure(entity, key, result.status, result.error));
6717
+ }
6718
+ return result;
6719
+ });
6720
+ };
6721
+ };
6722
+ }
6723
+ function updateBulkEntities(entity) {
6724
+ return (payload) => {
6725
+ const key = keyMakerUpdate(entity, payload[0]);
6726
+ return (dispatch, _2, api) => {
6727
+ dispatch(rpcAnnounce(entity, key));
6728
+ const rpc = pickMethod(api, "updateBulk", entity);
6729
+ return rpc(payload).then((result) => {
6730
+ if (result.ok === true) {
6731
+ dispatch(
6732
+ recordsActions.setUpdateRequest({
6733
+ key,
6734
+ operation: "updateBulk",
6735
+ status: "SUCCESS" /* SUCCESS */,
6736
+ type: entity,
6737
+ data: result.data
6738
+ })
6739
+ );
5873
6740
  } else {
5874
6741
  dispatch(rpcFailure(entity, key, result.status, result.error));
5875
6742
  }
6743
+ return result;
5876
6744
  });
5877
6745
  };
5878
6746
  };
@@ -5880,18 +6748,20 @@ function updateHandlerFactory(entity) {
5880
6748
  function deleteHandlerFactory(entity) {
5881
6749
  return (payload) => {
5882
6750
  const key = keyMakerDelete(entity, payload);
5883
- return (dispatch, _, api) => {
6751
+ return (dispatch, _2, api) => {
5884
6752
  dispatch(rpcAnnounce(entity, key));
5885
6753
  const rpc = pickMethod(api, "delete", entity);
5886
6754
  return rpc(payload).then((result) => {
5887
6755
  if (result.ok === true) {
5888
- dispatch(recordsActions.setDeleteRequest({
5889
- key,
5890
- operation: "delete",
5891
- status: "SUCCESS" /* SUCCESS */,
5892
- type: entity,
5893
- data: result.data
5894
- }));
6756
+ dispatch(
6757
+ recordsActions.setDeleteRequest({
6758
+ key,
6759
+ operation: "delete",
6760
+ status: "SUCCESS" /* SUCCESS */,
6761
+ type: entity,
6762
+ data: result.data
6763
+ })
6764
+ );
5895
6765
  } else {
5896
6766
  dispatch(rpcFailure(entity, key, result.status, result.error));
5897
6767
  }
@@ -5901,8 +6771,8 @@ function deleteHandlerFactory(entity) {
5901
6771
  }
5902
6772
  function keyMakerCreate(entity, params) {
5903
6773
  if (entity === "variant") {
5904
- const p = params;
5905
- return `create(variant, [${p.dimension_id}, ${p.name}])`;
6774
+ const p2 = params;
6775
+ return `create(variant, [${p2.dimension_id}, ${p2.name}])`;
5906
6776
  }
5907
6777
  return `create(${entity}, [${Object.keys(params)}])`;
5908
6778
  }
@@ -5917,11 +6787,22 @@ function keyMakerUpdate(entity, params) {
5917
6787
  function keyMakerDelete(entity, params) {
5918
6788
  return `delete(${entity}, ${params})`;
5919
6789
  }
6790
+ function keyMakerClone(entity, params) {
6791
+ const id = params.id == null ? null : `'${params.id}'`;
6792
+ return `clone(${entity}, ${id})`;
6793
+ }
5920
6794
 
5921
6795
  // store/actions.ts
5922
- var { setStatus, setPreviews, setSectionState, resetSectionState, setCurrentLocale } = statusActions;
6796
+ var {
6797
+ setStatus,
6798
+ setPreviews,
6799
+ setSectionState,
6800
+ resetSectionState,
6801
+ setCurrentLocale,
6802
+ setPreferredLocale
6803
+ } = statusActions;
5923
6804
  function variantValidateSlug(dimension, slug) {
5924
- return async (_, __, api) => {
6805
+ return async (_2, __, api) => {
5925
6806
  const result = await api.validateVariantSlug({ dimension, slug });
5926
6807
  if ("error" in result) {
5927
6808
  throw new Error(result.error);
@@ -5930,7 +6811,7 @@ function variantValidateSlug(dimension, slug) {
5930
6811
  };
5931
6812
  }
5932
6813
  function reportSearch(filters) {
5933
- return async (_, __, api) => {
6814
+ return async (_2, __, api) => {
5934
6815
  const result = await api.searchReport(filters);
5935
6816
  if ("error" in result) {
5936
6817
  throw new Error(result.error);
@@ -5939,7 +6820,7 @@ function reportSearch(filters) {
5939
6820
  };
5940
6821
  }
5941
6822
  function searchRegenerate() {
5942
- return async (_, __, api) => {
6823
+ return async (_2, __, api) => {
5943
6824
  const result = await api.regenerateSearch(void 0);
5944
6825
  if ("error" in result) {
5945
6826
  throw new Error(result.error);
@@ -5948,7 +6829,7 @@ function searchRegenerate() {
5948
6829
  };
5949
6830
  }
5950
6831
  function readMember(params) {
5951
- return async (_, __, api) => {
6832
+ return async (_2, __, api) => {
5952
6833
  const result = await api.readMember(params);
5953
6834
  if ("error" in result) {
5954
6835
  throw new Error(result.error);
@@ -5957,7 +6838,7 @@ function readMember(params) {
5957
6838
  };
5958
6839
  }
5959
6840
  function searchMember(params) {
5960
- return async (_, __, api) => {
6841
+ return async (_2, __, api) => {
5961
6842
  const result = await api.searchMember(params);
5962
6843
  if (result.ok === true)
5963
6844
  return result.data;
@@ -5988,12 +6869,7 @@ function recalculateVariables(resource, params) {
5988
6869
  const blocks = state.records.entities.block;
5989
6870
  const formatterFunctions = resource.formatterFunctions[currentLocale];
5990
6871
  const { parsedParams, statusPayload } = parseVariableUpdateParams(state.status, params);
5991
- const {
5992
- sid,
5993
- bid,
5994
- previews,
5995
- query
5996
- } = parsedParams;
6872
+ const { sid, bid, previews, query } = parsedParams;
5997
6873
  if (Object.keys(statusPayload).length)
5998
6874
  dispatch(statusActions.setStatus(statusPayload));
5999
6875
  const attributes = {
@@ -6026,7 +6902,7 @@ function recalculateVariables(resource, params) {
6026
6902
  };
6027
6903
  }
6028
6904
  function readMetadata(filters) {
6029
- return async (_, __, api) => {
6905
+ return async (_2, __, api) => {
6030
6906
  const result = await api.readMetadata(filters);
6031
6907
  if ("error" in result) {
6032
6908
  throw new Error(result.error);
@@ -6035,7 +6911,7 @@ function readMetadata(filters) {
6035
6911
  };
6036
6912
  }
6037
6913
  function urlProxy2(url) {
6038
- return async (_, __, api) => {
6914
+ return async (_2, __, api) => {
6039
6915
  const result = await api.urlProxy({ url });
6040
6916
  if ("error" in result) {
6041
6917
  throw new Error(result.error);
@@ -6044,7 +6920,7 @@ function urlProxy2(url) {
6044
6920
  };
6045
6921
  }
6046
6922
  function searchRole() {
6047
- return async (_, __, api) => {
6923
+ return async (_2, __, api) => {
6048
6924
  const result = await api.searchRole("");
6049
6925
  if ("error" in result) {
6050
6926
  throw new Error(result.error);
@@ -6053,7 +6929,7 @@ function searchRole() {
6053
6929
  };
6054
6930
  }
6055
6931
  function searchUser(filters) {
6056
- return async (_, __, api) => {
6932
+ return async (_2, __, api) => {
6057
6933
  const result = await api.searchUser(filters);
6058
6934
  if ("error" in result) {
6059
6935
  throw new Error(result.error);
@@ -6062,7 +6938,7 @@ function searchUser(filters) {
6062
6938
  };
6063
6939
  }
6064
6940
  function readUser(userId) {
6065
- return async (_, __, api) => {
6941
+ return async (_2, __, api) => {
6066
6942
  const result = await api.readUser({ user_id: userId });
6067
6943
  if ("error" in result) {
6068
6944
  throw new Error(result.error);
@@ -6071,7 +6947,7 @@ function readUser(userId) {
6071
6947
  };
6072
6948
  }
6073
6949
  function updateUser({ user }) {
6074
- return async (_, __, api) => {
6950
+ return async (_2, __, api) => {
6075
6951
  const result = await api.updateUser(user);
6076
6952
  if ("error" in result) {
6077
6953
  throw new Error(result.error);
@@ -6079,9 +6955,9 @@ function updateUser({ user }) {
6079
6955
  return result.data;
6080
6956
  };
6081
6957
  }
6082
- function addNewReportToCurrentUser(params) {
6083
- return async (_, __, api) => {
6084
- const result = await api.addNewReportToCurrentUser(params);
6958
+ function updateMyData(params) {
6959
+ return async (_2, __, api) => {
6960
+ const result = await api.updateMyData(params);
6085
6961
  if ("error" in result) {
6086
6962
  throw new Error(result.error);
6087
6963
  }
@@ -6101,7 +6977,7 @@ function addBlockToState(newBlocks) {
6101
6977
  };
6102
6978
  }
6103
6979
  function readPrivateBlocks(params) {
6104
- return async (_, __, api) => {
6980
+ return async (_2, __, api) => {
6105
6981
  const result = await api.readPrivateBlocks({ ...params, roles: [] });
6106
6982
  if ("error" in result) {
6107
6983
  throw new Error(result.error);
@@ -6110,7 +6986,7 @@ function readPrivateBlocks(params) {
6110
6986
  };
6111
6987
  }
6112
6988
  function revalidateUrl(params) {
6113
- return async (_, __, api) => {
6989
+ return async (_2, __, api) => {
6114
6990
  const result = await api.revalidateUrl({ target: params.target });
6115
6991
  if ("error" in result) {
6116
6992
  throw new Error(result.error);
@@ -6119,10 +6995,11 @@ function revalidateUrl(params) {
6119
6995
  };
6120
6996
  }
6121
6997
  function revalidateReport(params) {
6122
- return async (_, __, api) => {
6123
- const result = await api.revalidateReport(
6124
- { reportId: params.reportId, profilePrefix: params.profilePrefix }
6125
- );
6998
+ return async (_2, __, api) => {
6999
+ const result = await api.revalidateReport({
7000
+ reportId: params.reportId,
7001
+ profilePrefix: params.profilePrefix
7002
+ });
6126
7003
  if ("error" in result) {
6127
7004
  throw new Error(result.error);
6128
7005
  }
@@ -6147,6 +7024,16 @@ var storeFactory = (_context) => configureStore({
6147
7024
  var storeWrapper = createWrapper(storeFactory);
6148
7025
 
6149
7026
  // views/BespokeManagerSSR.tsx
7027
+ function getInstalledPackageVersion(packageName) {
7028
+ const mainPath = process.cwd();
7029
+ const packageLockPath = path.resolve(
7030
+ mainPath.endsWith("/example") ? mainPath.replace("/example", "") : mainPath,
7031
+ "package-lock.json"
7032
+ );
7033
+ const packageLock = JSON.parse(fs.readFileSync(packageLockPath, "utf-8"));
7034
+ const version = packageLock.dependencies && packageLock.dependencies[packageName] && packageLock.dependencies[packageName].version !== "file:packages/reports" ? packageLock.dependencies[packageName].version : "0.dev";
7035
+ return version || "Version not found";
7036
+ }
6150
7037
  function BespokeManagerServerSideProps(options) {
6151
7038
  const noop = () => Promise.resolve({});
6152
7039
  const {
@@ -6159,6 +7046,7 @@ function BespokeManagerServerSideProps(options) {
6159
7046
  const { dispatch } = store;
6160
7047
  return async (ctx) => {
6161
7048
  await dispatch(useDatabaseApi);
7049
+ const bespokeVersion = await getInstalledPackageVersion("@datawheel/bespoke");
6162
7050
  const preResult = await preResolve(store, ctx);
6163
7051
  if ("redirect" in preResult)
6164
7052
  return { props: preResult };
@@ -6175,7 +7063,8 @@ function BespokeManagerServerSideProps(options) {
6175
7063
  return {
6176
7064
  props: {
6177
7065
  ...preResult,
6178
- ...postResult
7066
+ ...postResult,
7067
+ bespokeVersion
6179
7068
  }
6180
7069
  };
6181
7070
  };
@@ -6191,7 +7080,7 @@ function parseReportId(value) {
6191
7080
  var { locales: locales9 } = getLocales_default();
6192
7081
  var initialContext = {
6193
7082
  pathSegment: "path",
6194
- formatterFunctions: locales9.reduce((acc, d) => ({ ...acc, [d]: {} }), {}),
7083
+ formatterFunctions: locales9.reduce((acc, d2) => ({ ...acc, [d2]: {} }), {}),
6195
7084
  profilePrefix: "path",
6196
7085
  siteProps: {}
6197
7086
  };
@@ -6343,11 +7232,11 @@ function BespokeRendererStaticProps(options) {
6343
7232
  }
6344
7233
  function getSlugSegments(slugs = []) {
6345
7234
  const slugArray = [].concat(slugs);
6346
- let i = 0;
7235
+ let i2 = 0;
6347
7236
  return {
6348
7237
  next() {
6349
- const value = { variantSlug: slugArray[i++], memberSlug: slugArray[i++] };
6350
- return { value, done: i > slugArray.length };
7238
+ const value = { variantSlug: slugArray[i2++], memberSlug: slugArray[i2++] };
7239
+ return { value, done: i2 > slugArray.length };
6351
7240
  },
6352
7241
  [Symbol.iterator]() {
6353
7242
  return this;
@@ -6355,4 +7244,4 @@ function getSlugSegments(slugs = []) {
6355
7244
  };
6356
7245
  }
6357
7246
 
6358
- export { getSession_default as BespokeGetSession, handleAuth_default as BespokeHandleAuth, BespokeManagerServerSideProps, BespokeRendererStaticPaths, BespokeRendererStaticProps, searchUsersByMetadata_default as BespokeSearchUsersByMetadata, updateCurrentUserMetadata_default as BespokeUpdateCurrentUserMetadata, withApiRoleAuthRequired_default as BespokeWithApiRoleAuthRequired, crosswalk_default as ReportCrosswalkHandler, apiFactory as dbApiFactory, endpointKey, endpointNextJsHandlerFactory, getDB, useDatabaseApi };
7247
+ export { getSession_default as BespokeGetSession, handleAuth_default as BespokeHandleAuth, BespokeManagerServerSideProps, BespokeRendererStaticPaths, BespokeRendererStaticProps, searchUsersByMetadata_default as BespokeSearchUsersByMetadata, updateCurrentUserAppMetadata_default as BespokeUpdateCurrentUserAppMetadata, updateCurrentUserMetadata_default as BespokeUpdateCurrentUserMetadata, withApiRoleAuthRequired_default as BespokeWithApiRoleAuthRequired, crosswalk_default as ReportCrosswalkHandler, apiFactory as dbApiFactory, endpointKey, endpointNextJsHandlerFactory, getDB, useDatabaseApi };