@embeddable.com/sdk-core 3.2.0-next.9 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -4,6 +4,7 @@ var fs$1 = require('node:fs/promises');
4
4
  var path$1 = require('node:path');
5
5
  var vite = require('vite');
6
6
  require('node:child_process');
7
+ var crypto = require('node:crypto');
7
8
  var fs$2 = require('node:fs');
8
9
  var node = require('@stencil/core/sys/node');
9
10
  var compiler = require('@stencil/core/compiler');
@@ -43,6 +44,7 @@ function _interopNamespaceDefault(e) {
43
44
  var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs$1);
44
45
  var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path$1);
45
46
  var vite__namespace = /*#__PURE__*/_interopNamespaceDefault(vite);
47
+ var crypto__namespace = /*#__PURE__*/_interopNamespaceDefault(crypto);
46
48
  var fs__namespace$1 = /*#__PURE__*/_interopNamespaceDefault(fs$2);
47
49
  var YAML__namespace = /*#__PURE__*/_interopNamespaceDefault(YAML);
48
50
  var url__namespace = /*#__PURE__*/_interopNamespaceDefault(url$2);
@@ -257,6 +259,11 @@ let ZodError$1 = class ZodError extends Error {
257
259
  processError(this);
258
260
  return fieldErrors;
259
261
  }
262
+ static assert(value) {
263
+ if (!(value instanceof ZodError)) {
264
+ throw new Error(`Not a ZodError: ${value}`);
265
+ }
266
+ }
260
267
  toString() {
261
268
  return this.message;
262
269
  }
@@ -288,6 +295,11 @@ ZodError$1.create = (issues) => {
288
295
  const error = new ZodError$1(issues);
289
296
  return error;
290
297
  };
298
+
299
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
300
+ var e = new Error(message);
301
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
302
+ };
291
303
 
292
304
  var errorUtil$1;
293
305
  (function (errorUtil) {
@@ -363,6 +375,20 @@ const formatErrorPath = (path) => {
363
375
  return formatted;
364
376
  };
365
377
 
378
+ /**
379
+ * Get the hash of the content string. It returns the first 5 characters of the hash
380
+ * Example: getContentHash("Hello World")
381
+ * @param contentString The content string to hash
382
+ * @returns
383
+ */
384
+ const getContentHash = (contentString) => {
385
+ return crypto__namespace
386
+ .createHash("md5")
387
+ .update(contentString)
388
+ .digest("hex")
389
+ .substring(0, 5);
390
+ };
391
+
366
392
  const oraP$4 = import('ora');
367
393
  const EMB_TYPE_FILE_REGEX = /^(.*)\.type\.emb\.[jt]s$/;
368
394
  const EMB_OPTIONS_FILE_REGEX = /^(.*)\.options\.emb\.[jt]s$/;
@@ -395,6 +421,11 @@ async function build$1(ctx) {
395
421
  formats: ["es"],
396
422
  fileName: "embeddable-types",
397
423
  },
424
+ rollupOptions: {
425
+ output: {
426
+ entryFileNames: "embeddable-types-[hash].js",
427
+ },
428
+ },
398
429
  outDir: ctx.client.buildDir,
399
430
  },
400
431
  });
