UNPKG

@embeddable.com/sdk-core

Version:

Core Embeddable SDK module responsible for web-components bundling and publishing.

1,345 lines (1,316 loc) 723 kB
'use strict'; var fs = require('node:fs/promises'); var path = require('node:path'); var vite = require('vite'); require('node:child_process'); var crypto = require('node:crypto'); var fs$1 = require('node:fs'); var node = require('@stencil/core/sys/node'); var compiler = require('@stencil/core/compiler'); var sorcery = require('sorcery'); var os = require('node:os'); var ora = require('ora'); var YAML = require('yaml'); var url = require('node:url'); var require$$4$1 = require('util'); var require$$1 = require('os'); var require$$3 = require('http'); var require$$4 = require('https'); var require$$0$1 = require('url'); var require$$2$1 = require('fs'); var path$1 = require('path'); var axios = require('axios'); var archiver = require('archiver'); var prompts = require('@inquirer/prompts'); var http = require('node:http'); var ws = require('ws'); var chokidar = require('chokidar'); var minimist = require('minimist'); var fg = require('fast-glob'); var dotenv = require('dotenv'); var promises = require('fs/promises'); function _interopNamespaceDefault(e) { var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs); var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path); var vite__namespace = /*#__PURE__*/_interopNamespaceDefault(vite); var crypto__namespace = /*#__PURE__*/_interopNamespaceDefault(crypto); var fs__namespace$1 = /*#__PURE__*/_interopNamespaceDefault(fs$1); var sorcery__namespace = /*#__PURE__*/_interopNamespaceDefault(sorcery); var os__namespace = /*#__PURE__*/_interopNamespaceDefault(os); var YAML__namespace = /*#__PURE__*/_interopNamespaceDefault(YAML); var url__namespace = /*#__PURE__*/_interopNamespaceDefault(url); var require$$2__namespace = /*#__PURE__*/_interopNamespaceDefault(require$$2$1); var path__namespace$1 = /*#__PURE__*/_interopNamespaceDefault(path$1); var archiver__namespace = /*#__PURE__*/_interopNamespaceDefault(archiver); var http__namespace = /*#__PURE__*/_interopNamespaceDefault(http); var chokidar__namespace = /*#__PURE__*/_interopNamespaceDefault(chokidar); var dotenv__namespace = /*#__PURE__*/_interopNamespaceDefault(dotenv); var findFiles = async (initialSrcDir, regex) => { const filesList = []; async function findFilesRec(srcDir) { const allFiles = await fs.readdir(srcDir); for (const file of allFiles) { const filePath = path.join(srcDir, file); const status = await fs.lstat(filePath); if (status.isDirectory()) { await findFilesRec(filePath); } const fileName = file.match(regex); if (fileName) { filesList.push([fileName[1], filePath]); } } } await findFilesRec(initialSrcDir); return filesList; }; var util$2; (function (util) { util.assertEqual = (val) => val; function assertIs(_arg) { } util.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util.assertNever = assertNever; util.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util.getValidEnumValues = (obj) => { const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util.objectValues(filtered); }; util.objectValues = (obj) => { return util.objectKeys(obj).map(function (e) { return obj[e]; }); }; util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban : (object) => { const keys = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys.push(key); } } return keys; }; util.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return undefined; }; util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array .map((val) => (typeof val === "string" ? `'${val}'` : val)) .join(separator); } util.joinValues = joinValues; util.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util$2 || (util$2 = {})); var objectUtil$1; (function (objectUtil) { objectUtil.mergeShapes = (first, second) => { return { ...first, ...second, // second overwrites first }; }; })(objectUtil$1 || (objectUtil$1 = {})); util$2.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set", ]); const ZodIssueCode$1 = util$2.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite", ]); let ZodError$1 = class ZodError extends Error { constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { // eslint-disable-next-line ban/ban Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } get errors() { return this.issues; } format(_mapper) { const mapper = _mapper || function (issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error) => { for (const issue of error.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper(issue)); } else { let curr = fieldErrors; let i = 0; while (i < issue.path.length) { const el = issue.path[i]; const terminal = i === issue.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; // if (typeof el === "string") { // curr[el] = curr[el] || { _errors: [] }; // } else if (typeof el === "number") { // const errorArray: any = []; // errorArray._errors = []; // curr[el] = curr[el] || errorArray; // } } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util$2.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } }; ZodError$1.create = (issues) => { const error = new ZodError$1(issues); return error; }; typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; var errorUtil$1; (function (errorUtil) { errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; })(errorUtil$1 || (errorUtil$1 = {})); var ZodFirstPartyTypeKind$1; (function (ZodFirstPartyTypeKind) { ZodFirstPartyTypeKind["ZodString"] = "ZodString"; ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind$1 || (ZodFirstPartyTypeKind$1 = {})); const errorFormatter = (issues) => { const errors = []; for (let issue of issues) { if (issue.code === ZodIssueCode$1.invalid_union && issue.unionErrors.length) { const error = issue.unionErrors[issue.unionErrors.length - 1]; issue = error.issues[error.issues.length - 1]; } const path = formatErrorPath(issue.path); const message = issue.message; errors.push(`"${path}": ${message}`); } return errors; }; const formatErrorPath = (path) => { let formatted = ""; for (const pathElement of path) { if (formatted.length === 0) { formatted = `${pathElement}`; } else { formatted += typeof pathElement === "number" ? `[${pathElement}]` : `.${pathElement}`; } } return formatted; }; /** * Get the hash of the content string. It returns the first 5 characters of the hash * Example: getContentHash("Hello World") * @param contentString The content string to hash * @returns */ const getContentHash = (contentString) => { return crypto__namespace .createHash("md5") .update(contentString) .digest("hex") .substring(0, 5); }; const oraP$1 = import('ora'); const EMB_TYPE_FILE_REGEX = /^(.*)\.type\.emb\.[jt]s$/; const EMB_OPTIONS_FILE_REGEX = /^(.*)\.options\.emb\.[jt]s$/; var buildTypes = async (ctx) => { const ora = (await oraP$1).default; const progress = ora("Building types...").start(); await generate$1(ctx); await build$1(ctx); await cleanup$1(ctx); progress.succeed("Types built completed"); }; async function generate$1(ctx) { const typeFiles = await findFiles(ctx.client.srcDir, EMB_TYPE_FILE_REGEX); const optionsFiles = await findFiles(ctx.client.srcDir, EMB_OPTIONS_FILE_REGEX); const typeImports = typeFiles .concat(optionsFiles) .map(([_fileName, filePath]) => `import '../${path__namespace .relative(ctx.client.rootDir, filePath) .replaceAll("\\", "/")}';`) .join("\n"); await fs__namespace.writeFile(path__namespace.resolve(ctx.client.buildDir, ctx.outputOptions.typesEntryPointFilename), typeImports); } async function build$1(ctx) { var _a; const typesFilePath = path__namespace.resolve(ctx.client.buildDir, ctx.outputOptions.typesEntryPointFilename); await vite__namespace.build({ logLevel: "error", build: { emptyOutDir: false, lib: { entry: typesFilePath, formats: ["es"], fileName: "embeddable-types", }, outDir: ctx.client.buildDir, }, }); if (!((_a = ctx.dev) === null || _a === void 0 ? void 0 : _a.watch)) { const fileContent = await fs__namespace.readFile(typesFilePath, "utf8"); const fileHash = getContentHash(fileContent); const fileName = `embeddable-types-${fileHash}.js`; await fs__namespace.rename(path__namespace.resolve(ctx.client.buildDir, "embeddable-types.js"), path__namespace.resolve(ctx.client.buildDir, fileName)); } } async function cleanup$1(ctx) { await fs__namespace.rm(path__namespace.resolve(ctx.client.buildDir, "embeddable-types-entry-point.js")); } var prepare = async (ctx) => { await removeIfExists(ctx); await copyStencilConfigsToClient(ctx); await createComponentDir(ctx.client.componentDir); }; async function removeIfExists(ctx) { if (fs__namespace$1.existsSync(ctx.client.buildDir)) await fs__namespace.rm(ctx.client.buildDir, { recursive: true }); if (fs__namespace$1.existsSync(ctx.client.tmpDir)) await fs__namespace.rm(ctx.client.tmpDir, { recursive: true }); } async function copyStencilConfigsToClient(ctx) { await fs__namespace.cp(ctx.core.configsDir, ctx.client.buildDir, { recursive: true }); } async function createComponentDir(dir) { await fs__namespace.mkdir(dir); } const STYLE_IMPORTS_TOKEN = "{{STYLES_IMPORT}}"; const RENDER_IMPORT_TOKEN = "{{RENDER_IMPORT}}"; // stencil doesn't support dynamic component tag name, so we need to replace it manually const COMPONENT_TAG_TOKEN = "replace-this-with-component-name"; var generate = async (ctx, pluginName) => { await injectCSS(ctx, pluginName); await injectBundleRender(ctx, pluginName); await runStencil(ctx); await generateSourceMap(ctx, pluginName); }; async function injectCSS(ctx, pluginName) { const CUSTOMER_BUILD = path__namespace.resolve(ctx.client.buildDir, ctx[pluginName].outputOptions.buildName); const allFiles = await fs__namespace.readdir(CUSTOMER_BUILD); const cssFilesImportsStr = allFiles .filter((fileName) => fileName.endsWith(".css")) .map((fileName) => `@import '../${ctx[pluginName].outputOptions.buildName}/${fileName}';`) .join("\n"); const content = await fs__namespace.readFile(path__namespace.resolve(ctx.core.templatesDir, "style.css.template"), "utf8"); await fs__namespace.writeFile(path__namespace.resolve(ctx.client.componentDir, "style.css"), content.replace(STYLE_IMPORTS_TOKEN, cssFilesImportsStr)); } async function injectBundleRender(ctx, pluginName) { const importStr = `import render from '../${ctx[pluginName].outputOptions.buildName}/${ctx[pluginName].outputOptions.fileName}';`; let content = await fs__namespace.readFile(path__namespace.resolve(ctx.core.templatesDir, "component.tsx.template"), "utf8"); if (!!ctx.dev) { content = content.replace(COMPONENT_TAG_TOKEN, "embeddable-component"); } await fs__namespace.writeFile(path__namespace.resolve(ctx.client.componentDir, "component.tsx"), content.replace(RENDER_IMPORT_TOKEN, importStr)); } async function addComponentTagName(filePath, bundleHash) { // find entry file with a name *.entry.js const entryFiles = await findFiles(path__namespace.dirname(filePath), /.*\.entry\.js/); if (!entryFiles.length) { return; } const entryFileName = entryFiles[0]; const [entryFileContent, fileContent] = await Promise.all([ fs__namespace.readFile(entryFileName[1], "utf8"), fs__namespace.readFile(filePath, "utf8"), ]); const newFileContent = fileContent.replace(COMPONENT_TAG_TOKEN, `embeddable-component-${bundleHash}`); const newEntryFileContent = entryFileContent.replace(COMPONENT_TAG_TOKEN.replaceAll("-", "_"), `embeddable_component_${bundleHash}`); await Promise.all([ fs__namespace.writeFile(filePath, newFileContent), fs__namespace.writeFile(entryFileName[1], newEntryFileContent), ]); } async function runStencil(ctx) { var _a, _b; const logger = ((_a = ctx.dev) === null || _a === void 0 ? void 0 : _a.logger) || node.createNodeLogger(); const sys = ((_b = ctx.dev) === null || _b === void 0 ? void 0 : _b.sys) || node.createNodeSys({ process }); const devMode = !!ctx.dev; const isWindows = process.platform === "win32"; const validated = await compiler.loadConfig({ initTsConfig: true, logger, sys, config: { devMode, maxConcurrentWorkers: isWindows ? 0 : 8, // workers break on windows rootDir: ctx.client.buildDir, configPath: path__namespace.resolve(ctx.client.buildDir, "stencil.config.ts"), tsconfig: path__namespace.resolve(ctx.client.buildDir, "tsconfig.json"), namespace: "embeddable-wrapper", srcDir: path__namespace.resolve(ctx.client.buildDir, "component"), sourceMap: true, // always generate source maps in both dev and prod minifyJs: !devMode, minifyCss: !devMode, outputTargets: [ { type: "dist", }, ], watchDirs: [ path__namespace.resolve(ctx.client.buildDir, ctx["sdk-react"].outputOptions.buildName), ], }, }); const compiler$1 = await compiler.createCompiler(validated.config); const buildResults = await compiler$1.build(); if (!devMode) { if (buildResults.hasError) { console.error("Stencil build error:", buildResults.diagnostics); throw new Error("Stencil build error"); } else { await handleStencilBuildOutput(ctx); } await compiler$1.destroy(); } process.chdir(ctx.client.rootDir); } async function handleStencilBuildOutput(ctx) { var _a; const entryFilePath = path__namespace.resolve(ctx.client.stencilBuild, "embeddable-wrapper.esm.js"); let fileName = "embeddable-wrapper.esm.js"; if (!((_a = ctx.dev) === null || _a === void 0 ? void 0 : _a.watch)) { const entryFileContent = await fs__namespace.readFile(entryFilePath, "utf8"); const fileHash = getContentHash(entryFileContent); fileName = `embeddable-wrapper.esm-${fileHash}.js`; ctx.client.bundleHash = fileHash; await addComponentTagName(entryFilePath, ctx.client.bundleHash); } await fs__namespace.rename(entryFilePath, path__namespace.resolve(ctx.client.stencilBuild, fileName)); } async function generateSourceMap(ctx, pluginName) { const componentBuildDir = path__namespace.resolve(ctx.client.buildDir, ctx[pluginName].outputOptions.buildName); const stencilBuild = path__namespace.resolve(ctx.client.stencilBuild); const tmpComponentDir = path__namespace.resolve(stencilBuild, ctx[pluginName].outputOptions.buildName); await fs__namespace.cp(componentBuildDir, tmpComponentDir, { recursive: true }); const stencilFiles = await fs__namespace.readdir(stencilBuild); const jsFiles = stencilFiles.filter((file) => file.toLowerCase().endsWith(".js")); await Promise.all(jsFiles.map(async (jsFile) => { try { const chain = await sorcery__namespace.load(path__namespace.resolve(stencilBuild, jsFile)); // overwrite the existing file await chain.write(); } catch (e) { // do nothing if a map file can not be generated } })); await fs__namespace.rm(tmpComponentDir, { recursive: true }); } const CREDENTIALS_DIR = path__namespace.resolve(os__namespace.homedir(), ".embeddable"); const CREDENTIALS_FILE = path__namespace.resolve(CREDENTIALS_DIR, "credentials"); const checkNodeVersion = async () => { const spinner = ora("Checking node version...").start(); const [major, minor] = process.versions.node.split(".").map(Number); let packageJson; try { packageJson = JSON.parse(fs$1.readFileSync(path.join(undefined, "../package.json"), "utf-8")); } catch (e) { throw new Error("Failed to read package.json of core-sdk"); } const { engines: { node }, } = packageJson; const [minMajor, minMinor] = node .split(".") .map((v) => v.replace(/[^\d]/g, "")) .map(Number); if (major < minMajor || (major === minMajor && minor < minMinor)) { spinner.fail(`Node version ${minMajor}.${minMinor} or higher is required. You are running ${major}.${minor}.`); process.exit(1); } else { spinner.stop(); return true; } }; /** * Get the value of a process argument by key * Example: getArgumentByKey("--email") or getArgumentByKey(["--email", "-e"]) * @param key The key to search for in the process arguments * @returns */ const getArgumentByKey = (key) => { if (Array.isArray(key)) { for (const k of key) { if (process.argv.includes(k)) { const index = process.argv.indexOf(k); return index !== -1 ? process.argv[index + 1] : undefined; } } return undefined; } const index = process.argv.indexOf(key); return index !== -1 ? process.argv[index + 1] : undefined; }; const SUCCESS_FLAG_FILE = `${CREDENTIALS_DIR}/success`; /** * Store a flag in the credentials directory to indicate a successful build * This is used to determine if the build was successful or not */ const storeBuildSuccessFlag = async () => { try { await fs__namespace.access(CREDENTIALS_DIR); } catch (_e) { await fs__namespace.mkdir(CREDENTIALS_DIR); } await fs__namespace.writeFile(SUCCESS_FLAG_FILE, "true"); }; /** * Remove the success flag from the credentials directory */ const removeBuildSuccessFlag = async () => { try { await fs__namespace.unlink(SUCCESS_FLAG_FILE); } catch (_e) { } }; /** * Check if the build was successful */ const checkBuildSuccess = async () => { try { await fs__namespace.access(SUCCESS_FLAG_FILE); return true; } catch (_e) { return false; } }; const getPackageVersion = (packageName) => { const packageJsonPath = path.join(process.cwd(), "node_modules", packageName, "package.json"); try { const packageJson = require(packageJsonPath); return packageJson.version; } catch (e) { return undefined; } }; const getSDKVersions = () => { const packageNames = [ "@embeddable.com/core", "@embeddable.com/react", "@embeddable.com/sdk-core", "@embeddable.com/sdk-react", "@embeddable.com/sdk-utils", ]; const sdkVersions = packageNames.reduce((acc, packageName) => { const version = getPackageVersion(packageName); if (version) { acc[packageName] = version; } return acc; }, {}); return sdkVersions; }; const hrtimeToISO8601 = (hrtime) => { if (hrtime === null || hrtime === undefined) { return ""; } const seconds = hrtime[0]; const nanoseconds = hrtime[1]; // Convert time components const totalSeconds = seconds + nanoseconds / 1e9; const minutes = Math.floor(totalSeconds / 60); const remainingSeconds = totalSeconds % 60; // Format ISO 8601 duration without hours return `PT${minutes > 0 ? minutes + "M" : ""}${remainingSeconds.toFixed(3)}S`; }; var cleanup = async (ctx) => { await extractBuild(ctx); await removeObsoleteDir(ctx.client.buildDir); await moveBuildTOBuildDir(ctx); }; async function createManifest({ ctx, typesFileName, metaFileName, editorsMetaFileName, stencilWrapperFileName, }) { var _a, _b, _c, _d; const sdkVersions = getSDKVersions(); // identify user's package manager and its version let packageManager = "npm"; if ((_a = process.env.npm_config_user_agent) === null || _a === void 0 ? void 0 : _a.includes("yarn")) { packageManager = "yarn"; } if ((_b = process.env.npm_config_user_agent) === null || _b === void 0 ? void 0 : _b.includes("pnpm")) { packageManager = "pnpm"; } const packageManagerVersion = ((_d = (_c = process.env.npm_config_user_agent) === null || _c === void 0 ? void 0 : _c.match(/(\d+\.\d+\.\d+)/)) === null || _d === void 0 ? void 0 : _d[0]) || "unknown"; // write manifest file with files with hash const manifest = { entryFiles: { "embeddable-types.js": typesFileName, "embeddable-components-meta.js": metaFileName, "embeddable-editors-meta.js": editorsMetaFileName, "embeddable-wrapper.esm.js": stencilWrapperFileName, }, metadata: { nodeVersion: process.version, platform: process.platform, bundleHash: ctx.client.bundleHash, sdkVersions, packageManager, packageManagerVersion, metrics: { buildTime: hrtimeToISO8601(ctx.buildTime), }, }, }; await fs__namespace.writeFile(path__namespace.join(ctx.client.tmpDir, "embeddable-manifest.json"), JSON.stringify(manifest)); } async function extractBuild(ctx) { const stencilBuildFiles = await findFiles(ctx.client.stencilBuild, /embeddable-wrapper.esm-[a-z0-9]+\.js/); const [[, stencilWrapperFilePath]] = stencilBuildFiles || []; const stencilWrapperFileName = path__namespace.basename(stencilWrapperFilePath); await fs__namespace.rename(path__namespace.resolve(ctx.client.buildDir, ctx.client.stencilBuild), ctx.client.tmpDir); const typesBuildFiles = await findFiles(ctx.client.buildDir, /embeddable-types-[a-z0-9]+\.js/); const [[, typesFilePath]] = typesBuildFiles || []; const typesFileName = path__namespace.basename(typesFilePath); await fs__namespace.rename(typesFilePath, path__namespace.join(ctx.client.tmpDir, typesFileName)); const metaBuildFiles = await findFiles(ctx.client.buildDir, /embeddable-components-meta-[a-z0-9]+\.js/); const [[, metaFilePath]] = metaBuildFiles || []; const metaFileName = path__namespace.basename(metaFilePath); await fs__namespace.rename(metaFilePath, path__namespace.join(ctx.client.tmpDir, metaFileName)); const editorsMetaBuildFiles = await findFiles(ctx.client.buildDir, /embeddable-editors-meta-[a-z0-9]+\.js/); const [[, editorsMetaFilePath]] = editorsMetaBuildFiles || []; const editorsMetaFileName = path__namespace.basename(editorsMetaFilePath); await fs__namespace.rename(editorsMetaFilePath, path__namespace.join(ctx.client.tmpDir, editorsMetaFileName)); await createManifest({ ctx, typesFileName, metaFileName, editorsMetaFileName, stencilWrapperFileName, }); } async function removeObsoleteDir(dir) { await fs__namespace.rm(dir, { recursive: true }); } async function moveBuildTOBuildDir(ctx) { await fs__namespace.rename(ctx.client.tmpDir, ctx.client.buildDir); } var util$1; (function (util) { util.assertEqual = (val) => val; function assertIs(_arg) { } util.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util.assertNever = assertNever; util.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util.getValidEnumValues = (obj) => { const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util.objectValues(filtered); }; util.objectValues = (obj) => { return util.objectKeys(obj).map(function (e) { return obj[e]; }); }; util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban : (object) => { const keys = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys.push(key); } } return keys; }; util.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return undefined; }; util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array .map((val) => (typeof val === "string" ? `'${val}'` : val)) .join(separator); } util.joinValues = joinValues; util.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util$1 || (util$1 = {})); var objectUtil; (function (objectUtil) { objectUtil.mergeShapes = (first, second) => { return { ...first, ...second, // second overwrites first }; }; })(objectUtil || (objectUtil = {})); const ZodParsedType = util$1.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set", ]); const getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; const ZodIssueCode = util$1.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite", ]); const quotelessJson = (obj) => { const json = JSON.stringify(obj, null, 2); return json.replace(/"([^"]+)":/g, "$1:"); }; class ZodError extends Error { constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { // eslint-disable-next-line ban/ban Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } get errors() { return this.issues; } format(_mapper) { const mapper = _mapper || function (issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error) => { for (const issue of error.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper(issue)); } else { let curr = fieldErrors; let i = 0; while (i < issue.path.length) { const el = issue.path[i]; const terminal = i === issue.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; // if (typeof el === "string") { // curr[el] = curr[el] || { _errors: [] }; // } else if (typeof el === "number") { // const errorArray: any = []; // errorArray._errors = []; // curr[el] = curr[el] || errorArray; // } } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util$1.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } } ZodError.create = (issues) => { const error = new ZodError(issues); return error; }; const errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodIssueCode.invalid_type: if (issue.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util$1.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util$1.joinValues(issue.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util$1.joinValues(issue.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util$1.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodIssueCode.invalid_string: if (typeof issue.validation === "object") { if ("includes" in issue.validation) { message = `Invalid input: must include "${issue.validation.includes}"`; if (typeof issue.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; } } else if ("startsWith" in issue.validation) { message = `Invalid input: must start with "${issue.validation.startsWith}"`; } else if ("endsWith" in issue.validation) { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { util$1.assertNever(issue.validation); } } else if (issue.validation !== "regex") { message = `Invalid ${issue.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode.custom: message = `Invalid input`; break; case ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util$1.assertNever(issue); } return { message }; }; let overrideErrorMap = errorMap; function setErrorMap(map) { overrideErrorMap = map; } function getErrorMap() { return overrideErrorMap; } const makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...(issueData.path || [])]; const fullIssue = { ...issueData, path: fullPath, }; if (issueData.message !== undefined) { return { ...issueData, path: fullPath, message: issueData.message, }; } let errorMessage = ""; const maps = errorMaps .filter((m) => !!m) .slice() .reverse(); for (const map of maps) { errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: errorMessage, }; }; const EMPTY_PATH = []; function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap(); const issue = makeIssue({ issueData: issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, overrideMap, overrideMap === errorMap ? undefined : errorMap, // then global default map ].filter((x) => !!x), }); ctx.common.issues.push(issue); } class ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s of results) { if (s.status === "aborted") return INVALID; if (s.status === "dirty") status.dirty(); arrayValue.push(s.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs) { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value, }); } return ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs) { const finalObject = {}; for (const pair of pairs) { const { key, value } = pair; if (key.status === "aborted") return INVALID; if (value.status === "aborted") return INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } } const INVALID = Object.freeze({ status: "aborted", }); const DIRTY = (value) => ({ status: "dirty", value }); const OK = (value) => ({ status: "valid", value }); const isAborted = (x) => x.status === "aborted"; const isDirty = (x) => x.status === "dirty"; const isValid = (x) => x.status === "valid"; const isAsync$1 = (x) => typeof Promise !== "undefined" && x instanceof Promise; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function __classPrivateFieldGet(receiver, state, kind, f) { 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"); return state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { 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"); return (state.set(receiver, value)), value; } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; var errorUtil; (function (errorUtil) { errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; })(errorUtil || (errorUtil = {})); var _ZodEnum_cache, _ZodNativeEnum_cache; class ParseInputLazyPath { constructor(parent, value, path, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path; this._key = key; } get pa