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

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$/;
@@ -386,6 +412,7 @@ async function generate$1(ctx) {
386
412
  await fs__namespace.writeFile(path__namespace.resolve(ctx.client.rootDir, ctx.outputOptions.typesEntryPointFilename), typeImports);
387
413
  }
388
414
  async function build$1(ctx) {
415
+ var _a;
389
416
  await vite__namespace.build({
390
417
  logLevel: "error",
391
418
  build: {
@@ -395,6 +422,13 @@ async function build$1(ctx) {
395
422
  formats: ["es"],
396
423
  fileName: "embeddable-types",
397
424
  },
425
+ rollupOptions: ((_a = ctx.dev) === null || _a === void 0 ? void 0 : _a.watch)
426
+ ? undefined
427
+ : {
428
+ output: {
429
+ entryFileNames: "embeddable-types-[hash].js",
430
+ },
431
+ },
398
432
  outDir: ctx.client.buildDir,
399
433
  },
400
434
  });
@@ -411,6 +445,8 @@ var prepare = async (ctx) => {
411
445
  async function removeIfExists(ctx) {
412
446
  if (fs__namespace$1.existsSync(ctx.client.buildDir))
413
447
  await fs__namespace.rm(ctx.client.buildDir, { recursive: true });
448
+ if (fs__namespace$1.existsSync(ctx.client.tmpDir))
449
+ await fs__namespace.rm(ctx.client.tmpDir, { recursive: true });
414
450
  }
415
451
  async function copyStencilConfigsToClient(ctx) {
416
452
  await fs__namespace.cp(ctx.core.configsDir, ctx.client.buildDir, { recursive: true });
@@ -444,16 +480,18 @@ async function injectBundleRender(ctx, pluginName) {
444
480
  await fs__namespace.writeFile(path__namespace.resolve(ctx.client.componentDir, "component.tsx"), content.replace(RENDER_IMPORT_TOKEN, importStr));
445
481
  }
446
482
  async function runStencil(ctx) {
447
- var _a, _b;
483
+ var _a, _b, _c;
448
484
  const logger = ((_a = ctx.dev) === null || _a === void 0 ? void 0 : _a.logger) || node.createNodeLogger({ process });
449
485
  const sys = ((_b = ctx.dev) === null || _b === void 0 ? void 0 : _b.sys) || node.createNodeSys({ process });
450
486
  const devMode = !!ctx.dev;
487
+ const isWindows = process.platform === "win32";
451
488
  const validated = await compiler.loadConfig({
452
489
  initTsConfig: true,
453
490
  logger,
454
491
  sys,
455
492
  config: {
456
493
  devMode,
494
+ maxConcurrentWorkers: isWindows ? 0 : 8, // workers break on windows
457
495
  rootDir: ctx.client.buildDir,
458
496
  configPath: path__namespace.resolve(ctx.client.buildDir, "stencil.config.ts"),
459
497
  tsconfig: path__namespace.resolve(ctx.client.buildDir, "tsconfig.json"),
@@ -468,6 +506,14 @@ async function runStencil(ctx) {
468
506
  });
469
507
  const compiler$1 = await compiler.createCompiler(validated.config);
470
508
  await compiler$1.build();
509
+ const entryFilePath = path__namespace.resolve(ctx.client.stencilBuild, "embeddable-wrapper.esm.js");
510
+ let fileName = "embeddable-wrapper.esm.js";
511
+ if (!((_c = ctx.dev) === null || _c === void 0 ? void 0 : _c.watch)) {
512
+ const entryFileContent = await fs__namespace.readFile(entryFilePath, "utf8");
513
+ const fileHash = getContentHash(entryFileContent);
514
+ fileName = `embeddable-wrapper.esm-${fileHash}.js`;
515
+ }
516
+ await fs__namespace.rename(entryFilePath, path__namespace.resolve(ctx.client.stencilBuild, fileName));
471
517
  await compiler$1.destroy();
472
518
  process.chdir(ctx.client.rootDir);
473
519
  }
@@ -497,10 +543,28 @@ var cleanup = async (ctx) => {
497
543
  await moveBuildTOBuildDir(ctx);
498
544
  };
499
545
  async function extractBuild(ctx) {
546
+ const [[, stencilWrapperFilePath]] = await findFiles(ctx.client.stencilBuild, /embeddable-wrapper.esm-[a-z0-9]+\.js/);
547
+ const stencilWrapperFileName = path__namespace.basename(stencilWrapperFilePath);
500
548
  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"));
549
+ const [[, typesFilePath]] = await findFiles(ctx.client.buildDir, /embeddable-types-[a-z0-9]+\.js/);
550
+ const typesFileName = path__namespace.basename(typesFilePath);
551
+ await fs__namespace.rename(typesFilePath, path__namespace.join(ctx.client.tmpDir, typesFileName));
552
+ const [[, metaFilePath]] = await findFiles(ctx.client.buildDir, /embeddable-components-meta-[a-z0-9]+\.js/);
553
+ const metaFileName = path__namespace.basename(metaFilePath);
554
+ await fs__namespace.rename(metaFilePath, path__namespace.join(ctx.client.tmpDir, metaFileName));
555
+ const [[, editorsMetaFilePath]] = await findFiles(ctx.client.buildDir, /embeddable-editors-meta-[a-z0-9]+\.js/);
556
+ const editorsMetaFileName = path__namespace.basename(editorsMetaFilePath);
557
+ await fs__namespace.rename(editorsMetaFilePath, path__namespace.join(ctx.client.tmpDir, editorsMetaFileName));
558
+ // write manifest file with files with hash
559
+ const manifest = {
560
+ entryFiles: {
561
+ "embeddable-types.js": typesFileName,
562
+ "embeddable-components-meta.js": metaFileName,
563
+ "embeddable-editors-meta.js": editorsMetaFileName,
564
+ "embeddable-wrapper.esm.js": stencilWrapperFileName,
565
+ },
566
+ };
567
+ await fs__namespace.writeFile(path__namespace.join(ctx.client.tmpDir, "embeddable-manifest.json"), JSON.stringify(manifest));
504
568
  }
505
569
  async function removeObsoleteDir(dir) {
506
570
  await fs__namespace.rm(dir, { recursive: true });
@@ -743,6 +807,11 @@ class ZodError extends Error {
743
807
  processError(this);
744
808
  return fieldErrors;
745
809
  }
810
+ static assert(value) {
811
+ if (!(value instanceof ZodError)) {
812
+ throw new Error(`Not a ZodError: ${value}`);
813
+ }
814
+ }
746
815
  toString() {
747
816
  return this.message;
748
817
  }
@@ -915,6 +984,13 @@ const makeIssue = (params) => {
915
984
  ...issueData,
916
985
  path: fullPath,
917
986
  };
987
+ if (issueData.message !== undefined) {
988
+ return {
989
+ ...issueData,
990
+ path: fullPath,
991
+ message: issueData.message,
992
+ };
993
+ }
918
994
  let errorMessage = "";
919
995
  const maps = errorMaps
920
996
  .filter((m) => !!m)
@@ -926,11 +1002,12 @@ const makeIssue = (params) => {
926
1002
  return {
927
1003
  ...issueData,
928
1004
  path: fullPath,
929
- message: issueData.message || errorMessage,
1005
+ message: errorMessage,
930
1006
  };
931
1007
  };
932
1008
  const EMPTY_PATH = [];
933
1009
  function addIssueToContext(ctx, issueData) {
1010
+ const overrideMap = getErrorMap();
934
1011
  const issue = makeIssue({
935
1012
  issueData: issueData,
936
1013
  data: ctx.data,
@@ -938,8 +1015,8 @@ function addIssueToContext(ctx, issueData) {
938
1015
  errorMaps: [
939
1016
  ctx.common.contextualErrorMap,
940
1017
  ctx.schemaErrorMap,
941
- getErrorMap(),
942
- errorMap, // then global default map
1018
+ overrideMap,
1019
+ overrideMap === errorMap ? undefined : errorMap, // then global default map
943
1020
  ].filter((x) => !!x),
944
1021
  });
945
1022
  ctx.common.issues.push(issue);
@@ -970,9 +1047,11 @@ class ParseStatus {
970
1047
  static async mergeObjectAsync(status, pairs) {
971
1048
  const syncPairs = [];
972
1049
  for (const pair of pairs) {
1050
+ const key = await pair.key;
1051
+ const value = await pair.value;
973
1052
  syncPairs.push({
974
- key: await pair.key,
975
- value: await pair.value,
1053
+ key,
1054
+ value,
976
1055
  });
977
1056
  }
978
1057
  return ParseStatus.mergeObjectSync(status, syncPairs);
@@ -1007,12 +1086,46 @@ const isDirty = (x) => x.status === "dirty";
1007
1086
  const isValid = (x) => x.status === "valid";
1008
1087
  const isAsync$1 = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1009
1088
 
1089
+ /******************************************************************************
1090
+ Copyright (c) Microsoft Corporation.
1091
+
1092
+ Permission to use, copy, modify, and/or distribute this software for any
1093
+ purpose with or without fee is hereby granted.
1094
+
1095
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1096
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1097
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1098
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1099
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1100
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1101
+ PERFORMANCE OF THIS SOFTWARE.
1102
+ ***************************************************************************** */
1103
+
1104
+ function __classPrivateFieldGet(receiver, state, kind, f) {
1105
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1106
+ 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");
1107
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1108
+ }
1109
+
1110
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
1111
+ if (kind === "m") throw new TypeError("Private method is not writable");
1112
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1113
+ 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");
1114
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
1115
+ }
1116
+
1117
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
1118
+ var e = new Error(message);
1119
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1120
+ };
1121
+
1010
1122
  var errorUtil;
1011
1123
  (function (errorUtil) {
1012
1124
  errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
1013
1125
  errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
1014
1126
  })(errorUtil || (errorUtil = {}));
1015
1127
 
1128
+ var _ZodEnum_cache, _ZodNativeEnum_cache;
1016
1129
  class ParseInputLazyPath {
1017
1130
  constructor(parent, value, path, key) {
1018
1131
  this._cachedPath = [];
@@ -1063,12 +1176,17 @@ function processCreateParams(params) {
1063
1176
  if (errorMap)
1064
1177
  return { errorMap: errorMap, description };
1065
1178
  const customMap = (iss, ctx) => {
1066
- if (iss.code !== "invalid_type")
1067
- return { message: ctx.defaultError };
1179
+ var _a, _b;
1180
+ const { message } = params;
1181
+ if (iss.code === "invalid_enum_value") {
1182
+ return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
1183
+ }
1068
1184
  if (typeof ctx.data === "undefined") {
1069
- return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
1185
+ return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
1070
1186
  }
1071
- return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
1187
+ if (iss.code !== "invalid_type")
1188
+ return { message: ctx.defaultError };
1189
+ return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
1072
1190
  };
1073
1191
  return { errorMap: customMap, description };
1074
1192
  }
@@ -1326,11 +1444,13 @@ class ZodType {
1326
1444
  }
1327
1445
  }
1328
1446
  const cuidRegex = /^c[^\s-]{8,}$/i;
1329
- const cuid2Regex = /^[a-z][a-z0-9]*$/;
1447
+ const cuid2Regex = /^[0-9a-z]+$/;
1330
1448
  const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
1331
1449
  // const uuidRegex =
1332
1450
  // /^([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
1451
  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;
1452
+ const nanoidRegex = /^[a-z0-9_-]{21}$/i;
1453
+ 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
1454
  // from https://stackoverflow.com/a/46181/1550155
1335
1455
  // old version: too slow, didn't support unicode
1336
1456
  // 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 +1463,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
1463
  // /^[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
1464
  // const emailRegex =
1345
1465
  // /^(?:[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;
1466
+ const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1347
1467
  // const emailRegex =
1348
1468
  // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
1349
1469
  // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
1350
1470
  const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1351
1471
  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}))$/;
1472
+ // faster, simpler, safer
1473
+ 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
1474
  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) => {
1475
+ // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
1476
+ const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1477
+ // simple
1478
+ // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
1479
+ // no leap year validation
1480
+ // 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))`;
1481
+ // with leap year validation
1482
+ 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])))`;
1483
+ const dateRegex = new RegExp(`^${dateRegexSource}$`);
1484
+ function timeRegexSource(args) {
1485
+ // let regex = `\\d{2}:\\d{2}:\\d{2}`;
1486
+ let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
1356
1487
  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
- }
1488
+ regex = `${regex}\\.\\d{${args.precision}}`;
1363
1489
  }
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
- }
1371
- }
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
- }
1490
+ else if (args.precision == null) {
1491
+ regex = `${regex}(\\.\\d+)?`;
1379
1492
  }
1380
- };
1493
+ return regex;
1494
+ }
1495
+ function timeRegex(args) {
1496
+ return new RegExp(`^${timeRegexSource(args)}$`);
1497
+ }
1498
+ // Adapted from https://stackoverflow.com/a/3143231
1499
+ function datetimeRegex(args) {
1500
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1501
+ const opts = [];
1502
+ opts.push(args.local ? `Z?` : `Z`);
1503
+ if (args.offset)
1504
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1505
+ regex = `${regex}(${opts.join("|")})`;
1506
+ return new RegExp(`^${regex}$`);
1507
+ }
1381
1508
  function isValidIP(ip, version) {
1382
1509
  if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1383
1510
  return true;
@@ -1399,9 +1526,7 @@ class ZodString extends ZodType {
1399
1526
  code: ZodIssueCode.invalid_type,
1400
1527
  expected: ZodParsedType.string,
1401
1528
  received: ctx.parsedType,
1402
- }
1403
- //
1404
- );
1529
+ });
1405
1530
  return INVALID;
1406
1531
  }
1407
1532
  const status = new ParseStatus();
@@ -1499,6 +1624,17 @@ class ZodString extends ZodType {
1499
1624
  status.dirty();
1500
1625
  }
1501
1626
  }
1627
+ else if (check.kind === "nanoid") {
1628
+ if (!nanoidRegex.test(input.data)) {
1629
+ ctx = this._getOrReturnCtx(input, ctx);
1630
+ addIssueToContext(ctx, {
1631
+ validation: "nanoid",
1632
+ code: ZodIssueCode.invalid_string,
1633
+ message: check.message,
1634
+ });
1635
+ status.dirty();
1636
+ }
1637
+ }
1502
1638
  else if (check.kind === "cuid") {
1503
1639
  if (!cuidRegex.test(input.data)) {
1504
1640
  ctx = this._getOrReturnCtx(input, ctx);
@@ -1613,6 +1749,41 @@ class ZodString extends ZodType {
1613
1749
  status.dirty();
1614
1750
  }
1615
1751
  }
1752
+ else if (check.kind === "date") {
1753
+ const regex = dateRegex;
1754
+ if (!regex.test(input.data)) {
1755
+ ctx = this._getOrReturnCtx(input, ctx);
1756
+ addIssueToContext(ctx, {
1757
+ code: ZodIssueCode.invalid_string,
1758
+ validation: "date",
1759
+ message: check.message,
1760
+ });
1761
+ status.dirty();
1762
+ }
1763
+ }
1764
+ else if (check.kind === "time") {
1765
+ const regex = timeRegex(check);
1766
+ if (!regex.test(input.data)) {
1767
+ ctx = this._getOrReturnCtx(input, ctx);
1768
+ addIssueToContext(ctx, {
1769
+ code: ZodIssueCode.invalid_string,
1770
+ validation: "time",
1771
+ message: check.message,
1772
+ });
1773
+ status.dirty();
1774
+ }
1775
+ }
1776
+ else if (check.kind === "duration") {
1777
+ if (!durationRegex.test(input.data)) {
1778
+ ctx = this._getOrReturnCtx(input, ctx);
1779
+ addIssueToContext(ctx, {
1780
+ validation: "duration",
1781
+ code: ZodIssueCode.invalid_string,
1782
+ message: check.message,
1783
+ });
1784
+ status.dirty();
1785
+ }
1786
+ }
1616
1787
  else if (check.kind === "ip") {
1617
1788
  if (!isValidIP(input.data, check.version)) {
1618
1789
  ctx = this._getOrReturnCtx(input, ctx);
@@ -1624,6 +1795,17 @@ class ZodString extends ZodType {
1624
1795
  status.dirty();
1625
1796
  }
1626
1797
  }
1798
+ else if (check.kind === "base64") {
1799
+ if (!base64Regex.test(input.data)) {
1800
+ ctx = this._getOrReturnCtx(input, ctx);
1801
+ addIssueToContext(ctx, {
1802
+ validation: "base64",
1803
+ code: ZodIssueCode.invalid_string,
1804
+ message: check.message,
1805
+ });
1806
+ status.dirty();
1807
+ }
1808
+ }
1627
1809
  else {
1628
1810
  util$7.assertNever(check);
1629
1811
  }
@@ -1655,6 +1837,9 @@ class ZodString extends ZodType {
1655
1837
  uuid(message) {
1656
1838
  return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1657
1839
  }
1840
+ nanoid(message) {
1841
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1842
+ }
1658
1843
  cuid(message) {
1659
1844
  return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1660
1845
  }
@@ -1664,16 +1849,20 @@ class ZodString extends ZodType {
1664
1849
  ulid(message) {
1665
1850
  return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1666
1851
  }
1852
+ base64(message) {
1853
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1854
+ }
1667
1855
  ip(options) {
1668
1856
  return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1669
1857
  }
1670
1858
  datetime(options) {
1671
- var _a;
1859
+ var _a, _b;
1672
1860
  if (typeof options === "string") {
1673
1861
  return this._addCheck({
1674
1862
  kind: "datetime",
1675
1863
  precision: null,
1676
1864
  offset: false,
1865
+ local: false,
1677
1866
  message: options,
1678
1867
  });
1679
1868
  }
@@ -1681,9 +1870,30 @@ class ZodString extends ZodType {
1681
1870
  kind: "datetime",
1682
1871
  precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
1683
1872
  offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
1873
+ local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
1684
1874
  ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
1685
1875
  });
1686
1876
  }
1877
+ date(message) {
1878
+ return this._addCheck({ kind: "date", message });
1879
+ }
1880
+ time(options) {
1881
+ if (typeof options === "string") {
1882
+ return this._addCheck({
1883
+ kind: "time",
1884
+ precision: null,
1885
+ message: options,
1886
+ });
1887
+ }
1888
+ return this._addCheck({
1889
+ kind: "time",
1890
+ precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
1891
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
1892
+ });
1893
+ }
1894
+ duration(message) {
1895
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1896
+ }
1687
1897
  regex(regex, message) {
1688
1898
  return this._addCheck({
1689
1899
  kind: "regex",
@@ -1762,6 +1972,15 @@ class ZodString extends ZodType {
1762
1972
  get isDatetime() {
1763
1973
  return !!this._def.checks.find((ch) => ch.kind === "datetime");
1764
1974
  }
1975
+ get isDate() {
1976
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1977
+ }
1978
+ get isTime() {
1979
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1980
+ }
1981
+ get isDuration() {
1982
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1983
+ }
1765
1984
  get isEmail() {
1766
1985
  return !!this._def.checks.find((ch) => ch.kind === "email");
1767
1986
  }
@@ -1774,6 +1993,9 @@ class ZodString extends ZodType {
1774
1993
  get isUUID() {
1775
1994
  return !!this._def.checks.find((ch) => ch.kind === "uuid");
1776
1995
  }
1996
+ get isNANOID() {
1997
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1998
+ }
1777
1999
  get isCUID() {
1778
2000
  return !!this._def.checks.find((ch) => ch.kind === "cuid");
1779
2001
  }
@@ -1786,6 +2008,9 @@ class ZodString extends ZodType {
1786
2008
  get isIP() {
1787
2009
  return !!this._def.checks.find((ch) => ch.kind === "ip");
1788
2010
  }
2011
+ get isBase64() {
2012
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
2013
+ }
1789
2014
  get minLength() {
1790
2015
  let min = null;
1791
2016
  for (const ch of this._def.checks) {
@@ -2773,9 +2998,10 @@ class ZodObject extends ZodType {
2773
2998
  const syncPairs = [];
2774
2999
  for (const pair of pairs) {
2775
3000
  const key = await pair.key;
3001
+ const value = await pair.value;
2776
3002
  syncPairs.push({
2777
3003
  key,
2778
- value: await pair.value,
3004
+ value,
2779
3005
  alwaysSet: pair.alwaysSet,
2780
3006
  });
2781
3007
  }
@@ -3149,7 +3375,7 @@ const getDiscriminator = (type) => {
3149
3375
  }
3150
3376
  else if (type instanceof ZodNativeEnum) {
3151
3377
  // eslint-disable-next-line ban/ban
3152
- return Object.keys(type.enum);
3378
+ return util$7.objectValues(type.enum);
3153
3379
  }
3154
3380
  else if (type instanceof ZodDefault) {
3155
3381
  return getDiscriminator(type._def.innerType);
@@ -3160,8 +3386,23 @@ const getDiscriminator = (type) => {
3160
3386
  else if (type instanceof ZodNull) {
3161
3387
  return [null];
3162
3388
  }
3389
+ else if (type instanceof ZodOptional) {
3390
+ return [undefined, ...getDiscriminator(type.unwrap())];
3391
+ }
3392
+ else if (type instanceof ZodNullable) {
3393
+ return [null, ...getDiscriminator(type.unwrap())];
3394
+ }
3395
+ else if (type instanceof ZodBranded) {
3396
+ return getDiscriminator(type.unwrap());
3397
+ }
3398
+ else if (type instanceof ZodReadonly) {
3399
+ return getDiscriminator(type.unwrap());
3400
+ }
3401
+ else if (type instanceof ZodCatch) {
3402
+ return getDiscriminator(type._def.innerType);
3403
+ }
3163
3404
  else {
3164
- return null;
3405
+ return [];
3165
3406
  }
3166
3407
  };
3167
3408
  class ZodDiscriminatedUnion extends ZodType {
@@ -3224,7 +3465,7 @@ class ZodDiscriminatedUnion extends ZodType {
3224
3465
  // try {
3225
3466
  for (const type of options) {
3226
3467
  const discriminatorValues = getDiscriminator(type.shape[discriminator]);
3227
- if (!discriminatorValues) {
3468
+ if (!discriminatorValues.length) {
3228
3469
  throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
3229
3470
  }
3230
3471
  for (const value of discriminatorValues) {
@@ -3437,6 +3678,7 @@ class ZodRecord extends ZodType {
3437
3678
  pairs.push({
3438
3679
  key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3439
3680
  value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3681
+ alwaysSet: key in ctx.data,
3440
3682
  });
3441
3683
  }
3442
3684
  if (ctx.common.async) {
@@ -3796,6 +4038,10 @@ function createZodEnum(values, params) {
3796
4038
  });
3797
4039
  }
3798
4040
  class ZodEnum extends ZodType {
4041
+ constructor() {
4042
+ super(...arguments);
4043
+ _ZodEnum_cache.set(this, void 0);
4044
+ }
3799
4045
  _parse(input) {
3800
4046
  if (typeof input.data !== "string") {
3801
4047
  const ctx = this._getOrReturnCtx(input);
@@ -3807,7 +4053,10 @@ class ZodEnum extends ZodType {
3807
4053
  });
3808
4054
  return INVALID;
3809
4055
  }
3810
- if (this._def.values.indexOf(input.data) === -1) {
4056
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
4057
+ __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
4058
+ }
4059
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
3811
4060
  const ctx = this._getOrReturnCtx(input);
3812
4061
  const expectedValues = this._def.values;
3813
4062
  addIssueToContext(ctx, {
@@ -3843,15 +4092,26 @@ class ZodEnum extends ZodType {
3843
4092
  }
3844
4093
  return enumValues;
3845
4094
  }
3846
- extract(values) {
3847
- return ZodEnum.create(values);
4095
+ extract(values, newDef = this._def) {
4096
+ return ZodEnum.create(values, {
4097
+ ...this._def,
4098
+ ...newDef,
4099
+ });
3848
4100
  }
3849
- exclude(values) {
3850
- return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
4101
+ exclude(values, newDef = this._def) {
4102
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
4103
+ ...this._def,
4104
+ ...newDef,
4105
+ });
3851
4106
  }
3852
4107
  }
4108
+ _ZodEnum_cache = new WeakMap();
3853
4109
  ZodEnum.create = createZodEnum;
3854
4110
  class ZodNativeEnum extends ZodType {
4111
+ constructor() {
4112
+ super(...arguments);
4113
+ _ZodNativeEnum_cache.set(this, void 0);
4114
+ }
3855
4115
  _parse(input) {
3856
4116
  const nativeEnumValues = util$7.getValidEnumValues(this._def.values);
3857
4117
  const ctx = this._getOrReturnCtx(input);
@@ -3865,7 +4125,10 @@ class ZodNativeEnum extends ZodType {
3865
4125
  });
3866
4126
  return INVALID;
3867
4127
  }
3868
- if (nativeEnumValues.indexOf(input.data) === -1) {
4128
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
4129
+ __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util$7.getValidEnumValues(this._def.values)), "f");
4130
+ }
4131
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
3869
4132
  const expectedValues = util$7.objectValues(nativeEnumValues);
3870
4133
  addIssueToContext(ctx, {
3871
4134
  received: ctx.data,
@@ -3880,6 +4143,7 @@ class ZodNativeEnum extends ZodType {
3880
4143
  return this._def.values;
3881
4144
  }
3882
4145
  }
4146
+ _ZodNativeEnum_cache = new WeakMap();
3883
4147
  ZodNativeEnum.create = (values, params) => {
3884
4148
  return new ZodNativeEnum({
3885
4149
  values: values,
@@ -3949,33 +4213,43 @@ class ZodEffects extends ZodType {
3949
4213
  checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3950
4214
  if (effect.type === "preprocess") {
3951
4215
  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
4216
  if (ctx.common.async) {
3959
- return Promise.resolve(processed).then((processed) => {
3960
- return this._def.schema._parseAsync({
4217
+ return Promise.resolve(processed).then(async (processed) => {
4218
+ if (status.value === "aborted")
4219
+ return INVALID;
4220
+ const result = await this._def.schema._parseAsync({
3961
4221
  data: processed,
3962
4222
  path: ctx.path,
3963
4223
  parent: ctx,
3964
4224
  });
4225
+ if (result.status === "aborted")
4226
+ return INVALID;
4227
+ if (result.status === "dirty")
4228
+ return DIRTY(result.value);
4229
+ if (status.value === "dirty")
4230
+ return DIRTY(result.value);
4231
+ return result;
3965
4232
  });
3966
4233
  }
3967
4234
  else {
3968
- return this._def.schema._parseSync({
4235
+ if (status.value === "aborted")
4236
+ return INVALID;
4237
+ const result = this._def.schema._parseSync({
3969
4238
  data: processed,
3970
4239
  path: ctx.path,
3971
4240
  parent: ctx,
3972
4241
  });
4242
+ if (result.status === "aborted")
4243
+ return INVALID;
4244
+ if (result.status === "dirty")
4245
+ return DIRTY(result.value);
4246
+ if (status.value === "dirty")
4247
+ return DIRTY(result.value);
4248
+ return result;
3973
4249
  }
3974
4250
  }
3975
4251
  if (effect.type === "refinement") {
3976
- const executeRefinement = (acc
3977
- // effect: RefinementEffect<any>
3978
- ) => {
4252
+ const executeRefinement = (acc) => {
3979
4253
  const result = effect.refinement(acc, checkCtx);
3980
4254
  if (ctx.common.async) {
3981
4255
  return Promise.resolve(result);
@@ -4278,10 +4552,18 @@ class ZodPipeline extends ZodType {
4278
4552
  class ZodReadonly extends ZodType {
4279
4553
  _parse(input) {
4280
4554
  const result = this._def.innerType._parse(input);
4281
- if (isValid(result)) {
4282
- result.value = Object.freeze(result.value);
4283
- }
4284
- return result;
4555
+ const freeze = (data) => {
4556
+ if (isValid(data)) {
4557
+ data.value = Object.freeze(data.value);
4558
+ }
4559
+ return data;
4560
+ };
4561
+ return isAsync$1(result)
4562
+ ? result.then((data) => freeze(data))
4563
+ : freeze(result);
4564
+ }
4565
+ unwrap() {
4566
+ return this._def.innerType;
4285
4567
  }
4286
4568
  }
4287
4569
  ZodReadonly.create = (type, params) => {
@@ -4291,7 +4573,7 @@ ZodReadonly.create = (type, params) => {
4291
4573
  ...processCreateParams(params),
4292
4574
  });
4293
4575
  };
4294
- const custom = (check, params = {},
4576
+ function custom(check, params = {},
4295
4577
  /**
4296
4578
  * @deprecated
4297
4579
  *
@@ -4302,7 +4584,7 @@ const custom = (check, params = {},
4302
4584
  * ```
4303
4585
  *
4304
4586
  */
4305
- fatal) => {
4587
+ fatal) {
4306
4588
  if (check)
4307
4589
  return ZodAny.create().superRefine((data, ctx) => {
4308
4590
  var _a, _b;
@@ -4318,7 +4600,7 @@ fatal) => {
4318
4600
  }
4319
4601
  });
4320
4602
  return ZodAny.create();
4321
- };
4603
+ }
4322
4604
  const late = {
4323
4605
  object: ZodObject.lazycreate,
4324
4606
  };
