toilscript 0.1.58 → 0.1.60
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.
- package/dist/cli.js +615 -20
- package/dist/cli.js.map +2 -2
- package/dist/importmap.json +3 -3
- package/dist/web.js +4 -4
- package/package.json +11 -9
- package/std/assembly/bindings/daemon.ts +69 -0
- package/std/assembly/bindings/toildb.ts +1 -1
- package/std/assembly/bindings/webcrypto.ts +48 -0
- package/std/assembly/daemon.ts +315 -0
- package/std/assembly/toildb.ts +178 -15
- package/std/assembly/toilscript.d.ts +130 -6
package/dist/cli.js
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
* Copyright 2026 Daniel Wirtz / The ToilScript Authors
|
|
5
5
|
* SPDX-License-Identifier: Apache-2.0
|
|
6
6
|
*/
|
|
7
|
-
var le=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var dn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(a){throw n=[a],a}};var nn=(e,t)=>{for(var n in t)le(e,n,{get:t[n],enumerable:!0})},se=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Pe(t))!Ve.call(e,s)&&s!==n&&le(e,s,{get:()=>t[s],enumerable:!(a=Me(t,s))||a.enumerable});return e},In=(e,t,n)=>(se(e,t,"default"),n&&se(n,t,"default"));var ue={};nn(ue,{promises:()=>
|
|
8
|
-
`,o={},c=[];Object.keys(e).forEach(b=>{var p=e[b];if(p.description!=null){for(var g="";g.length<n;)g+=" ";for(g+="--"+b,p.alias&&(g+=", -"+p.alias);g.length<a;)g+=" ";var y;!t.noCategories&&p.category?(y=o[p.category])||(o[p.category]=y=[]):y=c,Array.isArray(p.description)?y.push(g+p.description[0]+p.description.slice(1).map(m=>{for(let i=0;i<a;++i)m=" "+m;return s+m}).join("")):y.push(g+p.description)}});var d=[],x=!1;return Object.keys(o).forEach(b=>{x=!0,d.push(s+" "+Tn.gray(b)+s),d.push(o[b].join(s))}),x&&c.length&&d.push(s+" "+Tn.gray("Other")+s),d.push(c.join(s)),d.join(s)}function ye(e,t){if(e!=null)switch(t){case void 0:case"b":return!!e;case"i":return Math.trunc(e)||0;case"f":return Number(e)||0;case"s":return e===!0?"":e===!1?null:String(e);case"I":return Array.isArray(e)||(e=[e]),e.map(n=>Math.trunc(n)||0);case"F":return Array.isArray(e)||(e=[e]),e.map(n=>Number(n)||0);case"S":return Array.isArray(e)||(e=[e]),e.map(String)}}function Mn(e,t,n,a){let s={};for(let[o,{type:c,mutuallyExclusive:d,isPath:x,useNodeResolution:b,cliOnly:p}]of Object.entries(e)){let g=ye(t[o],c),y=ye(n[o],c);if(g==null){if(y!=null){if(p)continue;if(Array.isArray(y)){let m;x&&(y=y.map(i=>tn(i,a,b))),d!=null&&(m=t[d])?s[o]=y.filter(i=>!m.includes(i)):s[o]=y.slice()}else x&&(y=tn(y,a,b)),s[o]=y}}else if(y==null)Array.isArray(g)?s[o]=g.slice():s[o]=g;else if(Array.isArray(g)){if(p){s[o]=g.slice();continue}let m;x&&(y=y.map(i=>tn(i,a,b))),d!=null&&(m=t[d])?s[o]=[...g,...y.filter(i=>!g.includes(i)&&!m.includes(i))]:s[o]=[...g,...y.filter(i=>!g.includes(i))]}else s[o]=g}return s}function Et(e){let t=E.parse(e);return t.root||(t.root="./"),E.format(t)}function tn(e,t,n=!1){return E.isAbsolute(e)?e:n&&!e.startsWith(".")&&be.resolve?be.resolve(e,{paths:[t]}):Et(E.join(t,e))}function Pn(e,t){for(let[n,{default:a}]of Object.entries(e))t[n]==null&&a!=null&&(t[n]=a)}var Ee="0.1.58",Y={version:{category:"General",description:"Prints just the compiler's version and exits.",type:"b",alias:"v"},help:{category:"General",description:"Prints this message and exits.",type:"b",alias:"h"},config:{category:"General",description:"Configuration file to apply. CLI arguments take precedence.",type:"s",cliOnly:!0},target:{category:"General",description:"Configuration file target to use. Defaults to 'release'.",type:"s",cliOnly:!0},targetMode:{category:"General",description:"Toil compile surface mode: 'hot' (request/stream) or 'cold' (daemon). Omit for the default request artifact.",type:"s"},authUser:{category:"General",description:"Built-in auth: inject the reserved toilUserId + username fields into the single @user (used by the toiljs server.auth build when the app declares its own @user).",type:"b"},noConfigEntries:{category:"General",description:"Ignore the toilconfig 'entries' array and compile ONLY the entry files given on the command line. Used by the toiljs multi-artifact build, which hands each pass (request/stream/daemon) its own entry subset.",type:"b"},optimize:{category:"Optimization",description:["Optimizes the module. Typical shorthands are:",""," Default optimizations -O"," Make a release build -O --noAssert"," Make a debug build --debug"," Optimize for speed -Ospeed"," Optimize for size -Osize",""],type:"b",alias:"O"},optimizeLevel:{category:"Optimization",description:"How much to focus on optimizing code. [0-3]",type:"i"},shrinkLevel:{category:"Optimization",description:"How much to focus on shrinking code size. [0-2, s=1, z=2]",type:"i"},converge:{category:"Optimization",description:"Re-optimizes until no further improvements can be made.",type:"b",default:!1},noAssert:{category:"Optimization",description:"Replaces assertions with just their value without trapping.",type:"b",default:!1},outFile:{category:"Output",description:"Specifies the WebAssembly output file (.wasm).",type:"s",alias:"o",isPath:!0},textFile:{category:"Output",description:"Specifies the WebAssembly text output file (.wat).",type:"s",alias:"t",isPath:!0},rpcModule:{category:"Output",description:"Emits a .ts module: the @data codec + the typed client-callable Server surface.",type:"s",isPath:!0},rpcSurfaceFiles:{category:"Output",description:"Files parsed for the rpc module's @rest/@stream client surface but NOT compiled into this artifact (folds a sibling tier's @stream classes into the Server surface).",type:"S",isPath:!0},rpcRuntime:{category:"Output",description:"Import specifier for the DataWriter/DataReader codec in the emitted RPC module.",type:"s",default:"toiljs/io"},bindings:{category:"Output",description:["Specifies the bindings to generate (.js + .d.ts).",""," esm JavaScript bindings & typings for ESM integration."," raw Like esm, but exports just the instantiate function."," Useful where modules are meant to be instantiated"," multiple times or non-ESM imports must be provided."],type:"S",alias:"b"},sourceMap:{category:"Debugging",description:["Enables source map generation. Optionally takes the URL","used to reference the source map from the binary file."],type:"s"},uncheckedBehavior:{category:"Debugging",description:["Changes the behavior of unchecked() expressions.","Using this option can potentially cause breakage.",""," default The default behavior: unchecked operations are"," only used inside of unchecked()."," never Unchecked operations are never used, even when"," inside of unchecked()."," always Unchecked operations are always used if possible,"," whether or not unchecked() is used."],type:"s",default:"default"},debug:{category:"Debugging",description:"Enables debug information in emitted binaries.",type:"b",default:!1},importMemory:{category:"Features",description:"Imports the memory from 'env.memory'.",type:"b",default:!1},noExportMemory:{category:"Features",description:"Does not export the memory as 'memory'.",type:"b",default:!1},initialMemory:{category:"Features",description:"Sets the initial memory size in pages.",type:"i",default:0},maximumMemory:{category:"Features",description:"Sets the maximum memory size in pages.",type:"i",default:0},sharedMemory:{category:"Features",description:"Declare memory as shared. Requires maximumMemory.",type:"b",default:!1},zeroFilledMemory:{category:"Features",description:"Assume imported memory is zeroed. Requires importMemory.",type:"b",default:!1},importTable:{category:"Features",description:"Imports the function table from 'env.table'.",type:"b",default:!1},exportTable:{category:"Features",description:"Exports the function table as 'table'.",type:"b",default:!1},exportStart:{category:"Features",description:["Exports the start function using the specified name instead","of calling it implicitly. Useful to obtain the exported memory","before executing any code accessing it."],type:"s"},runtime:{category:"Features",description:["Specifies the runtime variant to include in the program.",""," incremental TLSF + incremental GC (default)"," minimal TLSF + lightweight GC invoked externally"," stub Minimal runtime stub (never frees)"," ... Path to a custom runtime implementation",""],type:"s",default:"incremental"},exportRuntime:{category:"Features",description:["Always exports the runtime helpers (__new, __collect, __pin etc.).","Automatically determined when generation of --bindings is enabled."],type:"b",default:!1},stackSize:{category:"Features",description:["Overrides the stack size. Only relevant for incremental GC","or when using a custom runtime that requires stack space.","Defaults to 0 without and to 32768 with incremental GC."],default:0,type:"i"},enable:{category:"Features",description:["Enables WebAssembly features being disabled by default.",""," threads Threading and atomic operations."," simd SIMD types and operations."," reference-types Reference types and operations."," gc Garbage collection (WIP)."," stringref String reference types."," relaxed-simd Relaxed SIMD operations.",""],TODO_doesNothingYet:[" exception-handling Exception handling."," tail-calls Tail call operations."," multi-value Multi value types."," memory64 Memory64 operations."," extended-const Extended const expressions."],type:"S",mutuallyExclusive:"disable"},disable:{category:"Features",description:["Disables WebAssembly features being enabled by default.",""," mutable-globals Mutable global imports and exports."," sign-extension Sign-extension operations"," nontrapping-f2i Non-trapping float to integer ops."," bulk-memory Bulk memory operations.",""],type:"S",mutuallyExclusive:"enable"},use:{category:"Features",description:["Aliases a global object under another name, e.g., to switch","the default 'Math' implementation used: --use Math=JSMath","Can also be used to introduce an integer constant."],type:"S",alias:"u"},lowMemoryLimit:{category:"Features",description:"Enforces very low (<64k) memory constraints.",default:0,type:"i"},memoryBase:{category:"Linking",description:"Sets the start offset of emitted memory segments.",type:"i",default:0},tableBase:{category:"Linking",description:"Sets the start offset of emitted table elements.",type:"i",default:0},transform:{category:"API",description:"Specifies the path to a custom transform to load.",type:"S",isPath:!0,useNodeResolution:!0},trapMode:{category:"Binaryen",description:["Sets the trap mode to use.",""," allow Allow trapping operations. This is the default."," clamp Replace trapping operations with clamping semantics."," js Replace trapping operations with JS semantics.",""],type:"s",default:"allow"},runPasses:{category:"Binaryen",description:["Specifies additional Binaryen passes to run after other","optimizations, if any. See: Binaryen/src/passes/pass.cpp"],type:"s"},noValidate:{category:"Binaryen",description:"Skips validating the module using Binaryen.",type:"b",default:!1},baseDir:{description:"Specifies the base directory of input and output files.",type:"s",default:"."},noColors:{description:"Disables terminal colors.",type:"b",default:!1},noUnsafe:{description:["Disallows the use of unsafe features in user code.","Does not affect library files and external modules."],type:"b",default:!1},disableWarning:{description:["Disables warnings matching the given diagnostic code.","If no diagnostic code is given, all warnings are disabled."],type:"I"},noEmit:{description:"Performs compilation as usual but does not emit code.",type:"b",default:!1},showConfig:{description:"Print computed compiler options and exit.",type:"b",default:!1},stats:{description:"Prints statistics on I/O and compile times.",type:"b",default:!1},pedantic:{description:"Make yourself sad for no good reason.",type:"b",default:!1},lib:{description:["Adds one or multiple paths to custom library components and","uses exports of all top-level files at this path as globals."],type:"S",isPath:!0},path:{description:["Adds one or multiple paths to package resolution, similar","to node_modules. Prefers an 'ascMain' entry in a package's","package.json and falls back to an inner 'assembly/' folder."],type:"S",isPath:!0},wasm:{description:"Uses the specified Wasm binary of the compiler.",type:"s"}," ...":{description:"Specifies node.js options (CLI only). See: node --help"},"-Os":{value:{optimizeLevel:0,shrinkLevel:1}},"-Oz":{value:{optimizeLevel:0,shrinkLevel:2}},"-O0":{value:{optimizeLevel:0,shrinkLevel:0}},"-O1":{value:{optimizeLevel:1,shrinkLevel:0}},"-O2":{value:{optimizeLevel:2,shrinkLevel:0}},"-O3":{value:{optimizeLevel:3,shrinkLevel:0}},"-O0s":{value:{optimizeLevel:0,shrinkLevel:1}},"-O1s":{value:{optimizeLevel:1,shrinkLevel:1}},"-O2s":{value:{optimizeLevel:2,shrinkLevel:1}},"-O3s":{value:{optimizeLevel:3,shrinkLevel:1}},"-O0z":{value:{optimizeLevel:0,shrinkLevel:2}},"-O1z":{value:{optimizeLevel:1,shrinkLevel:2}},"-O2z":{value:{optimizeLevel:2,shrinkLevel:2}},"-O3z":{value:{optimizeLevel:3,shrinkLevel:2}},"-Ospeed":{value:{optimizeLevel:3,shrinkLevel:0}},"-Osize":{value:{optimizeLevel:0,shrinkLevel:2,converge:!0}},"--measure":{value:{stats:!0}}},Ae="~lib/",_e={array:`/// <reference path="./rt/index.d.ts" />
|
|
7
|
+
var le=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var dn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(a){throw n=[a],a}};var nn=(e,t)=>{for(var n in t)le(e,n,{get:t[n],enumerable:!0})},se=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Pe(t))!Ve.call(e,s)&&s!==n&&le(e,s,{get:()=>t[s],enumerable:!(a=Me(t,s))||a.enumerable});return e},In=(e,t,n)=>(se(e,t,"default"),n&&se(n,t,"default"));var ue={};nn(ue,{promises:()=>He});var He,fe=dn(()=>{"use strict";He={}});var ce={};nn(ce,{createRequire:()=>Ge});function Ge(){return function(t){throw new Error(`Cannot find module: '${t}'`)}}var de=dn(()=>{"use strict"});var kn={};nn(kn,{argv:()=>Xe,cwd:()=>Ln,exit:()=>qe,hrtime:()=>Ye,platform:()=>je,umask:()=>Ke});function Ln(){return"."}function Ke(){return 0}function qe(e=0){throw Error(`exit ${e}`)}function Ye(e){var t=We.call(he),n=Math.floor(t*.001),a=Math.floor(t*1e6-n*1e9);return e&&(n-=e[0],a-=e[1],a<0&&(n--,a+=1e9)),[n,a]}var je,Xe,he,We,On=dn(()=>{"use strict";je="linux";Xe=[];he=globalThis.performance||{},We=he.now||function(){return new Date().getTime()}});var Nn={};nn(Nn,{basename:()=>et,delimiter:()=>at,dirname:()=>nt,extname:()=>tt,format:()=>it,isAbsolute:()=>Ze,join:()=>$e,normalize:()=>xe,parse:()=>rt,relative:()=>Qe,resolve:()=>hn,sep:()=>Rn,win32:()=>ot});function H(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function pe(e,t){for(var n="",a=0,s=-1,o=0,c,d=0;d<=e.length;++d){if(d<e.length)c=e.charCodeAt(d);else{if(c===47)break;c=47}if(c===47){if(!(s===d-1||o===1))if(s!==d-1&&o===2){if(n.length<2||a!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var x=n.lastIndexOf("/");if(x!==n.length-1){x===-1?(n="",a=0):(n=n.slice(0,x),a=n.length-1-n.lastIndexOf("/")),s=d,o=0;continue}}else if(n.length===2||n.length===1){n="",a=0,s=d,o=0;continue}}t&&(n.length>0?n+="/..":n="..",a=2)}else n.length>0?n+="/"+e.slice(s+1,d):n=e.slice(s+1,d),a=d-s-1;s=d,o=0}else c===46&&o!==-1?++o:o=-1}return n}function Je(e,t){var n=t.dir||t.root,a=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+a:n+e+a:a}function hn(){for(var e="",t=!1,n,a=arguments.length-1;a>=-1&&!t;a--){var s;a>=0?s=arguments[a]:(n===void 0&&(n=Ln()),s=n),H(s),s.length!==0&&(e=s+"/"+e,t=s.charCodeAt(0)===47)}return e=pe(e,!t),t?e.length>0?"/"+e:"/":e.length>0?e:"."}function xe(e){if(H(e),e.length===0)return".";var t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47;return e=pe(e,!t),e.length===0&&!t&&(e="."),e.length>0&&n&&(e+="/"),t?"/"+e:e}function Ze(e){return H(e),e.length>0&&e.charCodeAt(0)===47}function $e(){if(arguments.length===0)return".";for(var e,t=0;t<arguments.length;++t){var n=arguments[t];H(n),n.length>0&&(e===void 0?e=n:e+="/"+n)}return e===void 0?".":xe(e)}function Qe(e,t){if(H(e),H(t),e===t||(e=hn(e),t=hn(t),e===t))return"";if(e===".")return t;for(var n=1;n<e.length&&e.charCodeAt(n)===47;++n);for(var a=e.length,s=a-n,o=1;o<t.length&&t.charCodeAt(o)===47;++o);for(var c=t.length,d=c-o,x=s<d?s:d,b=-1,h=0;h<=x;++h){if(h===x){if(d>x){if(t.charCodeAt(o+h)===47)return t.slice(o+h+1);if(h===0)return t.slice(o+h)}else s>x&&(e.charCodeAt(n+h)===47?b=h:h===0&&(b=0));break}var g=e.charCodeAt(n+h),y=t.charCodeAt(o+h);if(g!==y)break;g===47&&(b=h)}var m="";for(h=n+b+1;h<=a;++h)(h===a||e.charCodeAt(h)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+t.slice(o+b):(o+=b,t.charCodeAt(o)===47&&++o,t.slice(o))}function nt(e){if(H(e),e.length===0)return".";for(var t=e.charCodeAt(0),n=t===47,a=-1,s=!0,o=e.length-1;o>=1;--o)if(t=e.charCodeAt(o),t===47){if(!s){a=o;break}}else s=!1;return a===-1?n?"/":".":n&&a===1?"//":e.slice(0,a)}function et(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');H(e);var n=0,a=-1,s=!0,o;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var c=t.length-1,d=-1;for(o=e.length-1;o>=0;--o){var x=e.charCodeAt(o);if(x===47){if(!s){n=o+1;break}}else d===-1&&(s=!1,d=o+1),c>=0&&(x===t.charCodeAt(c)?--c===-1&&(a=o):(c=-1,a=d))}return n===a?a=d:a===-1&&(a=e.length),e.slice(n,a)}else{for(o=e.length-1;o>=0;--o)if(e.charCodeAt(o)===47){if(!s){n=o+1;break}}else a===-1&&(s=!1,a=o+1);return a===-1?"":e.slice(n,a)}}function tt(e){H(e);for(var t=-1,n=0,a=-1,s=!0,o=0,c=e.length-1;c>=0;--c){var d=e.charCodeAt(c);if(d===47){if(!s){n=c+1;break}continue}a===-1&&(s=!1,a=c+1),d===46?t===-1?t=c:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||a===-1||o===0||o===1&&t===a-1&&t===n+1?"":e.slice(t,a)}function it(e){if(e===null||typeof e!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return Je("/",e)}function rt(e){H(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;var n=e.charCodeAt(0),a=n===47,s;a?(t.root="/",s=1):s=0;for(var o=-1,c=0,d=-1,x=!0,b=e.length-1,h=0;b>=s;--b){if(n=e.charCodeAt(b),n===47){if(!x){c=b+1;break}continue}d===-1&&(x=!1,d=b+1),n===46?o===-1?o=b:h!==1&&(h=1):o!==-1&&(h=-1)}return o===-1||d===-1||h===0||h===1&&o===d-1&&o===c+1?d!==-1&&(c===0&&a?t.base=t.name=e.slice(1,d):t.base=t.name=e.slice(c,d)):(c===0&&a?(t.name=e.slice(1,o),t.base=e.slice(1,d)):(t.name=e.slice(c,o),t.base=e.slice(c,d)),t.ext=e.slice(o,d)),c>0?t.dir=e.slice(0,c-1):a&&(t.dir="/"),t}var Rn,at,ot,Un=dn(()=>{"use strict";On();Rn="/",at=":",ot=null});var ge={};nn(ge,{pathToFileURL:()=>lt});function st(e){return e.replace(/%/g,"%25").replace(/\\/g,"%5C").replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/\t/g,"%09")}function lt(e){let t=hn(e);e.charCodeAt(e.length-1)===47&&t[t.length-1]!==Rn&&(t+="/");let n=new URL("file://");return n.pathname=st(t),n}var me=dn(()=>{"use strict";Un()});var Yn={};nn(Yn,{Stats:()=>zn,checkDiagnostics:()=>mn,compileString:()=>Dt,configToArguments:()=>Wn,createMemoryStream:()=>Xn,default:()=>Yn,defaultOptimizeLevel:()=>we,defaultShrinkLevel:()=>Be,definitionFiles:()=>Bt,libraryFiles:()=>j,libraryPrefix:()=>V,main:()=>De,options:()=>wt,tscOptions:()=>It,version:()=>Kn});var ut=Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]",M,sn,E,P,pn;ut?(M=await import("fs"),sn=await import("module"),E=await import("path"),P=globalThis.process,pn=await import("url")):(M=await Promise.resolve().then(()=>(fe(),ue)),sn=await Promise.resolve().then(()=>(de(),ce)),E=await Promise.resolve().then(()=>(Un(),Nn)),P=await Promise.resolve().then(()=>(On(),kn)),pn=await Promise.resolve().then(()=>(me(),ge)));var _n=typeof process<"u"&&process||{},ft=_n.env&&"CI"in _n.env,ct="\x1B[90m",dt="\x1B[91m",ht="\x1B[92m",pt="\x1B[93m",xt="\x1B[94m",gt="\x1B[95m",mt="\x1B[96m",bt="\x1B[97m",W="\x1B[0m",en=class{constructor(t){this.stream=t,this.enabled=!!(this.stream&&this.stream.isTTY||ft)}gray(t){return this.enabled?ct+t+W:t}red(t){return this.enabled?dt+t+W:t}green(t){return this.enabled?ht+t+W:t}yellow(t){return this.enabled?pt+t+W:t}blue(t){return this.enabled?xt+t+W:t}magenta(t){return this.enabled?gt+t+W:t}cyan(t){return this.enabled?mt+t+W:t}white(t){return this.enabled?bt+t+W:t}},Tn=new en(_n.stdout),Ot=new en(_n.stderr);function yt(e){for(var t=0,n=0,a=e.length;n<a;++n){let s=e.charCodeAt(n);s<128?t+=1:s<2048?t+=2:(s&64512)===55296&&n+1<a&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3}return t}function vt(e,t,n){var a=n-t;if(a<1)return"";for(var s=null,o=[],c=0,d;t<n;)d=e[t++],d<128?o[c++]=d:d>191&&d<224?o[c++]=(d&31)<<6|e[t++]&63:d>239&&d<365?(d=((d&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,o[c++]=55296+(d>>10),o[c++]=56320+(d&1023)):o[c++]=(d&15)<<12|(e[t++]&63)<<6|e[t++]&63,c>=8192&&((s||(s=[])).push(String.fromCharCode(...o)),c=0);return s?(c&&s.push(String.fromCharCode(...o.slice(0,c))),s.join("")):String.fromCharCode(...o.slice(0,c))}function Ft(e,t,n){for(var a=n,s=0,o=e.length;s<o;++s){let c=e.charCodeAt(s),d;c<128?t[n++]=c:c<2048?(t[n++]=c>>6|192,t[n++]=c&63|128):(c&64512)===55296&&s+1<o&&((d=e.charCodeAt(s+1))&64512)===56320?(c=65536+((c&1023)<<10)+(d&1023),++s,t[n++]=c>>18|240,t[n++]=c>>12&63|128,t[n++]=c>>6&63|128,t[n++]=c&63|128):(t[n++]=c>>12|224,t[n++]=c>>6&63|128,t[n++]=c&63|128)}return n-a}var Cn={length:yt,read:vt,write:Ft};var be=sn.createRequire(import.meta.url);function ve(e,t,n=!0){var a={},s=[],o=[],c=[],d={};Object.keys(t).forEach(h=>{if(!h.startsWith(" ")){var g=t[h];g.alias!=null&&(typeof g.alias=="string"?d[g.alias]=h:Array.isArray(g.alias)&&g.alias.forEach(y=>d[y]=h)),n&&g.default!=null&&(a[h]=g.default)}});for(var x=0,b=(e=e.slice()).length;x<b;++x){let h=e[x];if(h=="--"){++x;break}let g=/^(?:(-\w)(?:=(.*))?|(--\w{2,})(?:=(.*))?)$/.exec(h),y,m;if(g)t[h]?y=t[m=h]:g[1]!=null?(y=t[m=d[g[1].substring(1)]],y&&g[2]!=null&&(e[x--]=g[2])):g[3]!=null&&(y=t[m=g[3].substring(2)],y&&g[4]!=null&&(e[x--]=g[4]));else if(h.charCodeAt(0)==45)y=t[m=h];else{o.push(h);continue}if(y)if(y.value)Object.keys(y.value).forEach(i=>a[i]=y.value[i]);else if(y.type==null||y.type==="b")a[m]=!0;else if(x+1<e.length&&e[x+1].charCodeAt(0)!=45)switch(y.type){case"i":a[m]=parseInt(e[++x],10);break;case"I":a[m]=(a[m]||[]).concat(parseInt(e[++x],10));break;case"f":a[m]=parseFloat(e[++x]);break;case"F":a[m]=(a[m]||[]).concat(parseFloat(e[++x]));break;case"s":a[m]=String(e[++x]);break;case"S":a[m]=(a[m]||[]).concat(e[++x].split(","));break;default:s.push(h),--x}else switch(y.type){case"i":case"f":a[m]=y.default||0;break;case"s":a[m]=y.default||"";break;case"I":case"F":case"S":a[m]=y.default||[];break;default:s.push(h)}else s.push(h)}for(;x<b;)c.push(e[x++]);return n&&Pn(t,a),{options:a,unknown:s,arguments:o,trailing:c}}function Fe(e,t){t||(t={});var n=t.indent||2,a=t.padding||24,s=t.eol||`
|
|
8
|
+
`,o={},c=[];Object.keys(e).forEach(b=>{var h=e[b];if(h.description!=null){for(var g="";g.length<n;)g+=" ";for(g+="--"+b,h.alias&&(g+=", -"+h.alias);g.length<a;)g+=" ";var y;!t.noCategories&&h.category?(y=o[h.category])||(o[h.category]=y=[]):y=c,Array.isArray(h.description)?y.push(g+h.description[0]+h.description.slice(1).map(m=>{for(let i=0;i<a;++i)m=" "+m;return s+m}).join("")):y.push(g+h.description)}});var d=[],x=!1;return Object.keys(o).forEach(b=>{x=!0,d.push(s+" "+Tn.gray(b)+s),d.push(o[b].join(s))}),x&&c.length&&d.push(s+" "+Tn.gray("Other")+s),d.push(c.join(s)),d.join(s)}function ye(e,t){if(e!=null)switch(t){case void 0:case"b":return!!e;case"i":return Math.trunc(e)||0;case"f":return Number(e)||0;case"s":return e===!0?"":e===!1?null:String(e);case"I":return Array.isArray(e)||(e=[e]),e.map(n=>Math.trunc(n)||0);case"F":return Array.isArray(e)||(e=[e]),e.map(n=>Number(n)||0);case"S":return Array.isArray(e)||(e=[e]),e.map(String)}}function Mn(e,t,n,a){let s={};for(let[o,{type:c,mutuallyExclusive:d,isPath:x,useNodeResolution:b,cliOnly:h}]of Object.entries(e)){let g=ye(t[o],c),y=ye(n[o],c);if(g==null){if(y!=null){if(h)continue;if(Array.isArray(y)){let m;x&&(y=y.map(i=>tn(i,a,b))),d!=null&&(m=t[d])?s[o]=y.filter(i=>!m.includes(i)):s[o]=y.slice()}else x&&(y=tn(y,a,b)),s[o]=y}}else if(y==null)Array.isArray(g)?s[o]=g.slice():s[o]=g;else if(Array.isArray(g)){if(h){s[o]=g.slice();continue}let m;x&&(y=y.map(i=>tn(i,a,b))),d!=null&&(m=t[d])?s[o]=[...g,...y.filter(i=>!g.includes(i)&&!m.includes(i))]:s[o]=[...g,...y.filter(i=>!g.includes(i))]}else s[o]=g}return s}function Et(e){let t=E.parse(e);return t.root||(t.root="./"),E.format(t)}function tn(e,t,n=!1){return E.isAbsolute(e)?e:n&&!e.startsWith(".")&&be.resolve?be.resolve(e,{paths:[t]}):Et(E.join(t,e))}function Pn(e,t){for(let[n,{default:a}]of Object.entries(e))t[n]==null&&a!=null&&(t[n]=a)}var Ee="0.1.60",Y={version:{category:"General",description:"Prints just the compiler's version and exits.",type:"b",alias:"v"},help:{category:"General",description:"Prints this message and exits.",type:"b",alias:"h"},config:{category:"General",description:"Configuration file to apply. CLI arguments take precedence.",type:"s",cliOnly:!0},target:{category:"General",description:"Configuration file target to use. Defaults to 'release'.",type:"s",cliOnly:!0},targetMode:{category:"General",description:"Toil compile surface mode: 'hot' (request/stream) or 'cold' (daemon). Omit for the default request artifact.",type:"s"},authUser:{category:"General",description:"Built-in auth: inject the reserved toilUserId + username fields into the single @user (used by the toiljs server.auth build when the app declares its own @user).",type:"b"},noConfigEntries:{category:"General",description:"Ignore the toilconfig 'entries' array and compile ONLY the entry files given on the command line. Used by the toiljs multi-artifact build, which hands each pass (request/stream/daemon) its own entry subset.",type:"b"},optimize:{category:"Optimization",description:["Optimizes the module. Typical shorthands are:",""," Default optimizations -O"," Make a release build -O --noAssert"," Make a debug build --debug"," Optimize for speed -Ospeed"," Optimize for size -Osize",""],type:"b",alias:"O"},optimizeLevel:{category:"Optimization",description:"How much to focus on optimizing code. [0-3]",type:"i"},shrinkLevel:{category:"Optimization",description:"How much to focus on shrinking code size. [0-2, s=1, z=2]",type:"i"},converge:{category:"Optimization",description:"Re-optimizes until no further improvements can be made.",type:"b",default:!1},noAssert:{category:"Optimization",description:"Replaces assertions with just their value without trapping.",type:"b",default:!1},outFile:{category:"Output",description:"Specifies the WebAssembly output file (.wasm).",type:"s",alias:"o",isPath:!0},textFile:{category:"Output",description:"Specifies the WebAssembly text output file (.wat).",type:"s",alias:"t",isPath:!0},rpcModule:{category:"Output",description:"Emits a .ts module: the @data codec + the typed client-callable Server surface.",type:"s",isPath:!0},rpcSurfaceFiles:{category:"Output",description:"Files parsed for the rpc module's @rest/@stream client surface but NOT compiled into this artifact (folds a sibling tier's @stream classes into the Server surface).",type:"S",isPath:!0},rpcRuntime:{category:"Output",description:"Import specifier for the DataWriter/DataReader codec in the emitted RPC module.",type:"s",default:"toiljs/io"},bindings:{category:"Output",description:["Specifies the bindings to generate (.js + .d.ts).",""," esm JavaScript bindings & typings for ESM integration."," raw Like esm, but exports just the instantiate function."," Useful where modules are meant to be instantiated"," multiple times or non-ESM imports must be provided."],type:"S",alias:"b"},sourceMap:{category:"Debugging",description:["Enables source map generation. Optionally takes the URL","used to reference the source map from the binary file."],type:"s"},uncheckedBehavior:{category:"Debugging",description:["Changes the behavior of unchecked() expressions.","Using this option can potentially cause breakage.",""," default The default behavior: unchecked operations are"," only used inside of unchecked()."," never Unchecked operations are never used, even when"," inside of unchecked()."," always Unchecked operations are always used if possible,"," whether or not unchecked() is used."],type:"s",default:"default"},debug:{category:"Debugging",description:"Enables debug information in emitted binaries.",type:"b",default:!1},importMemory:{category:"Features",description:"Imports the memory from 'env.memory'.",type:"b",default:!1},noExportMemory:{category:"Features",description:"Does not export the memory as 'memory'.",type:"b",default:!1},initialMemory:{category:"Features",description:"Sets the initial memory size in pages.",type:"i",default:0},maximumMemory:{category:"Features",description:"Sets the maximum memory size in pages.",type:"i",default:0},sharedMemory:{category:"Features",description:"Declare memory as shared. Requires maximumMemory.",type:"b",default:!1},zeroFilledMemory:{category:"Features",description:"Assume imported memory is zeroed. Requires importMemory.",type:"b",default:!1},importTable:{category:"Features",description:"Imports the function table from 'env.table'.",type:"b",default:!1},exportTable:{category:"Features",description:"Exports the function table as 'table'.",type:"b",default:!1},exportStart:{category:"Features",description:["Exports the start function using the specified name instead","of calling it implicitly. Useful to obtain the exported memory","before executing any code accessing it."],type:"s"},runtime:{category:"Features",description:["Specifies the runtime variant to include in the program.",""," incremental TLSF + incremental GC (default)"," minimal TLSF + lightweight GC invoked externally"," stub Minimal runtime stub (never frees)"," ... Path to a custom runtime implementation",""],type:"s",default:"incremental"},exportRuntime:{category:"Features",description:["Always exports the runtime helpers (__new, __collect, __pin etc.).","Automatically determined when generation of --bindings is enabled."],type:"b",default:!1},stackSize:{category:"Features",description:["Overrides the stack size. Only relevant for incremental GC","or when using a custom runtime that requires stack space.","Defaults to 0 without and to 32768 with incremental GC."],default:0,type:"i"},enable:{category:"Features",description:["Enables WebAssembly features being disabled by default.",""," threads Threading and atomic operations."," simd SIMD types and operations."," reference-types Reference types and operations."," gc Garbage collection (WIP)."," stringref String reference types."," relaxed-simd Relaxed SIMD operations.",""],TODO_doesNothingYet:[" exception-handling Exception handling."," tail-calls Tail call operations."," multi-value Multi value types."," memory64 Memory64 operations."," extended-const Extended const expressions."],type:"S",mutuallyExclusive:"disable"},disable:{category:"Features",description:["Disables WebAssembly features being enabled by default.",""," mutable-globals Mutable global imports and exports."," sign-extension Sign-extension operations"," nontrapping-f2i Non-trapping float to integer ops."," bulk-memory Bulk memory operations.",""],type:"S",mutuallyExclusive:"enable"},use:{category:"Features",description:["Aliases a global object under another name, e.g., to switch","the default 'Math' implementation used: --use Math=JSMath","Can also be used to introduce an integer constant."],type:"S",alias:"u"},lowMemoryLimit:{category:"Features",description:"Enforces very low (<64k) memory constraints.",default:0,type:"i"},memoryBase:{category:"Linking",description:"Sets the start offset of emitted memory segments.",type:"i",default:0},tableBase:{category:"Linking",description:"Sets the start offset of emitted table elements.",type:"i",default:0},transform:{category:"API",description:"Specifies the path to a custom transform to load.",type:"S",isPath:!0,useNodeResolution:!0},trapMode:{category:"Binaryen",description:["Sets the trap mode to use.",""," allow Allow trapping operations. This is the default."," clamp Replace trapping operations with clamping semantics."," js Replace trapping operations with JS semantics.",""],type:"s",default:"allow"},runPasses:{category:"Binaryen",description:["Specifies additional Binaryen passes to run after other","optimizations, if any. See: Binaryen/src/passes/pass.cpp"],type:"s"},noValidate:{category:"Binaryen",description:"Skips validating the module using Binaryen.",type:"b",default:!1},baseDir:{description:"Specifies the base directory of input and output files.",type:"s",default:"."},noColors:{description:"Disables terminal colors.",type:"b",default:!1},noUnsafe:{description:["Disallows the use of unsafe features in user code.","Does not affect library files and external modules."],type:"b",default:!1},disableWarning:{description:["Disables warnings matching the given diagnostic code.","If no diagnostic code is given, all warnings are disabled."],type:"I"},noEmit:{description:"Performs compilation as usual but does not emit code.",type:"b",default:!1},showConfig:{description:"Print computed compiler options and exit.",type:"b",default:!1},stats:{description:"Prints statistics on I/O and compile times.",type:"b",default:!1},pedantic:{description:"Make yourself sad for no good reason.",type:"b",default:!1},lib:{description:["Adds one or multiple paths to custom library components and","uses exports of all top-level files at this path as globals."],type:"S",isPath:!0},path:{description:["Adds one or multiple paths to package resolution, similar","to node_modules. Prefers an 'ascMain' entry in a package's","package.json and falls back to an inner 'assembly/' folder."],type:"S",isPath:!0},wasm:{description:"Uses the specified Wasm binary of the compiler.",type:"s"}," ...":{description:"Specifies node.js options (CLI only). See: node --help"},"-Os":{value:{optimizeLevel:0,shrinkLevel:1}},"-Oz":{value:{optimizeLevel:0,shrinkLevel:2}},"-O0":{value:{optimizeLevel:0,shrinkLevel:0}},"-O1":{value:{optimizeLevel:1,shrinkLevel:0}},"-O2":{value:{optimizeLevel:2,shrinkLevel:0}},"-O3":{value:{optimizeLevel:3,shrinkLevel:0}},"-O0s":{value:{optimizeLevel:0,shrinkLevel:1}},"-O1s":{value:{optimizeLevel:1,shrinkLevel:1}},"-O2s":{value:{optimizeLevel:2,shrinkLevel:1}},"-O3s":{value:{optimizeLevel:3,shrinkLevel:1}},"-O0z":{value:{optimizeLevel:0,shrinkLevel:2}},"-O1z":{value:{optimizeLevel:1,shrinkLevel:2}},"-O2z":{value:{optimizeLevel:2,shrinkLevel:2}},"-O3z":{value:{optimizeLevel:3,shrinkLevel:2}},"-Ospeed":{value:{optimizeLevel:3,shrinkLevel:0}},"-Osize":{value:{optimizeLevel:0,shrinkLevel:2,converge:!0}},"--measure":{value:{stats:!0}}},Ae="~lib/",_e={array:`/// <reference path="./rt/index.d.ts" />
|
|
9
9
|
|
|
10
10
|
import { BLOCK_MAXSIZE } from "./rt/common";
|
|
11
11
|
import { Runtime } from "shared/runtime";
|
|
@@ -4292,6 +4292,75 @@ export declare function stop_unwind(): void;
|
|
|
4292
4292
|
export declare function start_rewind(data: StackDescriptor): void;
|
|
4293
4293
|
/** Stops rewinding the call stack. */
|
|
4294
4294
|
export declare function stop_rewind(): void;
|
|
4295
|
+
`,"bindings/daemon":`// Host-import declarations for the daemon (L4 cold box) scheduler surface.
|
|
4296
|
+
//
|
|
4297
|
+
// Unlike every other host import, these do NOT live under \`env\`. Production
|
|
4298
|
+
// registers them in their OWN wasm module namespace, \`("daemon", "<name>")\`
|
|
4299
|
+
// (toil-backend \`src/wasm/cold/imports.rs\`, \`NS_DAEMON\`), and only for a cold
|
|
4300
|
+
// box: the request module's deploy-time allowlist carries no daemon entries.
|
|
4301
|
+
// A cold box that declares them as dotted names under \`env\` resolves against a
|
|
4302
|
+
// dev emulator but falls through to the trap-on-use stub at the edge, so the
|
|
4303
|
+
// namespace here is load-bearing rather than cosmetic.
|
|
4304
|
+
//
|
|
4305
|
+
// The host registers only the functions the module actually declares, so a
|
|
4306
|
+
// daemon that never calls one never pays for it.
|
|
4307
|
+
//
|
|
4308
|
+
// Return convention:
|
|
4309
|
+
// >= 0 success: a count, an epoch, or a written byte length.
|
|
4310
|
+
// -1 \`httpCall\`: the response did not fit \`outCap\` (retry bigger).
|
|
4311
|
+
// \`nextFireMs\`: unknown id, or a cron that never fires again.
|
|
4312
|
+
// Neither is an error code.
|
|
4313
|
+
// -(0x10000 + c) a typed failure carrying the u16 subsystem code \`c\`; see
|
|
4314
|
+
// \`DaemonError\` in \`~lib/daemon\`, which decodes this band.
|
|
4315
|
+
//
|
|
4316
|
+
// The \`httpCall\` request/response envelopes are a bespoke little-endian framing
|
|
4317
|
+
// (NOT the \`@data\` codec); \`DaemonHttpRequest\` / \`DaemonHttpResponse\` own it.
|
|
4318
|
+
|
|
4319
|
+
export namespace daemonHost {
|
|
4320
|
+
// daemon.is_leader() -> 1 when this node currently holds the lease, else 0.
|
|
4321
|
+
// @ts-ignore: decorator
|
|
4322
|
+
@external("daemon", "is_leader")
|
|
4323
|
+
export declare function isLeader(): i32;
|
|
4324
|
+
|
|
4325
|
+
// daemon.current_epoch() -> the monotonic fencing token, or -1 when not leader.
|
|
4326
|
+
// @ts-ignore: decorator
|
|
4327
|
+
@external("daemon", "current_epoch")
|
|
4328
|
+
export declare function currentEpoch(): i64;
|
|
4329
|
+
|
|
4330
|
+
// daemon.yield() -> 0 while still leader, else the bridged \`LeaseLost\`. Named
|
|
4331
|
+
// \`yieldNow\` because \`yield\` is a reserved word.
|
|
4332
|
+
// @ts-ignore: decorator
|
|
4333
|
+
@external("daemon", "yield")
|
|
4334
|
+
export declare function yieldNow(): i32;
|
|
4335
|
+
|
|
4336
|
+
// daemon.sleep_ms(ms) -> 0 when the sleep completed, else the bridged
|
|
4337
|
+
// \`LeaseLost\` if the lease was lost while parked. The host CLAMPS \`ms\` to its
|
|
4338
|
+
// own ceiling (3s) and treats a negative \`ms\` as 0, so neither can park a
|
|
4339
|
+
// daemon thread for an unbounded interval.
|
|
4340
|
+
// @ts-ignore: decorator
|
|
4341
|
+
@external("daemon", "sleep_ms")
|
|
4342
|
+
export declare function sleepMs(ms: i64): i32;
|
|
4343
|
+
|
|
4344
|
+
// daemon.task_count() -> the number of registered \`@scheduled\` tasks.
|
|
4345
|
+
// @ts-ignore: decorator
|
|
4346
|
+
@external("daemon", "task_count")
|
|
4347
|
+
export declare function taskCount(): i32;
|
|
4348
|
+
|
|
4349
|
+
// daemon.next_fire_ms(taskId) -> the next wall-clock fire time in epoch ms, or
|
|
4350
|
+
// -1 for an out-of-range id / a cron that never fires again.
|
|
4351
|
+
// @ts-ignore: decorator
|
|
4352
|
+
@external("daemon", "next_fire_ms")
|
|
4353
|
+
export declare function nextFireMs(taskId: i32): i64;
|
|
4354
|
+
|
|
4355
|
+
// daemon.http_call(reqPtr, reqLen, outPtr, outCap) -> the response envelope
|
|
4356
|
+
// LENGTH written to \`outPtr\` (>= 0, not packed with a pointer: the guest
|
|
4357
|
+
// supplied the buffer), -1 when it did not fit \`outCap\`, or a bridged
|
|
4358
|
+
// \`DaemonError\`. Soft-fenced: a non-leader gets \`NotLeader\` without hitting
|
|
4359
|
+
// the wire.
|
|
4360
|
+
// @ts-ignore: decorator
|
|
4361
|
+
@external("daemon", "http_call")
|
|
4362
|
+
export declare function httpCall(reqPtr: usize, reqLen: i32, outPtr: usize, outCap: i32): i64;
|
|
4363
|
+
}
|
|
4295
4364
|
`,"bindings/dom":`@external("env", "globalThis")
|
|
4296
4365
|
export declare const globalThis: externref;
|
|
4297
4366
|
|
|
@@ -4885,7 +4954,7 @@ export namespace analyticsHost {
|
|
|
4885
4954
|
@external("env", "analytics_read")
|
|
4886
4955
|
export declare function read(domainPtr: usize, domainLen: i32): i32;
|
|
4887
4956
|
|
|
4888
|
-
// analytics_series(domain, metricId, range): frame length (
|
|
4957
|
+
// analytics_series(domain, metricId, range): frame length (v3 series frame) stashed for takeResult,
|
|
4889
4958
|
// or a negative status (-2 absent / -3 forbidden / bad metric or range).
|
|
4890
4959
|
// @ts-ignore: decorator
|
|
4891
4960
|
@external("env", "analytics_series")
|
|
@@ -5002,6 +5071,54 @@ export namespace webcrypto {
|
|
|
5002
5071
|
paramsLen: i32,
|
|
5003
5072
|
lengthBits: i32
|
|
5004
5073
|
): i32;
|
|
5074
|
+
|
|
5075
|
+
// --- Post-quantum -------------------------------------------------------
|
|
5076
|
+
//
|
|
5077
|
+
// These are NOT WebCrypto: they are the three post-quantum primitives the edge
|
|
5078
|
+
// exposes, under the same \`crypto.*\` namespace. All are VERIFY / DECAPSULATE
|
|
5079
|
+
// only. The host never generates or holds a long-lived secret on the guest's
|
|
5080
|
+
// behalf, and there is no key handle: every input is passed by (ptr, len).
|
|
5081
|
+
|
|
5082
|
+
// mldsaVerify -> 1 valid, 0 invalid, negative error. \`ctx\` is the ML-DSA
|
|
5083
|
+
// context string (may be empty).
|
|
5084
|
+
// @ts-ignore: decorator
|
|
5085
|
+
@external("env", "crypto.mldsa_verify")
|
|
5086
|
+
export declare function mldsaVerify(
|
|
5087
|
+
pkPtr: usize,
|
|
5088
|
+
pkLen: i32,
|
|
5089
|
+
msgPtr: usize,
|
|
5090
|
+
msgLen: i32,
|
|
5091
|
+
sigPtr: usize,
|
|
5092
|
+
sigLen: i32,
|
|
5093
|
+
ctxPtr: usize,
|
|
5094
|
+
ctxLen: i32
|
|
5095
|
+
): i32;
|
|
5096
|
+
|
|
5097
|
+
// mlkemDecapsulate -> 0 on success (the shared secret is written to \`outPtr\`)
|
|
5098
|
+
// or a negative error. The caller owns \`sk\`; the host holds no KEM key.
|
|
5099
|
+
// @ts-ignore: decorator
|
|
5100
|
+
@external("env", "crypto.mlkem_decapsulate")
|
|
5101
|
+
export declare function mlkemDecapsulate(
|
|
5102
|
+
ctPtr: usize,
|
|
5103
|
+
ctLen: i32,
|
|
5104
|
+
skPtr: usize,
|
|
5105
|
+
skLen: i32,
|
|
5106
|
+
outPtr: usize
|
|
5107
|
+
): i32;
|
|
5108
|
+
|
|
5109
|
+
// voprfEvaluate -> 0 on success (the evaluated element is written to \`outPtr\`)
|
|
5110
|
+
// or a negative error. \`seed\` is the guest's own OPRF seed.
|
|
5111
|
+
// @ts-ignore: decorator
|
|
5112
|
+
@external("env", "crypto.voprf_evaluate")
|
|
5113
|
+
export declare function voprfEvaluate(
|
|
5114
|
+
seedPtr: usize,
|
|
5115
|
+
seedLen: i32,
|
|
5116
|
+
infoPtr: usize,
|
|
5117
|
+
infoLen: i32,
|
|
5118
|
+
blindedPtr: usize,
|
|
5119
|
+
blindedLen: i32,
|
|
5120
|
+
outPtr: usize
|
|
5121
|
+
): i32;
|
|
5005
5122
|
}
|
|
5006
5123
|
`,bitflags:`// Type-safe bit manipulation utilities.
|
|
5007
5124
|
// Pure @inline functions \u2014 each compiles to 1-2 wasm instructions.
|
|
@@ -8591,6 +8708,321 @@ export class SubtleCrypto {
|
|
|
8591
8708
|
return this.importKey(FMT_RAW, bits, derivedKeyAlgorithm, extractable, usages);
|
|
8592
8709
|
}
|
|
8593
8710
|
}
|
|
8711
|
+
`,daemon:`// Daemon: the developer-facing L4 (cold box) scheduler API.
|
|
8712
|
+
//
|
|
8713
|
+
// \`@daemon class Jobs { onStart(): void {} @scheduled("1s") tick(): void {} }\`
|
|
8714
|
+
// declares the daemon; the compiler emits the \`daemon_start\` / \`daemon_dispatch\`
|
|
8715
|
+
// entrypoints and the \`toildaemon.catalog\` section. THIS file is what a task body
|
|
8716
|
+
// calls to read its own leadership, park, introspect its schedule, and make an
|
|
8717
|
+
// outbound HTTP request.
|
|
8718
|
+
//
|
|
8719
|
+
// These wrap \`bindings/daemon\`, whose imports live in the \`daemon\` wasm module
|
|
8720
|
+
// (not \`env\`). They resolve only inside a cold box: calling them from a request
|
|
8721
|
+
// handler produces a module the edge will not run.
|
|
8722
|
+
//
|
|
8723
|
+
// Leadership is cooperative. Exactly one node holds the lease; \`isLeader()\` is a
|
|
8724
|
+
// snapshot, and a long task should re-check it (or call \`yieldNow()\`) rather than
|
|
8725
|
+
// assume the lease it started with is still held. Every call that can observe a
|
|
8726
|
+
// lost lease reports it as \`DaemonError.LeaseLost\`.
|
|
8727
|
+
|
|
8728
|
+
import { daemonHost } from "bindings/daemon";
|
|
8729
|
+
|
|
8730
|
+
/// The host bridges a typed failure as \`-(0x10000 + code)\`; this is that base.
|
|
8731
|
+
const DAEMON_ERR_BASE: i64 = 0x10000;
|
|
8732
|
+
|
|
8733
|
+
/// \`http_call\` request caps, mirrored from the host so an over-cap envelope fails
|
|
8734
|
+
/// in the guest instead of costing a rejected round trip (toil-backend
|
|
8735
|
+
/// \`config::daemon_http\`).
|
|
8736
|
+
const DAEMON_MAX_METHOD_BYTES: i32 = 16;
|
|
8737
|
+
const DAEMON_MAX_URL_BYTES: i32 = 8 * 1024;
|
|
8738
|
+
const DAEMON_MAX_HEADERS: i32 = 64;
|
|
8739
|
+
const DAEMON_MAX_HEADER_BYTES: i32 = 8 * 1024;
|
|
8740
|
+
const DAEMON_MAX_REQUEST_BYTES: i32 = 256 * 1024;
|
|
8741
|
+
|
|
8742
|
+
/// The host truncates a response body to 1 MiB. The default \`httpCall\` buffer is
|
|
8743
|
+
/// smaller; callers expecting large bodies pass their own capacity.
|
|
8744
|
+
const DAEMON_DEFAULT_RESPONSE_CAP: i32 = 64 * 1024;
|
|
8745
|
+
|
|
8746
|
+
/// A typed daemon failure. The three positive values are the host's u16 subsystem
|
|
8747
|
+
/// codes (toil-backend \`ERR_DAEMON_*\`), bridged as \`-(0x10000 + code)\`. The
|
|
8748
|
+
/// negative values are guest-side outcomes that never travel the wire.
|
|
8749
|
+
@global
|
|
8750
|
+
export enum DaemonError {
|
|
8751
|
+
/// No failure.
|
|
8752
|
+
None = 0,
|
|
8753
|
+
/// This node does not hold the lease; the host refused without acting.
|
|
8754
|
+
NotLeader = 0x0401,
|
|
8755
|
+
/// The lease was lost while the call was in flight (mid-park, mid-request).
|
|
8756
|
+
LeaseLost = 0x0402,
|
|
8757
|
+
/// The outbound request did not complete (SSRF guard, timeout, transport).
|
|
8758
|
+
CallFailed = 0x0405,
|
|
8759
|
+
/// The response did not fit the buffer. The call ALREADY HAPPENED: retrying it
|
|
8760
|
+
/// re-issues the request. Pass a larger \`responseCap\` next time instead.
|
|
8761
|
+
ResponseTooLarge = -1,
|
|
8762
|
+
/// The request violates a host cap, or the response envelope was malformed.
|
|
8763
|
+
/// Nothing was sent (encode) or the bytes could not be trusted (decode).
|
|
8764
|
+
BadEnvelope = -2,
|
|
8765
|
+
/// A negative status outside every band above.
|
|
8766
|
+
Unknown = -3,
|
|
8767
|
+
}
|
|
8768
|
+
|
|
8769
|
+
/// The last failure observed by a \`Daemon\` call, in this instance. Read it right
|
|
8770
|
+
/// after a call that returned \`null\`; any later call overwrites it.
|
|
8771
|
+
// @ts-ignore: decorator
|
|
8772
|
+
@lazy
|
|
8773
|
+
var __daemonLastError: DaemonError = DaemonError.None;
|
|
8774
|
+
|
|
8775
|
+
/// Decode a negative host return into a typed failure. Non-negative is \`None\`.
|
|
8776
|
+
function __daemonDecode(status: i64): DaemonError {
|
|
8777
|
+
if (status >= 0) return DaemonError.None;
|
|
8778
|
+
if (status == -1) return DaemonError.ResponseTooLarge;
|
|
8779
|
+
const code: i64 = -status - DAEMON_ERR_BASE;
|
|
8780
|
+
if (code < 0 || code > 0xFFFF) return DaemonError.Unknown;
|
|
8781
|
+
const c = <i32>code;
|
|
8782
|
+
if (c == <i32>DaemonError.NotLeader) return DaemonError.NotLeader;
|
|
8783
|
+
if (c == <i32>DaemonError.LeaseLost) return DaemonError.LeaseLost;
|
|
8784
|
+
if (c == <i32>DaemonError.CallFailed) return DaemonError.CallFailed;
|
|
8785
|
+
return DaemonError.Unknown;
|
|
8786
|
+
}
|
|
8787
|
+
|
|
8788
|
+
/// Record and return the failure for \`status\` (\`None\` when it is not a failure).
|
|
8789
|
+
function __daemonNote(status: i64): DaemonError {
|
|
8790
|
+
const e = __daemonDecode(status);
|
|
8791
|
+
__daemonLastError = e;
|
|
8792
|
+
return e;
|
|
8793
|
+
}
|
|
8794
|
+
|
|
8795
|
+
/// One \`name: value\` header of an outbound request or an inbound response.
|
|
8796
|
+
@global
|
|
8797
|
+
export class DaemonHttpHeader {
|
|
8798
|
+
name: string;
|
|
8799
|
+
value: string;
|
|
8800
|
+
constructor(name: string, value: string) {
|
|
8801
|
+
this.name = name;
|
|
8802
|
+
this.value = value;
|
|
8803
|
+
}
|
|
8804
|
+
}
|
|
8805
|
+
|
|
8806
|
+
/// An outbound HTTP request. \`url\` must be an absolute \`http(s)\` URL; the host
|
|
8807
|
+
/// applies an SSRF guard to the resolved address, so a private/loopback target
|
|
8808
|
+
/// fails with \`DaemonError.CallFailed\` rather than connecting.
|
|
8809
|
+
@global
|
|
8810
|
+
export class DaemonHttpRequest {
|
|
8811
|
+
method: string = "GET";
|
|
8812
|
+
url: string = "";
|
|
8813
|
+
headers: DaemonHttpHeader[] = [];
|
|
8814
|
+
body: Uint8Array = new Uint8Array(0);
|
|
8815
|
+
|
|
8816
|
+
constructor(method: string = "GET", url: string = "") {
|
|
8817
|
+
this.method = method;
|
|
8818
|
+
this.url = url;
|
|
8819
|
+
}
|
|
8820
|
+
|
|
8821
|
+
/// Append a header. Returns \`this\` so calls chain.
|
|
8822
|
+
header(name: string, value: string): DaemonHttpRequest {
|
|
8823
|
+
this.headers.push(new DaemonHttpHeader(name, value));
|
|
8824
|
+
return this;
|
|
8825
|
+
}
|
|
8826
|
+
|
|
8827
|
+
/// Encode the little-endian request envelope the host decodes, or \`null\` when a
|
|
8828
|
+
/// field breaks a host cap (nothing is sent). Layout:
|
|
8829
|
+
/// u8 methodLen | method | u16 urlLen | url | u16 nHeaders
|
|
8830
|
+
/// | nHeaders * (u16 nameLen | name | u16 valLen | val)
|
|
8831
|
+
/// | u32 bodyLen | body
|
|
8832
|
+
encode(): Uint8Array | null {
|
|
8833
|
+
const method = Uint8Array.wrap(String.UTF8.encode(this.method));
|
|
8834
|
+
const url = Uint8Array.wrap(String.UTF8.encode(this.url));
|
|
8835
|
+
const nHeaders = this.headers.length;
|
|
8836
|
+
if (method.byteLength < 1 || method.byteLength > DAEMON_MAX_METHOD_BYTES) return null;
|
|
8837
|
+
if (url.byteLength > DAEMON_MAX_URL_BYTES) return null;
|
|
8838
|
+
if (nHeaders > DAEMON_MAX_HEADERS) return null;
|
|
8839
|
+
if (this.body.byteLength > DAEMON_MAX_REQUEST_BYTES) return null;
|
|
8840
|
+
|
|
8841
|
+
// Encode every header once: sizing and writing must agree on the byte counts.
|
|
8842
|
+
const names = new Array<Uint8Array>();
|
|
8843
|
+
const values = new Array<Uint8Array>();
|
|
8844
|
+
let headerBytes = 0;
|
|
8845
|
+
for (let i = 0; i < nHeaders; i++) {
|
|
8846
|
+
const h = this.headers[i];
|
|
8847
|
+
const n = Uint8Array.wrap(String.UTF8.encode(h.name));
|
|
8848
|
+
const v = Uint8Array.wrap(String.UTF8.encode(h.value));
|
|
8849
|
+
if (n.byteLength > DAEMON_MAX_HEADER_BYTES || v.byteLength > DAEMON_MAX_HEADER_BYTES) {
|
|
8850
|
+
return null;
|
|
8851
|
+
}
|
|
8852
|
+
names.push(n);
|
|
8853
|
+
values.push(v);
|
|
8854
|
+
headerBytes += 4 + n.byteLength + v.byteLength;
|
|
8855
|
+
}
|
|
8856
|
+
|
|
8857
|
+
// The host caps \`req_len\`, the WHOLE envelope, not just the body, and going over
|
|
8858
|
+
// is a trap rather than a typed error (\`daemon.http_call: req_len over cap\`). So
|
|
8859
|
+
// the total is what must be checked: a body just under the cap plus headers and a
|
|
8860
|
+
// long URL would otherwise kill the daemon.
|
|
8861
|
+
const size = 1 + method.byteLength + 2 + url.byteLength + 2 + headerBytes + 4 + this.body.byteLength;
|
|
8862
|
+
if (size > DAEMON_MAX_REQUEST_BYTES) return null;
|
|
8863
|
+
|
|
8864
|
+
const buf = new Uint8Array(size);
|
|
8865
|
+
const base = buf.dataStart;
|
|
8866
|
+
let off: usize = 0;
|
|
8867
|
+
|
|
8868
|
+
store<u8>(base + off, <u8>method.byteLength); off += 1;
|
|
8869
|
+
memory.copy(base + off, method.dataStart, <usize>method.byteLength); off += <usize>method.byteLength;
|
|
8870
|
+
store<u16>(base + off, <u16>url.byteLength); off += 2;
|
|
8871
|
+
memory.copy(base + off, url.dataStart, <usize>url.byteLength); off += <usize>url.byteLength;
|
|
8872
|
+
store<u16>(base + off, <u16>nHeaders); off += 2;
|
|
8873
|
+
for (let i = 0; i < nHeaders; i++) {
|
|
8874
|
+
const n = names[i];
|
|
8875
|
+
const v = values[i];
|
|
8876
|
+
store<u16>(base + off, <u16>n.byteLength); off += 2;
|
|
8877
|
+
memory.copy(base + off, n.dataStart, <usize>n.byteLength); off += <usize>n.byteLength;
|
|
8878
|
+
store<u16>(base + off, <u16>v.byteLength); off += 2;
|
|
8879
|
+
memory.copy(base + off, v.dataStart, <usize>v.byteLength); off += <usize>v.byteLength;
|
|
8880
|
+
}
|
|
8881
|
+
store<u32>(base + off, <u32>this.body.byteLength); off += 4;
|
|
8882
|
+
memory.copy(base + off, this.body.dataStart, <usize>this.body.byteLength);
|
|
8883
|
+
return buf;
|
|
8884
|
+
}
|
|
8885
|
+
}
|
|
8886
|
+
|
|
8887
|
+
/// An inbound HTTP response. \`status\` is 0 when the host itself failed before a
|
|
8888
|
+
/// reply existed. The body is truncated by the host at 1 MiB.
|
|
8889
|
+
@global
|
|
8890
|
+
export class DaemonHttpResponse {
|
|
8891
|
+
status: u16 = 0;
|
|
8892
|
+
headers: DaemonHttpHeader[] = [];
|
|
8893
|
+
body: Uint8Array = new Uint8Array(0);
|
|
8894
|
+
|
|
8895
|
+
/// Read a header's value (case-sensitive, first match), or \`null\`.
|
|
8896
|
+
header(name: string): string | null {
|
|
8897
|
+
for (let i = 0, n = this.headers.length; i < n; i++) {
|
|
8898
|
+
if (this.headers[i].name == name) return this.headers[i].value;
|
|
8899
|
+
}
|
|
8900
|
+
return null;
|
|
8901
|
+
}
|
|
8902
|
+
|
|
8903
|
+
/// The body decoded as UTF-8.
|
|
8904
|
+
text(): string {
|
|
8905
|
+
return String.UTF8.decodeUnsafe(this.body.dataStart, <usize>this.body.byteLength);
|
|
8906
|
+
}
|
|
8907
|
+
|
|
8908
|
+
/// Decode the little-endian response envelope, or \`null\` when it is truncated /
|
|
8909
|
+
/// self-inconsistent. Layout:
|
|
8910
|
+
/// u16 status | u16 nHeaders
|
|
8911
|
+
/// | nHeaders * (u16 nameLen | name | u16 valLen | val)
|
|
8912
|
+
/// | u32 bodyLen | body
|
|
8913
|
+
static decode(buf: Uint8Array, len: i32): DaemonHttpResponse | null {
|
|
8914
|
+
if (len < 0 || len > buf.byteLength) return null;
|
|
8915
|
+
const base = buf.dataStart;
|
|
8916
|
+
let off = 0;
|
|
8917
|
+
|
|
8918
|
+
if (off + 2 > len) return null;
|
|
8919
|
+
const out = new DaemonHttpResponse();
|
|
8920
|
+
out.status = load<u16>(base + <usize>off); off += 2;
|
|
8921
|
+
|
|
8922
|
+
if (off + 2 > len) return null;
|
|
8923
|
+
const nHeaders = <i32>load<u16>(base + <usize>off); off += 2;
|
|
8924
|
+
for (let i = 0; i < nHeaders; i++) {
|
|
8925
|
+
if (off + 2 > len) return null;
|
|
8926
|
+
const nameLen = <i32>load<u16>(base + <usize>off); off += 2;
|
|
8927
|
+
if (off + nameLen > len) return null;
|
|
8928
|
+
const name = String.UTF8.decodeUnsafe(base + <usize>off, <usize>nameLen); off += nameLen;
|
|
8929
|
+
|
|
8930
|
+
if (off + 2 > len) return null;
|
|
8931
|
+
const valLen = <i32>load<u16>(base + <usize>off); off += 2;
|
|
8932
|
+
if (off + valLen > len) return null;
|
|
8933
|
+
const value = String.UTF8.decodeUnsafe(base + <usize>off, <usize>valLen); off += valLen;
|
|
8934
|
+
|
|
8935
|
+
out.headers.push(new DaemonHttpHeader(name, value));
|
|
8936
|
+
}
|
|
8937
|
+
|
|
8938
|
+
if (off + 4 > len) return null;
|
|
8939
|
+
const bodyLen = <i32>load<u32>(base + <usize>off); off += 4;
|
|
8940
|
+
if (bodyLen < 0 || off + bodyLen > len) return null;
|
|
8941
|
+
const body = new Uint8Array(bodyLen);
|
|
8942
|
+
memory.copy(body.dataStart, base + <usize>off, <usize>bodyLen); off += bodyLen;
|
|
8943
|
+
|
|
8944
|
+
// A trailing tail means the guest and the host disagree on the framing.
|
|
8945
|
+
if (off != len) return null;
|
|
8946
|
+
out.body = body;
|
|
8947
|
+
return out;
|
|
8948
|
+
}
|
|
8949
|
+
}
|
|
8950
|
+
|
|
8951
|
+
/// The daemon scheduler surface. Every member is static: a cold box has exactly
|
|
8952
|
+
/// one daemon, and these read the resident host state.
|
|
8953
|
+
@global
|
|
8954
|
+
export class Daemon {
|
|
8955
|
+
/// Whether THIS node currently holds the lease. A snapshot: re-check it inside a
|
|
8956
|
+
/// long task rather than trusting the value it started with.
|
|
8957
|
+
static isLeader(): bool {
|
|
8958
|
+
return daemonHost.isLeader() != 0;
|
|
8959
|
+
}
|
|
8960
|
+
|
|
8961
|
+
/// The monotonic fencing token, bumped on every (re)acquire, or -1 when this
|
|
8962
|
+
/// node does not hold the lease. Stamp it into work that must not outlive the
|
|
8963
|
+
/// lease that authorized it.
|
|
8964
|
+
static epoch(): i64 {
|
|
8965
|
+
return daemonHost.currentEpoch();
|
|
8966
|
+
}
|
|
8967
|
+
|
|
8968
|
+
/// The number of registered \`@scheduled\` tasks.
|
|
8969
|
+
static taskCount(): i32 {
|
|
8970
|
+
return daemonHost.taskCount();
|
|
8971
|
+
}
|
|
8972
|
+
|
|
8973
|
+
/// The next wall-clock fire time for \`taskId\` in epoch ms, or -1 for an
|
|
8974
|
+
/// out-of-range id or a cron that never fires again.
|
|
8975
|
+
static nextFireMs(taskId: i32): i64 {
|
|
8976
|
+
return daemonHost.nextFireMs(taskId);
|
|
8977
|
+
}
|
|
8978
|
+
|
|
8979
|
+
/// Give the host a chance to observe a lost lease. \`None\` means still leader.
|
|
8980
|
+
/// Named \`yieldNow\` because \`yield\` is reserved.
|
|
8981
|
+
static yieldNow(): DaemonError {
|
|
8982
|
+
return __daemonNote(<i64>daemonHost.yieldNow());
|
|
8983
|
+
}
|
|
8984
|
+
|
|
8985
|
+
/// Park for \`ms\`, clamped by the host to its 3s ceiling (a negative \`ms\` does
|
|
8986
|
+
/// not park at all). \`None\` means the sleep completed and the lease still holds;
|
|
8987
|
+
/// \`LeaseLost\` means it was lost while parked, and the task should stop.
|
|
8988
|
+
static sleep(ms: i64): DaemonError {
|
|
8989
|
+
return __daemonNote(<i64>daemonHost.sleepMs(ms));
|
|
8990
|
+
}
|
|
8991
|
+
|
|
8992
|
+
/// Make an outbound HTTP request. Returns the response, or \`null\` on failure
|
|
8993
|
+
/// (read \`Daemon.lastError()\`).
|
|
8994
|
+
///
|
|
8995
|
+
/// \`responseCap\` sizes the guest buffer the host writes into. When the envelope
|
|
8996
|
+
/// does not fit, this returns \`null\` with \`ResponseTooLarge\` and DOES NOT retry:
|
|
8997
|
+
/// the request already went out, so a blind retry would issue it twice. Pass a
|
|
8998
|
+
/// bigger \`responseCap\` if you expect a large body.
|
|
8999
|
+
static httpCall(
|
|
9000
|
+
request: DaemonHttpRequest,
|
|
9001
|
+
responseCap: i32 = DAEMON_DEFAULT_RESPONSE_CAP,
|
|
9002
|
+
): DaemonHttpResponse | null {
|
|
9003
|
+
const req = request.encode();
|
|
9004
|
+
if (req == null) {
|
|
9005
|
+
__daemonLastError = DaemonError.BadEnvelope;
|
|
9006
|
+
return null;
|
|
9007
|
+
}
|
|
9008
|
+
const reqBuf = <Uint8Array>req;
|
|
9009
|
+
const cap = responseCap > 0 ? responseCap : DAEMON_DEFAULT_RESPONSE_CAP;
|
|
9010
|
+
const out = new Uint8Array(cap);
|
|
9011
|
+
const n = daemonHost.httpCall(reqBuf.dataStart, reqBuf.byteLength, out.dataStart, cap);
|
|
9012
|
+
if (n < 0) {
|
|
9013
|
+
__daemonNote(n);
|
|
9014
|
+
return null;
|
|
9015
|
+
}
|
|
9016
|
+
const res = DaemonHttpResponse.decode(out, <i32>n);
|
|
9017
|
+
__daemonLastError = res == null ? DaemonError.BadEnvelope : DaemonError.None;
|
|
9018
|
+
return res;
|
|
9019
|
+
}
|
|
9020
|
+
|
|
9021
|
+
/// The failure recorded by the most recent \`Daemon\` call.
|
|
9022
|
+
static lastError(): DaemonError {
|
|
9023
|
+
return __daemonLastError;
|
|
9024
|
+
}
|
|
9025
|
+
}
|
|
8594
9026
|
`,data:`/**
|
|
8595
9027
|
* Binary buffers for the \`@data\` tagged codec.
|
|
8596
9028
|
*
|
|
@@ -18840,6 +19272,151 @@ function __toildbTakeGrow(): Uint8Array {
|
|
|
18840
19272
|
return buf.subarray(0, n);
|
|
18841
19273
|
}
|
|
18842
19274
|
|
|
19275
|
+
/// A typed ToilDB failure, the \`TDLnnn\` diagnostic of spec 27.1. The host bridges
|
|
19276
|
+
/// one as \`-(1000 + nnn)\`; the two small sentinels are NOT failures (\`-1\` output
|
|
19277
|
+
/// buffer too small, \`-2\` absent), so both decode to \`None\`.
|
|
19278
|
+
///
|
|
19279
|
+
/// Only a SUBSET can ever reach guest code. A hard fault (budget/quota, storage,
|
|
19280
|
+
/// integrity, capability/schema) is indistinguishable from a benign outcome at the
|
|
19281
|
+
/// ABI, so returning it would silently drop the op; the host TRAPS the request
|
|
19282
|
+
/// instead and the guest never runs again (toil-backend \`status_is_hard_fault\`).
|
|
19283
|
+
/// The members below say which is which. Every code is still listed, because
|
|
19284
|
+
/// \`Db.errorOf\` decodes any raw status.
|
|
19285
|
+
///
|
|
19286
|
+
/// So after a read returns \`null\`, \`Db.lastError()\` is either \`None\` (the row is
|
|
19287
|
+
/// absent) or one of the four RETRYABLE availability signals. \`AlreadyExists\` and
|
|
19288
|
+
/// \`Conflict\` are write outcomes, not read ones.
|
|
19289
|
+
@global
|
|
19290
|
+
export enum DbError {
|
|
19291
|
+
/// No failure: the operation succeeded, or the row was simply absent.
|
|
19292
|
+
None = 0,
|
|
19293
|
+
/// TDL001: the collection handle is not one the host issued. HARD FAULT: traps.
|
|
19294
|
+
InvalidHandle = 1,
|
|
19295
|
+
/// TDL002: wrong tenant, or the row's MAC did not verify. HARD FAULT: traps.
|
|
19296
|
+
TenantMismatch = 2,
|
|
19297
|
+
/// TDL003: a \`create\` found the key already present. A write outcome.
|
|
19298
|
+
AlreadyExists = 3,
|
|
19299
|
+
/// TDL004: a compare-and-set lost, or a \`@unique\` value is owned elsewhere. A
|
|
19300
|
+
/// write outcome.
|
|
19301
|
+
Conflict = 4,
|
|
19302
|
+
/// TDL005: the operation is not supported here. HARD FAULT: traps.
|
|
19303
|
+
Unsupported = 5,
|
|
19304
|
+
/// TDL006: the value did not decode against its schema. HARD FAULT: traps.
|
|
19305
|
+
Codec = 6,
|
|
19306
|
+
/// TDL007: an internal storage failure. HARD FAULT: traps.
|
|
19307
|
+
Backend = 7,
|
|
19308
|
+
/// TDL010: the op does not exist for this collection family. HARD FAULT: traps.
|
|
19309
|
+
OpNotAllowedForFamily = 10,
|
|
19310
|
+
/// TDL011: the op is not allowed for this kind, or at this tier. HARD FAULT: traps.
|
|
19311
|
+
OpNotAllowedInKind = 11,
|
|
19312
|
+
/// TDL020: too many ops, or too many keys in one multi-op. HARD FAULT: traps.
|
|
19313
|
+
OpBudget = 20,
|
|
19314
|
+
/// TDL021: the request or its result exceeds the byte budget. HARD FAULT: traps.
|
|
19315
|
+
ByteBudget = 21,
|
|
19316
|
+
/// TDL022: the value nests too deeply. HARD FAULT: traps.
|
|
19317
|
+
DepthBudget = 22,
|
|
19318
|
+
/// TDL025: the tenant is over its plan quota. HARD FAULT: traps, so a guest can
|
|
19319
|
+
/// never observe this. It is here only to decode a raw status.
|
|
19320
|
+
QuotaExceeded = 25,
|
|
19321
|
+
/// TDL030: a backfill is throttling this read. RETRYABLE.
|
|
19322
|
+
FillThrottled = 30,
|
|
19323
|
+
/// TDL031: the home region, or the data, is temporarily unavailable. RETRYABLE.
|
|
19324
|
+
Unavailable = 31,
|
|
19325
|
+
/// TDL040: this key is a hot partition. RETRYABLE.
|
|
19326
|
+
HotPartition = 40,
|
|
19327
|
+
/// TDL041: too many cold reads at once. RETRYABLE.
|
|
19328
|
+
ColdStorm = 41,
|
|
19329
|
+
/// TDL070: the schema is temporarily unavailable. HARD FAULT: traps.
|
|
19330
|
+
SchemaUnavailable = 70,
|
|
19331
|
+
/// TDL090: a catalog op outside an admin context. HARD FAULT: traps.
|
|
19332
|
+
CatalogOutsideAdmin = 90,
|
|
19333
|
+
/// A negative status that carries no known \`TDLnnn\`.
|
|
19334
|
+
Unknown = -1,
|
|
19335
|
+
}
|
|
19336
|
+
|
|
19337
|
+
/// The typed failure of the last read that returned \`null\`/empty. See \`Db\`.
|
|
19338
|
+
// @ts-ignore: decorator
|
|
19339
|
+
@lazy
|
|
19340
|
+
var __toildbLastError: DbError = DbError.None;
|
|
19341
|
+
|
|
19342
|
+
/// Decode a raw host status into a typed failure. Non-negative, \`-1\` (buffer too
|
|
19343
|
+
/// small) and \`-2\` (absent) are all \`None\`: only the \`<= -1000\` band is a failure.
|
|
19344
|
+
function __toildbErrorOf(status: i32): DbError {
|
|
19345
|
+
if (status >= -2) return DbError.None;
|
|
19346
|
+
const code = -status - 1000;
|
|
19347
|
+
if (code < 0) return DbError.Unknown;
|
|
19348
|
+
switch (code) {
|
|
19349
|
+
case 1: return DbError.InvalidHandle;
|
|
19350
|
+
case 2: return DbError.TenantMismatch;
|
|
19351
|
+
case 3: return DbError.AlreadyExists;
|
|
19352
|
+
case 4: return DbError.Conflict;
|
|
19353
|
+
case 5: return DbError.Unsupported;
|
|
19354
|
+
case 6: return DbError.Codec;
|
|
19355
|
+
case 7: return DbError.Backend;
|
|
19356
|
+
case 10: return DbError.OpNotAllowedForFamily;
|
|
19357
|
+
case 11: return DbError.OpNotAllowedInKind;
|
|
19358
|
+
case 20: return DbError.OpBudget;
|
|
19359
|
+
case 21: return DbError.ByteBudget;
|
|
19360
|
+
case 22: return DbError.DepthBudget;
|
|
19361
|
+
case 25: return DbError.QuotaExceeded;
|
|
19362
|
+
case 30: return DbError.FillThrottled;
|
|
19363
|
+
case 31: return DbError.Unavailable;
|
|
19364
|
+
case 40: return DbError.HotPartition;
|
|
19365
|
+
case 41: return DbError.ColdStorm;
|
|
19366
|
+
case 70: return DbError.SchemaUnavailable;
|
|
19367
|
+
case 90: return DbError.CatalogOutsideAdmin;
|
|
19368
|
+
default: return DbError.Unknown;
|
|
19369
|
+
}
|
|
19370
|
+
}
|
|
19371
|
+
|
|
19372
|
+
/// Record the outcome of a read that is about to return \`null\`. An absent row
|
|
19373
|
+
/// records \`None\`, so \`null\` + \`None\` means "not found" and \`null\` + anything else
|
|
19374
|
+
/// means "failed".
|
|
19375
|
+
function __toildbMiss(status: i32): void {
|
|
19376
|
+
__toildbLastError = __toildbErrorOf(status);
|
|
19377
|
+
}
|
|
19378
|
+
|
|
19379
|
+
/// ToilDB diagnostics. Read \`lastError()\` immediately after a read returns \`null\`
|
|
19380
|
+
/// to tell an absent row from a failed one; the next read overwrites it.
|
|
19381
|
+
///
|
|
19382
|
+
/// \`\`\`ts
|
|
19383
|
+
/// const u = App.users.get(id);
|
|
19384
|
+
/// if (u == null && Db.isRetryable(Db.lastError())) {
|
|
19385
|
+
/// // The row may well exist: the store is briefly unavailable. Retry or 503.
|
|
19386
|
+
/// }
|
|
19387
|
+
/// \`\`\`
|
|
19388
|
+
///
|
|
19389
|
+
/// ONLY \`Documents.get\`, \`Documents.getDelete\`, \`View.get\` and \`Unique.lookup\`
|
|
19390
|
+
/// record into this. Every other ToilDB op either succeeds or traps. The \`Analytics\`
|
|
19391
|
+
/// reads also answer \`null\`, but on their own \`-2 absent\` / \`-3 forbidden\` statuses
|
|
19392
|
+
/// rather than a \`TDLnnn\`, so they leave \`lastError()\` untouched: do not consult it
|
|
19393
|
+
/// after one, or you will read a stale value from an earlier ToilDB read.
|
|
19394
|
+
@global
|
|
19395
|
+
export class Db {
|
|
19396
|
+
/// The failure recorded by the most recent read that returned \`null\`. \`None\`
|
|
19397
|
+
/// when that read simply found nothing.
|
|
19398
|
+
static lastError(): DbError {
|
|
19399
|
+
return __toildbLastError;
|
|
19400
|
+
}
|
|
19401
|
+
|
|
19402
|
+
/// Decode a raw negative host status into its typed failure.
|
|
19403
|
+
static errorOf(status: i32): DbError {
|
|
19404
|
+
return __toildbErrorOf(status);
|
|
19405
|
+
}
|
|
19406
|
+
|
|
19407
|
+
/// Whether \`err\` is a transient availability signal, so the same read may well
|
|
19408
|
+
/// succeed later. These are the ONLY failures a read can hand back: everything
|
|
19409
|
+
/// else traps the request before the guest resumes.
|
|
19410
|
+
static isRetryable(err: DbError): bool {
|
|
19411
|
+
return (
|
|
19412
|
+
err == DbError.FillThrottled ||
|
|
19413
|
+
err == DbError.Unavailable ||
|
|
19414
|
+
err == DbError.HotPartition ||
|
|
19415
|
+
err == DbError.ColdStorm
|
|
19416
|
+
);
|
|
19417
|
+
}
|
|
19418
|
+
}
|
|
19419
|
+
|
|
18843
19420
|
/// A mutable keyed-entity collection (spec 7.1). \`V\` is the \`@data\` value type,
|
|
18844
19421
|
/// \`K\` the \`@data\` key type.
|
|
18845
19422
|
@global
|
|
@@ -18866,7 +19443,7 @@ export class Documents<K, V> {
|
|
|
18866
19443
|
get(key: K): V | null {
|
|
18867
19444
|
const kb = key.encode();
|
|
18868
19445
|
const status = toildbHost.get(this.__handle, kb.dataStart, kb.byteLength);
|
|
18869
|
-
if (status < 0) return null;
|
|
19446
|
+
if (status < 0) { __toildbMiss(status); return null; }
|
|
18870
19447
|
__toildbResetMigrated();
|
|
18871
19448
|
const v = instantiate<V>();
|
|
18872
19449
|
v.decodeInto(__toildbTake(status));
|
|
@@ -18994,7 +19571,7 @@ export class Documents<K, V> {
|
|
|
18994
19571
|
getDelete(key: K): V | null {
|
|
18995
19572
|
const kb = key.encode();
|
|
18996
19573
|
const status = toildbHost.getDelete(this.__handle, kb.dataStart, kb.byteLength, 0);
|
|
18997
|
-
if (status < 0) return null;
|
|
19574
|
+
if (status < 0) { __toildbMiss(status); return null; }
|
|
18998
19575
|
const v = instantiate<V>();
|
|
18999
19576
|
v.decodeInto(__toildbTake(status));
|
|
19000
19577
|
return v;
|
|
@@ -19017,7 +19594,7 @@ export class View<K, V> {
|
|
|
19017
19594
|
get(key: K): V | null {
|
|
19018
19595
|
const kb = key.encode();
|
|
19019
19596
|
const status = toildbHost.viewGet(this.__handle, kb.dataStart, kb.byteLength);
|
|
19020
|
-
if (status < 0) return null;
|
|
19597
|
+
if (status < 0) { __toildbMiss(status); return null; }
|
|
19021
19598
|
const v = instantiate<V>();
|
|
19022
19599
|
v.decodeInto(__toildbTake(status));
|
|
19023
19600
|
return v;
|
|
@@ -19063,7 +19640,7 @@ export class Unique<K, V> {
|
|
|
19063
19640
|
lookup(key: K): V | null {
|
|
19064
19641
|
const kb = key.encode();
|
|
19065
19642
|
const status = toildbHost.uniqueLookup(this.__handle, kb.dataStart, kb.byteLength);
|
|
19066
|
-
if (status < 0) return null;
|
|
19643
|
+
if (status < 0) { __toildbMiss(status); return null; }
|
|
19067
19644
|
const v = instantiate<V>();
|
|
19068
19645
|
v.decodeInto(__toildbTake(status));
|
|
19069
19646
|
return v;
|
|
@@ -19299,6 +19876,14 @@ export enum MetricId {
|
|
|
19299
19876
|
/// section.
|
|
19300
19877
|
export const METRIC_COUNTERS: i32 = 42;
|
|
19301
19878
|
|
|
19879
|
+
/// The sustained-rate window (seconds): requests are metered over a 3-minute ROLLING window. A plan's
|
|
19880
|
+
/// sustained request rate \`X\` (rps) permits \`X * BURST_WINDOW_SECS\` requests across it. Instantaneous
|
|
19881
|
+
/// spikes ABOVE the sustained rate are NOT tier-capped (only the box firewall's global pps ceiling, the
|
|
19882
|
+
/// DDoS backstop, applies); throttling (HTTP 429) begins only once the window's allowance is spent.
|
|
19883
|
+
/// The window slides continuously rather than resetting on a boundary, so a spend does not become free
|
|
19884
|
+
/// all at once: it ages out gradually over the following 3 minutes.
|
|
19885
|
+
export const BURST_WINDOW_SECS: i32 = 180;
|
|
19886
|
+
|
|
19302
19887
|
/// A dashboard time range for \`Analytics.series\`. Short ranges (1h/6h) read the per-MINUTE ring; the long
|
|
19303
19888
|
/// ranges (60d/90d) read the per-DAY ring (90-day retention); the rest read the per-HOUR ring (30-day).
|
|
19304
19889
|
/// Append-only: never renumber (D60/D90 were added after D30, keeping the wire ids stable).
|
|
@@ -19324,11 +19909,14 @@ export class TenantStats {
|
|
|
19324
19909
|
/// Live gauges (current level, not a total).
|
|
19325
19910
|
connectedStreams: u64 = 0;
|
|
19326
19911
|
committedMemory: u64 = 0;
|
|
19327
|
-
/// Request
|
|
19328
|
-
|
|
19329
|
-
|
|
19330
|
-
|
|
19331
|
-
|
|
19912
|
+
/// Request meters (fleet-global, across every edge location) against the plan (cap 0 = unmetered).
|
|
19913
|
+
/// Burst: requests in the trailing 3-minute ROLLING window vs its allowance
|
|
19914
|
+
/// (\`sustained_rps * BURST_WINDOW_SECS\`). 30d: requests in the current 30-day bucket vs the quota
|
|
19915
|
+
/// (the quota still tumbles: it is a billing period, not a rate).
|
|
19916
|
+
reqBurstUsed: u64 = 0;
|
|
19917
|
+
reqBurstCap: u64 = 0;
|
|
19918
|
+
req30dUsed: u64 = 0;
|
|
19919
|
+
req30dCap: u64 = 0;
|
|
19332
19920
|
/// LIVE per-second gauges (rates), computed edge-side from the last completed minute bucket so the
|
|
19333
19921
|
/// guest is STATELESS (no client diffing of two snapshots). Idle -> 0.0. \`f64\` (a rate is fractional
|
|
19334
19922
|
/// and bounded; f64 cannot overflow for any real value).
|
|
@@ -19404,6 +19992,13 @@ export class TenantStats {
|
|
|
19404
19992
|
const total = hits + this.cacheMisses;
|
|
19405
19993
|
return total > 0 ? <f64>hits / <f64>total : 0.0;
|
|
19406
19994
|
}
|
|
19995
|
+
|
|
19996
|
+
/// The plan's SUSTAINED request rate (requests/second), derived from the 3-minute burst cap
|
|
19997
|
+
/// (\`reqBurstCap / BURST_WINDOW_SECS\`). 0.0 means unmetered. Spikes above this rate are allowed;
|
|
19998
|
+
/// throttling only starts once \`reqBurstUsed\` passes \`reqBurstCap\` in the current bucket.
|
|
19999
|
+
get sustainedRpsCap(): f64 {
|
|
20000
|
+
return this.reqBurstCap == 0 ? 0.0 : <f64>this.reqBurstCap / <f64>BURST_WINDOW_SECS;
|
|
20001
|
+
}
|
|
19407
20002
|
}
|
|
19408
20003
|
|
|
19409
20004
|
/// One metric's time series for a range: \`points\` oldest\u2192newest (per-bucket totals, \`u64\` \u2014 non-negative),
|
|
@@ -19446,7 +20041,7 @@ export class Analytics {
|
|
|
19446
20041
|
const r = new DataReader(buf);
|
|
19447
20042
|
const stats = new TenantStats();
|
|
19448
20043
|
const version = r.readU16();
|
|
19449
|
-
if (version <
|
|
20044
|
+
if (version < 3) return stats; // pre-v3 edge: refuse rather than mis-decode (clean break, no v2)
|
|
19450
20045
|
stats.nowMs = r.readU64();
|
|
19451
20046
|
const count = <i32>r.readU32();
|
|
19452
20047
|
for (let i: i32 = 0; i < count && r.ok; i++) {
|
|
@@ -19456,10 +20051,10 @@ export class Analytics {
|
|
|
19456
20051
|
}
|
|
19457
20052
|
stats.connectedStreams = r.readU64();
|
|
19458
20053
|
stats.committedMemory = r.readU64();
|
|
19459
|
-
stats.
|
|
19460
|
-
stats.
|
|
19461
|
-
stats.
|
|
19462
|
-
stats.
|
|
20054
|
+
stats.reqBurstUsed = r.readU64();
|
|
20055
|
+
stats.reqBurstCap = r.readU64();
|
|
20056
|
+
stats.req30dUsed = r.readU64();
|
|
20057
|
+
stats.req30dCap = r.readU64();
|
|
19463
20058
|
// LIVE per-second rates (f64), appended after the windows. VERSION-GATE by LENGTH: a pre-rates
|
|
19464
20059
|
// (shorter) frame from an older edge exhausts the buffer here, so \`readF64\` returns 0.0 for each
|
|
19465
20060
|
// missing rate (DataReader is bounds-checked). No frame-version bump needed.
|
|
@@ -19477,7 +20072,7 @@ export class Analytics {
|
|
|
19477
20072
|
const r = new DataReader(buf);
|
|
19478
20073
|
const out = new Series();
|
|
19479
20074
|
const version = r.readU16();
|
|
19480
|
-
if (version <
|
|
20075
|
+
if (version < 3) return out; // pre-v3 edge: refuse rather than mis-decode (clean break, no v2)
|
|
19481
20076
|
out.metric = <MetricId>r.readU16();
|
|
19482
20077
|
out.bucketSecs = r.readU32();
|
|
19483
20078
|
out.headMs = r.readU64();
|
|
@@ -30693,7 +31288,7 @@ declare interface Float64Array {
|
|
|
30693
31288
|
// FIXME: remove
|
|
30694
31289
|
declare function offsetof<T>(fieldName?: string): usize;
|
|
30695
31290
|
declare function idof<T>(): u32;
|
|
30696
|
-
`};var xn={};nn(xn,{default:()=>gn});In(xn,Vt);import*as Vt from"binaryen";import{default as gn}from"binaryen";import*as Tt from"toilscript";var
|
|
31291
|
+
`};var xn={};nn(xn,{default:()=>gn});In(xn,Vt);import*as Vt from"binaryen";import{default as gn}from"binaryen";import*as Tt from"toilscript";var p=Tt,Vn=P.argv.indexOf("--wasm");if(~Vn){let e=String(P.argv[Vn+1]);P.argv.splice(Vn,2),p=await import(new URL(e,pn.pathToFileURL(P.cwd()+"/")))}var Hn=sn.createRequire(import.meta.url),qn=P.platform==="win32",T=qn?`\r
|
|
30697
31292
|
`:`
|
|
30698
|
-
`,Hn=qn?"\\":"/",_=".ts",Ct=`.d${_}`,ln=new RegExp("\\"+_+"$"),zt=new RegExp("^(?!.*\\.d\\"+_+"$).*\\"+_+"$");function Ce(e){return e.replace(/-/g,"_").toUpperCase()}function St(e){return typeof e=="string"&&e!==""}var Kn=Ee,wt=Y,V=Ae,j=_e,Bt=Te,we=3,Be=0;function Wn(e,t=[]){return Object.keys(e||{}).forEach(n=>{let a=e[n],s=Y[n];s&&s.type==="b"?a&&t.push(`--${n}`):Array.isArray(a)?a.forEach(o=>{t.push(`--${n}`,String(o))}):t.push(`--${n}`,String(a))}),t}async function Dt(e,t={}){typeof e=="string"&&(e={[`input${_}`]:e});let n=["--outFile","binary","--textFile","text"];Wn(t,n);let a={},s=await De(n.concat(Object.keys(e)),{readFile:o=>Object.prototype.hasOwnProperty.call(e,o)?e[o]:null,writeFile:(o,c)=>{a[o]=c},listFiles:()=>[]});return Object.assign(s,a)}async function De(e,t){Array.isArray(e)||(e=Wn(e)),t||(t={});let n=t.stats||new zn,a=n.begin(),s=0,o=0,c=0,d=(Kn||"").split(".");d.length===3&&(o=parseInt(d[0])|0,s=parseInt(d[1])|0,c=parseInt(d[2])|0);let x=t.stdout||Xn(),b=t.stderr||Xn(),p=t.readFile||te,g=t.writeFile||ie,y=t.listFiles||re,m=ve(e,Y,!1),i=m.options;e=m.arguments;let Sn=new en(x),H=new en(b);i.noColors&&(Sn.enabled=!1,H.enabled=!1);let Jn=m.unknown;Jn.length&&Jn.forEach(r=>{b.write(`${H.yellow("WARNING ")}Unknown option '${r}'${T}`)});let Zn=m.trailing;Zn.length&&b.write(`${H.yellow("WARNING ")}Unsupported trailing arguments: ${Zn.join(" ")}${T}`);let K=null,R=null,z=(r,l={})=>(r&&b.write(`${H.red("FAILURE ")}${r.stack.replace(/^ERROR: /i,"")}${T}`),R&&R.dispose(),n.total||(n.total=n.end(a)),Object.assign({error:r,stdout:x,stderr:b,stats:n},l));if(i.version)return x.write(`Version ${Kn}${T}`),z(null);let S=E.normalize(i.baseDir||"."),X=tn(i.config||"toilconfig.json",S),wn=E.basename(X),J=E.dirname(X),N=await ze(wn,J,p),Ie=N!=null&&Array.isArray(N.entries)&&N.entries.length;if(i.help||!e.length&&!Ie){let r=i.help?x:b,l=i.help?Sn:H;return r.write([l.white("SYNTAX")," "+l.cyan("toilscript")+" [entryFile ...] [options]","",l.white("EXAMPLES")," "+l.cyan("toilscript")+" hello"+_," "+l.cyan("toilscript")+" hello"+_+" -o hello.wasm -t hello.wat"," "+l.cyan("toilscript")+" hello1"+_+" hello2"+_+" -o -O > hello.wasm"," "+l.cyan("toilscript")+" --config toilconfig.json --target release","",l.white("OPTIONS")].concat(Fe(Y,24,T)).join(T)+T),z(null)}if(!(M.promises&&M.promises.readFile)){if(p===te)throw Error("'options.readFile' must be specified");if(g===ie)throw Error("'options.writeFile' must be specified");if(y===re)throw Error("'options.listFiles' must be specified")}let Bn=new Set;Bn.add(X);let ke=!!i.noConfigEntries,Oe=i.target||"release";for(;N;){if(N.targets){let l=N.targets[Oe];l&&(i=Mn(Y,i,l,J))}let r=N.options;if(r&&(i=Mn(Y,i,r,J)),N.entries&&!ke)for(let l of N.entries)e.push(tn(l,J));if(N.extends){if(X=tn(N.extends,J,!0),wn=E.basename(X),J=E.dirname(X),Bn.has(X))break;Bn.add(X),N=await ze(wn,J,p)}else break}if(Pn(Y,i),i.showConfig)return b.write(JSON.stringify({options:i,entries:e},null,2)),z(null);function $n(r){return[...new Set(r)]}let w,rn,bn,C=h.newOptions();switch(i.runtime){case"stub":rn=0;break;case"minimal":rn=1;break;case"memory":rn=3;break;default:rn=2;break}switch(i.uncheckedBehavior){default:bn=0;break;case"never":bn=1;break;case"always":bn=2;break}let un=null;if(i.targetMode!=null&&String(i.targetMode).length>0&&(un=String(i.targetMode),un!=="hot"&&un!=="cold"))return z(Error(`Target mode '${un}' is invalid; expected 'hot' or 'cold'.`));if(h.setTargetMode(C,un),h.setAuthUser(C,!!i.authUser),h.setTarget(C,0),h.setDebugInfo(C,!!i.debug),h.setRuntime(C,rn),h.setNoAssert(C,i.noAssert),h.setExportMemory(C,!i.noExportMemory),h.setImportMemory(C,i.importMemory),h.setInitialMemory(C,i.initialMemory>>>0),h.setMaximumMemory(C,i.maximumMemory>>>0),h.setSharedMemory(C,i.sharedMemory),h.setImportTable(C,i.importTable),h.setExportTable(C,i.exportTable),i.exportStart!=null&&h.setExportStart(C,St(i.exportStart)?i.exportStart:"_start"),h.setMemoryBase(C,i.memoryBase>>>0),h.setTableBase(C,i.tableBase>>>0),h.setSourceMap(C,i.sourceMap!=null),h.setUncheckedBehavior(C,bn),h.setNoUnsafe(C,i.noUnsafe),h.setPedantic(C,i.pedantic),h.setLowMemoryLimit(C,i.lowMemoryLimit>>>0),h.setExportRuntime(C,i.exportRuntime),h.setBundleVersion(C,o,s,c),!i.stackSize&&rn===2&&(i.stackSize=h.DEFAULT_STACK_SIZE),h.setStackSize(C,i.stackSize),h.setBindingsHint(C,i.bindings&&i.bindings.length>0),i.use){let r=i.use;for(let l=0,f=r.length;l<f;++l){let u=r[l],v=u.indexOf("=");if(v<0)return z(Error(`Global alias '${u}' is invalid.`));let F=u.substring(0,v).trim(),A=u.substring(v+1).trim();if(!F.length)return z(Error(`Global alias '${u}' is invalid.`));h.addGlobalAlias(C,F,A)}}let U;if((U=i.disable)!=null){typeof U=="string"&&(U=U.split(","));for(let r=0,l=U.length;r<l;++r){let f=U[r].trim(),u=h[`FEATURE_${Ce(f)}`];if(!u)return z(Error(`Feature '${f}' is unknown.`));h.setFeature(C,u,!1)}}if((U=i.enable)!=null){typeof U=="string"&&(U=U.split(","));for(let r=0,l=U.length;r<l;++r){let f=U[r].trim(),u=h[`FEATURE_${Ce(f)}`];if(!u)return z(Error(`Feature '${f}' is unknown.`));h.setFeature(C,u,!0)}}let Z=0,$=0;i.optimize&&(Z=we,$=Be),typeof i.optimizeLevel=="number"&&(Z=i.optimizeLevel),typeof i.shrinkLevel=="number"&&($=i.shrinkLevel),Z=Math.min(Math.max(Z,0),3),$=Math.min(Math.max($,0),2),h.setOptimizeLevelHints(C,Z,$),w=h.newProgram(C);let an=[];if(Array.isArray(t.transforms)&&an.push(...t.transforms),i.transform){let r=$n(i.transform);for(let l=0,f=r.length;l<f;++l){let u=r[l].trim(),v,F;if(Gn.resolve)try{v=Gn.resolve(u,{paths:[P.cwd(),S]}),F=await import(hn.pathToFileURL(v)),F.default&&(F=F.default)}catch(A){try{F=Gn(v)}catch{return z(A)}}else try{F=await import(new URL(u,import.meta.url)),F.default&&(F=F.default)}catch(A){return z(A)}if(!F||typeof F!="function"&&typeof F!="object")return z(Error("not a transform: "+r[l]));an.push(F)}}try{an=an.map(r=>(typeof r=="function"&&(Object.assign(r.prototype,{program:w,binaryen:gn,baseDir:S,stdout:x,stderr:b,log:console.error,readFile:p,writeFile:g,listFiles:y}),r=new r),r))}catch(r){return z(r)}async function Dn(r,...l){for(let f=0,u=an.length;f<u;++f){let v=an[f];if(typeof v[r]=="function")try{let F=n.begin();n.transformCount++,await v[r](...l),n.transformTime+=n.end(F)}catch(F){return F}}}Object.keys(j).forEach(r=>{if(r.includes("/"))return;let l=n.begin();n.parseCount++,h.parse(w,j[r],V+r+_,!1),n.parseTime+=n.end(l)});let on=[];if(i.lib){let r=i.lib;typeof r=="string"&&(r=r.split(",")),on.push(...r.map(l=>l.trim())),on=$n(on);for(let l=0,f=on.length;l<f;++l){let u=on[l],v;u.endsWith(_)?(v=[E.basename(u)],u=E.dirname(u)):v=await y(u,S)||[];for(let F of v){let A=await p(F,u);if(A==null)return z(Error(`Library file '${F}' not found.`));j[F.replace(ln,"")]=A;let k=n.begin();n.parseCount++,h.parse(w,A,V+F,!1),n.parseTime+=n.end(k)}}}i.path=i.path||[];let yn=new Map;async function Le(r,l){let f=null,u=null;if(!r.startsWith(V))(f=await p(u=r+_,S))==null&&(f=await p(u=r+"/index"+_,S))==null&&(u=r+_,f=await p(r+Ct,S));else{let v=r.substring(V.length),F=`${v}/index`;if(Object.prototype.hasOwnProperty.call(j,v))f=j[v],u=V+v+_;else if(Object.prototype.hasOwnProperty.call(j,F))f=j[F],u=V+F+_;else{for(let A of on)if((f=await p(v+_,A))!=null){u=V+v+_;break}else if((f=await p(F+_,A))!=null){u=V+F+_;break}if(f==null){let A=r.match(/^~lib\/((?:@[^/]+\/)?[^/]+)(?:\/(.+))?/);if(A){let k=A[1],q=A[2]||"index",En=yn.has(l)?yn.get(l):".",O=[],D=E.resolve(S,En).split(Hn);for(let B=D.length,L=qn?1:0;B>=L;--B)D[B-1]!=="node_modules"&&O.push(`${D.slice(0,B).join(Hn)}${Hn}node_modules`);O.push(...i.path);for(let B of O.map(L=>E.relative(S,L))){let L=q;if((f=await p(E.join(B,k,L+_),S))!=null){u=`${V}${k}/${L}${_}`,yn.set(u.replace(ln,""),E.join(B,k));break}let cn=`${q}/index`;if((f=await p(E.join(B,k,cn+_),S))!=null){u=`${V}${k}/${cn}${_}`,yn.set(u.replace(ln,""),E.join(B,k));break}}}}}}return f==null?null:{sourceText:f,sourcePath:u}}function Re(r=[]){do{let l=h.nextFile(w);if(l==null)break;r.push(l)}while(!0);return r}async function Qn(){let r;for(;(r=Re()).length;){let f=[];for(let u of r){let v=h.getDependee(w,u);f.push(Le(u,v))}f=await Promise.all(f);for(let u=0,v=r.length;u<v;++u){let F=r[u],A=f[u],k=n.begin();n.parseCount++,A?h.parse(w,A.sourceText,A.sourcePath,!1):h.parse(w,null,F+_,!1),n.parseTime+=n.end(k)}}let l=mn(w,b,i.disableWarning,t.reportDiagnostic,H.enabled);if(l){let f=Error(`${l} parse error(s)`);return f.stack=f.message,z(f)}}{let r=String(i.runtime),l=`rt/index-${r}`,f=j[l];if(f==null){if(l=r,f=await p(l+_,S),f==null)return z(Error(`Runtime '${E.resolve(S,l+_)}' is not found.`))}else l=`~lib/${l}`;let u=n.begin();n.parseCount++,h.parse(w,f,l+_,!0),n.parseTime+=n.end(u)}for(let r=0,l=e.length;r<l;++r){let f=String(e[r]),u=E.isAbsolute(f)?E.relative(S,f):E.normalize(f);u=u.replace(/\\/g,"/").replace(ln,"").replace(/\/$/,"");let v=await p(u+_,S);if(v==null){let A=`${u}/index${_}`;v=await p(A,S),v!=null?u=A:u+=_}else u+=_;let F=n.begin();n.parseCount++,h.parse(w,v,u,!0),n.parseTime+=n.end(F)}if(i.rpcSurfaceFiles!=null&&i.rpcSurfaceFiles.length)for(let r=0,l=i.rpcSurfaceFiles.length;r<l;++r){let f=String(i.rpcSurfaceFiles[r]),u=E.isAbsolute(f)?E.relative(S,f):E.normalize(f);u=u.replace(/\\/g,"/").replace(ln,"").replace(/\/$/,"");let v=await p(u+_,S);if(v==null){let F=`${u}/index${_}`;v=await p(F,S),v!=null?u=F:u+=_}else u+=_;v!=null?(n.parseCount++,h.parse(w,v,u,!1)):h.parse(w,null,u,!1)}if(M.promises&&M.promises.readdir){let r=[],l=async(f,u)=>{let v;try{v=await M.promises.readdir(f,{withFileTypes:!0})}catch{return}for(let F of v){let A=F.name;if(F.isDirectory()){if(A==="node_modules"||A==="build"||A==="dist"||A.charAt(0)===".")continue;await l(E.join(f,A),u?u+"/"+A:A)}else A.endsWith(".migration"+_)&&r.push(u?u+"/"+A:A)}};await l(E.resolve(S),"");for(let f of r){let u=f.replace(/\\/g,"/"),v=await p(u,S);v!=null&&(n.parseCount++,h.parse(w,v,u,!1))}}{let r=await Qn();if(r)return r}{let r=await Dn("afterParse",w.parser);if(r)return z(r)}{let r=await Qn();if(r)return r}{let r=n.begin();n.initializeCount++;try{h.initializeProgram(w)}catch(l){I("initialize",l)}n.initializeTime+=n.end(r)}{let r=await Dn("afterInitialize",w);if(r)return z(r)}{let r=n.begin();n.compileCount++;try{K=h.compile(w)}catch(l){let f=mn(w,b,i.disableWarning,t.reportDiagnostic,H.enabled);if(f){let u=Error(`${f} compile error(s)`);return u.stack=u.message,z(u)}I("compile",l)}n.compileTime+=n.end(r)}R=gn.wrapModule(typeof K=="number"||K instanceof Number?h.getBinaryenModuleRef(K):K.ref);let fn=mn(w,b,i.disableWarning,t.reportDiagnostic,H.enabled);if(fn){let r=Error(`${fn} compile error(s)`);return r.stack=r.message,z(r)}{let r=await Dn("afterCompile",R);if(r)return z(r)}if(fn=mn(w,b,i.disableWarning,t.reportDiagnostic,H.enabled),fn){let r=Error(`${fn} afterCompile error(s)`);return r.stack=r.message,z(r)}if(!i.noValidate){let r=n.begin();n.validateCount++;let l=h.validate(K);if(n.validateTime+=n.end(r),!l)return z(Error("validate error"))}if(i.trapMode==="clamp"||i.trapMode==="js"){let r=n.begin();try{R.runPasses([`trap-mode-${i.trapMode}`])}catch(l){I("runPasses",l)}n.compileTime+=n.end(r)}else if(i.trapMode!=="allow")return z(Error("Unsupported trap mode"));let ne=i.debug,Ne=i.converge,ee=i.importMemory?i.zeroFilledMemory:!1,vn=[];i.runPasses&&(typeof i.runPasses=="string"&&(i.runPasses=i.runPasses.split(",")),i.runPasses.length&&i.runPasses.forEach(r=>{vn.includes(r=r.trim())||vn.push(r)}));{let r=n.begin();try{n.optimizeCount++,h.optimize(K,Z,$,ne,ee)}catch(l){I("optimize",l)}try{R.runPasses(vn)}catch(l){I("runPasses",l)}if(Ne){let l;try{let f=n.begin();n.emitCount++,l=R.emitBinary(),n.emitTime+=n.end(f)}catch(f){I("emitBinary (converge)",f)}do{try{n.optimizeCount++,h.optimize(K,Z,$,ne,ee)}catch(u){I("optimize (converge)",u)}try{R.runPasses(vn)}catch(u){I("runPasses (converge)",u)}let f;try{let u=n.begin();n.emitCount++,f=R.emitBinary(),n.emitTime+=n.end(u)}catch(u){I("emitBinary (converge)",u)}if(f.length>=l.length){f.length>l.length&&b.write(`Last converge was suboptimal.${T}`);break}l=f}while(!0)}n.optimizeTime+=n.end(r)}let Q=[];if(!i.noEmit){if(i.binaryFile)return z(Error("Usage of the --binaryFile compiler option is no longer supported. Use --outFile instead."));let r=i.bindings||[],l=!1,f=i.outFile!=null,u=i.textFile!=null,v=f||u,F=f&&i.outFile.length>0||u&&i.textFile.length>0,A=F?(i.outFile||i.textFile).replace(/\.\w+$/,""):null,k=F?E.basename(A):"output";if(h.setBasenameHint(C,k),i.outFile!=null){let O=i.sourceMap!=null?i.sourceMap.length?i.sourceMap:`./${k}.wasm.map`:null,D=n.begin();n.emitCount++;let B;try{B=R.emitBinary(O)}catch(L){I("emitBinary",L)}if(n.emitTime+=n.end(D),i.outFile.length?Q.push(g(i.outFile,B.binary,S)):(l=!0,Fn(B.binary)),B.sourceMap!="")if(i.outFile.length){let L=JSON.parse(B.sourceMap);L.sourceRoot=`./${k}`;let cn=[];for(let An=0,Ue=L.sources.length;An<Ue;++An){let ae=L.sources[An],oe=h.getSource(w,ae.replace(ln,""));if(oe==null)return z(Error(`Source of file '${ae}' not found.`));cn[An]=oe}L.sourcesContent=cn,Q.push(g(E.join(E.dirname(i.outFile),E.basename(O)).replace(/^\.\//,""),JSON.stringify(L),S))}else b.write(`Skipped source map (no output path)${T}`)}if(i.textFile!=null||!v){let O=n.begin();n.emitCount++;let D;try{gn.setOptimizeStackIR(!0),D=i.textFile?.endsWith(".wast")?R.emitText():R.emitStackIR()}catch(B){I("emitText",B)}n.emitTime+=n.end(O),i.textFile!=null&&i.textFile.length?Q.push(g(i.textFile,D,S)):l||Fn(D)}let q=r.includes("esm"),En=!q&&r.includes("raw");if(q||En)if(A){let O=n.begin();n.emitCount++;let D;try{D=h.buildTSD(w,q)}catch(B){I("buildTSD",B)}n.emitTime+=n.end(O),Q.push(g(A+".d.ts",D,S))}else b.write(`Skipped TypeScript binding (no output path)${T}`);if(q||En)if(A){let O=n.begin();n.emitCount++;let D;try{D=h.buildJS(w,q)}catch(B){I("buildJS",B)}n.emitTime+=n.end(O),Q.push(g(A+".js",D,S))}else b.write(`Skipped JavaScript binding (no output path)${T}`);if(i.rpcModule!=null&&i.rpcModule.length){let O=n.begin();n.emitCount++;let D;try{D=h.buildServerModule(w,i.rpcRuntime||"toiljs/io")}catch(B){I("buildServerModule",B)}n.emitTime+=n.end(O),D!=null&&Q.push(g(i.rpcModule,D,S))}}try{await Promise.all(Q)}catch(r){return z(r)}return n.total=n.end(a),i.stats&&b.write(n.toString()),z(null);async function te(r,l){let f=E.resolve(l,r);try{return n.readCount++,await M.promises.readFile(f,"utf8")}catch{return null}}async function ie(r,l,f){try{n.writeCount++;let u=E.resolve(f,E.dirname(r)),v=E.join(u,E.basename(r));return await M.promises.mkdir(u,{recursive:!0}),await M.promises.writeFile(v,l),!0}catch{return!1}}async function re(r,l){try{return n.readCount++,(await M.promises.readdir(E.join(l,r))).filter(f=>zt.test(f))}catch{return null}}function Fn(r){Fn.used||(Fn.used=!0,n.writeCount++),x.write(r)}function I(r,l){let f=Sn.red("\u258C ");console.error([T,f,"Whoops, the ToilScript compiler has crashed during ",r," :-(",T,f,T,(typeof l.stack=="string"?[f,"Here is the stack trace hinting at the problem, perhaps it's useful?",T,f,T,l.stack.replace(/^/mg,f),T]:[f,"There is no stack trace. Perhaps a Binaryen exception above / in console?",T,f,T,f,"> "+l.stack,T]).join(""),f,T,f,"If you see where the error is, feel free to send us a pull request. If not,",T,f,"please let us know: https://github.com/dacely-cloud/toilscript/issues",T,f,T,f,"Thank you!",T].join("")),P.exit(1)}}function jn(e){return Object.prototype.toString.call(e)==="[object Object]"}async function ze(e,t,n){let a=await n(e,t),s=E.join(t,e);if(!a)return null;let o;try{o=JSON.parse(a)}catch(c){throw new Error(`Toilconfig is not valid json: ${s}`,{cause:c})}if(o.options&&!jn(o.options))throw new Error(`Toilconfig.options is not an object: ${s}`);if(o.include&&!Array.isArray(o.include))throw new Error(`Toilconfig.include is not an array: ${s}`);if(o.targets){if(!jn(o.targets))throw new Error(`Toilconfig.targets is not an object: ${s}`);let c=Object.keys(o.targets);for(let d=0;d<c.length;d++){let x=c[d];if(!jn(o.targets[x]))throw new Error(`Toilconfig.targets.${x} is not an object: ${s}`)}}if(o.extends&&typeof o.extends!="string")throw new Error(`Toilconfig.extends is not a string: ${s}`);return o}function mn(e,t,n,a,s){typeof s>"u"&&t&&(s=t.isTTY);let o=0;do{let x=h.nextDiagnostic(e);if(!x)break;if(t){let b=p=>{if(n==null)return!1;if(!n.length)return!0;let g=h.getDiagnosticCode(p);return n.includes(g)};(h.isError(x)||!b(x))&&t.write(h.formatDiagnostic(x,s,!0)+T+T)}if(a){let b=function(g){return g&&{start:h.getRangeStart(g),end:h.getRangeEnd(g),source:p(h.getRangeSource(g))}||null},p=function(g){return g&&{normalizedPath:h.getSourceNormalizedPath(g)}||null};var c=b,d=p;a({message:h.getDiagnosticMessage(x),code:h.getDiagnosticCode(x),category:h.getDiagnosticCategory(x),range:b(h.getDiagnosticRange(x)),relatedRange:b(h.getDiagnosticRelatedRange(x))})}h.isError(x)&&++o}while(!0);return o}var zn=class{readCount=0;writeCount=0;parseTime=0;parseCount=0;initializeTime=0;initializeCount=0;compileTime=0;compileCount=0;emitTime=0;emitCount=0;validateTime=0;validateCount=0;optimizeTime=0;optimizeCount=0;transformTime=0;transformCount=0;begin(){return P.hrtime()}end(t){let n=P.hrtime(t);return n[0]*1e9+n[1]}toString(){let t=m=>m?`${(m/1e6).toFixed(3)} ms`:"n/a",n=Object.keys(this).filter(m=>m.endsWith("Time")).map(m=>m.substring(0,m.length-4)),a=n.map(m=>t(this[`${m}Time`])),s=n.map(m=>this[`${m}Count`].toString()),o=n.reduce((m,i)=>Math.max(i.length,m),0),c=a.reduce((m,i)=>Math.max(i.length,m),0),d=s.reduce((m,i)=>Math.max(i.length,m),0),x=o+c+d+6,b=[];b.push(`\u256D\u2500${"\u2500".repeat(x)}\u2500\u256E${T}`);let p="Stats";b.push(`\u2502 ${p}${" ".repeat(x-p.length)} \u2502${T}`),b.push(`\u255E\u2550${"\u2550".repeat(o)}\u2550\u2564\u2550${"\u2550".repeat(c)}\u2550\u2564\u2550${"\u2550".repeat(d)}\u2550\u2561${T}`);for(let m=0,i=n.length;m<i;++m)b.push(`\u2502 ${n[m].padEnd(o)} \u2502 ${a[m].padStart(c)} \u2502 ${s[m].padStart(d)} \u2502${T}`);b.push(`\u251C\u2500${"\u2500".repeat(o)}\u2500\u2534\u2500${"\u2500".repeat(c)}\u2500\u2534\u2500${"\u2500".repeat(d)}\u2500\u2524${T}`);let g=`Took ${t(this.total)}`;b.push(`\u2502 ${g}${" ".repeat(x-g.length)} \u2502${T}`);let y=`${this.readCount} reads, ${this.writeCount} writes`;return b.push(`\u2502 ${y}${" ".repeat(x-y.length)} \u2502${T}`),b.push(`\u2570\u2500${"\u2500".repeat(x)}\u2500\u256F${T}`),b.join("")}},Se=typeof global<"u"&&global.Buffer?global.Buffer.allocUnsafe||(e=>new global.Buffer(e)):e=>new Uint8Array(e);function Xn(e){let t=[];return t.write=function(n){if(e&&e(n),typeof n=="string"){let a=Se(Cn.length(n));Cn.write(n,a,0),n=a}this.push(n)},t.reset=function(){t.length=0},t.toBuffer=function(){let n=0,a=0,s=this.length;for(;a<s;)n+=this[a++].length;let o=Se(n);for(n=a=0;a<s;)o.set(this[a],n),n+=this[a].length,++a;return o},t.toString=function(){let n=this.toBuffer();return Cn.read(n,0,n.length)},t}var It={alwaysStrict:!0,strictNullChecks:!0,noImplicitAny:!0,noImplicitReturns:!0,noImplicitThis:!0,noEmitOnError:!0,noPropertyAccessFromIndexSignature:!0,experimentalDecorators:!0,target:"esnext",noLib:!0,types:[],allowJs:!1};export{zn as Stats,mn as checkDiagnostics,Dt as compileString,Wn as configToArguments,Xn as createMemoryStream,Yn as default,we as defaultOptimizeLevel,Be as defaultShrinkLevel,Bt as definitionFiles,j as libraryFiles,V as libraryPrefix,De as main,wt as options,It as tscOptions,Kn as version};
|
|
31293
|
+
`,Gn=qn?"\\":"/",_=".ts",Ct=`.d${_}`,ln=new RegExp("\\"+_+"$"),zt=new RegExp("^(?!.*\\.d\\"+_+"$).*\\"+_+"$");function Ce(e){return e.replace(/-/g,"_").toUpperCase()}function St(e){return typeof e=="string"&&e!==""}var Kn=Ee,wt=Y,V=Ae,j=_e,Bt=Te,we=3,Be=0;function Wn(e,t=[]){return Object.keys(e||{}).forEach(n=>{let a=e[n],s=Y[n];s&&s.type==="b"?a&&t.push(`--${n}`):Array.isArray(a)?a.forEach(o=>{t.push(`--${n}`,String(o))}):t.push(`--${n}`,String(a))}),t}async function Dt(e,t={}){typeof e=="string"&&(e={[`input${_}`]:e});let n=["--outFile","binary","--textFile","text"];Wn(t,n);let a={},s=await De(n.concat(Object.keys(e)),{readFile:o=>Object.prototype.hasOwnProperty.call(e,o)?e[o]:null,writeFile:(o,c)=>{a[o]=c},listFiles:()=>[]});return Object.assign(s,a)}async function De(e,t){Array.isArray(e)||(e=Wn(e)),t||(t={});let n=t.stats||new zn,a=n.begin(),s=0,o=0,c=0,d=(Kn||"").split(".");d.length===3&&(o=parseInt(d[0])|0,s=parseInt(d[1])|0,c=parseInt(d[2])|0);let x=t.stdout||Xn(),b=t.stderr||Xn(),h=t.readFile||te,g=t.writeFile||ie,y=t.listFiles||re,m=ve(e,Y,!1),i=m.options;e=m.arguments;let Sn=new en(x),G=new en(b);i.noColors&&(Sn.enabled=!1,G.enabled=!1);let Jn=m.unknown;Jn.length&&Jn.forEach(r=>{b.write(`${G.yellow("WARNING ")}Unknown option '${r}'${T}`)});let Zn=m.trailing;Zn.length&&b.write(`${G.yellow("WARNING ")}Unsupported trailing arguments: ${Zn.join(" ")}${T}`);let K=null,R=null,z=(r,l={})=>(r&&b.write(`${G.red("FAILURE ")}${r.stack.replace(/^ERROR: /i,"")}${T}`),R&&R.dispose(),n.total||(n.total=n.end(a)),Object.assign({error:r,stdout:x,stderr:b,stats:n},l));if(i.version)return x.write(`Version ${Kn}${T}`),z(null);let S=E.normalize(i.baseDir||"."),X=tn(i.config||"toilconfig.json",S),wn=E.basename(X),J=E.dirname(X),N=await ze(wn,J,h),Ie=N!=null&&Array.isArray(N.entries)&&N.entries.length;if(i.help||!e.length&&!Ie){let r=i.help?x:b,l=i.help?Sn:G;return r.write([l.white("SYNTAX")," "+l.cyan("toilscript")+" [entryFile ...] [options]","",l.white("EXAMPLES")," "+l.cyan("toilscript")+" hello"+_," "+l.cyan("toilscript")+" hello"+_+" -o hello.wasm -t hello.wat"," "+l.cyan("toilscript")+" hello1"+_+" hello2"+_+" -o -O > hello.wasm"," "+l.cyan("toilscript")+" --config toilconfig.json --target release","",l.white("OPTIONS")].concat(Fe(Y,24,T)).join(T)+T),z(null)}if(!(M.promises&&M.promises.readFile)){if(h===te)throw Error("'options.readFile' must be specified");if(g===ie)throw Error("'options.writeFile' must be specified");if(y===re)throw Error("'options.listFiles' must be specified")}let Bn=new Set;Bn.add(X);let Le=!!i.noConfigEntries,ke=i.target||"release";for(;N;){if(N.targets){let l=N.targets[ke];l&&(i=Mn(Y,i,l,J))}let r=N.options;if(r&&(i=Mn(Y,i,r,J)),N.entries&&!Le)for(let l of N.entries)e.push(tn(l,J));if(N.extends){if(X=tn(N.extends,J,!0),wn=E.basename(X),J=E.dirname(X),Bn.has(X))break;Bn.add(X),N=await ze(wn,J,h)}else break}if(Pn(Y,i),i.showConfig)return b.write(JSON.stringify({options:i,entries:e},null,2)),z(null);function $n(r){return[...new Set(r)]}let w,rn,bn,C=p.newOptions();switch(i.runtime){case"stub":rn=0;break;case"minimal":rn=1;break;case"memory":rn=3;break;default:rn=2;break}switch(i.uncheckedBehavior){default:bn=0;break;case"never":bn=1;break;case"always":bn=2;break}let un=null;if(i.targetMode!=null&&String(i.targetMode).length>0&&(un=String(i.targetMode),un!=="hot"&&un!=="cold"))return z(Error(`Target mode '${un}' is invalid; expected 'hot' or 'cold'.`));if(p.setTargetMode(C,un),p.setAuthUser(C,!!i.authUser),p.setTarget(C,0),p.setDebugInfo(C,!!i.debug),p.setRuntime(C,rn),p.setNoAssert(C,i.noAssert),p.setExportMemory(C,!i.noExportMemory),p.setImportMemory(C,i.importMemory),p.setInitialMemory(C,i.initialMemory>>>0),p.setMaximumMemory(C,i.maximumMemory>>>0),p.setSharedMemory(C,i.sharedMemory),p.setImportTable(C,i.importTable),p.setExportTable(C,i.exportTable),i.exportStart!=null&&p.setExportStart(C,St(i.exportStart)?i.exportStart:"_start"),p.setMemoryBase(C,i.memoryBase>>>0),p.setTableBase(C,i.tableBase>>>0),p.setSourceMap(C,i.sourceMap!=null),p.setUncheckedBehavior(C,bn),p.setNoUnsafe(C,i.noUnsafe),p.setPedantic(C,i.pedantic),p.setLowMemoryLimit(C,i.lowMemoryLimit>>>0),p.setExportRuntime(C,i.exportRuntime),p.setBundleVersion(C,o,s,c),!i.stackSize&&rn===2&&(i.stackSize=p.DEFAULT_STACK_SIZE),p.setStackSize(C,i.stackSize),p.setBindingsHint(C,i.bindings&&i.bindings.length>0),i.use){let r=i.use;for(let l=0,f=r.length;l<f;++l){let u=r[l],v=u.indexOf("=");if(v<0)return z(Error(`Global alias '${u}' is invalid.`));let F=u.substring(0,v).trim(),A=u.substring(v+1).trim();if(!F.length)return z(Error(`Global alias '${u}' is invalid.`));p.addGlobalAlias(C,F,A)}}let U;if((U=i.disable)!=null){typeof U=="string"&&(U=U.split(","));for(let r=0,l=U.length;r<l;++r){let f=U[r].trim(),u=p[`FEATURE_${Ce(f)}`];if(!u)return z(Error(`Feature '${f}' is unknown.`));p.setFeature(C,u,!1)}}if((U=i.enable)!=null){typeof U=="string"&&(U=U.split(","));for(let r=0,l=U.length;r<l;++r){let f=U[r].trim(),u=p[`FEATURE_${Ce(f)}`];if(!u)return z(Error(`Feature '${f}' is unknown.`));p.setFeature(C,u,!0)}}let Z=0,$=0;i.optimize&&(Z=we,$=Be),typeof i.optimizeLevel=="number"&&(Z=i.optimizeLevel),typeof i.shrinkLevel=="number"&&($=i.shrinkLevel),Z=Math.min(Math.max(Z,0),3),$=Math.min(Math.max($,0),2),p.setOptimizeLevelHints(C,Z,$),w=p.newProgram(C);let an=[];if(Array.isArray(t.transforms)&&an.push(...t.transforms),i.transform){let r=$n(i.transform);for(let l=0,f=r.length;l<f;++l){let u=r[l].trim(),v,F;if(Hn.resolve)try{v=Hn.resolve(u,{paths:[P.cwd(),S]}),F=await import(pn.pathToFileURL(v)),F.default&&(F=F.default)}catch(A){try{F=Hn(v)}catch{return z(A)}}else try{F=await import(new URL(u,import.meta.url)),F.default&&(F=F.default)}catch(A){return z(A)}if(!F||typeof F!="function"&&typeof F!="object")return z(Error("not a transform: "+r[l]));an.push(F)}}try{an=an.map(r=>(typeof r=="function"&&(Object.assign(r.prototype,{program:w,binaryen:gn,baseDir:S,stdout:x,stderr:b,log:console.error,readFile:h,writeFile:g,listFiles:y}),r=new r),r))}catch(r){return z(r)}async function Dn(r,...l){for(let f=0,u=an.length;f<u;++f){let v=an[f];if(typeof v[r]=="function")try{let F=n.begin();n.transformCount++,await v[r](...l),n.transformTime+=n.end(F)}catch(F){return F}}}Object.keys(j).forEach(r=>{if(r.includes("/"))return;let l=n.begin();n.parseCount++,p.parse(w,j[r],V+r+_,!1),n.parseTime+=n.end(l)});let on=[];if(i.lib){let r=i.lib;typeof r=="string"&&(r=r.split(",")),on.push(...r.map(l=>l.trim())),on=$n(on);for(let l=0,f=on.length;l<f;++l){let u=on[l],v;u.endsWith(_)?(v=[E.basename(u)],u=E.dirname(u)):v=await y(u,S)||[];for(let F of v){let A=await h(F,u);if(A==null)return z(Error(`Library file '${F}' not found.`));j[F.replace(ln,"")]=A;let L=n.begin();n.parseCount++,p.parse(w,A,V+F,!1),n.parseTime+=n.end(L)}}}i.path=i.path||[];let yn=new Map;async function Oe(r,l){let f=null,u=null;if(!r.startsWith(V))(f=await h(u=r+_,S))==null&&(f=await h(u=r+"/index"+_,S))==null&&(u=r+_,f=await h(r+Ct,S));else{let v=r.substring(V.length),F=`${v}/index`;if(Object.prototype.hasOwnProperty.call(j,v))f=j[v],u=V+v+_;else if(Object.prototype.hasOwnProperty.call(j,F))f=j[F],u=V+F+_;else{for(let A of on)if((f=await h(v+_,A))!=null){u=V+v+_;break}else if((f=await h(F+_,A))!=null){u=V+F+_;break}if(f==null){let A=r.match(/^~lib\/((?:@[^/]+\/)?[^/]+)(?:\/(.+))?/);if(A){let L=A[1],q=A[2]||"index",En=yn.has(l)?yn.get(l):".",k=[],D=E.resolve(S,En).split(Gn);for(let B=D.length,O=qn?1:0;B>=O;--B)D[B-1]!=="node_modules"&&k.push(`${D.slice(0,B).join(Gn)}${Gn}node_modules`);k.push(...i.path);for(let B of k.map(O=>E.relative(S,O))){let O=q;if((f=await h(E.join(B,L,O+_),S))!=null){u=`${V}${L}/${O}${_}`,yn.set(u.replace(ln,""),E.join(B,L));break}let cn=`${q}/index`;if((f=await h(E.join(B,L,cn+_),S))!=null){u=`${V}${L}/${cn}${_}`,yn.set(u.replace(ln,""),E.join(B,L));break}}}}}}return f==null?null:{sourceText:f,sourcePath:u}}function Re(r=[]){do{let l=p.nextFile(w);if(l==null)break;r.push(l)}while(!0);return r}async function Qn(){let r;for(;(r=Re()).length;){let f=[];for(let u of r){let v=p.getDependee(w,u);f.push(Oe(u,v))}f=await Promise.all(f);for(let u=0,v=r.length;u<v;++u){let F=r[u],A=f[u],L=n.begin();n.parseCount++,A?p.parse(w,A.sourceText,A.sourcePath,!1):p.parse(w,null,F+_,!1),n.parseTime+=n.end(L)}}let l=mn(w,b,i.disableWarning,t.reportDiagnostic,G.enabled);if(l){let f=Error(`${l} parse error(s)`);return f.stack=f.message,z(f)}}{let r=String(i.runtime),l=`rt/index-${r}`,f=j[l];if(f==null){if(l=r,f=await h(l+_,S),f==null)return z(Error(`Runtime '${E.resolve(S,l+_)}' is not found.`))}else l=`~lib/${l}`;let u=n.begin();n.parseCount++,p.parse(w,f,l+_,!0),n.parseTime+=n.end(u)}for(let r=0,l=e.length;r<l;++r){let f=String(e[r]),u=E.isAbsolute(f)?E.relative(S,f):E.normalize(f);u=u.replace(/\\/g,"/").replace(ln,"").replace(/\/$/,"");let v=await h(u+_,S);if(v==null){let A=`${u}/index${_}`;v=await h(A,S),v!=null?u=A:u+=_}else u+=_;let F=n.begin();n.parseCount++,p.parse(w,v,u,!0),n.parseTime+=n.end(F)}if(i.rpcSurfaceFiles!=null&&i.rpcSurfaceFiles.length)for(let r=0,l=i.rpcSurfaceFiles.length;r<l;++r){let f=String(i.rpcSurfaceFiles[r]),u=E.isAbsolute(f)?E.relative(S,f):E.normalize(f);u=u.replace(/\\/g,"/").replace(ln,"").replace(/\/$/,"");let v=await h(u+_,S);if(v==null){let F=`${u}/index${_}`;v=await h(F,S),v!=null?u=F:u+=_}else u+=_;v!=null?(n.parseCount++,p.parse(w,v,u,!1)):p.parse(w,null,u,!1)}if(M.promises&&M.promises.readdir){let r=[],l=async(f,u)=>{let v;try{v=await M.promises.readdir(f,{withFileTypes:!0})}catch{return}for(let F of v){let A=F.name;if(F.isDirectory()){if(A==="node_modules"||A==="build"||A==="dist"||A.charAt(0)===".")continue;await l(E.join(f,A),u?u+"/"+A:A)}else A.endsWith(".migration"+_)&&r.push(u?u+"/"+A:A)}};await l(E.resolve(S),"");for(let f of r){let u=f.replace(/\\/g,"/"),v=await h(u,S);v!=null&&(n.parseCount++,p.parse(w,v,u,!1))}}{let r=await Qn();if(r)return r}{let r=await Dn("afterParse",w.parser);if(r)return z(r)}{let r=await Qn();if(r)return r}{let r=n.begin();n.initializeCount++;try{p.initializeProgram(w)}catch(l){I("initialize",l)}n.initializeTime+=n.end(r)}{let r=await Dn("afterInitialize",w);if(r)return z(r)}{let r=n.begin();n.compileCount++;try{K=p.compile(w)}catch(l){let f=mn(w,b,i.disableWarning,t.reportDiagnostic,G.enabled);if(f){let u=Error(`${f} compile error(s)`);return u.stack=u.message,z(u)}I("compile",l)}n.compileTime+=n.end(r)}R=gn.wrapModule(typeof K=="number"||K instanceof Number?p.getBinaryenModuleRef(K):K.ref);let fn=mn(w,b,i.disableWarning,t.reportDiagnostic,G.enabled);if(fn){let r=Error(`${fn} compile error(s)`);return r.stack=r.message,z(r)}{let r=await Dn("afterCompile",R);if(r)return z(r)}if(fn=mn(w,b,i.disableWarning,t.reportDiagnostic,G.enabled),fn){let r=Error(`${fn} afterCompile error(s)`);return r.stack=r.message,z(r)}if(!i.noValidate){let r=n.begin();n.validateCount++;let l=p.validate(K);if(n.validateTime+=n.end(r),!l)return z(Error("validate error"))}if(i.trapMode==="clamp"||i.trapMode==="js"){let r=n.begin();try{R.runPasses([`trap-mode-${i.trapMode}`])}catch(l){I("runPasses",l)}n.compileTime+=n.end(r)}else if(i.trapMode!=="allow")return z(Error("Unsupported trap mode"));let ne=i.debug,Ne=i.converge,ee=i.importMemory?i.zeroFilledMemory:!1,vn=[];i.runPasses&&(typeof i.runPasses=="string"&&(i.runPasses=i.runPasses.split(",")),i.runPasses.length&&i.runPasses.forEach(r=>{vn.includes(r=r.trim())||vn.push(r)}));{let r=n.begin();try{n.optimizeCount++,p.optimize(K,Z,$,ne,ee)}catch(l){I("optimize",l)}try{R.runPasses(vn)}catch(l){I("runPasses",l)}if(Ne){let l;try{let f=n.begin();n.emitCount++,l=R.emitBinary(),n.emitTime+=n.end(f)}catch(f){I("emitBinary (converge)",f)}do{try{n.optimizeCount++,p.optimize(K,Z,$,ne,ee)}catch(u){I("optimize (converge)",u)}try{R.runPasses(vn)}catch(u){I("runPasses (converge)",u)}let f;try{let u=n.begin();n.emitCount++,f=R.emitBinary(),n.emitTime+=n.end(u)}catch(u){I("emitBinary (converge)",u)}if(f.length>=l.length){f.length>l.length&&b.write(`Last converge was suboptimal.${T}`);break}l=f}while(!0)}n.optimizeTime+=n.end(r)}let Q=[];if(!i.noEmit){if(i.binaryFile)return z(Error("Usage of the --binaryFile compiler option is no longer supported. Use --outFile instead."));let r=i.bindings||[],l=!1,f=i.outFile!=null,u=i.textFile!=null,v=f||u,F=f&&i.outFile.length>0||u&&i.textFile.length>0,A=F?(i.outFile||i.textFile).replace(/\.\w+$/,""):null,L=F?E.basename(A):"output";if(p.setBasenameHint(C,L),i.outFile!=null){let k=i.sourceMap!=null?i.sourceMap.length?i.sourceMap:`./${L}.wasm.map`:null,D=n.begin();n.emitCount++;let B;try{B=R.emitBinary(k)}catch(O){I("emitBinary",O)}if(n.emitTime+=n.end(D),i.outFile.length?Q.push(g(i.outFile,B.binary,S)):(l=!0,Fn(B.binary)),B.sourceMap!="")if(i.outFile.length){let O=JSON.parse(B.sourceMap);O.sourceRoot=`./${L}`;let cn=[];for(let An=0,Ue=O.sources.length;An<Ue;++An){let ae=O.sources[An],oe=p.getSource(w,ae.replace(ln,""));if(oe==null)return z(Error(`Source of file '${ae}' not found.`));cn[An]=oe}O.sourcesContent=cn,Q.push(g(E.join(E.dirname(i.outFile),E.basename(k)).replace(/^\.\//,""),JSON.stringify(O),S))}else b.write(`Skipped source map (no output path)${T}`)}if(i.textFile!=null||!v){let k=n.begin();n.emitCount++;let D;try{gn.setOptimizeStackIR(!0),D=i.textFile?.endsWith(".wast")?R.emitText():R.emitStackIR()}catch(B){I("emitText",B)}n.emitTime+=n.end(k),i.textFile!=null&&i.textFile.length?Q.push(g(i.textFile,D,S)):l||Fn(D)}let q=r.includes("esm"),En=!q&&r.includes("raw");if(q||En)if(A){let k=n.begin();n.emitCount++;let D;try{D=p.buildTSD(w,q)}catch(B){I("buildTSD",B)}n.emitTime+=n.end(k),Q.push(g(A+".d.ts",D,S))}else b.write(`Skipped TypeScript binding (no output path)${T}`);if(q||En)if(A){let k=n.begin();n.emitCount++;let D;try{D=p.buildJS(w,q)}catch(B){I("buildJS",B)}n.emitTime+=n.end(k),Q.push(g(A+".js",D,S))}else b.write(`Skipped JavaScript binding (no output path)${T}`);if(i.rpcModule!=null&&i.rpcModule.length){let k=n.begin();n.emitCount++;let D;try{D=p.buildServerModule(w,i.rpcRuntime||"toiljs/io")}catch(B){I("buildServerModule",B)}n.emitTime+=n.end(k),D!=null&&Q.push(g(i.rpcModule,D,S))}}try{await Promise.all(Q)}catch(r){return z(r)}return n.total=n.end(a),i.stats&&b.write(n.toString()),z(null);async function te(r,l){let f=E.resolve(l,r);try{return n.readCount++,await M.promises.readFile(f,"utf8")}catch{return null}}async function ie(r,l,f){try{n.writeCount++;let u=E.resolve(f,E.dirname(r)),v=E.join(u,E.basename(r));return await M.promises.mkdir(u,{recursive:!0}),await M.promises.writeFile(v,l),!0}catch{return!1}}async function re(r,l){try{return n.readCount++,(await M.promises.readdir(E.join(l,r))).filter(f=>zt.test(f))}catch{return null}}function Fn(r){Fn.used||(Fn.used=!0,n.writeCount++),x.write(r)}function I(r,l){let f=Sn.red("\u258C ");console.error([T,f,"Whoops, the ToilScript compiler has crashed during ",r," :-(",T,f,T,(typeof l.stack=="string"?[f,"Here is the stack trace hinting at the problem, perhaps it's useful?",T,f,T,l.stack.replace(/^/mg,f),T]:[f,"There is no stack trace. Perhaps a Binaryen exception above / in console?",T,f,T,f,"> "+l.stack,T]).join(""),f,T,f,"If you see where the error is, feel free to send us a pull request. If not,",T,f,"please let us know: https://github.com/dacely-cloud/toilscript/issues",T,f,T,f,"Thank you!",T].join("")),P.exit(1)}}function jn(e){return Object.prototype.toString.call(e)==="[object Object]"}async function ze(e,t,n){let a=await n(e,t),s=E.join(t,e);if(!a)return null;let o;try{o=JSON.parse(a)}catch(c){throw new Error(`Toilconfig is not valid json: ${s}`,{cause:c})}if(o.options&&!jn(o.options))throw new Error(`Toilconfig.options is not an object: ${s}`);if(o.include&&!Array.isArray(o.include))throw new Error(`Toilconfig.include is not an array: ${s}`);if(o.targets){if(!jn(o.targets))throw new Error(`Toilconfig.targets is not an object: ${s}`);let c=Object.keys(o.targets);for(let d=0;d<c.length;d++){let x=c[d];if(!jn(o.targets[x]))throw new Error(`Toilconfig.targets.${x} is not an object: ${s}`)}}if(o.extends&&typeof o.extends!="string")throw new Error(`Toilconfig.extends is not a string: ${s}`);return o}function mn(e,t,n,a,s){typeof s>"u"&&t&&(s=t.isTTY);let o=0;do{let x=p.nextDiagnostic(e);if(!x)break;if(t){let b=h=>{if(n==null)return!1;if(!n.length)return!0;let g=p.getDiagnosticCode(h);return n.includes(g)};(p.isError(x)||!b(x))&&t.write(p.formatDiagnostic(x,s,!0)+T+T)}if(a){let b=function(g){return g&&{start:p.getRangeStart(g),end:p.getRangeEnd(g),source:h(p.getRangeSource(g))}||null},h=function(g){return g&&{normalizedPath:p.getSourceNormalizedPath(g)}||null};var c=b,d=h;a({message:p.getDiagnosticMessage(x),code:p.getDiagnosticCode(x),category:p.getDiagnosticCategory(x),range:b(p.getDiagnosticRange(x)),relatedRange:b(p.getDiagnosticRelatedRange(x))})}p.isError(x)&&++o}while(!0);return o}var zn=class{readCount=0;writeCount=0;parseTime=0;parseCount=0;initializeTime=0;initializeCount=0;compileTime=0;compileCount=0;emitTime=0;emitCount=0;validateTime=0;validateCount=0;optimizeTime=0;optimizeCount=0;transformTime=0;transformCount=0;begin(){return P.hrtime()}end(t){let n=P.hrtime(t);return n[0]*1e9+n[1]}toString(){let t=m=>m?`${(m/1e6).toFixed(3)} ms`:"n/a",n=Object.keys(this).filter(m=>m.endsWith("Time")).map(m=>m.substring(0,m.length-4)),a=n.map(m=>t(this[`${m}Time`])),s=n.map(m=>this[`${m}Count`].toString()),o=n.reduce((m,i)=>Math.max(i.length,m),0),c=a.reduce((m,i)=>Math.max(i.length,m),0),d=s.reduce((m,i)=>Math.max(i.length,m),0),x=o+c+d+6,b=[];b.push(`\u256D\u2500${"\u2500".repeat(x)}\u2500\u256E${T}`);let h="Stats";b.push(`\u2502 ${h}${" ".repeat(x-h.length)} \u2502${T}`),b.push(`\u255E\u2550${"\u2550".repeat(o)}\u2550\u2564\u2550${"\u2550".repeat(c)}\u2550\u2564\u2550${"\u2550".repeat(d)}\u2550\u2561${T}`);for(let m=0,i=n.length;m<i;++m)b.push(`\u2502 ${n[m].padEnd(o)} \u2502 ${a[m].padStart(c)} \u2502 ${s[m].padStart(d)} \u2502${T}`);b.push(`\u251C\u2500${"\u2500".repeat(o)}\u2500\u2534\u2500${"\u2500".repeat(c)}\u2500\u2534\u2500${"\u2500".repeat(d)}\u2500\u2524${T}`);let g=`Took ${t(this.total)}`;b.push(`\u2502 ${g}${" ".repeat(x-g.length)} \u2502${T}`);let y=`${this.readCount} reads, ${this.writeCount} writes`;return b.push(`\u2502 ${y}${" ".repeat(x-y.length)} \u2502${T}`),b.push(`\u2570\u2500${"\u2500".repeat(x)}\u2500\u256F${T}`),b.join("")}},Se=typeof global<"u"&&global.Buffer?global.Buffer.allocUnsafe||(e=>new global.Buffer(e)):e=>new Uint8Array(e);function Xn(e){let t=[];return t.write=function(n){if(e&&e(n),typeof n=="string"){let a=Se(Cn.length(n));Cn.write(n,a,0),n=a}this.push(n)},t.reset=function(){t.length=0},t.toBuffer=function(){let n=0,a=0,s=this.length;for(;a<s;)n+=this[a++].length;let o=Se(n);for(n=a=0;a<s;)o.set(this[a],n),n+=this[a].length,++a;return o},t.toString=function(){let n=this.toBuffer();return Cn.read(n,0,n.length)},t}var It={alwaysStrict:!0,strictNullChecks:!0,noImplicitAny:!0,noImplicitReturns:!0,noImplicitThis:!0,noEmitOnError:!0,noPropertyAccessFromIndexSignature:!0,experimentalDecorators:!0,target:"esnext",noLib:!0,types:[],allowJs:!1};export{zn as Stats,mn as checkDiagnostics,Dt as compileString,Wn as configToArguments,Xn as createMemoryStream,Yn as default,we as defaultOptimizeLevel,Be as defaultShrinkLevel,Bt as definitionFiles,j as libraryFiles,V as libraryPrefix,De as main,wt as options,It as tscOptions,Kn as version};
|
|
30699
31294
|
//# sourceMappingURL=cli.js.map
|