isomorfeus-asset-manager 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +12 -0
  4. data/lib/iso_opal.rb +10 -0
  5. data/lib/isomorfeus/asset_manager/asset.rb +67 -0
  6. data/lib/isomorfeus/asset_manager/config.rb +69 -0
  7. data/lib/isomorfeus/asset_manager/js_import.rb +59 -0
  8. data/lib/isomorfeus/asset_manager/portfolio.rb +46 -0
  9. data/lib/isomorfeus/asset_manager/rack_middleware.rb +85 -0
  10. data/lib/isomorfeus/asset_manager/ruby_import.rb +33 -0
  11. data/lib/isomorfeus/asset_manager/server_socket_processor.rb +55 -0
  12. data/lib/isomorfeus/asset_manager/version.rb +5 -0
  13. data/lib/isomorfeus/asset_manager/view_helper.rb +9 -0
  14. data/lib/isomorfeus/asset_manager.rb +145 -0
  15. data/lib/isomorfeus-asset-manager.rb +27 -0
  16. data/node_modules/.bin/esbuild +12 -0
  17. data/node_modules/.bin/esbuild.cmd +17 -0
  18. data/node_modules/.bin/esbuild.ps1 +28 -0
  19. data/node_modules/.package-lock.json +18 -0
  20. data/node_modules/esbuild-wasm/README.md +3 -0
  21. data/node_modules/esbuild-wasm/bin/esbuild +84 -0
  22. data/node_modules/esbuild-wasm/esbuild.wasm +0 -0
  23. data/node_modules/esbuild-wasm/esm/browser.d.ts +397 -0
  24. data/node_modules/esbuild-wasm/esm/browser.js +2341 -0
  25. data/node_modules/esbuild-wasm/esm/browser.min.js +8 -0
  26. data/node_modules/esbuild-wasm/exit0.js +11 -0
  27. data/node_modules/esbuild-wasm/lib/browser.d.ts +397 -0
  28. data/node_modules/esbuild-wasm/lib/browser.js +2371 -0
  29. data/node_modules/esbuild-wasm/lib/browser.min.js +10 -0
  30. data/node_modules/esbuild-wasm/lib/main.d.ts +397 -0
  31. data/node_modules/esbuild-wasm/lib/main.js +1948 -0
  32. data/node_modules/esbuild-wasm/package.json +16 -0
  33. data/node_modules/esbuild-wasm/wasm_exec.js +654 -0
  34. data/package.json +9 -0
  35. metadata +162 -0