@@ -411,6 +442,8 @@ var prepare = async (ctx) => {
411
442
  async function removeIfExists(ctx) {
412
443
  if (fs__namespace$1.existsSync(ctx.client.buildDir))
413
444
  await fs__namespace.rm(ctx.client.buildDir, { recursive: true });
445
+ if (fs__namespace$1.existsSync(ctx.client.tmpDir))
446
+ await fs__namespace.rm(ctx.client.tmpDir, { recursive: true });
414
447
  }
415
448
  async function copyStencilConfigsToClient(ctx) {
416
449
  await fs__namespace.cp(ctx.core.configsDir, ctx.client.buildDir, { recursive: true });
@@ -448,12 +481,14 @@ async function runStencil(ctx) {
448
481
  const logger = ((_a = ctx.dev) === null || _a === void 0 ? void 0 : _a.logger) || node.createNodeLogger({ process });
449
482
  const sys = ((_b = ctx.dev) === null || _b === void 0 ? void 0 : _b.sys) || node.createNodeSys({ process });
450
483
  const devMode = !!ctx.dev;
484
+ const isWindows = process.platform === "win32";
451
485
  const validated = await compiler.loadConfig({
452
486
  initTsConfig: true,
453
487
  logger,
454
488
  sys,
455
489
  config: {
456
490
  devMode,
491
+ maxConcurrentWorkers: isWindows ? 0 : 8, // workers break on windows
457
492
  rootDir: ctx.client.buildDir,
458
493
  configPath: path__namespace.resolve(ctx.client.buildDir, "stencil.config.ts"),
459
494
  tsconfig: path__namespace.resolve(ctx.client.buildDir, "tsconfig.json"),
@@ -468,6 +503,11 @@ async function runStencil(ctx) {
468
503
  });
469
504
  const compiler$1 = await compiler.createCompiler(validated.config);
470
505
  await compiler$1.build();
506
+ const entryFilePath = path__namespace.resolve(ctx.client.stencilBuild, "embeddable-wrapper.esm.js");
507
+ const entryFileContent = await fs__namespace.readFile(entryFilePath, "utf8");
508
+ const fileHash = getContentHash(entryFileContent);
509
+ const newFileName = `embeddable-wrapper.esm-${fileHash}.js`;
510
+ await fs__namespace.rename(entryFilePath, path__namespace.resolve(ctx.client.stencilBuild, newFileName));
471
511
  await compiler$1.destroy();
472
512
  process.chdir(ctx.client.rootDir);
473
513
  }
@@ -497,10 +537,28 @@ var cleanup = async (ctx) => {
497
537
  await moveBuildTOBuildDir(ctx);
498
538
  };
499
539
  async function extractBuild(ctx) {
540
+ const [[, stencilWrapperFilePath]] = await findFiles(ctx.client.stencilBuild, /embeddable-wrapper.esm-[a-z0-9]+\.js/);
541
+ const stencilWrapperFileName = path__namespace.basename(stencilWrapperFilePath);
500
542
  await fs__namespace.rename(path__namespace.resolve(ctx.client.buildDir, ctx.client.stencilBuild), ctx.client.tmpDir);
501
- await fs__namespace.rename(path__namespace.resolve(ctx.client.buildDir, "embeddable-types.js"), path__namespace.join(ctx.client.tmpDir, "embeddable-types.js"));
502
- await fs__namespace.rename(path__namespace.resolve(ctx.client.buildDir, "embeddable-components-meta.js"), path__namespace.join(ctx.client.tmpDir, "embeddable-components-meta.js"));
503
- await fs__namespace.rename(path__namespace.resolve(ctx.client.buildDir, "embeddable-editors-meta.js"), path__namespace.join(ctx.client.tmpDir, "embeddable-editors-meta.js"));
543
+ const [[, typesFilePath]] = await findFiles(ctx.client.buildDir, /embeddable-types-[a-z0-9]+\.js/);
544
+ const typesFileName = path__namespace.basename(typesFilePath);
545
+ await fs__namespace.rename(typesFilePath, path__namespace.join(ctx.client.tmpDir, typesFileName));
546
+ const [[, metaFilePath]] = await findFiles(ctx.client.buildDir, /embeddable-components-meta-[a-z0-9]+\.js/);
547
+ const metaFileName = path__namespace.basename(metaFilePath);
548
+ await fs__namespace.rename(metaFilePath, path__namespace.join(ctx.client.tmpDir, metaFileName));
549
+ const [[, editorsMetaFilePath]] = await findFiles(ctx.client.buildDir, /embeddable-editors-meta-[a-z0-9]+\.js/);
550
+ const editorsMetaFileName = path__namespace.basename(editorsMetaFilePath);
551
+ await fs__namespace.rename(editorsMetaFilePath, path__namespace.join(ctx.client.tmpDir, editorsMetaFileName));
552
+ // write manifest file with files with hash
553
+ const manifest = {
554
+ entryFiles: {
555
+ "embeddable-types.js": typesFileName,
556
+ "embeddable-components-meta.js": metaFileName,
557
+ "embeddable-editors-meta.js": editorsMetaFileName,
558
+ "embeddable-wrapper.esm.js": stencilWrapperFileName,
559
+ },
560
+ };
561
+ await fs__namespace.writeFile(path__namespace.join(ctx.client.tmpDir, "embeddable-manifest.json"), JSON.stringify(manifest));
504
562
  }
505
563
  async function removeObsoleteDir(dir) {
506
564
  await fs__namespace.rm(dir, { recursive: true });
@@ -743,6 +801,11 @@ class ZodError extends Error {
743
801
  processError(this);
744
802
  return fieldErrors;
745
803
  }
804
+ static assert(value) {
805
+ if (!(value instanceof ZodError)) {
806
+ throw new Error(`Not a ZodError: ${value}`);
807
+ }
808
+ }
746
809
  toString() {
747
810
  return this.message;
748
811
  }
@@ -915,6 +978,13 @@ const makeIssue = (params) => {
915
978
  ...issueData,
916
979
  path: fullPath,
917
980
  };
981
+ if (issueData.message !== undefined) {
982
+ return {
983
+ ...issueData,
984
+ path: fullPath,
985
+ message: issueData.message,
986
+ };
987
+ }
918
988
  let errorMessage = "";
919
989
  const maps = errorMaps
920
990
  .filter((m) => !!m)
@@ -926,11 +996,12 @@ const makeIssue = (params) => {
926
996
  return {
927
997
  ...issueData,
928
998
  path: fullPath,
929
- message: issueData.message || errorMessage,
999
+ message: errorMessage,
930
1000
  };
931
1001
  };
932
1002
  const EMPTY_PATH = [];
933
1003
  function addIssueToContext(ctx, issueData) {
1004
+ const overrideMap = getErrorMap();
934
1005
  const issue = makeIssue({
935
1006
  issueData: issueData,
936
1007
  data: ctx.data,
@@ -938,8 +1009,8 @@ function addIssueToContext(ctx, issueData) {
938
1009
  errorMaps: [
939
1010
  ctx.common.contextualErrorMap,
940
1011
  ctx.schemaErrorMap,
941
- getErrorMap(),
942
- errorMap, // then global default map
1012
+ overrideMap,
1013
+ overrideMap === errorMap ? undefined : errorMap, // then global default map
943
1014
  ].filter((x) => !!x),
944
1015
  });
945
1016
  ctx.common.issues.push(issue);
@@ -970,9 +1041,11 @@ class ParseStatus {
970
1041
  static async mergeObjectAsync(status, pairs) {
971
1042
  const syncPairs = [];
972
1043
  for (const pair of pairs) {
1044
+ const key = await pair.key;
1045
+ const value = await pair.value;
973
1046
  syncPairs.push({
974
- key: await pair.key,
975
- value: await pair.value,
1047
+ key,
1048
+ value,
976
1049
  });
977
1050
  }
978
1051
  return ParseStatus.mergeObjectSync(status, syncPairs);
@@ -1007,12 +1080,46 @@ const isDirty = (x) => x.status === "dirty";
1007
1080
  const isValid = (x) => x.status === "valid";
1008
1081
  const isAsync$1 = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1009
1082
 
1083
+ /******************************************************************************
1084
+ Copyright (c) Microsoft Corporation.
1085
+
1086
+ Permission to use, copy, modify, and/or distribute this software for any
1087
+ purpose with or without fee is hereby granted.
1088
+
1089
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1090
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1091
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1092
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1093
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1094
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1095
+ PERFORMANCE OF THIS SOFTWARE.
1096
+ ***************************************************************************** */
1097
+
1098
+ function __classPrivateFieldGet(receiver, state, kind, f) {
1099
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1100
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
1101
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1102
+ }
1103
+
1104
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
1105
+ if (kind === "m") throw new TypeError("Private method is not writable");
1106
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1107
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
1108
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
1109
+ }
1110
+
1111
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
1112
+ var e = new Error(message);
1113
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1114
+ };
1115
+
1010
1116
  var errorUtil;
1011
1117
  (function (errorUtil) {
1012
1118
  errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
1013
1119
  errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
1014
1120
  })(errorUtil || (errorUtil = {}));
1015
1121
 
1122
+ var _ZodEnum_cache, _ZodNativeEnum_cache;
1016
1123
  class ParseInputLazyPath {
1017
1124
  constructor(parent, value, path, key) {
1018
1125
  this._cachedPath = [];
@@ -1063,12 +1170,17 @@ function processCreateParams(params) {
1063
1170
  if (errorMap)
1064
1171
  return { errorMap: errorMap, description };
1065
1172
  const customMap = (iss, ctx) => {
1066
- if (iss.code !== "invalid_type")
1067
- return { message: ctx.defaultError };
1173
+ var _a, _b;
1174
+ const { message } = params;
1175
+ if (iss.code === "invalid_enum_value") {
1176
+ return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
1177
+ }
1068
1178
  if (typeof ctx.data === "undefined") {
1069
- return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
1179
+ return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
1070
1180
  }
1071
- return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
1181
+ if (iss.code !== "invalid_type")
1182
+ return { message: ctx.defaultError };
1183
+ return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
1072
1184
  };
1073
1185
  return { errorMap: customMap, description };
1074
1186
  }
@@ -1326,11 +1438,13 @@ class ZodType {
1326
1438
  }
1327
1439
  }
1328
1440
  const cuidRegex = /^c[^\s-]{8,}$/i;
1329
- const cuid2Regex = /^[a-z][a-z0-9]*$/;
1441
+ const cuid2Regex = /^[0-9a-z]+$/;
1330
1442
  const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
1331
1443
  // const uuidRegex =
1332
1444
  // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
1333
1445
  const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
1446
+ const nanoidRegex = /^[a-z0-9_-]{21}$/i;
1447
+ const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
1334
1448
  // from https://stackoverflow.com/a/46181/1550155
1335
1449
  // old version: too slow, didn't support unicode
1336
1450
  // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
@@ -1343,41 +1457,48 @@ const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-
1343
1457
  // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
1344
1458
  // const emailRegex =
1345
1459
  // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
1346
- const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1460
+ const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1347
1461
  // const emailRegex =
1348
1462
  // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
1349
1463
  // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
1350
1464
  const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1351
1465
  let emojiRegex;
1352
- const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
1466
+ // faster, simpler, safer
1467
+ const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1353
1468
  const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
1354
- // Adapted from https://stackoverflow.com/a/3143231
1355
- const datetimeRegex = (args) => {
1469
+ // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
1470
+ const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1471
+ // simple
1472
+ // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
1473
+ // no leap year validation
1474
+ // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
1475
+ // with leap year validation
1476
+ const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
1477
+ const dateRegex = new RegExp(`^${dateRegexSource}$`);
1478
+ function timeRegexSource(args) {
1479
+ // let regex = `\\d{2}:\\d{2}:\\d{2}`;
1480
+ let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
1356
1481
  if (args.precision) {
1357
- if (args.offset) {
1358
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1359
- }
1360
- else {
1361
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
1362
- }
1363
- }
1364
- else if (args.precision === 0) {
1365
- if (args.offset) {
1366
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1367
- }
1368
- else {
1369
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
1370
- }
1482
+ regex = `${regex}\\.\\d{${args.precision}}`;
1371
1483
  }
1372
- else {
1373
- if (args.offset) {
1374
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1375
- }
1376
- else {
1377
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
1378
- }
1484
+ else if (args.precision == null) {
1485
+ regex = `${regex}(\\.\\d+)?`;
1379
1486
  }
1380
- };
1487
+ return regex;
1488
+ }
1489
+ function timeRegex(args) {
1490
+ return new RegExp(`^${timeRegexSource(args)}$`);
1491
+ }
1492
+ // Adapted from https://stackoverflow.com/a/3143231
1493
+ function datetimeRegex(args) {
1494
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1495
+ const opts = [];
1496
+ opts.push(args.local ? `Z?` : `Z`);
1497
+ if (args.offset)
1498
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1499
+ regex = `${regex}(${opts.join("|")})`;
1500
+ return new RegExp(`^${regex}$`);
1501
+ }
1381
1502
  function isValidIP(ip, version) {
1382
1503
  if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1383
1504
  return true;
@@ -1399,9 +1520,7 @@ class ZodString extends ZodType {
1399
1520
  code: ZodIssueCode.invalid_type,
1400
1521
  expected: ZodParsedType.string,
1401
1522
  received: ctx.parsedType,
1402
- }
1403
- //
1404
- );
1523
+ });
1405
1524
  return INVALID;
1406
1525
  }
1407
1526
  const status = new ParseStatus();
@@ -1499,6 +1618,17 @@ class ZodString extends ZodType {
1499
1618
  status.dirty();
1500
1619
  }
1501
1620
  }
1621
+ else if (check.kind === "nanoid") {
1622
+ if (!nanoidRegex.test(input.data)) {
1623
+ ctx = this._getOrReturnCtx(input, ctx);
1624
+ addIssueToContext(ctx, {
1625
+ validation: "nanoid",
1626
+ code: ZodIssueCode.invalid_string,
1627
+ message: check.message,
1628
+ });
1629
+ status.dirty();
1630
+ }
1631
+ }
1502
1632
  else if (check.kind === "cuid") {
1503
1633
  if (!cuidRegex.test(input.data)) {
1504
1634
  ctx = this._getOrReturnCtx(input, ctx);
@@ -1613,6 +1743,41 @@ class ZodString extends ZodType {
1613
1743
  status.dirty();
1614
1744
  }
1615
1745
  }
1746
+ else if (check.kind === "date") {
1747
+ const regex = dateRegex;
1748
+ if (!regex.test(input.data)) {
1749
+ ctx = this._getOrReturnCtx(input, ctx);
1750
+ addIssueToContext(ctx, {
1751
+ code: ZodIssueCode.invalid_string,
1752
+ validation: "date",
1753
+ message: check.message,
1754
+ });
1755
+ status.dirty();
1756
+ }
1757
+ }
1758
+ else if (check.kind === "time") {
1759
+ const regex = timeRegex(check);
1760
+ if (!regex.test(input.data)) {
1761
+ ctx = this._getOrReturnCtx(input, ctx);
1762
+ addIssueToContext(ctx, {
1763
+ code: ZodIssueCode.invalid_string,
1764
+ validation: "time",
1765
+ message: check.message,
1766
+ });
1767
+ status.dirty();
1768
+ }
1769
+ }
1770
+ else if (check.kind === "duration") {
1771
+ if (!durationRegex.test(input.data)) {
1772
+ ctx = this._getOrReturnCtx(input, ctx);
1773
+ addIssueToContext(ctx, {
1774
+ validation: "duration",
1775
+ code: ZodIssueCode.invalid_string,
1776
+ message: check.message,
1777
+ });
1778
+ status.dirty();
1779
+ }
1780
+ }
1616
1781
  else if (check.kind === "ip") {
1617
1782
  if (!isValidIP(input.data, check.version)) {
1618
1783
  ctx = this._getOrReturnCtx(input, ctx);
@@ -1624,6 +1789,17 @@ class ZodString extends ZodType {
1624
1789
  status.dirty();
1625
1790
  }
1626
1791
  }
1792
+ else if (check.kind === "base64") {
1793
+ if (!base64Regex.test(input.data)) {
1794
+ ctx = this._getOrReturnCtx(input, ctx);
1795
+ addIssueToContext(ctx, {
1796
+ validation: "base64",
1797
+ code: ZodIssueCode.invalid_string,
1798
+ message: check.message,
1799
+ });
1800
+ status.dirty();
1801
+ }
1802
+ }
1627
1803
  else {
1628
1804
  util$7.assertNever(check);
1629
1805
  }
@@ -1655,6 +1831,9 @@ class ZodString extends ZodType {
1655
1831
  uuid(message) {
1656
1832
  return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1657
1833
  }
1834
+ nanoid(message) {
1835
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1836
+ }
1658
1837
  cuid(message) {
1659
1838
  return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1660
1839
  }
@@ -1664,16 +1843,20 @@ class ZodString extends ZodType {
1664
1843
  ulid(message) {
1665
1844
  return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1666
1845
  }
1846
+ base64(message) {
1847
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1848
+ }
1667
1849
  ip(options) {
1668
1850
  return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1669
1851
  }
1670
1852
  datetime(options) {
1671
- var _a;
1853
+ var _a, _b;
1672
1854
  if (typeof options === "string") {
1673
1855
  return this._addCheck({
1674
1856
  kind: "datetime",
1675
1857
  precision: null,
1676
1858
  offset: false,
1859
+ local: false,
1677
1860
  message: options,
1678
1861
  });
1679
1862
  }
@@ -1681,9 +1864,30 @@ class ZodString extends ZodType {
1681
1864
  kind: "datetime",
1682
1865
  precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
1683
1866
  offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
1867
+ local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
1684
1868
  ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
1685
1869
  });
1686
1870
  }
1871
+ date(message) {
1872
+ return this._addCheck({ kind: "date", message });
1873
+ }
1874
+ time(options) {
1875
+ if (typeof options === "string") {
1876
+ return this._addCheck({
1877
+ kind: "time",
1878
+ precision: null,
1879
+ message: options,
1880
+ });
1881
+ }
1882
+ return this._addCheck({
1883
+ kind: "time",
1884
+ precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
1885
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
1886
+ });
1887
+ }
1888
+ duration(message) {
1889
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1890
+ }
1687
1891
  regex(regex, message) {
1688
1892
  return this._addCheck({
1689
1893
  kind: "regex",
@@ -1762,6 +1966,15 @@ class ZodString extends ZodType {
1762
1966
  get isDatetime() {
1763
1967
  return !!this._def.checks.find((ch) => ch.kind === "datetime");
1764
1968
  }
1969
+ get isDate() {
1970
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1971
+ }
1972
+ get isTime() {
1973
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1974
+ }
1975
+ get isDuration() {
1976
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1977
+ }
1765
1978
  get isEmail() {
1766
1979
  return !!this._def.checks.find((ch) => ch.kind === "email");
1767
1980
  }
@@ -1774,6 +1987,9 @@ class ZodString extends ZodType {
1774
1987
  get isUUID() {
1775
1988
  return !!this._def.checks.find((ch) => ch.kind === "uuid");
1776
1989
  }
1990
+ get isNANOID() {
1991
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1992
+ }
1777
1993
  get isCUID() {
1778
1994
  return !!this._def.checks.find((ch) => ch.kind === "cuid");
1779
1995
  }
@@ -1786,6 +2002,9 @@ class ZodString extends ZodType {
1786
2002
  get isIP() {
1787
2003
  return !!this._def.checks.find((ch) => ch.kind === "ip");
1788
2004
  }
2005
+ get isBase64() {
2006
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
2007
+ }
1789
2008
  get minLength() {
1790
2009
  let min = null;
1791
2010
  for (const ch of this._def.checks) {
@@ -2773,9 +2992,10 @@ class ZodObject extends ZodType {
2773
2992
  const syncPairs = [];
2774
2993
  for (const pair of pairs) {
2775
2994
  const key = await pair.key;
2995
+ const value = await pair.value;
2776
2996
  syncPairs.push({
2777
2997
  key,
2778
- value: await pair.value,
2998
+ value,
2779
2999
  alwaysSet: pair.alwaysSet,
2780
3000
  });
2781
3001
  }
@@ -3149,7 +3369,7 @@ const getDiscriminator = (type) => {
3149
3369
  }
3150
3370
  else if (type instanceof ZodNativeEnum) {
3151
3371
  // eslint-disable-next-line ban/ban
3152
- return Object.keys(type.enum);
3372
+ return util$7.objectValues(type.enum);
3153
3373
  }
3154
3374
  else if (type instanceof ZodDefault) {
3155
3375
  return getDiscriminator(type._def.innerType);
@@ -3160,8 +3380,23 @@ const getDiscriminator = (type) => {
3160
3380
  else if (type instanceof ZodNull) {
3161
3381
  return [null];
3162
3382
  }
3383
+ else if (type instanceof ZodOptional) {
3384
+ return [undefined, ...getDiscriminator(type.unwrap())];
3385
+ }
3386
+ else if (type instanceof ZodNullable) {
3387
+ return [null, ...getDiscriminator(type.unwrap())];
3388
+ }
3389
+ else if (type instanceof ZodBranded) {
3390
+ return getDiscriminator(type.unwrap());
3391
+ }
3392
+ else if (type instanceof ZodReadonly) {
3393
+ return getDiscriminator(type.unwrap());
3394
+ }
3395
+ else if (type instanceof ZodCatch) {
3396
+ return getDiscriminator(type._def.innerType);
3397
+ }
3163
3398
  else {
3164
- return null;
3399
+ return [];
3165
3400
  }
3166
3401
  };
3167
3402
  class ZodDiscriminatedUnion extends ZodType {
@@ -3224,7 +3459,7 @@ class ZodDiscriminatedUnion extends ZodType {
3224
3459
  // try {
3225
3460
  for (const type of options) {
3226
3461
  const discriminatorValues = getDiscriminator(type.shape[discriminator]);
3227
- if (!discriminatorValues) {
3462
+ if (!discriminatorValues.length) {
3228
3463
  throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
3229
3464
  }
3230
3465
  for (const value of discriminatorValues) {
@@ -3437,6 +3672,7 @@ class ZodRecord extends ZodType {
3437
3672
  pairs.push({
3438
3673
  key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3439
3674
  value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3675
+ alwaysSet: key in ctx.data,
3440
3676
  });
3441
3677
  }
3442
3678
  if (ctx.common.async) {
@@ -3796,6 +4032,10 @@ function createZodEnum(values, params) {
3796
4032
  });
3797
4033
  }
3798
4034
  class ZodEnum extends ZodType {
4035
+ constructor() {
4036
+ super(...arguments);
4037
+ _ZodEnum_cache.set(this, void 0);
4038
+ }
3799
4039
  _parse(input) {
3800
4040
  if (typeof input.data !== "string") {
3801
4041
  const ctx = this._getOrReturnCtx(input);
@@ -3807,7 +4047,10 @@ class ZodEnum extends ZodType {
3807
4047
  });
3808
4048
  return INVALID;
3809
4049
  }
3810
- if (this._def.values.indexOf(input.data) === -1) {
4050
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
4051
+ __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
4052
+ }
4053
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
3811
4054
  const ctx = this._getOrReturnCtx(input);
3812
4055
  const expectedValues = this._def.values;
3813
4056
  addIssueToContext(ctx, {
@@ -3843,15 +4086,26 @@ class ZodEnum extends ZodType {
3843
4086
  }
3844
4087
  return enumValues;
3845
4088
  }
3846
- extract(values) {
3847
- return ZodEnum.create(values);
4089
+ extract(values, newDef = this._def) {
4090
+ return ZodEnum.create(values, {
4091
+ ...this._def,
4092
+ ...newDef,
4093
+ });
3848
4094
  }
3849
- exclude(values) {
3850
- return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
4095
+ exclude(values, newDef = this._def) {
4096
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
4097
+ ...this._def,
4098
+ ...newDef,
4099
+ });
3851
4100
  }
3852
4101
  }
4102
+ _ZodEnum_cache = new WeakMap();
3853
4103
  ZodEnum.create = createZodEnum;
3854
4104
  class ZodNativeEnum extends ZodType {
4105
+ constructor() {
4106
+ super(...arguments);
4107
+ _ZodNativeEnum_cache.set(this, void 0);
4108
+ }
3855
4109
  _parse(input) {
3856
4110
  const nativeEnumValues = util$7.getValidEnumValues(this._def.values);
3857
4111
  const ctx = this._getOrReturnCtx(input);
@@ -3865,7 +4119,10 @@ class ZodNativeEnum extends ZodType {
3865
4119
  });
3866
4120
  return INVALID;
3867
4121
  }
3868
- if (nativeEnumValues.indexOf(input.data) === -1) {
4122
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
4123
+ __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util$7.getValidEnumValues(this._def.values)), "f");
4124
+ }
4125
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
3869
4126
  const expectedValues = util$7.objectValues(nativeEnumValues);
3870
4127
  addIssueToContext(ctx, {
3871
4128
  received: ctx.data,
@@ -3880,6 +4137,7 @@ class ZodNativeEnum extends ZodType {
3880
4137
  return this._def.values;
3881
4138
  }
3882
4139
  }
4140
+ _ZodNativeEnum_cache = new WeakMap();
3883
4141
  ZodNativeEnum.create = (values, params) => {
3884
4142
  return new ZodNativeEnum({
3885
4143
  values: values,
@@ -3949,33 +4207,43 @@ class ZodEffects extends ZodType {
3949
4207
  checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3950
4208
  if (effect.type === "preprocess") {
3951
4209
  const processed = effect.transform(ctx.data, checkCtx);
3952
- if (ctx.common.issues.length) {
3953
- return {
3954
- status: "dirty",
3955
- value: ctx.data,
3956
- };
3957
- }
3958
4210
  if (ctx.common.async) {
3959
- return Promise.resolve(processed).then((processed) => {
3960
- return this._def.schema._parseAsync({
4211
+ return Promise.resolve(processed).then(async (processed) => {
4212
+ if (status.value === "aborted")
4213
+ return INVALID;
4214
+ const result = await this._def.schema._parseAsync({
3961
4215
  data: processed,
3962
4216
  path: ctx.path,
3963
4217
  parent: ctx,
3964
4218
  });
4219
+ if (result.status === "aborted")
4220
+ return INVALID;
4221
+ if (result.status === "dirty")
4222
+ return DIRTY(result.value);
4223
+ if (status.value === "dirty")
4224
+ return DIRTY(result.value);
4225
+ return result;
3965
4226
  });
3966
4227
  }
3967
4228
  else {
3968
- return this._def.schema._parseSync({
4229
+ if (status.value === "aborted")
4230
+ return INVALID;
4231
+ const result = this._def.schema._parseSync({
3969
4232
  data: processed,
3970
4233
  path: ctx.path,
3971
4234
  parent: ctx,
3972
4235
  });
4236
+ if (result.status === "aborted")
4237
+ return INVALID;
4238
+ if (result.status === "dirty")
4239
+ return DIRTY(result.value);
4240
+ if (status.value === "dirty")
4241
+ return DIRTY(result.value);
4242
+ return result;
3973
4243
  }
3974
4244
  }
3975
4245
  if (effect.type === "refinement") {
3976
- const executeRefinement = (acc
3977
- // effect: RefinementEffect<any>
3978
- ) => {
4246
+ const executeRefinement = (acc) => {
3979
4247
  const result = effect.refinement(acc, checkCtx);
3980
4248
  if (ctx.common.async) {
3981
4249
  return Promise.resolve(result);
@@ -4278,10 +4546,18 @@ class ZodPipeline extends ZodType {
4278
4546
  class ZodReadonly extends ZodType {
4279
4547
  _parse(input) {
4280
4548
  const result = this._def.innerType._parse(input);
4281
- if (isValid(result)) {
4282
- result.value = Object.freeze(result.value);
4283
- }
4284
- return result;
4549
+ const freeze = (data) => {
4550
+ if (isValid(data)) {
4551
+ data.value = Object.freeze(data.value);
4552
+ }
4553
+ return data;
4554
+ };
4555
+ return isAsync$1(result)
4556
+ ? result.then((data) => freeze(data))
4557
+ : freeze(result);
4558
+ }
4559
+ unwrap() {
4560
+ return this._def.innerType;
4285
4561
  }
4286
4562
  }
4287
4563
  ZodReadonly.create = (type, params) => {
@@ -4291,7 +4567,7 @@ ZodReadonly.create = (type, params) => {
4291
4567
  ...processCreateParams(params),
4292
4568
  });
4293
4569
  };
4294
- const custom = (check, params = {},
4570
+ function custom(check, params = {},
4295
4571
  /**
4296
4572
  * @deprecated
4297
4573
  *
@@ -4302,7 +4578,7 @@ const custom = (check, params = {},
4302
4578
  * ```
4303
4579
  *
4304
4580
  */
4305
- fatal) => {
4581
+ fatal) {
4306
4582
  if (check)
4307
4583
  return ZodAny.create().superRefine((data, ctx) => {
4308
4584
  var _a, _b;
@@ -4318,7 +4594,7 @@ fatal) => {
4318
4594
  }
4319
4595
  });
4320
4596
  return ZodAny.create();
4321
- };
4597
+ }
4322
4598
  const late = {
4323
4599
  object: ZodObject.lazycreate,
4324
4600
  };
@@ -4436,6 +4712,7 @@ var z = /*#__PURE__*/Object.freeze({
4436
4712
  ZodParsedType: ZodParsedType,
4437
4713
  getParsedType: getParsedType,
4438
4714
  ZodType: ZodType,
4715
+ datetimeRegex: datetimeRegex,
4439
4716
  ZodString: ZodString,
4440
4717
  ZodNumber: ZodNumber,
4441
4718
  ZodBigInt: ZodBigInt,
@@ -4540,7 +4817,7 @@ var validate = async (ctx, exitIfInvalid = true) => {
4540
4817
  const ora = (await import('ora')).default;
4541
4818
  const spinnerValidate = ora("Data model validation...").start();
4542
4819
  const filesList = await findFiles(ctx.client.srcDir, CUBE_YAML_FILE_REGEX);
4543
- const securityContextFilesList = await findFiles(ctx.client.srcDir, SECURITY_CONTEXT_FILE_REGEX);
4820
+ const securityContextFilesList = await findFiles(ctx.client.modelsSrc || ctx.client.srcDir, SECURITY_CONTEXT_FILE_REGEX);
4544
4821
  const dataModelErrors = await dataModelsValidation(filesList);
4545
4822
  if (dataModelErrors.length) {
4546
4823
  spinnerValidate.fail("One or more cube.yaml files are invalid:");
@@ -4565,9 +4842,18 @@ async function dataModelsValidation(filesList) {
4565
4842
  for (const [_, filePath] of filesList) {
4566
4843
  const fileContentRaw = await fs__namespace.readFile(filePath, "utf8");
4567
4844
  const cube = YAML__namespace.parse(fileContentRaw);
4568
- const safeParse = cubeModelSchema.safeParse(cube);
4569
- if (!safeParse.success) {
4570
- errorFormatter(safeParse.error.issues).forEach((error) => {
4845
+ if (!(cube === null || cube === void 0 ? void 0 : cube.cubes) && !(cube === null || cube === void 0 ? void 0 : cube.views)) {
4846
+ return [`${filePath}: At least one cubes or views must be defined`];
4847
+ }
4848
+ const cubeModelSafeParse = cubeModelSchema.safeParse(cube);
4849
+ const viewModelSafeParse = viewModelSchema.safeParse(cube);
4850
+ if (cube.cubes && !cubeModelSafeParse.success) {
4851
+ errorFormatter(cubeModelSafeParse.error.issues).forEach((error) => {
4852
+ errors.push(`${filePath}: ${error}`);
4853
+ });
4854
+ }
4855
+ if (cube.views && !viewModelSafeParse.success) {
4856
+ errorFormatter(viewModelSafeParse.error.issues).forEach((error) => {
4571
4857
  errors.push(`${filePath}: ${error}`);
4572
4858
  });
4573
4859
  }
@@ -4646,6 +4932,19 @@ const cubeModelSchema = z
4646
4932
  message: "At least one measure or dimension must be defined",
4647
4933
  path: ["cubes"],
4648
4934
  });
4935
+ const viewModelSchema = z.object({
4936
+ views: z
4937
+ .object({
4938
+ name: z.string(),
4939
+ cubes: z
4940
+ .object({
4941
+ join_path: z.string(),
4942
+ })
4943
+ .array(),
4944
+ })
4945
+ .array()
4946
+ .min(1),
4947
+ });
4649
4948
  const securityContextSchema = z.array(z.object({
4650
4949
  name: z.string(),
4651
4950
  securityContext: z.object({}), // can be any object
@@ -20002,6 +20301,25 @@ const checkNodeVersion = async () => {
20002
20301
  process.exit(1);
20003
20302
  }
20004
20303
  };
20304
+ /**
20305
+ * Get the value of a process argument by key
20306
+ * Example: getArgumentByKey("--email") or getArgumentByKey(["--email", "-e"])
20307
+ * @param key The key to search for in the process arguments
20308
+ * @returns
20309
+ */
20310
+ const getArgumentByKey = (key) => {
20311
+ if (Array.isArray(key)) {
20312
+ for (const k of key) {
20313
+ if (process.argv.includes(k)) {
20314
+ const index = process.argv.indexOf(k);
20315
+ return index !== -1 ? process.argv[index + 1] : undefined;
20316
+ }
20317
+ }
20318
+ return undefined;
20319
+ }
20320
+ const index = process.argv.indexOf(key);
20321
+ return index !== -1 ? process.argv[index + 1] : undefined;
20322
+ };
20005
20323
 
20006
20324
  var build = async () => {
20007
20325
  try {
@@ -20112,29 +20430,58 @@ const inquirerSelect = import('@inquirer/select');
20112
20430
  const YAML_OR_JS_FILES = /^(.*)\.(cube|sc)\.(ya?ml|js)$/;
20113
20431
  let ora$1;
20114
20432
  var push = async () => {
20115
- var _a;
20433
+ var _a, _b;
20116
20434
  let spinnerPushing;
20117
20435
  try {
20118
20436
  checkNodeVersion();
20119
20437
  ora$1 = (await oraP$1).default;
20120
20438
  const config = await provideConfig();
20439
+ if (process.argv.includes("--api-key") || process.argv.includes("-k")) {
20440
+ spinnerPushing = ora$1("Using API key...").start();
20441
+ await pushByApiKey(config, spinnerPushing);
20442
+ spinnerPushing.succeed("Published using API key");
20443
+ return;
20444
+ }
20121
20445
  const token = await verify(config);
20122
20446
  const { workspaceId, name: workspaceName } = await selectWorkspace(config, token);
20123
- const spinnerArchive = ora$1("Building...").start();
20124
- const filesList = await findFiles(config.client.srcDir, YAML_OR_JS_FILES);
20125
- await archive(config, filesList);
20126
- spinnerArchive.succeed("Bundling completed");
20127
- spinnerPushing = ora$1(`Publishing to ${workspaceName} using ${config.pushBaseUrl}...`).start();
20447
+ const workspacePreviewUrl = `${config.previewBaseUrl}/workspace/${workspaceId}`;
20448
+ await buildArchive(config);
20449
+ spinnerPushing = ora$1(`Publishing to ${workspaceName} using ${workspacePreviewUrl}...`).start();
20128
20450
  await sendBuild(config, { workspaceId, token });
20129
- spinnerPushing.succeed(`Published to ${workspaceName} using ${config.pushBaseUrl}`);
20451
+ spinnerPushing.succeed(`Published to ${workspaceName} using ${workspacePreviewUrl}`);
20130
20452
  }
20131
20453
  catch (error) {
20132
20454
  spinnerPushing === null || spinnerPushing === void 0 ? void 0 : spinnerPushing.fail("Publishing failed");
20133
- console.error(((_a = error.response) === null || _a === void 0 ? void 0 : _a.data) || (error === null || error === void 0 ? void 0 : error.message) || error);
20455
+ if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.statusText) === "Unauthorized") {
20456
+ console.error("Unauthorized. Please check your credentials.");
20457
+ }
20458
+ else {
20459
+ console.error(((_b = error.response) === null || _b === void 0 ? void 0 : _b.data) || (error === null || error === void 0 ? void 0 : error.message) || error);
20460
+ }
20134
20461
  await reportErrorToRollbar(error);
20135
20462
  process.exit(1);
20136
20463
  }
20137
20464
  };
20465
+ async function pushByApiKey(config, spinner) {
20466
+ const apiKey = getArgumentByKey(["--api-key", "-k"]);
20467
+ if (!apiKey) {
20468
+ spinner.fail("No API key provided");
20469
+ process.exit(1);
20470
+ }
20471
+ const email = getArgumentByKey(["--email", "-e"]);
20472
+ if (!email || !/\S+@\S+\.\S+/.test(email)) {
20473
+ spinner.fail("Invalid email provided. Please provide a valid email using --email (-e) flag");
20474
+ process.exit(1);
20475
+ }
20476
+ // message is optional
20477
+ const message = getArgumentByKey(["--message", "-m"]);
20478
+ await buildArchive(config);
20479
+ return sendBuildByApiKey(config, {
20480
+ apiKey,
20481
+ email,
20482
+ message,
20483
+ });
20484
+ }
20138
20485
  async function selectWorkspace(ctx, token) {
20139
20486
  const workspaceSpinner = ora$1({
20140
20487
  text: `Fetching workspaces using ${ctx.pushBaseUrl}...`,
@@ -20180,6 +20527,12 @@ async function verify(ctx) {
20180
20527
  }
20181
20528
  return token;
20182
20529
  }
20530
+ async function buildArchive(config) {
20531
+ const spinnerArchive = ora$1("Building...").start();
20532
+ const filesList = await findFiles(config.client.modelsSrc || config.client.srcDir, YAML_OR_JS_FILES);
20533
+ await archive(config, filesList);
20534
+ return spinnerArchive.succeed("Bundling completed");
20535
+ }
20183
20536
  async function archive(ctx, yamlFiles, includeBuild = true) {
20184
20537
  const output = fs__namespace$1.createWriteStream(ctx.client.archiveFile);
20185
20538
  const _archiver = archiver__namespace.create("zip", {
@@ -20200,13 +20553,30 @@ async function archive(ctx, yamlFiles, includeBuild = true) {
20200
20553
  output.on("close", resolve);
20201
20554
  });
20202
20555
  }
20556
+ async function sendBuildByApiKey(ctx, { apiKey, email, message }) {
20557
+ var _a;
20558
+ const { FormData, Blob } = await import('formdata-node');
20559
+ const { fileFromPath } = await Promise.resolve().then(function () { return fileFromPath$1; });
20560
+ const file = await fileFromPath(ctx.client.archiveFile, "embeddable-build.zip");
20561
+ const form = new FormData();
20562
+ form.set("file", file, "embeddable-build.zip");
20563
+ const metadataBlob = new Blob([JSON.stringify({ authorEmail: email, description: message })], { type: "application/json" });
20564
+ form.set("metadata", metadataBlob, "metadata.json");
20565
+ const response = await uploadFile(form, `${ctx.pushBaseUrl}/api/v1/bundle/upload`, apiKey);
20566
+ await fs__namespace.rm(ctx.client.archiveFile);
20567
+ return { bundleId: (_a = response.data) === null || _a === void 0 ? void 0 : _a.bundleId, email, message };
20568
+ }
20203
20569
  async function sendBuild(ctx, { workspaceId, token }) {
20204
20570
  const { FormData } = await import('formdata-node');
20205
20571
  const { fileFromPath } = await Promise.resolve().then(function () { return fileFromPath$1; });
20206
20572
  const file = await fileFromPath(ctx.client.archiveFile, "embeddable-build.zip");
20207
20573
  const form = new FormData();
20208
20574
  form.set("file", file, "embeddable-build.zip");
20209
- await axios.post(`${ctx.pushBaseUrl}/bundle/${workspaceId}/upload`, form, {
20575
+ await uploadFile(form, `${ctx.pushBaseUrl}/bundle/${workspaceId}/upload`, token);
20576
+ await fs__namespace.rm(ctx.client.archiveFile);
20577
+ }
20578
+ async function uploadFile(formData, url, token) {
20579
+ return axios.post(url, formData, {
20210
20580
  headers: {
20211
20581
  "Content-Type": "multipart/form-data",
20212
20582
  Authorization: `Bearer ${token}`,
@@ -20214,7 +20584,6 @@ async function sendBuild(ctx, { workspaceId, token }) {
20214
20584
  maxContentLength: Infinity,
20215
20585
  maxBodyLength: Infinity,
20216
20586
  });
20217
- await fs__namespace.rm(ctx.client.archiveFile);
20218
20587
  }
20219
20588
  async function getWorkspaces(ctx, token, workspaceSpinner) {
20220
20589
  var _a;
@@ -20421,9 +20790,21 @@ const getPreviewWorkspace = async (ctx) => {
20421
20790
  }
20422
20791
  };
20423
20792
 
20424
- var defineConfig = ({ plugins, pushBaseUrl, audienceUrl, authDomain, authClientId, errorFallbackComponent, applicationEnvironment, rollbarAccessToken, previewBaseUrl, }) => {
20793
+ var defineConfig = ({ plugins, pushBaseUrl, audienceUrl, authDomain, authClientId, errorFallbackComponent, applicationEnvironment, rollbarAccessToken, previewBaseUrl, modelsSrc, componentsSrc = "src", }) => {
20425
20794
  const coreRoot = path__namespace.resolve(__dirname, "..");
20426
20795
  const clientRoot = process.cwd();
20796
+ if (!path__namespace.isAbsolute(componentsSrc)) {
20797
+ componentsSrc = path__namespace.resolve(clientRoot, componentsSrc);
20798
+ if (!fs$2.existsSync(componentsSrc)) {
20799
+ throw new Error(`componentsSrc directory ${componentsSrc} does not exist`);
20800
+ }
20801
+ }
20802
+ if (modelsSrc && !path__namespace.isAbsolute(modelsSrc)) {
20803
+ modelsSrc = path__namespace.resolve(clientRoot, modelsSrc);
20804
+ if (!fs$2.existsSync(modelsSrc)) {
20805
+ throw new Error(`modelsSrc directory ${modelsSrc} does not exist`);
20806
+ }
20807
+ }
20427
20808
  return {
20428
20809
  core: {
20429
20810
  rootDir: coreRoot,
@@ -20432,8 +20813,9 @@ var defineConfig = ({ plugins, pushBaseUrl, audienceUrl, authDomain, authClientI
20432
20813
  },
20433
20814
  client: {
20434
20815
  rootDir: clientRoot,
20816
+ srcDir: path__namespace.resolve(clientRoot, componentsSrc),
20817
+ modelsSrc: modelsSrc ? path__namespace.resolve(clientRoot, modelsSrc) : undefined,
20435
20818
  buildDir: path__namespace.resolve(clientRoot, ".embeddable-build"),
20436
- srcDir: path__namespace.resolve(clientRoot, "src"),
20437
20819
  tmpDir: path__namespace.resolve(clientRoot, ".embeddable-tmp"),
20438
20820
  componentDir: path__namespace.resolve(clientRoot, ".embeddable-build", "component"),
20439
20821
  stencilBuild: path__namespace.resolve(clientRoot, ".embeddable-build", "dist", "embeddable-wrapper"),