@stacksjs/tinker 0.75.559 → 0.75.561

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/index.d.ts CHANGED
@@ -39,7 +39,7 @@ export declare function isIncompleteSnippet(code: string, cwd: string): boolean;
39
39
  * import { startTinker } from '@stacksjs/tinker'
40
40
  *
41
41
  * await startTinker() // interactive
42
- * await startTinker({ print: 'await User.count()' }) // evaluate, print, exit
42
+ * await startTinker({ print: 'User.count()' }) // evaluate, print, exit
43
43
  * await startTinker({ serve: true }) // speak the frame protocol on stdio
44
44
  * ```
45
45
  */
@@ -69,3 +69,4 @@ export * from './magic';
69
69
  export * from './protocol';
70
70
  export * from './serialize';
71
71
  export * from './session';
72
+ export * from './settle';
package/dist/index.js CHANGED
@@ -1,48 +1,50 @@
1
1
  // @bun
2
- import{appendFileSync as Ce,chmodSync as ne,existsSync as re,readFileSync as ze,writeFileSync as ie,writeSync as Le}from"fs";import{homedir as De}from"os";import{join as qe,resolve as We}from"path";import F from"process";import{writeSync as _e}from"fs";import{isAbsolute as Me,resolve as ee}from"path";import A from"process";var ae=[">>>=","...","===","!==","**=","<<=",">>=",">>>","&&=","||=","??=","=>","==","!=","<=",">=","&&","||","??","?.","++","--","+=","-=","*=","/=","%=","&=","|=","^=","**","<<",">>"],ce=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]),q=new Set(["if","for","while","do","switch","try","function","class","import","export","throw","break","continue","interface","type","enum","declare","namespace"]);function ue(e){return/[\p{L}_$]/u.test(e)}function le(e){return/[\p{L}\p{N}_$]/u.test(e)}function U(e,i){let t=i+1;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n==="`")return t+1;if(n==="$"&&e[t+1]==="{"){t+=2;let r=1;while(t<e.length&&r>0){let o=e[t];if(o==="`"){t=U(e,t);continue}if(o==="'"||o==='"'){t=K(e,t);continue}if(o==="{")r++;else if(o==="}")r--;t++}continue}t++}return e.length}function K(e,i){let t=e[i],n=i+1;while(n<e.length){let r=e[n];if(r==="\\"){n+=2;continue}if(r===t||r===`
3
- `)return n+1;n++}return e.length}function me(e,i){let t=i+1,n=!1;while(t<e.length){let r=e[t];if(r==="\\"){t+=2;continue}if(r===`
4
- `)return-1;if(r==="[")n=!0;else if(r==="]")n=!1;else if(r==="/"&&!n){t++;while(t<e.length&&/[a-z]/i.test(e[t]))t++;return t}t++}return-1}function fe(e){let i=[],t=0,n,r=(o,a)=>{let u={type:o,start:t,end:a,text:e.slice(t,a)};if(i.push(u),o!=="ws"&&o!=="nl"&&o!=="comment")n=u;t=a};while(t<e.length){let o=e[t];if(o===`
5
- `)r("nl",t+1);else if(o===" "||o==="\t"||o==="\r"){let a=t+1;while(a<e.length&&(e[a]===" "||e[a]==="\t"||e[a]==="\r"))a++;r("ws",a)}else if(o==="/"&&e[t+1]==="/"){let a=t+2;while(a<e.length&&e[a]!==`
6
- `)a++;r("comment",a)}else if(o==="/"&&e[t+1]==="*"){let a=e.indexOf("*/",t+2);r("comment",a===-1?e.length:a+2)}else if(o==="'"||o==='"')r("string",K(e,t));else if(o==="`")r("template",U(e,t));else if(o==="/"){let a=n,k=!a||a.type==="punct"&&a.text!==")"&&a.text!=="]"&&a.text!=="}"||a.type==="word"&&ce.has(a.text)?me(e,t):-1;if(k!==-1)r("regex",k);else r("punct",e[t+1]==="="?t+2:t+1)}else if(/\d/.test(o)||o==="."&&/\d/.test(e[t+1]??"")){let a=t+1;while(a<e.length&&/[\w.]/.test(e[a]))a++;r("number",a)}else if(ue(o)||o==="#"){let a=t+1;while(a<e.length&&le(e[a]))a++;r("word",a)}else{let a=ae.find((u)=>e.startsWith(u,t));r("punct",t+(a?.length??1))}}return i}var de={")":"(","]":"[","}":"{"},J=new Set([")","]","}"]),H=new Set(["(","[","{"]),pe=new Set([".","?.",",","(","[","=","=>","+","-","*","/","%","**","&&","||","??","?",":","<",">","<=",">=","==","===","!=","!==","&","|","^","!","~","+=","-=","*=","/=","??=","||=","&&="]),W=new Set([".","?.",",",")","]","=","=>","+","-","*","/","%","**","&&","||","??","?",":","<",">","<=",">=","==","===","!=","!==","&","|","^"]),ge=new Set(["return","await","typeof","new","in","of","instanceof","yield","void","delete","const","let","var","as"]);function G(e){return Boolean(e)&&e.type!=="ws"&&e.type!=="nl"&&e.type!=="comment"}function v(e,i){for(let t=i;t>=0;t--)if(G(e[t]))return t;return-1}function P(e,i){for(let t=i;t<e.length;t++)if(G(e[t]))return t;return-1}function ye(e,i){let t=0,n=i;for(let r=i;r>=0;r--){let o=e[r];if(o.type==="comment"||o.type==="ws")continue;if(o.type==="nl"){if(t>0)continue;let a=v(e,r-1),u=P(e,r+1);if(a===-1)return n;let k=e[a],w=e[u];if(!(k.type==="punct"&&pe.has(k.text)||k.type==="word"&&ge.has(k.text)||w?.type==="punct"&&W.has(w.text)))return n;continue}if(o.type==="punct"){if(J.has(o.text)){if(t===0&&o.text==="}"){let a=P(e,r+1),u=e.slice(r+1,a===-1?void 0:a).some((w)=>w.type==="nl"),k=a===-1?void 0:e[a];if(r!==i&&u&&!(k?.type==="punct"&&W.has(k.text)))return n}t++,n=r;continue}if(H.has(o.text)){if(t===0)return n;t--,n=r;continue}if(t===0&&(o.text===";"||o.text==="=>"))return n}n=r}return t===0?n:-1}function ke(e,i){let t=v(e,i-1);if(t===-1||t!==i-1)return-1;let n=-1,r=!0;while(t>=0){let a=e[t];if(a.type==="ws"||a.type==="comment")break;if(r){if(a.type==="punct"&&(a.text===")"||a.text==="]")){let u=0,k=t;for(;k>=0;k--){let b=e[k];if(b.type!=="punct")continue;if(b.text===a.text)u++;else if(b.text===de[a.text])u--;if(u===0)break}if(k<0)return-1;n=k,t=k-1;let w=e[t];if(w&&(w.type==="word"||w.type==="punct"&&(w.text===")"||w.text==="]"))){r=!0;continue}r=!1;continue}if(a.type==="word"||a.type==="string"||a.type==="template"||a.type==="number"||a.type==="regex"){n=t,t--,r=!1;continue}return-1}if(a.type==="punct"&&(a.text==="."||a.text==="?.")){t--,r=!0;continue}break}if(n===-1||r)return-1;let o=v(e,n-1);if(o!==-1&&e[o].type==="word"&&(e[o].text==="await"||e[o].text==="new"))n=o;return n}function be(e,i,t){let n=P(e,i+1);if(n===-1||n>t)return;let r=e[n];if(r.type==="word")return r.text;if(r.type!=="punct"||r.text!=="{"&&r.text!=="[")return;let o=[],a=0;for(let u=n;u<=t;u++){let k=e[u];if(k.type==="punct"&&H.has(k.text))a++;else if(k.type==="punct"&&J.has(k.text))a--;else if(k.type==="word"&&a>0){let w=P(e,u+1),b=v(e,u-1),c=w!==-1&&e[w].text===":",x=b!==-1&&e[b].text==="=";if(!c&&!x)o.push(k.text)}if(a===0&&u>n)break}return o.length?`{ ${o.join(", ")} }`:void 0}var Y=/^\/\/\?(\.)?\s*$/,Q=/^\/\*\?(.*)\*\/$/s;function he(e){return e.includes("//?")||e.includes("/*?")}function X(e,i={probe:"__tinkerProbe",time:"__tinkerTime"}){if(!he(e))return{code:e,probes:[]};let t=[],n=e,r=Number.POSITIVE_INFINITY;for(let o=0;o<500;o++){let a=fe(n),u=-1;for(let b=a.length-1;b>=0;b--){let c=a[b];if(c.type==="comment"&&c.start<r&&(Y.test(c.text)||Q.test(c.text))){u=b;break}}if(u===-1)break;let k=a[u],w=xe(n,a,u,i);if(!w){r=k.start;continue}n=n.slice(0,w.start)+w.text+n.slice(k.end),r=w.start+w.text.length,t.unshift({line:w.line,kind:w.kind})}return{code:n,probes:t}}function we(e,i){let t=0;for(let n=0;n<i;n++)if(e.charCodeAt(n)===10)t++;return t}function xe(e,i,t,n){let r=i[t],o=Y.exec(r.text),a=o?null:Q.exec(r.text),u=we(e,r.start),k=a?a[1].trim():"",w=Boolean(o?.[1])||k===".",b=k&&!w?`, __v => __v${k.startsWith(".")||k.startsWith("[")||k.startsWith("?.")?"":"."}${k}`:"",c=v(i,t-1);if(c===-1)return;if(a&&!w&&c===t-1){let l=ke(i,t);if(l===-1)return;let h=e.slice(i[l].start,i[c].end);return{start:i[l].start,text:`${n.probe}(${u}, (${h})${b})`,line:u,kind:"value"}}let x=c;if(i[x].type==="punct"&&i[x].text===";")x=v(i,x-1);if(x===-1)return;let s=i[c].end,d=e.slice(s,r.start).includes(`
7
- `)?e.slice(s,r.start):"",f=ye(i,x);if(f===-1)return w?{start:s,text:`${d};${n.time}(${u})`,line:u,kind:"time"}:void 0;let y=i[f],m=e.slice(y.start,i[x].end);if(w)return!(y.type==="word"&&(y.text==="const"||y.text==="let"||y.text==="var"||y.text==="return"||q.has(y.text)))?{start:y.start,text:`${n.time}(${u}, (${m}))`,line:u,kind:"time"}:{start:s,text:`${d};${n.time}(${u})`,line:u,kind:"time"};if(y.type==="word"&&(y.text==="const"||y.text==="let"||y.text==="var")){let l=be(i,f,x);return l?{start:s,text:`;${n.probe}(${u}, ${l}${b})`,line:u,kind:"value"}:void 0}if(y.type==="word"&&y.text==="return"){let l=e.slice(y.end,i[x].end).trim();return l?{start:y.start,text:`return ${n.probe}(${u}, (${l})${b})`,line:u,kind:"value"}:void 0}if(y.type==="word"&&q.has(y.text))return;return{start:y.start,text:`${n.probe}(${u}, (${m})${b})`,line:u,kind:"value"}}var Te={maxDepth:8,maxItems:200,maxString:20000,maxNodes:50000},Se=/^\s*at\s+(?:(.*?)\s+\()?(.+?):(\d+):(\d+)\)?\s*$/;function $e(e){if(!e)return[];let i=[];for(let t of e.split(`
8
- `)){let n=Se.exec(t);if(!n)continue;i.push({function:n[1]||void 0,file:n[2],line:Number(n[3]),column:Number(n[4])})}return i}function Oe(e){if(Function.prototype.toString.call(e).startsWith("class"))return"class";let t=e.constructor?.name;if(t==="AsyncFunction"||t==="AsyncGeneratorFunction")return"async";if(t==="GeneratorFunction")return"generator";return"function"}function R(e){let i=Object.getPrototypeOf(e);if(i===null)return"null prototype";let t=i.constructor?.name;return typeof t==="string"&&t&&t!=="Object"?t:void 0}var Z=2000000;class I{kind;html;title;text;constructor(e,i,t,n){this.kind=e;this.html=i;this.title=t;this.text=n}}var Ne=["hasOne","hasMany","belongsTo","belongsToMany","hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany"];function B(e){let i=[];for(let t of Ne){let n=e[t];if(!n)continue;if(Array.isArray(n)){for(let r of n)if(typeof r==="string")i.push({kind:t,model:r});else if(r&&typeof r==="object"&&typeof r.model==="string")i.push({kind:t,model:r.model,...typeof r.relationName==="string"?{name:r.relationName}:{}})}else if(typeof n==="object"){for(let[r,o]of Object.entries(n))if(typeof o==="string")i.push({kind:t,model:o,name:r})}else if(typeof n==="string")i.push({kind:t,model:n})}return i}function Ee(e){let i=e._definition;return typeof i==="object"&&i!==null&&typeof i.name==="string"&&typeof e.toJSON==="function"&&typeof e.getAttributes==="function"}function E(e,i={}){let t={...Te,...i.limits},n=i.describers??[],r=new Map,o=0,a=1;function u(c,x){if(o++,c===void 0)return{t:"undefined"};if(c===null)return{t:"null"};switch(typeof c){case"boolean":return{t:"boolean",v:c};case"number":if(Number.isNaN(c))return{t:"number",v:"NaN"};if(c===Number.POSITIVE_INFINITY)return{t:"number",v:"Infinity"};if(c===Number.NEGATIVE_INFINITY)return{t:"number",v:"-Infinity"};if(Object.is(c,-0))return{t:"number",v:"-0"};return{t:"number",v:c};case"bigint":return{t:"bigint",v:c.toString()};case"string":return c.length>t.maxString?{t:"string",v:c.slice(0,t.maxString),truncated:c.length-t.maxString}:{t:"string",v:c};case"symbol":return{t:"symbol",v:c.description??""};case"function":return{t:"function",name:c.name||"(anonymous)",kind:Oe(c)}}let s=c,d=r.get(s);if(d!==void 0)return{t:"ref",id:d};if(s instanceof Date)return{t:"date",v:Number.isNaN(s.getTime())?null:s.toISOString()};if(s instanceof RegExp)return{t:"regexp",v:s.toString()};if(s instanceof URL)return{t:"url",v:s.href};if(s instanceof Promise)return{t:"promise"};if(ArrayBuffer.isView(s)||s instanceof ArrayBuffer){let m=s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength);return{t:"bytes",ctor:s.constructor?.name??"ArrayBuffer",length:m.byteLength,hex:Buffer.from(m.subarray(0,64)).toString("hex")}}if(x>=t.maxDepth)return{t:"cut",reason:"depth",ctor:R(s)??(Array.isArray(s)?"Array":"Object")};if(o>=t.maxNodes)return{t:"cut",reason:"nodes",ctor:R(s)};let f=a++;r.set(s,f);let y=(m)=>u(m,x+1);if(s instanceof Error)return b(s,y);if(s instanceof I){let m=s.html.length-Z;return{t:"html",kind:s.kind,...s.title?{title:s.title}:{},html:m>0?s.html.slice(0,Z):s.html,...s.text?{text:s.text.slice(0,t.maxString)}:{},...m>0?{truncated:m}:{}}}if(Ee(s))return k(s,f,y);for(let m of n){let l;try{l=m(s,y)}catch{l=void 0}if(l)return l}if(Array.isArray(s)){let m=[],l=Math.min(s.length,t.maxItems);for(let p=0;p<l&&o<t.maxNodes;p++)m.push(y(s[p]));let h=s.length-m.length,g=R(s);return{t:"array",id:f,...g&&g!=="Array"?{ctor:g}:{},length:s.length,items:m,...h>0?{more:h}:{}}}if(s instanceof Map){let m=[];for(let[h,g]of s){if(m.length>=t.maxItems||o>=t.maxNodes)break;m.push([y(h),y(g)])}let l=s.size-m.length;return{t:"map",id:f,size:s.size,entries:m,...l>0?{more:l}:{}}}if(s instanceof Set){let m=[];for(let h of s){if(m.length>=t.maxItems||o>=t.maxNodes)break;m.push(y(h))}let l=s.size-m.length;return{t:"set",id:f,size:s.size,items:m,...l>0?{more:l}:{}}}return w(s,f,y)}function k(c,x,s){let d=c._definition,f={};try{let T=c.toJSON();if(T&&typeof T==="object")f=T}catch{}let y={};try{y=c.getLoadedRelations?.()??{}}catch{y={}}let m=Object.keys(f).filter((T)=>!(T in y)),l=[];for(let T of m){if(l.length>=t.maxItems||o>=t.maxNodes)break;l.push([T,s(f[T])])}let h=Object.keys(c).filter((T)=>!(T in f)),g=[];for(let[T,V]of Object.entries(y)){if(g.length>=t.maxItems||o>=t.maxNodes)break;g.push([T,s(V)])}let p=B(d),S=typeof d.primaryKey==="string"?d.primaryKey:"id",O=m.length-l.length;return{t:"model",id:x,model:d.name,...typeof d.table==="string"?{table:d.table}:{},primaryKey:S,...f[S]!==void 0?{key:s(f[S])}:{},attributes:l,...h.length?{hidden:h}:{},...g.length?{loaded:g}:{},...p.length?{relations:p}:{},...O>0?{more:O}:{}}}function w(c,x,s){let d=R(c),f=c,y=Object.keys(c);if(y.length===0&&d&&typeof c.toJSON==="function")try{let h=c.toJSON();if(Array.isArray(h)){let g=s(h);return g.t==="array"?{...g,ctor:d}:g}if(h&&typeof h==="object")f=h,y=Object.keys(f)}catch{}let m=[];for(let h of y){if(m.length>=t.maxItems||o>=t.maxNodes)break;let g;try{g=f[h]}catch(p){g=p}m.push([h,s(g)])}let l=y.length-m.length;return{t:"object",id:x,...d?{ctor:d}:{},entries:m,...l>0?{more:l}:{}}}function b(c,x){let s={t:"error",name:c.name||"Error",message:String(c.message??"")};if(typeof c.stack==="string"){s.stack=c.stack;let f=$e(c.stack);if(f.length)s.frames=f}if(c.cause!==void 0)s.cause=x(c.cause);let d=[];for(let f of Object.keys(c)){if(f==="name"||f==="message"||f==="stack"||f==="cause")continue;if(d.length>=t.maxItems)break;d.push([f,x(c[f])])}if(d.length)s.entries=d;return s}return u(e,0)}function C(e,i={}){if(e instanceof Error)return E(e,i);return{t:"error",name:"Thrown",message:typeof e==="string"?e:Bun.inspect(e),cause:E(e,i)}}function ve(){let e=[],i=new Set;for(let t of Object.getOwnPropertyNames(globalThis)){let n;try{n=globalThis[t]}catch{continue}if(!n||typeof n!=="object"&&typeof n!=="function")continue;let r=n.getDefinition;if(typeof r!=="function")continue;let o;try{o=r.call(n)}catch{continue}if(!o||typeof o.name!=="string"||i.has(o.name))continue;i.add(o.name),e.push({name:o.name,...typeof o.table==="string"?{table:o.table}:{},...typeof o.primaryKey==="string"?{primaryKey:o.primaryKey}:{},attributes:o.attributes&&typeof o.attributes==="object"?Object.keys(o.attributes):[],relations:B(o)})}return e.sort((t,n)=>t.name.localeCompare(n.name))}function Ae(){return{html(e,i){return new I("html",String(e),i)},async mail(e,i={}){let{templateByName:n}=await import("@stacksjs/email"),r=await n(e,{variables:i});if(!r?.html)throw Error(`No mail template named "${e}" rendered. Templates live in resources/emails.`);return new I("mail",r.html,e,r.text)}}}class j extends Error{constructor(){super("dd");this.name="TinkerHalt"}}var Ie=/\bimport\((["'])(\.{1,2}\/[^"']*)\1\)/g;function z(e,i,t="tinker"){return`${new Bun.Transpiler({loader:"ts",replMode:!0}).transformSync(e).replace(Ie,(o,a,u)=>`import(${a}${ee(i,u)}${a})`)}
9
- //# sourceURL=${t}.ts`}function Ve(e){let i=e instanceof AggregateError?e.errors:[e],t=[];for(let n of i){if(!n||typeof n!=="object")continue;let{message:r,position:o}=n;t.push({message:typeof r==="string"?r:String(n),...o?.line!==void 0?{line:o.line}:{},...o?.column!==void 0?{column:o.column}:{},...o?.lineText?{lineText:o.lineText}:{}})}return t}async function Pe(e){let n=!0;try{let{overridesReady:r}=await import("@stacksjs/config");await r}catch(r){n=!1,e.push(`config not loaded: ${r instanceof Error?r.message:String(r)}`)}try{let{injectGlobalAutoImports:r}=await import("@stacksjs/server");await r()}catch(r){n=!1,e.push(`models and framework globals not injected: ${r instanceof Error?r.message:String(r)}`)}return n}var Re=["log","info","debug","dir","table"],je=["warn","error","trace"];async function _(e={}){let i=e.cwd?Me(e.cwd)?e.cwd:ee(A.cwd(),e.cwd):A.cwd();if(i!==A.cwd())A.chdir(i);let t={limits:e.limits,describers:e.describers},n=[],r=[],o="boot",a,u=(m)=>{a?.push(m);try{e.onFrame?.(m)}catch{}},k=console,w=(m)=>m.map((l)=>typeof l==="string"?l:Bun.inspect(l,{depth:6})).join(" ");for(let[m,l]of[[Re,"stdout"],[je,"stderr"]])for(let h of m){let g=k[h];k[h]=(...p)=>u({type:l,id:o,text:`${w(p)}
10
- `}),r.push(()=>{k[h]=g})}for(let[m,l]of[[A.stdout,"stdout"],[A.stderr,"stderr"]]){let h=m.write;m.write=(g,...p)=>(u({type:l,id:o,text:typeof g==="string"?g:Buffer.from(g).toString("utf8")}),p.find((O)=>typeof O==="function")?.(),!0),r.push(()=>{m.write=h})}let b=globalThis;b.dump=(...m)=>{for(let l of m)u({type:"dump",id:o,value:E(l,t)})},b.dd=(...m)=>{throw b.dump(...m),new j},b.preview=Ae();let c=performance.now();if(b.__tinkerProbe=(m,l,h)=>{let g=o,p=(S)=>u({type:"probe",id:g,line:m,kind:"value",value:E(S,t)});if(!h)return p(l),l;try{let S=h(l);if(S instanceof Promise)S.then(p,(O)=>p(O));else p(S)}catch(S){p(S)}return l},b.__tinkerTime=(m,l)=>(u({type:"probe",id:o,line:m,kind:"time",ms:Math.round((performance.now()-c)*100)/100}),l),e.globals)Object.assign(b,e.globals);let x=!1;if(typeof e.boot==="function")try{await e.boot(),x=!0}catch(m){n.push(`boot failed: ${m instanceof Error?m.message:String(m)}`)}else if(e.boot!==!1)x=await Pe(n);if(x&&e.boot!==!1&&typeof e.boot!=="function"){let m=(...g)=>{for(let p of g)u({type:"dump",id:o,value:E(p,t)})};b.dump=m,b.dd=(...g)=>{throw m(...g),new j};let l="@stacksjs/logging",h="@stacksjs/query-builder";try{let{registerTransport:g}=await import(l);r.push(g({name:"tinker",log(p){u({type:"log",id:o,level:p.level,message:p.message,timestamp:p.timestamp,...p.context?{context:E(p.context,t)}:{}})}}))}catch(g){n.push(`log capture unavailable: ${g instanceof Error?g.message:String(g)}`)}try{let{registerPersistentQueryHooks:g}=await import(h);r.push(g({onQueryEnd(p){u({type:"query",id:o,sql:p.sql,...p.params?.length?{params:E(p.params,t)}:{},...p.kind?{kind:p.kind}:{},durationMs:p.durationMs,...p.rowCount!==void 0?{rowCount:p.rowCount}:{}})},onQueryError(p){u({type:"query",id:o,sql:p.sql,...p.params?.length?{params:E(p.params,t)}:{},...p.kind?{kind:p.kind}:{},durationMs:p.durationMs,error:p.error instanceof Error?p.error.message:String(p.error)})}}))}catch(g){n.push(`query capture unavailable: ${g instanceof Error?g.message:String(g)}`)}}let s=eval,d=0,f=Promise.resolve();async function y(m,l){let h=[];a=h,o=l;let g=performance.now();c=g;let p=()=>Math.round((performance.now()-g)*100)/100,S;try{S=z(e.magic===!1?m:X(m).code,i,`tinker-${l}`)}catch(O){let T=p();return u({type:"error",id:l,phase:"parse",error:C(O,t),diagnostics:Ve(O),durationMs:T}),u({type:"done",id:l,ok:!1}),a=void 0,{id:l,ok:!1,thrown:O,frames:h,durationMs:T}}try{let T=(await s(S))?.value,V=p();return u({type:"result",id:l,value:E(T,t),durationMs:V}),u({type:"done",id:l,ok:!0}),{id:l,ok:!0,value:T,frames:h,durationMs:V}}catch(O){let T=p();if(O instanceof j)return u({type:"result",id:l,value:{t:"undefined"},durationMs:T}),u({type:"done",id:l,ok:!0}),{id:l,ok:!0,frames:h,durationMs:T};return u({type:"error",id:l,phase:"run",error:C(O,t),durationMs:T}),u({type:"done",id:l,ok:!1}),{id:l,ok:!1,thrown:O,frames:h,durationMs:T}}finally{a=void 0}}return{info:{cwd:i,booted:x,bun:Bun.version,warnings:n},models:ve,evaluate(m,l={}){let h=l.id??String(++d),g=f.then(()=>y(m,h));return f=g.catch(()=>{}),g},dispose(){while(r.length)r.pop()?.()}}}var L="\x1E",Fe=2;function Be(e){return`${L}${JSON.stringify(e)}
11
- `}function at(){let e="",i=(t)=>{if(t.startsWith(L))try{return{frame:JSON.parse(t.slice(L.length))}}catch{return{stray:t}}return{stray:t}};return{push(t){e+=t;let n=e.split(`
12
- `);return e=n.pop()??"",n.map(i)},flush(){if(!e)return[];let t=e;return e="",[{stray:t}]}}}async function te(e={}){let i=e.write??((d)=>{_e(1,d)}),t=(d)=>i(Be(d)),{input:n,write:r,once:o,...a}=e,u=await _({...a,onFrame:t});t({type:"ready",session:u.info,protocol:Fe});let k=!0,w=!1;if(o!==void 0)return{ok:(await u.evaluate(o)).ok,session:u};let b=new TextDecoder,c="",x=n??Bun.stdin.stream(),s=async(d)=>{if(!d.trim())return!0;let f;try{f=JSON.parse(d)}catch{return t({type:"protocol-error",message:"request is not valid JSON"}),!0}if(f.op==="exit")return!1;if(f.op==="ping")return t({type:"pong",...f.id?{id:f.id}:{}}),!0;if(f.op==="models")return t({type:"models",...f.id?{id:f.id}:{},models:u.models()}),!0;if(f.op==="eval"&&typeof f.code==="string"){if(!(await u.evaluate(f.code,{id:f.id})).ok)k=!1;return!0}return t({type:"protocol-error",message:`unknown request: ${String(f.op)}`}),!0};e:for await(let d of x){c+=typeof d==="string"?d:b.decode(d,{stream:!0});let f=c.indexOf(`
13
- `);while(f!==-1){let y=c.slice(0,f);if(c=c.slice(f+1),!await s(y)){w=!0;break e}f=c.indexOf(`
14
- `)}}if(!w&&c.trim())await s(c);return{ok:k,session:u}}function D(e){return e?.historyFile??qe(De(),".stacks_tinker_history")}function oe(e){let i=D(e);if(!re(i))return[];return ze(i,"utf-8").split(`
15
- `).filter(Boolean)}function Ue(e,i){let t=D(i),n=!re(t);if(Ce(t,`${e}
16
- `),n)try{ne(t,384)}catch{}let r=i?.historySize??5000,o=oe(i);if(o.length>r){let a=o.slice(o.length-r);ie(t,a.join(`
2
+ import{appendFileSync as ot,chmodSync as ce,existsSync as ue,readFileSync as at,writeFileSync as le,writeSync as ct}from"fs";import{homedir as ut}from"os";import{join as lt,resolve as ft}from"path";import B from"process";import{writeSync as rt}from"fs";import{isAbsolute as He,resolve as oe}from"path";import I from"process";var pe=[">>>=","...","===","!==","**=","<<=",">>=",">>>","&&=","||=","??=","=>","==","!=","<=",">=","&&","||","??","?.","++","--","+=","-=","*=","/=","%=","&=","|=","^=","**","<<",">>"],de=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]),J=new Set(["if","for","while","do","switch","try","function","class","import","export","throw","break","continue","interface","type","enum","declare","namespace"]);function ge(e){return/[\p{L}_$]/u.test(e)}function ye(e){return/[\p{L}\p{N}_$]/u.test(e)}function G(e,i){let t=i+1;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n==="`")return t+1;if(n==="$"&&e[t+1]==="{"){t+=2;let r=1;while(t<e.length&&r>0){let s=e[t];if(s==="`"){t=G(e,t);continue}if(s==="'"||s==='"'){t=Y(e,t);continue}if(s==="{")r++;else if(s==="}")r--;t++}continue}t++}return e.length}function Y(e,i){let t=e[i],n=i+1;while(n<e.length){let r=e[n];if(r==="\\"){n+=2;continue}if(r===t||r===`
3
+ `)return n+1;n++}return e.length}function be(e,i){let t=i+1,n=!1;while(t<e.length){let r=e[t];if(r==="\\"){t+=2;continue}if(r===`
4
+ `)return-1;if(r==="[")n=!0;else if(r==="]")n=!1;else if(r==="/"&&!n){t++;while(t<e.length&&/[a-z]/i.test(e[t]))t++;return t}t++}return-1}function ke(e){let i=[],t=0,n,r=(s,c)=>{let u={type:s,start:t,end:c,text:e.slice(t,c)};if(i.push(u),s!=="ws"&&s!=="nl"&&s!=="comment")n=u;t=c};while(t<e.length){let s=e[t];if(s===`
5
+ `)r("nl",t+1);else if(s===" "||s==="\t"||s==="\r"){let c=t+1;while(c<e.length&&(e[c]===" "||e[c]==="\t"||e[c]==="\r"))c++;r("ws",c)}else if(s==="/"&&e[t+1]==="/"){let c=t+2;while(c<e.length&&e[c]!==`
6
+ `)c++;r("comment",c)}else if(s==="/"&&e[t+1]==="*"){let c=e.indexOf("*/",t+2);r("comment",c===-1?e.length:c+2)}else if(s==="'"||s==='"')r("string",Y(e,t));else if(s==="`")r("template",G(e,t));else if(s==="/"){let c=n,h=!c||c.type==="punct"&&c.text!==")"&&c.text!=="]"&&c.text!=="}"||c.type==="word"&&de.has(c.text)?be(e,t):-1;if(h!==-1)r("regex",h);else r("punct",e[t+1]==="="?t+2:t+1)}else if(/\d/.test(s)||s==="."&&/\d/.test(e[t+1]??"")){let c=t+1;while(c<e.length&&/[\w.]/.test(e[c]))c++;r("number",c)}else if(ge(s)||s==="#"){let c=t+1;while(c<e.length&&ye(e[c]))c++;r("word",c)}else{let c=pe.find((u)=>e.startsWith(u,t));r("punct",t+(c?.length??1))}}return i}var he={")":"(","]":"[","}":"{"},Q=new Set([")","]","}"]),X=new Set(["(","[","{"]),xe=new Set([".","?.",",","(","[","=","=>","+","-","*","/","%","**","&&","||","??","?",":","<",">","<=",">=","==","===","!=","!==","&","|","^","!","~","+=","-=","*=","/=","??=","||=","&&="]),H=new Set([".","?.",",",")","]","=","=>","+","-","*","/","%","**","&&","||","??","?",":","<",">","<=",">=","==","===","!=","!==","&","|","^"]),we=new Set(["return","await","typeof","new","in","of","instanceof","yield","void","delete","const","let","var","as"]);function Z(e){return Boolean(e)&&e.type!=="ws"&&e.type!=="nl"&&e.type!=="comment"}function P(e,i){for(let t=i;t>=0;t--)if(Z(e[t]))return t;return-1}function V(e,i){for(let t=i;t<e.length;t++)if(Z(e[t]))return t;return-1}function Te(e,i){let t=0,n=i;for(let r=i;r>=0;r--){let s=e[r];if(s.type==="comment"||s.type==="ws")continue;if(s.type==="nl"){if(t>0)continue;let c=P(e,r-1),u=V(e,r+1);if(c===-1)return n;let h=e[c],b=e[u];if(!(h.type==="punct"&&xe.has(h.text)||h.type==="word"&&we.has(h.text)||b?.type==="punct"&&H.has(b.text)))return n;continue}if(s.type==="punct"){if(Q.has(s.text)){if(t===0&&s.text==="}"){let c=V(e,r+1),u=e.slice(r+1,c===-1?void 0:c).some((b)=>b.type==="nl"),h=c===-1?void 0:e[c];if(r!==i&&u&&!(h?.type==="punct"&&H.has(h.text)))return n}t++,n=r;continue}if(X.has(s.text)){if(t===0)return n;t--,n=r;continue}if(t===0&&(s.text===";"||s.text==="=>"))return n}n=r}return t===0?n:-1}function Se(e,i){let t=P(e,i-1);if(t===-1||t!==i-1)return-1;let n=-1,r=!0;while(t>=0){let c=e[t];if(c.type==="ws"||c.type==="comment")break;if(r){if(c.type==="punct"&&(c.text===")"||c.text==="]")){let u=0,h=t;for(;h>=0;h--){let k=e[h];if(k.type!=="punct")continue;if(k.text===c.text)u++;else if(k.text===he[c.text])u--;if(u===0)break}if(h<0)return-1;n=h,t=h-1;let b=e[t];if(b&&(b.type==="word"||b.type==="punct"&&(b.text===")"||b.text==="]"))){r=!0;continue}r=!1;continue}if(c.type==="word"||c.type==="string"||c.type==="template"||c.type==="number"||c.type==="regex"){n=t,t--,r=!1;continue}return-1}if(c.type==="punct"&&(c.text==="."||c.text==="?.")){t--,r=!0;continue}break}if(n===-1||r)return-1;let s=P(e,n-1);if(s!==-1&&e[s].type==="word"&&(e[s].text==="await"||e[s].text==="new"))n=s;return n}function Ee(e,i,t){let n=V(e,i+1);if(n===-1||n>t)return;let r=e[n];if(r.type==="word")return r.text;if(r.type!=="punct"||r.text!=="{"&&r.text!=="[")return;let s=[],c=0;for(let u=n;u<=t;u++){let h=e[u];if(h.type==="punct"&&X.has(h.text))c++;else if(h.type==="punct"&&Q.has(h.text))c--;else if(h.type==="word"&&c>0){let b=V(e,u+1),k=P(e,u-1),f=b!==-1&&e[b].text===":",T=k!==-1&&e[k].text==="=";if(!f&&!T)s.push(h.text)}if(c===0&&u>n)break}return s.length?`{ ${s.join(", ")} }`:void 0}var ee=/^\/\/\?(\.)?\s*$/,te=/^\/\*\?(.*)\*\/$/s;function $e(e){return e.includes("//?")||e.includes("/*?")}function ne(e,i={probe:"__tinkerProbe",time:"__tinkerTime"}){if(!$e(e))return{code:e,probes:[]};let t=[],n=e,r=Number.POSITIVE_INFINITY;for(let s=0;s<500;s++){let c=ke(n),u=-1;for(let k=c.length-1;k>=0;k--){let f=c[k];if(f.type==="comment"&&f.start<r&&(ee.test(f.text)||te.test(f.text))){u=k;break}}if(u===-1)break;let h=c[u],b=Oe(n,c,u,i);if(!b){r=h.start;continue}n=n.slice(0,b.start)+b.text+n.slice(h.end),r=b.start+b.text.length,t.unshift({line:b.line,kind:b.kind})}return{code:n,probes:t}}function Ne(e,i){let t=0;for(let n=0;n<i;n++)if(e.charCodeAt(n)===10)t++;return t}function Oe(e,i,t,n){let r=i[t],s=ee.exec(r.text),c=s?null:te.exec(r.text),u=Ne(e,r.start),h=c?c[1].trim():"",b=Boolean(s?.[1])||h===".",k=h&&!b?`, __v => __v${h.startsWith(".")||h.startsWith("[")||h.startsWith("?.")?"":"."}${h}`:"",f=P(i,t-1);if(f===-1)return;if(c&&!b&&f===t-1){let m=Se(i,t);if(m===-1)return;let d=e.slice(i[m].start,i[f].end);return{start:i[m].start,text:`${n.probe}(${u}, (${d})${k})`,line:u,kind:"value"}}let T=f;if(i[T].type==="punct"&&i[T].text===";")T=P(i,T-1);if(T===-1)return;let o=i[f].end,g=e.slice(o,r.start).includes(`
7
+ `)?e.slice(o,r.start):"",p=Te(i,T);if(p===-1)return b?{start:o,text:`${g};${n.time}(${u})`,line:u,kind:"time"}:void 0;let y=i[p],x=e.slice(y.start,i[T].end);if(b)return!(y.type==="word"&&(y.text==="const"||y.text==="let"||y.text==="var"||y.text==="return"||J.has(y.text)))?{start:y.start,text:`${n.time}(${u}, (${x}))`,line:u,kind:"time"}:{start:o,text:`${g};${n.time}(${u})`,line:u,kind:"time"};if(y.type==="word"&&(y.text==="const"||y.text==="let"||y.text==="var")){let m=Ee(i,p,T);return m?{start:o,text:`;${n.probe}(${u}, ${m}${k})`,line:u,kind:"value"}:void 0}if(y.type==="word"&&y.text==="return"){let m=e.slice(y.end,i[T].end).trim();return m?{start:y.start,text:`return ${n.probe}(${u}, (${m})${k})`,line:u,kind:"value"}:void 0}if(y.type==="word"&&J.has(y.text))return;return{start:y.start,text:`${n.probe}(${u}, (${x})${k})`,line:u,kind:"value"}}var _e={maxDepth:8,maxItems:200,maxString:20000,maxNodes:50000},Me=/^\s*at\s+(?:(.*?)\s+\()?(.+?):(\d+):(\d+)\)?\s*$/;function Ae(e){if(!e)return[];let i=[];for(let t of e.split(`
8
+ `)){let n=Me.exec(t);if(!n)continue;i.push({function:n[1]||void 0,file:n[2],line:Number(n[3]),column:Number(n[4])})}return i}function Pe(e){if(Function.prototype.toString.call(e).startsWith("class"))return"class";let t=e.constructor?.name;if(t==="AsyncFunction"||t==="AsyncGeneratorFunction")return"async";if(t==="GeneratorFunction")return"generator";return"function"}function C(e){let i=Object.getPrototypeOf(e);if(i===null)return"null prototype";let t=i.constructor?.name;return typeof t==="string"&&t&&t!=="Object"?t:void 0}var re=2000000;class R{kind;html;title;text;constructor(e,i,t,n){this.kind=e;this.html=i;this.title=t;this.text=n}}var Ie=["hasOne","hasMany","belongsTo","belongsToMany","hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany"];function L(e){let i=[];for(let t of Ie){let n=e[t];if(!n)continue;if(Array.isArray(n)){for(let r of n)if(typeof r==="string")i.push({kind:t,model:r});else if(r&&typeof r==="object"&&typeof r.model==="string")i.push({kind:t,model:r.model,...typeof r.relationName==="string"?{name:r.relationName}:{}})}else if(typeof n==="object"){for(let[r,s]of Object.entries(n))if(typeof s==="string")i.push({kind:t,model:s,name:r})}else if(typeof n==="string")i.push({kind:t,model:n})}return i}function ve(e){let i=e._definition;return typeof i==="object"&&i!==null&&typeof i.name==="string"&&typeof e.toJSON==="function"&&typeof e.getAttributes==="function"}function M(e,i={}){let t={..._e,...i.limits},n=i.describers??[],r=new Map,s=0,c=1;function u(f,T){if(s++,f===void 0)return{t:"undefined"};if(f===null)return{t:"null"};switch(typeof f){case"boolean":return{t:"boolean",v:f};case"number":if(Number.isNaN(f))return{t:"number",v:"NaN"};if(f===Number.POSITIVE_INFINITY)return{t:"number",v:"Infinity"};if(f===Number.NEGATIVE_INFINITY)return{t:"number",v:"-Infinity"};if(Object.is(f,-0))return{t:"number",v:"-0"};return{t:"number",v:f};case"bigint":return{t:"bigint",v:f.toString()};case"string":return f.length>t.maxString?{t:"string",v:f.slice(0,t.maxString),truncated:f.length-t.maxString}:{t:"string",v:f};case"symbol":return{t:"symbol",v:f.description??""};case"function":return{t:"function",name:f.name||"(anonymous)",kind:Pe(f)}}let o=f,g=r.get(o);if(g!==void 0)return{t:"ref",id:g};if(o instanceof Date)return{t:"date",v:Number.isNaN(o.getTime())?null:o.toISOString()};if(o instanceof RegExp)return{t:"regexp",v:o.toString()};if(o instanceof URL)return{t:"url",v:o.href};if(o instanceof Promise)return{t:"promise"};if(ArrayBuffer.isView(o)||o instanceof ArrayBuffer){let x=o instanceof ArrayBuffer?new Uint8Array(o):new Uint8Array(o.buffer,o.byteOffset,o.byteLength);return{t:"bytes",ctor:o.constructor?.name??"ArrayBuffer",length:x.byteLength,hex:Buffer.from(x.subarray(0,64)).toString("hex")}}if(T>=t.maxDepth)return{t:"cut",reason:"depth",ctor:C(o)??(Array.isArray(o)?"Array":"Object")};if(s>=t.maxNodes)return{t:"cut",reason:"nodes",ctor:C(o)};let p=c++;r.set(o,p);let y=(x)=>u(x,T+1);if(o instanceof Error)return k(o,y);if(o instanceof R){let x=o.html.length-re;return{t:"html",kind:o.kind,...o.title?{title:o.title}:{},html:x>0?o.html.slice(0,re):o.html,...o.text?{text:o.text.slice(0,t.maxString)}:{},...x>0?{truncated:x}:{}}}if(ve(o))return h(o,p,y);for(let x of n){let m;try{m=x(o,y)}catch{m=void 0}if(m)return m}if(Array.isArray(o)){let x=[],m=Math.min(o.length,t.maxItems);for(let a=0;a<m&&s<t.maxNodes;a++)x.push(y(o[a]));let d=o.length-x.length,w=C(o);return{t:"array",id:p,...w&&w!=="Array"?{ctor:w}:{},length:o.length,items:x,...d>0?{more:d}:{}}}if(o instanceof Map){let x=[];for(let[d,w]of o){if(x.length>=t.maxItems||s>=t.maxNodes)break;x.push([y(d),y(w)])}let m=o.size-x.length;return{t:"map",id:p,size:o.size,entries:x,...m>0?{more:m}:{}}}if(o instanceof Set){let x=[];for(let d of o){if(x.length>=t.maxItems||s>=t.maxNodes)break;x.push(y(d))}let m=o.size-x.length;return{t:"set",id:p,size:o.size,items:x,...m>0?{more:m}:{}}}return b(o,p,y)}function h(f,T,o){let g=f._definition,p={};try{let E=f.toJSON();if(E&&typeof E==="object")p=E}catch{}let y={};try{y=f.getLoadedRelations?.()??{}}catch{y={}}let x=Object.keys(p).filter((E)=>!(E in y)),m=[];for(let E of x){if(m.length>=t.maxItems||s>=t.maxNodes)break;m.push([E,o(p[E])])}let d=Object.keys(f).filter((E)=>!(E in p)),w=[];for(let[E,N]of Object.entries(y)){if(w.length>=t.maxItems||s>=t.maxNodes)break;w.push([E,o(N)])}let a=L(g),l=typeof g.primaryKey==="string"?g.primaryKey:"id",S=x.length-m.length;return{t:"model",id:T,model:g.name,...typeof g.table==="string"?{table:g.table}:{},primaryKey:l,...p[l]!==void 0?{key:o(p[l])}:{},attributes:m,...d.length?{hidden:d}:{},...w.length?{loaded:w}:{},...a.length?{relations:a}:{},...S>0?{more:S}:{}}}function b(f,T,o){let g=C(f),p=f,y=Object.keys(f);if(y.length===0&&g&&typeof f.toJSON==="function")try{let d=f.toJSON();if(Array.isArray(d)){let w=o(d);return w.t==="array"?{...w,ctor:g}:w}if(d&&typeof d==="object")p=d,y=Object.keys(p)}catch{}let x=[];for(let d of y){if(x.length>=t.maxItems||s>=t.maxNodes)break;let w;try{w=p[d]}catch(a){w=a}x.push([d,o(w)])}let m=y.length-x.length;return{t:"object",id:T,...g?{ctor:g}:{},entries:x,...m>0?{more:m}:{}}}function k(f,T){let o={t:"error",name:f.name||"Error",message:String(f.message??"")};if(typeof f.stack==="string"){o.stack=f.stack;let p=Ae(f.stack);if(p.length)o.frames=p}if(f.cause!==void 0)o.cause=T(f.cause);let g=[];for(let p of Object.keys(f)){if(p==="name"||p==="message"||p==="stack"||p==="cause")continue;if(g.length>=t.maxItems)break;g.push([p,T(f[p])])}if(g.length)o.entries=g;return o}return u(e,0)}function z(e,i={}){if(e instanceof Error)return M(e,i);return{t:"error",name:"Thrown",message:typeof e==="string"?e:Bun.inspect(e),cause:M(e,i)}}import{parse as Re}from"@babel/parser";var Ve={open:"(__tinkerPending(",close:") ? await __tinkerTake() : __tinkerTake())"},Tt={open:"__tinkerSettled(",close:")"},St=`declare function __tinkerSettled<T>(value: T | Promise<T>): T
9
+ `,Ce=["__tinkerProbe","__tinkerTime"],je=new Set(["CallExpression","OptionalCallExpression","NewExpression","TaggedTemplateExpression","ImportExpression"]),Fe=new Set(["FunctionDeclaration","FunctionExpression","ArrowFunctionExpression","ObjectMethod","ClassMethod","ClassPrivateMethod","ClassDeclaration","ClassExpression"]),ie=new Set(["TSAsExpression","TSSatisfiesExpression","TSNonNullExpression","TSTypeAssertion","TSInstantiationExpression"]),Be=new Set(["loc","extra","typeAnnotation","typeArguments","typeParameters","returnType","decorators","leadingComments","trailingComments","innerComments"]),Le=new Set(["then","catch","finally"]),ze=new Set(["Program","BlockStatement","SwitchCase","StaticBlock"]),De=new Set(["=","||=","&&=","??="]);function D(e){return Boolean(e)&&typeof e==="object"&&typeof e.type==="string"&&typeof e.start==="number"}function We(e){if(e.type!=="MemberExpression"&&e.type!=="OptionalMemberExpression"||e.computed)return;let i=e.property;return i.type==="Identifier"?i.name:void 0}function qe(e){if(e.type!=="CallExpression")return!1;let i=e.callee,t=i.object;return i.type==="MemberExpression"&&!i.computed&&t?.type==="Identifier"&&t.name==="Promise"}function Ue(e){let i=(t)=>Re(t,{sourceType:"module",plugins:["typescript","decorators"],errorRecovery:!0,allowReturnOutsideFunction:!0,allowUndeclaredExports:!0}).program;if(/^\s*\{/.test(e))try{let n=i(`(${e}
10
+ )`).body;if(n.length===1&&n[0].type==="ExpressionStatement"&&n[0].expression.type==="ObjectExpression")return{root:n[0].expression,shift:1}}catch{}try{return{root:i(e),shift:0}}catch{return}}function se(e,i={}){let t=i.wrap??Ve,n=new Set(i.transparent??Ce),r=Ue(e);if(!r)return{code:e,edits:[]};let s=new Set,c=new Set,u=(a)=>{let l=a.callee;return a.type==="CallExpression"&&l?.type==="Identifier"&&n.has(l.name)},h=(a,l,S)=>{if(u(a))return!1;if(!l)return!0;if(l.type==="AwaitExpression")return!1;if(l.type==="UnaryExpression"&&l.operator==="void")return!1;if(S==="object"&&Le.has(We(l)??""))return!1;if((l.type==="OptionalMemberExpression"||l.type==="OptionalCallExpression")&&l.optional===!1&&(S==="object"||S==="callee"))return!1;if(l.type==="AssignmentExpression"&&S==="left"||l.type==="UpdateExpression"||(l.type==="ForInStatement"||l.type==="ForOfStatement")&&S==="left")return!1;return!0},b=(a)=>{if(!D(a))return;if(ie.has(a.type)||a.type==="ParenthesizedExpression")return b(a.expression);switch(a.type){case"Identifier":if(a.name!=="undefined")s.add(a);return;case"MemberExpression":case"OptionalMemberExpression":s.add(a);return;case"AssignmentExpression":if(De.has(a.operator))b(a.right);return;case"ConditionalExpression":b(a.consequent),b(a.alternate);return;case"LogicalExpression":b(a.left),b(a.right);return;case"SequenceExpression":{let l=a.expressions;b(l[l.length-1])}}},k=(a,l,S)=>{if(Fe.has(a.type))return;if(a.type.startsWith("TS")){if(ie.has(a.type))k(a.expression,a,"expression");return}if(je.has(a.type)&&h(a,l,S))s.add(a);if(a.type==="ExpressionStatement")b(a.expression);else if(a.type==="VariableDeclarator")b(a.init);else if(a.type==="ExportDefaultDeclaration")b(a.declaration);else if(u(a))b(a.arguments[1]);let E=qe(a);for(let N of Object.keys(a)){if(Be.has(N)||E&&N==="arguments")continue;let O=a[N];if(Array.isArray(O)){for(let v of O)if(D(v))k(v,a,N)}else if(D(O))k(O,a,N)}if(a.type==="ExpressionStatement"&&l&&ze.has(l.type))c.add(a.start)},{root:f,shift:T}=r;if(k(f,void 0,""),!s.size)return{code:e,edits:[]};let o=[...s],g=o.slice().sort((a,l)=>a.end-l.end||l.start-a.start),p=o.slice().sort((a,l)=>a.start-l.start||l.end-a.end),y=[],x=0,m=0;while(x<g.length||m<p.length){let a=g[x],l=p[m];if(a&&(!l||a.end<=l.start))y.push({at:a.end-T,text:t.close}),x++;else if(l){let S=c.delete(l.start)?";":"";y.push({at:l.start-T,text:S+t.open}),m++}}let d="",w=0;for(let a of y)d+=e.slice(w,a.at)+a.text,w=a.at;return d+=e.slice(w),{code:d,edits:y}}function Et(e,i){let t=i;for(let n of e){if(n.at>i)break;t+=n.text.length}return t}function $t(e,i){let t=0;for(let n of e){let r=n.at+t;if(i<r)break;if(i<r+n.text.length)return n.at;t+=n.text.length}return i-t}var Ke=/__tinkerPending\(/g,Je=/\)\s*\?\s*await __tinkerTake\(\)\s*:\s*__tinkerTake\(\)/g;function W(e){return e.includes("__tinkerPending(")?e.replace(Ke,"").replace(Je,""):e}function Ge(){let e=[],i=new Set;for(let t of Object.getOwnPropertyNames(globalThis)){let n;try{n=globalThis[t]}catch{continue}if(!n||typeof n!=="object"&&typeof n!=="function")continue;let r=n.getDefinition;if(typeof r!=="function")continue;let s;try{s=r.call(n)}catch{continue}if(!s||typeof s.name!=="string"||i.has(s.name))continue;i.add(s.name),e.push({name:s.name,...typeof s.table==="string"?{table:s.table}:{},...typeof s.primaryKey==="string"?{primaryKey:s.primaryKey}:{},attributes:s.attributes&&typeof s.attributes==="object"?Object.keys(s.attributes):[],relations:L(s)})}return e.sort((t,n)=>t.name.localeCompare(n.name))}function Ye(){return{html(e,i){return new R("html",String(e),i)},async mail(e,i={}){let{templateByName:n}=await import("@stacksjs/email"),r=await n(e,{variables:i});if(!r?.html)throw Error(`No mail template named "${e}" rendered. Templates live in resources/emails.`);return new R("mail",r.html,e,r.text)}}}class j extends Error{constructor(){super("dd");this.name="TinkerHalt"}}var Qe=/\bimport\((["'])(\.{1,2}\/[^"']*)\1\)/g;function q(e,i,t="tinker",n={}){let r=new Bun.Transpiler({loader:"ts",replMode:!0}),s=(u)=>r.transformSync(u).replace(Qe,(h,b,k)=>`import(${b}${oe(i,k)}${b})`),c;if(n.settle){let u=se(e);if(u.edits.length)try{c=s(u.code)}catch{}}return`${c??s(e)}
11
+ //# sourceURL=${t}.ts`}function Xe(e){if(!(e instanceof Error)||!e.message.includes("__tinkerPending("))return;try{if(e.message=W(e.message),typeof e.stack==="string")e.stack=W(e.stack)}catch{}}function Ze(e){let i=e instanceof AggregateError?e.errors:[e],t=[];for(let n of i){if(!n||typeof n!=="object")continue;let{message:r,position:s}=n;t.push({message:typeof r==="string"?r:String(n),...s?.line!==void 0?{line:s.line}:{},...s?.column!==void 0?{column:s.column}:{},...s?.lineText?{lineText:s.lineText}:{}})}return t}async function et(e){let n=!0;try{let{overridesReady:r}=await import("@stacksjs/config");await r}catch(r){n=!1,e.push(`config not loaded: ${r instanceof Error?r.message:String(r)}`)}try{let{injectGlobalAutoImports:r}=await import("@stacksjs/server");await r()}catch(r){n=!1,e.push(`models and framework globals not injected: ${r instanceof Error?r.message:String(r)}`)}return n}var tt=["log","info","debug","dir","table"],nt=["warn","error","trace"];async function F(e={}){let i=e.cwd?He(e.cwd)?e.cwd:oe(I.cwd(),e.cwd):I.cwd();if(i!==I.cwd())I.chdir(i);let t={limits:e.limits,describers:e.describers},n=[],r=[],s="boot",c,u=(m)=>{c?.push(m);try{e.onFrame?.(m)}catch{}},h=console,b=(m)=>m.map((d)=>typeof d==="string"?d:Bun.inspect(d,{depth:6})).join(" ");for(let[m,d]of[[tt,"stdout"],[nt,"stderr"]])for(let w of m){let a=h[w];h[w]=(...l)=>u({type:d,id:s,text:`${b(l)}
12
+ `}),r.push(()=>{h[w]=a})}for(let[m,d]of[[I.stdout,"stdout"],[I.stderr,"stderr"]]){let w=m.write;m.write=(a,...l)=>(u({type:d,id:s,text:typeof a==="string"?a:Buffer.from(a).toString("utf8")}),l.find((E)=>typeof E==="function")?.(),!0),r.push(()=>{m.write=w})}let k=globalThis;k.dump=(...m)=>{for(let d of m)u({type:"dump",id:s,value:M(d,t)})},k.dd=(...m)=>{throw k.dump(...m),new j},k.preview=Ye();let f=performance.now();k.__tinkerProbe=(m,d,w)=>{let a=s,l=(S)=>u({type:"probe",id:a,line:m,kind:"value",value:M(S,t)});if(!w)return l(d),d;try{let S=w(d);if(S instanceof Promise)S.then(l,(E)=>l(E));else l(S)}catch(S){l(S)}return d};let T;if(k.__tinkerPending=(m)=>(T=m,m instanceof Promise),k.__tinkerTake=()=>{let m=T;return T=void 0,m},k.__tinkerTime=(m,d)=>(u({type:"probe",id:s,line:m,kind:"time",ms:Math.round((performance.now()-f)*100)/100}),d),e.globals)Object.assign(k,e.globals);let o=!1;if(typeof e.boot==="function")try{await e.boot(),o=!0}catch(m){n.push(`boot failed: ${m instanceof Error?m.message:String(m)}`)}else if(e.boot!==!1)o=await et(n);if(o&&e.boot!==!1&&typeof e.boot!=="function"){let m=(...a)=>{for(let l of a)u({type:"dump",id:s,value:M(l,t)})};k.dump=m,k.dd=(...a)=>{throw m(...a),new j};let d="@stacksjs/logging",w="@stacksjs/query-builder";try{let{registerTransport:a}=await import(d);r.push(a({name:"tinker",log(l){u({type:"log",id:s,level:l.level,message:l.message,timestamp:l.timestamp,...l.context?{context:M(l.context,t)}:{}})}}))}catch(a){n.push(`log capture unavailable: ${a instanceof Error?a.message:String(a)}`)}try{let{registerPersistentQueryHooks:a}=await import(w);r.push(a({onQueryEnd(l){u({type:"query",id:s,sql:l.sql,...l.params?.length?{params:M(l.params,t)}:{},...l.kind?{kind:l.kind}:{},durationMs:l.durationMs,...l.rowCount!==void 0?{rowCount:l.rowCount}:{}})},onQueryError(l){u({type:"query",id:s,sql:l.sql,...l.params?.length?{params:M(l.params,t)}:{},...l.kind?{kind:l.kind}:{},durationMs:l.durationMs,error:l.error instanceof Error?l.error.message:String(l.error)})}}))}catch(a){n.push(`query capture unavailable: ${a instanceof Error?a.message:String(a)}`)}}let g=eval,p=0,y=Promise.resolve();async function x(m,d,w){let a=[];c=a,s=d;let l=performance.now();f=l;let S=()=>Math.round((performance.now()-l)*100)/100,E;try{E=q(e.magic===!1?m:ne(m).code,i,`tinker-${d}`,{settle:w})}catch(N){let O=S();return u({type:"error",id:d,phase:"parse",error:z(N,t),diagnostics:Ze(N),durationMs:O}),u({type:"done",id:d,ok:!1}),c=void 0,{id:d,ok:!1,thrown:N,frames:a,durationMs:O}}try{let O=(await g(E))?.value,v=S();return u({type:"result",id:d,value:M(O,t),durationMs:v}),u({type:"done",id:d,ok:!0}),{id:d,ok:!0,value:O,frames:a,durationMs:v}}catch(N){let O=S();if(T=void 0,N instanceof j)return u({type:"result",id:d,value:{t:"undefined"},durationMs:O}),u({type:"done",id:d,ok:!0}),{id:d,ok:!0,frames:a,durationMs:O};return Xe(N),u({type:"error",id:d,phase:"run",error:z(N,t),durationMs:O}),u({type:"done",id:d,ok:!1}),{id:d,ok:!1,thrown:N,frames:a,durationMs:O}}finally{c=void 0}}return{info:{cwd:i,booted:o,bun:Bun.version,warnings:n},models:Ge,evaluate(m,d={}){let w=d.id??String(++p),a=y.then(()=>x(m,w,d.settle??e.settle!==!1));return y=a.catch(()=>{}),a},dispose(){while(r.length)r.pop()?.()}}}var U="\x1E",it=2;function st(e){return`${U}${JSON.stringify(e)}
13
+ `}function Vt(){let e="",i=(t)=>{if(t.startsWith(U))try{return{frame:JSON.parse(t.slice(U.length))}}catch{return{stray:t}}return{stray:t}};return{push(t){e+=t;let n=e.split(`
14
+ `);return e=n.pop()??"",n.map(i)},flush(){if(!e)return[];let t=e;return e="",[{stray:t}]}}}async function ae(e={}){let i=e.write??((g)=>{rt(1,g)}),t=(g)=>i(st(g)),{input:n,write:r,once:s,...c}=e,u=await F({...c,onFrame:t});t({type:"ready",session:u.info,protocol:it});let h=!0,b=!1;if(s!==void 0)return{ok:(await u.evaluate(s)).ok,session:u};let k=new TextDecoder,f="",T=n??Bun.stdin.stream(),o=async(g)=>{if(!g.trim())return!0;let p;try{p=JSON.parse(g)}catch{return t({type:"protocol-error",message:"request is not valid JSON"}),!0}if(p.op==="exit")return!1;if(p.op==="ping")return t({type:"pong",...p.id?{id:p.id}:{}}),!0;if(p.op==="models")return t({type:"models",...p.id?{id:p.id}:{},models:u.models()}),!0;if(p.op==="eval"&&typeof p.code==="string"){if(!(await u.evaluate(p.code,{id:p.id,...typeof p.settle==="boolean"?{settle:p.settle}:{}})).ok)h=!1;return!0}return t({type:"protocol-error",message:`unknown request: ${String(p.op)}`}),!0};e:for await(let g of T){f+=typeof g==="string"?g:k.decode(g,{stream:!0});let p=f.indexOf(`
15
+ `);while(p!==-1){let y=f.slice(0,p);if(f=f.slice(p+1),!await o(y)){b=!0;break e}p=f.indexOf(`
16
+ `)}}if(!b&&f.trim())await o(f);return{ok:h,session:u}}function K(e){return e?.historyFile??lt(ut(),".stacks_tinker_history")}function fe(e){let i=K(e);if(!ue(i))return[];return at(i,"utf-8").split(`
17
+ `).filter(Boolean)}function mt(e,i){let t=K(i),n=!ue(t);if(ot(t,`${e}
18
+ `),n)try{ce(t,384)}catch{}let r=i?.historySize??5000,s=fe(i);if(s.length>r){let c=s.slice(s.length-r);le(t,c.join(`
17
19
  `)+`
18
- `);try{ne(t,384)}catch{}}}function Ke(e){let i=D(e);ie(i,"")}function Je(e){let i=["",` \x1B[36mStacks Tinker\x1B[0m (Bun v${e.bun})`,e.booted?" Your app is booted: models, jobs, config and framework helpers are globals.":" Bare session: the app context is not booted."];for(let t of e.warnings)i.push(` \x1B[33m${t}\x1B[0m`);return i.push(""," \x1B[2mDeclarations persist between lines. dump(value) inspects, dd(value) inspects and stops."," .help for commands, .exit or Ctrl+D to leave.\x1B[0m","",""),i.join(`
19
- `)}function N(e,i=1){Le(i,e)}function M(e,i=""){let t=`${i} `;switch(e.t){case"undefined":return"undefined";case"null":return"null";case"boolean":return String(e.v);case"number":return String(e.v);case"bigint":return`${e.v}n`;case"string":return JSON.stringify(e.v)+(e.truncated?` ... ${e.truncated} more characters`:"");case"symbol":return`Symbol(${e.v})`;case"function":return`[${e.kind==="class"?"class":"Function"}: ${e.name}]`;case"date":return e.v??"Invalid Date";case"regexp":return e.v;case"url":return e.v;case"promise":return"Promise {}";case"bytes":return`${e.ctor}(${e.length}) <${e.hex}${e.length>64?" ...":""}>`;case"ref":return`[Circular *${e.id}]`;case"cut":return`[${e.ctor??"Object"}]`;case"error":return e.stack??`${e.name}: ${e.message}`;case"array":{if(!e.items.length&&!e.more)return`${e.ctor?`${e.ctor} `:""}[]`;let n=e.items.map((r)=>`${t}${M(r,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return`${e.ctor?`${e.ctor} `:""}[
20
+ `);try{ce(t,384)}catch{}}}function pt(e){let i=K(e);le(i,"")}function dt(e){let i=["",` \x1B[36mStacks Tinker\x1B[0m (Bun v${e.bun})`,e.booted?" Your app is booted: models, jobs, config and framework helpers are globals.":" Bare session: the app context is not booted."];for(let t of e.warnings)i.push(` \x1B[33m${t}\x1B[0m`);return i.push(""," \x1B[2mDeclarations persist between lines. A query needs no await: User.first() is the row."," dump(value) inspects, dd(value) inspects and stops."," .help for commands, .exit or Ctrl+D to leave.\x1B[0m","",""),i.join(`
21
+ `)}function _(e,i=1){ct(i,e)}function A(e,i=""){let t=`${i} `;switch(e.t){case"undefined":return"undefined";case"null":return"null";case"boolean":return String(e.v);case"number":return String(e.v);case"bigint":return`${e.v}n`;case"string":return JSON.stringify(e.v)+(e.truncated?` ... ${e.truncated} more characters`:"");case"symbol":return`Symbol(${e.v})`;case"function":return`[${e.kind==="class"?"class":"Function"}: ${e.name}]`;case"date":return e.v??"Invalid Date";case"regexp":return e.v;case"url":return e.v;case"promise":return"Promise {}";case"bytes":return`${e.ctor}(${e.length}) <${e.hex}${e.length>64?" ...":""}>`;case"ref":return`[Circular *${e.id}]`;case"cut":return`[${e.ctor??"Object"}]`;case"error":return e.stack??`${e.name}: ${e.message}`;case"array":{if(!e.items.length&&!e.more)return`${e.ctor?`${e.ctor} `:""}[]`;let n=e.items.map((r)=>`${t}${A(r,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return`${e.ctor?`${e.ctor} `:""}[
20
22
  ${n.join(`,
21
23
  `)}
22
- ${i}]`}case"set":{let n=e.items.map((r)=>`${t}${M(r,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return n.length?`Set(${e.size}) {
24
+ ${i}]`}case"set":{let n=e.items.map((r)=>`${t}${A(r,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return n.length?`Set(${e.size}) {
23
25
  ${n.join(`,
24
26
  `)}
25
- ${i}}`:"Set(0) {}"}case"map":{let n=e.entries.map(([r,o])=>`${t}${M(r,t)} => ${M(o,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return n.length?`Map(${e.size}) {
27
+ ${i}}`:"Set(0) {}"}case"map":{let n=e.entries.map(([r,s])=>`${t}${A(r,t)} => ${A(s,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return n.length?`Map(${e.size}) {
26
28
  ${n.join(`,
27
29
  `)}
28
- ${i}}`:"Map(0) {}"}case"html":return`[${e.kind}${e.title?` ${e.title}`:""}: ${e.html.length} characters of markup]`;case"model":{let n=e.attributes.map(([r,o])=>`${t}${r}: ${M(o,t)}`);for(let r of e.hidden??[])n.push(`${t}${r}: [hidden]`);for(let[r,o]of e.loaded??[])n.push(`${t}${r}: ${M(o,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return`${e.model} {
30
+ ${i}}`:"Map(0) {}"}case"html":return`[${e.kind}${e.title?` ${e.title}`:""}: ${e.html.length} characters of markup]`;case"model":{let n=e.attributes.map(([r,s])=>`${t}${r}: ${A(s,t)}`);for(let r of e.hidden??[])n.push(`${t}${r}: [hidden]`);for(let[r,s]of e.loaded??[])n.push(`${t}${r}: ${A(s,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return`${e.model} {
29
31
  ${n.join(`,
30
32
  `)}
31
- ${i}}`}case"object":{if(!e.entries.length&&!e.more)return`${e.ctor?`${e.ctor} `:""}{}`;let n=e.entries.map(([r,o])=>`${t}${r}: ${M(o,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return`${e.ctor?`${e.ctor} `:""}{
33
+ ${i}}`}case"object":{if(!e.entries.length&&!e.more)return`${e.ctor?`${e.ctor} `:""}{}`;let n=e.entries.map(([r,s])=>`${t}${r}: ${A(s,t)}`);if(e.more)n.push(`${t}... ${e.more} more`);return`${e.ctor?`${e.ctor} `:""}{
32
34
  ${n.join(`,
33
35
  `)}
34
- ${i}}`}}}function He(e,i){switch(e.type){case"stdout":N(e.text);break;case"stderr":N(e.text,2);break;case"dump":N(`${M(e.value)}
35
- `);break;case"probe":N(`\x1B[2m line ${e.line+1}:\x1B[0m ${e.kind==="time"?`${e.ms} ms`:M(e.value," ")}
36
- `);break;case"query":if(i)N(`\x1B[2m ${e.durationMs??"?"}ms ${e.sql}\x1B[0m
37
- `,2);break;case"log":if(i)N(`\x1B[2m [${e.level}] ${e.message}\x1B[0m
38
- `,2);break}}async function Ge(e,i){let t=[];for(let n of e??[]){let r=n.replace(/[@/\-.]/g,"_").replace(/^_+/,"");try{let o=n.startsWith(".")?We(i,n):n;globalThis[r]=await import(o)}catch(o){t.push(`${n}: ${o instanceof Error?o.message:String(o)}`)}}return t}var Ye=/Unexpected end of file|Unterminated|Expected "\}" but found end of file|Expected "\)" but found end of file|Expected "\]" but found end of file/;function Qe(e,i){try{return z(e,i),!1}catch(t){return(t instanceof AggregateError?t.errors.map((r)=>String(r?.message??r)):[String(t?.message??t)]).some((r)=>Ye.test(r))}}async function se(e={}){let i=e.cwd??F.cwd(),t=e.stacksPreload!==!1;if(e.serve){let s=e.eval??e.print,{ok:d}=await te({cwd:i,boot:t,...s!==void 0?{once:s}:{}});return{exitCode:d?0:1}}let n=e.verbose===!0,r=await _({cwd:i,boot:t,onFrame:(s)=>He(s,n)});for(let s of await Ge(e.preload,r.info.cwd))N(`\x1B[33mpreload failed: ${s}\x1B[0m
39
- `,2);let o=(s,d)=>{if(!s.ok){let f=s.thrown;N(`${f instanceof Error?Bun.inspect(f,{colors:Boolean(F.stderr.isTTY)}):`Uncaught ${Bun.inspect(f)}`}
40
- `,2);return}if(d&&s.value!==void 0)N(`${M(E(s.value))}
41
- `)};if(e.eval!==void 0||e.print!==void 0){for(let d of r.info.warnings)N(`\x1B[33m${d}\x1B[0m
42
- `,2);let s=await r.evaluate(e.print??e.eval??"");return o(s,e.print!==void 0),r.dispose(),{exitCode:s.ok?0:1}}if(e.banner!==!1)N(Je(r.info));let{createInterface:a}=await import("readline"),{Writable:u}=await import("stream"),k=new u({write(s,d,f){N(typeof s==="string"?s:Buffer.from(s).toString("utf8")),f()}}),w=e.historySize??5000,b=a({input:F.stdin,output:k,terminal:Boolean(F.stdin.isTTY),history:oe(e).slice(-w).reverse(),historySize:w,prompt:"> "}),c="",x=0;b.prompt();try{for await(let s of b){let d=s.trim();if(!c&&d.startsWith(".")){if(d===".exit")break;if(d===".help")N(` .exit leave
36
+ ${i}}`}}}function gt(e,i){switch(e.type){case"stdout":_(e.text);break;case"stderr":_(e.text,2);break;case"dump":_(`${A(e.value)}
37
+ `);break;case"probe":_(`\x1B[2m line ${e.line+1}:\x1B[0m ${e.kind==="time"?`${e.ms} ms`:A(e.value," ")}
38
+ `);break;case"query":if(i)_(`\x1B[2m ${e.durationMs??"?"}ms ${e.sql}\x1B[0m
39
+ `,2);break;case"log":if(i)_(`\x1B[2m [${e.level}] ${e.message}\x1B[0m
40
+ `,2);break}}async function yt(e,i){let t=[];for(let n of e??[]){let r=n.replace(/[@/\-.]/g,"_").replace(/^_+/,"");try{let s=n.startsWith(".")?ft(i,n):n;globalThis[r]=await import(s)}catch(s){t.push(`${n}: ${s instanceof Error?s.message:String(s)}`)}}return t}var bt=/Unexpected end of file|Unterminated|Expected "\}" but found end of file|Expected "\)" but found end of file|Expected "\]" but found end of file/;function kt(e,i){try{return q(e,i),!1}catch(t){return(t instanceof AggregateError?t.errors.map((r)=>String(r?.message??r)):[String(t?.message??t)]).some((r)=>bt.test(r))}}async function me(e={}){let i=e.cwd??B.cwd(),t=e.stacksPreload!==!1;if(e.serve){let o=e.eval??e.print,{ok:g}=await ae({cwd:i,boot:t,...o!==void 0?{once:o}:{}});return{exitCode:g?0:1}}let n=e.verbose===!0,r=await F({cwd:i,boot:t,onFrame:(o)=>gt(o,n)});for(let o of await yt(e.preload,r.info.cwd))_(`\x1B[33mpreload failed: ${o}\x1B[0m
41
+ `,2);let s=(o,g)=>{if(!o.ok){let p=o.thrown;_(`${p instanceof Error?Bun.inspect(p,{colors:Boolean(B.stderr.isTTY)}):`Uncaught ${Bun.inspect(p)}`}
42
+ `,2);return}if(g&&o.value!==void 0)_(`${A(M(o.value))}
43
+ `)};if(e.eval!==void 0||e.print!==void 0){for(let g of r.info.warnings)_(`\x1B[33m${g}\x1B[0m
44
+ `,2);let o=await r.evaluate(e.print??e.eval??"");return s(o,e.print!==void 0),r.dispose(),{exitCode:o.ok?0:1}}if(e.banner!==!1)_(dt(r.info));let{createInterface:c}=await import("readline"),{Writable:u}=await import("stream"),h=new u({write(o,g,p){_(typeof o==="string"?o:Buffer.from(o).toString("utf8")),p()}}),b=e.historySize??5000,k=c({input:B.stdin,output:h,terminal:Boolean(B.stdin.isTTY),history:fe(e).slice(-b).reverse(),historySize:b,prompt:"> "}),f="",T=0;k.prompt();try{for await(let o of k){let g=o.trim();if(!f&&g.startsWith(".")){if(g===".exit")break;if(g===".help")_(` .exit leave
43
45
  .clear forget the history file
44
46
  .help this list
45
47
  dump(v), dd(v) inspect a value; dd also stops the line
46
- `);else if(d===".clear")Ke(e);else N(` unknown command ${d}
47
- `);b.prompt();continue}if(c=c?`${c}
48
- ${s}`:s,!c.trim()){c="",b.prompt();continue}if(Qe(c,r.info.cwd)){b.setPrompt("... "),b.prompt();continue}let f=c;c="";try{Ue(f.replace(/\n/g," "),e)}catch{}let y=await r.evaluate(f);o(y,!0),x=y.ok?0:x,b.setPrompt("> "),b.prompt()}}finally{b.close(),r.dispose()}return{exitCode:x}}async function yt(e,i={}){return se({...i,eval:e})}async function kt(e,i={}){return se({...i,print:e})}export{L as FRAME_MARKER,Fe as PROTOCOL_VERSION,I as TinkerPreview,Ue as appendHistory,Ke as clearHistory,z as compileSnippet,at as createFrameReader,_ as createTinkerSession,Te as defaultSerializeLimits,Be as encodeFrame,D as getHistoryPath,he as hasMagicComments,X as instrumentMagicComments,Qe as isIncompleteSnippet,Ee as isModelInstance,ve as listModels,$e as parseStack,oe as readHistory,B as relationsOf,M as renderValue,E as serialize,C as serializeThrown,te as serveTinker,se as startTinker,yt as tinkerEval,kt as tinkerPrint,fe as tokenize};
48
+ `);else if(g===".clear")pt(e);else _(` unknown command ${g}
49
+ `);k.prompt();continue}if(f=f?`${f}
50
+ ${o}`:o,!f.trim()){f="",k.prompt();continue}if(kt(f,r.info.cwd)){k.setPrompt("... "),k.prompt();continue}let p=f;f="";try{mt(p.replace(/\n/g," "),e)}catch{}let y=await r.evaluate(p);s(y,!0),T=y.ok?0:T,k.setPrompt("> "),k.prompt()}}finally{k.close(),r.dispose()}return{exitCode:T}}async function qt(e,i={}){return me({...i,eval:e})}async function Ut(e,i={}){return me({...i,print:e})}export{U as FRAME_MARKER,it as PROTOCOL_VERSION,Ve as SETTLE_RUNTIME_WRAP,Ce as SETTLE_TRANSPARENT,St as SETTLE_TYPE_AMBIENT,Tt as SETTLE_TYPE_WRAP,R as TinkerPreview,mt as appendHistory,pt as clearHistory,q as compileSnippet,Vt as createFrameReader,F as createTinkerSession,_e as defaultSerializeLimits,st as encodeFrame,K as getHistoryPath,$e as hasMagicComments,ne as instrumentMagicComments,kt as isIncompleteSnippet,ve as isModelInstance,Ge as listModels,$t as originalOffset,Ae as parseStack,fe as readHistory,L as relationsOf,A as renderValue,M as serialize,z as serializeThrown,ae as serveTinker,se as settleTopLevel,Et as settledOffset,me as startTinker,qt as tinkerEval,Ut as tinkerPrint,ke as tokenize,W as unsettleText};
@@ -37,7 +37,7 @@ export declare interface ServeOptions extends Omit<TinkerSessionOptions, 'onFram
37
37
  write?: (text: string) => void
38
38
  once?: string
39
39
  }
40
- export type TinkerRequest = | { op: 'eval', id?: string, code: string }
40
+ export type TinkerRequest = | { op: 'eval', id?: string, code: string, settle?: boolean }
41
41
  | { op: 'ping', id?: string }
42
42
  | { op: 'models', id?: string }
43
43
  | { op: 'exit' }
package/dist/session.d.ts CHANGED
@@ -11,8 +11,12 @@ export declare function listModels(): TinkerModelSummary[];
11
11
  * Evaluated code has no file, so a relative `import('./app/Actions/Foo')`
12
12
  * would resolve against this package instead of the project. Those specifiers
13
13
  * are made absolute against the session's directory.
14
+ *
15
+ * With `settle`, promises at the snippet's top level are waited for. The
16
+ * compiled code then calls `__tinkerPending` and `__tinkerTake`, which a
17
+ * session provides.
14
18
  */
15
- export declare function compileSnippet(code: string, cwd: string, sourceName?: string): string;
19
+ export declare function compileSnippet(code: string, cwd: string, sourceName?: string, options?: { settle?: boolean }): string;
16
20
  export declare function createTinkerSession(options?: TinkerSessionOptions): Promise<TinkerSession>;
17
21
  export declare interface TinkerDiagnostic {
18
22
  message: string
@@ -31,6 +35,7 @@ export declare interface TinkerSessionOptions extends SerializeOptions {
31
35
  boot?: boolean | (() => Promise<void> | void)
32
36
  globals?: Record<string, unknown>
33
37
  magic?: boolean
38
+ settle?: boolean
34
39
  onFrame?: (frame: TinkerFrame) => void
35
40
  }
36
41
  export declare interface TinkerEvaluation {
@@ -49,10 +54,14 @@ export declare interface TinkerModelSummary {
49
54
  attributes: string[]
50
55
  relations: Array<{ kind: string, model: string, name?: string }>
51
56
  }
57
+ export declare interface TinkerEvaluateOptions {
58
+ id?: string
59
+ settle?: boolean
60
+ }
52
61
  export declare interface TinkerSession {
53
62
  info: TinkerSessionInfo
54
63
  models: () => TinkerModelSummary[]
55
- evaluate: (code: string, options?: { id?: string }) => Promise<TinkerEvaluation>
64
+ evaluate: (code: string, options?: TinkerEvaluateOptions) => Promise<TinkerEvaluation>
56
65
  dispose: () => void
57
66
  }
58
67
  /**
@@ -65,6 +74,11 @@ export declare interface TinkerSession {
65
74
  * globals by Bun's REPL transform, so `const user = await User.find(1)` in one
66
75
  * run is still `user` in the next, and each run reports what happened as
67
76
  * frames: output, logs, queries, dumps, then a typed result or an error.
77
+ *
78
+ * A promise at the top level of a snippet is waited for (see settle.ts), so
79
+ * `const user = User.find(1)` binds the row as well: a query reads the way it
80
+ * does in every other tinker tool, and `await` is only needed inside a
81
+ * function.
68
82
  */
69
83
  export type TinkerFrame = | { type: 'stdout' | 'stderr', id: string, text: string }
70
84
  | { type: 'log', id: string, level: string, message: string, timestamp: string, context?: TinkerValue }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Rewrite a snippet so that promises at its top level are waited for.
3
+ * Returns the code unchanged when there is nothing to wait for, or when it
4
+ * does not parse.
5
+ */
6
+ export declare function settleTopLevel(code: string, options?: SettleOptions): Settled;
7
+ /** Where an offset in the original text is in the rewritten text. */
8
+ export declare function settledOffset(edits: SettleEdit[], offset: number): number;
9
+ /** Where an offset in the rewritten text is in the original. An offset inside an insertion maps to where it was inserted. */
10
+ export declare function originalOffset(edits: SettleEdit[], offset: number): number;
11
+ /**
12
+ * Take the runtime form back out of a message. An engine quotes the code it
13
+ * was evaluating when it failed, and that is the rewritten code: without this
14
+ * a `TypeError` would show the user text they never wrote.
15
+ */
16
+ export declare function unsettleText(text: string): string;
17
+ /**
18
+ * The runtime form. `__tinkerPending(value)` keeps the value and says whether
19
+ * it is a promise; `__tinkerTake()` hands it back. A value that is not a
20
+ * promise never reaches `await`, which is what keeps code with no promise in
21
+ * it running in one turn.
22
+ */
23
+ export declare const SETTLE_RUNTIME_WRAP: SettleWrap;
24
+ /**
25
+ * The form a type checker reads. A language service that wants `user` in
26
+ * `const user = User.first()` typed as the row, as it is when the snippet
27
+ * runs, checks the snippet rewritten with this wrap and with
28
+ * `SETTLE_TYPE_AMBIENT` in scope, and maps positions through `edits`.
29
+ */
30
+ export declare const SETTLE_TYPE_WRAP: SettleWrap;
31
+ /**
32
+ * `T | Promise<T>` rather than a conditional type: the contextual type still
33
+ * reaches the argument (`const tags: Set<string> = new Set()` stays valid),
34
+ * and a thenable that is not a `Promise` is left alone, as it is at runtime.
35
+ */
36
+ export declare const SETTLE_TYPE_AMBIENT: 'declare function __tinkerSettled<T>(value: T | Promise<T>): T\n';
37
+ /** The calls magic comments are rewritten into (see magic.ts). */
38
+ export declare const SETTLE_TRANSPARENT: string[];
39
+ /** What goes before and after an expression that is to be settled. */
40
+ export declare interface SettleWrap {
41
+ open: string
42
+ close: string
43
+ }
44
+ /** One insertion into the original text, at `at`. */
45
+ export declare interface SettleEdit {
46
+ at: number
47
+ text: string
48
+ }
49
+ export declare interface Settled {
50
+ code: string
51
+ edits: SettleEdit[]
52
+ }
53
+ export declare interface SettleOptions {
54
+ wrap?: SettleWrap
55
+ transparent?: string[]
56
+ }
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/tinker",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.559",
5
+ "version": "0.75.561",
6
6
  "description": "Interactive REPL with Stacks framework preloaded.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -58,6 +58,9 @@
58
58
  "test": "bun test",
59
59
  "typecheck": "bun tsc --noEmit"
60
60
  },
61
+ "dependencies": {
62
+ "@babel/parser": "^8.1.2"
63
+ },
61
64
  "devDependencies": {
62
65
  "better-dx": "^0.2.24"
63
66
  }