@@ -0,0 +1,8 @@
1
+ var Xe=Object.defineProperty,Ze=Object.defineProperties;var et=Object.getOwnPropertyDescriptors;var Me=Object.getOwnPropertySymbols;var tt=Object.prototype.hasOwnProperty,rt=Object.prototype.propertyIsEnumerable;var Le=(e,t,r)=>t in e?Xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,$e=(e,t)=>{for(var r in t||(t={}))tt.call(t,r)&&Le(e,r,t[r]);if(Me)for(var r of Me(t))rt.call(t,r)&&Le(e,r,t[r]);return e},De=(e,t)=>Ze(e,et(t));function Pe(e){let t=o=>{if(o===null)r.write8(0);else if(typeof o=="boolean")r.write8(1),r.write8(+o);else if(typeof o=="number")r.write8(2),r.write32(o|0);else if(typeof o=="string")r.write8(3),r.write(se(o));else if(o instanceof Uint8Array)r.write8(4),r.write(o);else if(o instanceof Array){r.write8(5),r.write32(o.length);for(let f of o)t(f)}else{let f=Object.keys(o);r.write8(6),r.write32(f.length);for(let l of f)r.write(se(l)),t(o[l])}},r=new Be;return r.write32(0),r.write32(e.id<<1|+!e.isRequest),t(e.value),Fe(r.buf,r.len-4,0),r.buf.subarray(0,r.len)}function Ue(e){let t=()=>{switch(r.read8()){case 0:return null;case 1:return!!r.read8();case 2:return r.read32();case 3:return ue(r.read());case 4:return r.read();case 5:{let u=r.read32(),i=[];for(let v=0;v<u;v++)i.push(t());return i}case 6:{let u=r.read32(),i={};for(let v=0;v<u;v++)i[ue(r.read())]=t();return i}default:throw new Error("Invalid packet")}},r=new Be(e),o=r.read32(),f=(o&1)==0;o>>>=1;let l=t();if(r.ptr!==e.length)throw new Error("Invalid packet");return{id:o,isRequest:f,value:l}}var Be=class{constructor(t=new Uint8Array(1024)){this.buf=t;this.len=0;this.ptr=0}_write(t){if(this.len+t>this.buf.length){let r=new Uint8Array((this.len+t)*2);r.set(this.buf),this.buf=r}return this.len+=t,this.len-t}write8(t){let r=this._write(1);this.buf[r]=t}write32(t){let r=this._write(4);Fe(this.buf,t,r)}write(t){let r=this._write(4+t.length);Fe(this.buf,t.length,r),this.buf.set(t,r+4)}_read(t){if(this.ptr+t>this.buf.length)throw new Error("Invalid packet");return this.ptr+=t,this.ptr-t}read8(){return this.buf[this._read(1)]}read32(){return Te(this.buf,this._read(4))}read(){let t=this.read32(),r=new Uint8Array(t),o=this._read(r.length);return r.set(this.buf.subarray(o,o+t)),r}},se,ue;if(typeof TextEncoder!="undefined"&&typeof TextDecoder!="undefined"){let e=new TextEncoder,t=new TextDecoder;se=r=>e.encode(r),ue=r=>t.decode(r)}else if(typeof Buffer!="undefined")se=e=>{let t=Buffer.from(e);return t instanceof Uint8Array||(t=new Uint8Array(t)),t},ue=e=>{let{buffer:t,byteOffset:r,byteLength:o}=e;return Buffer.from(t,r,o).toString()};else throw new Error("No UTF-8 codec found");function Te(e,t){return e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}function Fe(e,t,r){e[r++]=t,e[r++]=t>>8,e[r++]=t>>16,e[r++]=t>>24}function We(e){if(e+="",e.indexOf(",")>=0)throw new Error(`Invalid target: ${e}`);return e}var je=()=>null,W=e=>typeof e=="boolean"?null:"a boolean",nt=e=>typeof e=="boolean"||typeof e=="object"&&!Array.isArray(e)?null:"a boolean or an object",h=e=>typeof e=="string"?null:"a string",qe=e=>e instanceof RegExp?null:"a RegExp object",pe=e=>typeof e=="number"&&e===(e|0)?null:"an integer",Ae=e=>typeof e=="function"?null:"a function",q=e=>Array.isArray(e)?null:"an array",ge=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"an object",lt=e=>typeof e=="object"&&e!==null?null:"an array or an object",Ke=e=>typeof e=="object"&&!Array.isArray(e)?null:"an object or null",Ne=e=>typeof e=="string"||typeof e=="boolean"?null:"a string or a boolean",it=e=>typeof e=="string"||typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"a string or an object",st=e=>typeof e=="string"||Array.isArray(e)?null:"a string or an array",ot=e=>typeof e=="string"||e instanceof Uint8Array?null:"a string or a Uint8Array";function n(e,t,r,o){let f=e[r];if(t[r+""]=!0,f===void 0)return;let l=o(f);if(l!==null)throw new Error(`"${r}" must be ${l}`);return f}function z(e,t,r){for(let o in e)if(!(o in t))throw new Error(`Invalid option ${r}: "${o}"`)}function _e(e){let t=Object.create(null),r=n(e,t,"wasmURL",h),o=n(e,t,"worker",W);return z(e,t,"in startService() call"),{wasmURL:r,worker:o}}function Re(e,t,r,o,f){let l=n(t,r,"color",W),u=n(t,r,"logLevel",h),i=n(t,r,"logLimit",pe);l!==void 0?e.push(`--color=${l}`):o&&e.push("--color=true"),e.push(`--log-level=${u||f}`),e.push(`--log-limit=${i||0}`)}function Ve(e,t,r){let o=n(t,r,"legalComments",h),f=n(t,r,"sourceRoot",h),l=n(t,r,"sourcesContent",W),u=n(t,r,"target",st),i=n(t,r,"format",h),v=n(t,r,"globalName",h),S=n(t,r,"minify",W),x=n(t,r,"minifySyntax",W),A=n(t,r,"minifyWhitespace",W),K=n(t,r,"minifyIdentifiers",W),$=n(t,r,"charset",h),M=n(t,r,"treeShaking",Ne),ee=n(t,r,"jsx",h),Q=n(t,r,"jsxFactory",h),re=n(t,r,"jsxFragment",h),te=n(t,r,"define",ge),oe=n(t,r,"pure",q),ae=n(t,r,"keepNames",W);if(o&&e.push(`--legal-comments=${o}`),f!==void 0&&e.push(`--source-root=${f}`),l!==void 0&&e.push(`--sources-content=${l}`),u&&(Array.isArray(u)?e.push(`--target=${Array.from(u).map(We).join(",")}`):e.push(`--target=${We(u)}`)),i&&e.push(`--format=${i}`),v&&e.push(`--global-name=${v}`),S&&e.push("--minify"),x&&e.push("--minify-syntax"),A&&e.push("--minify-whitespace"),K&&e.push("--minify-identifiers"),$&&e.push(`--charset=${$}`),M!==void 0&&M!==!0&&e.push(`--tree-shaking=${M}`),ee&&e.push(`--jsx=${ee}`),Q&&e.push(`--jsx-factory=${Q}`),re&&e.push(`--jsx-fragment=${re}`),te)for(let H in te){if(H.indexOf("=")>=0)throw new Error(`Invalid define: ${H}`);e.push(`--define:${H}=${te[H]}`)}if(oe)for(let H of oe)e.push(`--pure:${H}`);ae&&e.push("--keep-names")}function at(e,t,r,o,f){var j;let l=[],u=[],i=Object.create(null),v=null,S=null,x=null;Re(l,t,i,r,o),Ve(l,t,i);let A=n(t,i,"sourcemap",Ne),K=n(t,i,"bundle",W),$=n(t,i,"watch",nt),M=n(t,i,"splitting",W),ee=n(t,i,"preserveSymlinks",W),Q=n(t,i,"metafile",W),re=n(t,i,"outfile",h),te=n(t,i,"outdir",h),oe=n(t,i,"outbase",h),ae=n(t,i,"platform",h),H=n(t,i,"tsconfig",h),ve=n(t,i,"resolveExtensions",q),we=n(t,i,"nodePaths",q),xe=n(t,i,"mainFields",q),ke=n(t,i,"conditions",q),p=n(t,i,"external",q),c=n(t,i,"loader",ge),a=n(t,i,"outExtension",ge),g=n(t,i,"publicPath",h),L=n(t,i,"entryNames",h),F=n(t,i,"chunkNames",h),B=n(t,i,"assetNames",h),C=n(t,i,"inject",q),P=n(t,i,"banner",ge),D=n(t,i,"footer",ge),R=n(t,i,"entryPoints",lt),N=n(t,i,"absWorkingDir",h),k=n(t,i,"stdin",ge),O=(j=n(t,i,"write",W))!=null?j:f,E=n(t,i,"allowOverwrite",W),m=n(t,i,"incremental",W)===!0;if(i.plugins=!0,z(t,i,`in ${e}() call`),A&&l.push(`--sourcemap${A===!0?"":`=${A}`}`),K&&l.push("--bundle"),E&&l.push("--allow-overwrite"),$)if(l.push("--watch"),typeof $=="boolean")x={};else{let s=Object.create(null),y=n($,s,"onRebuild",Ae);z($,s,`on "watch" in ${e}() call`),x={onRebuild:y}}if(M&&l.push("--splitting"),ee&&l.push("--preserve-symlinks"),Q&&l.push("--metafile"),re&&l.push(`--outfile=${re}`),te&&l.push(`--outdir=${te}`),oe&&l.push(`--outbase=${oe}`),ae&&l.push(`--platform=${ae}`),H&&l.push(`--tsconfig=${H}`),ve){let s=[];for(let y of ve){if(y+="",y.indexOf(",")>=0)throw new Error(`Invalid resolve extension: ${y}`);s.push(y)}l.push(`--resolve-extensions=${s.join(",")}`)}if(g&&l.push(`--public-path=${g}`),L&&l.push(`--entry-names=${L}`),F&&l.push(`--chunk-names=${F}`),B&&l.push(`--asset-names=${B}`),xe){let s=[];for(let y of xe){if(y+="",y.indexOf(",")>=0)throw new Error(`Invalid main field: ${y}`);s.push(y)}l.push(`--main-fields=${s.join(",")}`)}if(ke){let s=[];for(let y of ke){if(y+="",y.indexOf(",")>=0)throw new Error(`Invalid condition: ${y}`);s.push(y)}l.push(`--conditions=${s.join(",")}`)}if(p)for(let s of p)l.push(`--external:${s}`);if(P)for(let s in P){if(s.indexOf("=")>=0)throw new Error(`Invalid banner file type: ${s}`);l.push(`--banner:${s}=${P[s]}`)}if(D)for(let s in D){if(s.indexOf("=")>=0)throw new Error(`Invalid footer file type: ${s}`);l.push(`--footer:${s}=${D[s]}`)}if(C)for(let s of C)l.push(`--inject:${s}`);if(c)for(let s in c){if(s.indexOf("=")>=0)throw new Error(`Invalid loader extension: ${s}`);l.push(`--loader:${s}=${c[s]}`)}if(a)for(let s in a){if(s.indexOf("=")>=0)throw new Error(`Invalid out extension: ${s}`);l.push(`--out-extension:${s}=${a[s]}`)}if(R)if(Array.isArray(R))for(let s of R)u.push(["",s+""]);else for(let[s,y]of Object.entries(R))u.push([s+"",y+""]);if(k){let s=Object.create(null),y=n(k,s,"contents",h),d=n(k,s,"resolveDir",h),w=n(k,s,"sourcefile",h),I=n(k,s,"loader",h);z(k,s,'in "stdin" object'),w&&l.push(`--sourcefile=${w}`),I&&l.push(`--loader=${I}`),d&&(S=d+""),v=y?y+"":""}let b=[];if(we)for(let s of we)s+="",b.push(s);return{entries:u,flags:l,write:O,stdinContents:v,stdinResolveDir:S,absWorkingDir:N,incremental:m,nodePaths:b,watch:x}}function ut(e,t,r,o){let f=[],l=Object.create(null);Re(f,t,l,r,o),Ve(f,t,l);let u=n(t,l,"sourcemap",Ne),i=n(t,l,"tsconfigRaw",it),v=n(t,l,"sourcefile",h),S=n(t,l,"loader",h),x=n(t,l,"banner",h),A=n(t,l,"footer",h);return z(t,l,`in ${e}() call`),u&&f.push(`--sourcemap=${u===!0?"external":u}`),i&&f.push(`--tsconfig-raw=${typeof i=="string"?i:JSON.stringify(i)}`),v&&f.push(`--sourcefile=${v}`),S&&f.push(`--loader=${S}`),x&&f.push(`--banner=${x}`),A&&f.push(`--footer=${A}`),f}function Je(e){let t=new Map,r=new Map,o=new Map,f=new Map,l=0,u=!1,i=0,v=0,S=new Uint8Array(16*1024),x=0,A=p=>{let c=x+p.length;if(c>S.length){let g=new Uint8Array(c*2);g.set(S),S=g}S.set(p,x),x+=p.length;let a=0;for(;a+4<=x;){let g=Te(S,a);if(a+4+g>x)break;a+=4,re(S.subarray(a,a+g)),a+=g}a>0&&(S.copyWithin(0,a,x),x-=a)},K=()=>{u=!0;for(let p of t.values())p("The service was stopped",null);t.clear();for(let p of f.values())p.onWait("The service was stopped");f.clear();for(let p of o.values())try{p(new Error("The service was stopped"),null)}catch(c){console.error(c)}o.clear()},$=(p,c,a)=>{if(u)return a("The service is no longer running",null);let g=i++;t.set(g,(L,F)=>{try{a(L,F)}finally{p&&p.unref()}}),p&&p.ref(),e.writeToStdin(Pe({id:g,isRequest:!0,value:c}))},M=(p,c)=>{if(u)throw new Error("The service is no longer running");e.writeToStdin(Pe({id:p,isRequest:!1,value:c}))},ee=async(p,c)=>{try{switch(c.command){case"ping":{M(p,{});break}case"start":{let a=r.get(c.key);a?M(p,await a(c)):M(p,{});break}case"resolve":{let a=r.get(c.key);a?M(p,await a(c)):M(p,{});break}case"load":{let a=r.get(c.key);a?M(p,await a(c)):M(p,{});break}case"serve-request":{let a=f.get(c.serveID);a&&a.onRequest&&a.onRequest(c.args),M(p,{});break}case"serve-wait":{let a=f.get(c.serveID);a&&a.onWait(c.error),M(p,{});break}case"watch-rebuild":{let a=o.get(c.watchID);try{a&&a(null,c.args)}catch(g){console.error(g)}M(p,{});break}default:throw new Error("Invalid command: "+c.command)}}catch(a){M(p,{errors:[me(a,e,null,void 0,"")]})}},Q=!0,re=p=>{if(Q){Q=!1;let a=String.fromCharCode(...p);if(a!=="0.12.25")throw new Error(`Cannot start service: Host version "0.12.25" does not match binary version ${JSON.stringify(a)}`);return}let c=Ue(p);if(c.isRequest)ee(c.id,c.value);else{let a=t.get(c.id);t.delete(c.id),c.value.error?a(c.value.error,{}):a(null,c.value)}},te=async(p,c,a,g)=>{let L=[],F=[],B={},C={},P=0,D=0,R=[];c=[...c];for(let E of c){let m={};if(typeof E!="object")throw new Error(`Plugin at index ${D} must be an object`);let b=n(E,m,"name",h);if(typeof b!="string"||b==="")throw new Error(`Plugin at index ${D} is missing a name`);try{let j=n(E,m,"setup",Ae);if(typeof j!="function")throw new Error("Plugin is missing a setup function");z(E,m,`on plugin ${JSON.stringify(b)}`);let s={name:b,onResolve:[],onLoad:[]};D++;let y=j({initialOptions:p,onStart(d){let w='This error came from the "onStart" callback registered here',I=Oe(new Error(w),e,"onStart");L.push({name:b,callback:d,note:I})},onEnd(d){let w='This error came from the "onEnd" callback registered here',I=Oe(new Error(w),e,"onEnd");F.push({name:b,callback:d,note:I})},onResolve(d,w){let I='This error came from the "onResolve" callback registered here',U=Oe(new Error(I),e,"onResolve"),_={},V=n(d,_,"filter",qe),Y=n(d,_,"namespace",h);if(z(d,_,`in onResolve() call for plugin ${JSON.stringify(b)}`),V==null)throw new Error("onResolve() call is missing a filter");let J=P++;B[J]={name:b,callback:w,note:U},s.onResolve.push({id:J,filter:V.source,namespace:Y||""})},onLoad(d,w){let I='This error came from the "onLoad" callback registered here',U=Oe(new Error(I),e,"onLoad"),_={},V=n(d,_,"filter",qe),Y=n(d,_,"namespace",h);if(z(d,_,`in onLoad() call for plugin ${JSON.stringify(b)}`),V==null)throw new Error("onLoad() call is missing a filter");let J=P++;C[J]={name:b,callback:w,note:U},s.onLoad.push({id:J,filter:V.source,namespace:Y||""})}});y&&await y,R.push(s)}catch(j){return{ok:!1,error:j,pluginName:b}}}let N=async E=>{switch(E.command){case"start":{let m={errors:[],warnings:[]};return await Promise.all(L.map(async({name:b,callback:j,note:s})=>{try{let y=await j();if(y!=null){if(typeof y!="object")throw new Error(`Expected onStart() callback in plugin ${JSON.stringify(b)} to return an object`);let d={},w=n(y,d,"errors",q),I=n(y,d,"warnings",q);z(y,d,`from onStart() callback in plugin ${JSON.stringify(b)}`),w!=null&&m.errors.push(...ce(w,"errors",g,b)),I!=null&&m.warnings.push(...ce(I,"warnings",g,b))}}catch(y){m.errors.push(me(y,e,g,s&&s(),b))}})),m}case"resolve":{let m={},b="",j,s;for(let y of E.ids)try{({name:b,callback:j,note:s}=B[y]);let d=await j({path:E.path,importer:E.importer,namespace:E.namespace,resolveDir:E.resolveDir,kind:E.kind,pluginData:g.load(E.pluginData)});if(d!=null){if(typeof d!="object")throw new Error(`Expected onResolve() callback in plugin ${JSON.stringify(b)} to return an object`);let w={},I=n(d,w,"pluginName",h),U=n(d,w,"path",h),_=n(d,w,"namespace",h),V=n(d,w,"external",W),Y=n(d,w,"sideEffects",W),J=n(d,w,"pluginData",je),le=n(d,w,"errors",q),ie=n(d,w,"warnings",q),T=n(d,w,"watchFiles",q),G=n(d,w,"watchDirs",q);z(d,w,`from onResolve() callback in plugin ${JSON.stringify(b)}`),m.id=y,I!=null&&(m.pluginName=I),U!=null&&(m.path=U),_!=null&&(m.namespace=_),V!=null&&(m.external=V),Y!=null&&(m.sideEffects=Y),J!=null&&(m.pluginData=g.store(J)),le!=null&&(m.errors=ce(le,"errors",g,b)),ie!=null&&(m.warnings=ce(ie,"warnings",g,b)),T!=null&&(m.watchFiles=Se(T,"watchFiles")),G!=null&&(m.watchDirs=Se(G,"watchDirs"));break}}catch(d){return{id:y,errors:[me(d,e,g,s&&s(),b)]}}return m}case"load":{let m={},b="",j,s;for(let y of E.ids)try{({name:b,callback:j,note:s}=C[y]);let d=await j({path:E.path,namespace:E.namespace,pluginData:g.load(E.pluginData)});if(d!=null){if(typeof d!="object")throw new Error(`Expected onLoad() callback in plugin ${JSON.stringify(b)} to return an object`);let w={},I=n(d,w,"pluginName",h),U=n(d,w,"contents",ot),_=n(d,w,"resolveDir",h),V=n(d,w,"pluginData",je),Y=n(d,w,"loader",h),J=n(d,w,"errors",q),le=n(d,w,"warnings",q),ie=n(d,w,"watchFiles",q),T=n(d,w,"watchDirs",q);z(d,w,`from onLoad() callback in plugin ${JSON.stringify(b)}`),m.id=y,I!=null&&(m.pluginName=I),U instanceof Uint8Array?m.contents=U:U!=null&&(m.contents=se(U)),_!=null&&(m.resolveDir=_),V!=null&&(m.pluginData=g.store(V)),Y!=null&&(m.loader=Y),J!=null&&(m.errors=ce(J,"errors",g,b)),le!=null&&(m.warnings=ce(le,"warnings",g,b)),ie!=null&&(m.watchFiles=Se(ie,"watchFiles")),T!=null&&(m.watchDirs=Se(T,"watchDirs"));break}}catch(d){return{id:y,errors:[me(d,e,g,s&&s(),b)]}}return m}default:throw new Error("Invalid command: "+E.command)}},k=(E,m,b)=>b();F.length>0&&(k=(E,m,b)=>{(async()=>{for(let{name:j,callback:s,note:y}of F)try{await s(E)}catch(d){E.errors.push(await new Promise(w=>m(d,j,y&&y(),w)))}})().then(b)});let O=0;return{ok:!0,requestPlugins:R,runOnEndCallbacks:k,pluginRefs:{ref(){++O==1&&r.set(a,N)},unref(){--O==0&&r.delete(a)}}}},oe=(p,c,a)=>{let g={},L=n(c,g,"port",pe),F=n(c,g,"host",h),B=n(c,g,"servedir",h),C=n(c,g,"onRequest",Ae),P=l++,D,R=new Promise((N,k)=>{D=O=>{f.delete(P),O!==null?k(new Error(O)):N()}});return a.serve={serveID:P},z(c,g,"in serve() call"),L!==void 0&&(a.serve.port=L),F!==void 0&&(a.serve.host=F),B!==void 0&&(a.serve.servedir=B),f.set(P,{onRequest:C,onWait:D}),{wait:R,stop(){$(p,{command:"serve-stop",serveID:P},()=>{})}}},ae="warning",H="silent",ve=p=>{let c=v++,a=ze(),g,{refs:L,options:F,isTTY:B,callback:C}=p;if(typeof F=="object"){let R=F.plugins;if(R!==void 0){if(!Array.isArray(R))throw new Error('"plugins" must be an array');g=R}}let P=(R,N,k,O)=>{let E=[];try{Re(E,F,{},B,ae)}catch(b){}let m=me(R,e,a,k,N);$(L,{command:"error",flags:E,error:m},()=>{m.detail=a.load(m.detail),O(m)})},D=(R,N)=>{P(R,N,void 0,k=>{C(ye("Build failed",[k],[]),null)})};if(g&&g.length>0){if(e.isSync)return D(new Error("Cannot use plugins in synchronous API calls"),"");te(F,g,c,a).then(R=>{if(!R.ok)D(R.error,R.pluginName);else try{we(De($e({},p),{key:c,details:a,logPluginError:P,requestPlugins:R.requestPlugins,runOnEndCallbacks:R.runOnEndCallbacks,pluginRefs:R.pluginRefs}))}catch(N){D(N,"")}},R=>D(R,""))}else try{we(De($e({},p),{key:c,details:a,logPluginError:P,requestPlugins:null,runOnEndCallbacks:(R,N,k)=>k(),pluginRefs:null}))}catch(R){D(R,"")}},we=({callName:p,refs:c,serveOptions:a,options:g,isTTY:L,defaultWD:F,callback:B,key:C,details:P,logPluginError:D,requestPlugins:R,runOnEndCallbacks:N,pluginRefs:k})=>{let O={ref(){k&&k.ref(),c&&c.ref()},unref(){k&&k.unref(),c&&c.unref()}},E=!e.isBrowser,{entries:m,flags:b,write:j,stdinContents:s,stdinResolveDir:y,absWorkingDir:d,incremental:w,nodePaths:I,watch:U}=at(p,g,L,ae,E),_={command:"build",key:C,entries:m,flags:b,write:j,stdinContents:s,stdinResolveDir:y,absWorkingDir:d||F,incremental:w,nodePaths:I};R&&(_.plugins=R);let V=a&&oe(O,a,_),Y,J,le=(T,G)=>{T.outputFiles&&(G.outputFiles=T.outputFiles.map(ct)),T.metafile&&(G.metafile=JSON.parse(T.metafile)),T.writeToStdout!==void 0&&console.log(ue(T.writeToStdout).replace(/\n$/,""))},ie=(T,G)=>{let X={errors:he(T.errors,P),warnings:he(T.warnings,P)};le(T,X),N(X,D,()=>{if(X.errors.length>0)return G(ye("Build failed",X.errors,X.warnings),null);if(T.rebuildID!==void 0){if(!Y){let ne=!1;Y=()=>new Promise((fe,de)=>{if(ne||u)throw new Error("Cannot rebuild");$(O,{command:"rebuild",rebuildID:T.rebuildID},(Z,Ge)=>{if(Z)return G(ye("Build failed",[{pluginName:"",text:Z,location:null,notes:[],detail:void 0}],[]),null);ie(Ge,(Ee,Qe)=>{Ee?de(Ee):fe(Qe)})})}),O.ref(),Y.dispose=()=>{ne||(ne=!0,$(O,{command:"rebuild-dispose",rebuildID:T.rebuildID},()=>{}),O.unref())}}X.rebuild=Y}if(T.watchID!==void 0){if(!J){let ne=!1;O.ref(),J=()=>{ne||(ne=!0,o.delete(T.watchID),$(O,{command:"watch-stop",watchID:T.watchID},()=>{}),O.unref())},U&&o.set(T.watchID,(fe,de)=>{if(fe){U.onRebuild&&U.onRebuild(fe,null);return}let Z={errors:he(de.errors,P),warnings:he(de.warnings,P)};le(de,Z),N(Z,D,()=>{if(Z.errors.length>0){U.onRebuild&&U.onRebuild(ye("Build failed",Z.errors,Z.warnings),null);return}de.rebuildID!==void 0&&(Z.rebuild=Y),Z.stop=J,U.onRebuild&&U.onRebuild(null,Z)})})}X.stop=J}G(null,X)})};if(j&&e.isBrowser)throw new Error('Cannot enable "write" in the browser');if(w&&e.isSync)throw new Error('Cannot use "incremental" with a synchronous build');if(U&&e.isSync)throw new Error('Cannot use "watch" with a synchronous build');$(O,_,(T,G)=>{if(T)return B(new Error(T),null);if(V){let X=G,ne=!1;O.ref();let fe={port:X.port,host:X.host,wait:V.wait,stop(){ne||(ne=!0,V.stop(),O.unref())}};return O.ref(),V.wait.then(O.unref,O.unref),B(null,fe)}return ie(G,B)})};return{readFromStdout:A,afterClose:K,service:{buildOrServe:ve,transform:({callName:p,refs:c,input:a,options:g,isTTY:L,fs:F,callback:B})=>{let C=ze(),P=D=>{try{if(typeof a!="string")throw new Error('The input to "transform" must be a string');let R=ut(p,g,L,H);$(c,{command:"transform",flags:R,inputFS:D!==null,input:D!==null?D:a},(k,O)=>{if(k)return B(new Error(k),null);let E=he(O.errors,C),m=he(O.warnings,C),b=1,j=()=>--b==0&&B(null,{warnings:m,code:O.code,map:O.map});if(E.length>0)return B(ye("Transform failed",E,m),null);O.codeFS&&(b++,F.readFile(O.code,(s,y)=>{s!==null?B(s,null):(O.code=y,j())})),O.mapFS&&(b++,F.readFile(O.map,(s,y)=>{s!==null?B(s,null):(O.map=y,j())})),j()})}catch(R){let N=[];try{Re(N,g,{},L,H)}catch(O){}let k=me(R,e,C,void 0,"");$(c,{command:"error",flags:N,error:k},()=>{k.detail=C.load(k.detail),B(ye("Transform failed",[k],[]),null)})}};if(typeof a=="string"&&a.length>1024*1024){let D=P;P=()=>F.writeFile(a,D)}P(null)},formatMessages:({callName:p,refs:c,messages:a,options:g,callback:L})=>{let F=ce(a,"messages",null,"");if(!g)throw new Error(`Missing second argument in ${p}() call`);let B={},C=n(g,B,"kind",h),P=n(g,B,"color",W),D=n(g,B,"terminalWidth",pe);if(z(g,B,`in ${p}() call`),C===void 0)throw new Error(`Missing "kind" in ${p}() call`);if(C!=="error"&&C!=="warning")throw new Error(`Expected "kind" to be "error" or "warning" in ${p}() call`);let R={command:"format-msgs",messages:F,isWarning:C==="warning"};P!==void 0&&(R.color=P),D!==void 0&&(R.terminalWidth=D),$(c,R,(N,k)=>{if(N)return L(new Error(N),null);L(null,k.messages)})}}}}function ze(){let e=new Map,t=0;return{load(r){return e.get(r)},store(r){if(r===void 0)return-1;let o=t++;return e.set(o,r),o}}}function Oe(e,t,r){let o,f=!1;return()=>{if(f)return o;f=!0;try{let l=(e.stack+"").split(`
2
+ `);l.splice(1,1);let u=Ye(t,l,r);if(u)return o={text:e.message,location:u},o}catch(l){}}}function me(e,t,r,o,f){let l="Internal error",u=null;try{l=(e&&e.message||e)+""}catch(i){}try{u=Ye(t,(e.stack+"").split(`
3
+ `),"")}catch(i){}return{pluginName:f,text:l,location:u,notes:o?[o]:[],detail:r?r.store(e):-1}}function Ye(e,t,r){let o=" at ";if(e.readFileSync&&!t[0].startsWith(o)&&t[1].startsWith(o))for(let f=1;f<t.length;f++){let l=t[f];if(!!l.startsWith(o))for(l=l.slice(o.length);;){let u=/^(?:new |async )?\S+ \((.*)\)$/.exec(l);if(u){l=u[1];continue}if(u=/^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(l),u){l=u[1];continue}if(u=/^(\S+):(\d+):(\d+)$/.exec(l),u){let i;try{i=e.readFileSync(u[1],"utf8")}catch(A){break}let v=i.split(/\r\n|\r|\n|\u2028|\u2029/)[+u[2]-1]||"",S=+u[3]-1,x=v.slice(S,S+r.length)===r?r.length:0;return{file:u[1],namespace:"file",line:+u[2],column:se(v.slice(0,S)).length,length:se(v.slice(S,S+x)).length,lineText:v+`
4
+ `+t.slice(1).join(`
5
+ `),suggestion:""}}break}}return null}function ye(e,t,r){let o=5,f=t.length<1?"":` with ${t.length} error${t.length<2?"":"s"}:`+t.slice(0,o+1).map((u,i)=>{if(i===o)return`
6
+ ...`;if(!u.location)return`
7
+ error: ${u.text}`;let{file:v,line:S,column:x}=u.location,A=u.pluginName?`[plugin: ${u.pluginName}] `:"";return`
8
+ ${v}:${S}:${x}: error: ${A}${u.text}`}).join(""),l=new Error(`${e}${f}`);return l.errors=t,l.warnings=r,l}function he(e,t){for(let r of e)r.detail=t.load(r.detail);return e}function He(e,t){if(e==null)return null;let r={},o=n(e,r,"file",h),f=n(e,r,"namespace",h),l=n(e,r,"line",pe),u=n(e,r,"column",pe),i=n(e,r,"length",pe),v=n(e,r,"lineText",h),S=n(e,r,"suggestion",h);return z(e,r,t),{file:o||"",namespace:f||"",line:l||0,column:u||0,length:i||0,lineText:v||"",suggestion:S||""}}function ce(e,t,r,o){let f=[],l=0;for(let u of e){let i={},v=n(u,i,"pluginName",h),S=n(u,i,"text",h),x=n(u,i,"location",Ke),A=n(u,i,"notes",q),K=n(u,i,"detail",je),$=`in element ${l} of "${t}"`;z(u,i,$);let M=[];if(A)for(let ee of A){let Q={},re=n(ee,Q,"text",h),te=n(ee,Q,"location",Ke);z(ee,Q,$),M.push({text:re||"",location:He(te,$)})}f.push({pluginName:v||o,text:S||"",location:He(x,$),notes:M,detail:r?r.store(K):-1}),l++}return f}function Se(e,t){let r=[];for(let o of e){if(typeof o!="string")throw new Error(`${JSON.stringify(t)} must be an array of strings`);r.push(o)}return r}function ct({path:e,contents:t}){let r=null;return{path:e,contents:t,get text(){return r===null&&(r=ue(t)),r}}}var ht="0.12.25",bt=e=>Ie().build(e),wt=()=>{throw new Error('The "serve" API only works in node')},vt=(e,t)=>Ie().transform(e,t),Rt=(e,t)=>Ie().formatMessages(e,t),Ot=()=>{throw new Error('The "buildSync" API only works in node')},St=()=>{throw new Error('The "transformSync" API only works in node')},xt=()=>{throw new Error('The "formatMessagesSync" API only works in node')},be,Ce,Ie=()=>{if(Ce)return Ce;throw be?new Error('You need to wait for the promise returned from "initialize" to be resolved before calling this'):new Error('You need to call "initialize" before calling this')},kt=e=>{e=_e(e||{});let t=e.wasmURL,r=e.worker!==!1;if(!t)throw new Error('Must provide the "wasmURL" option');if(t+="",be)throw new Error('Cannot call "initialize" more than once');return be=ft(t,r),be.catch(()=>{be=void 0}),be},ft=async(e,t)=>{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to download ${JSON.stringify(e)}`);let o=await r.arrayBuffer(),f='{let global={};for(let o=self;o;o=Object.getPrototypeOf(o))for(let k of Object.getOwnPropertyNames(o))if(!(k in global))Object.defineProperty(global,k,{get:()=>self[k]});\n// Copyright 2018 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n(()=>{if(typeof global=="undefined")if(typeof window!="undefined")window.global=window;else if(typeof self!="undefined")self.global=self;else throw new Error("cannot export Go (neither global, window nor self is defined)");if(!global.require&&typeof require!="undefined"&&(global.require=require),!global.fs&&global.require){const r=require("fs");typeof r=="object"&&r!==null&&Object.keys(r).length!==0&&(global.fs=Object.assign({},r,{write(i,s,n,l,f,h){if(n===0&&l===s.length&&f===null){if(i===process.stdout.fd){try{process.stdout.write(s,u=>u?h(u,0,null):h(null,l,s))}catch(u){h(u,0,null)}return}if(i===process.stderr.fd){try{process.stderr.write(s,u=>u?h(u,0,null):h(null,l,s))}catch(u){h(u,0,null)}return}}r.write(i,s,n,l,f,h)}}))}const a=()=>{const r=new Error("not implemented");return r.code="ENOSYS",r};if(!global.fs){let r="";global.fs={constants:{O_WRONLY:-1,O_RDWR:-1,O_CREAT:-1,O_TRUNC:-1,O_APPEND:-1,O_EXCL:-1},writeSync(i,s){r+=g.decode(s);const n=r.lastIndexOf(`\n`);return n!=-1&&(console.log(r.substr(0,n)),r=r.substr(n+1)),s.length},write(i,s,n,l,f,h){if(n!==0||l!==s.length||f!==null){h(a());return}const u=this.writeSync(i,s);h(null,u)},chmod(i,s,n){n(a())},chown(i,s,n,l){l(a())},close(i,s){s(a())},fchmod(i,s,n){n(a())},fchown(i,s,n,l){l(a())},fstat(i,s){s(a())},fsync(i,s){s(null)},ftruncate(i,s,n){n(a())},lchown(i,s,n,l){l(a())},link(i,s,n){n(a())},lstat(i,s){s(a())},mkdir(i,s,n){n(a())},open(i,s,n,l){l(a())},read(i,s,n,l,f,h){h(a())},readdir(i,s){s(a())},readlink(i,s){s(a())},rename(i,s,n){n(a())},rmdir(i,s){s(a())},stat(i,s){s(a())},symlink(i,s,n){n(a())},truncate(i,s,n){n(a())},unlink(i,s){s(a())},utimes(i,s,n,l){l(a())}}}if(global.process||(global.process={getuid(){return-1},getgid(){return-1},geteuid(){return-1},getegid(){return-1},getgroups(){throw a()},pid:-1,ppid:-1,umask(){throw a()},cwd(){throw a()},chdir(){throw a()}}),!global.crypto&&global.require){const r=require("crypto");global.crypto={getRandomValues(i){r.randomFillSync(i)}}}if(!global.crypto)throw new Error("global.crypto is not available, polyfill required (getRandomValues only)");if(global.performance||(global.performance={now(){const[r,i]=process.hrtime();return r*1e3+i/1e6}}),!global.TextEncoder&&global.require&&(global.TextEncoder=require("util").TextEncoder),!global.TextEncoder)throw new Error("global.TextEncoder is not available, polyfill required");if(!global.TextDecoder&&global.require&&(global.TextDecoder=require("util").TextDecoder),!global.TextDecoder)throw new Error("global.TextDecoder is not available, polyfill required");const d=new TextEncoder("utf-8"),g=new TextDecoder("utf-8");if(global.Go=class{constructor(){this.argv=["js"],this.env={},this.exit=e=>{e!==0&&console.warn("exit code:",e)},this._exitPromise=new Promise(e=>{this._resolveExitPromise=e}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;const r=(e,t)=>{this.mem.setUint32(e+0,t,!0),this.mem.setUint32(e+4,Math.floor(t/4294967296),!0)},i=e=>{const t=this.mem.getUint32(e+0,!0),o=this.mem.getInt32(e+4,!0);return t+o*4294967296},s=e=>{const t=this.mem.getFloat64(e,!0);if(t===0)return;if(!isNaN(t))return t;const o=this.mem.getUint32(e,!0);return this._values[o]},n=(e,t)=>{const o=2146959360;if(typeof t=="number"&&t!==0){if(isNaN(t)){this.mem.setUint32(e+4,o,!0),this.mem.setUint32(e,0,!0);return}this.mem.setFloat64(e,t,!0);return}if(t===void 0){this.mem.setFloat64(e,0,!0);return}let c=this._ids.get(t);c===void 0&&(c=this._idPool.pop(),c===void 0&&(c=this._values.length),this._values[c]=t,this._goRefCounts[c]=0,this._ids.set(t,c)),this._goRefCounts[c]++;let m=0;switch(typeof t){case"object":t!==null&&(m=1);break;case"string":m=2;break;case"symbol":m=3;break;case"function":m=4;break}this.mem.setUint32(e+4,o|m,!0),this.mem.setUint32(e,c,!0)},l=e=>{const t=i(e+0),o=i(e+8);return new Uint8Array(this._inst.exports.mem.buffer,t,o)},f=e=>{const t=i(e+0),o=i(e+8),c=new Array(o);for(let m=0;m<o;m++)c[m]=s(t+m*8);return c},h=e=>{const t=i(e+0),o=i(e+8);return g.decode(new DataView(this._inst.exports.mem.buffer,t,o))},u=Date.now()-performance.now();this.importObject={go:{"runtime.wasmExit":e=>{e>>>=0;const t=this.mem.getInt32(e+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(t)},"runtime.wasmWrite":e=>{e>>>=0;const t=i(e+8),o=i(e+16),c=this.mem.getInt32(e+24,!0);fs.writeSync(t,new Uint8Array(this._inst.exports.mem.buffer,o,c))},"runtime.resetMemoryDataView":e=>{e>>>=0,this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":e=>{e>>>=0,r(e+8,(u+performance.now())*1e6)},"runtime.walltime":e=>{e>>>=0;const t=new Date().getTime();r(e+8,t/1e3),this.mem.setInt32(e+16,t%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":e=>{e>>>=0;const t=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(t,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(t);)console.warn("scheduleTimeoutEvent: missed timeout event"),this._resume()},i(e+8)+1)),this.mem.setInt32(e+16,t,!0)},"runtime.clearTimeoutEvent":e=>{e>>>=0;const t=this.mem.getInt32(e+8,!0);clearTimeout(this._scheduledTimeouts.get(t)),this._scheduledTimeouts.delete(t)},"runtime.getRandomData":e=>{e>>>=0,crypto.getRandomValues(l(e+8))},"syscall/js.finalizeRef":e=>{e>>>=0;const t=this.mem.getUint32(e+8,!0);if(this._goRefCounts[t]--,this._goRefCounts[t]===0){const o=this._values[t];this._values[t]=null,this._ids.delete(o),this._idPool.push(t)}},"syscall/js.stringVal":e=>{e>>>=0,n(e+24,h(e+8))},"syscall/js.valueGet":e=>{e>>>=0;const t=Reflect.get(s(e+8),h(e+16));e=this._inst.exports.getsp()>>>0,n(e+32,t)},"syscall/js.valueSet":e=>{e>>>=0,Reflect.set(s(e+8),h(e+16),s(e+32))},"syscall/js.valueDelete":e=>{e>>>=0,Reflect.deleteProperty(s(e+8),h(e+16))},"syscall/js.valueIndex":e=>{e>>>=0,n(e+24,Reflect.get(s(e+8),i(e+16)))},"syscall/js.valueSetIndex":e=>{e>>>=0,Reflect.set(s(e+8),i(e+16),s(e+24))},"syscall/js.valueCall":e=>{e>>>=0;try{const t=s(e+8),o=Reflect.get(t,h(e+16)),c=f(e+32),m=Reflect.apply(o,t,c);e=this._inst.exports.getsp()>>>0,n(e+56,m),this.mem.setUint8(e+64,1)}catch(t){e=this._inst.exports.getsp()>>>0,n(e+56,t),this.mem.setUint8(e+64,0)}},"syscall/js.valueInvoke":e=>{e>>>=0;try{const t=s(e+8),o=f(e+16),c=Reflect.apply(t,void 0,o);e=this._inst.exports.getsp()>>>0,n(e+40,c),this.mem.setUint8(e+48,1)}catch(t){e=this._inst.exports.getsp()>>>0,n(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueNew":e=>{e>>>=0;try{const t=s(e+8),o=f(e+16),c=Reflect.construct(t,o);e=this._inst.exports.getsp()>>>0,n(e+40,c),this.mem.setUint8(e+48,1)}catch(t){e=this._inst.exports.getsp()>>>0,n(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueLength":e=>{e>>>=0,r(e+16,parseInt(s(e+8).length))},"syscall/js.valuePrepareString":e=>{e>>>=0;const t=d.encode(String(s(e+8)));n(e+16,t),r(e+24,t.length)},"syscall/js.valueLoadString":e=>{e>>>=0;const t=s(e+8);l(e+16).set(t)},"syscall/js.valueInstanceOf":e=>{e>>>=0,this.mem.setUint8(e+24,s(e+8)instanceof s(e+16)?1:0)},"syscall/js.copyBytesToGo":e=>{e>>>=0;const t=l(e+8),o=s(e+32);if(!(o instanceof Uint8Array||o instanceof Uint8ClampedArray)){this.mem.setUint8(e+48,0);return}const c=o.subarray(0,t.length);t.set(c),r(e+40,c.length),this.mem.setUint8(e+48,1)},"syscall/js.copyBytesToJS":e=>{e>>>=0;const t=s(e+8),o=l(e+16);if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray)){this.mem.setUint8(e+48,0);return}const c=o.subarray(0,t.length);t.set(c),r(e+40,c.length),this.mem.setUint8(e+48,1)},debug:e=>{console.log(e)}}}}async run(r){if(!(r instanceof WebAssembly.Instance))throw new Error("Go.run: WebAssembly.Instance expected");this._inst=r,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,global,this],this._goRefCounts=new Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[global,5],[this,6]]),this._idPool=[],this.exited=!1;let i=4096;const s=u=>{const e=i,t=d.encode(u+"\\0");return new Uint8Array(this.mem.buffer,i,t.length).set(t),i+=t.length,i%8!=0&&(i+=8-i%8),e},n=this.argv.length,l=[];this.argv.forEach(u=>{l.push(s(u))}),l.push(0),Object.keys(this.env).sort().forEach(u=>{l.push(s(`${u}=${this.env[u]}`))}),l.push(0);const h=i;l.forEach(u=>{this.mem.setUint32(i,u,!0),this.mem.setUint32(i+4,0,!0),i+=8}),this._inst.exports.run(n,h),this.exited&&this._resolveExitPromise(),await this._exitPromise}_resume(){if(this.exited)throw new Error("Go program has already exited");this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(r){const i=this;return function(){const s={id:r,this:this,args:arguments};return i._pendingEvent=s,i._resume(),s.result}}},typeof module!="undefined"&&global.require&&global.require.main===module&&global.process&&global.process.versions&&!global.process.versions.electron){process.argv.length<3&&(console.error("usage: go_js_wasm_exec [wasm binary] [arguments]"),process.exit(1));const r=new Go;r.argv=process.argv.slice(2),r.env=Object.assign({TMPDIR:require("os").tmpdir()},process.env),r.exit=process.exit,WebAssembly.instantiate(fs.readFileSync(process.argv[2]),r.importObject).then(i=>(process.on("exit",s=>{s===0&&!r.exited&&(r._pendingEvent={id:0},r._resume())}),r.run(i.instance))).catch(i=>{console.error(i),process.exit(1)})}})();\nonmessage=({data:c})=>{let y=new TextDecoder,s=global.fs,a="";s.writeSync=(e,t)=>{if(e===1)postMessage(t);else if(e===2){a+=y.decode(t);let n=a.split(`\n`);n.length>1&&console.log(n.slice(0,-1).join(`\n`)),a=n[n.length-1]}else throw new Error("Bad write");return t.length};let l=[],i,r=0;onmessage=({data:e})=>{e.length>0&&(l.push(e),i&&i())},s.read=(e,t,n,d,h,m)=>{if(e!==0||n!==0||d!==t.length||h!==null)throw new Error("Bad read");if(l.length===0){i=()=>s.read(e,t,n,d,h,m);return}let g=l[0],u=Math.max(0,Math.min(d,g.length-r));t.set(g.subarray(r,r+u),n),r+=u,r===g.length&&(l.shift(),r=0),m(null,u)};let o=new global.Go;o.argv=["","--service=0.12.25"],WebAssembly.instantiate(c,o.importObject).then(({instance:e})=>o.run(e))};}',l;if(t){let v=new Blob([f],{type:"text/javascript"});l=new Worker(URL.createObjectURL(v))}else{let S=new Function("postMessage",f+"var onmessage; return m => onmessage(m)")(x=>l.onmessage({data:x}));l={onmessage:null,postMessage:x=>S({data:x}),terminate(){}}}l.postMessage(o),l.onmessage=({data:v})=>u(v);let{readFromStdout:u,service:i}=Je({writeToStdin(v){l.postMessage(v)},isSync:!1,isBrowser:!0});Ce={build:v=>new Promise((S,x)=>i.buildOrServe({callName:"build",refs:null,serveOptions:null,options:v,isTTY:!1,defaultWD:"/",callback:(A,K)=>A?x(A):S(K)})),transform:(v,S)=>new Promise((x,A)=>i.transform({callName:"transform",refs:null,input:v,options:S||{},isTTY:!1,fs:{readFile(K,$){$(new Error("Internal error"),null)},writeFile(K,$){$(null)}},callback:(K,$)=>K?A(K):x($)})),formatMessages:(v,S)=>new Promise((x,A)=>i.formatMessages({callName:"formatMessages",refs:null,messages:v,options:S,callback:(K,$)=>K?A(K):x($)}))}};export{bt as build,Ot as buildSync,Rt as formatMessages,xt as formatMessagesSync,kt as initialize,wt as serve,vt as transform,St as transformSync,ht as version};
@@ -0,0 +1,11 @@
1
+
2
+ // Each of these is a native module that calls "exit(0)". This is a workaround
3
+ // for https://github.com/nodejs/node/issues/36616. These native modules are
4
+ // stored in a string both to make them smaller and to hide them from Yarn 2,
5
+ // since they make Yarn 2 unzip this package.
6
+
7
+ module.exports = {
8
+ "darwin-x64-LE.node": "7d3LaxNBHAfwmaRNQx92DwUVX0VawUMaC0ULCm20hRSLLbZCb9Nsd9subjZhHzYV1AUfUEToXyAe9ar+AT15tEf9B8QKVjx4EA+uM7uTOk3T3PT0/cCw+WV3v/uYuc7O9q/d3x2E0DQhJMNbF2+jbYQ8JhoRjvP2kRLC2Pzkwjw5aLx53a40gTHfrPl/D2vM6x9LtpeUuk3NbSOhWjLm+YHuHZq3IPMySk2V87MyL7Mvj62adtV0m+QtyrxupU61vL/AWbMcg1nOcqVJni3zZpU6RQ7HmLnKlt1S2Wz+vFtj+7tD1OkWeaJfd+KcicJ8oUl/HrJNy5bauy9j3TbU+2yepyl1uuVz2iXmrZf1is2qvnsgT5N5WaVW8/hY3tfP4jmLce701I3rkxNT9XcWNjyfrF/Kkjbk9MicYw3/O9Vy3vT0wLKN3FrJ40XN8i/kjZLLez9XuziSm54cciqG7Lb4vYkMLUzG90KYjIEuZSykZKPyXdMW72s2bBg3YXL8CXmdR+GbzzPDV3483X33PPo2szNQ74v2TpLp7YzH86g8Nr6mQdtFQj7w3Lxt6aLNrXu+WR66OsS72tKTy5yTOdkw6YvzstZCAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwzxTmpp+d+rAVRYW5aHCb/9F7hkSD7/mPzdit4san4sOvWnHj3s/iRvB9ONoR0283o8HX8fn87Fd88+VtFEVix0mZq27FvFsx332EJK0+d138FvN/u/kRfcksX9qf7NqbEtwnt/TuTUJrGtW6O7KbfO+AzF6MEkf3HuiI9iR1rac+751oWyx6QEhWbuvz3AEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADg/xFrdqcJyby43xcvbX+Wt9M0+R6BcFnWI7IWXyHo5fW4rMU641T5HkF9ffh+wpxS1WKuuWJ5vumycsUIbJPdGRZL2dcsn4h145nnBzrTLcewnBW2atpV05VLyrPlwFlidqVyO6jyvD8=",
9
+ "linux-x64-LE.node": "7VtfbBRFGJ+99trDlvYkKNeWlA1CAkiXa7HyL4WGSrsgNVhoQqJm3fa27cb7U3b3oMWgNQRjISQYn3zCx77wbGKilmAIb9Yn9cFYNMSSED0xmOJD15nd77vuTrockQc1mR/Z++33ffObmZ3Z2e2wM+8eOtobkySCqCL7CbPeTPp2N/jV9nIS6ttN6uhvC2n20laTaOyOh5lAvkwXD9g8H5LCHNR55cng53iWhDmoq2GmAu79YU7FIJtYWBcDnQw6eX+YZ6UwJ0BeDccM5MczX31edwvS8byJhBnb/vgdJ/NPyjsGuqj23E7CjOW9SnU15PGB3TsA5UX1Q0kKsxQoNwn3TN8rg6xfZqu9+3U5vhZsFu9veDi8q+2L1zr6Rut7Tx1f9+O6t2qD/Yn3A5nyq4bX8sNzrQOVrkNewZ+jx5oV/FJE+u0R/l56bFzBP+jl30CanvbtVgxo2miukNdsR7ccTSPa4RP9WsawjFHTdgzrRH9PtpA3TuhDWcOPrRzRhid0bcTM61nzrEHy+rhZTqjlCpli1tBOtxPNmDAdkjWHhhW7oLxI+o4ePtijdSgdSufyaGG/kvfPDvR7sdlcxSLnSLi/8T5MwnWlOP8cZCB3h/1ozx/wuSZwrzAsBPxVAX8p4A8+txYD/njAn4JyastXJyAgICAgICAgIPD/xR+NrX+p5+8l1Evx73fQaf6FWSfmzqnnv0rc8OJu50/Ufd/d/DOlxg1e+jEWuH/3tuu6V5hNo9e86Et+ftT+HG31ctd1lu/l+GeM9iw6z9CiRqCoVe5844Yplt0NYJr+Qy9950VGW5fU6ZJ6/dcD6vXFKlW6qX6z5KylGXRCBgl3fsQrB/Ws/Kmu/h1syvH8oHq+aw07VafvOPXqpS6FGguHab0XMvTnZnwztaU3qDakv3uGBtnJINXRxkmq0+cW1eli6UtvZtFEo8vtVm4pAQEBAQEBAQEBAQEBAYH/LqSWqn3sWyT7FiaXXFel3E15nPIxyh9QbvrddT+B9GtRd3aASBNJqaW+NnFF8r9Hr6fH3G+u633XbEj2NqSONNadSUyRA817t+3ctBH1dLpObtF0yUA9mP91esxy/hQ9HHqconXxvnkeaki+H+tZXSO6TkBAQEBAQEBAQEBA4ImA6zDnAuumGWzg+nJCn1aDuRt0TRiGdZwtYOO6zWac10F8PRd/sOQWGJdgsSWuxZyFRZw470uB/RTY08B1gXkjQ3ntJ6zjjHFxnM/WAq8DluNh/0R1uJ4zwKu4/JZcv/4nIb0LNrZjCewjEH8IdtW/1N+4jp1Hmlt329fTs1feMjhUzDtFeY+yU0m3te8qemb7Ox1pJf3CVt9NiGKP2Y7l6ENEyRccQxnNF5VxqzBuWM5kwDVUNLOZNjNDPGtMt8eIkpnM25M5nx3Lj5w2LNss5EOGRmOWkdVZQjgbzzpEMfMm/aWnymgBTmxjmCiOMUHNERomijGmjVh6ztDGMtay5Ws13bL0ST8lntMi9JxJM6FZ+qVkdEcnypBtE2W4kMsZeefJ+6GOhNcYR63fJ9x4QbRy+qh9Awh+zwbb3vEnvRdRj+OvxOmrI8rfB9cQ48YnMo6XOIyFBDduemAMxLjxjjzN/78VZ78MYw31OL6QG7j6xzg+CWO3bFeHWY6oP2IU8o5xzwvkmYj2w+s/BbGD3PMHORXQP7uC/m0S2NMQeD4jt1To/9OcXk5yzL8nOH6P03cnw5ysoL/I6Y8lw1xJ/xGnx/1LyN9G6BEfc3p8nyGvrtB+V0Ff3iMQsY8mSn+N06flMF+pMP4/hXu8inv/4j6bRIQema1hagzo8f2cekz91yS816K8Twr0uD8qzumwHy7A9aMe93XM73j08w/5O05f3riWfjz9bU6P7z05/ejrR/wCPtRvAf2WCD3//LoHvjTnR/22CH2QV/obYgD0DyqU/zc=",
10
+ "win32-x64-LE.node": "842awMDMwMDAAsT//zMw7GCAAAcGwuAGEPPJ7+Jj2MJ5VnEHo89ZxZCMzGKFgqL89KLEXIXkxLy8/BKFpFSFotI8hcw8BRf/YIXc/JRUPV5eLhWoGVdLWI9OFM2eBsOnarOmTwKzs6ZNANKhVfnTIXQ2lM4E00GZyRkg9bjcFuDKwJDSxsyQv4svASb2gUFJgZuJT5KBCephGBAAkw2MMDZQng0qBaPBAQLVw8SQwAjTBKMw+RCmgCIDQwyQzgHSGsgONGBg4MHibgEFBgYZBhKAAoqVGECvJLWiBKIM7jcUv0PkEvSKUhJLEhkYjjBCFTMhex4eBA56BRB1PFA/gNVxYKpjGAVDAnh0hqgIeHT6qHB4NL/RMD75ghUk2HxE4/B/1Qf8o+Ez3MEKRUwxWJnJC8RXgFgHWB7osCEKNQVYuaKSm4dcBullgsoGFVPkcgxWroDMuALnq1RVVaUkpYMUKkL1VkDUwcpLvVQIH1RuiiDMNgIX1EAxCYSYMUhshiKKG0xgfpNBiJkhl7uwcoyRj5GBzwnV////g2pCBgYnoH5QcQjDFkC+DRA7KELCIQQcduWZecZGuhVmJro+rnp5wOqNIS+xIDO+KDU9s7gktSgeWOOV5qTGlxmC3QgD2xRhhTJx8ZLC6FqRWRJQlJ+cWlzM4O0a5OfqY2ykl5KTQ2ECAPpDSgASD6Ng5AEA"
11
+ };
@@ -0,0 +1,397 @@
1
+ export type Platform = 'browser' | 'node' | 'neutral';
2
+ export type Format = 'iife' | 'cjs' | 'esm';
3
+ export type Loader = 'js' | 'jsx' | 'ts' | 'tsx' | 'css' | 'json' | 'text' | 'base64' | 'file' | 'dataurl' | 'binary' | 'default';
4
+ export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent';
5
+ export type Charset = 'ascii' | 'utf8';
6
+ export type TreeShaking = true | 'ignore-annotations';
7
+
8
+ interface CommonOptions {
9
+ sourcemap?: boolean | 'inline' | 'external' | 'both';
10
+ legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external';
11
+ sourceRoot?: string;
12
+ sourcesContent?: boolean;
13
+
14
+ format?: Format;
15
+ globalName?: string;
16
+ target?: string | string[];
17
+
18
+ minify?: boolean;
19
+ minifyWhitespace?: boolean;
20
+ minifyIdentifiers?: boolean;
21
+ minifySyntax?: boolean;
22
+ charset?: Charset;
23
+ treeShaking?: TreeShaking;
24
+
25
+ jsx?: 'transform' | 'preserve';
26
+ jsxFactory?: string;
27
+ jsxFragment?: string;
28
+
29
+ define?: { [key: string]: string };
30
+ pure?: string[];
31
+ keepNames?: boolean;
32
+
33
+ color?: boolean;
34
+ logLevel?: LogLevel;
35
+ logLimit?: number;
36
+ }
37
+
38
+ export interface BuildOptions extends CommonOptions {
39
+ bundle?: boolean;
40
+ splitting?: boolean;
41
+ preserveSymlinks?: boolean;
42
+ outfile?: string;
43
+ metafile?: boolean;
44
+ outdir?: string;
45
+ outbase?: string;
46
+ platform?: Platform;
47
+ external?: string[];
48
+ loader?: { [ext: string]: Loader };
49
+ resolveExtensions?: string[];
50
+ mainFields?: string[];
51
+ conditions?: string[];
52
+ write?: boolean;
53
+ allowOverwrite?: boolean;
54
+ tsconfig?: string;
55
+ outExtension?: { [ext: string]: string };
56
+ publicPath?: string;
57
+ entryNames?: string;
58
+ chunkNames?: string;
59
+ assetNames?: string;
60
+ inject?: string[];
61
+ banner?: { [type: string]: string };
62
+ footer?: { [type: string]: string };
63
+ incremental?: boolean;
64
+ entryPoints?: string[] | Record<string, string>;
65
+ stdin?: StdinOptions;
66
+ plugins?: Plugin[];
67
+ absWorkingDir?: string;
68
+ nodePaths?: string[]; // The "NODE_PATH" variable from Node.js
69
+ watch?: boolean | WatchMode;
70
+ }
71
+
72
+ export interface WatchMode {
73
+ onRebuild?: (error: BuildFailure | null, result: BuildResult | null) => void;
74
+ }
75
+
76
+ export interface StdinOptions {
77
+ contents: string;
78
+ resolveDir?: string;
79
+ sourcefile?: string;
80
+ loader?: Loader;
81
+ }
82
+
83
+ export interface Message {
84
+ pluginName: string;
85
+ text: string;
86
+ location: Location | null;
87
+ notes: Note[];
88
+
89
+ // Optional user-specified data that is passed through unmodified. You can
90
+ // use this to stash the original error, for example.
91
+ detail: any;
92
+ }
93
+
94
+ export interface Note {
95
+ text: string;
96
+ location: Location | null;
97
+ }
98
+
99
+ export interface Location {
100
+ file: string;
101
+ namespace: string;
102
+ line: number; // 1-based
103
+ column: number; // 0-based, in bytes
104
+ length: number; // in bytes
105
+ lineText: string;
106
+ suggestion: string;
107
+ }
108
+
109
+ export interface OutputFile {
110
+ path: string;
111
+ contents: Uint8Array; // "text" as bytes
112
+ text: string; // "contents" as text
113
+ }
114
+
115
+ export interface BuildInvalidate {
116
+ (): Promise<BuildIncremental>;
117
+ dispose(): void;
118
+ }
119
+
120
+ export interface BuildIncremental extends BuildResult {
121
+ rebuild: BuildInvalidate;
122
+ }
123
+
124
+ export interface BuildResult {
125
+ errors: Message[];
126
+ warnings: Message[];
127
+ outputFiles?: OutputFile[]; // Only when "write: false"
128
+ rebuild?: BuildInvalidate; // Only when "incremental: true"
129
+ stop?: () => void; // Only when "watch: true"
130
+ metafile?: Metafile; // Only when "metafile: true"
131
+ }
132
+
133
+ export interface BuildFailure extends Error {
134
+ errors: Message[];
135
+ warnings: Message[];
136
+ }
137
+
138
+ export interface ServeOptions {
139
+ port?: number;
140
+ host?: string;
141
+ servedir?: string;
142
+ onRequest?: (args: ServeOnRequestArgs) => void;
143
+ }
144
+
145
+ export interface ServeOnRequestArgs {
146
+ remoteAddress: string;
147
+ method: string;
148
+ path: string;
149
+ status: number;
150
+ timeInMS: number; // The time to generate the response, not to send it
151
+ }
152
+
153
+ export interface ServeResult {
154
+ port: number;
155
+ host: string;
156
+ wait: Promise<void>;
157
+ stop: () => void;
158
+ }
159
+
160
+ export interface TransformOptions extends CommonOptions {
161
+ tsconfigRaw?: string | {
162
+ compilerOptions?: {
163
+ jsxFactory?: string,
164
+ jsxFragmentFactory?: string,
165
+ useDefineForClassFields?: boolean,
166
+ importsNotUsedAsValues?: 'remove' | 'preserve' | 'error',
167
+ },
168
+ };
169
+
170
+ sourcefile?: string;
171
+ loader?: Loader;
172
+ banner?: string;
173
+ footer?: string;
174
+ }
175
+
176
+ export interface TransformResult {
177
+ code: string;
178
+ map: string;
179
+ warnings: Message[];
180
+ }
181
+
182
+ export interface TransformFailure extends Error {
183
+ errors: Message[];
184
+ warnings: Message[];
185
+ }
186
+
187
+ export interface Plugin {
188
+ name: string;
189
+ setup: (build: PluginBuild) => (void | Promise<void>);
190
+ }
191
+
192
+ export interface PluginBuild {
193
+ initialOptions: BuildOptions;
194
+ onStart(callback: () =>
195
+ (OnStartResult | null | void | Promise<OnStartResult | null | void>)): void;
196
+ onEnd(callback: (result: BuildResult) =>
197
+ (void | Promise<void>)): void;
198
+ onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) =>
199
+ (OnResolveResult | null | undefined | Promise<OnResolveResult | null | undefined>)): void;
200
+ onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) =>
201
+ (OnLoadResult | null | undefined | Promise<OnLoadResult | null | undefined>)): void;
202
+ }
203
+
204
+ export interface OnStartResult {
205
+ errors?: PartialMessage[];
206
+ warnings?: PartialMessage[];
207
+ }
208
+
209
+ export interface OnResolveOptions {
210
+ filter: RegExp;
211
+ namespace?: string;
212
+ }
213
+
214
+ export interface OnResolveArgs {
215
+ path: string;
216
+ importer: string;
217
+ namespace: string;
218
+ resolveDir: string;
219
+ kind: ImportKind;
220
+ pluginData: any;
221
+ }
222
+
223
+ export type ImportKind =
224
+ | 'entry-point'
225
+
226
+ // JS
227
+ | 'import-statement'
228
+ | 'require-call'
229
+ | 'dynamic-import'
230
+ | 'require-resolve'
231
+
232
+ // CSS
233
+ | 'import-rule'
234
+ | 'url-token'
235
+
236
+ export interface OnResolveResult {
237
+ pluginName?: string;
238
+
239
+ errors?: PartialMessage[];
240
+ warnings?: PartialMessage[];
241
+
242
+ path?: string;
243
+ external?: boolean;
244
+ sideEffects?: boolean;
245
+ namespace?: string;
246
+ pluginData?: any;
247
+
248
+ watchFiles?: string[];
249
+ watchDirs?: string[];
250
+ }
251
+
252
+ export interface OnLoadOptions {
253
+ filter: RegExp;
254
+ namespace?: string;
255
+ }
256
+
257
+ export interface OnLoadArgs {
258
+ path: string;
259
+ namespace: string;
260
+ pluginData: any;
261
+ }
262
+
263
+ export interface OnLoadResult {
264
+ pluginName?: string;
265
+
266
+ errors?: PartialMessage[];
267
+ warnings?: PartialMessage[];
268
+
269
+ contents?: string | Uint8Array;
270
+ resolveDir?: string;
271
+ loader?: Loader;
272
+ pluginData?: any;
273
+
274
+ watchFiles?: string[];
275
+ watchDirs?: string[];
276
+ }
277
+
278
+ export interface PartialMessage {
279
+ pluginName?: string;
280
+ text?: string;
281
+ location?: Partial<Location> | null;
282
+ notes?: PartialNote[];
283
+ detail?: any;
284
+ }
285
+
286
+ export interface PartialNote {
287
+ text?: string;
288
+ location?: Partial<Location> | null;
289
+ }
290
+
291
+ export interface Metafile {
292
+ inputs: {
293
+ [path: string]: {
294
+ bytes: number
295
+ imports: {
296
+ path: string
297
+ kind: ImportKind
298
+ }[]
299
+ }
300
+ }
301
+ outputs: {
302
+ [path: string]: {
303
+ bytes: number
304
+ inputs: {
305
+ [path: string]: {
306
+ bytesInOutput: number
307
+ }
308
+ }
309
+ imports: {
310
+ path: string
311
+ kind: ImportKind
312
+ }[]
313
+ exports: string[]
314
+ entryPoint?: string
315
+ }
316
+ }
317
+ }
318
+
319
+ export interface FormatMessagesOptions {
320
+ kind: 'error' | 'warning';
321
+ color?: boolean;
322
+ terminalWidth?: number;
323
+ }
324
+
325
+ // This function invokes the "esbuild" command-line tool for you. It returns a
326
+ // promise that either resolves with a "BuildResult" object or rejects with a
327
+ // "BuildFailure" object.
328
+ //
329
+ // Works in node: yes
330
+ // Works in browser: yes
331
+ export declare function build(options: BuildOptions & { write: false }): Promise<BuildResult & { outputFiles: OutputFile[] }>;
332
+ export declare function build(options: BuildOptions & { incremental: true }): Promise<BuildIncremental>;
333
+ export declare function build(options: BuildOptions): Promise<BuildResult>;
334
+
335
+ // This function is similar to "build" but it serves the resulting files over
336
+ // HTTP on a localhost address with the specified port.
337
+ //
338
+ // Works in node: yes
339
+ // Works in browser: no
340
+ export declare function serve(serveOptions: ServeOptions, buildOptions: BuildOptions): Promise<ServeResult>;
341
+
342
+ // This function transforms a single JavaScript file. It can be used to minify
343
+ // JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript
344
+ // to older JavaScript. It returns a promise that is either resolved with a
345
+ // "TransformResult" object or rejected with a "TransformFailure" object.
346
+ //
347
+ // Works in node: yes
348
+ // Works in browser: yes
349
+ export declare function transform(input: string, options?: TransformOptions): Promise<TransformResult>;
350
+
351
+ // Converts log messages to formatted message strings suitable for printing in
352
+ // the terminal. This allows you to reuse the built-in behavior of esbuild's
353
+ // log message formatter. This is a batch-oriented API for efficiency.
354
+ //
355
+ // Works in node: yes
356
+ // Works in browser: yes
357
+ export declare function formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise<string[]>;
358
+
359
+ // A synchronous version of "build".
360
+ //
361
+ // Works in node: yes
362
+ // Works in browser: no
363
+ export declare function buildSync(options: BuildOptions & { write: false }): BuildResult & { outputFiles: OutputFile[] };
364
+ export declare function buildSync(options: BuildOptions): BuildResult;
365
+
366
+ // A synchronous version of "transform".
367
+ //
368
+ // Works in node: yes
369
+ // Works in browser: no
370
+ export declare function transformSync(input: string, options?: TransformOptions): TransformResult;
371
+
372
+ // A synchronous version of "formatMessages".
373
+ //
374
+ // Works in node: yes
375
+ // Works in browser: no
376
+ export declare function formatMessagesSync(messages: PartialMessage[], options: FormatMessagesOptions): string[];
377
+
378
+ // This configures the browser-based version of esbuild. It is necessary to
379
+ // call this first and wait for the returned promise to be resolved before
380
+ // making other API calls when using esbuild in the browser.
381
+ //
382
+ // Works in node: yes
383
+ // Works in browser: yes ("options" is required)
384
+ export declare function initialize(options: InitializeOptions): Promise<void>;
385
+
386
+ export interface InitializeOptions {
387
+ // The URL of the "esbuild.wasm" file. This must be provided when running
388
+ // esbuild in the browser.
389
+ wasmURL?: string
390
+
391
+ // By default esbuild runs the WebAssembly-based browser API in a web worker
392
+ // to avoid blocking the UI thread. This can be disabled by setting "worker"
393
+ // to false.
394
+ worker?: boolean
395
+ }
396
+
397
+ export let version: string;
@@ -0,0 +1,2371 @@
1
+ (exports=>{
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
5
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
22
+ var __export = (target, all) => {
23
+ __markAsModule(target);
24
+ for (var name in all)
25
+ __defProp(target, name, { get: all[name], enumerable: true });
26
+ };
27
+ var __async = (__this, __arguments, generator) => {
28
+ return new Promise((resolve, reject) => {
29
+ var fulfilled = (value) => {
30
+ try {
31
+ step(generator.next(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var rejected = (value) => {
37
+ try {
38
+ step(generator.throw(value));
39
+ } catch (e) {
40
+ reject(e);
41
+ }
42
+ };
43
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
44
+ step((generator = generator.apply(__this, __arguments)).next());
45
+ });
46
+ };
47
+
48
+ // lib/npm/browser.ts
49
+ __export(exports, {
50
+ build: () => build,
51
+ buildSync: () => buildSync,
52
+ formatMessages: () => formatMessages,
53
+ formatMessagesSync: () => formatMessagesSync,
54
+ initialize: () => initialize,
55
+ serve: () => serve,
56
+ transform: () => transform,
57
+ transformSync: () => transformSync,
58
+ version: () => version
59
+ });
60
+
61
+ // lib/shared/stdio_protocol.ts
62
+ function encodePacket(packet) {
63
+ let visit = (value) => {
64
+ if (value === null) {
65
+ bb.write8(0);
66
+ } else if (typeof value === "boolean") {
67
+ bb.write8(1);
68
+ bb.write8(+value);
69
+ } else if (typeof value === "number") {
70
+ bb.write8(2);
71
+ bb.write32(value | 0);
72
+ } else if (typeof value === "string") {
73
+ bb.write8(3);
74
+ bb.write(encodeUTF8(value));
75
+ } else if (value instanceof Uint8Array) {
76
+ bb.write8(4);
77
+ bb.write(value);
78
+ } else if (value instanceof Array) {
79
+ bb.write8(5);
80
+ bb.write32(value.length);
81
+ for (let item of value) {
82
+ visit(item);
83
+ }
84
+ } else {
85
+ let keys = Object.keys(value);
86
+ bb.write8(6);
87
+ bb.write32(keys.length);
88
+ for (let key of keys) {
89
+ bb.write(encodeUTF8(key));
90
+ visit(value[key]);
91
+ }
92
+ }
93
+ };
94
+ let bb = new ByteBuffer();
95
+ bb.write32(0);
96
+ bb.write32(packet.id << 1 | +!packet.isRequest);
97
+ visit(packet.value);
98
+ writeUInt32LE(bb.buf, bb.len - 4, 0);
99
+ return bb.buf.subarray(0, bb.len);
100
+ }
101
+ function decodePacket(bytes) {
102
+ let visit = () => {
103
+ switch (bb.read8()) {
104
+ case 0:
105
+ return null;
106
+ case 1:
107
+ return !!bb.read8();
108
+ case 2:
109
+ return bb.read32();
110
+ case 3:
111
+ return decodeUTF8(bb.read());
112
+ case 4:
113
+ return bb.read();
114
+ case 5: {
115
+ let count = bb.read32();
116
+ let value2 = [];
117
+ for (let i = 0; i < count; i++) {
118
+ value2.push(visit());
119
+ }
120
+ return value2;
121
+ }
122
+ case 6: {
123
+ let count = bb.read32();
124
+ let value2 = {};
125
+ for (let i = 0; i < count; i++) {
126
+ value2[decodeUTF8(bb.read())] = visit();
127
+ }
128
+ return value2;
129
+ }
130
+ default:
131
+ throw new Error("Invalid packet");
132
+ }
133
+ };
134
+ let bb = new ByteBuffer(bytes);
135
+ let id = bb.read32();
136
+ let isRequest = (id & 1) === 0;
137
+ id >>>= 1;
138
+ let value = visit();
139
+ if (bb.ptr !== bytes.length) {
140
+ throw new Error("Invalid packet");
141
+ }
142
+ return { id, isRequest, value };
143
+ }
144
+ var ByteBuffer = class {
145
+ constructor(buf = new Uint8Array(1024)) {
146
+ this.buf = buf;
147
+ this.len = 0;
148
+ this.ptr = 0;
149
+ }
150
+ _write(delta) {
151
+ if (this.len + delta > this.buf.length) {
152
+ let clone = new Uint8Array((this.len + delta) * 2);
153
+ clone.set(this.buf);
154
+ this.buf = clone;
155
+ }
156
+ this.len += delta;
157
+ return this.len - delta;
158
+ }
159
+ write8(value) {
160
+ let offset = this._write(1);
161
+ this.buf[offset] = value;
162
+ }
163
+ write32(value) {
164
+ let offset = this._write(4);
165
+ writeUInt32LE(this.buf, value, offset);
166
+ }
167
+ write(bytes) {
168
+ let offset = this._write(4 + bytes.length);
169
+ writeUInt32LE(this.buf, bytes.length, offset);
170
+ this.buf.set(bytes, offset + 4);
171
+ }
172
+ _read(delta) {
173
+ if (this.ptr + delta > this.buf.length) {
174
+ throw new Error("Invalid packet");
175
+ }
176
+ this.ptr += delta;
177
+ return this.ptr - delta;
178
+ }
179
+ read8() {
180
+ return this.buf[this._read(1)];
181
+ }
182
+ read32() {
183
+ return readUInt32LE(this.buf, this._read(4));
184
+ }
185
+ read() {
186
+ let length = this.read32();
187
+ let bytes = new Uint8Array(length);
188
+ let ptr = this._read(bytes.length);
189
+ bytes.set(this.buf.subarray(ptr, ptr + length));
190
+ return bytes;
191
+ }
192
+ };
193
+ var encodeUTF8;
194
+ var decodeUTF8;
195
+ if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
196
+ let encoder = new TextEncoder();
197
+ let decoder = new TextDecoder();
198
+ encodeUTF8 = (text) => encoder.encode(text);
199
+ decodeUTF8 = (bytes) => decoder.decode(bytes);
200
+ } else if (typeof Buffer !== "undefined") {
201
+ encodeUTF8 = (text) => {
202
+ let buffer = Buffer.from(text);
203
+ if (!(buffer instanceof Uint8Array)) {
204
+ buffer = new Uint8Array(buffer);
205
+ }
206
+ return buffer;
207
+ };
208
+ decodeUTF8 = (bytes) => {
209
+ let { buffer, byteOffset, byteLength } = bytes;
210
+ return Buffer.from(buffer, byteOffset, byteLength).toString();
211
+ };
212
+ } else {
213
+ throw new Error("No UTF-8 codec found");
214
+ }
215
+ function readUInt32LE(buffer, offset) {
216
+ return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
217
+ }
218
+ function writeUInt32LE(buffer, value, offset) {
219
+ buffer[offset++] = value;
220
+ buffer[offset++] = value >> 8;
221
+ buffer[offset++] = value >> 16;
222
+ buffer[offset++] = value >> 24;
223
+ }
224
+
225
+ // lib/shared/common.ts
226
+ function validateTarget(target) {
227
+ target += "";
228
+ if (target.indexOf(",") >= 0)
229
+ throw new Error(`Invalid target: ${target}`);
230
+ return target;
231
+ }
232
+ var canBeAnything = () => null;
233
+ var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
234
+ var mustBeBooleanOrObject = (value) => typeof value === "boolean" || typeof value === "object" && !Array.isArray(value) ? null : "a boolean or an object";
235
+ var mustBeString = (value) => typeof value === "string" ? null : "a string";
236
+ var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
237
+ var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
238
+ var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
239
+ var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
240
+ var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
241
+ var mustBeArrayOrRecord = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
242
+ var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
243
+ var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
244
+ var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
245
+ var mustBeStringOrArray = (value) => typeof value === "string" || Array.isArray(value) ? null : "a string or an array";
246
+ var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
247
+ function getFlag(object, keys, key, mustBeFn) {
248
+ let value = object[key];
249
+ keys[key + ""] = true;
250
+ if (value === void 0)
251
+ return void 0;
252
+ let mustBe = mustBeFn(value);
253
+ if (mustBe !== null)
254
+ throw new Error(`"${key}" must be ${mustBe}`);
255
+ return value;
256
+ }
257
+ function checkForInvalidFlags(object, keys, where) {
258
+ for (let key in object) {
259
+ if (!(key in keys)) {
260
+ throw new Error(`Invalid option ${where}: "${key}"`);
261
+ }
262
+ }
263
+ }
264
+ function validateInitializeOptions(options) {
265
+ let keys = Object.create(null);
266
+ let wasmURL = getFlag(options, keys, "wasmURL", mustBeString);
267
+ let worker = getFlag(options, keys, "worker", mustBeBoolean);
268
+ checkForInvalidFlags(options, keys, "in startService() call");
269
+ return {
270
+ wasmURL,
271
+ worker
272
+ };
273
+ }
274
+ function pushLogFlags(flags, options, keys, isTTY, logLevelDefault) {
275
+ let color = getFlag(options, keys, "color", mustBeBoolean);
276
+ let logLevel = getFlag(options, keys, "logLevel", mustBeString);
277
+ let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
278
+ if (color !== void 0)
279
+ flags.push(`--color=${color}`);
280
+ else if (isTTY)
281
+ flags.push(`--color=true`);
282
+ flags.push(`--log-level=${logLevel || logLevelDefault}`);
283
+ flags.push(`--log-limit=${logLimit || 0}`);
284
+ }
285
+ function pushCommonFlags(flags, options, keys) {
286
+ let legalComments = getFlag(options, keys, "legalComments", mustBeString);
287
+ let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
288
+ let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
289
+ let target = getFlag(options, keys, "target", mustBeStringOrArray);
290
+ let format = getFlag(options, keys, "format", mustBeString);
291
+ let globalName = getFlag(options, keys, "globalName", mustBeString);
292
+ let minify = getFlag(options, keys, "minify", mustBeBoolean);
293
+ let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
294
+ let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
295
+ let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
296
+ let charset = getFlag(options, keys, "charset", mustBeString);
297
+ let treeShaking = getFlag(options, keys, "treeShaking", mustBeStringOrBoolean);
298
+ let jsx = getFlag(options, keys, "jsx", mustBeString);
299
+ let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
300
+ let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
301
+ let define = getFlag(options, keys, "define", mustBeObject);
302
+ let pure = getFlag(options, keys, "pure", mustBeArray);
303
+ let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
304
+ if (legalComments)
305
+ flags.push(`--legal-comments=${legalComments}`);
306
+ if (sourceRoot !== void 0)
307
+ flags.push(`--source-root=${sourceRoot}`);
308
+ if (sourcesContent !== void 0)
309
+ flags.push(`--sources-content=${sourcesContent}`);
310
+ if (target) {
311
+ if (Array.isArray(target))
312
+ flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`);
313
+ else
314
+ flags.push(`--target=${validateTarget(target)}`);
315
+ }
316
+ if (format)
317
+ flags.push(`--format=${format}`);
318
+ if (globalName)
319
+ flags.push(`--global-name=${globalName}`);
320
+ if (minify)
321
+ flags.push("--minify");
322
+ if (minifySyntax)
323
+ flags.push("--minify-syntax");
324
+ if (minifyWhitespace)
325
+ flags.push("--minify-whitespace");
326
+ if (minifyIdentifiers)
327
+ flags.push("--minify-identifiers");
328
+ if (charset)
329
+ flags.push(`--charset=${charset}`);
330
+ if (treeShaking !== void 0 && treeShaking !== true)
331
+ flags.push(`--tree-shaking=${treeShaking}`);
332
+ if (jsx)
333
+ flags.push(`--jsx=${jsx}`);
334
+ if (jsxFactory)
335
+ flags.push(`--jsx-factory=${jsxFactory}`);
336
+ if (jsxFragment)
337
+ flags.push(`--jsx-fragment=${jsxFragment}`);
338
+ if (define) {
339
+ for (let key in define) {
340
+ if (key.indexOf("=") >= 0)
341
+ throw new Error(`Invalid define: ${key}`);
342
+ flags.push(`--define:${key}=${define[key]}`);
343
+ }
344
+ }
345
+ if (pure)
346
+ for (let fn of pure)
347
+ flags.push(`--pure:${fn}`);
348
+ if (keepNames)
349
+ flags.push(`--keep-names`);
350
+ }
351
+ function flagsForBuildOptions(callName, options, isTTY, logLevelDefault, writeDefault) {
352
+ var _a;
353
+ let flags = [];
354
+ let entries = [];
355
+ let keys = Object.create(null);
356
+ let stdinContents = null;
357
+ let stdinResolveDir = null;
358
+ let watchMode = null;
359
+ pushLogFlags(flags, options, keys, isTTY, logLevelDefault);
360
+ pushCommonFlags(flags, options, keys);
361
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
362
+ let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
363
+ let watch = getFlag(options, keys, "watch", mustBeBooleanOrObject);
364
+ let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
365
+ let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
366
+ let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
367
+ let outfile = getFlag(options, keys, "outfile", mustBeString);
368
+ let outdir = getFlag(options, keys, "outdir", mustBeString);
369
+ let outbase = getFlag(options, keys, "outbase", mustBeString);
370
+ let platform = getFlag(options, keys, "platform", mustBeString);
371
+ let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
372
+ let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArray);
373
+ let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArray);
374
+ let mainFields = getFlag(options, keys, "mainFields", mustBeArray);
375
+ let conditions = getFlag(options, keys, "conditions", mustBeArray);
376
+ let external = getFlag(options, keys, "external", mustBeArray);
377
+ let loader = getFlag(options, keys, "loader", mustBeObject);
378
+ let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
379
+ let publicPath = getFlag(options, keys, "publicPath", mustBeString);
380
+ let entryNames = getFlag(options, keys, "entryNames", mustBeString);
381
+ let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
382
+ let assetNames = getFlag(options, keys, "assetNames", mustBeString);
383
+ let inject = getFlag(options, keys, "inject", mustBeArray);
384
+ let banner = getFlag(options, keys, "banner", mustBeObject);
385
+ let footer = getFlag(options, keys, "footer", mustBeObject);
386
+ let entryPoints = getFlag(options, keys, "entryPoints", mustBeArrayOrRecord);
387
+ let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
388
+ let stdin = getFlag(options, keys, "stdin", mustBeObject);
389
+ let write = (_a = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a : writeDefault;
390
+ let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
391
+ let incremental = getFlag(options, keys, "incremental", mustBeBoolean) === true;
392
+ keys.plugins = true;
393
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
394
+ if (sourcemap)
395
+ flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
396
+ if (bundle)
397
+ flags.push("--bundle");
398
+ if (allowOverwrite)
399
+ flags.push("--allow-overwrite");
400
+ if (watch) {
401
+ flags.push("--watch");
402
+ if (typeof watch === "boolean") {
403
+ watchMode = {};
404
+ } else {
405
+ let watchKeys = Object.create(null);
406
+ let onRebuild = getFlag(watch, watchKeys, "onRebuild", mustBeFunction);
407
+ checkForInvalidFlags(watch, watchKeys, `on "watch" in ${callName}() call`);
408
+ watchMode = { onRebuild };
409
+ }
410
+ }
411
+ if (splitting)
412
+ flags.push("--splitting");
413
+ if (preserveSymlinks)
414
+ flags.push("--preserve-symlinks");
415
+ if (metafile)
416
+ flags.push(`--metafile`);
417
+ if (outfile)
418
+ flags.push(`--outfile=${outfile}`);
419
+ if (outdir)
420
+ flags.push(`--outdir=${outdir}`);
421
+ if (outbase)
422
+ flags.push(`--outbase=${outbase}`);
423
+ if (platform)
424
+ flags.push(`--platform=${platform}`);
425
+ if (tsconfig)
426
+ flags.push(`--tsconfig=${tsconfig}`);
427
+ if (resolveExtensions) {
428
+ let values = [];
429
+ for (let value of resolveExtensions) {
430
+ value += "";
431
+ if (value.indexOf(",") >= 0)
432
+ throw new Error(`Invalid resolve extension: ${value}`);
433
+ values.push(value);
434
+ }
435
+ flags.push(`--resolve-extensions=${values.join(",")}`);
436
+ }
437
+ if (publicPath)
438
+ flags.push(`--public-path=${publicPath}`);
439
+ if (entryNames)
440
+ flags.push(`--entry-names=${entryNames}`);
441
+ if (chunkNames)
442
+ flags.push(`--chunk-names=${chunkNames}`);
443
+ if (assetNames)
444
+ flags.push(`--asset-names=${assetNames}`);
445
+ if (mainFields) {
446
+ let values = [];
447
+ for (let value of mainFields) {
448
+ value += "";
449
+ if (value.indexOf(",") >= 0)
450
+ throw new Error(`Invalid main field: ${value}`);
451
+ values.push(value);
452
+ }
453
+ flags.push(`--main-fields=${values.join(",")}`);
454
+ }
455
+ if (conditions) {
456
+ let values = [];
457
+ for (let value of conditions) {
458
+ value += "";
459
+ if (value.indexOf(",") >= 0)
460
+ throw new Error(`Invalid condition: ${value}`);
461
+ values.push(value);
462
+ }
463
+ flags.push(`--conditions=${values.join(",")}`);
464
+ }
465
+ if (external)
466
+ for (let name of external)
467
+ flags.push(`--external:${name}`);
468
+ if (banner) {
469
+ for (let type in banner) {
470
+ if (type.indexOf("=") >= 0)
471
+ throw new Error(`Invalid banner file type: ${type}`);
472
+ flags.push(`--banner:${type}=${banner[type]}`);
473
+ }
474
+ }
475
+ if (footer) {
476
+ for (let type in footer) {
477
+ if (type.indexOf("=") >= 0)
478
+ throw new Error(`Invalid footer file type: ${type}`);
479
+ flags.push(`--footer:${type}=${footer[type]}`);
480
+ }
481
+ }
482
+ if (inject)
483
+ for (let path of inject)
484
+ flags.push(`--inject:${path}`);
485
+ if (loader) {
486
+ for (let ext in loader) {
487
+ if (ext.indexOf("=") >= 0)
488
+ throw new Error(`Invalid loader extension: ${ext}`);
489
+ flags.push(`--loader:${ext}=${loader[ext]}`);
490
+ }
491
+ }
492
+ if (outExtension) {
493
+ for (let ext in outExtension) {
494
+ if (ext.indexOf("=") >= 0)
495
+ throw new Error(`Invalid out extension: ${ext}`);
496
+ flags.push(`--out-extension:${ext}=${outExtension[ext]}`);
497
+ }
498
+ }
499
+ if (entryPoints) {
500
+ if (Array.isArray(entryPoints)) {
501
+ for (let entryPoint of entryPoints) {
502
+ entries.push(["", entryPoint + ""]);
503
+ }
504
+ } else {
505
+ for (let [key, value] of Object.entries(entryPoints)) {
506
+ entries.push([key + "", value + ""]);
507
+ }
508
+ }
509
+ }
510
+ if (stdin) {
511
+ let stdinKeys = Object.create(null);
512
+ let contents = getFlag(stdin, stdinKeys, "contents", mustBeString);
513
+ let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
514
+ let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
515
+ let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
516
+ checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
517
+ if (sourcefile)
518
+ flags.push(`--sourcefile=${sourcefile}`);
519
+ if (loader2)
520
+ flags.push(`--loader=${loader2}`);
521
+ if (resolveDir)
522
+ stdinResolveDir = resolveDir + "";
523
+ stdinContents = contents ? contents + "" : "";
524
+ }
525
+ let nodePaths = [];
526
+ if (nodePathsInput) {
527
+ for (let value of nodePathsInput) {
528
+ value += "";
529
+ nodePaths.push(value);
530
+ }
531
+ }
532
+ return {
533
+ entries,
534
+ flags,
535
+ write,
536
+ stdinContents,
537
+ stdinResolveDir,
538
+ absWorkingDir,
539
+ incremental,
540
+ nodePaths,
541
+ watch: watchMode
542
+ };
543
+ }
544
+ function flagsForTransformOptions(callName, options, isTTY, logLevelDefault) {
545
+ let flags = [];
546
+ let keys = Object.create(null);
547
+ pushLogFlags(flags, options, keys, isTTY, logLevelDefault);
548
+ pushCommonFlags(flags, options, keys);
549
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
550
+ let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
551
+ let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
552
+ let loader = getFlag(options, keys, "loader", mustBeString);
553
+ let banner = getFlag(options, keys, "banner", mustBeString);
554
+ let footer = getFlag(options, keys, "footer", mustBeString);
555
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
556
+ if (sourcemap)
557
+ flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
558
+ if (tsconfigRaw)
559
+ flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
560
+ if (sourcefile)
561
+ flags.push(`--sourcefile=${sourcefile}`);
562
+ if (loader)
563
+ flags.push(`--loader=${loader}`);
564
+ if (banner)
565
+ flags.push(`--banner=${banner}`);
566
+ if (footer)
567
+ flags.push(`--footer=${footer}`);
568
+ return flags;
569
+ }
570
+ function createChannel(streamIn) {
571
+ let responseCallbacks = new Map();
572
+ let pluginCallbacks = new Map();
573
+ let watchCallbacks = new Map();
574
+ let serveCallbacks = new Map();
575
+ let nextServeID = 0;
576
+ let isClosed = false;
577
+ let nextRequestID = 0;
578
+ let nextBuildKey = 0;
579
+ let stdout = new Uint8Array(16 * 1024);
580
+ let stdoutUsed = 0;
581
+ let readFromStdout = (chunk) => {
582
+ let limit = stdoutUsed + chunk.length;
583
+ if (limit > stdout.length) {
584
+ let swap = new Uint8Array(limit * 2);
585
+ swap.set(stdout);
586
+ stdout = swap;
587
+ }
588
+ stdout.set(chunk, stdoutUsed);
589
+ stdoutUsed += chunk.length;
590
+ let offset = 0;
591
+ while (offset + 4 <= stdoutUsed) {
592
+ let length = readUInt32LE(stdout, offset);
593
+ if (offset + 4 + length > stdoutUsed) {
594
+ break;
595
+ }
596
+ offset += 4;
597
+ handleIncomingPacket(stdout.subarray(offset, offset + length));
598
+ offset += length;
599
+ }
600
+ if (offset > 0) {
601
+ stdout.copyWithin(0, offset, stdoutUsed);
602
+ stdoutUsed -= offset;
603
+ }
604
+ };
605
+ let afterClose = () => {
606
+ isClosed = true;
607
+ for (let callback of responseCallbacks.values()) {
608
+ callback("The service was stopped", null);
609
+ }
610
+ responseCallbacks.clear();
611
+ for (let callbacks of serveCallbacks.values()) {
612
+ callbacks.onWait("The service was stopped");
613
+ }
614
+ serveCallbacks.clear();
615
+ for (let callback of watchCallbacks.values()) {
616
+ try {
617
+ callback(new Error("The service was stopped"), null);
618
+ } catch (e) {
619
+ console.error(e);
620
+ }
621
+ }
622
+ watchCallbacks.clear();
623
+ };
624
+ let sendRequest = (refs, value, callback) => {
625
+ if (isClosed)
626
+ return callback("The service is no longer running", null);
627
+ let id = nextRequestID++;
628
+ responseCallbacks.set(id, (error, response) => {
629
+ try {
630
+ callback(error, response);
631
+ } finally {
632
+ if (refs)
633
+ refs.unref();
634
+ }
635
+ });
636
+ if (refs)
637
+ refs.ref();
638
+ streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
639
+ };
640
+ let sendResponse = (id, value) => {
641
+ if (isClosed)
642
+ throw new Error("The service is no longer running");
643
+ streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
644
+ };
645
+ let handleRequest = (id, request) => __async(this, null, function* () {
646
+ try {
647
+ switch (request.command) {
648
+ case "ping": {
649
+ sendResponse(id, {});
650
+ break;
651
+ }
652
+ case "start": {
653
+ let callback = pluginCallbacks.get(request.key);
654
+ if (!callback)
655
+ sendResponse(id, {});
656
+ else
657
+ sendResponse(id, yield callback(request));
658
+ break;
659
+ }
660
+ case "resolve": {
661
+ let callback = pluginCallbacks.get(request.key);
662
+ if (!callback)
663
+ sendResponse(id, {});
664
+ else
665
+ sendResponse(id, yield callback(request));
666
+ break;
667
+ }
668
+ case "load": {
669
+ let callback = pluginCallbacks.get(request.key);
670
+ if (!callback)
671
+ sendResponse(id, {});
672
+ else
673
+ sendResponse(id, yield callback(request));
674
+ break;
675
+ }
676
+ case "serve-request": {
677
+ let callbacks = serveCallbacks.get(request.serveID);
678
+ if (callbacks && callbacks.onRequest)
679
+ callbacks.onRequest(request.args);
680
+ sendResponse(id, {});
681
+ break;
682
+ }
683
+ case "serve-wait": {
684
+ let callbacks = serveCallbacks.get(request.serveID);
685
+ if (callbacks)
686
+ callbacks.onWait(request.error);
687
+ sendResponse(id, {});
688
+ break;
689
+ }
690
+ case "watch-rebuild": {
691
+ let callback = watchCallbacks.get(request.watchID);
692
+ try {
693
+ if (callback)
694
+ callback(null, request.args);
695
+ } catch (err) {
696
+ console.error(err);
697
+ }
698
+ sendResponse(id, {});
699
+ break;
700
+ }
701
+ default:
702
+ throw new Error(`Invalid command: ` + request.command);
703
+ }
704
+ } catch (e) {
705
+ sendResponse(id, { errors: [extractErrorMessageV8(e, streamIn, null, void 0, "")] });
706
+ }
707
+ });
708
+ let isFirstPacket = true;
709
+ let handleIncomingPacket = (bytes) => {
710
+ if (isFirstPacket) {
711
+ isFirstPacket = false;
712
+ let binaryVersion = String.fromCharCode(...bytes);
713
+ if (binaryVersion !== "0.12.25") {
714
+ throw new Error(`Cannot start service: Host version "${"0.12.25"}" does not match binary version ${JSON.stringify(binaryVersion)}`);
715
+ }
716
+ return;
717
+ }
718
+ let packet = decodePacket(bytes);
719
+ if (packet.isRequest) {
720
+ handleRequest(packet.id, packet.value);
721
+ } else {
722
+ let callback = responseCallbacks.get(packet.id);
723
+ responseCallbacks.delete(packet.id);
724
+ if (packet.value.error)
725
+ callback(packet.value.error, {});
726
+ else
727
+ callback(null, packet.value);
728
+ }
729
+ };
730
+ let handlePlugins = (initialOptions, plugins, buildKey, stash) => __async(this, null, function* () {
731
+ let onStartCallbacks = [];
732
+ let onEndCallbacks = [];
733
+ let onResolveCallbacks = {};
734
+ let onLoadCallbacks = {};
735
+ let nextCallbackID = 0;
736
+ let i = 0;
737
+ let requestPlugins = [];
738
+ plugins = [...plugins];
739
+ for (let item of plugins) {
740
+ let keys = {};
741
+ if (typeof item !== "object")
742
+ throw new Error(`Plugin at index ${i} must be an object`);
743
+ let name = getFlag(item, keys, "name", mustBeString);
744
+ if (typeof name !== "string" || name === "")
745
+ throw new Error(`Plugin at index ${i} is missing a name`);
746
+ try {
747
+ let setup = getFlag(item, keys, "setup", mustBeFunction);
748
+ if (typeof setup !== "function")
749
+ throw new Error(`Plugin is missing a setup function`);
750
+ checkForInvalidFlags(item, keys, `on plugin ${JSON.stringify(name)}`);
751
+ let plugin = {
752
+ name,
753
+ onResolve: [],
754
+ onLoad: []
755
+ };
756
+ i++;
757
+ let promise = setup({
758
+ initialOptions,
759
+ onStart(callback2) {
760
+ let registeredText = `This error came from the "onStart" callback registered here`;
761
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
762
+ onStartCallbacks.push({ name, callback: callback2, note: registeredNote });
763
+ },
764
+ onEnd(callback2) {
765
+ let registeredText = `This error came from the "onEnd" callback registered here`;
766
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
767
+ onEndCallbacks.push({ name, callback: callback2, note: registeredNote });
768
+ },
769
+ onResolve(options, callback2) {
770
+ let registeredText = `This error came from the "onResolve" callback registered here`;
771
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
772
+ let keys2 = {};
773
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
774
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
775
+ checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${JSON.stringify(name)}`);
776
+ if (filter == null)
777
+ throw new Error(`onResolve() call is missing a filter`);
778
+ let id = nextCallbackID++;
779
+ onResolveCallbacks[id] = { name, callback: callback2, note: registeredNote };
780
+ plugin.onResolve.push({ id, filter: filter.source, namespace: namespace || "" });
781
+ },
782
+ onLoad(options, callback2) {
783
+ let registeredText = `This error came from the "onLoad" callback registered here`;
784
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
785
+ let keys2 = {};
786
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
787
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
788
+ checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${JSON.stringify(name)}`);
789
+ if (filter == null)
790
+ throw new Error(`onLoad() call is missing a filter`);
791
+ let id = nextCallbackID++;
792
+ onLoadCallbacks[id] = { name, callback: callback2, note: registeredNote };
793
+ plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || "" });
794
+ }
795
+ });
796
+ if (promise)
797
+ yield promise;
798
+ requestPlugins.push(plugin);
799
+ } catch (e) {
800
+ return { ok: false, error: e, pluginName: name };
801
+ }
802
+ }
803
+ const callback = (request) => __async(this, null, function* () {
804
+ switch (request.command) {
805
+ case "start": {
806
+ let response = { errors: [], warnings: [] };
807
+ yield Promise.all(onStartCallbacks.map((_0) => __async(this, [_0], function* ({ name, callback: callback2, note }) {
808
+ try {
809
+ let result = yield callback2();
810
+ if (result != null) {
811
+ if (typeof result !== "object")
812
+ throw new Error(`Expected onStart() callback in plugin ${JSON.stringify(name)} to return an object`);
813
+ let keys = {};
814
+ let errors = getFlag(result, keys, "errors", mustBeArray);
815
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
816
+ checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${JSON.stringify(name)}`);
817
+ if (errors != null)
818
+ response.errors.push(...sanitizeMessages(errors, "errors", stash, name));
819
+ if (warnings != null)
820
+ response.warnings.push(...sanitizeMessages(warnings, "warnings", stash, name));
821
+ }
822
+ } catch (e) {
823
+ response.errors.push(extractErrorMessageV8(e, streamIn, stash, note && note(), name));
824
+ }
825
+ })));
826
+ return response;
827
+ }
828
+ case "resolve": {
829
+ let response = {}, name = "", callback2, note;
830
+ for (let id of request.ids) {
831
+ try {
832
+ ({ name, callback: callback2, note } = onResolveCallbacks[id]);
833
+ let result = yield callback2({
834
+ path: request.path,
835
+ importer: request.importer,
836
+ namespace: request.namespace,
837
+ resolveDir: request.resolveDir,
838
+ kind: request.kind,
839
+ pluginData: stash.load(request.pluginData)
840
+ });
841
+ if (result != null) {
842
+ if (typeof result !== "object")
843
+ throw new Error(`Expected onResolve() callback in plugin ${JSON.stringify(name)} to return an object`);
844
+ let keys = {};
845
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
846
+ let path = getFlag(result, keys, "path", mustBeString);
847
+ let namespace = getFlag(result, keys, "namespace", mustBeString);
848
+ let external = getFlag(result, keys, "external", mustBeBoolean);
849
+ let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
850
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
851
+ let errors = getFlag(result, keys, "errors", mustBeArray);
852
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
853
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
854
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
855
+ checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${JSON.stringify(name)}`);
856
+ response.id = id;
857
+ if (pluginName != null)
858
+ response.pluginName = pluginName;
859
+ if (path != null)
860
+ response.path = path;
861
+ if (namespace != null)
862
+ response.namespace = namespace;
863
+ if (external != null)
864
+ response.external = external;
865
+ if (sideEffects != null)
866
+ response.sideEffects = sideEffects;
867
+ if (pluginData != null)
868
+ response.pluginData = stash.store(pluginData);
869
+ if (errors != null)
870
+ response.errors = sanitizeMessages(errors, "errors", stash, name);
871
+ if (warnings != null)
872
+ response.warnings = sanitizeMessages(warnings, "warnings", stash, name);
873
+ if (watchFiles != null)
874
+ response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
875
+ if (watchDirs != null)
876
+ response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
877
+ break;
878
+ }
879
+ } catch (e) {
880
+ return { id, errors: [extractErrorMessageV8(e, streamIn, stash, note && note(), name)] };
881
+ }
882
+ }
883
+ return response;
884
+ }
885
+ case "load": {
886
+ let response = {}, name = "", callback2, note;
887
+ for (let id of request.ids) {
888
+ try {
889
+ ({ name, callback: callback2, note } = onLoadCallbacks[id]);
890
+ let result = yield callback2({
891
+ path: request.path,
892
+ namespace: request.namespace,
893
+ pluginData: stash.load(request.pluginData)
894
+ });
895
+ if (result != null) {
896
+ if (typeof result !== "object")
897
+ throw new Error(`Expected onLoad() callback in plugin ${JSON.stringify(name)} to return an object`);
898
+ let keys = {};
899
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
900
+ let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
901
+ let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
902
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
903
+ let loader = getFlag(result, keys, "loader", mustBeString);
904
+ let errors = getFlag(result, keys, "errors", mustBeArray);
905
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
906
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
907
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
908
+ checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${JSON.stringify(name)}`);
909
+ response.id = id;
910
+ if (pluginName != null)
911
+ response.pluginName = pluginName;
912
+ if (contents instanceof Uint8Array)
913
+ response.contents = contents;
914
+ else if (contents != null)
915
+ response.contents = encodeUTF8(contents);
916
+ if (resolveDir != null)
917
+ response.resolveDir = resolveDir;
918
+ if (pluginData != null)
919
+ response.pluginData = stash.store(pluginData);
920
+ if (loader != null)
921
+ response.loader = loader;
922
+ if (errors != null)
923
+ response.errors = sanitizeMessages(errors, "errors", stash, name);
924
+ if (warnings != null)
925
+ response.warnings = sanitizeMessages(warnings, "warnings", stash, name);
926
+ if (watchFiles != null)
927
+ response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
928
+ if (watchDirs != null)
929
+ response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
930
+ break;
931
+ }
932
+ } catch (e) {
933
+ return { id, errors: [extractErrorMessageV8(e, streamIn, stash, note && note(), name)] };
934
+ }
935
+ }
936
+ return response;
937
+ }
938
+ default:
939
+ throw new Error(`Invalid command: ` + request.command);
940
+ }
941
+ });
942
+ let runOnEndCallbacks = (result, logPluginError, done) => done();
943
+ if (onEndCallbacks.length > 0) {
944
+ runOnEndCallbacks = (result, logPluginError, done) => {
945
+ (() => __async(this, null, function* () {
946
+ for (const { name, callback: callback2, note } of onEndCallbacks) {
947
+ try {
948
+ yield callback2(result);
949
+ } catch (e) {
950
+ result.errors.push(yield new Promise((resolve) => logPluginError(e, name, note && note(), resolve)));
951
+ }
952
+ }
953
+ }))().then(done);
954
+ };
955
+ }
956
+ let refCount = 0;
957
+ return {
958
+ ok: true,
959
+ requestPlugins,
960
+ runOnEndCallbacks,
961
+ pluginRefs: {
962
+ ref() {
963
+ if (++refCount === 1)
964
+ pluginCallbacks.set(buildKey, callback);
965
+ },
966
+ unref() {
967
+ if (--refCount === 0)
968
+ pluginCallbacks.delete(buildKey);
969
+ }
970
+ }
971
+ };
972
+ });
973
+ let buildServeData = (refs, options, request) => {
974
+ let keys = {};
975
+ let port = getFlag(options, keys, "port", mustBeInteger);
976
+ let host = getFlag(options, keys, "host", mustBeString);
977
+ let servedir = getFlag(options, keys, "servedir", mustBeString);
978
+ let onRequest = getFlag(options, keys, "onRequest", mustBeFunction);
979
+ let serveID = nextServeID++;
980
+ let onWait;
981
+ let wait = new Promise((resolve, reject) => {
982
+ onWait = (error) => {
983
+ serveCallbacks.delete(serveID);
984
+ if (error !== null)
985
+ reject(new Error(error));
986
+ else
987
+ resolve();
988
+ };
989
+ });
990
+ request.serve = { serveID };
991
+ checkForInvalidFlags(options, keys, `in serve() call`);
992
+ if (port !== void 0)
993
+ request.serve.port = port;
994
+ if (host !== void 0)
995
+ request.serve.host = host;
996
+ if (servedir !== void 0)
997
+ request.serve.servedir = servedir;
998
+ serveCallbacks.set(serveID, {
999
+ onRequest,
1000
+ onWait
1001
+ });
1002
+ return {
1003
+ wait,
1004
+ stop() {
1005
+ sendRequest(refs, { command: "serve-stop", serveID }, () => {
1006
+ });
1007
+ }
1008
+ };
1009
+ };
1010
+ const buildLogLevelDefault = "warning";
1011
+ const transformLogLevelDefault = "silent";
1012
+ let buildOrServe = (args) => {
1013
+ let key = nextBuildKey++;
1014
+ const details = createObjectStash();
1015
+ let plugins;
1016
+ let { refs, options, isTTY, callback } = args;
1017
+ if (typeof options === "object") {
1018
+ let value = options.plugins;
1019
+ if (value !== void 0) {
1020
+ if (!Array.isArray(value))
1021
+ throw new Error(`"plugins" must be an array`);
1022
+ plugins = value;
1023
+ }
1024
+ }
1025
+ let logPluginError = (e, pluginName, note, done) => {
1026
+ let flags = [];
1027
+ try {
1028
+ pushLogFlags(flags, options, {}, isTTY, buildLogLevelDefault);
1029
+ } catch (e2) {
1030
+ }
1031
+ const message = extractErrorMessageV8(e, streamIn, details, note, pluginName);
1032
+ sendRequest(refs, { command: "error", flags, error: message }, () => {
1033
+ message.detail = details.load(message.detail);
1034
+ done(message);
1035
+ });
1036
+ };
1037
+ let handleError = (e, pluginName) => {
1038
+ logPluginError(e, pluginName, void 0, (error) => {
1039
+ callback(failureErrorWithLog("Build failed", [error], []), null);
1040
+ });
1041
+ };
1042
+ if (plugins && plugins.length > 0) {
1043
+ if (streamIn.isSync)
1044
+ return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
1045
+ handlePlugins(options, plugins, key, details).then((result) => {
1046
+ if (!result.ok) {
1047
+ handleError(result.error, result.pluginName);
1048
+ } else {
1049
+ try {
1050
+ buildOrServeContinue(__spreadProps(__spreadValues({}, args), {
1051
+ key,
1052
+ details,
1053
+ logPluginError,
1054
+ requestPlugins: result.requestPlugins,
1055
+ runOnEndCallbacks: result.runOnEndCallbacks,
1056
+ pluginRefs: result.pluginRefs
1057
+ }));
1058
+ } catch (e) {
1059
+ handleError(e, "");
1060
+ }
1061
+ }
1062
+ }, (e) => handleError(e, ""));
1063
+ } else {
1064
+ try {
1065
+ buildOrServeContinue(__spreadProps(__spreadValues({}, args), {
1066
+ key,
1067
+ details,
1068
+ logPluginError,
1069
+ requestPlugins: null,
1070
+ runOnEndCallbacks: (result, logPluginError2, done) => done(),
1071
+ pluginRefs: null
1072
+ }));
1073
+ } catch (e) {
1074
+ handleError(e, "");
1075
+ }
1076
+ }
1077
+ };
1078
+ let buildOrServeContinue = ({
1079
+ callName,
1080
+ refs: callerRefs,
1081
+ serveOptions,
1082
+ options,
1083
+ isTTY,
1084
+ defaultWD,
1085
+ callback,
1086
+ key,
1087
+ details,
1088
+ logPluginError,
1089
+ requestPlugins,
1090
+ runOnEndCallbacks,
1091
+ pluginRefs
1092
+ }) => {
1093
+ const refs = {
1094
+ ref() {
1095
+ if (pluginRefs)
1096
+ pluginRefs.ref();
1097
+ if (callerRefs)
1098
+ callerRefs.ref();
1099
+ },
1100
+ unref() {
1101
+ if (pluginRefs)
1102
+ pluginRefs.unref();
1103
+ if (callerRefs)
1104
+ callerRefs.unref();
1105
+ }
1106
+ };
1107
+ let writeDefault = !streamIn.isBrowser;
1108
+ let {
1109
+ entries,
1110
+ flags,
1111
+ write,
1112
+ stdinContents,
1113
+ stdinResolveDir,
1114
+ absWorkingDir,
1115
+ incremental,
1116
+ nodePaths,
1117
+ watch
1118
+ } = flagsForBuildOptions(callName, options, isTTY, buildLogLevelDefault, writeDefault);
1119
+ let request = {
1120
+ command: "build",
1121
+ key,
1122
+ entries,
1123
+ flags,
1124
+ write,
1125
+ stdinContents,
1126
+ stdinResolveDir,
1127
+ absWorkingDir: absWorkingDir || defaultWD,
1128
+ incremental,
1129
+ nodePaths
1130
+ };
1131
+ if (requestPlugins)
1132
+ request.plugins = requestPlugins;
1133
+ let serve2 = serveOptions && buildServeData(refs, serveOptions, request);
1134
+ let rebuild;
1135
+ let stop;
1136
+ let copyResponseToResult = (response, result) => {
1137
+ if (response.outputFiles)
1138
+ result.outputFiles = response.outputFiles.map(convertOutputFiles);
1139
+ if (response.metafile)
1140
+ result.metafile = JSON.parse(response.metafile);
1141
+ if (response.writeToStdout !== void 0)
1142
+ console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1143
+ };
1144
+ let buildResponseToResult = (response, callback2) => {
1145
+ let result = {
1146
+ errors: replaceDetailsInMessages(response.errors, details),
1147
+ warnings: replaceDetailsInMessages(response.warnings, details)
1148
+ };
1149
+ copyResponseToResult(response, result);
1150
+ runOnEndCallbacks(result, logPluginError, () => {
1151
+ if (result.errors.length > 0) {
1152
+ return callback2(failureErrorWithLog("Build failed", result.errors, result.warnings), null);
1153
+ }
1154
+ if (response.rebuildID !== void 0) {
1155
+ if (!rebuild) {
1156
+ let isDisposed = false;
1157
+ rebuild = () => new Promise((resolve, reject) => {
1158
+ if (isDisposed || isClosed)
1159
+ throw new Error("Cannot rebuild");
1160
+ sendRequest(refs, { command: "rebuild", rebuildID: response.rebuildID }, (error2, response2) => {
1161
+ if (error2) {
1162
+ const message = { pluginName: "", text: error2, location: null, notes: [], detail: void 0 };
1163
+ return callback2(failureErrorWithLog("Build failed", [message], []), null);
1164
+ }
1165
+ buildResponseToResult(response2, (error3, result3) => {
1166
+ if (error3)
1167
+ reject(error3);
1168
+ else
1169
+ resolve(result3);
1170
+ });
1171
+ });
1172
+ });
1173
+ refs.ref();
1174
+ rebuild.dispose = () => {
1175
+ if (isDisposed)
1176
+ return;
1177
+ isDisposed = true;
1178
+ sendRequest(refs, { command: "rebuild-dispose", rebuildID: response.rebuildID }, () => {
1179
+ });
1180
+ refs.unref();
1181
+ };
1182
+ }
1183
+ result.rebuild = rebuild;
1184
+ }
1185
+ if (response.watchID !== void 0) {
1186
+ if (!stop) {
1187
+ let isStopped = false;
1188
+ refs.ref();
1189
+ stop = () => {
1190
+ if (isStopped)
1191
+ return;
1192
+ isStopped = true;
1193
+ watchCallbacks.delete(response.watchID);
1194
+ sendRequest(refs, { command: "watch-stop", watchID: response.watchID }, () => {
1195
+ });
1196
+ refs.unref();
1197
+ };
1198
+ if (watch) {
1199
+ watchCallbacks.set(response.watchID, (serviceStopError, watchResponse) => {
1200
+ if (serviceStopError) {
1201
+ if (watch.onRebuild)
1202
+ watch.onRebuild(serviceStopError, null);
1203
+ return;
1204
+ }
1205
+ let result2 = {
1206
+ errors: replaceDetailsInMessages(watchResponse.errors, details),
1207
+ warnings: replaceDetailsInMessages(watchResponse.warnings, details)
1208
+ };
1209
+ copyResponseToResult(watchResponse, result2);
1210
+ runOnEndCallbacks(result2, logPluginError, () => {
1211
+ if (result2.errors.length > 0) {
1212
+ if (watch.onRebuild)
1213
+ watch.onRebuild(failureErrorWithLog("Build failed", result2.errors, result2.warnings), null);
1214
+ return;
1215
+ }
1216
+ if (watchResponse.rebuildID !== void 0)
1217
+ result2.rebuild = rebuild;
1218
+ result2.stop = stop;
1219
+ if (watch.onRebuild)
1220
+ watch.onRebuild(null, result2);
1221
+ });
1222
+ });
1223
+ }
1224
+ }
1225
+ result.stop = stop;
1226
+ }
1227
+ callback2(null, result);
1228
+ });
1229
+ };
1230
+ if (write && streamIn.isBrowser)
1231
+ throw new Error(`Cannot enable "write" in the browser`);
1232
+ if (incremental && streamIn.isSync)
1233
+ throw new Error(`Cannot use "incremental" with a synchronous build`);
1234
+ if (watch && streamIn.isSync)
1235
+ throw new Error(`Cannot use "watch" with a synchronous build`);
1236
+ sendRequest(refs, request, (error, response) => {
1237
+ if (error)
1238
+ return callback(new Error(error), null);
1239
+ if (serve2) {
1240
+ let serveResponse = response;
1241
+ let isStopped = false;
1242
+ refs.ref();
1243
+ let result = {
1244
+ port: serveResponse.port,
1245
+ host: serveResponse.host,
1246
+ wait: serve2.wait,
1247
+ stop() {
1248
+ if (isStopped)
1249
+ return;
1250
+ isStopped = true;
1251
+ serve2.stop();
1252
+ refs.unref();
1253
+ }
1254
+ };
1255
+ refs.ref();
1256
+ serve2.wait.then(refs.unref, refs.unref);
1257
+ return callback(null, result);
1258
+ }
1259
+ return buildResponseToResult(response, callback);
1260
+ });
1261
+ };
1262
+ let transform2 = ({ callName, refs, input, options, isTTY, fs, callback }) => {
1263
+ const details = createObjectStash();
1264
+ let start = (inputPath) => {
1265
+ try {
1266
+ if (typeof input !== "string")
1267
+ throw new Error('The input to "transform" must be a string');
1268
+ let flags = flagsForTransformOptions(callName, options, isTTY, transformLogLevelDefault);
1269
+ let request = {
1270
+ command: "transform",
1271
+ flags,
1272
+ inputFS: inputPath !== null,
1273
+ input: inputPath !== null ? inputPath : input
1274
+ };
1275
+ sendRequest(refs, request, (error, response) => {
1276
+ if (error)
1277
+ return callback(new Error(error), null);
1278
+ let errors = replaceDetailsInMessages(response.errors, details);
1279
+ let warnings = replaceDetailsInMessages(response.warnings, details);
1280
+ let outstanding = 1;
1281
+ let next = () => --outstanding === 0 && callback(null, { warnings, code: response.code, map: response.map });
1282
+ if (errors.length > 0)
1283
+ return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
1284
+ if (response.codeFS) {
1285
+ outstanding++;
1286
+ fs.readFile(response.code, (err, contents) => {
1287
+ if (err !== null) {
1288
+ callback(err, null);
1289
+ } else {
1290
+ response.code = contents;
1291
+ next();
1292
+ }
1293
+ });
1294
+ }
1295
+ if (response.mapFS) {
1296
+ outstanding++;
1297
+ fs.readFile(response.map, (err, contents) => {
1298
+ if (err !== null) {
1299
+ callback(err, null);
1300
+ } else {
1301
+ response.map = contents;
1302
+ next();
1303
+ }
1304
+ });
1305
+ }
1306
+ next();
1307
+ });
1308
+ } catch (e) {
1309
+ let flags = [];
1310
+ try {
1311
+ pushLogFlags(flags, options, {}, isTTY, transformLogLevelDefault);
1312
+ } catch (e2) {
1313
+ }
1314
+ const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
1315
+ sendRequest(refs, { command: "error", flags, error }, () => {
1316
+ error.detail = details.load(error.detail);
1317
+ callback(failureErrorWithLog("Transform failed", [error], []), null);
1318
+ });
1319
+ }
1320
+ };
1321
+ if (typeof input === "string" && input.length > 1024 * 1024) {
1322
+ let next = start;
1323
+ start = () => fs.writeFile(input, next);
1324
+ }
1325
+ start(null);
1326
+ };
1327
+ let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
1328
+ let result = sanitizeMessages(messages, "messages", null, "");
1329
+ if (!options)
1330
+ throw new Error(`Missing second argument in ${callName}() call`);
1331
+ let keys = {};
1332
+ let kind = getFlag(options, keys, "kind", mustBeString);
1333
+ let color = getFlag(options, keys, "color", mustBeBoolean);
1334
+ let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
1335
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
1336
+ if (kind === void 0)
1337
+ throw new Error(`Missing "kind" in ${callName}() call`);
1338
+ if (kind !== "error" && kind !== "warning")
1339
+ throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
1340
+ let request = {
1341
+ command: "format-msgs",
1342
+ messages: result,
1343
+ isWarning: kind === "warning"
1344
+ };
1345
+ if (color !== void 0)
1346
+ request.color = color;
1347
+ if (terminalWidth !== void 0)
1348
+ request.terminalWidth = terminalWidth;
1349
+ sendRequest(refs, request, (error, response) => {
1350
+ if (error)
1351
+ return callback(new Error(error), null);
1352
+ callback(null, response.messages);
1353
+ });
1354
+ };
1355
+ return {
1356
+ readFromStdout,
1357
+ afterClose,
1358
+ service: {
1359
+ buildOrServe,
1360
+ transform: transform2,
1361
+ formatMessages: formatMessages2
1362
+ }
1363
+ };
1364
+ }
1365
+ function createObjectStash() {
1366
+ const map = new Map();
1367
+ let nextID = 0;
1368
+ return {
1369
+ load(id) {
1370
+ return map.get(id);
1371
+ },
1372
+ store(value) {
1373
+ if (value === void 0)
1374
+ return -1;
1375
+ const id = nextID++;
1376
+ map.set(id, value);
1377
+ return id;
1378
+ }
1379
+ };
1380
+ }
1381
+ function extractCallerV8(e, streamIn, ident) {
1382
+ let note;
1383
+ let tried = false;
1384
+ return () => {
1385
+ if (tried)
1386
+ return note;
1387
+ tried = true;
1388
+ try {
1389
+ let lines = (e.stack + "").split("\n");
1390
+ lines.splice(1, 1);
1391
+ let location = parseStackLinesV8(streamIn, lines, ident);
1392
+ if (location) {
1393
+ note = { text: e.message, location };
1394
+ return note;
1395
+ }
1396
+ } catch (e2) {
1397
+ }
1398
+ };
1399
+ }
1400
+ function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1401
+ let text = "Internal error";
1402
+ let location = null;
1403
+ try {
1404
+ text = (e && e.message || e) + "";
1405
+ } catch (e2) {
1406
+ }
1407
+ try {
1408
+ location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
1409
+ } catch (e2) {
1410
+ }
1411
+ return { pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
1412
+ }
1413
+ function parseStackLinesV8(streamIn, lines, ident) {
1414
+ let at = " at ";
1415
+ if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
1416
+ for (let i = 1; i < lines.length; i++) {
1417
+ let line = lines[i];
1418
+ if (!line.startsWith(at))
1419
+ continue;
1420
+ line = line.slice(at.length);
1421
+ while (true) {
1422
+ let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1423
+ if (match) {
1424
+ line = match[1];
1425
+ continue;
1426
+ }
1427
+ match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1428
+ if (match) {
1429
+ line = match[1];
1430
+ continue;
1431
+ }
1432
+ match = /^(\S+):(\d+):(\d+)$/.exec(line);
1433
+ if (match) {
1434
+ let contents;
1435
+ try {
1436
+ contents = streamIn.readFileSync(match[1], "utf8");
1437
+ } catch (e) {
1438
+ break;
1439
+ }
1440
+ let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1441
+ let column = +match[3] - 1;
1442
+ let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1443
+ return {
1444
+ file: match[1],
1445
+ namespace: "file",
1446
+ line: +match[2],
1447
+ column: encodeUTF8(lineText.slice(0, column)).length,
1448
+ length: encodeUTF8(lineText.slice(column, column + length)).length,
1449
+ lineText: lineText + "\n" + lines.slice(1).join("\n"),
1450
+ suggestion: ""
1451
+ };
1452
+ }
1453
+ break;
1454
+ }
1455
+ }
1456
+ }
1457
+ return null;
1458
+ }
1459
+ function failureErrorWithLog(text, errors, warnings) {
1460
+ let limit = 5;
1461
+ let summary = errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
1462
+ if (i === limit)
1463
+ return "\n...";
1464
+ if (!e.location)
1465
+ return `
1466
+ error: ${e.text}`;
1467
+ let { file, line, column } = e.location;
1468
+ let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
1469
+ return `
1470
+ ${file}:${line}:${column}: error: ${pluginText}${e.text}`;
1471
+ }).join("");
1472
+ let error = new Error(`${text}${summary}`);
1473
+ error.errors = errors;
1474
+ error.warnings = warnings;
1475
+ return error;
1476
+ }
1477
+ function replaceDetailsInMessages(messages, stash) {
1478
+ for (const message of messages) {
1479
+ message.detail = stash.load(message.detail);
1480
+ }
1481
+ return messages;
1482
+ }
1483
+ function sanitizeLocation(location, where) {
1484
+ if (location == null)
1485
+ return null;
1486
+ let keys = {};
1487
+ let file = getFlag(location, keys, "file", mustBeString);
1488
+ let namespace = getFlag(location, keys, "namespace", mustBeString);
1489
+ let line = getFlag(location, keys, "line", mustBeInteger);
1490
+ let column = getFlag(location, keys, "column", mustBeInteger);
1491
+ let length = getFlag(location, keys, "length", mustBeInteger);
1492
+ let lineText = getFlag(location, keys, "lineText", mustBeString);
1493
+ let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1494
+ checkForInvalidFlags(location, keys, where);
1495
+ return {
1496
+ file: file || "",
1497
+ namespace: namespace || "",
1498
+ line: line || 0,
1499
+ column: column || 0,
1500
+ length: length || 0,
1501
+ lineText: lineText || "",
1502
+ suggestion: suggestion || ""
1503
+ };
1504
+ }
1505
+ function sanitizeMessages(messages, property, stash, fallbackPluginName) {
1506
+ let messagesClone = [];
1507
+ let index = 0;
1508
+ for (const message of messages) {
1509
+ let keys = {};
1510
+ let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1511
+ let text = getFlag(message, keys, "text", mustBeString);
1512
+ let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1513
+ let notes = getFlag(message, keys, "notes", mustBeArray);
1514
+ let detail = getFlag(message, keys, "detail", canBeAnything);
1515
+ let where = `in element ${index} of "${property}"`;
1516
+ checkForInvalidFlags(message, keys, where);
1517
+ let notesClone = [];
1518
+ if (notes) {
1519
+ for (const note of notes) {
1520
+ let noteKeys = {};
1521
+ let noteText = getFlag(note, noteKeys, "text", mustBeString);
1522
+ let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1523
+ checkForInvalidFlags(note, noteKeys, where);
1524
+ notesClone.push({
1525
+ text: noteText || "",
1526
+ location: sanitizeLocation(noteLocation, where)
1527
+ });
1528
+ }
1529
+ }
1530
+ messagesClone.push({
1531
+ pluginName: pluginName || fallbackPluginName,
1532
+ text: text || "",
1533
+ location: sanitizeLocation(location, where),
1534
+ notes: notesClone,
1535
+ detail: stash ? stash.store(detail) : -1
1536
+ });
1537
+ index++;
1538
+ }
1539
+ return messagesClone;
1540
+ }
1541
+ function sanitizeStringArray(values, property) {
1542
+ const result = [];
1543
+ for (const value of values) {
1544
+ if (typeof value !== "string")
1545
+ throw new Error(`${JSON.stringify(property)} must be an array of strings`);
1546
+ result.push(value);
1547
+ }
1548
+ return result;
1549
+ }
1550
+ function convertOutputFiles({ path, contents }) {
1551
+ let text = null;
1552
+ return {
1553
+ path,
1554
+ contents,
1555
+ get text() {
1556
+ if (text === null)
1557
+ text = decodeUTF8(contents);
1558
+ return text;
1559
+ }
1560
+ };
1561
+ }
1562
+
1563
+ // lib/npm/browser.ts
1564
+ var version = "0.12.25";
1565
+ var build = (options) => ensureServiceIsRunning().build(options);
1566
+ var serve = () => {
1567
+ throw new Error(`The "serve" API only works in node`);
1568
+ };
1569
+ var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
1570
+ var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
1571
+ var buildSync = () => {
1572
+ throw new Error(`The "buildSync" API only works in node`);
1573
+ };
1574
+ var transformSync = () => {
1575
+ throw new Error(`The "transformSync" API only works in node`);
1576
+ };
1577
+ var formatMessagesSync = () => {
1578
+ throw new Error(`The "formatMessagesSync" API only works in node`);
1579
+ };
1580
+ var initializePromise;
1581
+ var longLivedService;
1582
+ var ensureServiceIsRunning = () => {
1583
+ if (longLivedService)
1584
+ return longLivedService;
1585
+ if (initializePromise)
1586
+ throw new Error('You need to wait for the promise returned from "initialize" to be resolved before calling this');
1587
+ throw new Error('You need to call "initialize" before calling this');
1588
+ };
1589
+ var initialize = (options) => {
1590
+ options = validateInitializeOptions(options || {});
1591
+ let wasmURL = options.wasmURL;
1592
+ let useWorker = options.worker !== false;
1593
+ if (!wasmURL)
1594
+ throw new Error('Must provide the "wasmURL" option');
1595
+ wasmURL += "";
1596
+ if (initializePromise)
1597
+ throw new Error('Cannot call "initialize" more than once');
1598
+ initializePromise = startRunningService(wasmURL, useWorker);
1599
+ initializePromise.catch(() => {
1600
+ initializePromise = void 0;
1601
+ });
1602
+ return initializePromise;
1603
+ };
1604
+ var startRunningService = (wasmURL, useWorker) => __async(void 0, null, function* () {
1605
+ let res = yield fetch(wasmURL);
1606
+ if (!res.ok)
1607
+ throw new Error(`Failed to download ${JSON.stringify(wasmURL)}`);
1608
+ let wasm = yield res.arrayBuffer();
1609
+ let code = `{let global={};for(let o=self;o;o=Object.getPrototypeOf(o))for(let k of Object.getOwnPropertyNames(o))if(!(k in global))Object.defineProperty(global,k,{get:()=>self[k]});// Copyright 2018 The Go Authors. All rights reserved.
1610
+ // Use of this source code is governed by a BSD-style
1611
+ // license that can be found in the LICENSE file.
1612
+
1613
+ (() => {
1614
+ // Map multiple JavaScript environments to a single common API,
1615
+ // preferring web standards over Node.js API.
1616
+ //
1617
+ // Environments considered:
1618
+ // - Browsers
1619
+ // - Node.js
1620
+ // - Electron
1621
+ // - Parcel
1622
+ // - Webpack
1623
+
1624
+ if (typeof global !== "undefined") {
1625
+ // global already exists
1626
+ } else if (typeof window !== "undefined") {
1627
+ window.global = window;
1628
+ } else if (typeof self !== "undefined") {
1629
+ self.global = self;
1630
+ } else {
1631
+ throw new Error("cannot export Go (neither global, window nor self is defined)");
1632
+ }
1633
+
1634
+ if (!global.require && typeof require !== "undefined") {
1635
+ global.require = require;
1636
+ }
1637
+
1638
+ if (!global.fs && global.require) {
1639
+ const fs = require("fs");
1640
+ if (typeof fs === "object" && fs !== null && Object.keys(fs).length !== 0) {
1641
+
1642
+ global.fs = Object.assign({}, fs, {
1643
+ // Hack around a Unicode bug in node: https://github.com/nodejs/node/issues/24550
1644
+ write(fd, buf, offset, length, position, callback) {
1645
+ if (offset === 0 && length === buf.length && position === null) {
1646
+ if (fd === process.stdout.fd) {
1647
+ try {
1648
+ process.stdout.write(buf, err => err ? callback(err, 0, null) : callback(null, length, buf));
1649
+ } catch (err) {
1650
+ callback(err, 0, null);
1651
+ }
1652
+ return;
1653
+ }
1654
+ if (fd === process.stderr.fd) {
1655
+ try {
1656
+ process.stderr.write(buf, err => err ? callback(err, 0, null) : callback(null, length, buf));
1657
+ } catch (err) {
1658
+ callback(err, 0, null);
1659
+ }
1660
+ return;
1661
+ }
1662
+ }
1663
+ fs.write(fd, buf, offset, length, position, callback);
1664
+ },
1665
+ });
1666
+
1667
+ }
1668
+ }
1669
+
1670
+ const enosys = () => {
1671
+ const err = new Error("not implemented");
1672
+ err.code = "ENOSYS";
1673
+ return err;
1674
+ };
1675
+
1676
+ if (!global.fs) {
1677
+ let outputBuf = "";
1678
+ global.fs = {
1679
+ constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused
1680
+ writeSync(fd, buf) {
1681
+ outputBuf += decoder.decode(buf);
1682
+ const nl = outputBuf.lastIndexOf("\\n");
1683
+ if (nl != -1) {
1684
+ console.log(outputBuf.substr(0, nl));
1685
+ outputBuf = outputBuf.substr(nl + 1);
1686
+ }
1687
+ return buf.length;
1688
+ },
1689
+ write(fd, buf, offset, length, position, callback) {
1690
+ if (offset !== 0 || length !== buf.length || position !== null) {
1691
+ callback(enosys());
1692
+ return;
1693
+ }
1694
+ const n = this.writeSync(fd, buf);
1695
+ callback(null, n);
1696
+ },
1697
+ chmod(path, mode, callback) { callback(enosys()); },
1698
+ chown(path, uid, gid, callback) { callback(enosys()); },
1699
+ close(fd, callback) { callback(enosys()); },
1700
+ fchmod(fd, mode, callback) { callback(enosys()); },
1701
+ fchown(fd, uid, gid, callback) { callback(enosys()); },
1702
+ fstat(fd, callback) { callback(enosys()); },
1703
+ fsync(fd, callback) { callback(null); },
1704
+ ftruncate(fd, length, callback) { callback(enosys()); },
1705
+ lchown(path, uid, gid, callback) { callback(enosys()); },
1706
+ link(path, link, callback) { callback(enosys()); },
1707
+ lstat(path, callback) { callback(enosys()); },
1708
+ mkdir(path, perm, callback) { callback(enosys()); },
1709
+ open(path, flags, mode, callback) { callback(enosys()); },
1710
+ read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
1711
+ readdir(path, callback) { callback(enosys()); },
1712
+ readlink(path, callback) { callback(enosys()); },
1713
+ rename(from, to, callback) { callback(enosys()); },
1714
+ rmdir(path, callback) { callback(enosys()); },
1715
+ stat(path, callback) { callback(enosys()); },
1716
+ symlink(path, link, callback) { callback(enosys()); },
1717
+ truncate(path, length, callback) { callback(enosys()); },
1718
+ unlink(path, callback) { callback(enosys()); },
1719
+ utimes(path, atime, mtime, callback) { callback(enosys()); },
1720
+ };
1721
+ }
1722
+
1723
+ if (!global.process) {
1724
+ global.process = {
1725
+ getuid() { return -1; },
1726
+ getgid() { return -1; },
1727
+ geteuid() { return -1; },
1728
+ getegid() { return -1; },
1729
+ getgroups() { throw enosys(); },
1730
+ pid: -1,
1731
+ ppid: -1,
1732
+ umask() { throw enosys(); },
1733
+ cwd() { throw enosys(); },
1734
+ chdir() { throw enosys(); },
1735
+ }
1736
+ }
1737
+
1738
+ if (!global.crypto && global.require) {
1739
+ const nodeCrypto = require("crypto");
1740
+ global.crypto = {
1741
+ getRandomValues(b) {
1742
+ nodeCrypto.randomFillSync(b);
1743
+ },
1744
+ };
1745
+ }
1746
+ if (!global.crypto) {
1747
+ throw new Error("global.crypto is not available, polyfill required (getRandomValues only)");
1748
+ }
1749
+
1750
+ if (!global.performance) {
1751
+ global.performance = {
1752
+ now() {
1753
+ const [sec, nsec] = process.hrtime();
1754
+ return sec * 1000 + nsec / 1000000;
1755
+ },
1756
+ };
1757
+ }
1758
+
1759
+ if (!global.TextEncoder && global.require) {
1760
+ global.TextEncoder = require("util").TextEncoder;
1761
+ }
1762
+ if (!global.TextEncoder) {
1763
+ throw new Error("global.TextEncoder is not available, polyfill required");
1764
+ }
1765
+
1766
+ if (!global.TextDecoder && global.require) {
1767
+ global.TextDecoder = require("util").TextDecoder;
1768
+ }
1769
+ if (!global.TextDecoder) {
1770
+ throw new Error("global.TextDecoder is not available, polyfill required");
1771
+ }
1772
+
1773
+ // End of polyfills for common API.
1774
+
1775
+ const encoder = new TextEncoder("utf-8");
1776
+ const decoder = new TextDecoder("utf-8");
1777
+
1778
+ global.Go = class {
1779
+ constructor() {
1780
+ this.argv = ["js"];
1781
+ this.env = {};
1782
+ this.exit = (code) => {
1783
+ if (code !== 0) {
1784
+ console.warn("exit code:", code);
1785
+ }
1786
+ };
1787
+ this._exitPromise = new Promise((resolve) => {
1788
+ this._resolveExitPromise = resolve;
1789
+ });
1790
+ this._pendingEvent = null;
1791
+ this._scheduledTimeouts = new Map();
1792
+ this._nextCallbackTimeoutID = 1;
1793
+
1794
+ const setInt64 = (addr, v) => {
1795
+ this.mem.setUint32(addr + 0, v, true);
1796
+ this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
1797
+ }
1798
+
1799
+ const getInt64 = (addr) => {
1800
+ const low = this.mem.getUint32(addr + 0, true);
1801
+ const high = this.mem.getInt32(addr + 4, true);
1802
+ return low + high * 4294967296;
1803
+ }
1804
+
1805
+ const loadValue = (addr) => {
1806
+ const f = this.mem.getFloat64(addr, true);
1807
+ if (f === 0) {
1808
+ return undefined;
1809
+ }
1810
+ if (!isNaN(f)) {
1811
+ return f;
1812
+ }
1813
+
1814
+ const id = this.mem.getUint32(addr, true);
1815
+ return this._values[id];
1816
+ }
1817
+
1818
+ const storeValue = (addr, v) => {
1819
+ const nanHead = 0x7FF80000;
1820
+
1821
+ if (typeof v === "number" && v !== 0) {
1822
+ if (isNaN(v)) {
1823
+ this.mem.setUint32(addr + 4, nanHead, true);
1824
+ this.mem.setUint32(addr, 0, true);
1825
+ return;
1826
+ }
1827
+ this.mem.setFloat64(addr, v, true);
1828
+ return;
1829
+ }
1830
+
1831
+ if (v === undefined) {
1832
+ this.mem.setFloat64(addr, 0, true);
1833
+ return;
1834
+ }
1835
+
1836
+ let id = this._ids.get(v);
1837
+ if (id === undefined) {
1838
+ id = this._idPool.pop();
1839
+ if (id === undefined) {
1840
+ id = this._values.length;
1841
+ }
1842
+ this._values[id] = v;
1843
+ this._goRefCounts[id] = 0;
1844
+ this._ids.set(v, id);
1845
+ }
1846
+ this._goRefCounts[id]++;
1847
+ let typeFlag = 0;
1848
+ switch (typeof v) {
1849
+ case "object":
1850
+ if (v !== null) {
1851
+ typeFlag = 1;
1852
+ }
1853
+ break;
1854
+ case "string":
1855
+ typeFlag = 2;
1856
+ break;
1857
+ case "symbol":
1858
+ typeFlag = 3;
1859
+ break;
1860
+ case "function":
1861
+ typeFlag = 4;
1862
+ break;
1863
+ }
1864
+ this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
1865
+ this.mem.setUint32(addr, id, true);
1866
+ }
1867
+
1868
+ const loadSlice = (addr) => {
1869
+ const array = getInt64(addr + 0);
1870
+ const len = getInt64(addr + 8);
1871
+ return new Uint8Array(this._inst.exports.mem.buffer, array, len);
1872
+ }
1873
+
1874
+ const loadSliceOfValues = (addr) => {
1875
+ const array = getInt64(addr + 0);
1876
+ const len = getInt64(addr + 8);
1877
+ const a = new Array(len);
1878
+ for (let i = 0; i < len; i++) {
1879
+ a[i] = loadValue(array + i * 8);
1880
+ }
1881
+ return a;
1882
+ }
1883
+
1884
+ const loadString = (addr) => {
1885
+ const saddr = getInt64(addr + 0);
1886
+ const len = getInt64(addr + 8);
1887
+ return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
1888
+ }
1889
+
1890
+ const timeOrigin = Date.now() - performance.now();
1891
+ this.importObject = {
1892
+ go: {
1893
+ // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
1894
+ // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
1895
+ // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
1896
+ // This changes the SP, thus we have to update the SP used by the imported function.
1897
+
1898
+ // func wasmExit(code int32)
1899
+ "runtime.wasmExit": (sp) => {
1900
+ sp >>>= 0;
1901
+ const code = this.mem.getInt32(sp + 8, true);
1902
+ this.exited = true;
1903
+ delete this._inst;
1904
+ delete this._values;
1905
+ delete this._goRefCounts;
1906
+ delete this._ids;
1907
+ delete this._idPool;
1908
+ this.exit(code);
1909
+ },
1910
+
1911
+ // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
1912
+ "runtime.wasmWrite": (sp) => {
1913
+ sp >>>= 0;
1914
+ const fd = getInt64(sp + 8);
1915
+ const p = getInt64(sp + 16);
1916
+ const n = this.mem.getInt32(sp + 24, true);
1917
+ fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
1918
+ },
1919
+
1920
+ // func resetMemoryDataView()
1921
+ "runtime.resetMemoryDataView": (sp) => {
1922
+ sp >>>= 0;
1923
+ this.mem = new DataView(this._inst.exports.mem.buffer);
1924
+ },
1925
+
1926
+ // func nanotime1() int64
1927
+ "runtime.nanotime1": (sp) => {
1928
+ sp >>>= 0;
1929
+ setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
1930
+ },
1931
+
1932
+ // func walltime() (sec int64, nsec int32)
1933
+ "runtime.walltime": (sp) => {
1934
+ sp >>>= 0;
1935
+ const msec = (new Date).getTime();
1936
+ setInt64(sp + 8, msec / 1000);
1937
+ this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
1938
+ },
1939
+
1940
+ // func scheduleTimeoutEvent(delay int64) int32
1941
+ "runtime.scheduleTimeoutEvent": (sp) => {
1942
+ sp >>>= 0;
1943
+ const id = this._nextCallbackTimeoutID;
1944
+ this._nextCallbackTimeoutID++;
1945
+ this._scheduledTimeouts.set(id, setTimeout(
1946
+ () => {
1947
+ this._resume();
1948
+ while (this._scheduledTimeouts.has(id)) {
1949
+ // for some reason Go failed to register the timeout event, log and try again
1950
+ // (temporary workaround for https://github.com/golang/go/issues/28975)
1951
+ console.warn("scheduleTimeoutEvent: missed timeout event");
1952
+ this._resume();
1953
+ }
1954
+ },
1955
+ getInt64(sp + 8) + 1, // setTimeout has been seen to fire up to 1 millisecond early
1956
+ ));
1957
+ this.mem.setInt32(sp + 16, id, true);
1958
+ },
1959
+
1960
+ // func clearTimeoutEvent(id int32)
1961
+ "runtime.clearTimeoutEvent": (sp) => {
1962
+ sp >>>= 0;
1963
+ const id = this.mem.getInt32(sp + 8, true);
1964
+ clearTimeout(this._scheduledTimeouts.get(id));
1965
+ this._scheduledTimeouts.delete(id);
1966
+ },
1967
+
1968
+ // func getRandomData(r []byte)
1969
+ "runtime.getRandomData": (sp) => {
1970
+ sp >>>= 0;
1971
+ crypto.getRandomValues(loadSlice(sp + 8));
1972
+ },
1973
+
1974
+ // func finalizeRef(v ref)
1975
+ "syscall/js.finalizeRef": (sp) => {
1976
+ sp >>>= 0;
1977
+ const id = this.mem.getUint32(sp + 8, true);
1978
+ this._goRefCounts[id]--;
1979
+ if (this._goRefCounts[id] === 0) {
1980
+ const v = this._values[id];
1981
+ this._values[id] = null;
1982
+ this._ids.delete(v);
1983
+ this._idPool.push(id);
1984
+ }
1985
+ },
1986
+
1987
+ // func stringVal(value string) ref
1988
+ "syscall/js.stringVal": (sp) => {
1989
+ sp >>>= 0;
1990
+ storeValue(sp + 24, loadString(sp + 8));
1991
+ },
1992
+
1993
+ // func valueGet(v ref, p string) ref
1994
+ "syscall/js.valueGet": (sp) => {
1995
+ sp >>>= 0;
1996
+ const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
1997
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
1998
+ storeValue(sp + 32, result);
1999
+ },
2000
+
2001
+ // func valueSet(v ref, p string, x ref)
2002
+ "syscall/js.valueSet": (sp) => {
2003
+ sp >>>= 0;
2004
+ Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
2005
+ },
2006
+
2007
+ // func valueDelete(v ref, p string)
2008
+ "syscall/js.valueDelete": (sp) => {
2009
+ sp >>>= 0;
2010
+ Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
2011
+ },
2012
+
2013
+ // func valueIndex(v ref, i int) ref
2014
+ "syscall/js.valueIndex": (sp) => {
2015
+ sp >>>= 0;
2016
+ storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
2017
+ },
2018
+
2019
+ // valueSetIndex(v ref, i int, x ref)
2020
+ "syscall/js.valueSetIndex": (sp) => {
2021
+ sp >>>= 0;
2022
+ Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
2023
+ },
2024
+
2025
+ // func valueCall(v ref, m string, args []ref) (ref, bool)
2026
+ "syscall/js.valueCall": (sp) => {
2027
+ sp >>>= 0;
2028
+ try {
2029
+ const v = loadValue(sp + 8);
2030
+ const m = Reflect.get(v, loadString(sp + 16));
2031
+ const args = loadSliceOfValues(sp + 32);
2032
+ const result = Reflect.apply(m, v, args);
2033
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
2034
+ storeValue(sp + 56, result);
2035
+ this.mem.setUint8(sp + 64, 1);
2036
+ } catch (err) {
2037
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
2038
+ storeValue(sp + 56, err);
2039
+ this.mem.setUint8(sp + 64, 0);
2040
+ }
2041
+ },
2042
+
2043
+ // func valueInvoke(v ref, args []ref) (ref, bool)
2044
+ "syscall/js.valueInvoke": (sp) => {
2045
+ sp >>>= 0;
2046
+ try {
2047
+ const v = loadValue(sp + 8);
2048
+ const args = loadSliceOfValues(sp + 16);
2049
+ const result = Reflect.apply(v, undefined, args);
2050
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
2051
+ storeValue(sp + 40, result);
2052
+ this.mem.setUint8(sp + 48, 1);
2053
+ } catch (err) {
2054
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
2055
+ storeValue(sp + 40, err);
2056
+ this.mem.setUint8(sp + 48, 0);
2057
+ }
2058
+ },
2059
+
2060
+ // func valueNew(v ref, args []ref) (ref, bool)
2061
+ "syscall/js.valueNew": (sp) => {
2062
+ sp >>>= 0;
2063
+ try {
2064
+ const v = loadValue(sp + 8);
2065
+ const args = loadSliceOfValues(sp + 16);
2066
+ const result = Reflect.construct(v, args);
2067
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
2068
+ storeValue(sp + 40, result);
2069
+ this.mem.setUint8(sp + 48, 1);
2070
+ } catch (err) {
2071
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
2072
+ storeValue(sp + 40, err);
2073
+ this.mem.setUint8(sp + 48, 0);
2074
+ }
2075
+ },
2076
+
2077
+ // func valueLength(v ref) int
2078
+ "syscall/js.valueLength": (sp) => {
2079
+ sp >>>= 0;
2080
+ setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
2081
+ },
2082
+
2083
+ // valuePrepareString(v ref) (ref, int)
2084
+ "syscall/js.valuePrepareString": (sp) => {
2085
+ sp >>>= 0;
2086
+ const str = encoder.encode(String(loadValue(sp + 8)));
2087
+ storeValue(sp + 16, str);
2088
+ setInt64(sp + 24, str.length);
2089
+ },
2090
+
2091
+ // valueLoadString(v ref, b []byte)
2092
+ "syscall/js.valueLoadString": (sp) => {
2093
+ sp >>>= 0;
2094
+ const str = loadValue(sp + 8);
2095
+ loadSlice(sp + 16).set(str);
2096
+ },
2097
+
2098
+ // func valueInstanceOf(v ref, t ref) bool
2099
+ "syscall/js.valueInstanceOf": (sp) => {
2100
+ sp >>>= 0;
2101
+ this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
2102
+ },
2103
+
2104
+ // func copyBytesToGo(dst []byte, src ref) (int, bool)
2105
+ "syscall/js.copyBytesToGo": (sp) => {
2106
+ sp >>>= 0;
2107
+ const dst = loadSlice(sp + 8);
2108
+ const src = loadValue(sp + 32);
2109
+ if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
2110
+ this.mem.setUint8(sp + 48, 0);
2111
+ return;
2112
+ }
2113
+ const toCopy = src.subarray(0, dst.length);
2114
+ dst.set(toCopy);
2115
+ setInt64(sp + 40, toCopy.length);
2116
+ this.mem.setUint8(sp + 48, 1);
2117
+ },
2118
+
2119
+ // func copyBytesToJS(dst ref, src []byte) (int, bool)
2120
+ "syscall/js.copyBytesToJS": (sp) => {
2121
+ sp >>>= 0;
2122
+ const dst = loadValue(sp + 8);
2123
+ const src = loadSlice(sp + 16);
2124
+ if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
2125
+ this.mem.setUint8(sp + 48, 0);
2126
+ return;
2127
+ }
2128
+ const toCopy = src.subarray(0, dst.length);
2129
+ dst.set(toCopy);
2130
+ setInt64(sp + 40, toCopy.length);
2131
+ this.mem.setUint8(sp + 48, 1);
2132
+ },
2133
+
2134
+ "debug": (value) => {
2135
+ console.log(value);
2136
+ },
2137
+ }
2138
+ };
2139
+ }
2140
+
2141
+ async run(instance) {
2142
+ if (!(instance instanceof WebAssembly.Instance)) {
2143
+ throw new Error("Go.run: WebAssembly.Instance expected");
2144
+ }
2145
+ this._inst = instance;
2146
+ this.mem = new DataView(this._inst.exports.mem.buffer);
2147
+ this._values = [ // JS values that Go currently has references to, indexed by reference id
2148
+ NaN,
2149
+ 0,
2150
+ null,
2151
+ true,
2152
+ false,
2153
+ global,
2154
+ this,
2155
+ ];
2156
+ this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
2157
+ this._ids = new Map([ // mapping from JS values to reference ids
2158
+ [0, 1],
2159
+ [null, 2],
2160
+ [true, 3],
2161
+ [false, 4],
2162
+ [global, 5],
2163
+ [this, 6],
2164
+ ]);
2165
+ this._idPool = []; // unused ids that have been garbage collected
2166
+ this.exited = false; // whether the Go program has exited
2167
+
2168
+ // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
2169
+ let offset = 4096;
2170
+
2171
+ const strPtr = (str) => {
2172
+ const ptr = offset;
2173
+ const bytes = encoder.encode(str + "\\0");
2174
+ new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
2175
+ offset += bytes.length;
2176
+ if (offset % 8 !== 0) {
2177
+ offset += 8 - (offset % 8);
2178
+ }
2179
+ return ptr;
2180
+ };
2181
+
2182
+ const argc = this.argv.length;
2183
+
2184
+ const argvPtrs = [];
2185
+ this.argv.forEach((arg) => {
2186
+ argvPtrs.push(strPtr(arg));
2187
+ });
2188
+ argvPtrs.push(0);
2189
+
2190
+ const keys = Object.keys(this.env).sort();
2191
+ keys.forEach((key) => {
2192
+ argvPtrs.push(strPtr(\`\${key}=\${this.env[key]}\`));
2193
+ });
2194
+ argvPtrs.push(0);
2195
+
2196
+ const argv = offset;
2197
+ argvPtrs.forEach((ptr) => {
2198
+ this.mem.setUint32(offset, ptr, true);
2199
+ this.mem.setUint32(offset + 4, 0, true);
2200
+ offset += 8;
2201
+ });
2202
+
2203
+ this._inst.exports.run(argc, argv);
2204
+ if (this.exited) {
2205
+ this._resolveExitPromise();
2206
+ }
2207
+ await this._exitPromise;
2208
+ }
2209
+
2210
+ _resume() {
2211
+ if (this.exited) {
2212
+ throw new Error("Go program has already exited");
2213
+ }
2214
+ this._inst.exports.resume();
2215
+ if (this.exited) {
2216
+ this._resolveExitPromise();
2217
+ }
2218
+ }
2219
+
2220
+ _makeFuncWrapper(id) {
2221
+ const go = this;
2222
+ return function () {
2223
+ const event = { id: id, this: this, args: arguments };
2224
+ go._pendingEvent = event;
2225
+ go._resume();
2226
+ return event.result;
2227
+ };
2228
+ }
2229
+ }
2230
+
2231
+ if (
2232
+ typeof module !== "undefined" &&
2233
+ global.require &&
2234
+ global.require.main === module &&
2235
+ global.process &&
2236
+ global.process.versions &&
2237
+ !global.process.versions.electron
2238
+ ) {
2239
+ if (process.argv.length < 3) {
2240
+ console.error("usage: go_js_wasm_exec [wasm binary] [arguments]");
2241
+ process.exit(1);
2242
+ }
2243
+
2244
+ const go = new Go();
2245
+ go.argv = process.argv.slice(2);
2246
+ go.env = Object.assign({ TMPDIR: require("os").tmpdir() }, process.env);
2247
+ go.exit = process.exit;
2248
+ WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => {
2249
+ process.on("exit", (code) => { // Node.js exits if no event handler is pending
2250
+ if (code === 0 && !go.exited) {
2251
+ // deadlock, make Go print error and stack traces
2252
+ go._pendingEvent = { id: 0 };
2253
+ go._resume();
2254
+ }
2255
+ });
2256
+ return go.run(result.instance);
2257
+ }).catch((err) => {
2258
+ console.error(err);
2259
+ process.exit(1);
2260
+ });
2261
+ }
2262
+ })();
2263
+ onmessage = ({ data: wasm }) => {
2264
+ let decoder = new TextDecoder();
2265
+ let fs = global.fs;
2266
+ let stderr = "";
2267
+ fs.writeSync = (fd, buffer) => {
2268
+ if (fd === 1) {
2269
+ postMessage(buffer);
2270
+ } else if (fd === 2) {
2271
+ stderr += decoder.decode(buffer);
2272
+ let parts = stderr.split("\\n");
2273
+ if (parts.length > 1)
2274
+ console.log(parts.slice(0, -1).join("\\n"));
2275
+ stderr = parts[parts.length - 1];
2276
+ } else {
2277
+ throw new Error("Bad write");
2278
+ }
2279
+ return buffer.length;
2280
+ };
2281
+ let stdin = [];
2282
+ let resumeStdin;
2283
+ let stdinPos = 0;
2284
+ onmessage = ({ data }) => {
2285
+ if (data.length > 0) {
2286
+ stdin.push(data);
2287
+ if (resumeStdin)
2288
+ resumeStdin();
2289
+ }
2290
+ };
2291
+ fs.read = (fd, buffer, offset, length, position, callback) => {
2292
+ if (fd !== 0 || offset !== 0 || length !== buffer.length || position !== null) {
2293
+ throw new Error("Bad read");
2294
+ }
2295
+ if (stdin.length === 0) {
2296
+ resumeStdin = () => fs.read(fd, buffer, offset, length, position, callback);
2297
+ return;
2298
+ }
2299
+ let first = stdin[0];
2300
+ let count = Math.max(0, Math.min(length, first.length - stdinPos));
2301
+ buffer.set(first.subarray(stdinPos, stdinPos + count), offset);
2302
+ stdinPos += count;
2303
+ if (stdinPos === first.length) {
2304
+ stdin.shift();
2305
+ stdinPos = 0;
2306
+ }
2307
+ callback(null, count);
2308
+ };
2309
+ let go = new global.Go();
2310
+ go.argv = ["", \`--service=\${"0.12.25"}\`];
2311
+ WebAssembly.instantiate(wasm, go.importObject).then(({ instance }) => go.run(instance));
2312
+ };}`;
2313
+ let worker;
2314
+ if (useWorker) {
2315
+ let blob = new Blob([code], { type: "text/javascript" });
2316
+ worker = new Worker(URL.createObjectURL(blob));
2317
+ } else {
2318
+ let fn = new Function("postMessage", code + `var onmessage; return m => onmessage(m)`);
2319
+ let onmessage = fn((data) => worker.onmessage({ data }));
2320
+ worker = {
2321
+ onmessage: null,
2322
+ postMessage: (data) => onmessage({ data }),
2323
+ terminate() {
2324
+ }
2325
+ };
2326
+ }
2327
+ worker.postMessage(wasm);
2328
+ worker.onmessage = ({ data }) => readFromStdout(data);
2329
+ let { readFromStdout, service } = createChannel({
2330
+ writeToStdin(bytes) {
2331
+ worker.postMessage(bytes);
2332
+ },
2333
+ isSync: false,
2334
+ isBrowser: true
2335
+ });
2336
+ longLivedService = {
2337
+ build: (options) => new Promise((resolve, reject) => service.buildOrServe({
2338
+ callName: "build",
2339
+ refs: null,
2340
+ serveOptions: null,
2341
+ options,
2342
+ isTTY: false,
2343
+ defaultWD: "/",
2344
+ callback: (err, res2) => err ? reject(err) : resolve(res2)
2345
+ })),
2346
+ transform: (input, options) => new Promise((resolve, reject) => service.transform({
2347
+ callName: "transform",
2348
+ refs: null,
2349
+ input,
2350
+ options: options || {},
2351
+ isTTY: false,
2352
+ fs: {
2353
+ readFile(_, callback) {
2354
+ callback(new Error("Internal error"), null);
2355
+ },
2356
+ writeFile(_, callback) {
2357
+ callback(null);
2358
+ }
2359
+ },
2360
+ callback: (err, res2) => err ? reject(err) : resolve(res2)
2361
+ })),
2362
+ formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
2363
+ callName: "formatMessages",
2364
+ refs: null,
2365
+ messages,
2366
+ options,
2367
+ callback: (err, res2) => err ? reject(err) : resolve(res2)
2368
+ }))
2369
+ };
2370
+ });
2371
+ })(typeof exports==="object"?exports:(typeof self!=="undefined"?self:this).esbuild={});