tjs-lang 0.7.3 → 0.7.4

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.
@@ -0,0 +1,58 @@
1
+ var ut=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Be=ut((Yt,yt)=>{yt.exports={name:"tjs-lang",version:"0.7.3",description:"Type-safe JavaScript dialect with runtime validation, sandboxed VM execution, and AI agent orchestration. Transpiles TypeScript to validated JS with fuel-metered execution for untrusted code.",keywords:["typescript","transpiler","runtime-validation","type-safety","sandbox","virtual-machine","wasm-alternative","ai-agents","llm","orchestration","security","fuel-metering","capability-based","json-ast","untrusted-code"],license:"Apache-2.0",main:"./dist/index.js",types:"./dist/src/index.d.ts",exports:{".":{bun:"./src/index.ts",types:"./dist/src/index.d.ts",default:"./dist/index.js"},"./eval":{bun:"./src/lang/eval.ts",types:"./dist/src/lang/eval.d.ts",default:"./dist/tjs-eval.js"},"./lang":{bun:"./src/lang/transpiler.ts",types:"./dist/src/lang/transpiler.d.ts",default:"./dist/tjs-lang.js"},"./lang/from-ts":{bun:"./src/lang/emitters/from-ts.ts",types:"./dist/src/lang/emitters/from-ts.d.ts",default:"./dist/tjs-from-ts.js"},"./vm":{bun:"./src/vm/index.ts",types:"./dist/src/vm/index.d.ts",default:"./dist/tjs-vm.js"},"./batteries":{bun:"./src/batteries/index.ts",types:"./dist/src/batteries/index.d.ts",default:"./dist/tjs-batteries.js"},"./src":"./src/index.ts","./editors/monaco":"./editors/monaco/ajs-monarch.js","./editors/codemirror":"./editors/codemirror/ajs-language.js","./editors/ace":"./editors/ace/ajs-mode.js"},bin:{tjs:"./src/cli/tjs.ts",tjsx:"./src/cli/tjsx.ts","tjs-playground":"./src/cli/playground.ts","create-tjs-app":"./src/cli/create-app.ts","ajs-install-vscode":"./bin/install-vscode.sh","ajs-install-cursor":"./bin/install-cursor.sh"},type:"module",files:["dist","src","docs","editors","bin","demo","tjs-lang.svg","CONTEXT.md","CLAUDE.md"],sideEffects:!1,repository:{type:"git",url:"https://github.com/tonioloewald/tjs-lang.git"},devDependencies:{"@codemirror/lang-css":"^6.3.1","@codemirror/lang-html":"^6.4.11","@codemirror/lang-javascript":"^6.2.4","@codemirror/lang-markdown":"^6.5.0","@codemirror/state":"^6.5.3","@codemirror/theme-one-dark":"^6.1.3","@codemirror/view":"^6.39.9","@happy-dom/global-registrator":"^20.1.0","@types/bun":"latest","@types/jsdom":"^21.1.7","@typescript-eslint/eslint-plugin":"^5.62.0","@typescript-eslint/parser":"^5.62.0","acorn-walk":"^8.3.4",chokidar:"^4.0.3",codemirror:"^6.0.2",esbuild:"^0.28.0",eslint:"^8.57.1",firebase:"^10.12.0","firebase-admin":"^13.6.0","firebase-functions":"^7.0.5",marked:"^9.1.6",prettier:"^2.8.8",tosijs:"^1.5.6","tosijs-ui":"^1.4.7",typescript:"^5.6.2",valibot:"^0.36.0",vitest:"^2.0.5"},scripts:{format:"bun eslint src --fix && bun prettier --write .",lint:"eslint src","build:grammars":"bun editors/build-grammars.ts","test:fast":"SKIP_LLM_TESTS=1 SKIP_BENCHMARKS=1 bun test","test:llm":"bun test src/batteries/models.integration.test.ts",bench:"bun bin/benchmarks.ts",make:"rm -rf dist && bun format && bun run build:grammars && tsc -p tsconfig.build.json && bun scripts/build.ts","build:bundles":"bun scripts/build.ts",typecheck:"tsc --noEmit",latest:"rm -rf node_modules && bun install",docs:"node bin/docs.js",dev:"bun run bin/dev.ts","build:demo":"bun scripts/build-demo.ts","build:cli":"bun build src/cli/tjs.ts --compile --outfile=dist/tjs && bun build src/cli/tjsx.ts --compile --outfile=dist/tjsx","functions:build":"cd functions && npm run build","functions:deploy":"cd functions && npm run deploy","functions:serve":"cd functions && npm run serve","deploy:hosting":"firebase deploy --only hosting",deploy:"npm run build:demo && npm run functions:deploy && firebase deploy --only hosting",start:"bun run build:demo && bun run dev"},dependencies:{acorn:"^8.15.0","acorn-walk":"^8.3.4","tosijs-schema":"^1.3.0"}}});import u from"typescript";import{validate as qe,s as oe}from"tosijs-schema";function G(e){if(e.nullable)return{anyOf:[G({...e,nullable:!1}),{type:"null"}]};switch(e.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"integer":return{type:"integer"};case"non-negative-integer":return{type:"integer",minimum:0};case"boolean":return{type:"boolean"};case"null":return{type:"null"};case"undefined":return{};case"any":return{};case"array":return e.items?{type:"array",items:G(e.items)}:{type:"array"};case"object":if(e.shape){let t={},r=[];for(let[s,n]of Object.entries(e.shape))t[s]=G(n),r.push(s);return{type:"object",properties:t,required:r,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{anyOf:e.members.map(G)}:{};default:return{}}}function V(e){if(e===null)return{type:"null"};if(e===void 0)return{};switch(typeof e){case"string":return{type:"string"};case"number":return Number.isInteger(e)?{type:"integer"}:{type:"number"};case"boolean":return{type:"boolean"};case"object":{if(Array.isArray(e))return e.length===0?{type:"array"}:{type:"array",items:V(e[0])};let t={},r=[];for(let[s,n]of Object.entries(e))t[s]=V(n),r.push(s);return{type:"object",properties:t,required:r,additionalProperties:!1}}default:return{}}}function fe(e){let t={},r=[];for(let[i,a]of Object.entries(e.params))a?.type?.kind?t[i]=G(a.type):a?.example!==void 0?t[i]=V(a.example):t[i]={},a?.required!==!1&&r.push(i),a?.example!==void 0&&(t[i].examples=[a.example]);let s={type:"object",properties:t,required:r},n;return e.returns&&(e.returns.type?.kind?n=G(e.returns.type):e.returns.example!==void 0&&(n=V(e.returns.example))),{input:s,output:n}}import{validate as de,filter as ct,s as se}from"tosijs-schema";function q(e){return e!==null&&typeof e=="object"&&"__runtimeType"in e&&e.__runtimeType===!0}function Ie(e){return e!==null&&typeof e=="object"&&"schema"in e&&typeof e.schema=="object"}function pt(e){return e!==null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"}function I(e,t,r,s){let n,i,a,p=r,f=s;if(typeof e=="string")if(n=e,typeof t=="function")i=t,p!==void 0&&(a=se.infer(p));else if(t===void 0&&p!==void 0)a=se.infer(p);else if(Ie(t))a=t;else if(pt(t))a=t;else if(t!==void 0)p=t,f=p,a=se.infer(p);else throw new Error("Type(description) requires a predicate, schema, or example");else Ie(e),a=e,n=lt(a);let l;if(a){let o=a?.schema??a;o&&typeof o=="object"&&Array.isArray(o.examples)&&(l=o.examples)}return p===void 0&&l&&l.length>0&&(p=l[0]),{description:n,check:o=>i?i(o):a?de(o,a):!1,schema:a,predicate:i,example:p,examples:l,default:f,toJSONSchema(){if(a){let o=a?.schema??a;if(o&&typeof o=="object"&&"type"in o)return o}return p!==void 0?V(p):{description:n}},strip(o){return a?ct(o,a):o},__runtimeType:!0}}function lt(e){let t=e?.schema??e;if(t&&typeof t=="object"&&"type"in t){let r=t;switch(r.type){case"string":return r.format?`string (${r.format})`:r.pattern?`string matching ${r.pattern}`:r.minLength!==void 0&&r.maxLength!==void 0?`string (${r.minLength}-${r.maxLength} chars)`:"string";case"number":case"integer":return r.minimum!==void 0&&r.maximum!==void 0?`${r.type} (${r.minimum}-${r.maximum})`:r.minimum!==void 0?`${r.type} >= ${r.minimum}`:r.maximum!==void 0?`${r.type} <= ${r.maximum}`:r.type;case"boolean":return"boolean";case"array":return"array";case"object":return"object";case"null":return"null"}}return"value"}var me=I("string",e=>typeof e=="string"),ye=I("number",e=>typeof e=="number"),ge=I("boolean",e=>typeof e=="boolean"),Te=I("integer",e=>typeof e=="number"&&Number.isInteger(e)),xe=I("positive integer",e=>typeof e=="number"&&Number.isInteger(e)&&e>0),he=I("non-empty string",e=>typeof e=="string"&&e.length>0),Se=I("email address",e=>typeof e=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)),De=e=>{try{return new URL(e),!0}catch{return!1}},be=I("URL",e=>typeof e=="string"&&De(e)),ke=I("UUID",e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)),Le=e=>{let t=new Date(e);return!isNaN(t.getTime())&&e.includes("T")},_e=e=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let t=new Date(e+"T00:00:00Z");return!isNaN(t.getTime())},Je=I("ISO 8601 timestamp",e=>typeof e=="string"&&Le(e)),Ue=I("date (YYYY-MM-DD)",e=>typeof e=="string"&&_e(e));function Ee(e){return I(`${e.description} or null`,t=>t===null||e.check(t))}function we(e){return I(`${e.description} (optional)`,t=>t==null||e.check(t))}function je(e,t,...r){if(typeof e=="string"&&Array.isArray(t)){let i=e,a=t,p=new Set(a);return{description:i,check:l=>p.has(l),toJSONSchema:()=>({enum:a}),strip:l=>l,__runtimeType:!0,values:a}}let s=[];q(e)&&s.push(e),q(t)&&s.push(t),s.push(...r);let n=s.map(i=>i.description).join(" | ");return I(n,i=>s.some(a=>a.check(i)))}function $e(e){return I(`array of ${e.description}`,t=>Array.isArray(t)&&t.every(r=>e.check(r)))}function ft(e){if(q(e))return r=>e.check(r);if(e&&typeof e=="object"&&"schema"in e)return r=>de(r,e);let t=se.infer(e);return r=>de(r,t)}function ee(e,t,r){let s=[],n=[];for(let a of e)typeof a=="string"?(s.push(a),n.push(void 0)):(s.push(a[0]),n.push(a[1]));let i=(...a)=>{let p=s.map((l,c)=>{let o=c<a.length?a[c]:n[c];return o===void 0?()=>!0:ft(o)}),f=r;return s.forEach((l,c)=>{let o=c<a.length?a[c]:n[c],y="any";q(o)?y=o.description:o!==void 0&&(y=typeof o=="string"?"string":JSON.stringify(o)),f=f.replace(new RegExp(`\\b${l}\\b`,"g"),y)}),I(f,l=>t(l,...p))};return i.params=s,i.description=r,i}var Ne=ee(["T","U"],(e,t,r)=>Array.isArray(e)&&e.length===2&&t(e[0])&&r(e[1]),"Pair<T, U>"),Pe=ee(["V"],(e,t)=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).every(t),"Record<string, V>");function Re(e,t){let r=Object.values(t),s=new Set(r),n=Object.keys(t),i={};for(let[p,f]of Object.entries(t))i[f]=p;return{description:e,check:p=>s.has(p),toJSONSchema:()=>({enum:r}),strip:p=>p,__runtimeType:!0,members:t,names:i,values:r,keys:n}}function dt(e){if(e===null)return"null";if(e===void 0)return"undefined";switch(typeof e){case"string":return"string";case"boolean":return"boolean";case"number":return Number.isInteger(e)?"integer":"number";case"object":return Array.isArray(e)?"array":"object";default:return null}}function ie(e,t,r){if(Array.isArray(t)&&r){let s=t,n=[],i=[];for(let p of s)Array.isArray(p)?(n.push(p[0]),i.push(p[1])):(n.push(p),i.push(void 0));let a=((...p)=>{let f=n.map((c,o)=>o<p.length?p[o]:i[o]),l=r(...f);return ie(e,l)});return Object.defineProperties(a,{typeParamNames:{value:n,enumerable:!0},description:{value:e,enumerable:!0},__runtimeType:{value:!0,enumerable:!0}}),a}return mt(e,t)}function mt(e,t){let r={},s,n="assertReturns";if(typeof t=="function"){let a=t.__tjs;if(a){if(a.params)for(let[p,f]of Object.entries(a.params))r[p]=f?.example??null;a.returns&&(s=a.returns?.example??null),a.safeReturn?n="checkedReturns":a.unsafe?n="assertReturns":n="returns"}}else r=t.params??{},s=t.returns,n=t.returnContract??"assertReturns";return{description:e,params:r,returns:s,returnContract:n,toJSONSchema:()=>({description:e,type:"function"}),strip:a=>a,check:a=>{if(typeof a!="function")return!1;let p=Object.keys(r).length;if(p>0){let l=a.__tjs;if(l?.params){if(Object.keys(l.params).length!==p)return!1;let o=Object.keys(r),y=Object.keys(l.params);for(let d=0;d<o.length;d++){let k=l.params[y[d]],m=r[o[d]];if(k?.type?.kind&&m!==void 0){let h=dt(m);if(h&&k.type.kind!==h&&k.type.kind!=="any")return!1}}}}return!0},__runtimeType:!0}}var gt=Be(),ze=gt.version,te=Symbol.for("tjs.equals");function ue(e){let[t=0,r=0,s=0]=e.split(".").map(Number);return{major:t,minor:r,patch:s}}function Fe(e,t){let r=ue(e),s=ue(t);return r.major!==s.major?r.major<s.major?-1:1:r.minor!==s.minor?r.minor<s.minor?-1:1:r.patch!==s.patch?r.patch<s.patch?-1:1:0}function Ge(e,t){let r=ue(e),s=ue(t);return r.major===s.major}var Z=class e extends Error{path;expected;actual;callStack;constructor(t,r,s,n,i){super(t),this.name="MonadicError",this.path=r,this.expected=s,this.actual=n,this.callStack=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function Tt(e,t,r){let s=r===null?"null":typeof r,n=C.callStacks||C.debug?ve():void 0,i=new Z(`Expected ${t} for '${e}', got ${s}`,e,t,s,n);if(C.trackErrors!==!1){let a=C.maxErrors??ce;He[H]=i,H=(H+1)%a,F<a&&F++,pe++}if(C.logTypeErrors&&console.error(`[TJS TypeError] ${i.message}`),C.throwTypeErrors)throw i;return i}function Ae(e){return e instanceof Error&&e.name==="MonadicError"&&"path"in e}var Me={debug:!1,safety:"inputs",requireReturnTypes:!1,callStacks:!1,maxStackSize:64,trackErrors:!0,maxErrors:64},C={...Me},re=64,Ve=new Array(re).fill(""),z=0,_=0,ce=64,He=new Array(ce).fill(null),H=0,F=0,pe=0,X=0;function xt(){X++}function ht(){X>0&&X--}function St(){return X>0}function bt(e){C={...C,...e}}function kt(){return{...C}}function We(e){if((C.callStacks||C.debug)&&e){let t=C.maxStackSize??re;Ve[z]=e,z=(z+1)%t,_<t&&_++}}function ae(){if((C.callStacks||C.debug)&&_>0){let e=C.maxStackSize??re;z=(z-1+e)%e,_--}}function ve(){if(_===0)return[];let e=C.maxStackSize??re,t=[],r=(z-_+e)%e;for(let s=0;s<_;s++)t.push(Ve[(r+s)%e]);return t}function Ye(){if(C.trackErrors===!1||F===0)return[];let e=C.maxErrors??ce,t=[],r=(H-F+e)%e;for(let s=0;s<F;s++)t.push(He[(r+s)%e]);return t}function Et(){let e=Ye();return H=0,F=0,pe=0,e}function wt(){return pe}function jt(){C={...Me},z=0,_=0,H=0,F=0,pe=0,X=0}function W(e,t){if(e!==null&&typeof e=="object"&&typeof e[te]=="function")return e[te](t);if(t!==null&&typeof t=="object"&&typeof t[te]=="function")return t[te](e);if(e!==null&&typeof e=="object"&&typeof e.Equals=="function")return e.Equals(t);if(t!==null&&typeof t=="object"&&typeof t.Equals=="function")return t.Equals(e);if((e instanceof String||e instanceof Number||e instanceof Boolean)&&(e=e.valueOf()),(t instanceof String||t instanceof Number||t instanceof Boolean)&&(t=t.valueOf()),e===t||typeof e=="number"&&typeof t=="number"&&isNaN(e)&&isNaN(t)||e==null&&t==null)return!0;if(e==null||t===null||t===void 0||typeof e!=typeof t||typeof e!="object")return!1;if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,i]of e)if(!t.has(n)||!W(i,t.get(n)))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp&&t instanceof RegExp)return e.toString()===t.toString();if(Array.isArray(e)&&Array.isArray(t))return e.length!==t.length?!1:e.every((n,i)=>W(n,t[i]));if(Array.isArray(e)!==Array.isArray(t))return!1;let r=Object.keys(e),s=Object.keys(t);return r.length!==s.length?!1:r.every(n=>W(e[n],t[n]))}function Ze(e,t){return!W(e,t)}function Xe(e){return e===null?"null":typeof e}function Oe(e,t){return(e instanceof String||e instanceof Number||e instanceof Boolean)&&(e=e.valueOf()),(t instanceof String||t instanceof Number||t instanceof Boolean)&&(t=t.valueOf()),!!(e===t||typeof e=="number"&&typeof t=="number"&&isNaN(e)&&isNaN(t)||e==null&&t==null)}function Qe(e,t){return!Oe(e,t)}function U(e){return e!==null&&typeof e=="object"&&e.$error===!0}function J(e,t){let r={$error:!0,message:e,...t};if((C.callStacks||C.debug)&&_>0){let s=ve(),n=t?.path?[...s,t.path]:s;r.stack=n}return r}function Ce(e,t){if(e.length===0)return J("Unknown error");if(e.length===1)return e[0];let r=e.map(n=>{if(n.path){let i=n.path.split(".");return i[i.length-1]}return"unknown"}).join(", "),s=`Multiple parameter errors in ${t||"function"}: ${r}`;return J(s,{path:t,errors:e})}function ne(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";let t=typeof e;if(t!=="object")return t;let r=e.constructor?.name;return r&&r!=="Object"?r:"object"}function et(e,t){if(e==null||typeof e!="object"&&typeof e!="function")return!1;let r=e;for(;r!==null;){if(r.constructor?.name===t)return!0;r=Object.getPrototypeOf(r)}return!1}function Y(e,t,r){if(U(e))return e;if(typeof t=="object"&&t!==null&&"check"in t)return t.check(e)?null:J(`Expected ${t.description} but got ${ne(e)}`,{path:r,expected:t.description,actual:ne(e)});let s=ne(e);return t==="any"||t===s||t==="number"&&s==="number"||t==="integer"&&s==="number"&&Number.isInteger(e)||t==="non-negative-integer"&&s==="number"&&Number.isInteger(e)&&e>=0||t==="object"&&s==="object"?null:J(`Expected ${t} but got ${s}`,{path:r,expected:t,actual:s})}function tt(e,t,r){for(let[s,n]of Object.entries(t.params)){let i=e[s];if(U(i))return i;if(n.required&&i===void 0){let p=typeof n.type=="string"?n.type:n.type.description;return J(`Missing required parameter '${s}'`,{path:r?`${r}.${s}`:s,expected:p,actual:"undefined",loc:n.loc})}if(i===void 0)continue;let a=Y(i,n.type,r?`${r}.${s}`:s);if(a)return n.loc&&(a.loc=n.loc),a}return null}function nt(e,t){if(e.__tjs=t,e.__tjs.schema=()=>fe(t),!(!t.polymorphic&&(t.safe||t.safeReturn||C.safety!=="none"&&!t.unsafe||t.returns&&C.safety==="all"&&!t.unsafeReturn)))return e;let s=!!t.returns,n=!!t.unsafe,i=!!t.safe,a=!!t.unsafeReturn,p=!!t.safeReturn,f=t.returns?.defaults,l=Object.entries(t.params),c=l.length,o=e.name||t.name||"anonymous",y=function(...d){if(X>0)return e.apply(this,d);let k=i||!n&&C.safety!=="none",m=s&&(p||!a&&C.safety==="all");if(!k&&!m)return e.apply(this,d);if(d.length>0&&U(d[0]))return d[0];if(k){let w=d.length===1&&typeof d[0]=="object"&&d[0]!==null&&!Array.isArray(d[0]),j=[];if(w){let $=d[0];for(let N=0;N<c;N++){let[E,v]=l[N],A=$[E];if(U(A)){j.push(A);continue}if(v.required&&A===void 0){j.push(J(`Missing required parameter '${E}'`,{path:`${o}.${E}`,expected:typeof v.type=="string"?v.type:v.type?.description||"value",actual:"undefined",loc:v.loc}));continue}if(A!==void 0){let D=Y(A,v.type,`${o}.${E}`);D&&(v.loc&&(D.loc=v.loc),j.push(D))}}}else for(let $=0;$<c;$++){let[N,E]=l[$],v=d[$];if(U(v)){j.push(v);continue}if(E.required&&v===void 0){j.push(J(`Missing required parameter '${N}'`,{path:`${o}.${N}`,expected:typeof E.type=="string"?E.type:E.type?.description||"value",actual:"undefined",loc:E.loc}));continue}if(v!==void 0){let A=Y(v,E.type,`${o}.${N}`);A&&(E.loc&&(A.loc=E.loc),j.push(A))}}if(j.length>0)return Ce(j,o)}let h=C.callStacks||C.debug;h&&We(o);try{let w=e.apply(this,d);if(m&&t.returns&&!U(w)){let j=f&&typeof w=="object"&&w!==null?Object.assign({},f,w):w,$=Y(j,t.returns.type,`${o}()`);if($)return h&&ae(),$}return h&&ae(),w}catch(w){return h&&ae(),J(w.message||String(w),{path:o,cause:w})}};return Object.defineProperty(y,"name",{value:e.name}),y.__tjs=t,y.__tjs.schema=()=>fe(t),y}function rt(e){let t=new Proxy(e,{construct(r,s,n){return Reflect.construct(r,s,n)},apply(r,s,n){return Reflect.construct(r,n)}});Object.defineProperty(t,"name",{value:e.name});for(let r of Object.getOwnPropertyNames(e))r!=="length"&&r!=="name"&&r!=="prototype"&&Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(e,r));return t}function st(){let e={...C},t=e.maxStackSize??re,r=new Array(t).fill(""),s=0,n=0,i=e.maxErrors??ce,a=new Array(i).fill(null),p=0,f=0,l=0,c=0;function o(g){e={...e,...g}}function y(){return{...e}}function d(g){(e.callStacks||e.debug)&&g&&(r[s]=g,s=(s+1)%t,n<t&&n++)}function k(){(e.callStacks||e.debug)&&n>0&&(s=(s-1+t)%t,n--)}function m(){if(n===0)return[];let g=[],S=(s-n+t)%t;for(let R=0;R<n;R++)g.push(r[(S+R)%t]);return g}function h(){e={...Me},s=0,n=0,p=0,f=0,l=0,c=0}function w(){c++}function j(){c>0&&c--}function $(){return c>0}let N=new Map;function E(g,S,R){N.has(g)||N.set(g,new Map),N.get(g).set(S,R)}function v(g,S){let R=typeof g,O;if(g==null)return;if(R==="string")O="String";else if(R==="number")O="Number";else if(R==="boolean")O="Boolean";else if(Array.isArray(g))O="Array";else if(R==="object")O=g.constructor?.name||"Object";else return;let L=O;for(;L;){let Ke=N.get(L);if(Ke?.has(S))return Ke.get(S);if(R==="object"&&!Array.isArray(g)){if(L=Object.getPrototypeOf(L===O?g:Object.getPrototypeOf(g))?.constructor?.name,L==="Object"||L===O)break}else break}let B=N.get("Object");if(B?.has(S))return B.get(S)}function A(g,S,R){let O=R===null?"null":typeof R,L=e.callStacks||e.debug?m():void 0,B=new Z(`Expected ${S} for '${g}', got ${O}`,g,S,O,L);if(e.trackErrors!==!1&&(a[p]=B,p=(p+1)%i,f<i&&f++,l++),e.logTypeErrors&&console.error(`[TJS TypeError] ${B.message}`),e.throwTypeErrors)throw B;return B}function D(){if(e.trackErrors===!1||f===0)return[];let g=[],S=(p-f+i)%i;for(let R=0;R<f;R++)g.push(a[(S+R)%i]);return g}function T(){let g=D();return p=0,f=0,l=0,g}function b(){return l}function x(g,S){let R={$error:!0,message:g,...S};if((e.callStacks||e.debug)&&n>0){let O=S?.path?[...m(),S.path]:m();R.stack=O}return R}function P(g,S){return g==null?A(`bang.${S}`,"non-null",g):Ae(g)?g:g[S]}return{version:ze,MonadicError:Z,typeError:A,isMonadicError:Ae,bang:P,isError:U,error:x,composeErrors:Ce,typeOf:ne,isNativeType:et,checkType:Y,validateArgs:tt,wrap:nt,wrapClass:rt,compareVersions:Fe,versionsCompatible:Ge,createRuntime:st,configure:o,getConfig:y,pushStack:d,popStack:k,getStack:m,errors:D,clearErrors:T,getErrorCount:b,resetRuntime:h,enterUnsafe:w,exitUnsafe:j,isUnsafeMode:$,validate:qe,infer:oe.infer.bind(oe),Type:I,isRuntimeType:q,Union:je,Generic:ee,Enum:Re,FunctionPredicate:ie,Nullable:Ee,Optional:we,TArray:$e,TString:me,TNumber:ye,TBoolean:ge,TInteger:Te,TPositiveInt:xe,TNonEmptyString:he,TEmail:Se,TUrl:be,TUuid:ke,TPair:Ne,TRecord:Pe,Is:W,IsNot:Ze,Eq:Oe,NotEq:Qe,TypeOf:Xe,tjsEquals:te,registerExtension:E,resolveExtension:v}}var en={version:ze,MonadicError:Z,typeError:Tt,isMonadicError:Ae,isError:U,error:J,composeErrors:Ce,typeOf:ne,isNativeType:et,checkType:Y,validateArgs:tt,wrap:nt,wrapClass:rt,compareVersions:Fe,versionsCompatible:Ge,configure:bt,getConfig:kt,pushStack:We,popStack:ae,getStack:ve,errors:Ye,clearErrors:Et,getErrorCount:wt,resetRuntime:jt,enterUnsafe:xt,exitUnsafe:ht,isUnsafeMode:St,createRuntime:st,validate:qe,infer:oe.infer.bind(oe),Type:I,isRuntimeType:q,Union:je,Generic:ee,Enum:Re,FunctionPredicate:ie,Nullable:Ee,Optional:we,TArray:$e,TString:me,TNumber:ye,TBoolean:ge,TInteger:Te,TPositiveInt:xe,TNonEmptyString:he,TEmail:Se,TUrl:be,TUuid:ke,Timestamp:Je,LegalDate:Ue,TPair:Ne,TRecord:Pe,Is:W,IsNot:Ze,Eq:Oe,NotEq:Qe,TypeOf:Xe};function it(e){return`
2
+ // TJS: callable without new
3
+ ${e} = new Proxy(${e}, { apply(t, _, a) { return Reflect.construct(t, a) } });
4
+ `.trim()}var $t=20,ot=new Set(["Event","CustomEvent","MouseEvent","KeyboardEvent","PointerEvent","TouchEvent","FocusEvent","InputEvent","CompositionEvent","WheelEvent","DragEvent","AnimationEvent","TransitionEvent","ClipboardEvent","UIEvent","ProgressEvent","ErrorEvent","MessageEvent","PopStateEvent","HashChangeEvent","PageTransitionEvent","StorageEvent","BeforeUnloadEvent","SubmitEvent","EventTarget","EventListener","Node","Element","HTMLElement","SVGElement","Document","DocumentFragment","ShadowRoot","Text","Comment","Attr","HTMLInputElement","HTMLTextAreaElement","HTMLSelectElement","HTMLButtonElement","HTMLFormElement","HTMLAnchorElement","HTMLImageElement","HTMLVideoElement","HTMLAudioElement","HTMLCanvasElement","HTMLDivElement","HTMLSpanElement","HTMLParagraphElement","HTMLTableElement","HTMLTemplateElement","HTMLSlotElement","HTMLDialogElement","HTMLDetailsElement","HTMLLabelElement","HTMLOptionElement","HTMLIFrameElement","HTMLScriptElement","HTMLStyleElement","HTMLLinkElement","HTMLMetaElement","HTMLHeadElement","HTMLBodyElement","HTMLMediaElement","SVGSVGElement","SVGPathElement","SVGGElement","SVGCircleElement","SVGRectElement","SVGTextElement","SVGLineElement","SVGPolygonElement","NodeList","HTMLCollection","NamedNodeMap","DOMTokenList","DOMStringMap","CSSStyleDeclaration","DOMRect","DOMRectReadOnly","DOMPoint","DOMMatrix","Range","Selection","StaticRange","MutationObserver","MutationRecord","IntersectionObserver","IntersectionObserverEntry","ResizeObserver","ResizeObserverEntry","PerformanceObserver","PerformanceEntry","Window","Location","History","Navigator","Screen","Storage","CanvasRenderingContext2D","WebGLRenderingContext","WebGL2RenderingContext","OffscreenCanvas","ImageData","ImageBitmap","MediaStream","MediaRecorder","AudioContext","AudioNode","AudioBuffer","Worker","SharedWorker","ServiceWorker","ServiceWorkerRegistration","BroadcastChannel","MessageChannel","MessagePort","WebSocket","XMLHttpRequest","FileReader","FileList","DataTransfer","Crypto","SubtleCrypto","CryptoKey","Geolocation","Notification","PermissionStatus","MediaQueryList","TreeWalker","NodeIterator","ClipboardItem"]);function M(e,t,r,s){if(!e)return"undefined";switch(e.kind){case u.SyntaxKind.StringKeyword:return"''";case u.SyntaxKind.NumberKeyword:return"0.0";case u.SyntaxKind.BooleanKeyword:return"false";case u.SyntaxKind.NullKeyword:return"null";case u.SyntaxKind.UndefinedKeyword:return"undefined";case u.SyntaxKind.VoidKeyword:return"undefined";case u.SyntaxKind.AnyKeyword:return"any";case u.SyntaxKind.UnknownKeyword:return"any";case u.SyntaxKind.NeverKeyword:return"null";case u.SyntaxKind.SymbolKeyword:return"Symbol('example')";case u.SyntaxKind.BigIntKeyword:return"0n";case u.SyntaxKind.ObjectKeyword:return"{}";case u.SyntaxKind.ArrayType:{let i=M(e.elementType,t);return i==="any"&&(i="null"),`[${i}]`}case u.SyntaxKind.TypeReference:{let n=e,i=n.typeName.getText();if(i==="Array"&&n.typeArguments?.length)return`[${M(n.typeArguments[0],t,r,s)}]`;if(i==="Promise"||i==="Generator"||i==="AsyncGenerator"||i==="IterableIterator"||i==="AsyncIterableIterator")return n.typeArguments?.length?M(n.typeArguments[0],t,r,s):"undefined";if(i==="Record")return"{}";let a={Map:"new Map()",Set:"new Set()",WeakMap:"new WeakMap()",WeakSet:"new WeakSet()",WeakRef:"new WeakRef({})",Error:"new Error('example')",TypeError:"new TypeError('example')",RangeError:"new RangeError('example')",SyntaxError:"new SyntaxError('example')",ReferenceError:"new ReferenceError('example')",URIError:"new URIError('example')",EvalError:"new EvalError('example')",Date:"new Date()",RegExp:"/example/",ArrayBuffer:"new ArrayBuffer(0)",SharedArrayBuffer:"new SharedArrayBuffer(0)",DataView:"new DataView(new ArrayBuffer(0))",Float32Array:"new Float32Array(0)",Float64Array:"new Float64Array(0)",Int8Array:"new Int8Array(0)",Int16Array:"new Int16Array(0)",Int32Array:"new Int32Array(0)",Uint8Array:"new Uint8Array(0)",Uint16Array:"new Uint16Array(0)",Uint32Array:"new Uint32Array(0)",Uint8ClampedArray:"new Uint8ClampedArray(0)",BigInt64Array:"new BigInt64Array(0)",BigUint64Array:"new BigUint64Array(0)",URL:"new URL('https://example.com')",URLSearchParams:"new URLSearchParams()",Headers:"new Headers()",FormData:"new FormData()",Blob:"new Blob()",File:"new File([], 'example')",Response:"new Response()",Request:"new Request('https://example.com')",AbortController:"new AbortController()",AbortSignal:"AbortSignal.abort()",ReadableStream:"new ReadableStream()",WritableStream:"new WritableStream()",TransformStream:"new TransformStream()",TextEncoder:"new TextEncoder()",TextDecoder:"new TextDecoder()",Promise:"Promise.resolve(null)"};if(i in a)return a[i];if(s?.typeAliases?.has(i)){let p=s.visited??new Set;if(p.has(i))return r?.push(`Circular type reference '${i}' - using 'any'`),"any";p.add(i);let f=s.typeAliases.get(i);return M(f,t,r,{...s,visited:p})}if(s?.interfaces?.has(i)){let p=s.visited??new Set;if(p.has(i))return r?.push(`Circular type reference '${i}' - using 'any'`),"any";p.add(i);let f=s.interfaces.get(i),l=[];for(let c of f.members)if(u.isPropertySignature(c)&&c.name){let o=c.name.getText(s.sourceFile),y=M(c.type,t,r,{...s,visited:p});l.push(`${o}: ${y}`)}return`{ ${l.join(", ")} }`}if(s?.typeParams?.has(i)){let p=s.typeParams.get(i);if(p.constraint)return M(p.constraint,t,r,s);if(p.default)return M(p.default,t,r,s)}return ot.has(i)?"{}":/^[A-Z]$/.test(i)||["T","K","V","U","TKey","TValue","TItem","TResult"].includes(i)?(r?.push(`Generic type parameter '${i}' converted to 'any' - consider specializing`),"any"):(r?.push(`Unknown type '${i}' converted to 'any' - may need manual review`),"any")}case u.SyntaxKind.TypeLiteral:{let n=e,i=[];for(let a of n.members)if(u.isPropertySignature(a)&&a.name){let p=a.name.getText(),f=M(a.type,t);f==="any"&&(f="null"),i.push(`${p}: ${f}`)}return`{ ${i.join(", ")} }`}case u.SyntaxKind.UnionType:{let n=e,i=o=>o.kind===u.SyntaxKind.NullKeyword||u.isLiteralTypeNode(o)&&o.literal.kind===u.SyntaxKind.NullKeyword,a=o=>o.kind===u.SyntaxKind.UndefinedKeyword||u.isLiteralTypeNode(o)&&o.literal.kind===u.SyntaxKind.UndefinedKeyword,p=n.types.filter(o=>!i(o)&&!a(o)),f=n.types.some(i),l=n.types.some(a);if(p.length===0)return f?"null":"undefined";if(p.length===1&&(f||l)){let o=M(p[0],t,r,s);if(o==="any")return"any";if(f)return`${o} | null`;if(l)return`${o} | undefined`}let c=n.types.map(o=>M(o,t,r,s)).filter((o,y,d)=>d.indexOf(o)===y);return c.some(o=>o==="any")?"any":c.length===1?c[0]:c.length>0?c.some(y=>/[()]/.test(y)||y.startsWith("new "))?"any":c.join(" | "):"undefined"}case u.SyntaxKind.LiteralType:{let n=e;return u.isStringLiteral(n.literal)?`'${n.literal.text}'`:u.isNumericLiteral(n.literal)?n.literal.text:n.literal.kind===u.SyntaxKind.TrueKeyword?"true":n.literal.kind===u.SyntaxKind.FalseKeyword?"false":n.literal.kind===u.SyntaxKind.NullKeyword?"null":"undefined"}case u.SyntaxKind.ParenthesizedType:return M(e.type,t);case u.SyntaxKind.FunctionType:{let n=e,i=[];for(let f of n.parameters){let l=f.name?.getText()||"_";if(l==="this")continue;let c=M(f.type,t,r,s);c==="any"&&(c="null"),i.push(`${l}: ${c}`)}let a=M(n.type,t,r,s);a==="any"&&(a="null");let p=[];return i.length>0&&p.push(`params: { ${i.join(", ")} }`),a!=="undefined"&&p.push(`returns: ${a}`),`FunctionPredicate('function', { ${p.join(", ")} })`}case u.SyntaxKind.TupleType:return`[${e.elements.map(a=>{let p=u.isNamedTupleMember(a)?M(a.type,t):M(a,t);return p==="any"?"null":p}).join(", ")}]`;default:return"undefined"}}function K(e,t){if(!e)return{kind:"any"};let r=t?.depth??0;if(r>$t)return{kind:"any"};switch(t=t?{...t,depth:r+1}:void 0,e.kind){case u.SyntaxKind.StringKeyword:return{kind:"string"};case u.SyntaxKind.NumberKeyword:return{kind:"number"};case u.SyntaxKind.BooleanKeyword:return{kind:"boolean"};case u.SyntaxKind.NullKeyword:return{kind:"null"};case u.SyntaxKind.UndefinedKeyword:case u.SyntaxKind.VoidKeyword:return{kind:"undefined"};case u.SyntaxKind.ArrayType:return{kind:"array",items:K(e.elementType,t)};case u.SyntaxKind.TypeLiteral:{let s=e,n={};for(let i of s.members)if(u.isPropertySignature(i)&&i.name){let a=i.name.getText();n[a]=K(i.type,t)}return{kind:"object",shape:n}}case u.SyntaxKind.UnionType:{let s=e,n=s.types.filter(a=>a.kind!==u.SyntaxKind.NullKeyword&&a.kind!==u.SyntaxKind.UndefinedKeyword),i=s.types.some(a=>a.kind===u.SyntaxKind.NullKeyword);return n.length===1&&i?{...K(n[0],t),nullable:!0}:{kind:"union",members:s.types.map(a=>K(a,t))}}case u.SyntaxKind.IntersectionType:{let s=e,n={};for(let i of s.types){let a=K(i,t);a.kind==="object"&&a.shape&&Object.assign(n,a.shape)}return Object.keys(n).length>0?{kind:"object",shape:n}:{kind:"any"}}case u.SyntaxKind.TupleType:{let s=e,n=[];for(let i of s.elements)u.isNamedTupleMember(i)?n.push(K(i.type,t)):n.push(K(i,t));return{kind:"tuple",elements:n}}case u.SyntaxKind.TypeReference:{let s=e,n=s.typeName.getText();if(n==="Array"&&s.typeArguments?.length)return{kind:"array",items:K(s.typeArguments[0],t)};if(n==="Promise"&&s.typeArguments?.length||(n==="Generator"||n==="AsyncGenerator"||n==="IterableIterator"||n==="AsyncIterableIterator")&&s.typeArguments?.length)return K(s.typeArguments[0],t);if(s.typeArguments?.length){let i=K(s.typeArguments[0],t);if(n==="Partial"||n==="Required"||n==="Readonly")return i;if(n==="Record"&&s.typeArguments.length>=2)return{kind:"object",shape:{"[key]":K(s.typeArguments[1],t)}};if(n==="Pick"||n==="Omit")return i;if(n==="NonNullable")return i.nullable?{...i,nullable:!1}:i;if(["ReturnType","Parameters","ConstructorParameters"].includes(n))return{kind:"any"}}if(t?.typeAliases?.has(n)){if(t.resolvedCache?.has(n))return t.resolvedCache.get(n);let i=t.visited??new Set;if(i.has(n))return{kind:"any"};i.add(n);let a=t.typeAliases.get(n),p=K(a,{...t,visited:i});return t.resolvedCache?.set(n,p),p}if(t?.interfaces?.has(n)){if(t.resolvedCache?.has(n))return t.resolvedCache.get(n);let i=t.visited??new Set;if(i.has(n))return{kind:"any"};i.add(n);let a=t.interfaces.get(n),p={};if(a.heritageClauses){for(let l of a.heritageClauses)if(l.token===u.SyntaxKind.ExtendsKeyword)for(let c of l.types){let o=c.expression.getText(t.sourceFile);if(t.interfaces?.has(o)&&!i.has(o)){let y={kind:u.SyntaxKind.TypeReference,typeName:{getText:()=>o}},d=K(y,{...t,visited:i});d.kind==="object"&&d.shape&&Object.assign(p,d.shape)}}}for(let l of a.members)if(u.isPropertySignature(l)&&l.name){let c=l.name.getText(t.sourceFile);p[c]=K(l.type,{...t,visited:i})}let f={kind:"object",shape:p};return t.resolvedCache?.set(n,f),f}if(t?.typeParams?.has(n)){let i=t.typeParams.get(n);if(i.constraint)return K(i.constraint,t);if(i.default)return K(i.default,t)}return ot.has(n)?{kind:"object"}:{kind:"any"}}default:return{kind:"any"}}}function Nt(e,t){if(!e.typeParameters||e.typeParameters.length===0)return;let r={};for(let s of e.typeParameters){let n=s.name.getText(),i={};if(s.constraint){let a=M(s.constraint,void 0,t);if(a.startsWith("{"))try{i.constraint=a}catch{i.constraint=a}else i.constraint=a}if(s.default){let a=M(s.default,void 0,t);i.default=a}r[n]=i}return Object.keys(r).length>0?r:void 0}function Pt(e,t,r,s){let n=e.name.getText(t);if(e.typeParameters&&e.typeParameters.length>0)return Rt(e,t,r,s);let i=s?.find(l=>l.kind==="example"),a=s?.find(l=>l.kind==="predicate"),p;if(i?.text)p=i.text;else{let l=[];for(let c of e.members)if(u.isPropertySignature(c)&&c.name){let o=c.name.getText(t),y=M(c.type,void 0,r);y==="any"&&(y="null"),l.push(`${o}: ${y}`)}if(l.length===0&&!a)return`Type ${n} {}`;p=l.length>0?`{ ${l.join(", ")} }`:"{}"}let f=[`example: ${p}`];return a?.text&&f.push(a.text),`Type ${n} {
5
+ ${f.join(`
6
+ `)}
7
+ }`}function Rt(e,t,r,s){let n=e.name.getText(t),i=[];for(let c of e.typeParameters||[]){let o=c.name.getText(t);if(c.default){let y=M(c.default,void 0,r);i.push(`${o} = ${y}`)}else i.push(o)}let a=s?.find(c=>c.kind==="predicate"),p=s?.find(c=>c.kind==="declaration"),f;if(a?.text)f=a.text;else{let c=(e.typeParameters||[]).map(d=>d.name.getText(t)),o=["typeof x === 'object'","x !== null"];for(let d of e.members)if(u.isPropertySignature(d)&&d.name){let k=d.name.getText(t),m=k.startsWith("[")&&k.endsWith("]"),h=m?k.slice(1,-1):null;if(m?o.push(`${h} in x`):o.push(`'${k}' in x`),d.type&&u.isTypeReferenceNode(d.type)){let w=d.type.typeName.getText(t);c.includes(w)&&(m?o.push(`${w}(x[${h}])`):o.push(`${w}(x.${k})`))}}f=`predicate(${["x",...c].join(", ")}) { return ${o.join(" && ")} }`}let l=[`description: '${n}'`,f];if(p?.text)l.push(`declaration ${p.text}`);else{let c=[];for(let o of e.members)if(u.isPropertySignature(o)&&o.name){let y=o.name.getText(t),d=o.questionToken?"?":"",k=o.type?o.type.getText(t):"any";c.push(`${y}${d}: ${k}`)}else if(u.isMethodSignature(o)&&o.name){let y=o.getText(t).trim();c.push(y.replace(/;$/,""))}c.length>0&&l.push(`declaration {
8
+ ${c.join(`
9
+ `)}
10
+ }`)}return`Generic ${n}<${i.join(", ")}> {
11
+ ${l.join(`
12
+ `)}
13
+ }`}function At(e,t){if(!u.isUnionTypeNode(e))return null;let r=[];for(let s of e.types)if(u.isLiteralTypeNode(s))if(u.isStringLiteral(s.literal))r.push(`'${s.literal.text}'`);else if(u.isNumericLiteral(s.literal))r.push(s.literal.text);else if(s.literal.kind===u.SyntaxKind.TrueKeyword)r.push("true");else if(s.literal.kind===u.SyntaxKind.FalseKeyword)r.push("false");else if(s.literal.kind===u.SyntaxKind.NullKeyword)r.push("null");else return null;else if(s.kind===u.SyntaxKind.NullKeyword)r.push("null");else if(s.kind===u.SyntaxKind.UndefinedKeyword)r.push("undefined");else return null;return r.length>0?r:null}function Mt(e,t,r){let s=e.name.getText(t),n=[],i=0;for(let a of e.members){let p=a.name.getText(t);if(a.initializer)if(u.isStringLiteral(a.initializer))n.push(` ${p} = '${a.initializer.text}'`);else if(u.isNumericLiteral(a.initializer)){let f=parseInt(a.initializer.text,10);n.push(` ${p} = ${f}`),i=f+1}else if(u.isPrefixUnaryExpression(a.initializer)&&a.initializer.operator===u.SyntaxKind.MinusToken){let f=a.initializer.operand;if(u.isNumericLiteral(f)){let l=-parseInt(f.text,10);n.push(` ${p} = ${l}`),i=l+1}}else n.push(` ${p} = ${a.initializer.getText(t)}`);else n.push(` ${p} = ${i}`),i++}return`Enum ${s} '${s}' {
14
+ ${n.join(`
15
+ `)}
16
+ }`}function vt(e,t,r,s){let n=e.name.getText(t);if(e.typeParameters&&e.typeParameters.length>0)return e.type.kind===u.SyntaxKind.FunctionType?Ot(e,t,r):Ct(e,t,r,s);let i=At(e.type,t);if(i)return`Union ${n} '${n}' ${i.join(" | ")}`;if(e.type.kind===u.SyntaxKind.FunctionType){let p=e.type,f=[];for(let o of p.parameters){let y=o.name?.getText(t)||"_";if(y==="this")continue;let d=M(o.type,void 0,r);d==="any"&&(d="null"),f.push(`${y}: ${d}`)}let l=M(p.type,void 0,r);l==="any"&&(l="null");let c=[];return f.length>0&&c.push(`params: { ${f.join(", ")} }`),l!=="undefined"&&c.push(`returns: ${l}`),`FunctionPredicate ${n} {
17
+ ${c.join(`
18
+ `)}
19
+ }`}let a=M(e.type,void 0,r);if(a==="any"||a==="undefined"){let p=e.type.getText(t).trim();return`Type ${n} {
20
+ // TS: ${p}
21
+ }`}return a==="''"||a==="0"||a==="true"||a==="null"?`Type ${n} ${a}`:`Type ${n} {
22
+ example: ${a}
23
+ }`}function Ot(e,t,r){let s=e.name.getText(t),n=e.type,i=new Set,a=[];for(let o of e.typeParameters){let y=o.name.getText(t);if(i.add(y),o.default){let d=M(o.default,void 0,r);a.push(`${y} = ${d}`)}else a.push(y)}let p=[];for(let o of n.parameters){let y=o.name?.getText(t)||"_";if(y==="this")continue;let d=o.type?.getText(t)||"any";if(i.has(d))p.push(`${y}: ${d}`);else{let k=M(o.type,void 0,r);k==="any"&&(k="null"),p.push(`${y}: ${k}`)}}let f=n.type?.getText(t)||"void",l;f!=="void"&&(i.has(f)?l=f:(l=M(n.type,void 0,r),l==="any"&&(l="null"),l==="undefined"&&(l=void 0)));let c=[];return p.length>0&&c.push(`params: { ${p.join(", ")} }`),l!==void 0&&c.push(`returns: ${l}`),`FunctionPredicate ${s}<${a.join(", ")}> {
24
+ ${c.join(`
25
+ `)}
26
+ }`}function Ct(e,t,r,s){let n=e.name.getText(t),i=[];for(let o of e.typeParameters||[]){let y=o.name.getText(t);if(o.default){let d=M(o.default,void 0,r);i.push(`${y} = ${d}`)}else i.push(y)}let a=(e.typeParameters||[]).map(o=>o.name.getText(t)),p=s?.find(o=>o.kind==="predicate"),f=s?.find(o=>o.kind==="declaration"),l;p?.text?l=p.text:l=`predicate(${["x",...a].join(", ")}) { return true }`;let c=[`description: '${n}'`,l];if(f?.text)c.push(`declaration ${f.text}`);else{let o=e.type;if(o&&u.isTypeLiteralNode(o)){let y=[];for(let d of o.members)if(u.isPropertySignature(d)&&d.name){let k=d.name.getText(t),m=d.questionToken?"?":"",h=d.type?d.type.getText(t):"any";y.push(`${k}${m}: ${h}`)}else u.isMethodSignature(d)&&d.name&&y.push(d.getText(t).trim().replace(/;$/,""));y.length>0&&c.push(`declaration {
27
+ ${y.join(`
28
+ `)}
29
+ }`)}else if(o){let y=o.getText(t).trim();c.push(`declaration {
30
+ // TS: ${y}
31
+ }`)}}return`Generic ${n}<${i.join(", ")}> {
32
+ ${c.join(`
33
+ `)}
34
+ }`}function at(e,t,r,s,n,i){let a;if(e.typeParameters&&e.typeParameters.length>0){a=new Map;for(let A of e.typeParameters)a.set(A.name.getText(t),{constraint:A.constraint,default:A.default})}let p=a||i?{...i,typeParams:a??i?.typeParams}:i,f=[],l=Q(e.parameters,t,s,f,p),{line:c}=t.getLineAndCharacterOfPosition(e.getStart(t)),o=n?`/* line ${c+1} */
35
+ `:"",y=r||(u.isFunctionDeclaration(e)&&e.name?e.name.getText(t):""),d=e.type?M(e.type,void 0,s,p):"",k=d&&d!=="undefined"&&d!=="any"&&!d.startsWith("new ")?`:! ${d}`:"";if(e.type&&(d==="any"||d==="undefined")){let A=e.type.getText(t);A!=="any"&&A!=="unknown"&&A!=="void"&&f.push(`return: ${A}`)}let m="";if(e.body){let A=u.isBlock(e.body)?e.body.getText(t):`{ return ${e.body.getText(t)} }`;m=u.transpileModule(A,{compilerOptions:{target:u.ScriptTarget.ESNext,module:u.ModuleKind.ESNext,removeComments:!1}}).outputText.trim()}else m="{ }";let h=e.modifiers?.some(A=>A.kind===u.SyntaxKind.ExportKeyword),w=e.modifiers?.some(A=>A.kind===u.SyntaxKind.AsyncKeyword),j=!!e.asteriskToken,$=h?"export ":"",N=w?"async ":"",E=j?"function* ":"function ",v=f.length>0?`/* TODO: TS types degraded \u2014 ${f.join(", ")} */
36
+ `:"";return`${o}${v}${$}${N}${E}${y}(${l.join(", ")})${k} ${m}`}function Kt(e,t,r,s){let n=t.name?.getText(r)||"",i=`_${n}_impl`,a=[],p=Q(t.parameters,r,s),f="{ }";if(t.body){let d=t.body.getText(r);f=u.transpileModule(d,{compilerOptions:{target:u.ScriptTarget.ESNext,module:u.ModuleKind.ESNext,removeComments:!1}}).outputText.trim()}let l=t.modifiers?.some(d=>d.kind===u.SyntaxKind.AsyncKeyword),c=!!t.asteriskToken,o=l?"async ":"",y=c?"function* ":"function ";a.push(`${o}${y}${i}(${p.join(", ")}) ${f}`);for(let d of e){let k=Q(d.parameters,r,s),m=d.parameters.map(E=>E.name.getText(r)),h=d.type?M(d.type,void 0,s):"",w=h&&h!=="undefined"&&h!=="any"?`:! ${h}`:"",{line:j}=r.getLineAndCharacterOfPosition(d.getStart(r)),$=`/* line ${j+1} */
37
+ `,N=c?"yield* ":"return ";a.push(`${$}${o}${y}${n}(${k.join(", ")})${w} { ${N}${i}(${m.join(", ")}) }`)}return a}function It(e,t,r,s,n=!1){let i=s;if(e.typeParameters&&e.typeParameters.length>0){let m=new Map;for(let h of e.typeParameters)m.set(h.name.getText(t),{constraint:h.constraint,default:h.default});i={...s,typeParams:m}}let a=e.name?.getText(t)||"Anonymous",f=e.heritageClauses?.find(m=>m.token===u.SyntaxKind.ExtendsKeyword)?.types[0]?.expression?.getText(t),l=new Map;if(n){for(let m of e.members)if(u.isPropertyDeclaration(m)&&m.name){let h=m.name.getText(t);m.modifiers?.some(j=>j.kind===u.SyntaxKind.PrivateKeyword)&&!h.startsWith("#")&&l.set(h,`#${h}`)}}let c=m=>{let h=m;for(let[w,j]of l)h=h.replace(new RegExp(`(\\b\\w+)\\.${w}\\b`,"g"),`$1.${j}`);return h},o=[];for(let m of e.members){if(u.isConstructorDeclaration(m)){let h=Q(m.parameters,t,r),w="{ }";if(m.body){let j=u.transpileModule(m.body.getText(t),{compilerOptions:{target:u.ScriptTarget.ESNext,module:u.ModuleKind.ESNext,removeComments:!1}});w=c(j.outputText.trim())}o.push(` constructor(${h.join(", ")}) ${w}`)}if(u.isMethodDeclaration(m)&&m.name){let h=m.name.getText(t),w=m.modifiers?.some(x=>x.kind===u.SyntaxKind.StaticKeyword),j=m.modifiers?.some(x=>x.kind===u.SyntaxKind.AsyncKeyword),$=Q(m.parameters,t,r,void 0,i),N=m.type?M(m.type,void 0,r,i):"",E=N&&N!=="undefined"&&N!=="any"?`:! ${N}`:"",v="{ }";if(m.body){let x=u.transpileModule(m.body.getText(t),{compilerOptions:{target:u.ScriptTarget.ESNext,module:u.ModuleKind.ESNext,removeComments:!1}});v=c(x.outputText.trim())}let A=!!m.asteriskToken,D=w?"static ":"",T=j?"async ":"",b=A?"*":"";o.push(` ${D}${T}${b}${h}(${$.join(", ")})${E} ${v}`)}if(u.isGetAccessorDeclaration(m)&&m.name){let h=m.name.getText(t),j=m.modifiers?.some(v=>v.kind===u.SyntaxKind.StaticKeyword)?"static ":"",$=m.type?M(m.type,void 0,r,i):"",N=$&&$!=="undefined"&&$!=="any"&&!$.startsWith("new ")?`: ${$}`:"",E="{ }";if(m.body){let v=u.transpileModule(m.body.getText(t),{compilerOptions:{target:u.ScriptTarget.ESNext,module:u.ModuleKind.ESNext,removeComments:!1}});E=c(v.outputText.trim())}o.push(` ${j}get ${h}()${N} ${E}`)}if(u.isSetAccessorDeclaration(m)&&m.name){let h=m.name.getText(t),j=m.modifiers?.some(E=>E.kind===u.SyntaxKind.StaticKeyword)?"static ":"",$=Q(m.parameters,t,r),N="{ }";if(m.body){let E=u.transpileModule(m.body.getText(t),{compilerOptions:{target:u.ScriptTarget.ESNext,module:u.ModuleKind.ESNext,removeComments:!1}});N=c(E.outputText.trim())}o.push(` ${j}set ${h}(${$.join(", ")}) ${N}`)}if(u.isPropertyDeclaration(m)&&m.name){let h=m.name.getText(t),j=m.modifiers?.some(N=>N.kind===u.SyntaxKind.StaticKeyword)?"static ":"",$=l.get(h)||h;if(m.initializer){let N=m.initializer.getText(t),E=N.trimStart().startsWith("{")?`(${N})`:N,A=u.transpileModule(E,{compilerOptions:{target:u.ScriptTarget.ESNext,module:u.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();E!==N&&(A=A.replace(/^\(/,"").replace(/\);?\s*$/,"")),o.push(` ${j}${$} = ${A}`)}else o.push(` ${j}${$}`)}}let d=e.modifiers?.some(m=>m.kind===u.SyntaxKind.ExportKeyword)?"export ":"",k=f?` extends ${f}`:"";return`${d}class ${a}${k} {
38
+ ${o.join(`
39
+ `)}
40
+ }`}function Q(e,t,r,s,n){let i=[];for(let a of e){let p=a.name.getText(t);if(p==="this")continue;let f=!!a.dotDotDotToken,l=!!a.questionToken||!!a.initializer,c=M(a.type,void 0,r,n);if(f)c==="any"||c==="undefined"?i.push(`...${p}: [null]`):i.push(`...${p}: ${c}`);else if(a.initializer){let o=a.initializer.getText(t);i.push(`${p} = ${o}`)}else if(c==="any"||c==="undefined"){if(i.push(p),s&&a.type){let o=a.type.getText(t);o!=="any"&&o!=="unknown"&&s.push(`${p}: ${o}`)}}else l?i.push(`${p}: ${c} | undefined`):i.push(`${p}: ${c}`)}return i}function le(e,t,r,s){let n=s;if(e.typeParameters&&e.typeParameters.length>0){let l=new Map;for(let c of e.typeParameters)l.set(c.name.getText(t),{constraint:c.constraint,default:c.default});n={...s,typeParams:l}}let i=u.isFunctionDeclaration(e)&&e.name?e.name.getText(t):"anonymous",a={};for(let l of e.parameters){let c=l.name.getText(t),o=!!l.questionToken||!!l.initializer,y;if(l.initializer){let d=l.initializer.getText(t);try{y=JSON.parse(d)}catch{y=d}}a[c]={type:K(l.type,n),required:!o,default:y}}let p={name:i,params:a,returns:e.type?K(e.type,n):void 0},f=Nt(e,r);return f&&(p.typeParams=f),p}function Dt(e,t,r,s){let n=s;if(e.typeParameters&&e.typeParameters.length>0){let c=new Map;for(let o of e.typeParameters)c.set(o.name.getText(t),{constraint:o.constraint,default:o.default});n={...s,typeParams:c}}let i=e.name?.getText(t)||"anonymous",a={},p={},f;for(let c of e.members){if(u.isConstructorDeclaration(c)){let o={};for(let y of c.parameters){let d=y.name.getText(t),k=!!y.questionToken||!!y.initializer,m;if(y.initializer){let h=y.initializer.getText(t);try{m=JSON.parse(h)}catch{m=h}}o[d]={type:K(y.type,n),required:!k,default:m}}f={params:o}}if(u.isMethodDeclaration(c)&&c.name){let o=c.name.getText(t),y=c.modifiers?.some(m=>m.kind===u.SyntaxKind.StaticKeyword),d={};for(let m of c.parameters){let h=m.name.getText(t),w=!!m.questionToken||!!m.initializer,j;if(m.initializer){let $=m.initializer.getText(t);try{j=JSON.parse($)}catch{j=$}}d[h]={type:K(m.type,n),required:!w,default:j}}let k={name:o,params:d,returns:c.type?K(c.type,n):void 0};y?p[o]=k:a[o]=k}}let l={name:i,methods:a,staticMethods:p,constructor:f};if(e.typeParameters&&e.typeParameters.length>0){let c={};for(let o of e.typeParameters){let y=o.name.getText(t),d={};o.constraint&&(d.constraint=M(o.constraint,void 0,r,s)),o.default&&(d.default=M(o.default,void 0,r,s)),c[y]=d}l.typeParams=c}return l}var Lt=new Set(["TjsStrict","TjsEquals","TjsClass","TjsDate","TjsNoeval","TjsNoVar","TjsStandard","TjsSafeEval"]);function _t(e){let t=[],r=/\/\*\s*@tjs\s+((?:Tjs\w+\s*)+)\*\//g,s;for(;(s=r.exec(e))!==null;){let n=s[1].trim().split(/\s+/);for(let i of n)Lt.has(i)&&!t.includes(i)&&t.push(i)}return t}function Jt(e){let t=[],r=/\/\*\s*@tjs-skip\s*\*\//g,s;for(;(s=r.exec(e))!==null;)t.push({index:s.index,kind:"skip"});let n=/\/\*\s*@tjs\s+predicate(\([^)]*\)\s*\{[\s\S]*?\})\s*\*\//g;for(;(s=n.exec(e))!==null;)t.push({index:s.index,kind:"predicate",text:`predicate${s[1].trim()}`});let i=/\/\*\s*@tjs\s+example:\s*([\s\S]*?)\s*\*\//g;for(;(s=i.exec(e))!==null;)t.push({index:s.index,kind:"example",text:s[1].trim()});let a=/\/\*\s*@tjs\s+declaration\s*(\{[\s\S]*?\})\s*\*\//g;for(;(s=a.exec(e))!==null;)t.push({index:s.index,kind:"declaration",text:s[1].trim()});return t.sort((p,f)=>p.index-f.index)}function Ut(e,t){let r=new Map;if(e.length===0)return r;let s=t.statements;for(let n=0;n<s.length;n++){let i=s[n],a;if((u.isInterfaceDeclaration(i)||u.isTypeAliasDeclaration(i)||u.isEnumDeclaration(i))&&(a=i.name.getText(t)),!a)continue;let p=i.getStart(t),f=n>0?s[n-1].getEnd():0,l=e.filter(c=>c.index>=f&&c.index<p);l.length>0&&r.set(a,l)}return r}function Bt(e){let t=[],r=/\/\*test\s+(['"`])([^'"`]*)\1\s*\{[\s\S]*?\}\s*\*\/|\/\*test\s*\{[\s\S]*?\}\s*\*\//g,s;for(;(s=r.exec(e))!==null;)t.push(s[0]);return t}function qt(e){let t=[],r=/\/\*#[\s\S]*?\*\//g,s=0,n=null,i=[];for(let p=0;p<e.length;p++){let f=e[p],l=p>0?e[p-1]:"";!n&&(f==='"'||f==="'"||f==="`")?n=f:n&&f===n&&l!=="\\"&&(n=null),n||(f==="{"&&s++,f==="}"&&s--),i[p]=s}let a;for(;(a=r.exec(e))!==null;)i[a.index]===0&&t.push({content:a[0],index:a.index});return t}function sn(e,t={}){let{emitTJS:r=!1,filename:s="input.ts"}=t,n=[],i=Bt(e),a=r?qt(e):[],p=r?Jt(e):[],f=_t(e),l=f.includes("TjsClass")||f.includes("TjsStrict"),c=u.createSourceFile(s,e,u.ScriptTarget.Latest,!0),o=r?Ut(p,c):new Map,y=[],d=new Set,k={},m={},h=new Set,w=T=>{for(let b=0;b<a.length;b++){let x=a[b];!h.has(b)&&x.index<T&&(y.push(x.content),h.add(b))}},j=new Map,$=new Map;function N(T){if(u.isTypeAliasDeclaration(T)&&j.set(T.name.getText(c),T.type),u.isInterfaceDeclaration(T)){let b=T.name.getText(c),x=$.get(b);if(x){let P=u.factory.updateInterfaceDeclaration(x,x.modifiers,x.name,x.typeParameters,x.heritageClauses,[...x.members,...T.members]);$.set(b,P)}else $.set(b,T)}u.forEachChild(T,N)}N(c);let E={typeAliases:j,interfaces:$,sourceFile:c,warnings:n,resolvedCache:new Map},v=new Map;for(let T of c.statements)if(u.isFunctionDeclaration(T)&&T.name){let b=T.name.getText(c);v.has(b)||v.set(b,{signatures:[],implementation:null});let x=v.get(b);T.body?x.implementation=T:x.signatures.push(T)}for(let[T,b]of v)(b.signatures.length===0||!b.implementation)&&v.delete(T);for(let T of c.statements){let b=!1;if(r&&w(T.getStart(c)),u.isFunctionDeclaration(T)&&T.name){let x=T.name.getText(c);b=!0;let P=v.get(x);if(P){if(T.body)if(r)y.push(...Kt(P.signatures,T,c,n));else{let g=[];for(let R of P.signatures)g.push(le(R,c,n,E));let S=le(T,c,n,E);S.overloads=g,k[x]=S}}else r?y.push(at(T,c,void 0,n,!0,E)):k[x]=le(T,c,n,E)}if(u.isVariableStatement(T)){let x=!1,P=T.modifiers?.some(g=>g.kind===u.SyntaxKind.ExportKeyword);for(let g of T.declarationList.declarations)if(u.isIdentifier(g.name)&&g.initializer&&(u.isArrowFunction(g.initializer)||u.isFunctionExpression(g.initializer))){x=!0;let S=g.name.getText(c),R=g.initializer;if(r){let O=at(R,c,S,n,!0,E);if(P&&!O.includes("export ")){let L=O.search(/^(async\s+)?function[\s*]/m);L>0?O=O.slice(0,L)+"export "+O.slice(L):O="export "+O}y.push(O)}else{let O=le(R,c,n,E);O.name=S,k[S]=O}}if(!x&&r){let g=u.transpileModule(T.getText(c),{compilerOptions:{target:u.ScriptTarget.ESNext,module:u.ModuleKind.ESNext,removeComments:!1}});y.push(g.outputText.trim())}b=!0}if(u.isInterfaceDeclaration(T)&&(b=!0,r)){let x=T.name.getText(c),P=o.get(x);if(!d.has(x)&&(d.add(x),!P?.some(g=>g.kind==="skip"))){let g=$.get(x)||T,S=Pt(g,c,n,P);if(S){let R=T.modifiers?.some(O=>O.kind===u.SyntaxKind.ExportKeyword);y.push(R?S.replace(/^(\/\*[\s\S]*?\*\/\s*)?/,"$1export "):S)}}}if(u.isTypeAliasDeclaration(T)&&(b=!0,r)){let x=T.name.getText(c),P=o.get(x);if(!d.has(x)&&(d.add(x),!P?.some(g=>g.kind==="skip"))){let g=vt(T,c,n,P);if(g){let S=T.modifiers?.some(R=>R.kind===u.SyntaxKind.ExportKeyword);y.push(S?g.replace(/^(\/\*[\s\S]*?\*\/\s*)?/,"$1export "):g)}}}if(u.isEnumDeclaration(T)&&(b=!0,r)){let x=T.name.getText(c),P=o.get(x);if(!d.has(x)&&(d.add(x),!P?.some(g=>g.kind==="skip"))){let g=Mt(T,c,n);g&&y.push(g)}}if(u.isClassDeclaration(T)&&T.name){let x=T.name.getText(c);if(b=!0,r){let P=It(T,c,n,void 0,l);y.push(P)}else m[x]=Dt(T,c,n,E)}if(u.isImportDeclaration(T)&&(b=!0,r&&!(T.importClause?.isTypeOnly||T.importClause?.namedBindings&&u.isNamedImports(T.importClause.namedBindings)&&T.importClause.namedBindings.elements.every(P=>P.isTypeOnly))))if(T.importClause?.namedBindings&&u.isNamedImports(T.importClause.namedBindings)){let P=T.importClause.namedBindings.elements.filter(g=>!g.isTypeOnly).map(g=>{let S=g.name.getText(c),R=g.propertyName?.getText(c);return R?`${R} as ${S}`:S});if(P.length>0){let g=T.moduleSpecifier.text;y.push(`import { ${P.join(", ")} } from '${g}'`)}}else{let g=T.getText(c).replace(/\btype\s+/g,"").replace(/\s*:\s*\w+/g,"");y.push(g)}if((u.isExportDeclaration(T)||u.isExportAssignment(T))&&(b=!0,r)){let P=u.transpileModule(T.getText(c),{compilerOptions:{target:u.ScriptTarget.ESNext,module:u.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();P&&y.push(P)}if(!b&&r){let P=u.transpileModule(T.getText(c),{compilerOptions:{target:u.ScriptTarget.ESNext,module:u.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();P&&y.push(P)}}if(r){w(1/0);let T=s||"unknown",x=`${f.length>0?f.join(`
41
+ `)+`
42
+
43
+ `:""}/* tjs <- ${T} */
44
+
45
+ `,P=i.length>0?`
46
+
47
+ `+i.join(`
48
+
49
+ `):"";return{code:x+y.join(`
50
+
51
+ `)+P,warnings:n.length>0?n:void 0}}let D=u.transpileModule(e,{compilerOptions:{target:u.ScriptTarget.ESNext,module:u.ModuleKind.ESNext,removeComments:!1}}).outputText;for(let[T,b]of Object.entries(k)){let x={params:Object.fromEntries(Object.entries(b.params).map(([g,S])=>[g,{type:S.type.kind,required:S.required,default:S.default}])),returns:b.returns?{type:b.returns.kind}:void 0};b.typeParams&&(x.typeParams=b.typeParams);let P=JSON.stringify(x,null,2);D+=`
52
+ ${T}.__tjs = ${P};
53
+ `}for(let[T,b]of Object.entries(m)){let x={constructor:b.constructor?{params:Object.fromEntries(Object.entries(b.constructor.params??{}).map(([g,S])=>[g,{type:S.type.kind,required:S.required,default:S.default}]))}:void 0,methods:Object.fromEntries(Object.entries(b.methods??{}).map(([g,S])=>[g,{params:Object.fromEntries(Object.entries(S.params??{}).map(([R,O])=>[R,{type:O.type.kind,required:O.required}])),returns:S.returns?{type:S.returns.kind}:void 0}])),staticMethods:Object.fromEntries(Object.entries(b.staticMethods??{}).map(([g,S])=>[g,{params:Object.fromEntries(Object.entries(S.params??{}).map(([R,O])=>[R,{type:O.type.kind,required:O.required}])),returns:S.returns?{type:S.returns.kind}:void 0}]))};b.typeParams&&(x.typeParams=b.typeParams);let P=JSON.stringify(x,null,2);D+=`
54
+ ${T}.__tjs = ${P};
55
+ `,D+=`
56
+ ${it(T)}
57
+ `}return{code:D,types:k,classes:Object.keys(m).length>0?m:void 0,warnings:n.length>0?n:void 0}}export{sn as fromTS};
58
+ //# sourceMappingURL=tjs-from-ts.js.map