@@ -4436,6 +4718,7 @@ var z = /*#__PURE__*/Object.freeze({
4436
4718
  ZodParsedType: ZodParsedType,
4437
4719
  getParsedType: getParsedType,
4438
4720
  ZodType: ZodType,
4721
+ datetimeRegex: datetimeRegex,
4439
4722
  ZodString: ZodString,
4440
4723
  ZodNumber: ZodNumber,
4441
4724
  ZodBigInt: ZodBigInt,
@@ -4540,7 +4823,7 @@ var validate = async (ctx, exitIfInvalid = true) => {
4540
4823
  const ora = (await import('ora')).default;
4541
4824
  const spinnerValidate = ora("Data model validation...").start();
4542
4825
  const filesList = await findFiles(ctx.client.srcDir, CUBE_YAML_FILE_REGEX);
4543
- const securityContextFilesList = await findFiles(ctx.client.srcDir, SECURITY_CONTEXT_FILE_REGEX);
4826
+ const securityContextFilesList = await findFiles(ctx.client.modelsSrc || ctx.client.srcDir, SECURITY_CONTEXT_FILE_REGEX);
4544
4827
  const dataModelErrors = await dataModelsValidation(filesList);
4545
4828
  if (dataModelErrors.length) {
4546
4829
  spinnerValidate.fail("One or more cube.yaml files are invalid:");
@@ -4565,9 +4848,18 @@ async function dataModelsValidation(filesList) {
4565
4848
  for (const [_, filePath] of filesList) {
4566
4849
  const fileContentRaw = await fs__namespace.readFile(filePath, "utf8");
4567
4850
  const cube = YAML__namespace.parse(fileContentRaw);
4568
- const safeParse = cubeModelSchema.safeParse(cube);
4569
- if (!safeParse.success) {
4570
- errorFormatter(safeParse.error.issues).forEach((error) => {
4851
+ if (!(cube === null || cube === void 0 ? void 0 : cube.cubes) && !(cube === null || cube === void 0 ? void 0 : cube.views)) {
4852
+ return [`${filePath}: At least one cubes or views must be defined`];
4853
+ }
4854
+ const cubeModelSafeParse = cubeModelSchema.safeParse(cube);
4855
+ const viewModelSafeParse = viewModelSchema.safeParse(cube);
4856
+ if (cube.cubes && !cubeModelSafeParse.success) {
4857
+ errorFormatter(cubeModelSafeParse.error.issues).forEach((error) => {
4858
+ errors.push(`${filePath}: ${error}`);
4859
+ });
4860
+ }
4861
+ if (cube.views && !viewModelSafeParse.success) {
4862
+ errorFormatter(viewModelSafeParse.error.issues).forEach((error) => {
4571
4863
  errors.push(`${filePath}: ${error}`);
4572
4864
  });
4573
4865
  }
@@ -4646,6 +4938,19 @@ const cubeModelSchema = z
4646
4938
  message: "At least one measure or dimension must be defined",
4647
4939
  path: ["cubes"],
4648
4940
  });
4941
+ const viewModelSchema = z.object({
4942
+ views: z
4943
+ .object({
4944
+ name: z.string(),
4945
+ cubes: z
4946
+ .object({
4947
+ join_path: z.string(),
4948
+ })
4949
+ .array(),
4950
+ })
4951
+ .array()
4952
+ .min(1),
4953
+ });
4649
4954
  const securityContextSchema = z.array(z.object({
4650
4955
  name: z.string(),
4651
4956
  securityContext: z.object({}), // can be any object
@@ -20002,6 +20307,25 @@ const checkNodeVersion = async () => {
20002
20307
  process.exit(1);
20003
20308
  }
20004
20309
  };
20310
+ /**
20311
+ * Get the value of a process argument by key
20312
+ * Example: getArgumentByKey("--email") or getArgumentByKey(["--email", "-e"])
20313
+ * @param key The key to search for in the process arguments
20314
+ * @returns
20315
+ */
20316
+ const getArgumentByKey = (key) => {
20317
+ if (Array.isArray(key)) {
20318
+ for (const k of key) {
20319
+ if (process.argv.includes(k)) {
20320
+ const index = process.argv.indexOf(k);
20321
+ return index !== -1 ? process.argv[index + 1] : undefined;
20322
+ }
20323
+ }
20324
+ return undefined;
20325
+ }
20326
+ const index = process.argv.indexOf(key);
20327
+ return index !== -1 ? process.argv[index + 1] : undefined;
20328
+ };
20005
20329
 
20006
20330
  var build = async () => {
20007
20331
  try {
@@ -20112,29 +20436,58 @@ const inquirerSelect = import('@inquirer/select');
20112
20436
  const YAML_OR_JS_FILES = /^(.*)\.(cube|sc)\.(ya?ml|js)$/;
20113
20437
  let ora$1;
20114
20438
  var push = async () => {
20115
- var _a;
20439
+ var _a, _b;
20116
20440
  let spinnerPushing;
20117
20441
  try {
20118
20442
  checkNodeVersion();
20119
20443
  ora$1 = (await oraP$1).default;
20120
20444
  const config = await provideConfig();
20445
+ if (process.argv.includes("--api-key") || process.argv.includes("-k")) {
20446
+ spinnerPushing = ora$1("Using API key...").start();
20447
+ await pushByApiKey(config, spinnerPushing);
20448
+ spinnerPushing.succeed("Published using API key");
20449
+ return;
20450
+ }
20121
20451
  const token = await verify(config);
20122
20452
  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();
20453
+ const workspacePreviewUrl = `${config.previewBaseUrl}/workspace/${workspaceId}`;
20454
+ await buildArchive(config);
20455
+ spinnerPushing = ora$1(`Publishing to ${workspaceName} using ${workspacePreviewUrl}...`).start();
20128
20456
  await sendBuild(config, { workspaceId, token });
20129
- spinnerPushing.succeed(`Published to ${workspaceName} using ${config.pushBaseUrl}`);
20457
+ spinnerPushing.succeed(`Published to ${workspaceName} using ${workspacePreviewUrl}`);
20130
20458
  }
20131
20459
  catch (error) {
20132
20460
  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);
20461
+ if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.statusText) === "Unauthorized") {
20462
+ console.error("Unauthorized. Please check your credentials.");
20463
+ }
20464
+ else {
20465
+ console.error(((_b = error.response) === null || _b === void 0 ? void 0 : _b.data) || (error === null || error === void 0 ? void 0 : error.message) || error);
20466
+ }
20134
20467
  await reportErrorToRollbar(error);
20135
20468
  process.exit(1);
20136
20469
  }
20137
20470
  };
20471
+ async function pushByApiKey(config, spinner) {
20472
+ const apiKey = getArgumentByKey(["--api-key", "-k"]);
20473
+ if (!apiKey) {
20474
+ spinner.fail("No API key provided");
20475
+ process.exit(1);
20476
+ }
20477
+ const email = getArgumentByKey(["--email", "-e"]);
20478
+ if (!email || !/\S+@\S+\.\S+/.test(email)) {
20479
+ spinner.fail("Invalid email provided. Please provide a valid email using --email (-e) flag");
20480
+ process.exit(1);
20481
+ }
20482
+ // message is optional
20483
+ const message = getArgumentByKey(["--message", "-m"]);
20484
+ await buildArchive(config);
20485
+ return sendBuildByApiKey(config, {
20486
+ apiKey,
20487
+ email,
20488
+ message,
20489
+ });
20490
+ }
20138
20491
  async function selectWorkspace(ctx, token) {
20139
20492
  const workspaceSpinner = ora$1({
20140
20493
  text: `Fetching workspaces using ${ctx.pushBaseUrl}...`,
@@ -20180,6 +20533,12 @@ async function verify(ctx) {
20180
20533
  }
20181
20534
  return token;
20182
20535
  }
20536
+ async function buildArchive(config) {
20537
+ const spinnerArchive = ora$1("Building...").start();
20538
+ const filesList = await findFiles(config.client.modelsSrc || config.client.srcDir, YAML_OR_JS_FILES);
20539
+ await archive(config, filesList);
20540
+ return spinnerArchive.succeed("Bundling completed");
20541
+ }
20183
20542
  async function archive(ctx, yamlFiles, includeBuild = true) {
20184
20543
  const output = fs__namespace$1.createWriteStream(ctx.client.archiveFile);
20185
20544
  const _archiver = archiver__namespace.create("zip", {
@@ -20200,13 +20559,30 @@ async function archive(ctx, yamlFiles, includeBuild = true) {
20200
20559
  output.on("close", resolve);
20201
20560
  });
20202
20561
  }
20562
+ async function sendBuildByApiKey(ctx, { apiKey, email, message }) {
20563
+ var _a;
20564
+ const { FormData, Blob } = await import('formdata-node');
20565
+ const { fileFromPath } = await Promise.resolve().then(function () { return fileFromPath$1; });
20566
+ const file = await fileFromPath(ctx.client.archiveFile, "embeddable-build.zip");
20567
+ const form = new FormData();
20568
+ form.set("file", file, "embeddable-build.zip");
20569
+ const metadataBlob = new Blob([JSON.stringify({ authorEmail: email, description: message })], { type: "application/json" });
20570
+ form.set("metadata", metadataBlob, "metadata.json");
20571
+ const response = await uploadFile(form, `${ctx.pushBaseUrl}/api/v1/bundle/upload`, apiKey);
20572
+ await fs__namespace.rm(ctx.client.archiveFile);
20573
+ return { bundleId: (_a = response.data) === null || _a === void 0 ? void 0 : _a.bundleId, email, message };
20574
+ }
20203
20575
  async function sendBuild(ctx, { workspaceId, token }) {
20204
20576
  const { FormData } = await import('formdata-node');
20205
20577
  const { fileFromPath } = await Promise.resolve().then(function () { return fileFromPath$1; });
20206
20578
  const file = await fileFromPath(ctx.client.archiveFile, "embeddable-build.zip");
20207
20579
  const form = new FormData();
20208
20580
  form.set("file", file, "embeddable-build.zip");
20209
- await axios.post(`${ctx.pushBaseUrl}/bundle/${workspaceId}/upload`, form, {
20581
+ await uploadFile(form, `${ctx.pushBaseUrl}/bundle/${workspaceId}/upload`, token);
20582
+ await fs__namespace.rm(ctx.client.archiveFile);
20583
+ }
20584
+ async function uploadFile(formData, url, token) {
20585
+ return axios.post(url, formData, {
20210
20586
  headers: {
20211
20587
  "Content-Type": "multipart/form-data",
20212
20588
  Authorization: `Bearer ${token}`,
@@ -20214,7 +20590,6 @@ async function sendBuild(ctx, { workspaceId, token }) {
20214
20590
  maxContentLength: Infinity,
20215
20591
  maxBodyLength: Infinity,
20216
20592
  });
20217
- await fs__namespace.rm(ctx.client.archiveFile);
20218
20593
  }
20219
20594
  async function getWorkspaces(ctx, token, workspaceSpinner) {
20220
20595
  var _a;
@@ -20421,9 +20796,21 @@ const getPreviewWorkspace = async (ctx) => {
20421
20796
  }
20422
20797
  };
20423
20798
 
20424
- var defineConfig = ({ plugins, pushBaseUrl, audienceUrl, authDomain, authClientId, errorFallbackComponent, applicationEnvironment, rollbarAccessToken, previewBaseUrl, }) => {
20799
+ var defineConfig = ({ plugins, pushBaseUrl, audienceUrl, authDomain, authClientId, errorFallbackComponent, applicationEnvironment, rollbarAccessToken, previewBaseUrl, modelsSrc, componentsSrc = "src", }) => {
20425
20800
  const coreRoot = path__namespace.resolve(__dirname, "..");
20426
20801
  const clientRoot = process.cwd();
20802
+ if (!path__namespace.isAbsolute(componentsSrc)) {
20803
+ componentsSrc = path__namespace.resolve(clientRoot, componentsSrc);
20804
+ if (!fs$2.existsSync(componentsSrc)) {
20805
+ throw new Error(`componentsSrc directory ${componentsSrc} does not exist`);
20806
+ }
20807
+ }
20808
+ if (modelsSrc && !path__namespace.isAbsolute(modelsSrc)) {
20809
+ modelsSrc = path__namespace.resolve(clientRoot, modelsSrc);
20810
+ if (!fs$2.existsSync(modelsSrc)) {
20811
+ throw new Error(`modelsSrc directory ${modelsSrc} does not exist`);
20812
+ }
20813
+ }
20427
20814
  return {
20428
20815
  core: {
20429
20816
  rootDir: coreRoot,
@@ -20432,8 +20819,9 @@ var defineConfig = ({ plugins, pushBaseUrl, audienceUrl, authDomain, authClientI
20432
20819
  },
20433
20820
  client: {
20434
20821
  rootDir: clientRoot,
20822
+ srcDir: path__namespace.resolve(clientRoot, componentsSrc),
20823
+ modelsSrc: modelsSrc ? path__namespace.resolve(clientRoot, modelsSrc) : undefined,
20435
20824
  buildDir: path__namespace.resolve(clientRoot, ".embeddable-build"),
20436
- srcDir: path__namespace.resolve(clientRoot, "src"),
20437
20825
  tmpDir: path__namespace.resolve(clientRoot, ".embeddable-tmp"),
20438
20826
  componentDir: path__namespace.resolve(clientRoot, ".embeddable-build", "component"),
20439
20827
  stencilBuild: path__namespace.resolve(clientRoot, ".embeddable-build", "dist", "embeddable-wrapper"),