create-modulo
Version:
Starter projects for Modulo.html - Ready for all uses - Markdown-SSG / SSR / API-backed SPA
11 lines (10 loc) • 30.8 kB
JavaScript
import{createRequire as Zz}from"node:module";var a=Object.create;var{getPrototypeOf:t,defineProperty:C,getOwnPropertyNames:e}=Object;var zz=Object.prototype.hasOwnProperty;var S=(z,Z,J)=>{J=z!=null?a(t(z)):{};let Q=Z||!z||!z.__esModule?C(J,"default",{value:z,enumerable:!0}):J;for(let G of e(z))if(!zz.call(Q,G))C(Q,G,{get:()=>z[G],enumerable:!0});return Q};var A=(z,Z)=>{for(var J in Z)C(z,J,{get:Z[J],enumerable:!0,configurable:!0,set:(Q)=>Z[J]=()=>Q})};var b=Zz(import.meta.url);import{readFileSync as Sz,writeFileSync as bz}from"node:fs";var F={};A(F,{parse:()=>Jz,LexHelper:()=>E});function Jz(z,Z,J=null){let{HTMLElement:Q}=z._virtual.window,G=new E(Z,[z],Q);while(G.text){if(G.peekOpen(),G.pushUntil("<"),G.untilRegExp(/\s*/),G.text.length<1)break;let $=G.text.charCodeAt(0);if($>=65&&$<=122){let Y=G.untilRegExp(/[\s>]/).toUpperCase().trim(),K=z.ownerDocument.createElement(Y);if(K._isAutoClosing)G.sliceStack(null,K._autoClosingValue),G.sliceStack(Y);while(G.text.trim()&&G.match!==">"){let W=G.untilRegExp(/[\s =>]/).trim(),X="";if(G.match==="="&&G.text[0]!==">"){if(X=G.untilRegExp(/['"\s>]/),(G.match==='"'||G.match==="'")&&!X.trim())X=G.until(G.match)}if(W)K.setAttribute(W,X)}if(G.topOfStack.append(K),K.tagName==="SCRIPT"||K.tagName==="STYLE"){let W=new RegExp("</"+K.tagName+"s*>","i");K.nodeValue=G.untilRegExp(W)}else if(!K._isSelfClosing)G.stack.push(K)}else if($===47){let Y=G.until(">").toUpperCase().replace(/[^A-Z0-9_:-]/g,""),K=G.sliceStack(Y);if(K&&K._isDocumentStructure)G.mergeStructuralElement(K)}else if($===33&&G.text.substr(0,3)==="!--")G.pushUntil("-->",8,!0)}if(J===null)z._virtual.resumeDOM();else if(J===!1)z._virtual.domQueue=[]}class E{constructor(z,Z=[],J=null){this.text=z,this.stack=Z,this.elemCls=J,this.match="",this.peekOpen()}untilRegExp(z){let Z=this.text.match(z)||{0:"",index:this.text.length};this.match=Z[0];let J=this.text.substr(0,Z.index);return this.text=this.text.substr(Z.index+Z[0].length),J}until(z){let Z=this.text.indexOf(z),J=Z===-1?this.text:this.text.substr(0,Z);return this.text=Z===-1?"":this.text.substr(Z+z.length),J}sliceStack(z,Z=0){let J=this.stack.length;while(J>0){J=J-1;let Q=this.stack[J];if(Z===0?z===Q.tagName:Z<=Q._autoClosingValue)return this.stack.splice(J),this.peekOpen(),Q}return null}peekOpen(){this.topOfStack=this.stack.length<1?null:this.stack[this.stack.length-1]}pushUntil(z,Z=3,J=!1){let Q=new this.elemCls,G=this.until(z);G=J?G.substr(z.length):G,Q._setupNode({nodeType:Z,nodeValue:G}),this.topOfStack.append(Q)}mergeStructuralElement(z){let Z=z.ownerDocument;if(z.tagName!=="HTML")Z=Z[z.tagName==="BODY"?"body":"head"];if(Z&&Z!==z){for(let J of z.getAttributeNames())Z.setAttribute(J,z.getAttribute(J)||"");Z.append(...z.childNodes),z.remove()}}}var T={};A(T,{HTMLElement:()=>M,Event:()=>g,Attr:()=>N});var _={docStructure:{HTML:1,HEAD:1,BODY:1},head:{TITLE:1,LINK:1,META:1,TEMPLATE:1},selfClosing:{AREA:1,BASE:1,BR:1,COL:1,COMMAND:1,EMBED:1,HR:1,IMG:1,INPUT:1,KEYGEN:1,LINK:1,META:1,PARAM:1,SOURCE:1,TRACK:1,WBR:1},autoClosing:{P:8,DT:7,DD:7,LI:6,OPTION:9,THEAD:3,TH:5,TBODY:3,TR:4,TD:5,TFOOT:3,COLGROUP:4},literalValue:{SCRIPT:1,STYLE:1}},Qz={quot:'"',gt:">",lt:"<",apos:"'"},Gz=/^(script|iframe|.+-.+)$/i;class N{constructor(z){if("value"in z)Object.assign(this,z)}cloneNode(){return new N(this)}}class g{constructor(z){this.type=z}}class M{constructor(){this._setupNode({nodeType:3,nodeValue:"",childNodes:[],isConnected:!1,parentNode:null,style:{},_parentIndex:-1,_attributeNames:[],_attributeValues:{},_eventListeners:{}})}_setupNode(z){if(Object.assign(this,z),this.tagName)this.tagName=this.tagName.toUpperCase(),this._isDocumentStructure=this.tagName in _.docStructure,this._isHeadPreferred=this.tagName in _.head,this._isSelfClosing=this.tagName in _.selfClosing,this._isAutoClosing=this.tagName in _.autoClosing,this._isLiteralValue=this.tagName in _.literalValue,this._autoClosingValue=_.autoClosing[this.tagName]||0}_extractContent(){let{nodeValue:z,childNodes:Z}=this;return this.nodeValue=void 0,this.childNodes=[],{nodeValue:z,childNodes:Z}}_decodeEntities(z){return z=z||"",z.replace(/&(quot|gt|lt);/ig,(Z,J)=>Qz[J]).replace(/&#x([a-f0-9]+);/ig,(Z,J)=>String.fromCharCode(parseInt(J,16)))}remove(){if(this.parentNode)this.parentNode.childNodes.splice(this._parentIndex,1),this._parentIndex=-1,this.parentNode._rebuildNodeIndices(),this.parentNode=null}removeChild(z){for(let Z of this.childNodes)if(Z===z){Z.remove();break}}replaceWith(...z){if(this.parentNode)for(let Z of z)this.parentNode.insertBefore(Z,this);this.remove()}append(...z){for(let Z of z){if(Z.remove)Z.remove();this._appendNode(Z)}}_appendNode(z){if(this.tagName==="BODY"&&z._isHeadPreferred)return this.ownerDocument.head._appendNode(z);z.parentNode=this,this.childNodes.push(z),this._rebuildNodeIndices(),this._checkForConnection(z)}_checkForConnection(z){if(z.nodeType===1&&!z.isConnected&&this.isConnected&&this.tagName!=="TEMPLATE"){if(z.isConnected=!0,Gz.test(z.tagName)){if(z._virtual.enqueueDOM(z),z._virtual.window.document.readyState==="complete")z._virtual.resumeDOM()}for(let Z of z.children)z._checkForConnection(Z)}}_insertNode(z,Z){let J=this.childNodes.slice(Z);this.childNodes=this.childNodes.slice(0,Z),this.childNodes.push(z),this.childNodes.push(...J),this._rebuildNodeIndices(),this._checkForConnection(z)}appendChild(...z){this.append(...z)}insertBefore(z,Z){if(Z.parentNode!==this||!("_parentIndex"in Z))throw new Error("Invalid insertBefore");this._insertNode(z,Z._parentIndex)}_rebuildNodeIndices(){let z=0;for(let Z of this.childNodes)Z._parentIndex=z++}isEqualNode(z){return this.outerHTML===z.outerHTML}addEventListener(z,Z){if(!(z in this._eventListeners))this._eventListeners[z]=[];this._eventListeners[z].push(Z)}dispatchEvent(z){for(let Z of this._eventListeners[z.type]||[])Z(z)}removeEventListener(z,Z){if(z in this._eventListeners)this._eventListeners[z]=this._eventListeners[z].filter((J)=>J!==Z)}get firstChild(){return this.childNodes.length>0?this.childNodes[0]:null}get firstElementChild(){return this.children.length>0?this.children[0]:null}get lastChild(){return this.childNodes.length>0?this.childNodes[this.childNodes.length-1]:null}get lastElementChild(){return this.children.length>0?this.children[this.children.length-1]:null}get nextSibling(){if(!this.parentNode||this._parentIndex+1>=this.parentNode.childNodes.length)return null;return this.parentNode.childNodes[this._parentIndex+1]}get previousSibling(){if(!this.parentNode||this._parentIndex<=0)return null;return this.parentNode.childNodes[this._parentIndex-1]}get textContent(){if(this.nodeType===3)return this._decodeEntities(this.nodeValue);else if(this._isLiteralValue)return this.nodeValue;else return this.childNodes.map((z)=>z.textContent).join("")}set textContent(z){if(this.nodeType===1&&!this._isLiteralValue)this.childNodes=[new M],this.childNodes[0]._setupNode({nodeType:3,nodeValue:z});else if(this.nodeValue=z,this.tagName==="SCRIPT"&&z)this._virtual.enqueueDOM(this),this._virtual.resumeDOM()}get children(){return this.childNodes.filter(({nodeType:z})=>z===1)}get attributes(){let z=(Z)=>new N({name:Z,value:this.getAttribute(Z)});return this._attributeNames.map(z)}getAttributeNames(){return this._attributeNames}getAttribute(z){return this._attributeValues[z.toLowerCase()]}setAttribute(z,Z){if(Z=Z||"",z==="/")return;else if(z==="style"){this.style={};for(let J of(Z||"").split(";")){let[Q,G]=J.trim().split(/\s*:\s*/);this.style[Q]=G}Z=this._getStyleAttr()}this._updateAttribute(z,Z)}_updateAttribute(z,Z){if(!this.hasAttribute(z))this._attributeNames.push(z);let J=z.toLowerCase();if(Z=""+Z,this._attributeValues[J]=Z,this.tagName==="IFRAME"&&J in{src:1,srcdoc:1})this.contentWindow=this._virtual.newChild(),this._virtual.enqueueDOM(this);else if(this.tagName==="SCRIPT"&&J==="src")this._virtual.enqueueDOM(this)}hasAttribute(z){return z.toLowerCase()in this._attributeValues}_getStyleAttr(){let z=(J)=>J.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),Z=(J)=>z(J.trim())+": "+this.style[J];return Object.keys(this.style).map(Z).join("; ")}_makeAttributeString(){if(!("style"in this._attributeValues)&&Object.keys(this.style).length>0)this._updateAttribute("style",this._getStyleAttr());let z="";function Z(J){if(/^[a-z0-9_\.]+$/.test(J))return J;else if(!J.includes('"'))return`"${J}"`;return J=J.replace(/'/g,"'"),`'${J}'`}for(let J of this._attributeNames){let Q=this._attributeValues[J.toLowerCase()];z+=" "+J+(Q?"="+Z(Q):"")}return z}setAttributeNode(z){this.setAttribute(z.name,z.value)}getAttributeNode(z){return new N({name:z,value:this._attributeValues[z.toLowerCase()]})}attachShadow(z){this.shadowRoot=this.ownerDocument.createElement("shadow:root")}hasChildNodes(){return this.childNodes.length>0}set innerHTML(z){if(this._isLiteralValue)this.textContent=z;else this.childNodes=[],this._virtual.parse(this,z)}get nodeName(){return this.tagName}get src(){return this.getAttribute("src")}get href(){return this.getAttribute("href")}get id(){return this.getAttribute("id")}get type(){return this.getAttribute("type")}set src(z){return this.setAttribute("src",z)}set href(z){return this.setAttribute("href",z)}set id(z){return this.setAttribute("id",z)}set type(z){return this.setAttribute("type",z)}get _moduloTagName(){if(this.isModulo&&this.cparts&&this.cparts.component&&this.cparts.component.conf){let{namespace:z,name:Z}=this.cparts.component.conf;return`${z}-${Z}`}return(this.tagName||"").toLowerCase()}get innerHTML(){if(this.tagName==="SCRIPT"||this.nodeType===8)return this.nodeValue;let z="";for(let Z of this.childNodes)if(Z.nodeType===3)z+=Z.textContent;else if(Z.nodeType===1)z+=Z.outerHTML;else if(Z.nodeType===8)z+="<!--"+(Z.nodeValue||" ")+"-->";return z}get outerHTML(){let z=(this.tagName||"").toLowerCase();if(!z)return"";let Z=" />";if(this._isLiteralValue)Z=">"+this.nodeValue+"</"+z+">";else if(!this._isSelfClosing)Z=">"+this.innerHTML+"</"+z+">";return"<"+z+this._makeAttributeString()+Z}querySelector(z){let Z=this.querySelectorAll(z);if(Z.length)return Z[0];else return null}closest(z){let Z=this.parentNode;while(Z){if(Z._selectorMatches(z))return Z;Z=Z.parentNode}return null}contains(z){let Z=this.childNodes;while(Z.length){let J=Z.shift();if(J===z)return!0;else if(J.childNodes&&J.childNodes.length)Z.push(...J.childNodes)}return!1}_selectorMatches(z){let Z=(z||"").trim().split(",");for(let J of Z){let Q=J.trim();if(Q==="*")return!0;if(Q.toLowerCase()===this.tagName.toLowerCase())return!0;if(Q.includes("#")){let G=Q.split("#");if(this.getAttribute("id")===G[1])return!0}if(Q.includes(".")){let G=Q.split(".");if(G[0]){if(G[0].toLowerCase()!==this.tagName.toLowerCase())continue}if(this.getAttribute("class").split(" ").includes(G[1]))return!0}if(Q.includes("[")){let G=Q.split("[");if(G[0]){if(G[0].toLowerCase()!==this.tagName.toLowerCase())continue}if(G[1]){let[$,Y]=G[1].split("=");if($.endsWith("$")){Y=Y.replace(/['"]/g,"");let K=this.getAttribute($.replace(/\$$/,""));if(K!==null&&K.endsWith(Y))return!0}else{let K=this.getAttribute($);if(!Y&&K!==null||Y===K)return!0}}}}return!1}querySelectorAll(z,Z=!1){let J=[];for(let Q of this.children){if(Q._selectorMatches(z))J.push(Q);J.push(...Q.querySelectorAll(z))}return J}toString(){return"[object HTMLElement]"}}var R={};A(R,{encodeURIComponent:()=>p,encodeURI:()=>Yz,decodeURIComponent:()=>P,URLSearchParams:()=>u,URL:()=>V,Response:()=>c,Headers:()=>d});class V{constructor(z,Z){let J=String(z).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(?:\/\/(?:([^:@\/?#]*)(?::([^:@\/?#]*))?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);if(!J)throw new RangeError;let Q=J[1]||"",G=J[2]||"",$=J[3]||"",Y=J[4]||"",K=J[5]||"",W=J[6]||"",X=J[7]||"",O=J[8]||"",H=J[9]||"";if(Z!==void 0){let q=new this.constructor(Z),D=Q===""&&Y===""&&G==="";if(D&&X===""&&O==="")O=q.search;if(D&&X.charAt(0)!=="/")X=X!==""?((q.host!==""||q.username!=="")&&q.pathname===""?"/":"")+q.pathname.slice(0,q.pathname.lastIndexOf("/")+1)+X:q.pathname;let j=[];if(X.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(B){if(B==="/..")j.pop();else j.push(B)}),X=j.join("").replace(/^\//,X.charAt(0)==="/"?"/":""),D)W=q.port,K=q.hostname,Y=q.host,$=q.password,G=q.username;if(Q==="")Q=q.protocol}this.origin=Q+(Q!==""||Y!==""?"//":"")+Y,this.href=Q+(Q!==""||Y!==""?"//":"")+(G!==""?G+($!==""?":"+$:"")+"@":"")+Y+X+O+H,this.protocol=Q,this.username=G,this.password=$,this.host=Y,this.hostname=K,this.port=W,this.pathname=X,this.search=O,this.hash=H}toString(){return this.href}}class u{constructor(z){if(z&&z.startsWith("?"))z=z.substring(1);let Z=(J)=>P(J);this.data=z.split("&").map((J)=>J.split("=").map(Z))}get(z){return(this.getAll(z)||[null])[0]}getAll(z){return this.data.filter(([Z,J])=>Z===z).map((Z)=>Z[1])}}class c{constructor(z,Z=null){this._url=Z,this._data=z}json(){return new Promise((z,Z)=>{try{z(JSON.parse((this._data||"").toString()))}catch(J){Z(J)}})}text(){return new Promise((z,Z)=>{z((this._data||"").toString())})}bytes(){return new Promise((z,Z)=>z(this._data))}}class d{}var p=(z)=>{let Z=new RegExp("([^A-Za-z0-9\\-_\\.!~\\*'\\(\\)])","g");return z.replace(Z,(J,Q,G)=>"%"+z.charCodeAt(G))},P=(z)=>{return z.replace(/%([a-f0-9][a-f0-9])/ig,(Z,J)=>String.fromCharCode(J))},Yz=p;var x={};A(x,{utils:()=>I,internal:()=>Fz,cli:()=>k});var I={};A(I,{template:()=>Az,saveNamedCache:()=>Vz,runScript:()=>Uz,runFrame:()=>Mz,rewriteModuleScript:()=>y,resolvePath:()=>m,renderText:()=>_z,htmShlex:()=>Iz,hash:()=>f,getCachePath:()=>Nz,formatConsole:()=>Hz,defaultConsole:()=>Bz,Bundler:()=>s});var i=new RegExp("/","g"),$z=/import\s*(\w+|\{[^\*\}]+\}|\*\s*as\s*\S+)\s*from *("[^"]+"|'[^']+');?/ig,Kz=/\n\s*export\s+(const|let|var)\s+(\w+)/gm,qz=/\n\s*export\s+(async\s+function\*?|function\*?|class)\s+(\w+)/gm,Xz=/(?:^|\n)\s*export\s+(?:default)?([^]+)$/gm,Wz=/export\s+(\w+|\{[^\*\}]+\})\s*from/g;var fz="_OLUDOM_SYM"+Math.random();function Dz(z,Z){let J=(G,$,Y)=>{return Z.push(Y),`
`+$+" "+Y},Q=(G,$)=>{return Z.push($),`
import `+$};return z.replace(Kz,J).replace(qz,J).replace(Wz,Q)}function y(z,Z,J=[],Q=null){let G=Q||"window.navigator.extensions.internal.modules",$=[],Y=Dz(Z,$);if($.length)Y+=`export default {${$.join(", ")}}`;else if(/=\s*require\(['"].+["']\)/.test(Y));Y=Y.replace(Xz,`
return $1;`);let K=(W,X,O)=>{let H=O.replace(/(^'|^"|'$|"$)/g,""),q=m(z,"..",H),D=JSON.stringify(q);J.push(q);let j=X.replace(/^\*\s*as\s*/,""),B=`(typeof ${G}[${D}] === "function" ? (${G}[${D}] = ${G}[${D}]()) : ${G}[${D}])
`;return`;const ${j} = `+B};return Y=Y.replace($z,K),`${G}[${JSON.stringify(z)}]=function (){${Y}}`}function m(...z){let Z=[];for(let J of z){if(J.startsWith("/")){Z=J.split(i);continue}for(let Q of J.split(i))if(Q.startsWith(".")){if(Q==="..")Z.pop()}else if(Q)Z.push(Q)}return Z.join("/")}function Hz(z){let Z=[],J=!1;for(let Q of z){if(J){J=!1;continue}else if(typeof Q==="object")try{if("outerHTML"in Q)Q=Q.outerHTML;else Q=JSON.stringify(Q,null,2)}catch(G){}else if(Q&&Q.startsWith&&Q.startsWith("%c"))Q=Q.substr(2),J=!0;Z.push(Q)}return Z}var Oz={log:"| ",group:"|----+",groupEnd:"|----+---",error:"|!ERR|",info:"|(i) |",warn:"|WARN|"},jz=0;function Bz(z,Z){let J=z==="count"?`|${++jz}|`:Oz[z];console.log(J,...Z)}function f(z){let Z=0;for(let Q=0;Q<z.length;Q++)Z=Math.imul(31,Z)+z.charCodeAt(Q)|0;return("---------"+(Z||0).toString(32)).slice(-8).replace(/-/g,"0")}async function r(z){if(z.__run)return;z.__run=!0;let Z={javascript:1,"application/javascript":1,module:1},J=z.getAttribute("type");if(J&&!(J in Z))return;if(z.closest("template"))return;let Q=z.nodeValue,G=z.hasAttribute("src")?z.getAttribute("src"):"";if(G)Q=await(await z._virtual.window.fetch(G)).text();if(J!=="module"){z._virtual.window.Function(Q)();return}let{internal:$}=z._virtual.window.navigator.extensions;Q=y(G,Q,$.moduleQueue),z._virtual.window.Function(Q)();while($.moduleQueue.length>0){let K=$.moduleQueue.shift().replace(/(^'|^"|'$|"$)/g,"");if(!(K in $.modules)){let W=z._virtual.document.createElement("script");W.setAttribute("type","module"),W.setAttribute("src",K),await r(W)}}if(z.isConnected){let Y=z._virtual.document.createElement("script"),K="window.navigator.extensions.internal.modules";Y.nodeValue=`window.navigator.extensions.internal.modules[${JSON.stringify(G)}]();`,z._virtual.enqueueDOM(Y)}}function Iz(z,Z){let J=z._virtual.window,Q=z.firstElementChild,G=/^<([a-z0-9\._:-]+)/i,$=/^[^<#\u001b]/,Y=RegExp("(</"+(Q?Q.tagName:"")+"|/) *>\\s*$","i"),K={};if($.test(Z))Z="<"+Z+" />";if(Q||G.test(Z)){if(z._shellBuffer=(z._shellBuffer||"")+Z,z.innerHTML=z._shellBuffer,z._shellBuffer.endsWith("/>"))Q=z.firstElementChild,K.Sync=!0,K.stdin="-"}if(Q&&Y.test(Z)){K.Params=`?argv=${Q.tagName.toLowerCase()}`;for(let W of Q.getAttributeNames()){let X=Q.getAttribute(W);if(!X||/^(a|argv)[0-9]+/i.test(W))X=X?X:W,W="argv";else K[W]=X;K.Params+=`&${W}=${J.encodeURIComponent(X)}`}K.Params+="stdin"in K?"":"&stdin=PROC",K.Content=(K.content||"")+(Q.innerHTML||""),K.File=(K.href||J.location.href)+K.Params,z.innerHTML="",z._shellBuffer=""}return K}function _z(z,Z=null){let J=z._virtual.window;Z=Z||{wordWrap:80,tagsToSkip:{SCRIPT:1,TEMPLATE:1,TITLE:1},preTags:{PRE:1,CODE:1,TT:1}};let Q=new RegExp(`(?![^\\n]{1,${Z.wordWrap}}$)([^\\n]{1,${Z.wordWrap}})\\s`,"g"),G=(Y)=>Y.replace(Q,`$1
`),$=(Y)=>Y.replace(/[\n\s]+/g," ").trim();for(let Y of z.childNodes){if(Y.tagName&&Y.tagName in Z.tagsToSkip)continue;let K=Y.textContent||"";if(!(Y.tagName in Z.preTags))K=G($(K)).trim();if(K)J.console.log(K)}}async function Vz(z,Z,J){let Q={};Q["local-cache-name-hint"]=J,await z.fetch(Z,{method:"OPTIONS",headers:Q})}function Az(z,Z,J=/\{\{(.*?)\}\}/g){return z.replace(J,(Q,G)=>Z[G.trim().toLowerCase()])}function Nz(z,Z){let J=new z.URL(Z,z.location.toString()),Q=f(J.toString()),G=J.pathname.split("/").pop()||Q;return`./_cache/remotes/${J.protocol}${J.host}/${Q}/${G}`}class s{constructor(z,Z){this.files={},this.copyFiles={},this.queue=[],this.prefix=[Z.jsPrefix||`var ${Z.globalVar}={};`],this.suffix=[Z.jsSuffix||""],Object.assign(this,{loaders:z,config:Z})}rewriteModule(z,Z){return y(z,Z,this.queue,this.config.globalVar)}async add(z,Z=!1){let J=(z.split(/[:\.]/g).pop()||"").toLowerCase(),Q=({types:Y,match:K})=>K?K(z):(J in Y),G=z.replace(/\.([a-z0-9]+):[a-z0-9]+$/i,".$1");if(G in this.files)return;if(Z&&G===z)this.suffix.push(`${this.config.globalVar}["${G}"]();`);let $=this.loaders.find(Q);if(this.files[G]=await $.load(G,this),$.copy)this.copyFiles[G]=$.copy}async addQueue(z){while(this.queue.length>0){let J=this.queue.shift().replace(/(^'|^"|'$|"$)/g,"");await this.add(J)}}generate(z,Z="js"){this.prefix.sort(),this.suffix.sort();let J=Object.keys(this.files);J.sort();let Q=this.prefix.concat(J.map(($)=>this.files[$]));Q.push(...this.suffix);let G=Q.join(`
`);return this.filename=`${z}.${f(G)}.${Z}`,G}}async function Mz(z,Z=!1){let J=z.src||"about:blank";if(!z.hasAttribute("srcdoc")&&J==="about:blank")return;if(z.__run&&(Q||z.src)===z.__run&&!Z)return;if(z.closest("template"))return;let Q=null;if(z.hasAttribute("srcdoc"))Q=z.getAttribute("srcdoc"),z.__run=Q;else z.__run=J,Q=await(await z._virtual.window.fetch(J)).text();z.contentWindow._readyFrame(),z.contentWindow.window.parent=z._virtual.window,z.contentWindow.window.location=new z.contentWindow.window.URL(J),z.contentWindow.document._loadPage(Q)}var Uz=r;class v{constructor(z){this.name=z,this.data={fdata:{},log:[]},this.subscribers=[]}getItem(z){return z in this.data.fdata?this.data.fdata[z]:null}removeItem(z,Z){this.setItem(z,null)}propagate(z,Z,J=null,Q=null){for(let G of this.subscribers){if(G===J)continue;if(Q&&"fileCallback"in G)G.fileCallback(Q,Z);else if("stateChangedCallback"in G)G.stateChangedCallback(z,Z,J);else throw new Error("Invalid subscriber: ",G)}}setItem(z,Z){this.data.fdata[z]=Z,this.propagate("fdata",this.data.fdata,this,z),this.data.log.push([z,new Date().getTime()/1000]),this.propagate("log",this.data.log,this)}}var Fz={cache:new v("CACHE"),modules:{},moduleQueue:[]},k={FileStore:v};function Tz(z=null){let Z=Object.assign({Document:L},F,T,R),J=Object.assign({_queue:[]},Z);J.window=J,J.customElements=Pz(J),J.Function=Rz(J),J.eval=(Y)=>new Function("return "+Y)(),J.history={pushState:()=>{}},J.setTimeout=(Y)=>J._queue.push(Y),J.__yield=()=>{let Y=0;while(J._queue.length)J._queue.shift()(),Y++;return Y},J.navigator={extensions:Object.assign({modules:{}},x),userAgent:"oludom"};let{defaultConsole:Q,formatConsole:G}=I;z=z||Q;let $=(Y,K)=>z(Y,G(K),K);return J.console=Object.assign({log:(...Y)=>$("log",Y),group:(...Y)=>$("group",Y),groupEnd:(...Y)=>$("groupEnd",Y),error:(...Y)=>$("error",Y),info:(...Y)=>$("info",Y),warn:(...Y)=>$("warn",Y),count:(...Y)=>$("count",Y)}),J.sessionStorage=new k.FileStore("sessionStorage"),J.localStorage=new k.FileStore("localStorage"),J.document=new L,J.document._setupParentWindowFrame(null),J.frames=[],J.addEventListener=(...Y)=>J.document.addEventListener(...Y),J.dispatchEvent=(...Y)=>J.document.dispatchEvent(...Y),J}function Pz(z){return{unknown:{},_upgrade:(Z)=>{Z=Z.toUpperCase();for(let J of z.customElements.unknown[Z]||[]){let Q="deref"in J?J.deref():J;if(Q&&Q.tagName&&Q.tagName===Z){let G=Q.ownerDocument.createElement(Q.tagName);G._attributeNames=Q._attributeNames,G._attributeValues=Q._attributeValues,G.append(...Q.childNodes),Q.replaceWith(G),G.connectedCallback()}}delete z.customElements.unknown[Z]},elemClasses:{},define:(Z,J)=>{Z=Z.toUpperCase(),z.customElements.elemClasses[Z]=J,z.customElements._upgrade(Z)}}}function Rz(z){return function Z(...J){let Q=J.pop(),$=Object.keys(z).filter((K)=>Q.includes(K)).filter((K)=>!J.includes(K)),Y=Function(...$.concat(J),Q);return(...K)=>Y(...$.map((W)=>z[W]),...K)}}class L extends M{_setupParentWindowFrame(z){this._setupNode({nodeType:1,tagName:"HTML"}),this._virtual=z,this.isConnected=!0}toString(){return(this._doctype?this._doctype+`
`:"")+this.outerHTML}_loadPage(z){if(this.head=this.createElement("head"),this.body=this.createElement("body"),this.append(this.head,this.body),this._setupOwnerDocument(this),z!==null){if(/^\s*<[!\?][^-]/.test(z))this._doctype=z.split(">")[0]+">",z=z.substr(this._doctype.length);this.addEventListener("DOMContentLoaded",()=>{this.readyState="complete"}),this.write(z)}}_setupOwnerDocument(z,Z){z.documentElement=this,z.ownerDocument=this,z._virtual=this._virtual}write(z){if(this.readyState==="complete")throw new Error("Attempt to write to closed document.");this._virtual.parse(this.body,z,!0)}getElementById(z){return this.querySelector("#"+z)}createElement(z){let Z=this._virtual.window,J=Z.customElements.elemClasses,Q=z.toUpperCase(),$=new(Q in J?J[Q]:Z.HTMLElement);return this._setupOwnerDocument($),$._setupNode({nodeType:1,tagName:z}),$}createElementNS(z,Z){return this.createElement(name)}createTextNode(z){let Z=new HTMLElement;return Z.nodeValue=z,Z}}class U{constructor(z){this.interceptor=z.interceptor,this.options=z,this.logger=this.options.logger,this.prompter=this.options.prompter,this.cliSettings=this.options.cliSettings,this.vwindow=Object.assign({Document:L},F,T,R),this.domQueue=[],this._readyFrame()}newChild(){let z=new U(this.options);return z.window.parent=this.window,z.window.location=new z.window.URL("about:blank"),this.window.frames.push(z),this.window.setTimeout(this.resumeDOM.bind(this),0),z}_readyFrame(){this.parse=this.vwindow.parse;let z=Tz(this.options.consoleFunction);this.window=z,this.document=z.document,z.fetch=this.fetch.bind(this),z.prompt=this.prompter,z.confirm=this.confirmer,z.__isPromptInteractive=this.options.isInteractive,z.document._setupParentWindowFrame(this)}fetch(...z){let Z=z[0]||"",J=z[1]||{method:"GET",headers:{}};return new Promise((Q,G)=>{this.fetchInterceptedSync(Q,G,J.method,Z,J.headers)})}fetchInterceptedSync(z,Z,J,Q,G){let $={request:{method:J,url:Q,headers:G},window:this.window},Y=this.interceptor.beforeSyncRequest($);if(!Y||!("body"in Y)||Y.body===null)Z(new Error(`File access error: ${Q} not found (local 404)`));else z(new this.window.Response(Y.body))}fetchSync(z){let Z={request:{method:"GET",url:z},window:this.window},J=this.interceptor.beforeSyncRequest(Z);if(!J)return null;return J.body}navigate(z){return this._readyFrame(),this.window.location=new this.window.URL(z),this.fetch(z).then((Z)=>Z.text()).then((Z)=>this.document._loadPage(Z))}tryDispatch(z){let Z=null,J=new this.window.Event(z);try{this.window.__yield(),this.window.document.dispatchEvent(J),this.window.__yield()}catch(Q){Z=Q}return Z}enqueueDOM(z){let{elemClasses:Z,unknown:J}=this.window.customElements;if(z.tagName==="IFRAME")this.domQueue.push(z);else if(z.tagName==="SCRIPT"||z.tagName in Z)this.domQueue.push(z);else J[z.tagName]=J[z.tagName]||[],J[z.tagName].push(new WeakRef(z))}async resumeDOM(){let{elemClasses:z,unknown:Z}=this.window.customElements,J=[];while(this.domQueue.length>0){let Q=this.domQueue.shift();if(Q.tagName==="SCRIPT")await I.runScript(Q);else if(Q.tagName==="IFRAME")await I.runFrame(Q);else{let G=Q._extractContent();J.push([Q,G])}}for(let[Q,G]of J){if("connectedCallback"in Q)Q.connectedCallback();else if(!(Q.tagName in z))Z[Q.tagName]=Z[Q.tagName]||[],Z[Q.tagName].push(new WeakRef(Q));Object.assign(Q,G)}for(let Q of this.window.frames)await Q.resumeDOM()}async domContentYield(){let z=[];try{await this.resumeDOM(),this.window.__yield()}catch(Q){z.push(Q)}let Z=new this.window.Event("DOMContentLoaded"),J=this.window.document._eventListeners[Z.type];for(let Q of J||[()=>{}])try{await this.resumeDOM(),this.window.__yield(),await Q(Z),await this.resumeDOM(),this.window.__yield()}catch(G){z.push(G)}return z.length?z:null}}var kz='[JavaScript Warning: "';function Lz(z){let{files:Z,urlPrefix:J}=z,Q=new V(J).pathname;function G(X,O=""){let H=new V(O,J)+"",q=new V(X,H).pathname;return q.startsWith(Q)?q.replace(Q,""):q}function $(X,O){console.log("|OLUDOM| ER404 |",O),console.log("|------+-------+ (Hint:)"),console.log(...X.argv,O),console.log("|------+-------+")}async function Y(X,O){let H=async(D)=>await D.jsonValue(),q=[];try{q=await Promise.all(O.args().map(H))}catch(D){X.error("BROWSER Error occured during log attempt:",D)}if(q=q.filter((D)=>D.startsWith&&!D.startsWith(kz)),q.length)X.log(...q)}async function K(X,O){let H=G(X.request().url(),O);if(H in Z)await X.fulfill({path:H});else if(H){$(z,H);let q="404 (OluDOM)";await X.fulfill({status:404,contentType:"text/plain",body:q})}}function W(X){let O=X.window.location+"",H=G(X.request.url,O);if(H in Z)return{body:Z[H]};else if(H)return $(z,H),{body:null}}return{beforeSyncRequest:W,handleRoute:K,handleConsole:Y}}class l{constructor(z=null){this.writeCallback=z}async fromAnchor(z=null){this.name=await z.getAttribute("download");let Z=await z.getAttribute("href");this.data=P(Z)}suggestedFilename(){return this.name}async saveAs(z){return this.writeCallback(z,this.data)}}class w{constructor(z){this.urlPrefix=z.urlPrefix,this.delay=z.delay,this.interceptor=z.interceptor||Lz(z),z.interceptor=this.interceptor,this.mainFrame=new U(z),this.frames=[this.mainFrame]}async saveAnchorAs(z,Z){if(this.driver&&this.driver.waitForEvent){let J=this.driver.waitForEvent("download");return await z.click(),await J}else{let J=new l(Z);return await J.fromAnchor(z),J}}async setupPageDriver(z){this.driver=z;let{handleRoute:Z,handleConsole:J}=this.interceptor;if(z.on){let{console:Q}=this.mainFrame.window;z.on("console",async(G)=>await J(Q,G))}if(z.route)await z.route("**/*",(Q)=>Z(Q,this.url))}async goto(z){if(this.url=this.urlPrefix+z,this.driver)delete this.mainFrame,await this.driver.goto(this.url);else await this.mainFrame.navigate(this.url),this.exceptionList=await this.mainFrame.domContentYield()}locator(z){if(this.driver)return this.driver.locator(z);else return{all:async()=>this.mainFrame.window.document.querySelectorAll(z)}}async waitUntilComplete(){if(this.driver&&this.driver.waitUntilComplete)await this.driver.waitUntilComplete();else if(this.driver&&this.driver.waitForLoadState)await this.driver.waitForLoadState("networkidle");else if(this.mainFrame)await this.mainFrame.resumeDOM(),this.mainFrame.window.__yield();if(this.delay&&this.driver.waitForTimeout)await this.driver.waitForTimeout(this.delay)}}class h{constructor(z){this.configureDefaults(z),this.options=z,this.pages=[],this.driver=null}async readyDriver(){if(!this.options.driver)return null;this.driver=await this.options.driver.launch(this.options)}configureDefaults(z){z.server=Object.assign({proto:"http",host:"local.oludom",port:80,path:""},z.server);let Z=z.server,J=`${Z.proto}://`;if(!(Z.proto in{file:1,about:1})){let Q=`:${Z.port}`;J+=Z.host+(Q===":80"?"":Q)}z.urlPrefix=J+(Z.path||"")+"/"}async newPage(){await this.readyDriver();let z=new w(this.options);if(this.driver){let Z=await this.driver.newPage();await z.setupPageDriver(Z)}return this.pages.push(z),z}async close(){if(this.driver&&this.driver.close)await this.driver.close();else for(let z of this.pages)await z.waitUntilComplete()}}async function n(z,Z,J){let Q={},G={},$=null,Y=[],K=0,W={argv:z,download:"a[download]",delay:3000};for(let q of z){if(q.endsWith("node")&&q===z[0]||q.endsWith("-oludom.mjs")&&q===z[1])continue;if(q.startsWith("--")){await Cz(q.slice(2,q.length),W);continue}if(q.includes("?"))Y.push(q),q=q.replace(/\?.*$/,"");else if(q.startsWith("_")){$=$||q,G[q]=!0;continue}else if(W.skipRead)Q[q]=1;try{Q[q]=Z(q,"utf8")}catch(D){console.error("Oludom Cannot Read ERROR:",q),console.error(D),console.log("To run again, allowing access:"),console.log(`---
`),console.log(...z,q)}}W.files=Q;let X=new h(W);if(!Y.length)console.log('ERROR, no file to execute: At least one argument must have a "?"'),console.log("Example 1: oludom file.html?"),console.log("Example 2: oludom index.html? _build _cache *.* **/*.*"),console.log(`---
`),console.log(...z,"index.html?");else{for(let q of Y)await H(q);await X.close()}function O(q,D){for(let[j,B]of Object.entries(D))j=j.replace("..","./."),J(q+j,B)}async function H(q){let D=await X.newPage();if(await D.goto(q),await D.waitUntilComplete(),D.exceptionList&&D.exceptionList.length>0){for(let j of D.exceptionList.slice(1))console.error(j);throw D.exceptionList[0]}for(let j of await D.locator(W.download).all()){let B=await D.saveAnchorAs(j,J),o=B.suggestedFilename().replace(/\.+/g,".");await B.saveAs($+"/"+o)}}}async function Cz(z,Z){let[J,Q]=z.split("=");if(J==="happydom"){let{Browser:G}=await import("happy-dom"),$=(Y)=>new G(Y);Z.driverName=J,Z.driver={launch:$}}else if(J==="oludom");else if(J in{firefox:1,chromium:1}){if(Z.driverName=J,Z.headless=Q!=="gui",Z.skipRead=!0,J==="firefox"){let{firefox:G}=await import("playwright");Z.driver=G}else if(J==="chromium"){let{chromium:G}=await import("playwright");Z.driver=G}}else if(J in{proto:1,host:1,port:1,path:1})Z.server=Z.server||{},Z.server[J]=Q;else throw new Error("Unknown flag: --"+J)}await n(process.argv,Sz,bz);