UNPKG

@builder.io/sdk-vue

Version:
49 lines (43 loc) 7.75 kB
"use strict";const node_module=require("node:module");var _documentCurrentScript=typeof document<"u"?document.currentScript:null;const TARGET="vue",MSG_PREFIX="[Builder.io]: ",logger={log:(...e)=>console.log(MSG_PREFIX,...e),error:(...e)=>console.error(MSG_PREFIX,...e),warn:(...e)=>console.warn(MSG_PREFIX,...e),debug:(...e)=>console.debug(MSG_PREFIX,...e)};function isBrowser(){return typeof window<"u"&&typeof document<"u"}const convertSearchParamsToQueryObject=e=>{const t={};return e.forEach((n,r)=>{t[r]=n}),t},normalizeSearchParams=e=>e instanceof URLSearchParams?convertSearchParamsToQueryObject(e):e,getSearchString=e=>typeof e=="string"?e:e instanceof URLSearchParams?e.toString():new URLSearchParams(e).toString();function isIframe(){return isBrowser()&&window.self!==window.top}function isEditing(e){return isIframe()&&getSearchString(e||window.location.search).indexOf("builder.frameEditing=")!==-1}const getLocation=()=>{if(isBrowser()){const e=new URL(location.href);return e.pathname===""&&(e.pathname="/"),e}else return console.warn("Cannot get location for tracking in non-browser environment"),null},getUserAgent=()=>typeof navigator=="object"&&navigator.userAgent||"",getUserAttributes=()=>{const e=getUserAgent(),t={Android(){return e.match(/Android/i)},BlackBerry(){return e.match(/BlackBerry/i)},iOS(){return e.match(/iPhone|iPod/i)},Opera(){return e.match(/Opera Mini/i)},Windows(){return e.match(/IEMobile/i)||e.match(/WPDesktop/i)},any(){return t.Android()||t.BlackBerry()||t.iOS()||t.Opera()||t.Windows()||TARGET==="reactNative"}},n=e.match(/Tablet|iPad/i),r=getLocation();return{urlPath:r==null?void 0:r.pathname,host:(r==null?void 0:r.host)||(r==null?void 0:r.hostname),device:n?"tablet":t.any()?"mobile":"desktop"}},getFunctionArguments=({builder:e,context:t,event:n,state:r})=>Object.entries({state:r,Builder:e,builder:e,context:t,event:n}),getBuilderGlobals=()=>({isEditing:isEditing(),isBrowser:isBrowser(),isServer:!isBrowser(),getUserAttributes:()=>getUserAttributes()}),parseCode=(e,{isExpression:t=!0})=>t&&!(e.includes(";")||e.includes(" return ")||e.trim().startsWith("return "))?`return (${e});`:e;function flattenState({rootState:e,localState:t,rootSetState:n}){return new Proxy(e,{get:(r,o)=>{if(t&&o in t)return t[o];const s=r[o];return typeof s=="object"&&s!==null?flattenState({rootState:s,localState:void 0,rootSetState:n?i=>{r[o]=i,n(r)}:void 0}):s},set:(r,o,s)=>{if(t&&o in t)throw new Error("Writing to local state is not allowed as it is read-only.");return r[o]=s,n==null||n(r),!0}})}const SDK_NAME_FOR_TARGET=(()=>{switch(TARGET){case"rsc":return"react-nextjs";case"reactNative":return"react-native";default:return TARGET}})(),SDK_NAME=`@builder.io/sdk-${SDK_NAME_FOR_TARGET}`,fastClone=e=>JSON.parse(JSON.stringify(e)),set=(e,t,n)=>{if(Object(e)!==e)return e;const r=Array.isArray(t)?t:t.toString().match(/[^.[\]]+/g);return r.slice(0,-1).reduce((o,s,i)=>Object(o[s])===o[s]?o[s]:o[s]=Math.abs(Number(r[i+1]))>>0===+r[i+1]?[]:{},e)[r[r.length-1]]=n,e},noop=()=>{};let safeDynamicRequire=noop;try{safeDynamicRequire=node_module.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&_documentCurrentScript.src||new URL("should-force-browser-runtime-in-node-IsToRTN-.cjs",document.baseURI).href)}catch(error){try{safeDynamicRequire=eval("require")}catch(e){}}const getSyncValName=e=>`bldr_${e}_sync`,BUILDER_SET_STATE_NAME="BUILDER_SET_STATE",INJECTED_IVM_GLOBAL="BUILDER_IVM",REF_TO_PROXY_FN=` var refToProxy = (obj) => { if (typeof obj !== 'object' || obj === null) { return obj; } return new Proxy({}, { get(target, key) { if (key === 'copySync') { return () => obj.copySync(); } const val = obj.getSync(key); if (typeof val?.getSync === 'function') { return refToProxy(val); } return val; }, set(target, key, value) { const v = typeof value === 'object' ? new ${INJECTED_IVM_GLOBAL}.Reference(value) : value; obj.setSync(key, v); ${BUILDER_SET_STATE_NAME}(key, value) }, deleteProperty(target, key) { obj.deleteSync(key); } }) } `,processCode=({code:e,args:t})=>{const n=t.map(([r])=>`var ${r} = refToProxy(${getSyncValName(r)}); `).join("");return` ${REF_TO_PROXY_FN} ${n} function theFunction() { ${e} } const output = theFunction() if (typeof output === 'object' && output !== null) { return JSON.stringify(output.copySync ? output.copySync() : output); } else { return output; } `};let IVM_INSTANCE=null,IVM_OPTIONS={memoryLimit:128};const setIvm=(e,t)=>{IVM_INSTANCE||(IVM_INSTANCE=e,t&&(IVM_OPTIONS=t))},SHOULD_MENTION_INITIALIZE_SCRIPT=SDK_NAME==="@builder.io/sdk-react-nextjs"||SDK_NAME==="@builder.io/sdk-react"||SDK_NAME==="@builder.io/sdk-qwik"||SDK_NAME==="@builder.io/sdk-vue",getIvm=()=>{try{if(IVM_INSTANCE)return IVM_INSTANCE;const t=safeDynamicRequire("isolated-vm");if(t)return t}catch(t){logger.error("isolated-vm import error.",t)}const e=`${MSG_PREFIX}could not import \`isolated-vm\` module for safe script execution on a Node server. SOLUTION: In a server-only execution path within your application, do one of the following: ${SHOULD_MENTION_INITIALIZE_SCRIPT?`- import and call \`initializeNodeRuntime()\` from "${SDK_NAME}/node/init".`:""} - add the following import: \`await import('isolated-vm')\`. For more information, visit https://builder.io/c/docs/integration-tips#enabling-data-bindings-in-node-environments`;throw new Error(e)},runInNode=({code:e,builder:t,context:n,event:r,localState:o,rootSetState:s,rootState:i})=>{const d=getIvm();let l;try{l=new d.Isolate(IVM_OPTIONS);const f=l.createContextSync(),u=f.global;u.setSync("global",u.derefInto()),u.setSync("log",function(...c){console.log(...c)}),u.setSync(INJECTED_IVM_GLOBAL,d);const p=fastClone({...i,...o}),m=getFunctionArguments({builder:t,context:n,event:r,state:p});u.setSync(BUILDER_SET_STATE_NAME,function(c,a){set(i,c,a),s==null||s(i)}),m.forEach(([c,a])=>{const I=typeof a=="object"?new d.Reference(c==="builder"?{...a,getUserAttributes:()=>a.getUserAttributes()}:a):null;u.setSync(getSyncValName(c),I)});const y=processCode({code:e,args:m}),g=f.evalClosureSync(y);try{return JSON.parse(g)}catch{return g}}finally{if(l)try{l.dispose()}catch{}}},checkIsDefined=e=>e!=null;function isNodeRuntime(){var e;return typeof process<"u"&&checkIsDefined((e=process==null?void 0:process.versions)==null?void 0:e.node)}const shouldForceBrowserRuntimeInNode=({shouldLogWarning:e})=>{var o;if(!isNodeRuntime())return!1;const t=process.arch==="arm64",n=process.version.startsWith("v20"),r=(o=process.env.NODE_OPTIONS)==null?void 0:o.includes("--no-node-snapshot");return t&&n&&!r?(e&&logger.log("Skipping usage of `isolated-vm` to avoid crashes in Node v20 on an arm64 machine.\n If you would like to use the `isolated-vm` package on this machine, please provide the `NODE_OPTIONS=--no-node-snapshot` config to your Node process.\n See https://github.com/BuilderIO/builder/blob/main/packages/sdks/README.md#node-v20--m1-macs-apple-silicon-support for more information.\n "),!0):!1};exports.TARGET=TARGET;exports.checkIsDefined=checkIsDefined;exports.fastClone=fastClone;exports.flattenState=flattenState;exports.getBuilderGlobals=getBuilderGlobals;exports.getFunctionArguments=getFunctionArguments;exports.getSearchString=getSearchString;exports.getUserAttributes=getUserAttributes;exports.isBrowser=isBrowser;exports.isEditing=isEditing;exports.logger=logger;exports.normalizeSearchParams=normalizeSearchParams;exports.parseCode=parseCode;exports.runInNode=runInNode;exports.set=set;exports.setIvm=setIvm;exports.shouldForceBrowserRuntimeInNode=shouldForceBrowserRuntimeInNode;