UNPKG

hacksoft-interpreter

Version:

A library for interpreting .hks files

17 lines (16 loc) 15.8 kB
(function(U,I){typeof exports=="object"&&typeof module<"u"?I(exports):typeof define=="function"&&define.amd?define(["exports"],I):(U=typeof globalThis<"u"?globalThis:U||self,I(U.HackSoftInterpreter={}))})(this,function(U){"use strict";var I=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Y(l){return l&&l.__esModule&&Object.prototype.hasOwnProperty.call(l,"default")?l.default:l}var H={exports:{}},F={},M,G;function x(){return G||(G=1,M=function(a){return a&&typeof a=="object"&&typeof a.copy=="function"&&typeof a.fill=="function"&&typeof a.readUInt8=="function"}),M}var L={exports:{}},V;function ee(){return V||(V=1,typeof Object.create=="function"?L.exports=function(a,u){a.super_=u,a.prototype=Object.create(u.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}})}:L.exports=function(a,u){a.super_=u;var d=function(){};d.prototype=u.prototype,a.prototype=new d,a.prototype.constructor=a}),L.exports}var K;function re(){return K||(K=1,function(l){var a=/%[sdj%]/g;l.format=function(e){if(!b(e)){for(var n=[],o=0;o<arguments.length;o++)n.push(f(arguments[o]));return n.join(" ")}for(var o=1,v=arguments,z=v.length,w=String(e).replace(a,function(S){if(S==="%%")return"%";if(o>=z)return S;switch(S){case"%s":return String(v[o++]);case"%d":return Number(v[o++]);case"%j":try{return JSON.stringify(v[o++])}catch{return"[Circular]"}default:return S}}),h=v[o];o<z;h=v[++o])s(h)||!k(h)?w+=" "+h:w+=" "+f(h);return w},l.deprecate=function(e,n){if(A(I.process))return function(){return l.deprecate(e,n).apply(this,arguments)};if(process.noDeprecation===!0)return e;var o=!1;function v(){if(!o){if(process.throwDeprecation)throw new Error(n);process.traceDeprecation?console.trace(n):console.error(n),o=!0}return e.apply(this,arguments)}return v};var u={},d;l.debuglog=function(e){if(A(d)&&(d=process.env.NODE_DEBUG||""),e=e.toUpperCase(),!u[e])if(new RegExp("\\b"+e+"\\b","i").test(d)){var n=process.pid;u[e]=function(){var o=l.format.apply(l,arguments);console.error("%s %d: %s",e,n,o)}}else u[e]=function(){};return u[e]};function f(e,n){var o={seen:[],stylize:p};return arguments.length>=3&&(o.depth=arguments[2]),arguments.length>=4&&(o.colors=arguments[3]),i(n)?o.showHidden=n:n&&l._extend(o,n),A(o.showHidden)&&(o.showHidden=!1),A(o.depth)&&(o.depth=2),A(o.colors)&&(o.colors=!1),A(o.customInspect)&&(o.customInspect=!0),o.colors&&(o.stylize=E),m(o,e,o.depth)}l.inspect=f,f.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},f.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function E(e,n){var o=f.styles[n];return o?"\x1B["+f.colors[o][0]+"m"+e+"\x1B["+f.colors[o][1]+"m":e}function p(e,n){return e}function j(e){var n={};return e.forEach(function(o,v){n[o]=!0}),n}function m(e,n,o){if(e.customInspect&&n&&_(n.inspect)&&n.inspect!==l.inspect&&!(n.constructor&&n.constructor.prototype===n)){var v=n.inspect(o,e);return b(v)||(v=m(e,v,o)),v}var z=T(e,n);if(z)return z;var w=Object.keys(n),h=j(w);if(e.showHidden&&(w=Object.getOwnPropertyNames(n)),R(n)&&(w.indexOf("message")>=0||w.indexOf("description")>=0))return N(n);if(w.length===0){if(_(n)){var S=n.name?": "+n.name:"";return e.stylize("[Function"+S+"]","special")}if(O(n))return e.stylize(RegExp.prototype.toString.call(n),"regexp");if(q(n))return e.stylize(Date.prototype.toString.call(n),"date");if(R(n))return N(n)}var P="",D=!1,B=["{","}"];if(t(n)&&(D=!0,B=["[","]"]),_(n)){var ue=n.name?": "+n.name:"";P=" [Function"+ue+"]"}if(O(n)&&(P=" "+RegExp.prototype.toString.call(n)),q(n)&&(P=" "+Date.prototype.toUTCString.call(n)),R(n)&&(P=" "+N(n)),w.length===0&&(!D||n.length==0))return B[0]+P+B[1];if(o<0)return O(n)?e.stylize(RegExp.prototype.toString.call(n),"regexp"):e.stylize("[Object]","special");e.seen.push(n);var Z;return D?Z=c(e,n,o,h,w):Z=w.map(function(fe){return $(e,n,o,h,fe,D)}),e.seen.pop(),r(Z,P,B)}function T(e,n){if(A(n))return e.stylize("undefined","undefined");if(b(n)){var o="'"+JSON.stringify(n).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(o,"string")}if(y(n))return e.stylize(""+n,"number");if(i(n))return e.stylize(""+n,"boolean");if(s(n))return e.stylize("null","null")}function N(e){return"["+Error.prototype.toString.call(e)+"]"}function c(e,n,o,v,z){for(var w=[],h=0,S=n.length;h<S;++h)X(n,String(h))?w.push($(e,n,o,v,String(h),!0)):w.push("");return z.forEach(function(P){P.match(/^\d+$/)||w.push($(e,n,o,v,P,!0))}),w}function $(e,n,o,v,z,w){var h,S,P;if(P=Object.getOwnPropertyDescriptor(n,z)||{value:n[z]},P.get?P.set?S=e.stylize("[Getter/Setter]","special"):S=e.stylize("[Getter]","special"):P.set&&(S=e.stylize("[Setter]","special")),X(v,z)||(h="["+z+"]"),S||(e.seen.indexOf(P.value)<0?(s(o)?S=m(e,P.value,null):S=m(e,P.value,o-1),S.indexOf(` `)>-1&&(w?S=S.split(` `).map(function(D){return" "+D}).join(` `).substr(2):S=` `+S.split(` `).map(function(D){return" "+D}).join(` `))):S=e.stylize("[Circular]","special")),A(h)){if(w&&z.match(/^\d+$/))return S;h=JSON.stringify(""+z),h.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(h=h.substr(1,h.length-2),h=e.stylize(h,"name")):(h=h.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),h=e.stylize(h,"string"))}return h+": "+S}function r(e,n,o){var v=e.reduce(function(z,w){return w.indexOf(` `)>=0,z+w.replace(/\u001b\[\d\d?m/g,"").length+1},0);return v>60?o[0]+(n===""?"":n+` `)+" "+e.join(`, `)+" "+o[1]:o[0]+n+" "+e.join(", ")+" "+o[1]}function t(e){return Array.isArray(e)}l.isArray=t;function i(e){return typeof e=="boolean"}l.isBoolean=i;function s(e){return e===null}l.isNull=s;function g(e){return e==null}l.isNullOrUndefined=g;function y(e){return typeof e=="number"}l.isNumber=y;function b(e){return typeof e=="string"}l.isString=b;function C(e){return typeof e=="symbol"}l.isSymbol=C;function A(e){return e===void 0}l.isUndefined=A;function O(e){return k(e)&&W(e)==="[object RegExp]"}l.isRegExp=O;function k(e){return typeof e=="object"&&e!==null}l.isObject=k;function q(e){return k(e)&&W(e)==="[object Date]"}l.isDate=q;function R(e){return k(e)&&(W(e)==="[object Error]"||e instanceof Error)}l.isError=R;function _(e){return typeof e=="function"}l.isFunction=_;function oe(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"||typeof e=="symbol"||typeof e>"u"}l.isPrimitive=oe,l.isBuffer=x();function W(e){return Object.prototype.toString.call(e)}function J(e){return e<10?"0"+e.toString(10):e.toString(10)}var ae=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function le(){var e=new Date,n=[J(e.getHours()),J(e.getMinutes()),J(e.getSeconds())].join(":");return[e.getDate(),ae[e.getMonth()],n].join(" ")}l.log=function(){console.log("%s - %s",le(),l.format.apply(l,arguments))},l.inherits=ee(),l._extend=function(e,n){if(!n||!k(n))return e;for(var o=Object.keys(n),v=o.length;v--;)e[o[v]]=n[o[v]];return e};function X(e,n){return Object.prototype.hasOwnProperty.call(e,n)}}(F)),F}var Q;function te(){if(Q)return H.exports;Q=1;var l=process.platform==="win32",a=re();function u(r,t){for(var i=[],s=0;s<r.length;s++){var g=r[s];!g||g==="."||(g===".."?i.length&&i[i.length-1]!==".."?i.pop():t&&i.push(".."):i.push(g))}return i}function d(r){for(var t=r.length-1,i=0;i<=t&&!r[i];i++);for(var s=t;s>=0&&!r[s];s--);return i===0&&s===t?r:i>s?[]:r.slice(i,s+1)}var f=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,E=/^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/,p={};function j(r){var t=f.exec(r),i=(t[1]||"")+(t[2]||""),s=t[3]||"",g=E.exec(s),y=g[1],b=g[2],C=g[3];return[i,y,b,C]}function m(r){var t=f.exec(r),i=t[1]||"",s=!!i&&i[1]!==":";return{device:i,isUnc:s,isAbsolute:s||!!t[2],tail:t[3]}}function T(r){return"\\\\"+r.replace(/^[\\\/]+/,"").replace(/[\\\/]+/g,"\\")}p.resolve=function(){for(var r="",t="",i=!1,s=arguments.length-1;s>=-1;s--){var g;if(s>=0?g=arguments[s]:r?(g=process.env["="+r],(!g||g.substr(0,3).toLowerCase()!==r.toLowerCase()+"\\")&&(g=r+"\\")):g=process.cwd(),a.isString(g)){if(!g)continue}else throw new TypeError("Arguments to path.resolve must be strings");var y=m(g),b=y.device,C=y.isUnc,A=y.isAbsolute,O=y.tail;if(!(b&&r&&b.toLowerCase()!==r.toLowerCase())&&(r||(r=b),i||(t=O+"\\"+t,i=A),r&&i))break}return C&&(r=T(r)),t=u(t.split(/[\\\/]+/),!i).join("\\"),r+(i?"\\":"")+t||"."},p.normalize=function(r){var t=m(r),i=t.device,s=t.isUnc,g=t.isAbsolute,y=t.tail,b=/[\\\/]$/.test(y);return y=u(y.split(/[\\\/]+/),!g).join("\\"),!y&&!g&&(y="."),y&&b&&(y+="\\"),s&&(i=T(i)),i+(g?"\\":"")+y},p.isAbsolute=function(r){return m(r).isAbsolute},p.join=function(){for(var r=[],t=0;t<arguments.length;t++){var i=arguments[t];if(!a.isString(i))throw new TypeError("Arguments to path.join must be strings");i&&r.push(i)}var s=r.join("\\");return/^[\\\/]{2}[^\\\/]/.test(r[0])||(s=s.replace(/^[\\\/]{2,}/,"\\")),p.normalize(s)},p.relative=function(r,t){r=p.resolve(r),t=p.resolve(t);for(var i=r.toLowerCase(),s=t.toLowerCase(),g=d(t.split("\\")),y=d(i.split("\\")),b=d(s.split("\\")),C=Math.min(y.length,b.length),A=C,O=0;O<C;O++)if(y[O]!==b[O]){A=O;break}if(A==0)return t;for(var k=[],O=A;O<y.length;O++)k.push("..");return k=k.concat(g.slice(A)),k.join("\\")},p._makeLong=function(r){if(!a.isString(r))return r;if(!r)return"";var t=p.resolve(r);return/^[a-zA-Z]\:\\/.test(t)?"\\\\?\\"+t:/^\\\\[^?.]/.test(t)?"\\\\?\\UNC\\"+t.substring(2):r},p.dirname=function(r){var t=j(r),i=t[0],s=t[1];return!i&&!s?".":(s&&(s=s.substr(0,s.length-1)),i+s)},p.basename=function(r,t){var i=j(r)[2];return t&&i.substr(-1*t.length)===t&&(i=i.substr(0,i.length-t.length)),i},p.extname=function(r){return j(r)[3]},p.format=function(r){if(!a.isObject(r))throw new TypeError("Parameter 'pathObject' must be an object, not "+typeof r);var t=r.root||"";if(!a.isString(t))throw new TypeError("'pathObject.root' must be a string or undefined, not "+typeof r.root);var i=r.dir,s=r.base||"";return i?i[i.length-1]===p.sep?i+s:i+p.sep+s:s},p.parse=function(r){if(!a.isString(r))throw new TypeError("Parameter 'pathString' must be a string, not "+typeof r);var t=j(r);if(!t||t.length!==4)throw new TypeError("Invalid path '"+r+"'");return{root:t[0],dir:t[0]+t[1].slice(0,-1),base:t[2],ext:t[3],name:t[2].slice(0,t[2].length-t[3].length)}},p.sep="\\",p.delimiter=";";var N=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,c={};function $(r){return N.exec(r).slice(1)}return c.resolve=function(){for(var r="",t=!1,i=arguments.length-1;i>=-1&&!t;i--){var s=i>=0?arguments[i]:process.cwd();if(a.isString(s)){if(!s)continue}else throw new TypeError("Arguments to path.resolve must be strings");r=s+"/"+r,t=s[0]==="/"}return r=u(r.split("/"),!t).join("/"),(t?"/":"")+r||"."},c.normalize=function(r){var t=c.isAbsolute(r),i=r&&r[r.length-1]==="/";return r=u(r.split("/"),!t).join("/"),!r&&!t&&(r="."),r&&i&&(r+="/"),(t?"/":"")+r},c.isAbsolute=function(r){return r.charAt(0)==="/"},c.join=function(){for(var r="",t=0;t<arguments.length;t++){var i=arguments[t];if(!a.isString(i))throw new TypeError("Arguments to path.join must be strings");i&&(r?r+="/"+i:r+=i)}return c.normalize(r)},c.relative=function(r,t){r=c.resolve(r).substr(1),t=c.resolve(t).substr(1);for(var i=d(r.split("/")),s=d(t.split("/")),g=Math.min(i.length,s.length),y=g,b=0;b<g;b++)if(i[b]!==s[b]){y=b;break}for(var C=[],b=y;b<i.length;b++)C.push("..");return C=C.concat(s.slice(y)),C.join("/")},c._makeLong=function(r){return r},c.dirname=function(r){var t=$(r),i=t[0],s=t[1];return!i&&!s?".":(s&&(s=s.substr(0,s.length-1)),i+s)},c.basename=function(r,t){var i=$(r)[2];return t&&i.substr(-1*t.length)===t&&(i=i.substr(0,i.length-t.length)),i},c.extname=function(r){return $(r)[3]},c.format=function(r){if(!a.isObject(r))throw new TypeError("Parameter 'pathObject' must be an object, not "+typeof r);var t=r.root||"";if(!a.isString(t))throw new TypeError("'pathObject.root' must be a string or undefined, not "+typeof r.root);var i=r.dir?r.dir+c.sep:"",s=r.base||"";return i+s},c.parse=function(r){if(!a.isString(r))throw new TypeError("Parameter 'pathString' must be a string, not "+typeof r);var t=$(r);if(!t||t.length!==4)throw new TypeError("Invalid path '"+r+"'");return t[1]=t[1]||"",t[2]=t[2]||"",t[3]=t[3]||"",{root:t[0],dir:t[0]+t[1].slice(0,-1),base:t[2],ext:t[3],name:t[2].slice(0,t[2].length-t[3].length)}},c.sep="/",c.delimiter=":",l?H.exports=p:H.exports=c,H.exports.posix=c,H.exports.win32=p,H.exports}var ne=te();const ie=Y(ne);class se{constructor(){this.ast=null,this.eventHandlers=new Map}parse(a){var u;try{const d=a.split(` `).map(j=>j.trim()),f={type:"root",children:[]};let E=f;const p=[];for(let j of d)if(!(!j||j.startsWith("//"))){if(j.startsWith("/*")){for(;!j.includes("*/")&&d.length;)j=(u=d.shift())==null?void 0:u.trim();continue}if(j.includes("{")){const[m]=j.split("{"),[T,...N]=m.trim().split(/\s+/),c=N.join(" ").replace(/"/g,"").trim(),$={type:T,name:c,styles:{},content:"",children:[],events:{},attributes:{}};E.children.push($),p.push(E),E=$}else if(j.includes("}"))E=p.pop();else{const[m,T]=j.split(":").map(N=>N.trim());m&&T&&(m==="text"?E.content=T.replace(/[";]/g,""):m.startsWith("on")?E.events[m]=T.replace(/[";]/g,""):m==="src"||m==="href"||m==="alt"?E.attributes[m]=T.replace(/[";]/g,""):m==="columns"?(E.styles.display="grid",E.styles["grid-template-columns"]=`repeat(${T.replace(/[";]/g,"")}, 1fr)`,E.styles.gap="1rem"):E.styles[this.convertToCSSProperty(m)]=T.replace(/[";]/g,""))}}return this.ast=f,f}catch(d){return console.error("Parse error:",d),null}}convertToCSSProperty(a){return a.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}getAppropriateTag(a){const u=a.type.toLowerCase();return{page:"div",section:"section",box:"div",button:"button",input:"input",link:"a",image:"img",list:"ul",item:"li",table:"table",row:"tr",cell:"td",header:"th",form:"form",textarea:"textarea",select:"select",option:"option",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",p:"p",span:"span"}[u]||u}generateHTML(a=this.ast){if(!a)return"";const u=f=>{if(!f)return"";let E="";f.styles&&(E=Object.entries(f.styles).map(([c,$])=>`${c}: ${$}`).join(";"));let p="";f.attributes&&(p=Object.entries(f.attributes).map(([c,$])=>`${c}="${$}"`).join(" "));let j="";if(Object.keys(f.events).length>0){const c=`element-${Math.random().toString(36).substr(2,9)}`;Object.entries(f.events).forEach(([$,r])=>{this.eventHandlers.set(c,{event:$.toLowerCase().replace("on",""),handler:r})}),j=`id="${c}"`}const m=this.getAppropriateTag(f),T=f.children.map(u).join(""),N=f.content||"";return m==="img"||m==="input"?`<${m} style="${E}" class="hack-soft-${f.type}" ${p} ${j} />`:` <${m} style="${E}" class="hack-soft-${f.type}" ${p} ${j}> ${N} ${T} </${m}> `},d=a.children.map(u).join("");return this.attachEventHandlers(),d}attachEventHandlers(){setTimeout(()=>{this.eventHandlers.forEach((a,u)=>{const d=document.getElementById(u);d&&d.addEventListener(a.event,()=>{try{if(a.handler.startsWith("alert")){const f=a.handler.match(/alert\('(.+)'\)/)||a.handler.match(/alert\("(.+)"\)/);f&&alert(f[1])}else new Function(a.handler)()}catch(f){console.error("Event handler error:",f)}})})},0)}async loadFile(a){if(ie.extname(a)!==".hks")throw new Error("Invalid file extension. Only .hks files are supported.");const u=await fetch(a);if(!u.ok)throw new Error(`Failed to load file: ${u.statusText}`);return await u.text()}async interpret(a){let u;a.startsWith("http")||a.startsWith("/")?u=await this.loadFile(a):u=a;const d=this.parse(u);return d?this.generateHTML(d):"<div>Error parsing code</div>"}}U.HackSoftInterpreter=se,Object.defineProperty(U,Symbol.toStringTag,{value:"Module"})});