UNPKG

@knxcloud/lowcode-utils

Version:
602 lines (601 loc) 16.3 kB
var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; import { defineComponent, h } from "vue"; const noop = () => void 0; function fromPairs(entries) { const result = {}; for (const val of entries) { if (isArray(val) && val.length >= 2) { result[val[0]] = val[1]; } } return result; } function debounce(fn, ms) { let timerId = null; if (!ms) { return function() { if (!timerId) { timerId = setTimeout(() => { timerId = null; fn.apply(this); }); } }; } else { return function() { if (timerId) { clearTimeout(timerId); } timerId = setTimeout(() => { timerId = null; fn.apply(this); }, ms); }; } } const toString = (o) => Object.prototype.toString.call(o); function sleep(ms) { return new Promise((resolve) => { return setTimeout(resolve, ms); }); } const createObjectSplitter = (specialProps) => { const propsSet = new Set( isString(specialProps) ? specialProps.split(",") : isArray(specialProps) ? specialProps : [] ); const has = isFunction(specialProps) ? specialProps : (prop) => propsSet.has(prop); return (o) => { const keys = Object.keys(o); if (keys.every((k) => !has(k))) return [{}, o, 0]; let count = 0; const left = {}; const right = {}; for (const key of keys) { if (has(key)) { left[key] = o[key]; count++; } else { right[key] = o[key]; } } return [left, right, count]; }; }; const cached = (fn) => { const cacheStore = {}; return function(param) { return param in cacheStore ? cacheStore[param] : cacheStore[param] = fn.call(this, param); }; }; function isNil(val) { return val === null || val === void 0; } function isUndefined(val) { return val === void 0; } function isString(val) { return typeof val === "string"; } function isObject(val) { return !isNil(val) && typeof val === "object"; } function isBoolean(value) { return typeof value === "boolean"; } function isArray(val) { return Array.isArray(val); } function isFunction(val) { return typeof val === "function"; } function isPromise(val) { return isObject(val) && isFunction(val.then) && isFunction(val.catch); } function isPlainObject(val) { return !isNil(val) && toString(val) === "[object Object]"; } function isESModule(obj) { return obj && (Reflect.get(obj, "__esModule") || Reflect.get(obj, Symbol.toStringTag) === "Module"); } function isCSSUrl(url) { return /\.css$/.test(url); } function isElement(node) { return isObject(node) && node.nodeType === Node.ELEMENT_NODE; } function isJSFunction(val) { return val ? isObject(val) && (val.type === "JSFunction" || val.extType === "function") : false; } function isJSSlot(val) { return isObject(val) && val.type === "JSSlot"; } function isJSExpression(val) { return isObject(val) && val.type === "JSExpression" && val.extType !== "function"; } function isI18nData(val) { return isObject(val) && val.type === "i18n"; } function isDOMText(val) { return isString(val); } function isNodeSchema(data) { return data && data.componentName; } function isSlotSchema(data) { return isNodeSchema(data) && data.componentName === "Slot"; } function isComponentSchema(val) { return isObject(val) && val.componentName === "Component"; } function isContainerSchema(val) { return isNodeSchema(val) && (val.componentName === "Block" || val.componentName === "Page" || val.componentName === "Component"); } function isVueComponent(val) { if (isFunction(val)) return true; if (isObject(val) && ("render" in val || "setup" in val || "template" in val)) { return true; } return false; } const generateHtmlComp = cached((library) => { if (/^[a-z-]+$/.test(library)) { return defineComponent((_, { attrs, slots }) => { return () => h(library, attrs, slots); }); } }); function accessLibrary(library) { if (typeof library !== "string") { return library; } return window[library] || generateHtmlComp(library); } function getSubComponent(library, paths) { const l = paths.length; if (l < 1 || !library) { return library; } let i = 0; let component; while (i < l) { const key = paths[i]; let ex; try { component = library[key]; } catch (e) { ex = e; component = null; } if (i === 0 && component == null && key === "default") { if (ex) { return l === 1 ? library : null; } component = library; } else if (component == null) { return null; } library = component; i++; } return component; } function findComponent(libraryMap, componentName, npm) { if (!npm) { return accessLibrary(componentName); } const exportName = npm.exportName || npm.componentName || componentName; const libraryName = libraryMap[npm.package] || exportName; const library = accessLibrary(libraryName); const paths = npm.exportName && npm.subName ? npm.subName.split(".") : []; if (npm.destructuring) { paths.unshift(exportName); } else if (isESModule(library)) { paths.unshift("default"); } return getSubComponent(library, paths); } function buildComponents(libraryMap, componentsMap, createComponent) { const components = {}; Object.keys(componentsMap).forEach((componentName) => { let component = componentsMap[componentName]; if (isComponentSchema(component)) { if (createComponent) { components[componentName] = createComponent( component ); } } else if (isVueComponent(component)) { components[componentName] = component; } else { component = findComponent( libraryMap, componentName, component ); if (component) { components[componentName] = component; } } }); return components; } function buildUtils(libraryMap, utilsMetadata) { return utilsMetadata.filter((meta) => meta && meta.name).reduce( (utils, meta) => { const { name, content, type } = meta; if (type === "npm") { const { package: pkg, exportName, destructuring } = content != null ? content : {}; if (libraryMap[pkg]) { const library = accessLibrary(libraryMap[pkg]); if (library) { utils[name] = destructuring && exportName ? library[exportName] : library; } } } else if (type === "function") { utils[name] = isJSFunction(content) ? new Function(`return ${content.value}`)() : meta.content; } return utils; }, {} ); } var AssetLevel = /* @__PURE__ */ function(AssetLevel2) { AssetLevel2[AssetLevel2["Environment"] = 1] = "Environment"; AssetLevel2[AssetLevel2["Library"] = 2] = "Library"; AssetLevel2[AssetLevel2["Theme"] = 3] = "Theme"; AssetLevel2[AssetLevel2["Runtime"] = 4] = "Runtime"; AssetLevel2[AssetLevel2["Components"] = 5] = "Components"; AssetLevel2[AssetLevel2["App"] = 6] = "App"; return AssetLevel2; }({}); var AssetLevels = [AssetLevel.Environment, AssetLevel.Library, AssetLevel.Theme, AssetLevel.Runtime, AssetLevel.Components, AssetLevel.App]; var AssetType = /* @__PURE__ */ function(AssetType2) { AssetType2["JSUrl"] = "jsUrl"; AssetType2["CSSUrl"] = "cssUrl"; AssetType2["CSSText"] = "cssText"; AssetType2["JSText"] = "jsText"; AssetType2["Bundle"] = "bundle"; return AssetType2; }({}); function createDefer() { const r = {}; const promise = new Promise((resolve, reject) => { r.resolve = resolve; r.reject = reject; }); r.promise = () => promise; return r; } function evaluate(script) { const scriptEl = document.createElement("script"); scriptEl.text = script; document.head.appendChild(scriptEl); document.head.removeChild(scriptEl); } function load(url) { const node = document.createElement("script"); node.onload = onload; node.onerror = onload; const i = createDefer(); function onload(e) { node.onload = null; node.onerror = null; if (e.type === "load") { i.resolve(); } else { i.reject(); } } node.src = url; node.async = false; document.head.appendChild(node); return i.promise(); } function isAssetItem(obj) { return obj && !!obj.type; } function isAssetBundle(obj) { return obj && obj.type === AssetType.Bundle; } function assetItem(type, content, level, id) { return content ? { type, content, level, id } : null; } function parseAssetList(scripts, styles, assets, level) { for (const asset of assets) { parseAsset(scripts, styles, asset, level); } } function parseAsset(scripts, styles, asset, level) { if (!asset) { return; } if (isArray(asset)) { return parseAssetList(scripts, styles, asset, level); } if (isAssetBundle(asset)) { if (asset.assets) { if (isArray(asset.assets)) { parseAssetList(scripts, styles, asset.assets, asset.level || level); } else { parseAsset(scripts, styles, asset.assets, asset.level || level); } return; } return; } if (!isAssetItem(asset)) { asset = assetItem( isCSSUrl(asset) ? AssetType.CSSUrl : AssetType.JSUrl, asset, level ); } let lv = asset.level || level; if (!lv || AssetLevel[lv] == null) { lv = AssetLevel.App; } asset.level = lv; if (asset.type === AssetType.CSSUrl || asset.type == AssetType.CSSText) { styles[lv].push(asset); } else { scripts[lv].push(asset); } } class StylePoint { constructor(level, id) { __publicField(this, "lastContent"); __publicField(this, "lastUrl"); __publicField(this, "placeholder"); this.level = level; this.id = id; let placeholder = null; if (id) { placeholder = document.head.querySelector(`style[data-id="${id}"]`); } if (!placeholder) { placeholder = document.createTextNode(""); const meta = document.head.querySelector(`meta[level="${level}"]`); if (meta) { document.head.insertBefore(placeholder, meta); } else { document.head.appendChild(placeholder); } } this.placeholder = placeholder; } applyText(content) { if (this.lastContent === content) { return; } this.lastContent = content; this.lastUrl = void 0; const element = document.createElement("style"); element.setAttribute("type", "text/css"); if (this.id) { element.setAttribute("data-id", this.id); } element.appendChild(document.createTextNode(content)); document.head.insertBefore( element, this.placeholder.parentNode === document.head ? this.placeholder.nextSibling : null ); document.head.removeChild(this.placeholder); this.placeholder = element; } applyUrl(url) { if (this.lastUrl === url) { return; } this.lastContent = void 0; this.lastUrl = url; const element = document.createElement("link"); element.onload = onload; element.onerror = onload; const i = createDefer(); function onload(e) { element.onload = null; element.onerror = null; if (e.type === "load") { i.resolve(); } else { i.reject(); } } element.href = url; element.rel = "stylesheet"; if (this.id) { element.setAttribute("data-id", this.id); } document.head.insertBefore( element, this.placeholder.parentNode === document.head ? this.placeholder.nextSibling : null ); document.head.removeChild(this.placeholder); this.placeholder = element; return i.promise(); } } class AssetLoader { constructor() { __publicField(this, "stylePoints", /* @__PURE__ */ new Map()); } async load(asset) { const styles = {}; const scripts = {}; AssetLevels.forEach((lv) => { styles[lv] = []; scripts[lv] = []; }); parseAsset(scripts, styles, asset); const styleQueue = styles[AssetLevel.Environment].concat( styles[AssetLevel.Library], styles[AssetLevel.Theme], styles[AssetLevel.Runtime], styles[AssetLevel.App] ); const scriptQueue = scripts[AssetLevel.Environment].concat( scripts[AssetLevel.Library], scripts[AssetLevel.Theme], scripts[AssetLevel.Runtime], scripts[AssetLevel.App] ); await Promise.all( styleQueue.map( ({ content, level, type, id }) => this.loadStyle(content, level, type === AssetType.CSSUrl, id) ) ); await Promise.all( scriptQueue.map( ({ content, type }) => this.loadScript(content, type === AssetType.JSUrl) ) ); } loadStyle(content, level, isUrl, id) { if (!content) { return; } let point; if (id) { point = this.stylePoints.get(id); if (!point) { point = new StylePoint(level, id); this.stylePoints.set(id, point); } } else { point = new StylePoint(level); } return isUrl ? point.applyUrl(content) : point.applyText(content); } loadScript(content, isUrl) { if (!content) { return; } return isUrl ? load(content) : evaluate(content); } async loadAsyncLibrary(asyncLibraryMap) { const promiseList = []; const libraryKeyList = []; for (const key in asyncLibraryMap) { if (asyncLibraryMap[key].async) { promiseList.push(window[asyncLibraryMap[key].library]); libraryKeyList.push(asyncLibraryMap[key].library); } } await Promise.all(promiseList).then((mods) => { if (mods.length > 0) { mods.map((item, index) => { window[libraryKeyList[index]] = item; return item; }); } }); } } function setupHostEnvironment(project, vueRuntimeUrl) { project.onSimulatorHostReady((host) => { host.set("environment", [ assetItem( AssetType.JSText, "window.__is_simulator_env__=true;window.__VUE_DEVTOOLS_GLOBAL_HOOK__=window.parent.__VUE_DEVTOOLS_GLOBAL_HOOK__;" ), assetItem(AssetType.JSUrl, vueRuntimeUrl, void 0, "vue") ]); }); } function kebabCase(str) { if (!str) return str; return str.replace(/[A-Z]/g, (c, i) => { const suf = i > 0 ? "-" : ""; return suf + c.toLocaleLowerCase(); }); } function camelCase(str) { if (!str) return str; return str.replace(/-[a-zA-Z]/g, (c) => { return c.charAt(1).toLocaleUpperCase(); }); } function pascalCase(str) { const res = camelCase(str); return res && res.charAt(0).toLocaleUpperCase() + res.slice(1); } IPublicEnumTransformStage_1 = void 0; var IPublicEnumTransformStage = /* @__PURE__ */ function(IPublicEnumTransformStage2) { IPublicEnumTransformStage2["Render"] = "render"; IPublicEnumTransformStage2["Serilize"] = "serilize"; IPublicEnumTransformStage2["Save"] = "save"; IPublicEnumTransformStage2["Clone"] = "clone"; IPublicEnumTransformStage2["Init"] = "init"; IPublicEnumTransformStage2["Upgrade"] = "upgrade"; return IPublicEnumTransformStage2; }({}); var IPublicEnumTransformStage_1 = IPublicEnumTransformStage; function exportSchema(node) { if (isObject(node)) { if (isFunction(node.export)) { return node.export(IPublicEnumTransformStage_1.Render); } else if (isFunction(node.exportSchema)) { return node.exportSchema(IPublicEnumTransformStage_1.Render); } } return null; } export { AssetLevel, AssetLevels, AssetLoader, AssetType, StylePoint, accessLibrary, assetItem, buildComponents, buildUtils, cached, camelCase, createDefer, createObjectSplitter, debounce, exportSchema, findComponent, fromPairs, getSubComponent, isArray, isAssetBundle, isAssetItem, isBoolean, isCSSUrl, isComponentSchema, isContainerSchema, isDOMText, isESModule, isElement, isFunction, isI18nData, isJSExpression, isJSFunction, isJSSlot, isNil, isNodeSchema, isObject, isPlainObject, isPromise, isSlotSchema, isString, isUndefined, kebabCase, noop, pascalCase, setupHostEnvironment, sleep, toString }; //# sourceMappingURL=lowcode-utils.mjs.map