@datawheel/bespoke 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,58 +1,60 @@
1
- import * as pg from "pg";
2
- import { DataTypes, Model, Sequelize, Error as Error$1, fn, col, Op, literal } from "sequelize";
3
- import yn from "yn";
4
- import * as d3Array from "d3-array";
5
- import * as d3Collection from "d3-collection";
6
- import * as d3Format from "d3-format";
7
- import * as d3TimeFormat from "d3-time-format";
8
- import { formatAbbreviate } from "d3plus-format";
9
- import { date as date$1 } from "d3plus-axis";
10
- import { assign, closest, merge } from "d3plus-common";
11
- import { strip, titleCase } from "d3plus-text";
12
- import axios from "axios";
13
- import slugifyFn from "slugify";
14
- import lunr from "lunr";
15
- import Base58 from "base58";
16
- import FlickrSDK from "flickr-sdk";
17
- import sharp from "sharp";
18
- import { createApi } from "unsplash-js";
19
- import fs from "fs";
20
- import NextCors from "nextjs-cors";
21
- import formidable from "formidable";
22
- var getLogging = (env = process.env) => yn(env.REPORTS_LOGGING), __defProp$k = Object.defineProperty, __defProps$c = Object.defineProperties, __getOwnPropDescs$c = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$q = Object.getOwnPropertySymbols, __hasOwnProp$q = Object.prototype.hasOwnProperty, __propIsEnum$q = Object.prototype.propertyIsEnumerable, __defNormalProp$k = (obj, key, value) => key in obj ? __defProp$k(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$k = (a, b) => {
23
- for (var prop in b || (b = {}))
24
- __hasOwnProp$q.call(b, prop) && __defNormalProp$k(a, prop, b[prop]);
25
- if (__getOwnPropSymbols$q)
26
- for (var prop of __getOwnPropSymbols$q(b))
27
- __propIsEnum$q.call(b, prop) && __defNormalProp$k(a, prop, b[prop]);
28
- return a;
29
- }, __spreadProps$c = (a, b) => __defProps$c(a, __getOwnPropDescs$c(b));
30
- class BlockModel extends Model {
1
+ import * as pg from 'pg';
2
+ import { Sequelize, Error as Error$1, fn, col, Op, literal, DataTypes, Model } from 'sequelize';
3
+ import yn3 from 'yn';
4
+ import * as d3Array from 'd3-array';
5
+ import * as d3Collection from 'd3-collection';
6
+ import * as d3Format from 'd3-format';
7
+ import * as d3TimeFormat from 'd3-time-format';
8
+ import { formatAbbreviate } from 'd3plus-format';
9
+ import { date } from 'd3plus-axis';
10
+ import { assign, closest, merge } from 'd3plus-common';
11
+ import { strip, titleCase } from 'd3plus-text';
12
+ import axios from 'axios';
13
+ import slugifyFn from 'slugify';
14
+ import lunr from 'lunr';
15
+ import lunrStemmer from 'lunr-languages/lunr.stemmer.support';
16
+ import Base58 from 'base58';
17
+ import FlickrSDK from 'flickr-sdk';
18
+ import sharp from 'sharp';
19
+ import { createApi } from 'unsplash-js';
20
+ import fs from 'fs';
21
+ import NextCors from 'nextjs-cors';
22
+ import formidable from 'formidable';
23
+
24
+ var __defProp = Object.defineProperty;
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var getLogging_default = (env = process.env) => yn3(env.REPORTS_LOGGING);
30
+ var BlockModel = class extends Model {
31
31
  getContent(locale) {
32
32
  const content = this.contentByLocale.find((item) => item.locale === locale);
33
- if (!content)
33
+ if (!content) {
34
34
  throw new Error(`Missing SearchContent for locale '${locale}' on Search ID '${this.id}'`);
35
+ }
35
36
  return content;
36
37
  }
37
38
  toJSON() {
38
- const attributes = this.get({ plain: !0 });
39
+ const attributes = this.get({ plain: true });
39
40
  delete attributes.block_input;
40
41
  const { inputs = [], consumers = [], contentByLocale = [] } = this;
41
- return __spreadProps$c(__spreadValues$k({}, attributes), {
42
+ return {
43
+ ...attributes,
42
44
  inputs: inputs.map((item) => item.toJSON()),
43
45
  consumers: consumers.map((item) => item.toJSON()),
44
46
  contentByLocale: Object.fromEntries(
45
47
  contentByLocale.map((content) => [content.locale, content.toJSON()])
46
48
  )
47
- });
49
+ };
48
50
  }
49
- }
50
- function initModel$b(sequelize) {
51
- return BlockModel.init({
51
+ };
52
+ function initModel(sequelize) {
53
+ BlockModel.init({
52
54
  id: {
53
55
  type: DataTypes.INTEGER,
54
- primaryKey: !0,
55
- autoIncrement: !0
56
+ primaryKey: true,
57
+ autoIncrement: true
56
58
  },
57
59
  settings: {
58
60
  type: DataTypes.JSON,
@@ -64,7 +66,7 @@ function initModel$b(sequelize) {
64
66
  },
65
67
  shared: {
66
68
  type: DataTypes.BOOLEAN,
67
- defaultValue: !1
69
+ defaultValue: false
68
70
  },
69
71
  blockrow: DataTypes.STRING,
70
72
  blockcol: DataTypes.STRING,
@@ -80,27 +82,34 @@ function initModel$b(sequelize) {
80
82
  sequelize,
81
83
  modelName: "block",
82
84
  tableName: "bespoke_reports_block",
83
- freezeTableName: !0,
84
- timestamps: !1
85
- }), (models) => (BlockModel.hasMany(models.block_content, { foreignKey: "id", sourceKey: "id", as: "contentByLocale" }), BlockModel.belongsToMany(models.block, {
86
- through: "block_input",
87
- foreignKey: "block_id",
88
- otherKey: "input_id",
89
- as: "inputs"
90
- }), BlockModel.belongsToMany(models.block, {
91
- through: "block_input",
92
- foreignKey: "input_id",
93
- otherKey: "block_id",
94
- as: "consumers"
95
- }), BlockModel);
96
- }
97
- class BlockContentModel extends Model {
98
- }
99
- function initModel$a(sequelize) {
100
- return BlockContentModel.init({
85
+ freezeTableName: true,
86
+ timestamps: false
87
+ });
88
+ return (models) => {
89
+ BlockModel.hasMany(models.block_content, { foreignKey: "id", sourceKey: "id", as: "contentByLocale" });
90
+ BlockModel.belongsToMany(models.block, {
91
+ through: "block_input",
92
+ foreignKey: "block_id",
93
+ otherKey: "input_id",
94
+ as: "inputs"
95
+ });
96
+ BlockModel.belongsToMany(models.block, {
97
+ through: "block_input",
98
+ foreignKey: "input_id",
99
+ otherKey: "block_id",
100
+ as: "consumers"
101
+ });
102
+ return BlockModel;
103
+ };
104
+ }
105
+ var block_default = initModel;
106
+ var BlockContentModel = class extends Model {
107
+ };
108
+ function initModel2(sequelize) {
109
+ BlockContentModel.init({
101
110
  id: {
102
111
  type: DataTypes.INTEGER,
103
- primaryKey: !0,
112
+ primaryKey: true,
104
113
  onDelete: "cascade",
105
114
  references: {
106
115
  model: "bespoke_reports_block",
@@ -109,7 +118,7 @@ function initModel$a(sequelize) {
109
118
  },
110
119
  locale: {
111
120
  type: DataTypes.STRING,
112
- primaryKey: !0
121
+ primaryKey: true
113
122
  },
114
123
  content: {
115
124
  type: DataTypes.JSON,
@@ -119,18 +128,20 @@ function initModel$a(sequelize) {
119
128
  sequelize,
120
129
  modelName: "block_content",
121
130
  tableName: "bespoke_reports_block_content",
122
- freezeTableName: !0,
123
- timestamps: !1
124
- }), () => BlockContentModel;
125
- }
126
- class BlockInputModel extends Model {
131
+ freezeTableName: true,
132
+ timestamps: false
133
+ });
134
+ return () => BlockContentModel;
127
135
  }
128
- function initModel$9(sequelize) {
129
- return BlockInputModel.init({
136
+ var block_content_default = initModel2;
137
+ var BlockInputModel = class extends Model {
138
+ };
139
+ function initModel3(sequelize) {
140
+ BlockInputModel.init({
130
141
  id: {
131
142
  type: DataTypes.INTEGER,
132
- primaryKey: !0,
133
- autoIncrement: !0
143
+ primaryKey: true,
144
+ autoIncrement: true
134
145
  },
135
146
  block_id: {
136
147
  type: DataTypes.INTEGER,
@@ -152,209 +163,313 @@ function initModel$9(sequelize) {
152
163
  sequelize,
153
164
  modelName: "block_input",
154
165
  tableName: "bespoke_reports_block_input",
155
- freezeTableName: !0,
156
- timestamps: !1
157
- }), () => BlockInputModel;
166
+ freezeTableName: true,
167
+ timestamps: false
168
+ });
169
+ return () => BlockInputModel;
158
170
  }
171
+ var block_input_default = initModel3;
172
+
173
+ // libs/stats.js
159
174
  function logGamma(Z) {
160
175
  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);
161
176
  return (Z - 0.5) * Math.log(Z + 4.5) - (Z + 4.5) + Math.log(S * 2.50662827465);
162
177
  }
163
178
  function betinc(X, A, B) {
164
- let A0 = 0, B0 = 1, A1 = 1, B1 = 1, M9 = 0, A2 = 0, C9;
165
- for (; Math.abs((A1 - A2) / A1) > 1e-5; )
166
- A2 = A1, C9 = -(A + M9) * (A + B + M9) * X / (A + 2 * M9) / (A + 2 * M9 + 1), A0 = A1 + C9 * A0, B0 = B1 + C9 * B0, M9 += 1, C9 = M9 * (B - M9) * X / (A + 2 * M9 - 1) / (A + 2 * M9), A1 = A0 + C9 * A1, B1 = B0 + C9 * B1, A0 /= B1, B0 /= B1, A1 /= B1, B1 = 1;
179
+ let A0 = 0;
180
+ let B0 = 1;
181
+ let A1 = 1;
182
+ let B1 = 1;
183
+ let M9 = 0;
184
+ let A2 = 0;
185
+ let C9;
186
+ while (Math.abs((A1 - A2) / A1) > 1e-5) {
187
+ A2 = A1;
188
+ C9 = -(A + M9) * (A + B + M9) * X / (A + 2 * M9) / (A + 2 * M9 + 1);
189
+ A0 = A1 + C9 * A0;
190
+ B0 = B1 + C9 * B0;
191
+ M9 += 1;
192
+ C9 = M9 * (B - M9) * X / (A + 2 * M9 - 1) / (A + 2 * M9);
193
+ A1 = A0 + C9 * A1;
194
+ B1 = B0 + C9 * B1;
195
+ A0 /= B1;
196
+ B0 /= B1;
197
+ A1 /= B1;
198
+ B1 = 1;
199
+ }
167
200
  return A1 / A;
168
201
  }
169
202
  function binomialCdf(X, N, P) {
170
- let betacdf, bincdf;
203
+ let betacdf;
204
+ let bincdf;
171
205
  if (X < 0)
172
206
  bincdf = 0;
173
207
  else if (X >= N)
174
208
  bincdf = 1;
175
209
  else {
176
210
  X = Math.floor(X);
177
- const Z = P, A = X + 1, B = N - X, S = A + B, BT = Math.exp(logGamma(S) - logGamma(B) - logGamma(A) + A * Math.log(Z) + B * Math.log(1 - Z));
178
- Z < (A + 1) / (S + 2) ? betacdf = BT * betinc(Z, A, B) : betacdf = 1 - BT * betinc(1 - Z, B, A), bincdf = 1 - betacdf;
211
+ const Z = P;
212
+ const A = X + 1;
213
+ const B = N - X;
214
+ const S = A + B;
215
+ const BT = Math.exp(logGamma(S) - logGamma(B) - logGamma(A) + A * Math.log(Z) + B * Math.log(1 - Z));
216
+ if (Z < (A + 1) / (S + 2)) {
217
+ betacdf = BT * betinc(Z, A, B);
218
+ } else {
219
+ betacdf = 1 - BT * betinc(1 - Z, B, A);
220
+ }
221
+ bincdf = 1 - betacdf;
179
222
  }
180
223
  return Math.round(bincdf * 1e5) / 1e5;
181
224
  }
182
225
  function criticalValue(confLevel) {
183
- return {
226
+ const critMap = {
184
227
  0.99999: 15.137,
185
228
  0.99: 6.635,
186
229
  0.95: 3.841,
187
230
  0.9: 2.706
188
- }[confLevel];
231
+ };
232
+ return critMap[confLevel];
189
233
  }
190
234
  function binP(N, p, x1, x2) {
191
235
  const q = p / (1 - p);
192
- let k = 0, v = 1, s = 0, tot = 0;
193
- for (; k <= N; )
194
- tot += v, k >= x1 & k <= x2 && (s += v), tot > 1e30 && (s /= 1e30, tot /= 1e30, v /= 1e30), k += 1, v = v * q * (N + 1 - k) / k;
236
+ let k = 0;
237
+ let v = 1;
238
+ let s = 0;
239
+ let tot = 0;
240
+ while (k <= N) {
241
+ tot += v;
242
+ if (k >= x1 & k <= x2) {
243
+ s += v;
244
+ }
245
+ if (tot > 1e30) {
246
+ s /= 1e30;
247
+ tot /= 1e30;
248
+ v /= 1e30;
249
+ }
250
+ k += 1;
251
+ v = v * q * (N + 1 - k) / k;
252
+ }
195
253
  return s / tot;
196
254
  }
197
255
  function computeMidP(vx, vN, confLevel) {
198
- const vP = vx / vN, vTL = (100 - confLevel * 100) / 2;
199
- let T1, T2;
200
- if (vx === 0)
256
+ const vP = vx / vN;
257
+ const prob = confLevel * 100;
258
+ const vTL = (100 - prob) / 2;
259
+ let T1;
260
+ let T2;
261
+ if (vx === 0) {
201
262
  T1 = 0;
202
- else {
203
- let v = vP / 2, vsL = 0, vsH = vP;
263
+ } else {
264
+ let v = vP / 2;
265
+ let vsL = 0;
266
+ let vsH = vP;
204
267
  const p = vTL / 100;
205
- for (; vsH - vsL > 1e-5; )
206
- binP(vN, v, vx, vx) * 0.5 + binP(vN, v, vx + 1, vN) > p ? (vsH = v, v = (vsL + v) / 2) : (vsL = v, v = (vsH + v) / 2);
268
+ while (vsH - vsL > 1e-5) {
269
+ if (binP(vN, v, vx, vx) * 0.5 + binP(vN, v, vx + 1, vN) > p) {
270
+ vsH = v;
271
+ v = (vsL + v) / 2;
272
+ } else {
273
+ vsL = v;
274
+ v = (vsH + v) / 2;
275
+ }
276
+ }
207
277
  T1 = v;
208
278
  }
209
- if (vx === vN)
279
+ if (vx === vN) {
210
280
  T2 = 0;
211
- else {
212
- let v = (1 + vP) / 2, vsL = vP, vsH = 1;
281
+ } else {
282
+ let v = (1 + vP) / 2;
283
+ let vsL = vP;
284
+ let vsH = 1;
213
285
  const p = vTL / 100;
214
- for (; vsH - vsL > 1e-5; )
215
- binP(vN, v, vx, vx) * 0.5 + binP(vN, v, 0, vx - 1) < p ? (vsH = v, v = (vsL + v) / 2) : (vsL = v, v = (vsH + v) / 2);
286
+ while (vsH - vsL > 1e-5) {
287
+ if (binP(vN, v, vx, vx) * 0.5 + binP(vN, v, 0, vx - 1) < p) {
288
+ vsH = v;
289
+ v = (vsL + v) / 2;
290
+ } else {
291
+ vsL = v;
292
+ v = (vsH + v) / 2;
293
+ }
294
+ }
216
295
  T2 = v;
217
296
  }
218
297
  return { lci: T1, uci: T2 };
219
298
  }
220
299
  function smr(observedVal, expectedVal) {
221
- const vx = observedVal, vN = expectedVal, Obs = vx, Exp = vN, ci = 95;
222
- let v = 0.5, dv = 0.5, p = (100 - ci) / 2 / 100;
300
+ const vx = observedVal;
301
+ const vN = expectedVal;
302
+ const Obs = vx;
303
+ const Exp = vN;
304
+ const ci = 95;
305
+ let v = 0.5;
306
+ let dv = 0.5;
307
+ const vTL = (100 - ci) / 2;
308
+ let p = vTL / 100;
223
309
  const vZ = Obs;
224
- for (; dv > 1e-5; )
225
- dv /= 2, poisP((1 + vZ) * v / (1 - v), vZ + 1, 1e10) + 0.5 * poisP((1 + vZ) * v / (1 - v), vZ, vZ) > p ? v -= dv : v += dv;
310
+ while (dv > 1e-5) {
311
+ dv /= 2;
312
+ if (poisP((1 + vZ) * v / (1 - v), vZ + 1, 1e10) + 0.5 * poisP((1 + vZ) * v / (1 - v), vZ, vZ) > p) {
313
+ v -= dv;
314
+ } else {
315
+ v += dv;
316
+ }
317
+ }
226
318
  const QL = (1 + vZ) * v / (1 - v) / Exp;
227
- for (v = 0.5, dv = 0.5, p = (100 - ci) / 2 / 100; dv > 1e-5; )
228
- dv /= 2, poisP((1 + vZ) * v / (1 - v), 0, vZ - 1) + 0.5 * poisP((1 + vZ) * v / (1 - v), vZ, vZ) < p ? v -= dv : v += dv;
319
+ v = 0.5;
320
+ dv = 0.5;
321
+ const vTU = (100 - ci) / 2;
322
+ p = vTU / 100;
323
+ while (dv > 1e-5) {
324
+ dv /= 2;
325
+ if (poisP((1 + vZ) * v / (1 - v), 0, vZ - 1) + 0.5 * poisP((1 + vZ) * v / (1 - v), vZ, vZ) < p) {
326
+ v -= dv;
327
+ } else {
328
+ v += dv;
329
+ }
330
+ }
229
331
  const QU = (1 + vZ) * v / (1 - v) / Exp;
230
332
  return { lci: QL, uci: QU };
231
333
  }
232
334
  function poisP(Z, x1, x2) {
233
- let q = 1, tot = 0, s = 0, k = 0;
234
- for (; k < Z || q > tot * 1e-10; )
235
- tot += q, k >= x1 & k <= x2 && (s += q), tot > 1e30 && (s /= 1e30, tot /= 1e30, q /= 1e30), k += 1, q = q * Z / k;
335
+ let q = 1;
336
+ let tot = 0;
337
+ let s = 0;
338
+ let k = 0;
339
+ while (k < Z || q > tot * 1e-10) {
340
+ tot += q;
341
+ if (k >= x1 & k <= x2) {
342
+ s += q;
343
+ }
344
+ if (tot > 1e30) {
345
+ s /= 1e30;
346
+ tot /= 1e30;
347
+ q /= 1e30;
348
+ }
349
+ k += 1;
350
+ q = q * Z / k;
351
+ }
236
352
  return s / tot;
237
353
  }
238
- var stats = {
354
+ var stats_default = {
239
355
  binomialCdf,
240
356
  binP,
241
357
  computeMidP,
242
358
  criticalValue,
243
359
  smr
244
- }, __defProp$j = Object.defineProperty, __getOwnPropSymbols$p = Object.getOwnPropertySymbols, __hasOwnProp$p = Object.prototype.hasOwnProperty, __propIsEnum$p = Object.prototype.propertyIsEnumerable, __defNormalProp$j = (obj, key, value) => key in obj ? __defProp$j(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$j = (a, b) => {
245
- for (var prop in b || (b = {}))
246
- __hasOwnProp$p.call(b, prop) && __defNormalProp$j(a, prop, b[prop]);
247
- if (__getOwnPropSymbols$p)
248
- for (var prop of __getOwnPropSymbols$p(b))
249
- __propIsEnum$p.call(b, prop) && __defNormalProp$j(a, prop, b[prop]);
250
- return a;
251
360
  };
252
- const libs = {
253
- d3: __spreadValues$j(__spreadValues$j(__spreadValues$j(__spreadValues$j({}, d3Array), d3Collection), d3Format), d3TimeFormat),
361
+
362
+ // libs/libs.ts
363
+ var libs = {
364
+ d3: {
365
+ ...d3Array,
366
+ ...d3Collection,
367
+ ...d3Format,
368
+ ...d3TimeFormat
369
+ },
254
370
  d3plus: {
255
371
  assign,
256
372
  closest,
257
- date: date$1,
373
+ date,
258
374
  formatAbbreviate,
259
375
  merge,
260
376
  strip,
261
377
  titleCase
262
378
  },
263
- stats
264
- }, declaredFormatters = {};
379
+ stats: stats_default
380
+ };
381
+ var declaredFormatters = {};
265
382
  function declareFormatter(manifest) {
266
383
  const func = manifest.logicFactory(libs);
267
- return declaredFormatters[manifest.name] = {
384
+ declaredFormatters[manifest.name] = {
268
385
  description: manifest.description,
269
386
  inputType: manifest.inputType,
270
387
  logic: stringifyFn(func),
271
388
  testValue: manifest.testValue,
272
389
  type: manifest.type || "formatter"
273
- }, func;
390
+ };
391
+ return func;
274
392
  }
275
393
  function stringifyFn(func) {
276
394
  const strFunc = func.toString().trim();
277
- if (strFunc.startsWith("function"))
395
+ if (strFunc.startsWith("function")) {
278
396
  return strFunc.replace(/^function(?:\s\w+)?\([^\)]\)/, "").trim().replace(/^{([\s\S]+)\}$/, "$1");
397
+ }
279
398
  const noArgs = strFunc.replace(/^.+?=>/, "").trim();
280
399
  return noArgs.startsWith("{") ? noArgs.replace(/^{([\s\S]+)\}$/, "$1") : `return ${noArgs}`;
281
400
  }
282
- var __defProp$i = Object.defineProperty, __getOwnPropSymbols$o = Object.getOwnPropertySymbols, __hasOwnProp$o = Object.prototype.hasOwnProperty, __propIsEnum$o = Object.prototype.propertyIsEnumerable, __defNormalProp$i = (obj, key, value) => key in obj ? __defProp$i(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$i = (a, b) => {
283
- for (var prop in b || (b = {}))
284
- __hasOwnProp$o.call(b, prop) && __defNormalProp$i(a, prop, b[prop]);
285
- if (__getOwnPropSymbols$o)
286
- for (var prop of __getOwnPropSymbols$o(b))
287
- __propIsEnum$o.call(b, prop) && __defNormalProp$i(a, prop, b[prop]);
288
- return a;
289
- };
290
- const REPORT_TYPES = {
401
+ var REPORT_TYPES = {
291
402
  REPORT: "report",
292
403
  STORY: "story"
293
- }, REPORT_MODES = {
404
+ };
405
+ var REPORT_MODES = {
294
406
  UNILATERAL: "uni",
295
407
  MULTILATERAL: "multi"
296
- }, REPORT_FIELDS = {
408
+ };
409
+ var REPORT_FIELDS = {
297
410
  TITLE: "title",
298
411
  SUBTITLE: "subtitle",
299
412
  LABEL: "label"
300
413
  };
301
- REPORT_TYPES.REPORT + "", Object.values(REPORT_FIELDS), REPORT_TYPES.STORY + "", Object.values(REPORT_FIELDS);
302
- const ALLOWED = {
303
- ALLOWED: "allowed",
304
- ALLOWED_LOGIC: "allowedLogic"
305
- };
306
- __spreadValues$i({}, ALLOWED), __spreadValues$i({
307
- POSITION: "position",
308
- ICON: "icon"
309
- }, ALLOWED);
310
- const BLOCK_CONTENT_TYPES = {
311
- IMAGE: "image",
312
- PARAGRAPH: "paragraph",
313
- SELECTOR: "selector",
314
- STAT: "stat",
315
- SUBTITLE: "subtitle",
316
- TITLE: "title"
317
- }, BLOCK_LOGIC_TYPES = {
318
- GENERATOR: "generator",
319
- VIZ: "visualization"
320
- }, BLOCK_TYPES = __spreadValues$i(__spreadValues$i({}, BLOCK_CONTENT_TYPES), BLOCK_LOGIC_TYPES);
321
- BLOCK_TYPES.GENERATOR, BLOCK_TYPES.SELECTOR, BLOCK_TYPES.VIZ, BLOCK_TYPES.IMAGE;
322
- const BLOCK_FIELDS = {
323
- ALT: "alt",
324
- AUTHOR: "author",
325
- FOOTNOTE: "footnote",
326
- BIO: "bio",
327
- IMAGE: "image",
328
- LOGIC: "logic",
329
- SIMPLE: "simple",
330
- SIMPLE_ENABLED: "simpleEnabled",
331
- PARAGRAPH: "paragraph",
332
- SELECTOR_DEFAULT: "selectorDefault",
333
- SELECTOR_DYNAMIC: "selectorDynamic",
334
- SELECTOR_NAME: "selectorName",
335
- SELECTOR_TYPE: "selectorType",
336
- SRC: "src",
337
- SLUG: "slug",
338
- SUBTITLE: "subtitle",
339
- TITLE: "title",
340
- TOOLTIP: "tooltip",
341
- TWITTER: "twitter",
342
- VALUE: "value"
343
- };
344
- BLOCK_TYPES.IMAGE + "", BLOCK_FIELDS.SRC, BLOCK_FIELDS.ALT, BLOCK_TYPES.PARAGRAPH + "", BLOCK_TYPES.PARAGRAPH, BLOCK_FIELDS.TOOLTIP, BLOCK_TYPES.SELECTOR + "", BLOCK_FIELDS.SELECTOR_DEFAULT, BLOCK_FIELDS.SELECTOR_DYNAMIC, BLOCK_FIELDS.SELECTOR_NAME, BLOCK_FIELDS.SELECTOR_TYPE, BLOCK_TYPES.STAT + "", BLOCK_FIELDS.TITLE, BLOCK_FIELDS.SUBTITLE, BLOCK_FIELDS.VALUE, BLOCK_FIELDS.TOOLTIP, BLOCK_TYPES.SUBTITLE + "", BLOCK_FIELDS.SUBTITLE, BLOCK_FIELDS.TOOLTIP, BLOCK_TYPES.TITLE + "", BLOCK_FIELDS.TITLE, BLOCK_FIELDS.SLUG, BLOCK_FIELDS.TOOLTIP, BLOCK_TYPES.GENERATOR + "", BLOCK_TYPES.VIZ + "", __spreadValues$i({
345
- NAME: "name",
346
- DESCRIPTION: "description"
347
- }, ALLOWED);
348
- const FORMATTER_TYPES = {
414
+ ({
415
+ [REPORT_TYPES.REPORT]: Object.values(REPORT_FIELDS),
416
+ [REPORT_TYPES.STORY]: Object.values(REPORT_FIELDS)
417
+ });
418
+ var FORMATTER_TYPES = {
349
419
  FORMATTER: "formatter",
350
420
  FUNCTION: "function"
351
- }, FORMATTER_INPUT_TYPES = {
421
+ };
422
+ var FORMATTER_INPUT_TYPES = {
352
423
  STRING: "string",
353
424
  NUMBER: "number",
354
425
  OBJECT: "object",
355
426
  DATE: "date"
356
427
  };
357
- var abbreviate = declareFormatter({
428
+
429
+ // libs/formatters/index.ts
430
+ var formatters_exports = {};
431
+ __export(formatters_exports, {
432
+ abbreviate: () => abbreviate_default,
433
+ abs: () => abs_default,
434
+ bucket: () => bucket_default,
435
+ commas: () => commas_default,
436
+ date: () => date_default,
437
+ dollar: () => dollar_default,
438
+ formatFieldName: () => formatFieldName_default,
439
+ grewTo: () => grewTo_default,
440
+ grewWord: () => grewWord_default,
441
+ growing: () => growing_default,
442
+ growth: () => growth_default,
443
+ growthPct: () => growthPct_default,
444
+ growthWord: () => growthWord_default,
445
+ highWord: () => highWord_default,
446
+ increaseWord: () => increaseWord_default,
447
+ increasedWord: () => increasedWord_default,
448
+ increasing: () => increasing_default,
449
+ largerThan: () => largerThan_default,
450
+ list: () => list_default,
451
+ longWord: () => longWord_default,
452
+ lowerCaseFirst: () => lowerCaseFirst_default,
453
+ moreFewerWord: () => moreFewerWord_default,
454
+ moreLess: () => moreLess_default,
455
+ moreWord: () => moreWord_default,
456
+ olderWord: () => olderWord_default,
457
+ olderYounger: () => olderYounger_default,
458
+ plural: () => plural_default,
459
+ pxToInt: () => pxToInt_default,
460
+ salary: () => salary_default,
461
+ stripEntities: () => stripEntities_default,
462
+ stripHTML: () => stripHTML_default,
463
+ stripOL: () => stripOL_default,
464
+ stripP: () => stripP_default,
465
+ stripUL: () => stripUL_default,
466
+ toKebabCase: () => toKebabCase_default,
467
+ toSpacedCase: () => toSpacedCase_default,
468
+ upperCaseFirst: () => upperCaseFirst_default
469
+ });
470
+
471
+ // libs/formatters/abbreviate.js
472
+ var abbreviate_default = declareFormatter({
358
473
  name: "abbreviate",
359
474
  description: "Abbreviates a number into a smaller more human-readable number.",
360
475
  logicFactory(libs2) {
@@ -363,7 +478,10 @@ var abbreviate = declareFormatter({
363
478
  inputType: "number",
364
479
  testValue: "123456",
365
480
  type: "formatter"
366
- }), abs = declareFormatter({
481
+ });
482
+
483
+ // libs/formatters/abs.js
484
+ var abs_default = declareFormatter({
367
485
  name: "abs",
368
486
  description: "Simple Absolute Value.",
369
487
  logicFactory(libs2) {
@@ -373,18 +491,43 @@ var abbreviate = declareFormatter({
373
491
  testValue: "-123",
374
492
  type: "formatter"
375
493
  });
376
- const logicFactory$1 = () => function(n) {
377
- let nums = new RegExp(/([\$0-9\,]+)[A-z\-\s\&]*([\$0-9\,]*)/g).exec(n);
378
- return nums ? (nums = nums.slice(1).filter((d) => d.length).map((d) => (d.includes(",") && (d.indexOf(",") === d.length - 4 ? d = d.replace(/,000$/g, "k").replace(/([0-9]+)(,999$)/g, (n2) => `${parseInt(n2) + 1}k`) : d.indexOf(",") === d.length - 8 && (d = d.replace(/,000,000$/g, "M").replace(/([0-9]+)(,999,999$)/g, (n2) => `${parseInt(n2) + 1}M`))), d)), nums.length === 2 ? nums.join(" - ") : n.toLowerCase().match(/under|less|\</g) ? `< ${nums[0]}` : n.toLowerCase().match(/over|more|\+|\>/g) ? `${nums[0]}+` : `${nums[0]}`) : "None";
494
+
495
+ // libs/formatters/bucket.js
496
+ var logicFactory = () => function bucket(n) {
497
+ const re = new RegExp(/([\$0-9\,]+)[A-z\-\s\&]*([\$0-9\,]*)/g);
498
+ let nums = re.exec(n);
499
+ if (nums) {
500
+ nums = nums.slice(1).filter((d) => d.length).map((d) => {
501
+ if (d.includes(",")) {
502
+ if (d.indexOf(",") === d.length - 4) {
503
+ d = d.replace(/,000$/g, "k").replace(/([0-9]+)(,999$)/g, (n2) => `${parseInt(n2) + 1}k`);
504
+ } else if (d.indexOf(",") === d.length - 8) {
505
+ d = d.replace(/,000,000$/g, "M").replace(/([0-9]+)(,999,999$)/g, (n2) => `${parseInt(n2) + 1}M`);
506
+ }
507
+ }
508
+ return d;
509
+ });
510
+ if (nums.length === 2)
511
+ return nums.join(" - ");
512
+ if (n.toLowerCase().match(/under|less|\</g))
513
+ return `< ${nums[0]}`;
514
+ if (n.toLowerCase().match(/over|more|\+|\>/g))
515
+ return `${nums[0]}+`;
516
+ return `${nums[0]}`;
517
+ }
518
+ return "None";
379
519
  };
380
- var bucket = declareFormatter({
520
+ var bucket_default = declareFormatter({
381
521
  name: "bucket",
382
522
  description: "Sanitizes bucket strings to '< n', 'n1 - n2', and 'n+'",
383
- logicFactory: logicFactory$1,
523
+ logicFactory,
384
524
  inputType: "number",
385
525
  testValue: "1234",
386
526
  type: "formatter"
387
- }), commas = declareFormatter({
527
+ });
528
+
529
+ // libs/formatters/commas.js
530
+ var commas_default = declareFormatter({
388
531
  name: "commas",
389
532
  description: "* Rounds to nearest whole number and adds commas.",
390
533
  logicFactory(libs2) {
@@ -393,25 +536,43 @@ var bucket = declareFormatter({
393
536
  inputType: "number",
394
537
  testValue: "1234.6",
395
538
  type: "formatter"
396
- }), date = declareFormatter({
539
+ });
540
+
541
+ // libs/formatters/date.js
542
+ var date_default = declareFormatter({
397
543
  name: "date",
398
544
  description: "Formats a date into '%B %d, %Y' format.",
399
545
  logicFactory(libs2) {
400
- return (n) => (typeof n == "string" && (n = libs2.d3plus.date(n)), libs2.d3.timeFormat("%B %d, %Y")(n));
546
+ return (n) => {
547
+ if (typeof n === "string") {
548
+ n = libs2.d3plus.date(n);
549
+ }
550
+ return libs2.d3.timeFormat("%B %d, %Y")(n);
551
+ };
401
552
  },
402
553
  inputType: "date",
403
554
  testValue: "2022-01-01",
404
555
  type: "formatter"
405
- }), dollar = declareFormatter({
556
+ });
557
+
558
+ // libs/formatters/dollar.js
559
+ var dollar_default = declareFormatter({
406
560
  name: "date",
407
561
  description: "Adds a US dollar sign to the beginning of a String or Number.",
408
562
  logicFactory(libs2) {
409
- return (n) => (typeof n == "number" && (n = libs2.d3plus.formatAbbreviate(n)), n.charAt(0) === "-" ? n.replace("-", "-$") : `$${n}`);
563
+ return (n) => {
564
+ if (typeof n === "number")
565
+ n = libs2.d3plus.formatAbbreviate(n);
566
+ return n.charAt(0) === "-" ? n.replace("-", "-$") : `$${n}`;
567
+ };
410
568
  },
411
569
  inputType: "number",
412
570
  testValue: "123",
413
571
  type: "formatter"
414
- }), formatFieldName = declareFormatter({
572
+ });
573
+
574
+ // libs/formatters/formatFieldName.js
575
+ var formatFieldName_default = declareFormatter({
415
576
  name: "formatFieldName",
416
577
  description: "Based on field name returns a string",
417
578
  logicFactory(libs2) {
@@ -426,13 +587,24 @@ var bucket = declareFormatter({
426
587
  if (n.field === "tooltip")
427
588
  return "Tooltip text";
428
589
  }
429
- return n.contentType.toLowerCase() === "section" && n.field === "short" ? "Short title" : n.contentType.toLowerCase() === "description" && n.field === "description" ? "Paragraph" : n.field;
590
+ if (n.contentType.toLowerCase() === "section") {
591
+ if (n.field === "short")
592
+ return "Short title";
593
+ }
594
+ if (n.contentType.toLowerCase() === "description") {
595
+ if (n.field === "description")
596
+ return "Paragraph";
597
+ }
598
+ return n.field;
430
599
  };
431
600
  },
432
601
  inputType: "object",
433
602
  testValue: '{"field":"title","contentType":"stat"}',
434
603
  type: "formatter"
435
- }), grewTo = declareFormatter({
604
+ });
605
+
606
+ // libs/formatters/grewTo.js
607
+ var grewTo_default = declareFormatter({
436
608
  name: "grewTo",
437
609
  description: "Returns the text with grow direction: 'declined from', 'grew to' o 'stayed at'",
438
610
  logicFactory(libs2) {
@@ -441,7 +613,10 @@ var bucket = declareFormatter({
441
613
  inputType: "number",
442
614
  testValue: "-1234",
443
615
  type: "formatter"
444
- }), grewWord = declareFormatter({
616
+ });
617
+
618
+ // libs/formatters/grewWord.js
619
+ var grewWord_default = declareFormatter({
445
620
  name: "grewWord",
446
621
  description: "Returns either 'grew', 'declined', or 'stayed' depending on the provided number's sign.",
447
622
  logicFactory(libs2) {
@@ -450,7 +625,10 @@ var bucket = declareFormatter({
450
625
  inputType: "number",
451
626
  testValue: "-1234",
452
627
  type: "formatter"
453
- }), growing = declareFormatter({
628
+ });
629
+
630
+ // libs/formatters/growing.js
631
+ var growing_default = declareFormatter({
454
632
  name: "growing",
455
633
  description: "Returns either 'declining', 'growing' depending on the provided number's sign.",
456
634
  logicFactory(libs2) {
@@ -460,7 +638,9 @@ var bucket = declareFormatter({
460
638
  testValue: "-1234",
461
639
  type: "formatter"
462
640
  });
463
- const logicFactory = () => function(n) {
641
+
642
+ // libs/formatters/growth.js
643
+ var logicFactory2 = () => function growth(n) {
464
644
  const {
465
645
  curr,
466
646
  currMoe = 0,
@@ -469,20 +649,24 @@ const logicFactory = () => function(n) {
469
649
  } = n;
470
650
  let value;
471
651
  if (currMoe || prevMoe) {
472
- const f1 = (-prev / curr ** 2) ** 2 * currMoe ** 2, f2 = (1 / curr) ** 2 * prevMoe ** 2;
652
+ const f1 = (-prev / curr ** 2) ** 2 * currMoe ** 2;
653
+ const f2 = (1 / curr) ** 2 * prevMoe ** 2;
473
654
  value = Math.sqrt(f1 + f2);
474
655
  } else
475
656
  value = (curr - prev) / prev;
476
657
  return value * 100;
477
658
  };
478
- var growth = declareFormatter({
659
+ var growth_default = declareFormatter({
479
660
  name: "growth",
480
661
  description: "Calculates the growth percentage between two numbers provided the following object format: {curr, prev}. Also supports calculating the growth between two margin of errors using this format: {curr, currMoe, prev, prevMoe}",
481
- logicFactory,
662
+ logicFactory: logicFactory2,
482
663
  inputType: "object",
483
664
  testValue: '{"curr":10,"currMoe":0,"prev":13,"prevMoe":0}',
484
665
  type: "formatter"
485
- }), growthPct = declareFormatter({
666
+ });
667
+
668
+ // libs/formatters/growthPct.js
669
+ var growthPct_default = declareFormatter({
486
670
  name: "growthPct",
487
671
  description: "Abbreviates a growth value, turns it absolute, and adds a percent sign.",
488
672
  logicFactory(libs2) {
@@ -491,7 +675,10 @@ var growth = declareFormatter({
491
675
  inputType: "number",
492
676
  testValue: "12345",
493
677
  type: "formatter"
494
- }), growthWord = declareFormatter({
678
+ });
679
+
680
+ // libs/formatters/growthWord.js
681
+ var growthWord_default = declareFormatter({
495
682
  name: "growthWord",
496
683
  description: "Returns either 'growth' or 'decline' depending on the provided number's sign.",
497
684
  logicFactory(libs2) {
@@ -500,7 +687,10 @@ var growth = declareFormatter({
500
687
  inputType: "number",
501
688
  testValue: "-1234",
502
689
  type: "formatter"
503
- }), highWord = declareFormatter({
690
+ });
691
+
692
+ // libs/formatters/highWord.js
693
+ var highWord_default = declareFormatter({
504
694
  name: "highWord",
505
695
  description: "Returns either 'higher than', 'lower than', or 'approximately the same as' depending on the provided number's sign.",
506
696
  logicFactory(libs2) {
@@ -509,7 +699,10 @@ var growth = declareFormatter({
509
699
  inputType: "number",
510
700
  testValue: "0",
511
701
  type: "formatter"
512
- }), increaseWord = declareFormatter({
702
+ });
703
+
704
+ // libs/formatters/increaseWord.js
705
+ var increaseWord_default = declareFormatter({
513
706
  name: "increaseWord",
514
707
  description: "Returns either 'increase', 'decrease', or 'change' depending on the provided number's sign.",
515
708
  logicFactory(libs2) {
@@ -518,7 +711,10 @@ var growth = declareFormatter({
518
711
  inputType: "number",
519
712
  testValue: "1234",
520
713
  type: "formatter"
521
- }), increasedWord = declareFormatter({
714
+ });
715
+
716
+ // libs/formatters/increasedWord.js
717
+ var increasedWord_default = declareFormatter({
522
718
  name: "increasedWord",
523
719
  description: "Returns either 'increased', 'decreased', or 'remained the same' depending on the provided number's sign.",
524
720
  logicFactory(libs2) {
@@ -527,7 +723,10 @@ var growth = declareFormatter({
527
723
  inputType: "number",
528
724
  testValue: "0",
529
725
  type: "formatter"
530
- }), increasing = declareFormatter({
726
+ });
727
+
728
+ // libs/formatters/increasing.js
729
+ var increasing_default = declareFormatter({
531
730
  name: "increasing",
532
731
  description: "Returns either 'decreasing', 'increasing' or 'maintaining' depending on the provided number's sign.",
533
732
  logicFactory(libs2) {
@@ -536,7 +735,10 @@ var growth = declareFormatter({
536
735
  inputType: "number",
537
736
  testValue: "-1234",
538
737
  type: "formatter"
539
- }), largerThan = declareFormatter({
738
+ });
739
+
740
+ // libs/formatters/largerThan.js
741
+ var largerThan_default = declareFormatter({
540
742
  name: "largerThan",
541
743
  description: "Returns either 'higher than', 'lower than', or 'approximately the same as' depending on the provided number's sign",
542
744
  logicFactory(libs2) {
@@ -545,16 +747,32 @@ var growth = declareFormatter({
545
747
  inputType: "number",
546
748
  testValue: "-1234",
547
749
  type: "formatter"
548
- }), list = declareFormatter({
750
+ });
751
+
752
+ // libs/formatters/list.js
753
+ var list_default = declareFormatter({
549
754
  name: "list",
550
755
  description: "Joins an array of strings together, adding commas and 'and' when necessary.",
551
756
  logicFactory(libs2) {
552
- return (n) => n.reduce((str, item, i) => (i ? i === n.length - 1 && i === 1 ? str += ` and ${item}` : i === n.length - 1 ? str += `, and ${item}` : str += `, ${item}` : str += item, str), "");
757
+ return (n) => n.reduce((str, item, i) => {
758
+ if (!i)
759
+ str += item;
760
+ else if (i === n.length - 1 && i === 1)
761
+ str += ` and ${item}`;
762
+ else if (i === n.length - 1)
763
+ str += `, and ${item}`;
764
+ else
765
+ str += `, ${item}`;
766
+ return str;
767
+ }, "");
553
768
  },
554
769
  inputType: "object",
555
770
  testValue: '["foo","bar","bee"]',
556
771
  type: "formatter"
557
- }), longWord = declareFormatter({
772
+ });
773
+
774
+ // libs/formatters/longWord.js
775
+ var longWord_default = declareFormatter({
558
776
  name: "longWord",
559
777
  description: "",
560
778
  logicFactory(libs2) {
@@ -563,16 +781,22 @@ var growth = declareFormatter({
563
781
  inputType: "number",
564
782
  testValue: "5",
565
783
  type: "formatter"
566
- }), lowerCaseFirst = declareFormatter({
784
+ });
785
+
786
+ // libs/formatters/lowerCaseFirst.js
787
+ var lowerCaseFirst_default = declareFormatter({
567
788
  name: "lowerCaseFirst",
568
789
  description: "Converts the first letter of a string to lowercase",
569
790
  logicFactory(libs2) {
570
- return (n) => typeof n == "string" ? n.charAt(0).toLowerCase() + n.slice(1) : n;
791
+ return (n) => typeof n === "string" ? n.charAt(0).toLowerCase() + n.slice(1) : n;
571
792
  },
572
793
  inputType: "string",
573
794
  testValue: "foo",
574
795
  type: "formatter"
575
- }), moreFewerWord = declareFormatter({
796
+ });
797
+
798
+ // libs/formatters/moreFewerWord.js
799
+ var moreFewerWord_default = declareFormatter({
576
800
  name: "moreFewerWord",
577
801
  description: "",
578
802
  logicFactory(libs2) {
@@ -581,7 +805,10 @@ var growth = declareFormatter({
581
805
  inputType: "number",
582
806
  testValue: "-5",
583
807
  type: "formatter"
584
- }), moreLess = declareFormatter({
808
+ });
809
+
810
+ // libs/formatters/moreLess.js
811
+ var moreLess_default = declareFormatter({
585
812
  name: "moreLess",
586
813
  description: "Returns either 'more' or 'less' depending on the provided number's sign.",
587
814
  logicFactory(libs2) {
@@ -590,7 +817,10 @@ var growth = declareFormatter({
590
817
  inputType: "number",
591
818
  testValue: "-5",
592
819
  type: "formatter"
593
- }), moreWord = declareFormatter({
820
+ });
821
+
822
+ // libs/formatters/moreWord.js
823
+ var moreWord_default = declareFormatter({
594
824
  name: "moreLess",
595
825
  description: "Returns either 'more than', 'less than', or 'approximately the same' depending on the provided number's sign.",
596
826
  logicFactory(libs2) {
@@ -599,7 +829,10 @@ var growth = declareFormatter({
599
829
  inputType: "number",
600
830
  testValue: "-5",
601
831
  type: "formatter"
602
- }), olderWord = declareFormatter({
832
+ });
833
+
834
+ // libs/formatters/olderWord.js
835
+ var olderWord_default = declareFormatter({
603
836
  name: "olderWord",
604
837
  description: "",
605
838
  logicFactory(libs2) {
@@ -608,7 +841,10 @@ var growth = declareFormatter({
608
841
  inputType: "number",
609
842
  testValue: "-5",
610
843
  type: "formatter"
611
- }), olderYounger = declareFormatter({
844
+ });
845
+
846
+ // libs/formatters/olderYounger.js
847
+ var olderYounger_default = declareFormatter({
612
848
  name: "olderYounger",
613
849
  description: "",
614
850
  logicFactory(libs2) {
@@ -617,7 +853,10 @@ var growth = declareFormatter({
617
853
  inputType: "number",
618
854
  testValue: "-5",
619
855
  type: "formatter"
620
- }), plural = declareFormatter({
856
+ });
857
+
858
+ // libs/formatters/plural.js
859
+ var plural_default = declareFormatter({
621
860
  name: "plural",
622
861
  description: "Pluralizes a word.",
623
862
  logicFactory(libs2) {
@@ -626,7 +865,10 @@ var growth = declareFormatter({
626
865
  inputType: "string",
627
866
  testValue: "Foo",
628
867
  type: "formatter"
629
- }), pxToInt = declareFormatter({
868
+ });
869
+
870
+ // libs/formatters/pxToInt.js
871
+ var pxToInt_default = declareFormatter({
630
872
  name: "pxToInt",
631
873
  description: "Takes a pixel value and converts it to an integer",
632
874
  logicFactory(libs2) {
@@ -635,28 +877,41 @@ var growth = declareFormatter({
635
877
  inputType: "string",
636
878
  testValue: "12px",
637
879
  type: "formatter"
638
- }), salary = declareFormatter({
880
+ });
881
+
882
+ // libs/formatters/salary.js
883
+ var salary_default = declareFormatter({
639
884
  name: "salary",
640
885
  description: "Displays salary values with proper precision (ie. '$74,200' instead of '$74.2k')",
641
886
  logicFactory(libs2) {
642
887
  return (n) => {
643
888
  let str;
644
- return n < 1e6 ? str = libs2.d3.format(",")(n.toFixed(0)) : str = libs2.d3plus.formatAbbreviate(n), `$${str}`;
889
+ if (n < 1e6) {
890
+ str = libs2.d3.format(",")(n.toFixed(0));
891
+ } else
892
+ str = libs2.d3plus.formatAbbreviate(n);
893
+ return `$${str}`;
645
894
  };
646
895
  },
647
896
  inputType: "number",
648
897
  testValue: "1000000",
649
898
  type: "formatter"
650
- }), stripEntities$1 = declareFormatter({
899
+ });
900
+
901
+ // libs/formatters/stripEntities.js
902
+ var stripEntities_default = declareFormatter({
651
903
  name: "stripEntities",
652
904
  description: "Removes non breaking spaces & other html entities from a string",
653
905
  logicFactory(libs2) {
654
- return (n) => typeof n == "string" ? String(n).replace(/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});/ig, " ") : n;
906
+ return (n) => typeof n === "string" ? String(n).replace(/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});/ig, " ") : n;
655
907
  },
656
908
  inputType: "string",
657
909
  testValue: "<b>MyText</b>",
658
910
  type: "formatter"
659
- }), stripHTML$1 = declareFormatter({
911
+ });
912
+
913
+ // libs/formatters/stripHTML.js
914
+ var stripHTML_default = declareFormatter({
660
915
  name: "stripHTML",
661
916
  description: "Converts html tags to spaces, then removes redundant spaces",
662
917
  logicFactory(libs2) {
@@ -669,14 +924,21 @@ var growth = declareFormatter({
669
924
  "&#x27;": "'",
670
925
  "&#x60;": "`",
671
926
  "&nbsp;": ""
672
- }, source = `(?:${Object.keys(entities).join("|")})`, testRegexp = RegExp(source), replaceRegexp = RegExp(source, "g"), s = String(n).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
927
+ };
928
+ const source = `(?:${Object.keys(entities).join("|")})`;
929
+ const testRegexp = RegExp(source);
930
+ const replaceRegexp = RegExp(source, "g");
931
+ const s = String(n).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
673
932
  return testRegexp.test(s) ? s.replace(replaceRegexp, (match) => entities[match]) : s;
674
933
  };
675
934
  },
676
935
  inputType: "string",
677
936
  testValue: "<b>My text</b>",
678
937
  type: "formatter"
679
- }), stripOL = declareFormatter({
938
+ });
939
+
940
+ // libs/formatters/stripOL.js
941
+ var stripOL_default = declareFormatter({
680
942
  name: "stripOL",
681
943
  description: "Removes ordered list wrapper tags from a string.",
682
944
  logicFactory(libs2) {
@@ -685,7 +947,10 @@ var growth = declareFormatter({
685
947
  inputType: "string",
686
948
  testValue: "<ol><li>My list</li></ol>",
687
949
  type: "formatter"
688
- }), stripP = declareFormatter({
950
+ });
951
+
952
+ // libs/formatters/stripP.js
953
+ var stripP_default = declareFormatter({
689
954
  name: "stripP",
690
955
  description: "Removes all paragraph tags from a string.",
691
956
  logicFactory(libs2) {
@@ -694,7 +959,10 @@ var growth = declareFormatter({
694
959
  inputType: "string",
695
960
  testValue: "<p>My p</p>",
696
961
  type: "formatter"
697
- }), stripUL = declareFormatter({
962
+ });
963
+
964
+ // libs/formatters/stripUL.js
965
+ var stripUL_default = declareFormatter({
698
966
  name: "stripUL",
699
967
  description: "Removes unordered list wrapper tags from a string.",
700
968
  logicFactory(libs2) {
@@ -703,25 +971,45 @@ var growth = declareFormatter({
703
971
  inputType: "string",
704
972
  testValue: "<ul><li>My list</li></ul>",
705
973
  type: "formatter"
706
- }), toKebabCase = declareFormatter({
974
+ });
975
+
976
+ // libs/formatters/toKebabCase.js
977
+ var toKebabCase_default = declareFormatter({
707
978
  name: "toKebabCase",
708
979
  description: "Takes a camelCase or PascalCase string and converts it to kebab-case.",
709
980
  logicFactory(libs2) {
710
- return (n) => typeof n == "string" ? (n = n.charAt(0).toLowerCase() + n.substring(1), n.replace(/([A-Z])/g, "-$1").toLowerCase()) : "invalid string passed to toKebabCase()";
981
+ return (n) => {
982
+ if (typeof n === "string") {
983
+ n = n.charAt(0).toLowerCase() + n.substring(1);
984
+ return n.replace(/([A-Z])/g, "-$1").toLowerCase();
985
+ }
986
+ return "invalid string passed to toKebabCase()";
987
+ };
711
988
  },
712
989
  inputType: "string",
713
990
  testValue: "camelCaseText",
714
991
  type: "formatter"
715
- }), toSpacedCase = declareFormatter({
992
+ });
993
+
994
+ // libs/formatters/toSpacedCase.js
995
+ var toSpacedCase_default = declareFormatter({
716
996
  name: "toSpacedCase",
717
997
  description: "Takes a camelCase or PascalCase string and adds spaces (I know Spaced Case isn't a thing, deal with it).",
718
998
  logicFactory(libs2) {
719
- return (n) => typeof n == "string" ? n.replace(/([A-Z])/g, " $1").toLowerCase().trim() : "invalid string passed to toSpacedCase()";
999
+ return (n) => {
1000
+ if (typeof n === "string") {
1001
+ return n.replace(/([A-Z])/g, " $1").toLowerCase().trim();
1002
+ }
1003
+ return "invalid string passed to toSpacedCase()";
1004
+ };
720
1005
  },
721
1006
  inputType: "string",
722
1007
  testValue: "camelCaseText",
723
1008
  type: "formatter"
724
- }), upperCaseFirst = declareFormatter({
1009
+ });
1010
+
1011
+ // libs/formatters/upperCaseFirst.js
1012
+ var upperCaseFirst_default = declareFormatter({
725
1013
  name: "upperCaseFirst",
726
1014
  description: "Converts the first letter of a string to uppercase",
727
1015
  logicFactory(libs2) {
@@ -730,56 +1018,20 @@ var growth = declareFormatter({
730
1018
  inputType: "string",
731
1019
  testValue: "my name",
732
1020
  type: "formatter"
733
- }), formatters = /* @__PURE__ */ Object.freeze({
734
- __proto__: null,
735
- abbreviate,
736
- abs,
737
- bucket,
738
- commas,
739
- date,
740
- dollar,
741
- formatFieldName,
742
- grewTo,
743
- grewWord,
744
- growing,
745
- growth,
746
- growthPct,
747
- growthWord,
748
- highWord,
749
- increaseWord,
750
- increasedWord,
751
- increasing,
752
- largerThan,
753
- list,
754
- longWord,
755
- lowerCaseFirst,
756
- moreFewerWord,
757
- moreLess,
758
- moreWord,
759
- olderWord,
760
- olderYounger,
761
- plural,
762
- pxToInt,
763
- salary,
764
- stripEntities: stripEntities$1,
765
- stripHTML: stripHTML$1,
766
- stripOL,
767
- stripP,
768
- stripUL,
769
- toKebabCase,
770
- toSpacedCase,
771
- upperCaseFirst
772
1021
  });
773
- const verbose$3 = getLogging();
774
- verbose$3 && console.log(`Loaded formatters: ${Object.keys(formatters)}`);
775
- class FormatterModel extends Model {
776
- }
777
- function initModel$8(sequelize) {
778
- return FormatterModel.init({
1022
+
1023
+ // db/models/formatter.ts
1024
+ var verbose = getLogging_default();
1025
+ if (verbose)
1026
+ console.log(`Loaded formatters: ${Object.keys(formatters_exports)}`);
1027
+ var FormatterModel = class extends Model {
1028
+ };
1029
+ function initModel4(sequelize) {
1030
+ FormatterModel.init({
779
1031
  id: {
780
1032
  type: DataTypes.INTEGER,
781
- primaryKey: !0,
782
- autoIncrement: !0
1033
+ primaryKey: true,
1034
+ autoIncrement: true
783
1035
  },
784
1036
  name: {
785
1037
  type: DataTypes.STRING,
@@ -799,8 +1051,8 @@ function initModel$8(sequelize) {
799
1051
  sequelize,
800
1052
  modelName: "formatter",
801
1053
  tableName: "bespoke_reports_formatter",
802
- freezeTableName: !0,
803
- timestamps: !1,
1054
+ freezeTableName: true,
1055
+ timestamps: false,
804
1056
  hooks: {
805
1057
  async afterSync(options) {
806
1058
  const existingFormatters = await FormatterModel.findAll();
@@ -810,29 +1062,33 @@ function initModel$8(sequelize) {
810
1062
  }
811
1063
  }
812
1064
  }
813
- }), () => FormatterModel;
1065
+ });
1066
+ return () => FormatterModel;
814
1067
  }
815
- class ImageModel extends Model {
1068
+ var formatter_default = initModel4;
1069
+ var ImageModel = class extends Model {
816
1070
  getContent(locale) {
817
1071
  const { contentByLocale } = this;
818
- if (!contentByLocale)
1072
+ if (!contentByLocale) {
819
1073
  throw new Error("This ImageModel entity didn't include its ImageContentModel association.");
1074
+ }
820
1075
  const content = contentByLocale.find((item) => item.locale === locale);
821
- if (!content)
1076
+ if (!content) {
822
1077
  throw new Error(`Missing SearchContent for locale '${locale}' on Search ID '${this.id}'`);
1078
+ }
823
1079
  return content;
824
1080
  }
825
- }
826
- function initModel$7(sequelize) {
827
- return ImageModel.init({
1081
+ };
1082
+ function initModel5(sequelize) {
1083
+ ImageModel.init({
828
1084
  id: {
829
- autoIncrement: !0,
830
- primaryKey: !0,
1085
+ autoIncrement: true,
1086
+ primaryKey: true,
831
1087
  type: DataTypes.INTEGER
832
1088
  },
833
1089
  url: {
834
1090
  type: DataTypes.TEXT,
835
- unique: !0
1091
+ unique: true
836
1092
  },
837
1093
  author: DataTypes.TEXT,
838
1094
  license: DataTypes.TEXT,
@@ -842,20 +1098,25 @@ function initModel$7(sequelize) {
842
1098
  sequelize,
843
1099
  modelName: "image",
844
1100
  tableName: "bespoke_reports_image",
845
- freezeTableName: !0
846
- }), (models) => (ImageModel.hasMany(models.image_content, {
847
- foreignKey: "id",
848
- sourceKey: "id",
849
- as: "contentByLocale"
850
- }), ImageModel);
851
- }
852
- class ImageContentModel extends Model {
1101
+ freezeTableName: true
1102
+ });
1103
+ return (models) => {
1104
+ ImageModel.hasMany(models.image_content, {
1105
+ foreignKey: "id",
1106
+ sourceKey: "id",
1107
+ as: "contentByLocale"
1108
+ });
1109
+ return ImageModel;
1110
+ };
853
1111
  }
854
- function initModel$6(sequelize) {
855
- return ImageContentModel.init({
1112
+ var image_default = initModel5;
1113
+ var ImageContentModel = class extends Model {
1114
+ };
1115
+ function initModel6(sequelize) {
1116
+ ImageContentModel.init({
856
1117
  id: {
857
1118
  type: DataTypes.INTEGER,
858
- primaryKey: !0,
1119
+ primaryKey: true,
859
1120
  onDelete: "cascade",
860
1121
  references: {
861
1122
  model: "bespoke_reports_image",
@@ -864,51 +1125,47 @@ function initModel$6(sequelize) {
864
1125
  },
865
1126
  locale: {
866
1127
  type: DataTypes.STRING,
867
- primaryKey: !0
1128
+ primaryKey: true
868
1129
  },
869
1130
  meta: DataTypes.TEXT
870
1131
  }, {
871
1132
  sequelize,
872
1133
  modelName: "image_content",
873
1134
  tableName: "bespoke_reports_image_content",
874
- freezeTableName: !0,
875
- timestamps: !1
876
- }), () => ImageContentModel;
877
- }
878
- var __defProp$h = Object.defineProperty, __defProps$b = Object.defineProperties, __getOwnPropDescs$b = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$n = Object.getOwnPropertySymbols, __hasOwnProp$n = Object.prototype.hasOwnProperty, __propIsEnum$n = Object.prototype.propertyIsEnumerable, __defNormalProp$h = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$h = (a, b) => {
879
- for (var prop in b || (b = {}))
880
- __hasOwnProp$n.call(b, prop) && __defNormalProp$h(a, prop, b[prop]);
881
- if (__getOwnPropSymbols$n)
882
- for (var prop of __getOwnPropSymbols$n(b))
883
- __propIsEnum$n.call(b, prop) && __defNormalProp$h(a, prop, b[prop]);
884
- return a;
885
- }, __spreadProps$b = (a, b) => __defProps$b(a, __getOwnPropDescs$b(b));
886
- class ReportModel extends Model {
1135
+ freezeTableName: true,
1136
+ timestamps: false
1137
+ });
1138
+ return () => ImageContentModel;
1139
+ }
1140
+ var image_content_default = initModel6;
1141
+ var ReportModel = class extends Model {
887
1142
  toJSON() {
888
- const attributes = this.get({ plain: !0 }), { dimensions = [], sections = [] } = this;
889
- return __spreadProps$b(__spreadValues$h({}, attributes), {
1143
+ const attributes = this.get({ plain: true });
1144
+ const { dimensions = [], sections = [] } = this;
1145
+ return {
1146
+ ...attributes,
890
1147
  settings: attributes.settings,
891
1148
  date: new Date(this.date || Date.now()).toISOString(),
892
1149
  dimensions: dimensions.map((item) => item.toJSON()),
893
1150
  sections: sections.map((item) => item.toJSON())
894
- });
1151
+ };
895
1152
  }
896
- }
897
- function initModel$5(sequelize) {
898
- return ReportModel.init({
1153
+ };
1154
+ function initModel7(sequelize) {
1155
+ ReportModel.init({
899
1156
  id: {
900
1157
  type: DataTypes.INTEGER,
901
- primaryKey: !0,
902
- autoIncrement: !0
1158
+ primaryKey: true,
1159
+ autoIncrement: true
903
1160
  },
904
1161
  name: {
905
1162
  type: DataTypes.STRING,
906
- allowNull: !1,
1163
+ allowNull: false,
907
1164
  defaultValue: ""
908
1165
  },
909
1166
  visible: {
910
1167
  type: DataTypes.BOOLEAN,
911
- defaultValue: !0
1168
+ defaultValue: true
912
1169
  },
913
1170
  date: {
914
1171
  type: DataTypes.DATE,
@@ -929,40 +1186,40 @@ function initModel$5(sequelize) {
929
1186
  sequelize,
930
1187
  modelName: "report",
931
1188
  tableName: "bespoke_reports_report",
932
- freezeTableName: !0,
933
- timestamps: !1
934
- }), (models) => (ReportModel.hasMany(models.dimension, {
935
- foreignKey: "report_id",
936
- sourceKey: "id",
937
- as: "dimensions"
938
- }), ReportModel.hasMany(models.section, {
939
- foreignKey: "report_id",
940
- sourceKey: "id",
941
- as: "sections"
942
- }), ReportModel);
943
- }
944
- var __defProp$g = Object.defineProperty, __defProps$a = Object.defineProperties, __getOwnPropDescs$a = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$m = Object.getOwnPropertySymbols, __hasOwnProp$m = Object.prototype.hasOwnProperty, __propIsEnum$m = Object.prototype.propertyIsEnumerable, __defNormalProp$g = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$g = (a, b) => {
945
- for (var prop in b || (b = {}))
946
- __hasOwnProp$m.call(b, prop) && __defNormalProp$g(a, prop, b[prop]);
947
- if (__getOwnPropSymbols$m)
948
- for (var prop of __getOwnPropSymbols$m(b))
949
- __propIsEnum$m.call(b, prop) && __defNormalProp$g(a, prop, b[prop]);
950
- return a;
951
- }, __spreadProps$a = (a, b) => __defProps$a(a, __getOwnPropDescs$a(b));
952
- class DimensionModel extends Model {
1189
+ freezeTableName: true,
1190
+ timestamps: false
1191
+ });
1192
+ return (models) => {
1193
+ ReportModel.hasMany(models.dimension, {
1194
+ foreignKey: "report_id",
1195
+ sourceKey: "id",
1196
+ as: "dimensions"
1197
+ });
1198
+ ReportModel.hasMany(models.section, {
1199
+ foreignKey: "report_id",
1200
+ sourceKey: "id",
1201
+ as: "sections"
1202
+ });
1203
+ return ReportModel;
1204
+ };
1205
+ }
1206
+ var report_default = initModel7;
1207
+ var DimensionModel = class extends Model {
953
1208
  toJSON() {
954
- const attributes = this.get({ plain: !0 }), { variants = [] } = this;
955
- return __spreadProps$a(__spreadValues$g({}, attributes), {
1209
+ const attributes = this.get({ plain: true });
1210
+ const { variants = [] } = this;
1211
+ return {
1212
+ ...attributes,
956
1213
  variants: variants.map((item) => item.toJSON())
957
- });
1214
+ };
958
1215
  }
959
- }
960
- function initModel$4(sequelize) {
961
- return DimensionModel.init({
1216
+ };
1217
+ function initModel8(sequelize) {
1218
+ DimensionModel.init({
962
1219
  id: {
963
1220
  type: DataTypes.INTEGER,
964
- primaryKey: !0,
965
- autoIncrement: !0
1221
+ primaryKey: true,
1222
+ autoIncrement: true
966
1223
  },
967
1224
  report_id: {
968
1225
  type: DataTypes.INTEGER,
@@ -986,41 +1243,46 @@ function initModel$4(sequelize) {
986
1243
  },
987
1244
  visible: {
988
1245
  type: DataTypes.BOOLEAN,
989
- defaultValue: !0
1246
+ defaultValue: true
990
1247
  }
991
1248
  }, {
992
1249
  sequelize,
993
1250
  modelName: "dimension",
994
1251
  tableName: "bespoke_reports_report_dimension",
995
- freezeTableName: !0,
996
- timestamps: !1
997
- }), (models) => (DimensionModel.hasMany(models.variant, {
998
- foreignKey: "dimension_id",
999
- sourceKey: "id",
1000
- as: "variants",
1001
- constraints: !1
1002
- }), DimensionModel.belongsTo(models.report, {
1003
- foreignKey: "report_id",
1004
- targetKey: "id",
1005
- as: "report",
1006
- constraints: !1
1007
- }), DimensionModel);
1008
- }
1009
- class VariantModel extends Model {
1252
+ freezeTableName: true,
1253
+ timestamps: false
1254
+ });
1255
+ return (models) => {
1256
+ DimensionModel.hasMany(models.variant, {
1257
+ foreignKey: "dimension_id",
1258
+ sourceKey: "id",
1259
+ as: "variants",
1260
+ constraints: false
1261
+ });
1262
+ DimensionModel.belongsTo(models.report, {
1263
+ foreignKey: "report_id",
1264
+ targetKey: "id",
1265
+ as: "report",
1266
+ constraints: false
1267
+ });
1268
+ return DimensionModel;
1269
+ };
1270
+ }
1271
+ var report_dimension_default = initModel8;
1272
+ var VariantModel = class extends Model {
1010
1273
  get report() {
1011
- var _a;
1012
- return (_a = this.dimension) == null ? void 0 : _a.report;
1274
+ return this.dimension?.report;
1013
1275
  }
1014
1276
  toJSON() {
1015
- return this.get({ plain: !0 });
1277
+ return this.get({ plain: true });
1016
1278
  }
1017
- }
1018
- function initModel$3(sequelize) {
1019
- return VariantModel.init({
1279
+ };
1280
+ function initModel9(sequelize) {
1281
+ VariantModel.init({
1020
1282
  id: {
1021
1283
  type: DataTypes.INTEGER,
1022
- primaryKey: !0,
1023
- autoIncrement: !0
1284
+ primaryKey: true,
1285
+ autoIncrement: true
1024
1286
  },
1025
1287
  dimension_id: {
1026
1288
  type: DataTypes.INTEGER,
@@ -1048,41 +1310,49 @@ function initModel$3(sequelize) {
1048
1310
  },
1049
1311
  visible: {
1050
1312
  type: DataTypes.BOOLEAN,
1051
- defaultValue: !0
1313
+ defaultValue: true
1052
1314
  }
1053
1315
  }, {
1054
1316
  sequelize,
1055
1317
  modelName: "variant",
1056
1318
  tableName: "bespoke_reports_report_dimension_variant",
1057
- freezeTableName: !0,
1058
- timestamps: !1
1059
- }), (models) => (VariantModel.hasMany(models.search, {
1060
- foreignKey: "variant_id",
1061
- sourceKey: "id",
1062
- as: "members",
1063
- constraints: !1
1064
- }), VariantModel.belongsTo(models.dimension, {
1065
- foreignKey: "dimension_id",
1066
- targetKey: "id",
1067
- as: "dimension",
1068
- constraints: !1
1069
- }), VariantModel);
1070
- }
1071
- class SearchModel extends Model {
1319
+ freezeTableName: true,
1320
+ timestamps: false
1321
+ });
1322
+ return (models) => {
1323
+ VariantModel.hasMany(models.search, {
1324
+ foreignKey: "variant_id",
1325
+ sourceKey: "id",
1326
+ as: "members",
1327
+ constraints: false
1328
+ });
1329
+ VariantModel.belongsTo(models.dimension, {
1330
+ foreignKey: "dimension_id",
1331
+ targetKey: "id",
1332
+ as: "dimension",
1333
+ constraints: false
1334
+ });
1335
+ return VariantModel;
1336
+ };
1337
+ }
1338
+ var report_dimension_variant_default = initModel9;
1339
+ var SearchModel = class extends Model {
1072
1340
  getContent(locale) {
1073
1341
  const { contentByLocale } = this;
1074
- if (!contentByLocale)
1342
+ if (!contentByLocale) {
1075
1343
  throw new Error("This SearchModel entity didn't include its SearchContentModel association.");
1344
+ }
1076
1345
  const content = contentByLocale.find((item) => item.locale === locale);
1077
- if (!content)
1346
+ if (!content) {
1078
1347
  throw new Error(`Missing SearchContent for locale '${locale}' on Search ID '${this.id}'`);
1348
+ }
1079
1349
  return content;
1080
1350
  }
1081
- }
1082
- function initModel$2(sequelize) {
1083
- return SearchModel.init({
1351
+ };
1352
+ function initModel10(sequelize) {
1353
+ SearchModel.init({
1084
1354
  id: {
1085
- primaryKey: !0,
1355
+ primaryKey: true,
1086
1356
  type: DataTypes.TEXT
1087
1357
  },
1088
1358
  zvalue: DataTypes.DOUBLE,
@@ -1095,12 +1365,12 @@ function initModel$2(sequelize) {
1095
1365
  }
1096
1366
  },
1097
1367
  content_id: {
1098
- autoIncrement: !0,
1368
+ autoIncrement: true,
1099
1369
  type: DataTypes.INTEGER,
1100
- unique: !0
1370
+ unique: true
1101
1371
  },
1102
1372
  variant_id: {
1103
- primaryKey: !0,
1373
+ primaryKey: true,
1104
1374
  type: DataTypes.INTEGER,
1105
1375
  onDelete: "cascade",
1106
1376
  references: {
@@ -1109,7 +1379,7 @@ function initModel$2(sequelize) {
1109
1379
  }
1110
1380
  },
1111
1381
  dimension_id: {
1112
- primaryKey: !0,
1382
+ primaryKey: true,
1113
1383
  type: DataTypes.INTEGER,
1114
1384
  onDelete: "cascade",
1115
1385
  references: {
@@ -1118,7 +1388,7 @@ function initModel$2(sequelize) {
1118
1388
  }
1119
1389
  },
1120
1390
  report_id: {
1121
- primaryKey: !0,
1391
+ primaryKey: true,
1122
1392
  type: DataTypes.INTEGER,
1123
1393
  onDelete: "cascade",
1124
1394
  references: {
@@ -1128,47 +1398,56 @@ function initModel$2(sequelize) {
1128
1398
  },
1129
1399
  visible: {
1130
1400
  type: DataTypes.BOOLEAN,
1131
- defaultValue: !0
1401
+ defaultValue: true
1132
1402
  }
1133
1403
  }, {
1134
1404
  sequelize,
1135
1405
  modelName: "search",
1136
1406
  tableName: "bespoke_reports_search",
1137
- freezeTableName: !0,
1138
- timestamps: !1
1139
- }), (models) => (SearchModel.belongsTo(models.variant, {
1140
- foreignKey: "variant_id",
1141
- targetKey: "id",
1142
- as: "variant",
1143
- constraints: !1
1144
- }), SearchModel.belongsTo(models.dimension, {
1145
- foreignKey: "dimension_id",
1146
- targetKey: "id",
1147
- as: "dimension",
1148
- constraints: !1
1149
- }), SearchModel.belongsTo(models.report, {
1150
- foreignKey: "report_id",
1151
- targetKey: "id",
1152
- as: "report",
1153
- constraints: !1
1154
- }), SearchModel.belongsTo(models.image, {
1155
- foreignKey: "image_id",
1156
- targetKey: "id",
1157
- as: "image",
1158
- constraints: !1
1159
- }), SearchModel.hasMany(models.search_content, {
1160
- foreignKey: "id",
1161
- sourceKey: "content_id",
1162
- as: "contentByLocale"
1163
- }), SearchModel);
1164
- }
1165
- class SearchContentModel extends Model {
1166
- }
1167
- function initModel$1(sequelize) {
1168
- return SearchContentModel.init({
1407
+ freezeTableName: true,
1408
+ timestamps: false
1409
+ });
1410
+ return (models) => {
1411
+ SearchModel.belongsTo(models.variant, {
1412
+ foreignKey: "variant_id",
1413
+ targetKey: "id",
1414
+ as: "variant",
1415
+ constraints: false
1416
+ });
1417
+ SearchModel.belongsTo(models.dimension, {
1418
+ foreignKey: "dimension_id",
1419
+ targetKey: "id",
1420
+ as: "dimension",
1421
+ constraints: false
1422
+ });
1423
+ SearchModel.belongsTo(models.report, {
1424
+ foreignKey: "report_id",
1425
+ targetKey: "id",
1426
+ as: "report",
1427
+ constraints: false
1428
+ });
1429
+ SearchModel.belongsTo(models.image, {
1430
+ foreignKey: "image_id",
1431
+ targetKey: "id",
1432
+ as: "image",
1433
+ constraints: false
1434
+ });
1435
+ SearchModel.hasMany(models.search_content, {
1436
+ foreignKey: "id",
1437
+ sourceKey: "content_id",
1438
+ as: "contentByLocale"
1439
+ });
1440
+ return SearchModel;
1441
+ };
1442
+ }
1443
+ var search_default = initModel10;
1444
+ var SearchContentModel = class extends Model {
1445
+ };
1446
+ function initModel11(sequelize) {
1447
+ SearchContentModel.init({
1169
1448
  id: {
1170
1449
  type: DataTypes.INTEGER,
1171
- primaryKey: !0,
1450
+ primaryKey: true,
1172
1451
  onDelete: "cascade",
1173
1452
  references: {
1174
1453
  model: "bespoke_reports_search",
@@ -1177,7 +1456,7 @@ function initModel$1(sequelize) {
1177
1456
  },
1178
1457
  locale: {
1179
1458
  type: DataTypes.STRING,
1180
- primaryKey: !0
1459
+ primaryKey: true
1181
1460
  },
1182
1461
  name: DataTypes.TEXT,
1183
1462
  annotations: {
@@ -1193,32 +1472,28 @@ function initModel$1(sequelize) {
1193
1472
  sequelize,
1194
1473
  modelName: "search_content",
1195
1474
  tableName: "bespoke_reports_search_content",
1196
- freezeTableName: !0,
1197
- timestamps: !1
1198
- }), () => SearchContentModel;
1199
- }
1200
- var __defProp$f = Object.defineProperty, __defProps$9 = Object.defineProperties, __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$l = Object.getOwnPropertySymbols, __hasOwnProp$l = Object.prototype.hasOwnProperty, __propIsEnum$l = Object.prototype.propertyIsEnumerable, __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$f = (a, b) => {
1201
- for (var prop in b || (b = {}))
1202
- __hasOwnProp$l.call(b, prop) && __defNormalProp$f(a, prop, b[prop]);
1203
- if (__getOwnPropSymbols$l)
1204
- for (var prop of __getOwnPropSymbols$l(b))
1205
- __propIsEnum$l.call(b, prop) && __defNormalProp$f(a, prop, b[prop]);
1206
- return a;
1207
- }, __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b));
1208
- class SectionModel extends Model {
1475
+ freezeTableName: true,
1476
+ timestamps: false
1477
+ });
1478
+ return () => SearchContentModel;
1479
+ }
1480
+ var search_content_default = initModel11;
1481
+ var SectionModel = class extends Model {
1209
1482
  toJSON() {
1210
- const attributes = this.get({ plain: !0 }), { blocks = [] } = this;
1211
- return __spreadProps$9(__spreadValues$f({}, attributes), {
1483
+ const attributes = this.get({ plain: true });
1484
+ const { blocks = [] } = this;
1485
+ return {
1486
+ ...attributes,
1212
1487
  blocks: blocks.map((item) => item.toJSON())
1213
- });
1488
+ };
1214
1489
  }
1215
- }
1216
- function initModel(sequelize) {
1217
- return SectionModel.init({
1490
+ };
1491
+ function initModel12(sequelize) {
1492
+ SectionModel.init({
1218
1493
  id: {
1219
1494
  type: DataTypes.INTEGER,
1220
- primaryKey: !0,
1221
- autoIncrement: !0
1495
+ primaryKey: true,
1496
+ autoIncrement: true
1222
1497
  },
1223
1498
  settings: {
1224
1499
  type: DataTypes.JSON,
@@ -1241,42 +1516,60 @@ function initModel(sequelize) {
1241
1516
  sequelize,
1242
1517
  modelName: "section",
1243
1518
  tableName: "bespoke_reports_section",
1244
- freezeTableName: !0,
1245
- timestamps: !1
1246
- }), (models) => (SectionModel.hasMany(models.block, {
1247
- foreignKey: "section_id",
1248
- sourceKey: "id",
1249
- as: "blocks"
1250
- }), SectionModel);
1251
- }
1252
- const modelFactoryMap = {
1253
- block: initModel$b,
1254
- block_content: initModel$a,
1255
- block_input: initModel$9,
1256
- formatter: initModel$8,
1257
- image: initModel$7,
1258
- image_content: initModel$6,
1259
- report: initModel$5,
1260
- dimension: initModel$4,
1261
- variant: initModel$3,
1262
- search: initModel$2,
1263
- search_content: initModel$1,
1264
- section: initModel
1265
- }, verbose$2 = getLogging(), connectionString = process.env.REPORTS_DB_CONNECTION || "", shouldWipe = yn(process.env.REPORTS_DB_WIPE);
1266
- if (!connectionString)
1519
+ freezeTableName: true,
1520
+ timestamps: false
1521
+ });
1522
+ return (models) => {
1523
+ SectionModel.hasMany(models.block, {
1524
+ foreignKey: "section_id",
1525
+ sourceKey: "id",
1526
+ as: "blocks"
1527
+ });
1528
+ return SectionModel;
1529
+ };
1530
+ }
1531
+ var section_default = initModel12;
1532
+
1533
+ // db/models/index.ts
1534
+ var modelFactoryMap = {
1535
+ block: block_default,
1536
+ block_content: block_content_default,
1537
+ block_input: block_input_default,
1538
+ formatter: formatter_default,
1539
+ image: image_default,
1540
+ image_content: image_content_default,
1541
+ report: report_default,
1542
+ dimension: report_dimension_default,
1543
+ variant: report_dimension_variant_default,
1544
+ search: search_default,
1545
+ search_content: search_content_default,
1546
+ section: section_default
1547
+ };
1548
+
1549
+ // db/index.ts
1550
+ var verbose2 = getLogging_default();
1551
+ var connectionString = process.env.REPORTS_DB_CONNECTION || "";
1552
+ var shouldWipe = yn3(process.env.REPORTS_DB_WIPE);
1553
+ if (!connectionString) {
1267
1554
  throw new Error(`
1268
1555
  Env var 'REPORTS_DB_CONNECTION' is not present.
1269
1556
  This is required to connect to a database to save the Reports CMS changes.
1270
1557
  `);
1558
+ }
1271
1559
  function memoizeResult(factory) {
1272
1560
  let result;
1273
- return (...args) => (result = result || factory(...args), result);
1561
+ return (...args) => {
1562
+ result = result || factory(...args);
1563
+ return result;
1564
+ };
1274
1565
  }
1275
- const getDB = memoizeResult(() => {
1566
+ var getDB = memoizeResult(() => {
1276
1567
  let sequelize;
1277
1568
  try {
1278
- verbose$2 && console.log("INITIALIZING DB CONNECTION"), sequelize = new Sequelize(connectionString, {
1279
- logging: !1,
1569
+ if (verbose2)
1570
+ console.log("INITIALIZING DB CONNECTION");
1571
+ sequelize = new Sequelize(connectionString, {
1572
+ logging: false,
1280
1573
  dialectModule: pg
1281
1574
  });
1282
1575
  } catch (e) {
@@ -1287,32 +1580,38 @@ const getDB = memoizeResult(() => {
1287
1580
  ${e.message}
1288
1581
  `);
1289
1582
  }
1290
- return Object.values(modelFactoryMap).map((modelFactory) => modelFactory(sequelize)).map((modelAssociator) => modelAssociator(sequelize.models)), sequelize.sync({ force: shouldWipe }).catch((err) => {
1291
- throw err instanceof Error$1 && (console.error(
1292
- "=".repeat(40),
1293
- `
1294
- Error initializing sequelize connection:
1295
- `,
1296
- err.stack || err.message
1297
- ), process.exit(1)), err;
1583
+ Object.values(modelFactoryMap).map((modelFactory) => modelFactory(sequelize)).map((modelAssociator) => modelAssociator(sequelize.models));
1584
+ return sequelize.sync({ force: shouldWipe }).catch((err) => {
1585
+ if (err instanceof Error$1) {
1586
+ console.error(
1587
+ "=".repeat(40),
1588
+ "\nError initializing sequelize connection:\n",
1589
+ err.stack || err.message
1590
+ );
1591
+ process.exit(1);
1592
+ }
1593
+ throw err;
1298
1594
  }).then(() => sequelize.models);
1299
1595
  });
1300
- class BackendError extends Error {
1596
+
1597
+ // api/lib.ts
1598
+ var BackendError = class extends Error {
1301
1599
  constructor(code, message) {
1302
- super(message), this.code = code;
1600
+ super(message);
1601
+ this.code = code;
1303
1602
  }
1304
1603
  toJSON() {
1305
1604
  return failureResult(this);
1306
1605
  }
1307
1606
  static is(obj) {
1308
- return Object.prototype.hasOwnProperty.call(obj, "code") && typeof obj.code == "number";
1607
+ return Object.prototype.hasOwnProperty.call(obj, "code") && typeof obj.code === "number";
1309
1608
  }
1310
- }
1609
+ };
1311
1610
  function successResult(result) {
1312
- return { ok: !0, status: 200, data: result };
1611
+ return { ok: true, status: 200, data: result };
1313
1612
  }
1314
1613
  function failureResult(err) {
1315
- return { ok: !1, status: BackendError.is(err) ? err.code : 500, error: err.message };
1614
+ return { ok: false, status: BackendError.is(err) ? err.code : 500, error: err.message };
1316
1615
  }
1317
1616
  function resultWrapper(method) {
1318
1617
  return (param) => method(param).then(successResult, failureResult);
@@ -1324,12 +1623,20 @@ function pickMethod(api, operation, entity) {
1324
1623
  function capitalize(str) {
1325
1624
  return str[0].toUpperCase() + str.slice(1);
1326
1625
  }
1327
- var getLocales = () => {
1328
- var _a;
1329
- const localeDefault2 = process.env.NEXT_PUBLIC_REPORTS_LOCALE_DEFAULT || "en", locales2 = ((_a = process.env.NEXT_PUBLIC_REPORTS_LOCALES) == null ? void 0 : _a.split(",")) || [localeDefault2];
1330
- return locales2.includes(localeDefault2) || locales2.push(localeDefault2), { localeDefault: localeDefault2, locales: locales2 };
1626
+
1627
+ // libs/configs/getLocales.ts
1628
+ var getLocales_default = () => {
1629
+ const localeDefault5 = process.env.NEXT_PUBLIC_REPORTS_LOCALE_DEFAULT || "en";
1630
+ const locales6 = process.env.NEXT_PUBLIC_REPORTS_LOCALES?.split(",") || [localeDefault5];
1631
+ if (!locales6.includes(localeDefault5))
1632
+ locales6.push(localeDefault5);
1633
+ return { localeDefault: localeDefault5, locales: locales6 };
1331
1634
  };
1332
- const keyDiver = (obj, str) => str && typeof str == "string" ? str.split(".").reduce((o, i) => o[i], obj) : obj;
1635
+
1636
+ // libs/js/arrayUtils.ts
1637
+ var keyDiver = (obj, str) => !str ? obj : typeof str === "string" ? str.split(".").reduce((o, i) => o[i], obj) : obj;
1638
+
1639
+ // libs/js/stripHTML.ts
1333
1640
  function stripHTML(n) {
1334
1641
  const entities = {
1335
1642
  "&amp;": "&",
@@ -1339,43 +1646,60 @@ function stripHTML(n) {
1339
1646
  "&#x27;": "'",
1340
1647
  "&#x60;": "`",
1341
1648
  "&nbsp;": ""
1342
- }, source = `(?:${Object.keys(entities).join("|")})`, testRegexp = RegExp(source), replaceRegexp = RegExp(source, "g"), s = String(n).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
1649
+ };
1650
+ const source = `(?:${Object.keys(entities).join("|")})`;
1651
+ const testRegexp = RegExp(source);
1652
+ const replaceRegexp = RegExp(source, "g");
1653
+ const s = String(n).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
1343
1654
  return testRegexp.test(s) ? s.replace(replaceRegexp, (match) => entities[match]) : s;
1344
1655
  }
1656
+
1657
+ // libs/js/stripEntities.ts
1345
1658
  function stripEntities(n) {
1346
- return typeof n == "string" ? String(n).replace(/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});/ig, " ") : n;
1659
+ return typeof n === "string" ? String(n).replace(/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});/ig, " ") : n;
1347
1660
  }
1661
+
1662
+ // libs/js/slugify.ts
1348
1663
  function slugify(str) {
1349
- return str ? slugifyFn(
1664
+ if (!str)
1665
+ return "";
1666
+ return slugifyFn(
1350
1667
  stripEntities(stripHTML(str)),
1351
1668
  {
1352
1669
  replacement: "-",
1353
1670
  remove: /[*+~.()'"!:@]/g,
1354
- lower: !0,
1355
- strict: !0,
1356
- trim: !0
1671
+ lower: true,
1672
+ strict: true,
1673
+ trim: true
1357
1674
  }
1358
- ) : "";
1675
+ );
1359
1676
  }
1360
- const { localeDefault: localeDefault$3 } = getLocales();
1677
+ var slugify_default = slugify;
1678
+
1679
+ // api/db/member/ingestMembers.ts
1680
+ var { localeDefault } = getLocales_default();
1361
1681
  function ingestMembersFactory(db) {
1362
1682
  const { search: Search, search_content: SearchContent } = db;
1363
1683
  return ingestMembers;
1364
1684
  async function ingestMembers(variant) {
1365
- const { id, config = {} } = variant, defaultLocale = config[localeDefault$3] ? localeDefault$3 : Object.keys(config)[0], {
1685
+ const { id, config = {} } = variant;
1686
+ const defaultLocale = config[localeDefault] ? localeDefault : Object.keys(config)[0];
1687
+ const {
1366
1688
  accessor,
1367
1689
  path,
1368
1690
  idKey,
1369
1691
  labelKey
1370
- } = config[localeDefault$3];
1692
+ } = config[localeDefault];
1371
1693
  if (!path || !idKey || !labelKey)
1372
1694
  return;
1373
- const memberFetch = await axios.get(path).catch((e) => ({ data: [], error: e })), members = keyDiver(memberFetch.data, accessor);
1695
+ const memberFetch = await axios.get(path).catch((e) => ({ data: [], error: e }));
1696
+ const members = keyDiver(memberFetch.data, accessor);
1374
1697
  try {
1375
1698
  await ingestDefaultMembers(variant, defaultLocale, members);
1376
1699
  } catch (error) {
1377
1700
  const errorMsg = `[ERROR] Ingesting default member items for ${defaultLocale}`;
1378
- throw console.error(errorMsg, error), new BackendError(500, errorMsg);
1701
+ console.error(errorMsg, error);
1702
+ throw new BackendError(500, errorMsg);
1379
1703
  }
1380
1704
  const ingestions = Object.entries(config).map(async ([locale, config2]) => {
1381
1705
  const {
@@ -1387,9 +1711,12 @@ function ingestMembersFactory(db) {
1387
1711
  } = config2;
1388
1712
  if (!path2 || !idKey2 || !labelKey2)
1389
1713
  return;
1390
- const memberFetch2 = await axios.get(path2).catch((e) => ({ data: [], error: e })), members2 = keyDiver(memberFetch2.data, accessor2), contentHash = await Search.findAll({ where: { variant_id: id } }).then((arr) => Object.fromEntries(
1714
+ const memberFetch2 = await axios.get(path2).catch((e) => ({ data: [], error: e }));
1715
+ const members2 = keyDiver(memberFetch2.data, accessor2);
1716
+ const contentHash = await Search.findAll({ where: { variant_id: id } }).then((arr) => Object.fromEntries(
1391
1717
  arr.map((content) => [content.id, content.content_id])
1392
- )), contentMembers = members2.map((d) => ({
1718
+ ));
1719
+ const contentMembers = members2.map((d) => ({
1393
1720
  id: contentHash[d[idKey2]],
1394
1721
  locale,
1395
1722
  name: d[labelKey2],
@@ -1404,30 +1731,43 @@ function ingestMembersFactory(db) {
1404
1731
  await SearchContent.bulkCreate(contentMembers);
1405
1732
  } catch (error) {
1406
1733
  const errorMsg = `[ERROR] Ingesting search content items for ${locale}`;
1407
- throw console.error(errorMsg, error), new BackendError(500, errorMsg);
1734
+ console.error(errorMsg, error);
1735
+ throw new BackendError(500, errorMsg);
1408
1736
  }
1409
1737
  });
1410
1738
  await Promise.all(ingestions);
1411
1739
  }
1412
1740
  async function ingestDefaultMembers(variant, locale, members) {
1413
- const { id, dimension_id, slug } = variant, { report_id } = variant.dimension, { idKey, labelKey } = variant.config[locale], allSlugsFromOtherMembers = await Search.findAll({
1741
+ const { id, dimension_id, slug } = variant;
1742
+ const { report_id } = variant.dimension;
1743
+ const { idKey, labelKey } = variant.config[locale];
1744
+ const allSlugsFromOtherMembers = await Search.findAll({
1414
1745
  attributes: ["slug", [fn("COUNT", col("variant.id")), "slugCount"]],
1415
1746
  include: {
1416
1747
  association: "variant",
1417
1748
  attributes: [],
1418
- required: !1,
1419
- right: !0,
1420
- where: { dimension_id, slug }
1749
+ required: false,
1750
+ right: true,
1751
+ where: { dimension_id, slug, id: { [Op.not]: id } }
1421
1752
  },
1422
1753
  group: "search.slug"
1423
1754
  }).then((arr) => Object.fromEntries(arr.map((item) => {
1424
1755
  const count = item.getDataValue("slugCount");
1425
1756
  return [item.slug, Number.parseInt(`${count}`, 10)];
1426
- }))), searchMembers = members.map((member) => {
1427
- const slug2 = slugify(member[labelKey]), memberId = member[idKey];
1757
+ })));
1758
+ const toIngestSlugs = [];
1759
+ const searchMembers = members.map((member) => {
1760
+ const memberId = member[idKey];
1761
+ const slug2 = slugify_default(member[labelKey]);
1762
+ const hasDuplicateSlug = allSlugsFromOtherMembers[slug2] || toIngestSlugs.includes(slug2);
1763
+ if (hasDuplicateSlug) {
1764
+ console.log("Duplicate slug!", slug2, "replaced by", `${slug2}-${memberId}`);
1765
+ }
1766
+ const validateSlug = hasDuplicateSlug ? `${slug2}-${memberId}` : slug2;
1767
+ toIngestSlugs.push(slug2);
1428
1768
  return {
1429
1769
  id: memberId,
1430
- slug: allSlugsFromOtherMembers[slug2] > 1 ? `${slug2}-${memberId}` : slug2,
1770
+ slug: validateSlug,
1431
1771
  variant_id: id,
1432
1772
  dimension_id,
1433
1773
  report_id,
@@ -1435,47 +1775,51 @@ function ingestMembersFactory(db) {
1435
1775
  };
1436
1776
  });
1437
1777
  try {
1438
- await Search.destroy({ where: { variant_id: id } }), await Search.bulkCreate(searchMembers);
1778
+ await Search.destroy({ where: { variant_id: id } });
1779
+ await Search.bulkCreate(searchMembers);
1439
1780
  } catch (error) {
1440
- throw console.error(`[ERROR] Ingesting search members for ${locale}`, error), new Error(error);
1781
+ console.error(`[ERROR] Ingesting search members for ${locale}`, error);
1782
+ throw new Error(error);
1441
1783
  }
1442
1784
  }
1443
1785
  }
1444
- var __defProp$e = Object.defineProperty, __defProps$8 = Object.defineProperties, __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$k = Object.getOwnPropertySymbols, __hasOwnProp$k = Object.prototype.hasOwnProperty, __propIsEnum$k = Object.prototype.propertyIsEnumerable, __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$e = (a, b) => {
1445
- for (var prop in b || (b = {}))
1446
- __hasOwnProp$k.call(b, prop) && __defNormalProp$e(a, prop, b[prop]);
1447
- if (__getOwnPropSymbols$k)
1448
- for (var prop of __getOwnPropSymbols$k(b))
1449
- __propIsEnum$k.call(b, prop) && __defNormalProp$e(a, prop, b[prop]);
1450
- return a;
1451
- }, __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));
1452
1786
  function readMemberFactory(db) {
1453
1787
  const { search: Search } = db;
1454
1788
  return readMember;
1455
1789
  async function readMember(params) {
1456
- const {
1457
- mode,
1458
- ids,
1459
- slugs,
1460
- all,
1461
- locale
1462
- } = params, whereClause = {
1790
+ const { all, locale, mode } = params;
1791
+ const whereClause = {
1463
1792
  content_id: []
1464
1793
  };
1465
- if (mode === "ids")
1466
- whereClause.content_id = ids;
1467
- else if (mode === "slugs") {
1794
+ if (mode === "content_ids") {
1795
+ whereClause.content_id = params.content_ids;
1796
+ } else if (mode === "ids") {
1797
+ if (all) {
1798
+ throw new BackendError(404, "Search by ids doesn't support locale all. Pick one locale.");
1799
+ }
1468
1800
  const entities = await Search.findAll({
1469
1801
  attributes: ["content_id"],
1470
1802
  where: {
1471
- slug: slugs.map((item) => item.memberSlug)
1803
+ id: params.ids
1804
+ },
1805
+ include: [{
1806
+ association: "contentByLocale",
1807
+ where: { locale }
1808
+ }]
1809
+ });
1810
+ whereClause.content_id = entities.map((item) => item.content_id);
1811
+ } else if (mode === "slugs") {
1812
+ const entities = await Search.findAll({
1813
+ attributes: ["content_id"],
1814
+ where: {
1815
+ slug: params.slugs.map((item) => item.memberSlug)
1472
1816
  },
1473
1817
  include: {
1474
1818
  association: "variant",
1475
1819
  attributes: ["id", "name", "slug"],
1476
- required: !1,
1820
+ required: false,
1477
1821
  where: {
1478
- slug: slugs.map((item) => item.variantSlug)
1822
+ slug: params.slugs.map((item) => item.variantSlug)
1479
1823
  }
1480
1824
  }
1481
1825
  });
@@ -1483,7 +1827,8 @@ function readMemberFactory(db) {
1483
1827
  }
1484
1828
  const contentWhereClause = {
1485
1829
  locale: all ? { [Op.ne]: null } : locale
1486
- }, memberSearchResults = await Search.findAll({
1830
+ };
1831
+ const memberSearchResults = await Search.findAll({
1487
1832
  where: whereClause,
1488
1833
  include: [{
1489
1834
  association: "report",
@@ -1506,40 +1851,63 @@ function readMemberFactory(db) {
1506
1851
  where: contentWhereClause
1507
1852
  }]
1508
1853
  });
1509
- if (memberSearchResults.length !== (mode === "ids" ? ids.length : slugs.length))
1510
- throw new BackendError(404, "One of the members was not found.");
1854
+ if (memberSearchResults.length !== params[mode].length) {
1855
+ throw new BackendError(404, "One or more members were not found.");
1856
+ }
1511
1857
  memberSearchResults.sort(
1512
1858
  (a, b) => whereClause.content_id.indexOf(a.content_id) - whereClause.content_id.indexOf(b.content_id)
1513
1859
  );
1514
1860
  const normalizedResults = memberSearchResults.map((item) => {
1515
- const newItem = __spreadProps$8(__spreadValues$e({}, item.toJSON()), {
1861
+ const generalResult = {
1862
+ id: item.id,
1863
+ slug: item.slug,
1864
+ visible: item.visible,
1865
+ zvalue: item.zvalue,
1866
+ content_id: item.content_id,
1867
+ report_id: item.report_id,
1516
1868
  report_name: item.report.name,
1869
+ dimension_id: item.dimension_id,
1517
1870
  dimension_name: item.dimension.name,
1871
+ variant_id: item.variant_id,
1518
1872
  variant_name: item.variant.name,
1519
1873
  variant_slug: item.variant.slug
1520
- });
1874
+ };
1521
1875
  if (!all) {
1522
1876
  const localizedItem = item.getContent(locale);
1523
- if (newItem.locale = localizedItem.locale, newItem.name = localizedItem.name, newItem.attributes = localizedItem.attributes, newItem.keywords = localizedItem.keywords, delete newItem.contentByLocale, item.image) {
1524
- const localizedImage = item.image.getContent(locale);
1525
- newItem.image = __spreadProps$8(__spreadValues$e({}, item.image), {
1526
- meta: localizedImage.meta
1527
- }), delete newItem.image.contentByLocale;
1528
- }
1877
+ const localizedImage = item.image?.getContent(locale);
1878
+ const image = localizedImage && {
1879
+ id: item.image.id,
1880
+ author: item.image.author,
1881
+ url: item.image.url,
1882
+ license: item.image.license,
1883
+ meta: localizedImage.meta
1884
+ };
1885
+ const localizedResult = {
1886
+ ...generalResult,
1887
+ locale: localizedItem.locale,
1888
+ name: localizedItem.name,
1889
+ attributes: localizedItem.attributes,
1890
+ keywords: localizedItem.keywords,
1891
+ image: image || null,
1892
+ image_id: item.image_id
1893
+ };
1894
+ return localizedResult;
1895
+ } else {
1896
+ const contentByLocale = item.contentByLocale;
1897
+ generalResult.contentByLocale = contentByLocale;
1898
+ generalResult.image = item.image;
1899
+ generalResult.image_id = item.image_id;
1529
1900
  }
1530
- return delete newItem.report, delete newItem.dimension, delete newItem.variant, newItem;
1901
+ return generalResult;
1531
1902
  });
1532
1903
  return {
1533
- meta: {
1534
- locale: stripHTML(locale),
1535
- mode,
1536
- ids,
1537
- slugs
1538
- },
1904
+ meta: params,
1539
1905
  results: normalizedResults
1540
1906
  };
1541
1907
  }
1542
1908
  }
1909
+
1910
+ // api/db/member/readMemberImage.ts
1543
1911
  function readMemberImageFactory(db) {
1544
1912
  const { search: Search } = db;
1545
1913
  return readMemberImage;
@@ -1569,44 +1937,65 @@ function readMemberImageFactory(db) {
1569
1937
  ]
1570
1938
  });
1571
1939
  if (member && member.image) {
1572
- if (member.image[params.size])
1573
- return member.image[params.size];
1574
- } else
1575
- return Buffer.from(
1940
+ if (member.image[params.size]) {
1941
+ const image = member.image[params.size];
1942
+ return image;
1943
+ }
1944
+ } else {
1945
+ const emptyPixelImage = Buffer.from(
1576
1946
  "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkkAQAAB8AG7jymN8AAAAASUVORK5CYII=",
1577
1947
  "base64"
1578
1948
  );
1949
+ return emptyPixelImage;
1950
+ }
1579
1951
  throw new BackendError(404, "error in image, member not found");
1580
1952
  }
1581
1953
  }
1582
- require("lunr-languages/lunr.stemmer.support")(lunr);
1583
- const whitelist = ["ar", "da", "de", "du", "en", "es", "fi", "hi", "hu", "it", "ja", "jp", "nl", "no", "pt", "ro", "ru", "sv", "ta", "th", "tr", "vi", "zh"], verbose$1 = getLogging(), { locales: locales$4 } = getLocales(), enabledLocales = locales$4.filter((d) => whitelist.includes(d)), nonEnLocales = enabledLocales.filter((d) => whitelist.includes(d)).filter((d) => d !== "en");
1584
- for (const locale of nonEnLocales)
1585
- require(`lunr-languages/lunr.${locale}`)(lunr);
1586
- let search;
1587
- const getSearchIndexByLocale = async (db, forceRegenerate = !1) => {
1588
- if (forceRegenerate && (verbose$1 && console.log("REGENERATING SEARCH INDEX"), search = void 0), search)
1954
+ lunrStemmer(lunr);
1955
+ var whitelist = [
1956
+ "ar",
1957
+ "da",
1958
+ "de",
1959
+ "du",
1960
+ "en",
1961
+ "es",
1962
+ "fi",
1963
+ "hi",
1964
+ "hu",
1965
+ "it",
1966
+ "ja",
1967
+ "jp",
1968
+ "nl",
1969
+ "no",
1970
+ "pt",
1971
+ "ro",
1972
+ "ru",
1973
+ "sv",
1974
+ "ta",
1975
+ "th",
1976
+ "tr",
1977
+ "vi",
1978
+ "zh"
1979
+ ];
1980
+ var verbose3 = getLogging_default();
1981
+ var { locales } = getLocales_default();
1982
+ var enabledLocales = locales.filter((d) => whitelist.includes(d));
1983
+ var search;
1984
+ var initializing = false;
1985
+ var getSearchIndexByLocale = async (db, forceRegenerate = false) => {
1986
+ if (forceRegenerate) {
1987
+ if (verbose3)
1988
+ console.log("REGENERATING SEARCH INDEX");
1989
+ search = void 0;
1990
+ initializing = false;
1991
+ }
1992
+ if (search)
1589
1993
  return search;
1590
1994
  try {
1591
- verbose$1 && console.log("INITIALIZING SEARCH INDEX");
1592
- const results = await db.search.findAll({ include: [{ association: "contentByLocale" }] }).then((arr) => arr.map((d) => d.toJSON())).catch(() => []), searchIndexByLocale = {};
1593
- for (const locale of enabledLocales)
1594
- searchIndexByLocale[locale] = lunr(function() {
1595
- locale && locale !== "en" && this.use(lunr[locale]), this.ref("content_id"), this.field("id"), this.field("name"), this.field("keywords"), this.field("attr"), this.pipeline.reset(), this.searchPipeline.reset(), results.forEach((result) => {
1596
- const content = result.contentByLocale.find((d) => d.locale === locale);
1597
- if (content) {
1598
- const payload = {
1599
- id: result.id,
1600
- content_id: result.content_id,
1601
- name: content.name,
1602
- keywords: content.keywords,
1603
- attributes: content.attributes
1604
- };
1605
- this.add(payload, { boost: result.zvalue });
1606
- }
1607
- }, this);
1608
- });
1609
- search = searchIndexByLocale;
1995
+ if (!initializing) {
1996
+ initializing = true;
1997
+ search = await newSearchIndex(db);
1998
+ }
1610
1999
  } catch (e) {
1611
2000
  throw new Error(`
1612
2001
  Could not initialize Lunr search engine.
@@ -1616,20 +2005,55 @@ const getSearchIndexByLocale = async (db, forceRegenerate = !1) => {
1616
2005
  }
1617
2006
  return search;
1618
2007
  };
1619
- var __defProp$d = Object.defineProperty, __defProps$7 = Object.defineProperties, __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$j = Object.getOwnPropertySymbols, __hasOwnProp$j = Object.prototype.hasOwnProperty, __propIsEnum$j = Object.prototype.propertyIsEnumerable, __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$d = (a, b) => {
1620
- for (var prop in b || (b = {}))
1621
- __hasOwnProp$j.call(b, prop) && __defNormalProp$d(a, prop, b[prop]);
1622
- if (__getOwnPropSymbols$j)
1623
- for (var prop of __getOwnPropSymbols$j(b))
1624
- __propIsEnum$j.call(b, prop) && __defNormalProp$d(a, prop, b[prop]);
1625
- return a;
1626
- }, __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
1627
- const { localeDefault: localeDefault$2 } = getLocales();
2008
+ async function newSearchIndex(db) {
2009
+ if (verbose3)
2010
+ console.log("INITIALIZING SEARCH INDEX");
2011
+ const results = await db.search.findAll({
2012
+ include: [{ association: "contentByLocale" }]
2013
+ });
2014
+ const setups = enabledLocales.map(async (locale) => {
2015
+ if (!lunr[locale] && whitelist.includes(locale) && locale !== "en") {
2016
+ const lunrLang = (await import(`lunr-languages/lunr.${locale}`)).default;
2017
+ lunrLang(lunr);
2018
+ }
2019
+ return [locale, lunr(function() {
2020
+ if (locale && locale !== "en")
2021
+ this.use(lunr[locale]);
2022
+ this.ref("content_id");
2023
+ this.field("id");
2024
+ this.field("name");
2025
+ this.field("keywords");
2026
+ this.field("attr");
2027
+ this.pipeline.reset();
2028
+ this.searchPipeline.reset();
2029
+ results.forEach((result) => {
2030
+ const content = result.contentByLocale.find((d) => d.locale === locale);
2031
+ if (content) {
2032
+ const payload = {
2033
+ id: result.id,
2034
+ content_id: result.content_id,
2035
+ name: content.name,
2036
+ keywords: content.keywords,
2037
+ attributes: content.attributes
2038
+ };
2039
+ this.add(payload, { boost: result.zvalue });
2040
+ }
2041
+ }, this);
2042
+ })];
2043
+ });
2044
+ return Object.fromEntries(
2045
+ await Promise.all(setups)
2046
+ );
2047
+ }
2048
+ var search_default2 = getSearchIndexByLocale;
2049
+
2050
+ // api/db/member/searchMember.ts
2051
+ var { localeDefault: localeDefault2 } = getLocales_default();
1628
2052
  function dbSearchMemberFactory(db) {
1629
2053
  const { search: Search } = db;
1630
2054
  return searchMember;
1631
2055
  async function searchMember(params) {
1632
- const searchIndexByLocale = await getSearchIndexByLocale(db);
2056
+ const searchIndexByLocale = await search_default2(db);
1633
2057
  let resultsIds = [];
1634
2058
  const {
1635
2059
  query,
@@ -1648,40 +2072,56 @@ function dbSearchMemberFactory(db) {
1648
2072
  } = params;
1649
2073
  if (query && query !== "" && searchIndexByLocale[locale]) {
1650
2074
  const terms = query.split(" ").map((d) => `+${d}*`).join(" ");
1651
- resultsIds = searchIndexByLocale[locale].search(terms).map((d) => parseInt(d.ref, 10));
2075
+ const lunrResults = searchIndexByLocale[locale].search(terms);
2076
+ resultsIds = lunrResults.map((d) => parseInt(d.ref, 10));
1652
2077
  }
1653
- const whereClause = __spreadValues$d(__spreadValues$d(__spreadValues$d(__spreadValues$d(__spreadValues$d({}, visible ? { visible } : {}), noImage ? { image_id: { [Op.eq]: null } } : {}), variant.length ? { variant_id: variant } : {}), dimension.length ? { dimension_id: dimension } : {}), report.length ? { report_id: report } : {}), contentWhereClause = {
2078
+ const whereClause = {
2079
+ ...visible ? { visible } : {},
2080
+ ...noImage ? { image_id: { [Op.eq]: null } } : {},
2081
+ ...variant.length ? { variant_id: variant } : {},
2082
+ ...dimension.length ? { dimension_id: dimension } : {},
2083
+ ...report.length ? { report_id: report } : {}
2084
+ };
2085
+ const contentWhereClause = {
1654
2086
  locale: all ? { [Op.ne]: null } : locale
1655
2087
  };
1656
- query === "" && (resultsIds = (await Search.findAll({
1657
- attributes: [
1658
- "id",
1659
- "content_id",
1660
- "report_id",
1661
- [literal("rank() over(partition by report_id order by zvalue desc)"), "rank"]
1662
- ],
1663
- where: whereClause,
1664
- include: [{
1665
- association: "contentByLocale",
1666
- where: contentWhereClause
1667
- }]
1668
- }).then((arr) => arr.map((d) => d.toJSON()))).filter((item) => parseInt(item.rank, 10) <= limit).map((d) => d.content_id)), whereClause.content_id = resultsIds;
2088
+ if (query === "") {
2089
+ const rank = await Search.findAll({
2090
+ attributes: [
2091
+ "id",
2092
+ "content_id",
2093
+ "report_id",
2094
+ [literal("rank() over(partition by report_id order by zvalue desc)"), "rank"]
2095
+ ],
2096
+ where: whereClause,
2097
+ include: [{
2098
+ association: "contentByLocale",
2099
+ where: contentWhereClause
2100
+ }]
2101
+ }).then((arr) => arr.map((d) => d.toJSON()));
2102
+ resultsIds = rank.filter((item) => parseInt(item["rank"], 10) <= limit).map((d) => d.content_id);
2103
+ }
2104
+ whereClause.content_id = resultsIds;
1669
2105
  const includeClause = [{
1670
2106
  association: "contentByLocale",
1671
2107
  where: contentWhereClause
1672
2108
  }];
1673
- includes && includeClause.push({
1674
- association: "report",
1675
- attributes: ["id", "name"]
1676
- }, {
1677
- association: "dimension",
1678
- attributes: ["id", "name"]
1679
- }, {
1680
- association: "variant",
1681
- attributes: ["id", "slug", "name"]
1682
- });
2109
+ if (includes) {
2110
+ includeClause.push({
2111
+ association: "report",
2112
+ attributes: ["id", "name"]
2113
+ }, {
2114
+ association: "dimension",
2115
+ attributes: ["id", "name"]
2116
+ }, {
2117
+ association: "variant",
2118
+ attributes: ["id", "slug", "name"]
2119
+ });
2120
+ }
1683
2121
  const orderClause = [["zvalue", "DESC NULLS LAST"]];
1684
- sort && sort !== "name" && orderClause.unshift([sort, direction.toUpperCase()]);
2122
+ if (sort && sort !== "name") {
2123
+ orderClause.unshift([sort, direction.toUpperCase()]);
2124
+ }
1685
2125
  const results = await Search.findAll({
1686
2126
  limit: query ? limit : void 0,
1687
2127
  where: whereClause,
@@ -1691,17 +2131,22 @@ function dbSearchMemberFactory(db) {
1691
2131
  if (sort === "name") {
1692
2132
  const sortDirection = direction.toUpperCase() === "ASC" ? 1 : -1;
1693
2133
  results.sort((a, b) => {
1694
- const aValue = a.getContent(localeDefault$2), bValue = b.getContent(localeDefault$2);
1695
- return aValue && bValue ? aValue.name > bValue.name ? 1 * sortDirection : -1 * sortDirection : 0;
2134
+ const aValue = a.getContent(localeDefault2);
2135
+ const bValue = b.getContent(localeDefault2);
2136
+ if (aValue && bValue) {
2137
+ return aValue.name > bValue.name ? 1 * sortDirection : -1 * sortDirection;
2138
+ }
2139
+ return 0;
1696
2140
  });
1697
2141
  }
1698
2142
  const resultFormatter = format === "nested" ? nestedFormatter : plainFormatter;
1699
2143
  return {
1700
- meta: __spreadValues$d({
1701
- origin: "lunr"
1702
- }, Object.fromEntries(
1703
- Object.entries(params).map((entry) => [entry[0], stripHTML(entry[1])])
1704
- )),
2144
+ meta: {
2145
+ origin: "lunr",
2146
+ ...Object.fromEntries(
2147
+ Object.entries(params).map((entry) => [entry[0], stripHTML(entry[1])])
2148
+ )
2149
+ },
1705
2150
  results: results.map(resultFormatter)
1706
2151
  };
1707
2152
  function nestedFormatter(item) {
@@ -1709,23 +2154,18 @@ function dbSearchMemberFactory(db) {
1709
2154
  }
1710
2155
  function plainFormatter(item) {
1711
2156
  const localizedItem = item.getContent(locale);
1712
- return __spreadProps$7(__spreadValues$d({}, item.toJSON()), {
2157
+ return {
2158
+ ...item.toJSON(),
1713
2159
  locale: localizedItem.locale,
1714
2160
  name: localizedItem.name,
1715
2161
  attributes: localizedItem.attributes,
1716
2162
  keywords: localizedItem.keywords
1717
- });
2163
+ };
1718
2164
  }
1719
2165
  }
1720
2166
  }
1721
- var __defProp$c = Object.defineProperty, __getOwnPropSymbols$i = Object.getOwnPropertySymbols, __hasOwnProp$i = Object.prototype.hasOwnProperty, __propIsEnum$i = Object.prototype.propertyIsEnumerable, __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$c = (a, b) => {
1722
- for (var prop in b || (b = {}))
1723
- __hasOwnProp$i.call(b, prop) && __defNormalProp$c(a, prop, b[prop]);
1724
- if (__getOwnPropSymbols$i)
1725
- for (var prop of __getOwnPropSymbols$i(b))
1726
- __propIsEnum$i.call(b, prop) && __defNormalProp$c(a, prop, b[prop]);
1727
- return a;
1728
- };
2167
+
2168
+ // api/db/member/updateMember.ts
1729
2169
  function updateMemberFactory(db) {
1730
2170
  const {
1731
2171
  image: Image,
@@ -1743,7 +2183,8 @@ function updateMemberFactory(db) {
1743
2183
  } = params;
1744
2184
  let returnQuery = { where: { content_id } };
1745
2185
  const oldRecord = await Search.findOne(returnQuery);
1746
- if (await Search.update(params, { where: { content_id } }), contentByLocale) {
2186
+ await Search.update(params, { where: { content_id } });
2187
+ if (contentByLocale) {
1747
2188
  for (let index = 0; index < contentByLocale.length; index++) {
1748
2189
  const searchContent = contentByLocale[index];
1749
2190
  await SearchContent.update({
@@ -1753,28 +2194,40 @@ function updateMemberFactory(db) {
1753
2194
  }
1754
2195
  const relevantInclude = {
1755
2196
  include: [
1756
- { association: "contentByLocale", separate: !0 }
2197
+ { association: "contentByLocale", separate: true }
1757
2198
  ]
1758
2199
  };
1759
- returnQuery = __spreadValues$c(__spreadValues$c({}, returnQuery), relevantInclude);
2200
+ returnQuery = { ...returnQuery, ...relevantInclude };
1760
2201
  }
1761
2202
  if (image) {
1762
- if (image.id && (await Image.update(__spreadValues$c({}, image), { where: { id: image.id } }), image.contentByLocale))
1763
- for (let index = 0; index < image.contentByLocale.length; index++) {
1764
- const imageContent = image.contentByLocale[index];
1765
- await ImageContent.update({
1766
- meta: imageContent.meta
1767
- }, { where: { id: imageContent.id, locale: imageContent.locale } });
2203
+ if (image.id) {
2204
+ await Image.update({
2205
+ ...image
2206
+ }, { where: { id: image.id } });
2207
+ if (image.contentByLocale) {
2208
+ for (let index = 0; index < image.contentByLocale.length; index++) {
2209
+ const imageContent = image.contentByLocale[index];
2210
+ await ImageContent.update({
2211
+ meta: imageContent.meta
2212
+ }, { where: { id: imageContent.id, locale: imageContent.locale } });
2213
+ }
1768
2214
  }
1769
- } else
1770
- !image_id && oldRecord.image_id && (await db.search.findAll({
2215
+ }
2216
+ } else if (!image_id && oldRecord.image_id) {
2217
+ const othersMembersSameImage = await db.search.findAll({
1771
2218
  where: { image_id: oldRecord.image_id }
1772
- })).length === 0 && await Image.destroy({
1773
- where: { id: oldRecord.image_id }
1774
2219
  });
2220
+ if (othersMembersSameImage.length === 0) {
2221
+ await Image.destroy({
2222
+ where: { id: oldRecord.image_id }
2223
+ });
2224
+ }
2225
+ }
1775
2226
  return Search.findOne(returnQuery);
1776
2227
  }
1777
2228
  }
2229
+
2230
+ // api/db/member/index.ts
1778
2231
  function dbMemberFactory(db) {
1779
2232
  return {
1780
2233
  ingestMembers: ingestMembersFactory(db),
@@ -1784,34 +2237,32 @@ function dbMemberFactory(db) {
1784
2237
  readMemberImage: readMemberImageFactory(db)
1785
2238
  };
1786
2239
  }
1787
- var __defProp$b = Object.defineProperty, __getOwnPropSymbols$h = Object.getOwnPropertySymbols, __hasOwnProp$h = Object.prototype.hasOwnProperty, __propIsEnum$h = Object.prototype.propertyIsEnumerable, __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$b = (a, b) => {
1788
- for (var prop in b || (b = {}))
1789
- __hasOwnProp$h.call(b, prop) && __defNormalProp$b(a, prop, b[prop]);
1790
- if (__getOwnPropSymbols$h)
1791
- for (var prop of __getOwnPropSymbols$h(b))
1792
- __propIsEnum$h.call(b, prop) && __defNormalProp$b(a, prop, b[prop]);
1793
- return a;
1794
- };
1795
- const blockQuery = {
2240
+
2241
+ // api/db/include.ts
2242
+ var blockQuery = {
1796
2243
  include: [
1797
- { association: "contentByLocale", separate: !0 },
2244
+ { association: "contentByLocale", separate: true },
1798
2245
  { association: "inputs" },
1799
2246
  { association: "consumers" }
1800
2247
  ]
1801
- }, dimensionQuery = {
2248
+ };
2249
+ var dimensionQuery = {
1802
2250
  include: [
1803
- { association: "variants", separate: !0 }
2251
+ { association: "variants", separate: true }
1804
2252
  ]
1805
- }, sectionQuery = {
2253
+ };
2254
+ var sectionQuery = {
1806
2255
  include: [
1807
- __spreadValues$b({ association: "blocks", separate: !0 }, blockQuery)
2256
+ { association: "blocks", separate: true, ...blockQuery }
1808
2257
  ]
1809
- }, reportQuery = {
2258
+ };
2259
+ var reportQuery = {
1810
2260
  include: [
1811
- __spreadValues$b({ association: "dimensions", separate: !0 }, dimensionQuery),
1812
- __spreadValues$b({ association: "sections", separate: !0 }, sectionQuery)
2261
+ { association: "dimensions", separate: true, ...dimensionQuery },
2262
+ { association: "sections", separate: true, ...sectionQuery }
1813
2263
  ]
1814
- }, imageQueryThumbOnly = [
2264
+ };
2265
+ var imageQueryThumbOnly = [
1815
2266
  {
1816
2267
  association: "image",
1817
2268
  attributes: {
@@ -1823,22 +2274,8 @@ const blockQuery = {
1823
2274
  },
1824
2275
  { association: "contentByLocale" }
1825
2276
  ];
1826
- var __defProp$a = Object.defineProperty, __defProps$6 = Object.defineProperties, __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$g = Object.getOwnPropertySymbols, __hasOwnProp$g = Object.prototype.hasOwnProperty, __propIsEnum$g = Object.prototype.propertyIsEnumerable, __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$a = (a, b) => {
1827
- for (var prop in b || (b = {}))
1828
- __hasOwnProp$g.call(b, prop) && __defNormalProp$a(a, prop, b[prop]);
1829
- if (__getOwnPropSymbols$g)
1830
- for (var prop of __getOwnPropSymbols$g(b))
1831
- __propIsEnum$g.call(b, prop) && __defNormalProp$a(a, prop, b[prop]);
1832
- return a;
1833
- }, __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b)), __objRest$6 = (source, exclude) => {
1834
- var target = {};
1835
- for (var prop in source)
1836
- __hasOwnProp$g.call(source, prop) && exclude.indexOf(prop) < 0 && (target[prop] = source[prop]);
1837
- if (source != null && __getOwnPropSymbols$g)
1838
- for (var prop of __getOwnPropSymbols$g(source))
1839
- exclude.indexOf(prop) < 0 && __propIsEnum$g.call(source, prop) && (target[prop] = source[prop]);
1840
- return target;
1841
- };
2277
+
2278
+ // api/db/entityCRUD/block.ts
1842
2279
  function dbBlockFactory(db) {
1843
2280
  const { block: Block, block_content: BlockContent, block_input: BlockInput } = db;
1844
2281
  return {
@@ -1848,64 +2285,69 @@ function dbBlockFactory(db) {
1848
2285
  deleteBlock
1849
2286
  };
1850
2287
  async function createBlock(data) {
1851
- const _a = data, { locale } = _a, blockData = __objRest$6(_a, ["locale"]);
1852
- return (await Block.create(__spreadProps$6(__spreadValues$a({}, blockData), {
2288
+ const { locale, ...blockData } = data;
2289
+ const entity = await Block.create({
2290
+ ...blockData,
1853
2291
  consumers: [],
1854
2292
  inputs: [],
1855
2293
  contentByLocale: [{ locale }]
1856
- }), {
2294
+ }, {
1857
2295
  include: blockQuery.include
1858
- })).toJSON();
2296
+ });
2297
+ return entity.toJSON();
1859
2298
  }
1860
2299
  async function readBlock({ id, include } = {}) {
1861
- const idList = id == null ? [] : [].concat(id), entities = await Block.findAll({
2300
+ const idList = id == null ? [] : [].concat(id);
2301
+ const entities = await Block.findAll({
1862
2302
  where: idList.length > 0 ? { id: idList } : void 0,
1863
2303
  include: include ? blockQuery.include : void 0
1864
2304
  });
1865
- if (idList.length === 0 || entities.length === idList.length)
2305
+ if (idList.length === 0 || entities.length === idList.length) {
1866
2306
  return entities.map((entity) => entity.toJSON());
1867
- const found = entities.map((entity) => entity.id), missing = idList.filter((item) => !found.includes(item));
2307
+ }
2308
+ const found = entities.map((entity) => entity.id);
2309
+ const missing = idList.filter((item) => !found.includes(item));
1868
2310
  throw new BackendError(404, `Block(id=[${missing}]) does not exist.`);
1869
2311
  }
1870
2312
  async function updateBlock(data) {
1871
- const _a = data, {
2313
+ const {
1872
2314
  id,
1873
2315
  contentByLocale,
1874
2316
  consumers,
1875
2317
  inputs,
1876
- inputAction
1877
- } = _a, blockData = __objRest$6(_a, [
1878
- "id",
1879
- "contentByLocale",
1880
- "consumers",
1881
- "inputs",
1882
- "inputAction"
1883
- ]), entity = await Block.findByPk(id, {
2318
+ inputAction,
2319
+ ...blockData
2320
+ } = data;
2321
+ const entity = await Block.findByPk(id, {
1884
2322
  include: blockQuery.include,
1885
- rejectOnEmpty: !0
2323
+ rejectOnEmpty: true
1886
2324
  });
1887
- if (entity.set(blockData), contentByLocale) {
2325
+ entity.set(blockData);
2326
+ if (contentByLocale) {
1888
2327
  const contentList = Object.values(contentByLocale);
1889
2328
  await BlockContent.bulkCreate(contentList, {
1890
2329
  updateOnDuplicate: ["content"]
1891
2330
  });
1892
2331
  }
1893
- return inputAction && (inputAction.operation === "create" ? await BlockInput.create(inputAction.input) : await BlockInput.destroy({ where: inputAction.input })), await entity.save(), await entity.reload(), entity.toJSON();
2332
+ if (inputAction) {
2333
+ if (inputAction.operation === "create") {
2334
+ await BlockInput.create(inputAction.input);
2335
+ } else {
2336
+ await BlockInput.destroy({ where: inputAction.input });
2337
+ }
2338
+ }
2339
+ await entity.save();
2340
+ await entity.reload();
2341
+ return entity.toJSON();
1894
2342
  }
1895
2343
  async function deleteBlock(id) {
1896
- const entity = await Block.findByPk(id, { rejectOnEmpty: !0 });
1897
- return await entity.destroy(), { id, parentType: "section", parentId: entity.section_id };
1898
- }
1899
- }
1900
- var __getOwnPropSymbols$f = Object.getOwnPropertySymbols, __hasOwnProp$f = Object.prototype.hasOwnProperty, __propIsEnum$f = Object.prototype.propertyIsEnumerable, __objRest$5 = (source, exclude) => {
1901
- var target = {};
1902
- for (var prop in source)
1903
- __hasOwnProp$f.call(source, prop) && exclude.indexOf(prop) < 0 && (target[prop] = source[prop]);
1904
- if (source != null && __getOwnPropSymbols$f)
1905
- for (var prop of __getOwnPropSymbols$f(source))
1906
- exclude.indexOf(prop) < 0 && __propIsEnum$f.call(source, prop) && (target[prop] = source[prop]);
1907
- return target;
1908
- };
2344
+ const entity = await Block.findByPk(id, { rejectOnEmpty: true });
2345
+ await entity.destroy();
2346
+ return { id, parentType: "section", parentId: entity.section_id };
2347
+ }
2348
+ }
2349
+
2350
+ // api/db/entityCRUD/dimension.ts
1909
2351
  function dbDimensionFactory(db) {
1910
2352
  const { dimension: Dimension } = db;
1911
2353
  return {
@@ -1915,45 +2357,46 @@ function dbDimensionFactory(db) {
1915
2357
  deleteDimension
1916
2358
  };
1917
2359
  async function createDimension(data) {
1918
- return (await Dimension.create({
2360
+ const entity = await Dimension.create({
1919
2361
  name: data.name,
1920
2362
  report_id: data.report_id,
1921
2363
  variants: []
1922
2364
  }, {
1923
2365
  include: dimensionQuery.include
1924
- })).toJSON();
2366
+ });
2367
+ return entity.toJSON();
1925
2368
  }
1926
2369
  async function readDimension({ id, include } = {}) {
1927
- const idList = id == null ? [] : [].concat(id), entities = await Dimension.findAll({
2370
+ const idList = id == null ? [] : [].concat(id);
2371
+ const entities = await Dimension.findAll({
1928
2372
  where: idList.length > 0 ? { id: idList } : void 0,
1929
2373
  include: include ? dimensionQuery.include : void 0
1930
2374
  });
1931
- if (idList.length === 0 || entities.length === idList.length)
2375
+ if (idList.length === 0 || entities.length === idList.length) {
1932
2376
  return entities.map((entity) => entity.toJSON());
1933
- const found = entities.map((entity) => entity.id), missing = idList.filter((item) => !found.includes(item));
2377
+ }
2378
+ const found = entities.map((entity) => entity.id);
2379
+ const missing = idList.filter((item) => !found.includes(item));
1934
2380
  throw new BackendError(404, `Dimension(id=[${missing}]) does not exist.`);
1935
2381
  }
1936
2382
  async function updateDimension(data) {
1937
- const _a = data, { id, variants } = _a, dimensionData = __objRest$5(_a, ["id", "variants"]), entity = await Dimension.findByPk(id, {
2383
+ const { id, variants, ...dimensionData } = data;
2384
+ const entity = await Dimension.findByPk(id, {
1938
2385
  include: dimensionQuery.include,
1939
- rejectOnEmpty: !0
2386
+ rejectOnEmpty: true
1940
2387
  });
1941
- return entity.set(dimensionData), await entity.save(), entity.toJSON();
2388
+ entity.set(dimensionData);
2389
+ await entity.save();
2390
+ return entity.toJSON();
1942
2391
  }
1943
2392
  async function deleteDimension(id) {
1944
- const entity = await Dimension.findByPk(id, { rejectOnEmpty: !0 });
1945
- return await entity.destroy(), { id, parentType: "report", parentId: entity.report_id };
1946
- }
1947
- }
1948
- var __getOwnPropSymbols$e = Object.getOwnPropertySymbols, __hasOwnProp$e = Object.prototype.hasOwnProperty, __propIsEnum$e = Object.prototype.propertyIsEnumerable, __objRest$4 = (source, exclude) => {
1949
- var target = {};
1950
- for (var prop in source)
1951
- __hasOwnProp$e.call(source, prop) && exclude.indexOf(prop) < 0 && (target[prop] = source[prop]);
1952
- if (source != null && __getOwnPropSymbols$e)
1953
- for (var prop of __getOwnPropSymbols$e(source))
1954
- exclude.indexOf(prop) < 0 && __propIsEnum$e.call(source, prop) && (target[prop] = source[prop]);
1955
- return target;
1956
- };
2393
+ const entity = await Dimension.findByPk(id, { rejectOnEmpty: true });
2394
+ await entity.destroy();
2395
+ return { id, parentType: "report", parentId: entity.report_id };
2396
+ }
2397
+ }
2398
+
2399
+ // api/db/entityCRUD/formatter.ts
1957
2400
  function dbFormatterFactory(db) {
1958
2401
  const { formatter: Formatter } = db;
1959
2402
  return {
@@ -1963,34 +2406,35 @@ function dbFormatterFactory(db) {
1963
2406
  deleteFormatter
1964
2407
  };
1965
2408
  async function createFormatter(data) {
1966
- return (await Formatter.create(data)).toJSON();
2409
+ const entity = await Formatter.create(data);
2410
+ return entity.toJSON();
1967
2411
  }
1968
2412
  async function readFormatter({ id } = {}) {
1969
- const idList = id == null ? [] : [].concat(id), entities = await Formatter.findAll({
2413
+ const idList = id == null ? [] : [].concat(id);
2414
+ const entities = await Formatter.findAll({
1970
2415
  where: idList.length > 0 ? { id: idList } : void 0
1971
2416
  });
1972
- if (idList.length === 0 || entities.length === idList.length)
2417
+ if (idList.length === 0 || entities.length === idList.length) {
1973
2418
  return entities.map((entity) => entity.toJSON());
1974
- const found = entities.map((entity) => entity.id), missing = idList.filter((item) => !found.includes(item));
2419
+ }
2420
+ const found = entities.map((entity) => entity.id);
2421
+ const missing = idList.filter((item) => !found.includes(item));
1975
2422
  throw new BackendError(404, `Formatter(id=[${missing}]) does not exist.`);
1976
2423
  }
1977
2424
  async function updateFormatter(data) {
1978
- const _a = data, { id } = _a, formatterData = __objRest$4(_a, ["id"]), entity = await Formatter.findByPk(id, { rejectOnEmpty: !0 });
1979
- return await entity.update(formatterData), entity.toJSON();
2425
+ const { id, ...formatterData } = data;
2426
+ const entity = await Formatter.findByPk(id, { rejectOnEmpty: true });
2427
+ await entity.update(formatterData);
2428
+ return entity.toJSON();
1980
2429
  }
1981
2430
  async function deleteFormatter(id) {
1982
- return await (await Formatter.findByPk(id, { rejectOnEmpty: !0 })).destroy(), { id };
2431
+ const entity = await Formatter.findByPk(id, { rejectOnEmpty: true });
2432
+ await entity.destroy();
2433
+ return { id };
1983
2434
  }
1984
2435
  }
1985
- var __getOwnPropSymbols$d = Object.getOwnPropertySymbols, __hasOwnProp$d = Object.prototype.hasOwnProperty, __propIsEnum$d = Object.prototype.propertyIsEnumerable, __objRest$3 = (source, exclude) => {
1986
- var target = {};
1987
- for (var prop in source)
1988
- __hasOwnProp$d.call(source, prop) && exclude.indexOf(prop) < 0 && (target[prop] = source[prop]);
1989
- if (source != null && __getOwnPropSymbols$d)
1990
- for (var prop of __getOwnPropSymbols$d(source))
1991
- exclude.indexOf(prop) < 0 && __propIsEnum$d.call(source, prop) && (target[prop] = source[prop]);
1992
- return target;
1993
- };
2436
+
2437
+ // api/db/entityCRUD/report.ts
1994
2438
  function dbReportFactory(db) {
1995
2439
  const { report: Report } = db;
1996
2440
  return {
@@ -2000,52 +2444,58 @@ function dbReportFactory(db) {
2000
2444
  deleteReport
2001
2445
  };
2002
2446
  async function createReport(data) {
2003
- return (await Report.create({
2447
+ const entity = await Report.create({
2004
2448
  name: data.name,
2005
2449
  sections: [],
2006
2450
  dimensions: []
2007
2451
  }, {
2008
2452
  include: reportQuery.include
2009
- })).toJSON();
2453
+ });
2454
+ return entity.toJSON();
2010
2455
  }
2011
2456
  async function readReport({ id, include } = {}) {
2012
- const idList = id == null ? [] : [].concat(id), entities = await Report.findAll({
2457
+ const idList = id == null ? [] : [].concat(id);
2458
+ const entities = await Report.findAll({
2013
2459
  where: idList.length > 0 ? { id: idList } : void 0,
2014
2460
  include: include ? reportQuery.include : void 0
2015
2461
  });
2016
- if (idList.length === 0 || entities.length === idList.length)
2462
+ if (idList.length === 0 || entities.length === idList.length) {
2017
2463
  return entities.map((entity) => entity.toJSON());
2018
- const found = entities.map((entity) => entity.id), missing = idList.filter((item) => !found.includes(item));
2464
+ }
2465
+ const found = entities.map((entity) => entity.id);
2466
+ const missing = idList.filter((item) => !found.includes(item));
2019
2467
  throw new BackendError(404, `Report(id=${missing}) does not exist.`);
2020
2468
  }
2021
2469
  async function updateReport(data) {
2022
- const _a = data, {
2470
+ const {
2023
2471
  id,
2024
2472
  dimensions,
2025
- sections
2026
- } = _a, reportData = __objRest$3(_a, [
2027
- "id",
2028
- "dimensions",
2029
- "sections"
2030
- ]), entity = await Report.findByPk(id, {
2031
- include: reportQuery.include,
2032
- rejectOnEmpty: !0
2033
- });
2034
- return entity.set(reportData), await entity.save(), await entity.reload(), entity.toJSON();
2473
+ sections,
2474
+ ...reportData
2475
+ } = data;
2476
+ try {
2477
+ console.log("Update Report ID", id, reportData);
2478
+ const entity = await Report.findByPk(id, {
2479
+ include: reportQuery.include,
2480
+ rejectOnEmpty: true
2481
+ });
2482
+ entity.set(reportData);
2483
+ await entity.save();
2484
+ await entity.reload();
2485
+ return entity.toJSON();
2486
+ } catch (error) {
2487
+ console.log("Report id:", id, error);
2488
+ throw new BackendError(500, "Update Report error");
2489
+ }
2035
2490
  }
2036
2491
  async function deleteReport(id) {
2037
- return await (await Report.findByPk(id, { rejectOnEmpty: !0 })).destroy(), { id };
2492
+ const entity = await Report.findByPk(id, { rejectOnEmpty: true });
2493
+ await entity.destroy();
2494
+ return { id };
2038
2495
  }
2039
2496
  }
2040
- var __getOwnPropSymbols$c = Object.getOwnPropertySymbols, __hasOwnProp$c = Object.prototype.hasOwnProperty, __propIsEnum$c = Object.prototype.propertyIsEnumerable, __objRest$2 = (source, exclude) => {
2041
- var target = {};
2042
- for (var prop in source)
2043
- __hasOwnProp$c.call(source, prop) && exclude.indexOf(prop) < 0 && (target[prop] = source[prop]);
2044
- if (source != null && __getOwnPropSymbols$c)
2045
- for (var prop of __getOwnPropSymbols$c(source))
2046
- exclude.indexOf(prop) < 0 && __propIsEnum$c.call(source, prop) && (target[prop] = source[prop]);
2047
- return target;
2048
- };
2497
+
2498
+ // api/db/entityCRUD/section.ts
2049
2499
  function dbSectionFactory(db) {
2050
2500
  const { section: Section } = db;
2051
2501
  return {
@@ -2055,45 +2505,45 @@ function dbSectionFactory(db) {
2055
2505
  deleteSection
2056
2506
  };
2057
2507
  async function createSection(data) {
2058
- return (await Section.create({
2508
+ const entity = await Section.create({
2059
2509
  ordering: data.ordering,
2060
2510
  report_id: data.report_id,
2061
2511
  blocks: []
2062
2512
  }, {
2063
2513
  include: sectionQuery.include
2064
- })).toJSON();
2514
+ });
2515
+ return entity.toJSON();
2065
2516
  }
2066
2517
  async function readSection({ id, include } = {}) {
2067
- const idList = id == null ? [] : [].concat(id), entities = await Section.findAll({
2518
+ const idList = id == null ? [] : [].concat(id);
2519
+ const entities = await Section.findAll({
2068
2520
  where: idList.length > 0 ? { id: idList } : void 0,
2069
2521
  include: include ? sectionQuery.include : void 0
2070
2522
  });
2071
- if (idList.length === 0 || entities.length === idList.length)
2523
+ if (idList.length === 0 || entities.length === idList.length) {
2072
2524
  return entities.map((entity) => entity.toJSON());
2073
- const found = entities.map((entity) => entity.id), missing = idList.filter((item) => !found.includes(item));
2525
+ }
2526
+ const found = entities.map((entity) => entity.id);
2527
+ const missing = idList.filter((item) => !found.includes(item));
2074
2528
  throw new BackendError(404, `Section(id=${missing}) does not exist.`);
2075
2529
  }
2076
2530
  async function updateSection(data) {
2077
- const _a = data, { id, blocks } = _a, sectionData = __objRest$2(_a, ["id", "blocks"]), entity = await Section.findByPk(id, {
2531
+ const { id, blocks, ...sectionData } = data;
2532
+ const entity = await Section.findByPk(id, {
2078
2533
  include: sectionQuery.include,
2079
- rejectOnEmpty: !0
2534
+ rejectOnEmpty: true
2080
2535
  });
2081
- return entity.set(sectionData), await entity.save(), await entity.reload(), entity.toJSON();
2536
+ entity.set(sectionData);
2537
+ await entity.save();
2538
+ await entity.reload();
2539
+ return entity.toJSON();
2082
2540
  }
2083
2541
  async function deleteSection(id) {
2084
- const entity = await Section.findByPk(id, { rejectOnEmpty: !0 });
2085
- return await entity.destroy(), { id, parentType: "report", parentId: entity.report_id };
2086
- }
2087
- }
2088
- var __getOwnPropSymbols$b = Object.getOwnPropertySymbols, __hasOwnProp$b = Object.prototype.hasOwnProperty, __propIsEnum$b = Object.prototype.propertyIsEnumerable, __objRest$1 = (source, exclude) => {
2089
- var target = {};
2090
- for (var prop in source)
2091
- __hasOwnProp$b.call(source, prop) && exclude.indexOf(prop) < 0 && (target[prop] = source[prop]);
2092
- if (source != null && __getOwnPropSymbols$b)
2093
- for (var prop of __getOwnPropSymbols$b(source))
2094
- exclude.indexOf(prop) < 0 && __propIsEnum$b.call(source, prop) && (target[prop] = source[prop]);
2095
- return target;
2096
- };
2542
+ const entity = await Section.findByPk(id, { rejectOnEmpty: true });
2543
+ await entity.destroy();
2544
+ return { id, parentType: "report", parentId: entity.report_id };
2545
+ }
2546
+ }
2097
2547
  function dbVariantFactory(db, crud) {
2098
2548
  const { variant: Variant } = db;
2099
2549
  return {
@@ -2104,32 +2554,44 @@ function dbVariantFactory(db, crud) {
2104
2554
  validateVariantSlug
2105
2555
  };
2106
2556
  async function createVariant(body) {
2107
- const { dimension_id: dimension, name, slug } = body, validSlug = await validateVariantSlug({ dimension, slug });
2108
- return (await Variant.create({
2557
+ const { dimension_id: dimension, name, slug } = body;
2558
+ const validSlug = await validateVariantSlug({ dimension, slug });
2559
+ const entity = await Variant.create({
2109
2560
  dimension_id: dimension,
2110
2561
  name,
2111
2562
  slug: validSlug.valid ? validSlug.candidate : validSlug.suggestion
2112
- })).toJSON();
2563
+ });
2564
+ return entity.toJSON();
2113
2565
  }
2114
2566
  async function readVariant({ id } = {}) {
2115
- const idList = id == null ? [] : [].concat(id), entities = await Variant.findAll({
2567
+ const idList = id == null ? [] : [].concat(id);
2568
+ const entities = await Variant.findAll({
2116
2569
  where: idList.length > 0 ? { id: idList } : void 0
2117
2570
  });
2118
- if (idList.length === 0 || entities.length === idList.length)
2571
+ if (idList.length === 0 || entities.length === idList.length) {
2119
2572
  return entities.map((entity) => entity.toJSON());
2120
- const found = entities.map((entity) => entity.id), missing = idList.filter((item) => !found.includes(item));
2573
+ }
2574
+ const found = entities.map((entity) => entity.id);
2575
+ const missing = idList.filter((item) => !found.includes(item));
2121
2576
  throw new BackendError(404, `Variant(id=${missing}) does not exist.`);
2122
2577
  }
2123
2578
  async function updateVariant(data) {
2124
- const _a = data, { id } = _a, variantData = __objRest$1(_a, ["id"]), entity = await Variant.findByPk(id, {
2579
+ const { id, ...variantData } = data;
2580
+ const entity = await Variant.findByPk(id, {
2125
2581
  include: [{ association: "dimension" }],
2126
- rejectOnEmpty: !0
2582
+ rejectOnEmpty: true
2127
2583
  });
2128
- return entity.update(variantData), await crud.ingestMembers(entity), await getSearchIndexByLocale(db, !0), await entity.reload(), entity.toJSON();
2584
+ entity.update(variantData);
2585
+ await crud.ingestMembers(entity);
2586
+ await search_default2(db, true);
2587
+ await entity.reload();
2588
+ return entity.toJSON();
2129
2589
  }
2130
2590
  async function deleteVariant(id) {
2131
- const entity = await Variant.findByPk(id, { rejectOnEmpty: !0 });
2132
- return await entity.destroy(), getSearchIndexByLocale(db, !0), { id, parentType: "dimension", parentId: entity.dimension_id };
2591
+ const entity = await Variant.findByPk(id, { rejectOnEmpty: true });
2592
+ await entity.destroy();
2593
+ search_default2(db, true);
2594
+ return { id, parentType: "dimension", parentId: entity.dimension_id };
2133
2595
  }
2134
2596
  async function validateVariantSlug({ dimension, slug }) {
2135
2597
  const allSlugsFromOtherDimensions = await Variant.findAll({
@@ -2142,9 +2604,14 @@ function dbVariantFactory(db, crud) {
2142
2604
  const count = item.getDataValue("slugCount");
2143
2605
  return [item.slug, Number.parseInt(`${count}`, 10)];
2144
2606
  })));
2145
- let suggestion = slug, iteration = 1, valid = !0;
2146
- for (; allSlugsFromOtherDimensions[suggestion]; )
2147
- valid = !1, suggestion = `${slug}-${iteration}`, iteration++;
2607
+ let suggestion = slug;
2608
+ let iteration = 1;
2609
+ let valid = true;
2610
+ while (allSlugsFromOtherDimensions[suggestion]) {
2611
+ valid = false;
2612
+ suggestion = `${slug}-${iteration}`;
2613
+ iteration++;
2614
+ }
2148
2615
  return {
2149
2616
  candidate: slug,
2150
2617
  dimension_id: dimension,
@@ -2153,16 +2620,21 @@ function dbVariantFactory(db, crud) {
2153
2620
  };
2154
2621
  }
2155
2622
  }
2156
- var __defProp$9 = Object.defineProperty, __getOwnPropSymbols$a = Object.getOwnPropertySymbols, __hasOwnProp$a = Object.prototype.hasOwnProperty, __propIsEnum$a = Object.prototype.propertyIsEnumerable, __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$9 = (a, b) => {
2157
- for (var prop in b || (b = {}))
2158
- __hasOwnProp$a.call(b, prop) && __defNormalProp$9(a, prop, b[prop]);
2159
- if (__getOwnPropSymbols$a)
2160
- for (var prop of __getOwnPropSymbols$a(b))
2161
- __propIsEnum$a.call(b, prop) && __defNormalProp$9(a, prop, b[prop]);
2162
- return a;
2163
- };
2623
+
2624
+ // api/db/entityCRUD/index.ts
2164
2625
  function dbEntityFactory(dbModels) {
2165
- const simpleFactories = __spreadValues$9(__spreadValues$9(__spreadValues$9(__spreadValues$9(__spreadValues$9(__spreadValues$9({}, dbBlockFactory(dbModels)), dbDimensionFactory(dbModels)), dbFormatterFactory(dbModels)), dbMemberFactory(dbModels)), dbReportFactory(dbModels)), dbSectionFactory(dbModels)), crud = __spreadValues$9(__spreadValues$9({}, simpleFactories), dbVariantFactory(dbModels, simpleFactories));
2626
+ const simpleFactories = {
2627
+ ...dbBlockFactory(dbModels),
2628
+ ...dbDimensionFactory(dbModels),
2629
+ ...dbFormatterFactory(dbModels),
2630
+ ...dbMemberFactory(dbModels),
2631
+ ...dbReportFactory(dbModels),
2632
+ ...dbSectionFactory(dbModels)
2633
+ };
2634
+ const crud = {
2635
+ ...simpleFactories,
2636
+ ...dbVariantFactory(dbModels, simpleFactories)
2637
+ };
2166
2638
  return {
2167
2639
  createFormatter: resultWrapper(crud.createFormatter),
2168
2640
  deleteFormatter: resultWrapper(crud.deleteFormatter),
@@ -2195,54 +2667,67 @@ function dbEntityFactory(dbModels) {
2195
2667
  readMemberImage: resultWrapper(crud.readMemberImage)
2196
2668
  };
2197
2669
  }
2198
- const catcher = (e) => {
2199
- throw console.error("/methods/helpers/uploadImage.ts:", e), new Error(e.message);
2200
- }, splashWidth = Number(process.env.NEXT_PUBLIC_IMAGE_SPLASH_WIDTH) || 1400, thumbWidth = Number(process.env.NEXT_PUBLIC_IMAGE_THUMB_WIDTH) || 400, uploadImage = async (db, id, imageData) => {
2670
+ var catcher = (e) => {
2671
+ console.error("/methods/helpers/uploadImage.ts:", e);
2672
+ throw new Error(e.message);
2673
+ };
2674
+ var splashWidth = Number(process.env.NEXT_PUBLIC_IMAGE_SPLASH_WIDTH) || 1400;
2675
+ var thumbWidth = Number(process.env.NEXT_PUBLIC_IMAGE_THUMB_WIDTH) || 400;
2676
+ var uploadImage = async (db, id, imageData) => {
2201
2677
  const configs = [
2202
2678
  { type: "splash", res: splashWidth },
2203
2679
  { type: "thumb", res: thumbWidth }
2204
2680
  ];
2205
2681
  for (const config of configs) {
2206
- const buffer = await sharp(imageData).resize(config.res).toFormat("jpeg").jpeg({ force: !0 }).toBuffer().catch(catcher);
2682
+ const buffer = await sharp(imageData).resize(config.res).toFormat("jpeg").jpeg({ force: true }).toBuffer().catch(catcher);
2207
2683
  await db.image.update({ [config.type]: buffer }, { where: { id } }).catch(catcher);
2208
2684
  }
2209
2685
  };
2210
- var __defProp$8 = Object.defineProperty, __getOwnPropSymbols$9 = Object.getOwnPropertySymbols, __hasOwnProp$9 = Object.prototype.hasOwnProperty, __propIsEnum$9 = Object.prototype.propertyIsEnumerable, __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$8 = (a, b) => {
2211
- for (var prop in b || (b = {}))
2212
- __hasOwnProp$9.call(b, prop) && __defNormalProp$8(a, prop, b[prop]);
2213
- if (__getOwnPropSymbols$9)
2214
- for (var prop of __getOwnPropSymbols$9(b))
2215
- __propIsEnum$9.call(b, prop) && __defNormalProp$8(a, prop, b[prop]);
2216
- return a;
2217
- };
2218
- const validLicenses = ["4", "5", "7", "8", "9", "10"], validLicensesString = validLicenses.join(), { locales: locales$3 } = getLocales();
2219
- let flickr;
2220
- if (process.env.FLICKR_API_KEY)
2686
+ var uploadImage_default = uploadImage;
2687
+
2688
+ // api/db/image/providers/flickr.ts
2689
+ var validLicenses = ["4", "5", "7", "8", "9", "10"];
2690
+ var validLicensesString = validLicenses.join();
2691
+ var { locales: locales2 } = getLocales_default();
2692
+ var flickr;
2693
+ if (process.env.FLICKR_API_KEY) {
2221
2694
  try {
2222
2695
  flickr = new FlickrSDK(process.env.FLICKR_API_KEY);
2223
2696
  } catch (e) {
2224
- throw console.error("Flickr ERROR:", e), new Error(e.message);
2697
+ console.error("Flickr ERROR:", e);
2698
+ throw new Error(e.message);
2225
2699
  }
2700
+ }
2226
2701
  async function searchFlickrProvider(db, params) {
2227
2702
  try {
2228
2703
  const searchParams = {
2229
2704
  prompt: params.prompt || ""
2230
2705
  };
2231
- if (!flickr)
2232
- throw console.log("Flickr is not initialized. Check the credentials"), new Error("Flickr is not initialized. Check the credentials");
2233
- const q = searchParams.prompt, photos = (await flickr.photos.search({
2706
+ if (!flickr) {
2707
+ console.log("Flickr is not initialized. Check the credentials");
2708
+ throw new Error("Flickr is not initialized. Check the credentials");
2709
+ }
2710
+ const q = searchParams.prompt;
2711
+ const result = await flickr.photos.search({
2234
2712
  text: q,
2235
2713
  license: validLicensesString,
2236
2714
  sort: "relevance"
2237
- }).then((resp) => resp.body)).photos.photo, fetches = photos.reduce(
2715
+ }).then((resp) => resp.body);
2716
+ const photos = result.photos.photo;
2717
+ const fetches = photos.reduce(
2238
2718
  (acc, d) => acc.concat(flickr.photos.getSizes({ photo_id: d.id })),
2239
2719
  []
2240
- ), imagesResults = (await Promise.all(fetches).then((results2) => results2)).reduce((acc, d, i) => {
2720
+ );
2721
+ const results = await Promise.all(fetches).then((results2) => results2);
2722
+ const imagesResults = results.reduce((acc, d, i) => {
2241
2723
  const small = d.body.sizes.size.find((s) => s.label === "Small 320");
2242
- return small && acc.push({
2243
- id: photos[i].id,
2244
- source: small.source
2245
- }), acc;
2724
+ if (small) {
2725
+ acc.push({
2726
+ id: photos[i].id,
2727
+ source: small.source
2728
+ });
2729
+ }
2730
+ return acc;
2246
2731
  }, []);
2247
2732
  return {
2248
2733
  meta: {
@@ -2251,81 +2736,113 @@ async function searchFlickrProvider(db, params) {
2251
2736
  results: imagesResults
2252
2737
  };
2253
2738
  } catch (error) {
2254
- throw console.log(error), new Error("Error in search flickr provider");
2739
+ console.log(error);
2740
+ throw new Error("Error in search flickr provider");
2255
2741
  }
2256
2742
  }
2257
2743
  async function saveFlickrProvider(db, params) {
2258
2744
  try {
2259
- const { content_id, image_id } = params, searchParams = {
2745
+ const { content_id, image_id } = params;
2746
+ const searchParams = {
2260
2747
  content_id: stripHTML(`${content_id}`) || "",
2261
2748
  id: stripHTML(`${image_id}`) || ""
2262
- }, url = `https://flic.kr/p/${Base58.int_to_base58(image_id)}`;
2263
- if (!flickr)
2749
+ };
2750
+ const shortid = Base58.int_to_base58(image_id);
2751
+ const url = `https://flic.kr/p/${shortid}`;
2752
+ if (!flickr) {
2264
2753
  throw new Error("Flickr API Key not configured");
2754
+ }
2265
2755
  const info = await flickr.photos.getInfo({ photo_id: image_id }).then((resp) => resp.body);
2266
2756
  let newRow;
2267
- if (info)
2757
+ if (info) {
2268
2758
  if (validLicenses.includes(info.photo.license)) {
2269
- const searchRow = await db.search.findOne({ where: { content_id } }), imageRow = await db.image.findOne({ where: { url } });
2759
+ const searchRow = await db.search.findOne({ where: { content_id } });
2760
+ const imageRow = await db.image.findOne({ where: { url } });
2270
2761
  if (searchRow) {
2271
- if (imageRow)
2762
+ if (imageRow) {
2272
2763
  await db.search.update({ image_id: imageRow.id }, { where: { content_id } });
2273
- else {
2764
+ } else {
2274
2765
  const sizeObj = await flickr.photos.getSizes({ photo_id: image_id }).then((resp) => resp.body);
2275
2766
  let image = sizeObj.sizes.size.find(
2276
2767
  (d) => parseInt(d.width, 10) >= 1600
2277
2768
  );
2278
- if (image || (image = sizeObj.sizes.size.find(
2279
- (d) => parseInt(d.width, 10) >= 1e3
2280
- )), image || (image = sizeObj.sizes.size.find(
2281
- (d) => parseInt(d.width, 10) >= 500
2282
- )), !image || !image.source)
2769
+ if (!image) {
2770
+ image = sizeObj.sizes.size.find(
2771
+ (d) => parseInt(d.width, 10) >= 1e3
2772
+ );
2773
+ }
2774
+ if (!image) {
2775
+ image = sizeObj.sizes.size.find(
2776
+ (d) => parseInt(d.width, 10) >= 500
2777
+ );
2778
+ }
2779
+ if (!image || !image.source) {
2283
2780
  throw new Error("Flickr Source Error, try another image.");
2284
- const imageData = await axios.get(image.source, { responseType: "arraybuffer" }).then((d) => d.data), currentPhotoLicense = (await flickr.photos.licenses.getInfo().then((resp) => resp.body.licenses.license)).find((l) => l.id === parseInt(info.photo.license, 10)), payload = {
2781
+ }
2782
+ const imageData = await axios.get(image.source, { responseType: "arraybuffer" }).then((d) => d.data);
2783
+ const allLicenses = await flickr.photos.licenses.getInfo().then((resp) => resp.body.licenses.license);
2784
+ const currentPhotoLicense = allLicenses.find((l) => l.id === parseInt(info.photo.license, 10));
2785
+ const payload = {
2285
2786
  url,
2286
2787
  author: info.photo.owner.realname || info.photo.owner.username,
2287
2788
  license: currentPhotoLicense ? `${currentPhotoLicense.name}: ${currentPhotoLicense.url}` : ""
2288
- }, newImage = await db.image.create(payload);
2789
+ };
2790
+ const newImage = await db.image.create(payload);
2289
2791
  await db.image_content.destroy({ where: { id: newImage.id } });
2290
- const contentPayload = locales$3.map((locale) => ({
2792
+ const contentPayload = locales2.map((locale) => ({
2291
2793
  id: newImage.id,
2292
2794
  locale,
2293
2795
  meta: info.photo.title._content
2294
2796
  }));
2295
- await db.image_content.bulkCreate(contentPayload), await db.search.update({ image_id: newImage.id }, { where: { content_id } }), await uploadImage(db, newImage.id, imageData);
2797
+ await db.image_content.bulkCreate(contentPayload);
2798
+ await db.search.update({ image_id: newImage.id }, { where: { content_id } });
2799
+ await uploadImage_default(db, newImage.id, imageData);
2296
2800
  }
2297
2801
  const newRow2 = await db.search.findOne({
2298
2802
  where: { content_id },
2299
2803
  include: imageQueryThumbOnly
2300
2804
  });
2301
- newRow2 && newRow2.image && (newRow2.image.thumb = Boolean(newRow2.image.thumb));
2302
- } else
2805
+ if (newRow2 && newRow2.image) {
2806
+ newRow2.image.thumb = Boolean(newRow2.image.thumb);
2807
+ }
2808
+ } else {
2303
2809
  throw new Error("Error updating Search");
2304
- } else
2810
+ }
2811
+ } else {
2305
2812
  throw new Error("Bad License");
2306
- else
2813
+ }
2814
+ } else {
2307
2815
  throw new Error("Malformed URL");
2816
+ }
2308
2817
  return {
2309
- meta: __spreadValues$8({}, searchParams),
2818
+ meta: {
2819
+ ...searchParams
2820
+ },
2310
2821
  results: newRow
2311
2822
  };
2312
2823
  } catch (error) {
2313
- throw console.log(error), new Error("Error in save flickr provider");
2824
+ console.log(error);
2825
+ throw new Error("Error in save flickr provider");
2314
2826
  }
2315
2827
  }
2828
+
2829
+ // api/endpoints/lib.ts
2316
2830
  function endpoint(method, path, handler) {
2317
2831
  return { method, path, handler };
2318
2832
  }
2319
2833
  function parseFiniteNumber(value) {
2320
2834
  const num = Number.parseInt(`${value || ""}`, 10);
2321
- if (Number.isNaN(num) || !Number.isFinite(num))
2835
+ if (Number.isNaN(num) || !Number.isFinite(num)) {
2322
2836
  throw new BackendError(400, `Invalid numeric parameter: ${value}`);
2837
+ }
2323
2838
  return num;
2324
2839
  }
2325
2840
  function normalizeList(value) {
2326
2841
  return value == null || value === "" ? [] : value.toString().split(",");
2327
2842
  }
2328
- const { localeDefault: localeDefault$1 } = getLocales();
2843
+
2844
+ // api/endpoints/member.ts
2845
+ var { localeDefault: localeDefault3 } = getLocales_default();
2329
2846
  function endpointMemberFactory(operations) {
2330
2847
  const {
2331
2848
  readMember,
@@ -2335,13 +2852,14 @@ function endpointMemberFactory(operations) {
2335
2852
  } = operations;
2336
2853
  return [
2337
2854
  endpoint("GET", "read/members", async (req) => {
2338
- const params = parseReadMemberParams(req.query);
2339
- if (params.ids.length > 1 && params.slugs.length > 1)
2340
- throw new BackendError(400, "Both 'ids' and 'slugs' are filled. Pick one.");
2341
- if (params.ids.length === 0 && params.slugs.length === 0)
2342
- throw new BackendError(400, "Params 'ids' and 'slugs' are missing. Fill one.");
2343
- if ((params.mode === "ids" ? params.ids.length : params.slugs.length) > 5)
2344
- throw new BackendError(400, "Too many 'ids' and 'slugs' in the request. Try with less than 5.");
2855
+ const params = parseReadMembersParams(req.query);
2856
+ const list = params[params.mode] || [];
2857
+ if (list.length === 0) {
2858
+ throw new BackendError(400, `The request is missing the '${params.mode}' parameter.`);
2859
+ }
2860
+ if (list.length > 20) {
2861
+ throw new BackendError(400, `You can look for up to 20 '${params.mode}' in a single request.`);
2862
+ }
2345
2863
  return readMember(params);
2346
2864
  }),
2347
2865
  endpoint("GET", "search/members", (req) => {
@@ -2361,13 +2879,17 @@ function endpointMemberFactory(operations) {
2361
2879
  })
2362
2880
  ];
2363
2881
  }
2364
- function parseReadMemberParams(query) {
2365
- const ids = normalizeList(query.ids).map(parseFiniteNumber), locale = normalizeList(query.locale)[0] || localeDefault$1 || "en", localeIsAll = locale === "all";
2882
+ function parseReadMembersParams(query) {
2883
+ const ids = normalizeList(query.ids);
2884
+ const content_ids = normalizeList(query.content_ids).map(parseFiniteNumber);
2885
+ const locale = normalizeList(query.locale)[0] || localeDefault3 || "en";
2886
+ const localeIsAll = locale === "all";
2366
2887
  return {
2367
2888
  all: localeIsAll,
2889
+ locale: localeIsAll ? localeDefault3 : stripHTML(locale),
2890
+ mode: ids.length > 0 ? "ids" : content_ids.length > 0 ? "content_ids" : "slugs",
2368
2891
  ids,
2369
- locale: localeIsAll ? localeDefault$1 : locale,
2370
- mode: ids.length > 0 ? "ids" : "slugs",
2892
+ content_ids,
2371
2893
  slugs: normalizeList(query.slugs).map((token) => {
2372
2894
  const [variantSlug, memberSlug] = token.split("/");
2373
2895
  return { variantSlug, memberSlug };
@@ -2375,16 +2897,18 @@ function parseReadMemberParams(query) {
2375
2897
  };
2376
2898
  }
2377
2899
  function parseSearchMemberParams(query) {
2378
- var _a;
2379
- const locale = normalizeList(query.locale)[0] || localeDefault$1 || "en", localeIsAll = locale === "all", format = normalizeList(query.format)[0], formatIsNested = format ? format === "nested" : localeIsAll;
2900
+ const locale = normalizeList(query.locale)[0] || localeDefault3 || "en";
2901
+ const localeIsAll = locale === "all";
2902
+ const format = normalizeList(query.format)[0];
2903
+ const formatIsNested = format ? format === "nested" : localeIsAll;
2380
2904
  return {
2381
2905
  query: normalizeList(query.query || query.q)[0] || "",
2382
- locale: localeIsAll ? localeDefault$1 : locale,
2383
- limit: (_a = normalizeList(query.limit).map(parseFiniteNumber)[0]) != null ? _a : 5,
2906
+ locale: localeIsAll ? localeDefault3 : locale,
2907
+ limit: normalizeList(query.limit).map(parseFiniteNumber)[0] ?? 5,
2384
2908
  format: formatIsNested ? "nested" : "plain",
2385
- includes: yn(query.includes, { default: !0 }),
2386
- visible: yn(query.visible, { default: !0 }),
2387
- noImage: yn(query.noImage, { default: !1 }),
2909
+ includes: yn3(query.includes, { default: true }),
2910
+ visible: yn3(query.visible, { default: true }),
2911
+ noImage: yn3(query.noImage, { default: false }),
2388
2912
  variant: normalizeList(query.variant).map(parseFiniteNumber),
2389
2913
  dimension: normalizeList(query.dimension).map(parseFiniteNumber),
2390
2914
  report: normalizeList(query.report).map(parseFiniteNumber),
@@ -2393,20 +2917,17 @@ function parseSearchMemberParams(query) {
2393
2917
  direction: normalizeList(query.direction)[0]
2394
2918
  };
2395
2919
  }
2396
- var __defProp$7 = Object.defineProperty, __defProps$5 = Object.defineProperties, __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$8 = Object.getOwnPropertySymbols, __hasOwnProp$8 = Object.prototype.hasOwnProperty, __propIsEnum$8 = Object.prototype.propertyIsEnumerable, __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$7 = (a, b) => {
2397
- for (var prop in b || (b = {}))
2398
- __hasOwnProp$8.call(b, prop) && __defNormalProp$7(a, prop, b[prop]);
2399
- if (__getOwnPropSymbols$8)
2400
- for (var prop of __getOwnPropSymbols$8(b))
2401
- __propIsEnum$8.call(b, prop) && __defNormalProp$7(a, prop, b[prop]);
2402
- return a;
2403
- }, __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
2920
+
2921
+ // api/db/image/providers/local.ts
2404
2922
  async function searchLocalProvider(db, params) {
2405
- const dbSearchMember = dbSearchMemberFactory(db), searchParams = parseSearchMemberParams({
2923
+ const dbSearchMember = dbSearchMemberFactory(db);
2924
+ const searchParams = parseSearchMemberParams({
2406
2925
  query: params.prompt,
2407
2926
  limit: "50",
2408
2927
  visible: "false"
2409
- }), imagesResults = (await dbSearchMember(searchParams)).results.filter((member) => member.image_id).map((member) => ({
2928
+ });
2929
+ const resultsFromProfiles = await dbSearchMember(searchParams);
2930
+ const imagesResults = resultsFromProfiles.results.filter((member) => member.image_id).map((member) => ({
2410
2931
  id: member.image_id,
2411
2932
  source: `/api/cms/member/image.png?member=${member.content_id}&size=thumb`
2412
2933
  }));
@@ -2418,7 +2939,8 @@ async function searchLocalProvider(db, params) {
2418
2939
  };
2419
2940
  }
2420
2941
  async function saveLocalProvider(db, params) {
2421
- const { search: Search } = db, { content_id, image_id } = params;
2942
+ const { search: Search } = db;
2943
+ const { content_id, image_id } = params;
2422
2944
  await Search.update({ image_id }, { where: { content_id } });
2423
2945
  const item = await Search.findOne({
2424
2946
  where: { content_id },
@@ -2427,11 +2949,13 @@ async function saveLocalProvider(db, params) {
2427
2949
  if (!item2)
2428
2950
  return null;
2429
2951
  const plainItem = item2.toJSON();
2430
- return __spreadProps$5(__spreadValues$7({}, plainItem), {
2431
- image: __spreadProps$5(__spreadValues$7({}, item2.image.toJSON()), {
2952
+ return {
2953
+ ...plainItem,
2954
+ image: {
2955
+ ...item2.image.toJSON(),
2432
2956
  thumb: !!item2.image.thumb
2433
- })
2434
- });
2957
+ }
2958
+ };
2435
2959
  });
2436
2960
  return {
2437
2961
  meta: {
@@ -2441,35 +2965,32 @@ async function saveLocalProvider(db, params) {
2441
2965
  results: item
2442
2966
  };
2443
2967
  }
2444
- var __defProp$6 = Object.defineProperty, __getOwnPropSymbols$7 = Object.getOwnPropertySymbols, __hasOwnProp$7 = Object.prototype.hasOwnProperty, __propIsEnum$7 = Object.prototype.propertyIsEnumerable, __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$6 = (a, b) => {
2445
- for (var prop in b || (b = {}))
2446
- __hasOwnProp$7.call(b, prop) && __defNormalProp$6(a, prop, b[prop]);
2447
- if (__getOwnPropSymbols$7)
2448
- for (var prop of __getOwnPropSymbols$7(b))
2449
- __propIsEnum$7.call(b, prop) && __defNormalProp$6(a, prop, b[prop]);
2450
- return a;
2451
- };
2452
- const { locales: locales$2 } = getLocales();
2453
- let unsplash;
2454
- if (process.env.UNSPLASH_API_KEY)
2968
+ var { locales: locales3 } = getLocales_default();
2969
+ var unsplash;
2970
+ if (process.env.UNSPLASH_API_KEY) {
2455
2971
  try {
2456
2972
  unsplash = createApi({
2457
2973
  accessKey: process.env.UNSPLASH_API_KEY
2458
2974
  });
2459
2975
  } catch (e) {
2460
- throw console.error("Unsplash error:", e), new Error(e.message);
2976
+ console.error("Unsplash error:", e);
2977
+ throw new Error(e.message);
2461
2978
  }
2979
+ }
2462
2980
  async function searchUnsplashProvider(db, params) {
2463
2981
  try {
2464
2982
  const searchParams = {
2465
2983
  prompt: params.prompt || ""
2466
2984
  };
2467
- if (!unsplash)
2985
+ if (!unsplash) {
2468
2986
  throw new Error("Unsplash API Key not configured");
2469
- const q = searchParams.prompt, imagesResults = (await unsplash.search.getPhotos({
2987
+ }
2988
+ const q = searchParams.prompt;
2989
+ const result = await unsplash.search.getPhotos({
2470
2990
  query: q,
2471
2991
  perPage: 30
2472
- }).then((resp) => resp.response.results)).map((image) => ({
2992
+ }).then((resp) => resp.response.results);
2993
+ const imagesResults = result.map((image) => ({
2473
2994
  id: image.id,
2474
2995
  source: image.urls.thumb
2475
2996
  }));
@@ -2480,96 +3001,121 @@ async function searchUnsplashProvider(db, params) {
2480
3001
  results: imagesResults
2481
3002
  };
2482
3003
  } catch (error) {
2483
- throw console.log(error), new Error("Error in search unsplash provider");
3004
+ console.log(error);
3005
+ throw new Error("Error in search unsplash provider");
2484
3006
  }
2485
3007
  }
2486
3008
  async function saveUnsplashProvider(db, params) {
2487
3009
  try {
2488
- const { content_id, image_id } = params, saveParams = {
3010
+ const { content_id, image_id } = params;
3011
+ const saveParams = {
2489
3012
  content_id: stripHTML(`${content_id}`) || "",
2490
3013
  id: stripHTML(`${image_id}`) || ""
2491
3014
  };
2492
- if (!unsplash)
2493
- throw console.log("Unsplash is not initialized. Check the credentials"), new Error("Unsplash is not initialized. Check the credentials");
3015
+ if (!unsplash) {
3016
+ console.log("Unsplash is not initialized. Check the credentials");
3017
+ throw new Error("Unsplash is not initialized. Check the credentials");
3018
+ }
2494
3019
  const info = await unsplash.photos.get({ photoId: image_id }).then((resp) => resp.response);
2495
3020
  let newRow;
2496
3021
  if (info) {
2497
- const searchRow = await db.search.findOne({ where: { content_id } }), url = info.links.html, imageRow = await db.image.findOne({ where: { url } });
2498
- if (searchRow) {
2499
- if (imageRow)
2500
- await db.search.update({ image_id: imageRow.id }, { where: { content_id } });
2501
- else {
2502
- const imageData = await axios.get(info.urls.full, { responseType: "arraybuffer" }).then((d) => d.data), payload = {
2503
- url,
2504
- author: info.user.name || info.user.username,
2505
- license: "Free Unsplash license: https://unsplash.com/license"
2506
- }, newImage = await db.image.create(payload);
2507
- await db.image_content.destroy({ where: { id: newImage.id } });
2508
- const contentPayload = locales$2.map((locale) => ({
2509
- id: newImage.id,
2510
- locale,
2511
- meta: info.description || info.alt_description
2512
- }));
2513
- await db.image_content.bulkCreate(contentPayload), await db.search.update({ image_id: newImage.id }, { where: { content_id } }), await uploadImage(db, newImage.id, imageData);
3022
+ if (true) {
3023
+ const searchRow = await db.search.findOne({ where: { content_id } });
3024
+ const url = info.links.html;
3025
+ const imageRow = await db.image.findOne({ where: { url } });
3026
+ if (searchRow) {
3027
+ if (imageRow) {
3028
+ await db.search.update({ image_id: imageRow.id }, { where: { content_id } });
3029
+ } else {
3030
+ const imageData = await axios.get(info.urls.full, { responseType: "arraybuffer" }).then((d) => d.data);
3031
+ const payload = {
3032
+ url,
3033
+ author: info.user.name || info.user.username,
3034
+ license: "Free Unsplash license: https://unsplash.com/license"
3035
+ };
3036
+ const newImage = await db.image.create(payload);
3037
+ await db.image_content.destroy({ where: { id: newImage.id } });
3038
+ const contentPayload = locales3.map((locale) => ({
3039
+ id: newImage.id,
3040
+ locale,
3041
+ meta: info.description || info.alt_description
3042
+ }));
3043
+ await db.image_content.bulkCreate(contentPayload);
3044
+ await db.search.update({ image_id: newImage.id }, { where: { content_id } });
3045
+ await uploadImage_default(db, newImage.id, imageData);
3046
+ }
3047
+ const newRow2 = await db.search.findOne({
3048
+ where: { content_id },
3049
+ include: imageQueryThumbOnly
3050
+ });
3051
+ if (newRow2 && newRow2.image) {
3052
+ newRow2.image.thumb = Boolean(newRow2.image.thumb);
3053
+ }
3054
+ } else {
3055
+ throw new Error("Error updating Search");
2514
3056
  }
2515
- const newRow2 = await db.search.findOne({
2516
- where: { content_id },
2517
- include: imageQueryThumbOnly
2518
- });
2519
- newRow2 && newRow2.image && (newRow2.image.thumb = Boolean(newRow2.image.thumb));
2520
- } else
2521
- throw new Error("Error updating Search");
2522
- } else
3057
+ }
3058
+ } else {
2523
3059
  throw new Error("Malformed URL");
3060
+ }
2524
3061
  return {
2525
- meta: __spreadValues$6({}, saveParams),
3062
+ meta: {
3063
+ ...saveParams
3064
+ },
2526
3065
  results: newRow
2527
3066
  };
2528
3067
  } catch (error) {
2529
- throw console.log(error), new Error("Error in save unsplash provider");
3068
+ console.log(error);
3069
+ throw new Error("Error in save unsplash provider");
2530
3070
  }
2531
3071
  }
2532
- var __defProp$5 = Object.defineProperty, __getOwnPropSymbols$6 = Object.getOwnPropertySymbols, __hasOwnProp$6 = Object.prototype.hasOwnProperty, __propIsEnum$6 = Object.prototype.propertyIsEnumerable, __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$5 = (a, b) => {
2533
- for (var prop in b || (b = {}))
2534
- __hasOwnProp$6.call(b, prop) && __defNormalProp$5(a, prop, b[prop]);
2535
- if (__getOwnPropSymbols$6)
2536
- for (var prop of __getOwnPropSymbols$6(b))
2537
- __propIsEnum$6.call(b, prop) && __defNormalProp$5(a, prop, b[prop]);
2538
- return a;
2539
- };
2540
- const { locales: locales$1 } = getLocales();
3072
+ var { locales: locales4 } = getLocales_default();
2541
3073
  async function saveUploadProvider(db, params) {
2542
3074
  try {
2543
- const { content_id, image_source, files } = params, saveParams = {
3075
+ const { content_id, image_source, files } = params;
3076
+ const saveParams = {
2544
3077
  content_id: stripHTML(`${content_id}`) || ""
2545
3078
  };
2546
- if (await db.search.findOne({ where: { content_id } }) && files) {
2547
- const imageData = await fs.readFileSync(files.file.path), payload = {
3079
+ const searchRow = await db.search.findOne({ where: { content_id } });
3080
+ if (searchRow && files) {
3081
+ const imageData = await fs.readFileSync(files.file.path);
3082
+ const payload = {
2548
3083
  url: image_source,
2549
3084
  author: "",
2550
3085
  license: ""
2551
- }, newImage = await db.image.create(payload);
3086
+ };
3087
+ const newImage = await db.image.create(payload);
2552
3088
  await db.image_content.destroy({ where: { id: newImage.id } });
2553
- const contentPayload = locales$1.map((locale) => ({
3089
+ const contentPayload = locales4.map((locale) => ({
2554
3090
  id: newImage.id,
2555
3091
  locale,
2556
3092
  meta: ""
2557
3093
  }));
2558
- await db.image_content.bulkCreate(contentPayload), await db.search.update({ image_id: newImage.id }, { where: { content_id } }), await uploadImage(db, newImage.id, imageData);
3094
+ await db.image_content.bulkCreate(contentPayload);
3095
+ await db.search.update({ image_id: newImage.id }, { where: { content_id } });
3096
+ await uploadImage_default(db, newImage.id, imageData);
2559
3097
  }
2560
3098
  const newRow = await db.search.findOne({
2561
3099
  where: { content_id },
2562
3100
  include: imageQueryThumbOnly
2563
3101
  });
2564
- return newRow && newRow.image && (newRow.image.thumb = Boolean(newRow.image.thumb)), {
2565
- meta: __spreadValues$5({}, saveParams),
3102
+ if (newRow && newRow.image) {
3103
+ newRow.image.thumb = Boolean(newRow.image.thumb);
3104
+ }
3105
+ return {
3106
+ meta: {
3107
+ ...saveParams
3108
+ },
2566
3109
  results: newRow
2567
3110
  };
2568
3111
  } catch (error) {
2569
- throw console.log(error), new Error("Error in save upload provider");
3112
+ console.log(error);
3113
+ throw new Error("Error in save upload provider");
2570
3114
  }
2571
3115
  }
2572
- const saveProviders = {
3116
+
3117
+ // api/db/image/imageSave.ts
3118
+ var saveProviders = {
2573
3119
  local: saveLocalProvider,
2574
3120
  flickr: saveFlickrProvider,
2575
3121
  unsplash: saveUnsplashProvider,
@@ -2577,166 +3123,181 @@ const saveProviders = {
2577
3123
  };
2578
3124
  function dbImageSaveFactory(db, provider) {
2579
3125
  const saveProvider = saveProviders[provider];
2580
- if (!saveProvider)
3126
+ if (!saveProvider) {
2581
3127
  throw new BackendError(500, `Wrong provider dbImageSaveFactory.ts: ${provider}`);
3128
+ }
2582
3129
  return resultWrapper((params) => saveProvider(db, params));
2583
3130
  }
2584
- const searchProviders = {
3131
+
3132
+ // api/db/image/imageSearch.ts
3133
+ var searchProviders = {
2585
3134
  local: searchLocalProvider,
2586
3135
  flickr: searchFlickrProvider,
2587
3136
  unsplash: searchUnsplashProvider
2588
3137
  };
2589
3138
  function dbImageSearchFactory(db, provider) {
2590
3139
  const searchProvider = searchProviders[provider];
2591
- if (!searchProvider)
3140
+ if (!searchProvider) {
2592
3141
  throw new BackendError(500, `Wrong provider dbImageSearchFactory.ts: ${provider}`);
3142
+ }
2593
3143
  return resultWrapper((params) => searchProvider(db, params));
2594
3144
  }
2595
- var __defProp$4 = Object.defineProperty, __defProps$4 = Object.defineProperties, __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$5 = Object.getOwnPropertySymbols, __hasOwnProp$5 = Object.prototype.hasOwnProperty, __propIsEnum$5 = Object.prototype.propertyIsEnumerable, __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$4 = (a, b) => {
2596
- for (var prop in b || (b = {}))
2597
- __hasOwnProp$5.call(b, prop) && __defNormalProp$4(a, prop, b[prop]);
2598
- if (__getOwnPropSymbols$5)
2599
- for (var prop of __getOwnPropSymbols$5(b))
2600
- __propIsEnum$5.call(b, prop) && __defNormalProp$4(a, prop, b[prop]);
2601
- return a;
2602
- }, __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
3145
+
3146
+ // api/db/readMetadata.ts
2603
3147
  function dbReadMetadataFactory(db) {
2604
3148
  const { report: Report } = db;
2605
3149
  return dbReadMetadata;
2606
3150
  async function dbReadMetadata(_params) {
2607
- return {
2608
- data: (await Report.findAll({
3151
+ const results = await Report.findAll({
3152
+ attributes: ["id", "name"],
3153
+ include: [{
2609
3154
  attributes: ["id", "name"],
2610
- include: [{
2611
- attributes: ["id", "name"],
2612
- association: "dimensions",
2613
- separate: !0,
2614
- include: [
2615
- {
2616
- attributes: ["id", "name", "slug"],
2617
- association: "variants",
2618
- separate: !0
2619
- }
2620
- ]
2621
- }]
2622
- })).map((report) => __spreadProps$4(__spreadValues$4({}, report.toJSON()), {
3155
+ association: "dimensions",
3156
+ separate: true,
3157
+ include: [
3158
+ {
3159
+ attributes: ["id", "name", "slug"],
3160
+ association: "variants",
3161
+ separate: true
3162
+ }
3163
+ ]
3164
+ }]
3165
+ });
3166
+ return {
3167
+ data: results.map((report) => ({
3168
+ ...report.toJSON(),
2623
3169
  mode: report.dimensions.length === 1 ? REPORT_MODES.UNILATERAL : REPORT_MODES.MULTILATERAL
2624
3170
  }))
2625
3171
  };
2626
3172
  }
2627
3173
  }
3174
+
3175
+ // api/db/regenerateSearch.ts
2628
3176
  function dbRegenerateSearchFactory(db) {
2629
- return async (_params) => (await getSearchIndexByLocale(db, !0), { error: !1 });
2630
- }
2631
- var __defProp$3 = Object.defineProperty, __defProps$3 = Object.defineProperties, __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$4 = Object.getOwnPropertySymbols, __hasOwnProp$4 = Object.prototype.hasOwnProperty, __propIsEnum$4 = Object.prototype.propertyIsEnumerable, __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$3 = (a, b) => {
2632
- for (var prop in b || (b = {}))
2633
- __hasOwnProp$4.call(b, prop) && __defNormalProp$3(a, prop, b[prop]);
2634
- if (__getOwnPropSymbols$4)
2635
- for (var prop of __getOwnPropSymbols$4(b))
2636
- __propIsEnum$4.call(b, prop) && __defNormalProp$3(a, prop, b[prop]);
2637
- return a;
2638
- }, __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
2639
- const { locales, localeDefault } = getLocales(), addProfilesData = (items, metadata) => {
3177
+ return async (_params) => {
3178
+ await search_default2(db, true);
3179
+ return { error: false };
3180
+ };
3181
+ }
3182
+
3183
+ // api/db/searchReport.ts
3184
+ var { locales: locales5, localeDefault: localeDefault4 } = getLocales_default();
3185
+ var addProfilesData = (items, metadata) => {
2640
3186
  if (!items)
2641
3187
  return [];
2642
3188
  let profileResults = [];
2643
- return metadata.forEach((report) => {
3189
+ metadata.forEach((report) => {
2644
3190
  const results = items.filter((result) => result.metadata.report.id === report.id);
2645
- if (results.length > 0)
3191
+ if (results.length > 0) {
2646
3192
  if (report.mode === REPORT_MODES.UNILATERAL) {
2647
3193
  const dimension = report.dimensions[0];
2648
3194
  dimension.variants.forEach((variant) => {
2649
3195
  const members = results.filter(
2650
3196
  (result) => result.metadata.dimension.id === dimension.id && result.metadata.variant.id === variant.id
2651
3197
  );
2652
- members.length > 0 && (profileResults = profileResults.concat(members.map((member) => ({
2653
- path: `/${variant.slug}/${member.slug}`,
2654
- name: member.name,
2655
- report: {
2656
- id: report.id,
2657
- name: report.name,
2658
- mode: report.mode
2659
- },
2660
- members: [member],
2661
- id: `r-${report.id}-${[member].map((m) => `${m.id}`).join("-")}`
2662
- }))));
3198
+ if (members.length > 0) {
3199
+ profileResults = profileResults.concat(members.map((member) => ({
3200
+ path: `/${variant.slug}/${member.slug}`,
3201
+ name: member.name,
3202
+ report: {
3203
+ id: report.id,
3204
+ name: report.name,
3205
+ mode: report.mode
3206
+ },
3207
+ members: [member],
3208
+ id: `r-${report.id}-${[member].map((m) => `${m.id}`).join("-")}`
3209
+ })));
3210
+ }
2663
3211
  });
2664
- } else
2665
- report.mode;
2666
- }), profileResults;
2667
- }, formatNested = (items, metadata) => {
3212
+ } else if (report.mode === REPORT_MODES.MULTILATERAL) ;
3213
+ }
3214
+ });
3215
+ return profileResults;
3216
+ };
3217
+ var formatNested = (items, metadata) => {
2668
3218
  if (!items)
2669
3219
  return [];
2670
- let report, dimension, variant;
2671
- return items.map((item) => (report = __spreadValues$3({}, metadata.find((r) => r.id === item.report_id)), dimension = __spreadValues$3({}, report.dimensions.find((d) => d.id === item.dimension_id)), variant = __spreadValues$3({}, dimension.variants.find((v) => v.id === item.variant_id)), delete report.dimensions, delete dimension.variants, {
2672
- name: item.name,
2673
- confidence: item.zvalue,
2674
- metadata: {
2675
- id: item.id,
2676
- slug: item.slug,
2677
- report,
2678
- dimension,
2679
- variant
2680
- },
2681
- id: item.content_id,
2682
- slug: item.slug
2683
- }));
3220
+ let report;
3221
+ let dimension;
3222
+ let variant;
3223
+ return items.map((item) => {
3224
+ report = { ...metadata.find((r) => r.id === item.report_id) };
3225
+ dimension = { ...report.dimensions.find((d) => d.id === item.dimension_id) };
3226
+ variant = { ...dimension.variants.find((v) => v.id === item.variant_id) };
3227
+ delete report.dimensions;
3228
+ delete dimension.variants;
3229
+ return {
3230
+ name: item.name,
3231
+ confidence: item.zvalue,
3232
+ metadata: {
3233
+ id: item.id,
3234
+ slug: item.slug,
3235
+ report,
3236
+ dimension,
3237
+ variant
3238
+ },
3239
+ id: item.content_id,
3240
+ slug: item.slug
3241
+ };
3242
+ });
2684
3243
  };
2685
3244
  function dbSearchReportFactory(db) {
2686
- const dbSearchMember = dbSearchMemberFactory(db), dbReadMetadata = dbReadMetadataFactory(db);
3245
+ const dbSearchMember = dbSearchMemberFactory(db);
3246
+ const dbReadMetadata = dbReadMetadataFactory(db);
2687
3247
  return dbSearchReport;
2688
3248
  async function dbSearchReport(params) {
2689
- const format = params.format || "results", locale = locales.includes(params.locale) ? params.locale : localeDefault, memberSearchResponse = await dbSearchMember(__spreadProps$3(__spreadValues$3({}, params), {
3249
+ const format = params.format || "results";
3250
+ const locale = locales5.includes(params.locale) ? params.locale : localeDefault4;
3251
+ const memberSearchResponse = await dbSearchMember({
3252
+ ...params,
2690
3253
  format: "plain",
2691
3254
  locale: stripHTML(locale),
2692
- visible: !0
2693
- }));
2694
- let reportSearchResults = memberSearchResponse.results ? memberSearchResponse.results : [], tempResults;
2695
- const metadata = (await dbReadMetadata()).data;
3255
+ visible: true
3256
+ });
3257
+ let reportSearchResults = memberSearchResponse.results ? memberSearchResponse.results : [];
3258
+ let tempResults;
3259
+ const metadataResponse = await dbReadMetadata();
3260
+ const metadata = metadataResponse.data;
2696
3261
  switch (format) {
2697
3262
  case "profiles":
2698
- tempResults = formatNested(reportSearchResults, metadata), reportSearchResults = addProfilesData(tempResults, metadata);
3263
+ tempResults = formatNested(reportSearchResults, metadata);
3264
+ reportSearchResults = addProfilesData(tempResults, metadata);
2699
3265
  break;
2700
3266
  }
2701
3267
  return {
2702
- meta: __spreadProps$3(__spreadValues$3({}, memberSearchResponse.meta), {
3268
+ meta: {
3269
+ ...memberSearchResponse.meta,
2703
3270
  format
2704
- }),
3271
+ },
2705
3272
  results: reportSearchResults
2706
3273
  };
2707
3274
  }
2708
3275
  }
2709
3276
  function dbUrlProxyFactory() {
2710
3277
  return async (request) => {
2711
- var _a;
2712
- const config = typeof request == "string" ? { url: request } : request;
3278
+ const config = typeof request === "string" ? { url: request } : request;
2713
3279
  try {
2714
3280
  const response = await axios.request(config);
2715
3281
  return {
2716
- ok: !0,
3282
+ ok: true,
2717
3283
  status: response.status,
2718
3284
  data: response.data
2719
3285
  };
2720
3286
  } catch (err) {
2721
- throw new BackendError(((_a = err.response) == null ? void 0 : _a.status) || 500, err.message);
3287
+ throw new BackendError(err.response?.status || 500, err.message);
2722
3288
  }
2723
3289
  };
2724
3290
  }
2725
- var __defProp$2 = Object.defineProperty, __defProps$2 = Object.defineProperties, __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$3 = Object.getOwnPropertySymbols, __hasOwnProp$3 = Object.prototype.hasOwnProperty, __propIsEnum$3 = Object.prototype.propertyIsEnumerable, __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$2 = (a, b) => {
2726
- for (var prop in b || (b = {}))
2727
- __hasOwnProp$3.call(b, prop) && __defNormalProp$2(a, prop, b[prop]);
2728
- if (__getOwnPropSymbols$3)
2729
- for (var prop of __getOwnPropSymbols$3(b))
2730
- __propIsEnum$3.call(b, prop) && __defNormalProp$2(a, prop, b[prop]);
2731
- return a;
2732
- }, __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
3291
+
3292
+ // api/db/index.ts
2733
3293
  function useDatabaseApi(_, __, api) {
2734
3294
  return getDB().then((dbModels) => {
2735
3295
  Object.assign(api, apiFactory(dbModels));
2736
3296
  });
2737
3297
  }
2738
3298
  function apiFactory(dbModels) {
2739
- return __spreadProps$2(__spreadValues$2({}, dbEntityFactory(dbModels)), {
3299
+ return {
3300
+ ...dbEntityFactory(dbModels),
2740
3301
  searchReport: resultWrapper(dbSearchReportFactory(dbModels)),
2741
3302
  readMetadata: resultWrapper(dbReadMetadataFactory(dbModels)),
2742
3303
  regenerateSearch: resultWrapper(dbRegenerateSearchFactory(dbModels)),
@@ -2748,16 +3309,8 @@ function apiFactory(dbModels) {
2748
3309
  imageUnsplashSave: dbImageSaveFactory(dbModels, "unsplash"),
2749
3310
  imageUploadSave: dbImageSaveFactory(dbModels, "upload"),
2750
3311
  urlProxy: dbUrlProxyFactory()
2751
- });
3312
+ };
2752
3313
  }
2753
- var __defProp$1 = Object.defineProperty, __defProps$1 = Object.defineProperties, __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$2 = Object.getOwnPropertySymbols, __hasOwnProp$2 = Object.prototype.hasOwnProperty, __propIsEnum$2 = Object.prototype.propertyIsEnumerable, __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$1 = (a, b) => {
2754
- for (var prop in b || (b = {}))
2755
- __hasOwnProp$2.call(b, prop) && __defNormalProp$1(a, prop, b[prop]);
2756
- if (__getOwnPropSymbols$2)
2757
- for (var prop of __getOwnPropSymbols$2(b))
2758
- __propIsEnum$2.call(b, prop) && __defNormalProp$1(a, prop, b[prop]);
2759
- return a;
2760
- }, __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
2761
3314
  async function parseBody(req) {
2762
3315
  const form = new formidable.IncomingForm();
2763
3316
  form.encoding = "utf-8";
@@ -2770,20 +3323,25 @@ async function parseBody(req) {
2770
3323
  resolve({ fields, files });
2771
3324
  });
2772
3325
  });
2773
- return __spreadProps$1(__spreadValues$1({}, bodyData.fields), {
3326
+ return {
3327
+ ...bodyData.fields,
2774
3328
  files: bodyData.files
2775
- });
3329
+ };
2776
3330
  }
2777
3331
  function endpointCRUDFactory(api, entity) {
2778
- const crudCreate = pickMethod(api, "create", entity), crudRead = pickMethod(api, "read", entity), crudUpdate = pickMethod(api, "update", entity), crudDelete = pickMethod(api, "delete", entity);
3332
+ const crudCreate = pickMethod(api, "create", entity);
3333
+ const crudRead = pickMethod(api, "read", entity);
3334
+ const crudUpdate = pickMethod(api, "update", entity);
3335
+ const crudDelete = pickMethod(api, "delete", entity);
2779
3336
  return [
2780
3337
  endpoint("POST", `create/${entity}`, (req) => {
2781
3338
  const { body } = req;
2782
3339
  return crudCreate(body);
2783
3340
  }),
2784
3341
  endpoint("GET", `read/${entity}`, (req) => {
2785
- const params = req.query, id = normalizeList(params.id).map(parseFiniteNumber);
2786
- return crudRead({ id, include: yn(params.include) });
3342
+ const params = req.query;
3343
+ const id = normalizeList(params.id).map(parseFiniteNumber);
3344
+ return crudRead({ id, include: yn3(params.include) });
2787
3345
  }),
2788
3346
  endpoint("POST", `update/${entity}`, (req) => {
2789
3347
  const { body } = req;
@@ -2800,47 +3358,55 @@ function endpointVariantCRUDFactory(api) {
2800
3358
  return [
2801
3359
  ...endpointCRUDFactory(api, "variant"),
2802
3360
  endpoint("GET", "validate/variant", (req) => {
2803
- const params = req.query, dimension = parseFiniteNumber(params.dimension);
2804
- return validateVariantSlug({ dimension, slug: slugify(params.slug) });
3361
+ const params = req.query;
3362
+ const dimension = parseFiniteNumber(params.dimension);
3363
+ return validateVariantSlug({ dimension, slug: slugify_default(params.slug) });
2805
3364
  })
2806
3365
  ];
2807
3366
  }
3367
+
3368
+ // api/endpoints/image/imageSave.ts
2808
3369
  function endpointImageSaveFactory(operations, provider) {
2809
- const saveMethodKey = `image${capitalize(provider)}Save`, saveMethod = operations[saveMethodKey];
3370
+ const saveMethodKey = `image${capitalize(provider)}Save`;
3371
+ const saveMethod = operations[saveMethodKey];
2810
3372
  return endpoint("POST", `images/save/${provider}`, (req) => {
2811
3373
  const params = req.body;
2812
- if (!params.content_id)
3374
+ if (!params.content_id) {
2813
3375
  throw new BackendError(400, "Missing 'content_id' parameter.");
2814
- if (!params.image_id)
3376
+ }
3377
+ if (!params.image_id) {
2815
3378
  throw new BackendError(400, "Missing 'image_id' parameter.");
3379
+ }
2816
3380
  return saveMethod(params);
2817
3381
  });
2818
3382
  }
3383
+
3384
+ // api/endpoints/image/imageSearch.ts
2819
3385
  function endpointImageSearchFactory(operations, provider) {
2820
- const searchMethodKey = `image${capitalize(provider)}Search`, searchMethod = operations[searchMethodKey];
3386
+ const searchMethodKey = `image${capitalize(provider)}Search`;
3387
+ const searchMethod = operations[searchMethodKey];
2821
3388
  return endpoint("GET", `images/search/${provider}`, async (req) => {
2822
3389
  const prompt = normalizeList(req.query.prompt)[0];
2823
- if (!prompt)
3390
+ if (!prompt) {
2824
3391
  throw new BackendError(400, "Empty 'prompt' param.");
3392
+ }
2825
3393
  return searchMethod({ prompt });
2826
3394
  });
2827
3395
  }
3396
+
3397
+ // api/endpoints/readMetadata.ts
2828
3398
  function endpointReadMetadataFactory(operations) {
2829
3399
  const { readMetadata } = operations;
2830
3400
  return endpoint("GET", "read/metadata", () => readMetadata({}));
2831
3401
  }
3402
+
3403
+ // api/endpoints/regenerateSearch.ts
2832
3404
  function endpointRegenerateSearchFactory(operations) {
2833
3405
  const { regenerateSearch } = operations;
2834
3406
  return endpoint("POST", "search/regenerate", () => regenerateSearch(void 0));
2835
3407
  }
2836
- var __defProp = Object.defineProperty, __defProps = Object.defineProperties, __getOwnPropDescs = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$1 = Object.getOwnPropertySymbols, __hasOwnProp$1 = Object.prototype.hasOwnProperty, __propIsEnum$1 = Object.prototype.propertyIsEnumerable, __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues = (a, b) => {
2837
- for (var prop in b || (b = {}))
2838
- __hasOwnProp$1.call(b, prop) && __defNormalProp(a, prop, b[prop]);
2839
- if (__getOwnPropSymbols$1)
2840
- for (var prop of __getOwnPropSymbols$1(b))
2841
- __propIsEnum$1.call(b, prop) && __defNormalProp(a, prop, b[prop]);
2842
- return a;
2843
- }, __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
3408
+
3409
+ // api/endpoints/searchReport.ts
2844
3410
  function endpointSearchReportFactory(operations) {
2845
3411
  const { searchReport } = operations;
2846
3412
  return endpoint("GET", "search/reports", (req) => {
@@ -2849,30 +3415,27 @@ function endpointSearchReportFactory(operations) {
2849
3415
  });
2850
3416
  }
2851
3417
  function parseSearchReportParams(query) {
2852
- return __spreadProps(__spreadValues({}, parseSearchMemberParams(query)), {
3418
+ return {
3419
+ ...parseSearchMemberParams(query),
2853
3420
  format: normalizeList(query.format)[0]
2854
- });
3421
+ };
2855
3422
  }
3423
+
3424
+ // api/endpoints/urlProxy.ts
2856
3425
  function endpointUrlProxyFactory(operations) {
2857
3426
  const { urlProxy } = operations;
2858
3427
  return endpoint("GET", "url/proxy", (req) => {
2859
3428
  const { url, method } = req.query;
2860
- return console.log("endpointUrlProxy", url), urlProxy({
3429
+ console.log("endpointUrlProxy", url);
3430
+ return urlProxy({
2861
3431
  url: normalizeList(url)[0],
2862
3432
  method: normalizeList(method)[0] === "POST" ? "POST" : "GET"
2863
3433
  });
2864
3434
  });
2865
3435
  }
2866
- var __getOwnPropSymbols = Object.getOwnPropertySymbols, __hasOwnProp = Object.prototype.hasOwnProperty, __propIsEnum = Object.prototype.propertyIsEnumerable, __objRest = (source, exclude) => {
2867
- var target = {};
2868
- for (var prop in source)
2869
- __hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0 && (target[prop] = source[prop]);
2870
- if (source != null && __getOwnPropSymbols)
2871
- for (var prop of __getOwnPropSymbols(source))
2872
- exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop) && (target[prop] = source[prop]);
2873
- return target;
2874
- };
2875
- const verbose = getLogging();
3436
+
3437
+ // api/endpoints/index.ts
3438
+ var verbose4 = getLogging_default();
2876
3439
  function endpointKey(method, path) {
2877
3440
  return `${method.toUpperCase()} ${path.toLowerCase()}`;
2878
3441
  }
@@ -2899,46 +3462,54 @@ function getEndpointMap(db) {
2899
3462
  endpointUrlProxyFactory(api)
2900
3463
  ].map(({ handler, method, path }) => [endpointKey(method, path), handler]));
2901
3464
  }
2902
- const endpointMap = getDB().then(getEndpointMap);
3465
+ var endpointMap = getDB().then(getEndpointMap);
2903
3466
  async function endpointNextJsHandlerFactory(req, res) {
2904
3467
  await NextCors(req, res, {
2905
3468
  methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
2906
3469
  origin: "*"
2907
3470
  });
2908
- const { query: queryParams, method } = req, _a = queryParams, { path } = _a, query = __objRest(_a, ["path"]);
3471
+ const { query: queryParams, method } = req;
3472
+ const { path, ...query } = queryParams;
2909
3473
  if (path && method) {
2910
3474
  const handler = await endpointMap.then((map) => {
2911
- const pathString = [].concat(path).join("/"), key = endpointKey(method, pathString);
3475
+ const pathString = [].concat(path).join("/");
3476
+ const key = endpointKey(method, pathString);
2912
3477
  return map[key];
2913
3478
  });
2914
- if (handler)
2915
- return ["POST", "DELETE"].includes(method) && (req.body = await parseBody(req)), Promise.resolve(req).then(handler).then((result) => {
2916
- if ("error" in result)
3479
+ if (handler) {
3480
+ if (["POST", "DELETE"].includes(method)) {
3481
+ req.body = await parseBody(req);
3482
+ }
3483
+ return Promise.resolve(req).then(handler).then((result) => {
3484
+ if ("error" in result) {
2917
3485
  throw new BackendError(result.status, result.error);
3486
+ }
2918
3487
  if (result.data instanceof Buffer) {
2919
3488
  const image = result.data;
2920
3489
  res.writeHead(result.status, { "Content-Type": "image/png" }).end(image, "binary");
2921
- } else
3490
+ } else {
2922
3491
  res.status(result.status).json({ data: result.data });
3492
+ }
2923
3493
  }).catch((err) => {
2924
- verbose && console.trace(err), res.status(err.code).json({ error: err.message });
3494
+ if (verbose4)
3495
+ console.trace(err);
3496
+ res.status(err.code).json({ error: err.message });
2925
3497
  });
2926
- } else
2927
- path || await endpointMap.then(console.log);
3498
+ }
3499
+ } else if (!path) {
3500
+ await endpointMap.then(console.log);
3501
+ }
2928
3502
  return res.status(404).json({ error: "No matching route", path, query });
2929
3503
  }
2930
- const reportsCrosswalkEntrypointFn = (crosswalk) => {
3504
+
3505
+ // cms/crosswalk/index.ts
3506
+ var reportsCrosswalkEntrypointFn = (crosswalk) => {
2931
3507
  const crosswalkFn = crosswalk;
2932
3508
  return async function(req, res) {
2933
3509
  const response = await crosswalkFn({ test: "pala" });
2934
3510
  return res.json(response);
2935
3511
  };
2936
3512
  };
2937
- export {
2938
- reportsCrosswalkEntrypointFn as ReportCrosswalkHandler,
2939
- apiFactory as dbApiFactory,
2940
- endpointKey,
2941
- endpointNextJsHandlerFactory,
2942
- getDB,
2943
- useDatabaseApi
2944
- };
3513
+ var crosswalk_default = reportsCrosswalkEntrypointFn;
3514
+
3515
+ export { crosswalk_default as ReportCrosswalkHandler, apiFactory as dbApiFactory, endpointKey, endpointNextJsHandlerFactory, getDB, useDatabaseApi };