@tslite/checker 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +72 -257
- package/dist/index.d.ts +72 -257
- package/dist/index.js +1 -1
- package/package.json +8 -3
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var core=require('@tslite/core'),capability=require('@tslite/capability'),codec=require('@tslite/codec');var R=e=>Object.freeze(e),i={any:R({t:"any"}),unknown:R({t:"unknown"}),string:R({t:"string"}),number:R({t:"number"}),boolean:R({t:"boolean"}),null:R({t:"null"}),undefined:R({t:"undefined"}),literal:e=>({t:"literal",value:e}),object:e=>({t:"object",props:e}),array:e=>({t:"array",items:e}),fn:(e,n)=>({t:"fn",params:e,returns:n}),ctor:(e,n)=>({t:"fn",params:e,returns:n,construct:{params:e,returns:n}}),var:e=>({t:"var",name:e}),apply:(e,n=[])=>({t:"apply",name:e,args:n}),promise:e=>({t:"apply",name:"Promise",args:[e]}),union:e=>{let n=[];for(let t of e)t.t==="union"?n.push(...t.of):n.push(t);return {t:"union",of:n}}};function q(e){if(e.t==="undefined")return {type:{t:"union",of:[]},hadUndefined:true};if(e.t==="union"&&e.of.some(n=>n.t==="undefined")){let n=e.of.filter(t=>t.t!=="undefined");return {type:n.length===1?n[0]:{t:"union",of:n},hadUndefined:true}}return {type:e,hadUndefined:false}}function z(e,n=new WeakSet){switch(e.t){case "string":case "number":case "boolean":case "null":case "literal":return true;case "array":return n.has(e)?true:(n.add(e),z(q(e.items).type,n));case "object":return n.has(e)?true:(n.add(e),Object.values(e.props).every(t=>z(q(t.type).type,n)));case "union":return n.has(e)?true:(n.add(e),e.of.every(t=>z(t,n)));case "undefined":case "fn":case "var":case "apply":case "any":case "unknown":return false}}var _e=e=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e);function b(e,n=new WeakSet){switch(e.t){case "any":case "unknown":case "string":case "number":case "boolean":case "null":case "undefined":return e.t;case "var":return e.name;case "literal":return typeof e.value=="string"?JSON.stringify(e.value):String(e.value);case "array":{let t=b(e.items,n);return Je(e.items)?`(${t})[]`:`${t}[]`}case "union":{if(n.has(e))return "\u2026";n.add(e);let t=e.of.length===0?"never":e.of.map(r=>b(r,n)).join(" | ");return n.delete(e),t}case "object":{if(n.has(e))return "\u2026";n.add(e);let t=Object.entries(e.props),r=t.map(([a,o])=>`${_e(a)?a:JSON.stringify(a)}${o.optional?"?":""}: ${b(o.type,n)}`).join("; ");return n.delete(e),t.length===0?"{}":`{ ${r} }`}case "fn":{if(n.has(e))return "\u2026";n.add(e);let t=e.params.map(a=>{let o=a.variadic?"...":"",s=a.optional&&!a.variadic?"?":"";return `${o}${a.name}${s}: ${b(a.type,n)}`}).join(", "),r=b(e.returns,n);return n.delete(e),`(${t}) => ${r}`}case "apply":{if(n.has(e))return "\u2026";n.add(e);let t=e.args.length===0?e.name:`${e.name}<${e.args.map(r=>b(r,n)).join(", ")}>`;return n.delete(e),t}}}function Je(e){return e.t==="union"&&e.of.length>0||e.t==="fn"}function N(e,n,t=new WeakSet){switch(e.t){case "var":return n[e.name]??e;case "array":return {t:"array",items:N(e.items,n,t)};case "union":return {t:"union",of:e.of.map(r=>N(r,n,t))};case "object":{if(t.has(e))return e;t.add(e);let r={};for(let a in e.props){let o=e.props[a];r[a]={type:N(o.type,n,t),optional:o.optional};}return t.delete(e),{t:"object",props:r}}case "fn":{if(t.has(e))return e;t.add(e);let a={t:"fn",params:e.params.map(o=>({...o,type:N(o.type,n,t)})),returns:N(e.returns,n,t)};return t.delete(e),a}case "apply":return {t:"apply",name:e.name,args:e.args.map(r=>N(r,n,t))};default:return e}}function O(e,n){if(e.t!=="apply")return false;let t=n[e.name];return t!==void 0&&t.params.length===e.args.length}function A(e,n){if(e.t!=="apply")return e;let t=n[e.name];if(!t||t.params.length!==e.args.length)return e;let r={};return t.params.forEach((a,o)=>r[a]=e.args[o]),N(t.body,r)}function B(e){switch(e.t){case "literal":return `#${typeof e.value}:${String(e.value)}`;case "object":return `{${Object.keys(e.props).sort().map(n=>`${n}${e.props[n].optional?"?":""}:${B(e.props[n].type)}`).join(",")}}`;case "array":return `[${B(e.items)}]`;case "union":return `(${e.of.map(B).sort().join("|")})`;case "fn":return `(${e.params.map(n=>B(n.type)).join(",")})=>${B(e.returns)}`;case "var":return `v:${e.name}`;case "apply":return `${e.name}<${e.args.map(B).join(",")}>`;default:return e.t}}function S(e,n,t={}){return T(e,n,{seen:new WeakMap,exp:new Set,schemes:t})}function Q(e,n,t={}){return S(e,n,t)&&S(n,e,t)}function T(e,n,t){if(e.t==="any"||n.t==="any"||n.t==="unknown")return true;if(e.t==="unknown")return false;if(!(e.t==="apply"&&n.t==="apply"&&e.name===n.name&&e.args.length===n.args.length)&&(O(e,t.schemes)||O(n,t.schemes))){let o=`${B(e)}\u2264${B(n)}`;if(t.exp.has(o))return true;t.exp.add(o);let s=T(A(e,t.schemes),A(n,t.schemes),t);return t.exp.delete(o),s}let a=t.seen.get(e);if(a?.has(n))return true;if(a||(a=new WeakSet,t.seen.set(e,a)),a.add(n),e.t==="union")return e.of.every(o=>T(o,n,t));if(n.t==="union")return n.of.some(o=>T(e,o,t));switch(n.t){case "literal":return e.t==="literal"&&e.value===n.value;case "string":case "number":case "boolean":case "null":case "undefined":return e.t===n.t?true:e.t==="literal"&&He(e.value)===n.t;case "array":return e.t==="array"&&T(e.items,n.items,t);case "object":return e.t==="object"&&Ze(e,n,t);case "fn":return e.t==="fn"&&Ye(e,n,t);case "var":return e.t==="var"&&e.name===n.name;case "apply":return e.t==="apply"&&e.name===n.name&&e.args.length===n.args.length&&e.args.every((o,s)=>T(o,n.args[s],t))}}var He=e=>typeof e;function Ze(e,n,t){for(let r in n.props){let a=n.props[r],o=e.props[r];if(!o){if(!a.optional)return false;continue}if(o.optional&&!a.optional||!T(o.type,a.type,t))return false}return true}function Ye(e,n,t){if(!T(e.returns,n.returns,t))return false;for(let r=0;r<e.params.length;r++){let a=e.params[r];if(a.variadic)break;let o=n.params[r];if(!o){if(a.optional)continue;return false}if(!T(o.type,a.type,t))return false}return true}function k(e){let n=[];for(let r of e)r.t==="union"?n.push(...r.of):n.push(r);if(n.some(r=>r.t==="any"))return i.any;let t=[];for(let r of n)if(!t.some(a=>S(r,a))){for(let a=t.length-1;a>=0;a--)S(t[a],r)&&t.splice(a,1);t.push(r);}return t.length===1?t[0]:{t:"union",of:t}}var Qe=i.union([]);function Te(e,n){return X(e,n,new WeakMap)}function Xe(e){return e.reduce(Te,Qe)}function X(e,n,t){if(e.t==="any"||n.t==="any")return i.any;if(e===n)return e;let r=t.get(e)?.get(n);if(r)return r;if(e.t==="object"&&n.t==="object")return en(e,n,t);if(e.t==="array"&&n.t==="array"){let a={t:"array",items:i.unknown};return xe(t,e,n,a),a.items=X(e.items,n.items,t),a}return k([e,n])}function en(e,n,t){let r={t:"object",props:{}};xe(t,e,n,r);for(let a in e.props){let o=e.props[a],s=n.props[a];if(s){let l=X(o.type,s.type,t);r.props[a]=o.optional||s.optional?{type:l,optional:true}:{type:l};}else r.props[a]={type:o.type,optional:true};}for(let a in n.props)a in e.props||(r.props[a]={type:n.props[a].type,optional:true});return r}function xe(e,n,t,r){let a=e.get(n);a||(a=new WeakMap,e.set(n,a)),a.set(t,r);}function F(e,n,t={}){let r=e;for(let a of n){let o=ee(r,a,t);if(o===null)return null;r=o;}return {type:r,completions:ne(r,t)}}var nn=e=>e==="[]"||/^\d+$/.test(e);function ee(e,n,t,r=new Set){if(O(e,t)){let a=B(e);if(r.has(a))return null;r.add(a);let o=ee(A(e,t),n,t,r);return r.delete(a),o}switch(e.t){case "any":return e;case "object":return e.props[n]?.type??null;case "array":return nn(n)?e.items:null;case "union":{let a=e.of.map(o=>ee(o,n,t,r)).filter(o=>o!==null);return a.length?k(a):null}default:return null}}function ne(e,n,t=new WeakSet,r=new Set){if(O(e,n)){let a=B(e);if(r.has(a))return [];r.add(a);let o=ne(A(e,n),n,t,r);return r.delete(a),o}switch(e.t){case "object":return Object.entries(e.props).map(([a,o])=>({key:a,type:o.type,optional:!!o.optional}));case "array":return [{key:"[]",type:e.items,optional:false}];case "union":{if(t.has(e))return [];t.add(e);let a=[],o=new Set;for(let s of e.of)for(let l of ne(s,n,t,r))o.has(l.key)||(o.add(l.key),a.push(l));return t.delete(e),a}default:return []}}function x(e,n,t={}){if(e.t==="var"){let r=t[e.name];return r?S(n,r)||S(r,n)?t:null:{...t,[e.name]:n}}if(n.t==="any"||n.t==="unknown")return t;switch(e.t){case "array":return n.t==="array"?x(e.items,n.items,t):null;case "object":{if(n.t!=="object")return null;let r=t;for(let a in e.props){let o=e.props[a],s=n.props[a];if(!s){if(o.optional)continue;return null}if(r=x(o.type,s.type,r),r===null)return null}return r}case "fn":{if(n.t!=="fn")return null;let r=x(e.returns,n.returns,t);if(r===null)return null;let a=Math.min(e.params.length,n.params.length);for(let o=0;o<a;o++)if(r=x(e.params[o].type,n.params[o].type,r),r===null)return null;return r}case "apply":{if(n.t!=="apply"||n.name!==e.name||n.args.length!==e.args.length)return null;let r=t;for(let a=0;a<e.args.length;a++)if(r=x(e.args[a],n.args[a],r),r===null)return null;return r}default:return S(n,e)?t:null}}function tn(e,n){let t={};for(let r=0;r<e.params.length;r++){let a=e.params[r];if(a.variadic){for(let o=r;o<n.length;o++)if(t=x(a.type,n[o],t),t===null)return null;break}if(r>=n.length){if(a.optional)continue;return null}if(t=x(a.type,n[r],t),t===null)return null}return {returns:N(e.returns,t),bindings:t}}function V(e,n){let t={};for(let r=0;r<e.params.length&&r<n.length;r++){let a=e.params[r],o=x(a.type,n[r],t);o!==null&&(t=o);}return {returns:N(e.returns,t),bindings:t}}function C(e,n=new WeakSet){switch(e.t){case "var":return i.unknown;case "array":return {t:"array",items:C(e.items,n)};case "union":return {t:"union",of:e.of.map(t=>C(t,n))};case "object":{if(n.has(e))return e;n.add(e);let t={};for(let r in e.props){let a=e.props[r];t[r]={type:C(a.type,n),optional:a.optional};}return n.delete(e),{t:"object",props:t}}case "fn":{if(n.has(e))return e;n.add(e);let r={t:"fn",params:e.params.map(a=>({...a,type:C(a.type,n)})),returns:C(e.returns,n)};return n.delete(e),r}case "apply":return {t:"apply",name:e.name,args:e.args.map(t=>C(t,n))};default:return e}}var je=(e={})=>core.rootScope(e),j=(e,n)=>core.childScope(e,n),P=(e,n)=>core.lookup(e,n),te=e=>core.visibleNames(e),ln=(e={},n={},t={},r={})=>({scope:je(e),types:n,schemes:t,accessors:r}),un=(e,n)=>e.types[n],pn=(e,n)=>e.schemes[n];var D=(e,n,t)=>({code:e,severity:"error",node:n,message:t}),E=(e,n,t,r="error")=>({code:e,severity:r,node:n,message:t}),h={notAssignable:(e,n,t)=>D("not-assignable",e,`Type '${b(n)}' is not assignable to type '${b(t)}'.`),unknownName:(e,n)=>D("unknown-name",e,`Cannot find name '${n}'.`),notCallable:(e,n)=>D("not-callable",e,`Type '${b(n)}' is not callable.`),notNewable:(e,n)=>D("not-newable",e,`Type '${b(n)}' is not newable \u2014 only host constructors (with a construct signature) can be used with 'new'.`),noSuchMember:(e,n,t)=>D("no-such-member",e,`Property '${t}' does not exist on type '${b(n)}'.`),notObject:(e,n)=>D("not-object",e,`Type '${b(n)}' has no members to access.`),constNeedsInit:e=>D("const-needs-init",e,"'const' declarations must be initialized."),missingArgument:(e,n,t)=>D("missing-argument",e,`Missing argument '${n}' of type '${b(t)}'.`),unsupported:(e,n)=>D("unsupported",e,`${n} is not supported in this language.`),castUnsound:(e,n,t)=>E("cast-unsound",e,`Conversion of type '${b(n)}' to type '${b(t)}' may be a mistake \u2014 neither sufficiently overlaps the other. Cast through 'unknown' first if intentional.`,"warning")};function re(){let e=[];return {all:e,report(n){e.push(n);},hasErrors(){return e.some(n=>n.severity==="error")}}}function oe(e,n,t={}){return n.flatMap(r=>r(e,t))}function K(e,n){let t=r=>{n(r);for(let a of core.childrenOf(r))t(a);};t(e);}var mn=e=>Array.isArray(e)?e:[e],De=["ArrowFunctionExpression","FunctionExpression","FunctionDeclaration"];function se(e,n="error"){return t=>{let r=[];return K(t,a=>{let o=capability.nodeViolation(a,e);o&&r.push(E("node-not-allowed",a,`'${o}' is not allowed by the capability profile.`,n));}),r}}function ie(e,n="error"){let t=new Set(e);return r=>{let a=[];return K(r,o=>{if(o.type!=="CallExpression")return;let s=o.callee;if(s.type!=="Identifier")a.push(E("name-not-allowed",s,"Only direct calls to allowed functions are permitted.",n));else {let l=s.name;t.has(l)||a.push(E("name-not-allowed",s,`Function '${l}' is not allowed here.`,n));}}),a}}function _(e,n,t={}){let r=new Set(mn(e)),a=t.severity??"error",o=[...r].join("/");return s=>{let l=[],m=(c,f)=>{let d=r.has(c.type),y=d?f+1:f;d&&y>n&&l.push(E("too-deep",c,`Nesting of ${o} exceeds ${n}${t.hint?` \u2014 ${t.hint}`:""}.`,a));for(let g of core.childrenOf(c))m(g,y);};return m(s,0),l}}var le=(e=3,n="error")=>_(De,e,{hint:"use a pipe instead of nesting functions",severity:n}),ue=(e,n="error")=>_("CallExpression",e,{hint:"use a pipe instead of nesting calls",severity:n}),pe=(e,n="error")=>_("MemberExpression",e,{severity:n});function ce(e,n="error"){return t=>{let r=[],a=(o,s)=>{if(s>e){r.push(E("too-deep",o,`Expression nesting exceeds ${e}.`,n));return}for(let l of core.childrenOf(o))a(l,s+1);};return a(t,0),r}}function me(e,n="error"){return t=>{let r=0;return K(t,()=>{r++;}),r>e?[E("too-large",t,`Expression has ${r} nodes (max ${e}).`,n)]:[]}}function ye(e,n="error"){return t=>{let r=[];return K(t,a=>{if(a.type==="CallExpression"){let o=a.arguments;o&&o.length>e&&r.push(E("too-large",a,`Call has ${o.length} arguments (max ${e}).`,n));}}),r}}function fe(e,n={},t="error"){return (r,a)=>{let o=a.overlay?.get(r)?.type;return o?S(o,e,n)?[]:[E("wrong-result-type",r,`Result type '${b(o)}' is not assignable to the required '${b(e)}'.`,t)]:[]}}function $e(e){let n=[se(e)];return e.hostAllow!=="*"&&n.push(ie([...e.hostAllow])),n}function de(e){return $e(capability.compileProfile(e))}var Sn=e=>{let n={};for(let t of Object.keys(e))n[t]={params:[],body:e[t]};return n};function hn(e){let n=[];return e.maxDepth!==void 0&&n.push(ce(e.maxDepth)),e.maxNodes!==void 0&&n.push(me(e.maxNodes)),e.maxArgs!==void 0&&n.push(ye(e.maxArgs)),e.maxFunctionNesting!==void 0&&n.push(le(e.maxFunctionNesting)),e.maxCallNesting!==void 0&&n.push(ue(e.maxCallNesting)),e.memberDepth!==void 0&&n.push(pe(e.memberDepth)),n}function gn(e,n,t={}){let r={...Sn(n.types),...n.schemes,...bn(e)},a={overlay:new WeakMap,sink:re(),env:n,schemes:r},o=p(e,n.scope,a),s=[];t.profile&&s.push(...de(t.profile)),t.limits&&s.push(...hn(t.limits)),t.resultType&&s.push(fe(t.resultType,r));let l=s.length?[...a.sink.all,...oe(e,s,{overlay:a.overlay})]:a.sink.all;return {type:o,overlay:a.overlay,diagnostics:l}}var bn=e=>{let n={};return core.walk(e,{TSTypeAliasDeclaration(t){let r=t;r.id?.name&&r.typeAnnotation&&(n[r.id.name]={params:r.typeParameters??[],body:r.typeAnnotation});}}),n},ke=e=>e.typeAnnotation,Ie=e=>e.returnType,u=(e,n,t,r)=>(e.overlay.set(n,{type:t,scope:r}),t),Se=e=>e.type==="ArrowFunctionExpression",Le=e=>e.t==="apply"&&e.name==="Promise"&&e.args.length===1,he=e=>Le(e)?e.args[0]:e,J=e=>Le(e)?e:i.promise(e);function p(e,n,t){switch(e.type){case "Literal":return u(t,e,Ge(e),n);case "Identifier":{let r=e.name,a=P(n,r);return a===void 0?r==="undefined"?u(t,e,i.undefined,n):(t.sink.report(h.unknownName(e,r)),u(t,e,i.unknown,n)):u(t,e,a,n)}case "MemberExpression":return u(t,e,kn(e,n,t),n);case "CallExpression":return u(t,e,wn(e,n,t),n);case "NewExpression":return u(t,e,Bn(e,n,t),n);case "ArrowFunctionExpression":return Ne(e,n,t);case "FunctionDeclaration":return t.sink.report(h.unsupported(e,"function declaration (use 'const fn = () => \u2026')")),u(t,e,i.unknown,n);case "FunctionExpression":return t.sink.report(h.unsupported(e,"anonymous function (use an arrow)")),u(t,e,i.unknown,n);case "ThisExpression":return t.sink.report(h.unsupported(e,"'this'")),u(t,e,i.unknown,n);case "BlockStatement":return u(t,e,we(e,n,t),n);case "ReturnStatement":{let r=e.argument;return u(t,e,r?p(r,n,t):i.unknown,n)}case "IfStatement":return v(e,n,t),t.overlay.get(e)?.type??i.unknown;case "ForStatement":case "WhileStatement":case "DoWhileStatement":case "ForOfStatement":case "ForInStatement":case "BreakStatement":case "ContinueStatement":case "ThrowStatement":case "TryStatement":case "SwitchStatement":return v(e,n,t),t.overlay.get(e)?.type??i.unknown;case "AssignmentExpression":{let r=e;return p(r.left,n,t),u(t,e,p(r.right,n,t),n)}case "UpdateExpression":return p(e.argument,n,t),u(t,e,i.number,n);case "ExpressionStatement":return u(t,e,p(e.expression,n,t),n);case "VariableDeclaration":return Ee(e,n,t),u(t,e,i.unknown,n);case "TSTypeAliasDeclaration":return u(t,e,i.unknown,n);case "BinaryExpression":return u(t,e,On(e,n,t),n);case "LogicalExpression":{let r=e,a=p(r.left,n,t),o=p(r.right,n,t);return u(t,e,k([a,o]),n)}case "UnaryExpression":return u(t,e,Pn(e,n,t),n);case "ConditionalExpression":{let r=e;p(r.test,n,t);let a=p(r.consequent,n,t),o=p(r.alternate,n,t);return u(t,e,k([a,o]),n)}case "ObjectExpression":return u(t,e,In(e,n,t),n);case "ArrayExpression":return u(t,e,Ln(e,n,t),n);case "TemplateLiteral":{for(let r of e.expressions)p(r,n,t);return u(t,e,i.string,n)}case "AwaitExpression":{let r=e.argument,a=r?p(r,n,t):i.unknown;return u(t,e,he(a),n)}case "Program":return Be(e.body,n,t),u(t,e,i.unknown,n);case "JsonExpression":return u(t,e,be(e.body,n,t,e),n);case "ChainExpression":return u(t,e,k([p(e.expression,n,t),i.undefined]),n);case "TSAsExpression":{let r=e,a=p(r.expression,n,t),o=r.typeAnnotation;return !S(a,o,t.schemes)&&!S(o,a,t.schemes)&&t.sink.report(h.castUnsound(e,a,o)),u(t,e,o,n)}default:return t.sink.report(h.unsupported(e,`'${e.type}'`)),u(t,e,i.unknown,n)}}function Ge(e){let n=e;if(n.regex||n.bigint)return i.unknown;let t=n.value;if(t===null)return i.null;if(t===void 0)return i.undefined;switch(typeof t){case "string":return i.string;case "number":return i.number;case "boolean":return i.boolean;default:return i.unknown}}function kn(e,n,t){let r=p(e.object,n,t);if(e.computed){p(e.property,n,t);let s=F(r,["[]"],t.schemes);return s?s.type:i.unknown}let a=e.property.name,o=F(r,[a],t.schemes);return o?o.type:(r.t==="object"||r.t==="array"||r.t==="union"?t.sink.report(h.noSuchMember(e,r,a)):r.t!=="any"&&r.t!=="unknown"&&t.sink.report(h.notObject(e,r)),i.unknown)}function Nn(e){let n=r=>r&&r.type==="Literal"&&typeof r.value=="string"?r.value:null;if(e.length===1&&e[0].type==="ArrayExpression"){let r=[];for(let a of e[0].elements){let o=n(a);if(o===null)return null;r.push(o);}return r}let t=[];for(let r of e){let a=n(r);if(a===null)return null;t.push(a);}return t.length?t:null}function Me(e){if(e.type==="Identifier")return e.name;if(e.type==="MemberExpression"){let n=e;if(n.computed||n.property.type!=="Identifier")return null;let t=Me(n.object);return t===null?null:`${t}.${n.property.name}`}return null}function wn(e,n,t){let r=e.arguments,a=Me(e.callee);if(a){let f=t.env.accessors?.[a];if(f){let d=Nn(r);if(d){let y=F(f,d,t.schemes);return y?y.type:(t.sink.report(h.noSuchMember(e,f,d.join("."))),i.unknown)}return r.forEach(y=>p(y,n,t)),i.unknown}}let o=p(e.callee,n,t);if(o.t==="any")return r.forEach(f=>p(f,n,t)),i.any;if(o.t!=="fn")return r.forEach(f=>p(f,n,t)),t.sink.report(h.notCallable(e,o)),i.unknown;let s=o,l=r.map(f=>Se(f)?i.any:p(f,n,t)),m=V(s,l).bindings;r.forEach((f,d)=>{if(Se(f)){let y=N(s.params[d]?.type??i.any,m);l[d]=Ne(f,n,t,y);}});let{bindings:c}=V(s,l);return Ue(e,s,l,c,t),C(N(s.returns,c))}function Bn(e,n,t){let r=e.arguments,a=p(e.callee,n,t);if(a.t==="any")return r.forEach(c=>p(c,n,t)),i.any;let o=a.t==="fn"?a.construct:void 0;if(!o)return r.forEach(c=>p(c,n,t)),t.sink.report(h.notNewable(e,a)),i.unknown;let s={params:o.params,returns:o.returns},l=r.map(c=>Se(c)?i.any:p(c,n,t)),{bindings:m}=V(s,l);return Ue(e,s,l,m,t),C(N(o.returns,m))}function Ue(e,n,t,r,a){for(let o=0;o<n.params.length;o++){let s=n.params[o];if(s.variadic)break;let l=N(s.type,r);if(o>=t.length){s.optional||a.sink.report(h.missingArgument(e,s.name,l));continue}S(t[o],l,a.schemes)||a.sink.report(h.notAssignable(e.arguments[o],t[o],l));}}var We=e=>{let n=e.value;return n===null?i.null:typeof n=="string"||typeof n=="number"||typeof n=="boolean"?i.literal(n):Ge(e)},En=(e,n)=>{let t=e;for(let r=0;r<50&&t.t==="apply";r++){let a=A(t,n.schemes);if(a===t||a.t==="apply"&&a.name===t.name)break;t=a;}return t};function L(e,n,t,r){let a=En(n,r);switch(e.type){case "Literal":{let s=We(e);return S(s,n,r.schemes)||r.sink.report(h.notAssignable(e,s,n)),u(r,e,n,t)}case "ArrayExpression":{if(a.t==="array"){for(let s of e.elements){if(!s)continue;let l=s;l.type==="SpreadElement"?L(l.argument,n,t,r):L(l,a.items,t,r);}return u(r,e,n,t)}break}case "ObjectExpression":{if(a.t==="object"){let s={};for(let m of e.properties){let c=m;if(c.type==="SpreadElement"){p(c.argument,t,r);continue}let f=c,d=Ke(f),y=d!==null?a.props[d]?.type:void 0,g=y?L(f.value,y,t,r):p(f.value,t,r);d!==null&&(s[d]={type:g}),u(r,c,g,t);}let l={t:"object",props:s};return S(l,n,r.schemes)||r.sink.report(h.notAssignable(e,l,n)),u(r,e,n,t)}break}case "ArrowFunctionExpression":{if(a.t==="fn"){let s=Ne(e,t,r,a);return S(s,n,r.schemes)||r.sink.report(h.notAssignable(e,s,n)),u(r,e,n,t)}break}case "ConditionalExpression":{let s=e;return p(s.test,t,r),L(s.consequent,n,t,r),L(s.alternate,n,t,r),u(r,e,n,t)}}let o=p(e,t,r);return S(o,n,r.schemes)||r.sink.report(h.notAssignable(e,o,n)),u(r,e,o,t)}function vn(e){let n=Ie(e);return n?{t:"fn",params:e.params.map((r,a)=>({name:G(r)??`arg${a}`,type:ke(r)??i.unknown})),returns:e.async?J(n):n}:null}function Ne(e,n,t,r){let a=r&&r.t==="fn"?r:void 0,o={},s=e.params.map((y,g)=>{let w=y,M=G(w),$=ke(w)??a?.params[g]?.type??i.unknown;return M&&(o[M]=$),t.overlay.set(w,{type:$,scope:n}),{name:M??`arg${g}`,type:$}}),l=j(n,o),m=e.body,c=Ie(e);if(m.type!=="BlockStatement"&&c){let y=e.async?he(c):c;L(m,y,l,t);let g=e.async?J(c):c;return u(t,e,{t:"fn",params:s,returns:g},n)}let f=m.type==="BlockStatement"?u(t,m,we(m,l,t),l):p(m,l,t),d=e.async?J(f):f;if(c){let y=e.async?he(c):c,g=e.async?f:d;S(g,y,t.schemes)||t.sink.report(h.notAssignable(m,d,c));let w=e.async?J(c):c;return u(t,e,{t:"fn",params:s,returns:w},n)}return u(t,e,{t:"fn",params:s,returns:d},n)}function we(e,n,t){let{returns:r}=Be(e.body,n,t);return r.length?k(r):i.unknown}function Be(e,n,t){let r=n,a=[];for(let o of e){let s=o;if(s.type==="VariableDeclaration")r=Ee(s,r,t);else if(s.type==="FunctionDeclaration"){let l=p(s,r,t),m=G(s.id);m&&(r=j(r,{[m]:l}));}else if(s.type==="IfStatement"){a.push(...v(s,r,t));let l=s;!l.alternate&&H(l.consequent)&&(r=ge(r,ze(l.test,r,t.schemes).else));}else a.push(...v(s,r,t));}return {scope:r,returns:a}}var U={then:{},else:{}},Ve={string:i.string,number:i.number,boolean:i.boolean},W=e=>e.t==="union"?[...e.of]:[e];function Oe(e,n){let t=e,r=n;return e.type==="UnaryExpression"&&t.operator==="typeof"&&t.argument.type==="Identifier"&&n.type==="Literal"&&typeof r.value=="string"?{name:t.argument.name,tag:r.value}:null}function Cn(e,n){let t=Ve[n];if(!t)return null;if(e.t==="unknown"||e.t==="any")return t;let r=W(e).filter(a=>S(a,t));return r.length?k(r):t}function An(e,n){let t=Ve[n];if(!t||e.t==="unknown"||e.t==="any")return null;let r=W(e).filter(a=>!S(a,t));return r.length?k(r):null}function Fe(e,n){if(e.type==="Identifier"&&n.type==="Literal"){let t=We(n);if(t.t==="literal"||t.t==="null")return {name:e.name,lit:t}}return null}function Tn(e,n,t){return e.t==="unknown"||e.t==="any"||S(n,e,t)?n:null}function xn(e,n,t){let r=W(e),a=r.filter(o=>!Q(o,n,t));return a.length&&a.length<r.length?k(a):null}var qe=e=>e.t==="null"||e.t==="undefined",jn=e=>{if(e.t==="unknown"||e.t==="any")return null;let n=W(e),t=n.filter(r=>!qe(r));return t.length&&t.length<n.length?k(t):null},Dn=e=>{let n=W(e),t=n.filter(qe);return t.length&&t.length<n.length?k(t):null},Pe=e=>e.type==="Literal"&&e.value===null?"null":e.type==="Identifier"&&e.name==="undefined"?"undefined":null,I=(e,n,t)=>({then:n?{[e]:n}:{},else:t?{[e]:t}:{}}),$n=e=>e==="==="||e==="=="||e==="!=="||e==="!=";function ze(e,n,t){if(e.type==="BinaryExpression"){let r=e;if(!$n(r.operator))return U;let a=r.operator==="!=="||r.operator==="!=",o=r.left,s=r.right,l=Oe(o,s)??Oe(s,o);if(l){let y=P(n,l.name);if(!y)return U;let g=Cn(y,l.tag),w=An(y,l.tag);return a?I(l.name,w,g):I(l.name,g,w)}let m=Pe(o),c=Pe(s),f=m?s:c?o:null;if((m||c)&&f?.type==="Identifier"){let y=f.name,g=P(n,y);if(!g)return U;let M=r.operator==="=="||r.operator==="!="?["null","undefined"]:[m??c],$=W(g),ve=$.filter(Y=>M.includes(Y.t)),Z=$.filter(Y=>!M.includes(Y.t)),Ce=ve.length?k(ve):null,Ae=Z.length&&Z.length<$.length?k(Z):null;return a?I(y,Ae,Ce):I(y,Ce,Ae)}let d=Fe(o,s)??Fe(s,o);if(d){let y=P(n,d.name);if(!y)return U;let g=Tn(y,d.lit,t),w=xn(y,d.lit,t);return a?I(d.name,w,g):I(d.name,g,w)}return U}if(e.type==="Identifier"){let r=e.name,a=P(n,r);if(a)return I(r,jn(a),Dn(a))}return U}var ge=(e,n)=>Object.keys(n).length?j(e,n):e;function H(e){switch(e.type){case "ReturnStatement":case "ThrowStatement":return true;case "BlockStatement":{let n=e.body;return n.length>0&&H(n[n.length-1])}case "IfStatement":{let n=e;return !!n.alternate&&H(n.consequent)&&H(n.alternate)}default:return false}}function v(e,n,t){switch(e.type){case "ReturnStatement":{let r=e.argument,a=r?p(r,n,t):i.unknown;return u(t,e,a,n),[a]}case "IfStatement":{let r=e;p(r.test,n,t);let a=ze(r.test,n,t.schemes),o=v(r.consequent,ge(n,a.then),t);return r.alternate&&o.push(...v(r.alternate,ge(n,a.else),t)),u(t,e,i.unknown,n),o}case "BlockStatement":{let r=we(e,n,t);return u(t,e,r,n),r.t==="unknown"?[]:[r]}case "ForStatement":case "WhileStatement":case "DoWhileStatement":{let r=e,a=n;r.init&&(r.init.type==="VariableDeclaration"?a=Ee(r.init,a,t):p(r.init,a,t)),r.test&&p(r.test,a,t),r.update&&p(r.update,a,t);let o=v(r.body,a,t);return u(t,e,i.unknown,n),o}case "ForOfStatement":case "ForInStatement":{let r=e,a=p(r.right,n,t),o=e.type==="ForOfStatement"?a.t==="array"?a.items:i.unknown:i.string,s=Rn(r.left),l=s?j(n,{[s]:o}):n,m=v(r.body,l,t);return u(t,e,i.unknown,n),m}case "BreakStatement":case "ContinueStatement":return u(t,e,i.unknown,n),[];case "ThrowStatement":{let r=e.argument;return r&&p(r,n,t),u(t,e,i.unknown,n),[]}case "TryStatement":{let r=e,a=v(r.block,n,t);if(r.handler){let o=r.handler.param,s=o?G(o):null,l=s?j(n,{[s]:i.unknown}):n;a.push(...v(r.handler.body,l,t));}return r.finalizer&&a.push(...v(r.finalizer,n,t)),u(t,e,i.unknown,n),a}case "SwitchStatement":{let r=e;p(r.discriminant,n,t);let a=n,o=[];for(let s of r.cases){s.test&&p(s.test,a,t);let l=Be(s.consequent,a,t);a=l.scope,o.push(...l.returns);}return u(t,e,i.unknown,n),o}default:return p(e,n,t),[]}}var Rn=e=>{if(e.type==="VariableDeclaration"){let n=e.declarations[0];return n?G(n.id):null}return G(e)};function Ee(e,n,t){let r={};for(let a of e.declarations){let o=G(a.id),s=ke(a.id);if(!a.init){t.sink.report(h.constNeedsInit(a)),o&&(r[o]=s??i.unknown);continue}let l=s??(a.init.type==="ArrowFunctionExpression"?vn(a.init):null),m=o&&l?j(n,{[o]:l}):n,c;s?(L(a.init,s,m,t),c=s):c=p(a.init,m,t),u(t,a,c,n),o&&(r[o]=c);}return u(t,e,i.unknown,n),j(n,r)}function On(e,n,t){let r=p(e.left,n,t),a=p(e.right,n,t),o=e.operator;return o==="+"?S(r,i.string)||S(a,i.string)?i.string:i.number:Fn.has(o)?i.number:i.boolean}var Fn=new Set(["-","*","/","%","**","&","|","^","<<",">>",">>>"]);function Pn(e,n,t){switch(p(e.argument,n,t),e.operator){case "!":return i.boolean;case "-":case "+":case "~":return i.number;case "typeof":return i.string;case "delete":return i.boolean;case "void":return i.undefined;default:return i.unknown}}function In(e,n,t){let r={};for(let a of e.properties){let o=a;if(o.type==="SpreadElement"){p(o.argument,n,t);continue}let s=o,l=p(s.value,n,t),m=Ke(s);m!==null&&(r[m]={type:l}),u(t,o,l,n);}return {t:"object",props:r}}var Ke=e=>{if(e.computed)return null;let n=e.key;return n.type==="Identifier"?n.name:n.type==="Literal"?String(n.value??""):null};function Ln(e,n,t){let r=[];for(let a of e.elements){if(!a)continue;let o=a;if(o.type==="SpreadElement"){p(o.argument,n,t);continue}r.push(p(o,n,t));}return i.array(r.length?k(r):i.unknown)}function be(e,n,t,r){if(e===null)return i.null;switch(typeof e){case "string":return i.string;case "number":return i.number;case "boolean":return i.boolean;case "object":break;default:return i.unknown}if(Array.isArray(e)){let s=e.map(l=>be(l,n,t,r));return i.array(s.length?k(s):i.unknown)}let a=e;if(core.AST_MARKER in a){let s;try{s=codec.fromJson(a);}catch{return t.sink.report(h.unsupported(r,`'#ast: ${String(a[core.AST_MARKER])}'`)),i.unknown}return p(s,n,t)}let o={};for(let s of Object.keys(a))o[s]={type:be(a[s],n,t,r)};return {t:"object",props:o}}var G=e=>e.type==="Identifier"?e.name:null;var Gn=(e,n)=>({...e,typeAnnotation:n}),Mn=(e,n)=>({...e,returnType:n});function Un(e,n){return e.get(n)?.type}function Wn(e,n){return e.get(n)?.scope}function Vn(e,n){let t=e.get(n)?.type;return t?F(t,[])?.completions??[]:[]}function qn(e,n){let t=e.get(n)?.scope;return t?[...te(t)].map(([r,a])=>({key:r,type:a,optional:false})):[]}function zn(e,n){return e.filter(t=>t.node===n)}exports.FUNCTION_KINDS=De;exports.annotate=Gn;exports.annotateReturn=Mn;exports.calleeAllowlist=ie;exports.capabilityNodes=se;exports.check=gn;exports.childScope=j;exports.createEnv=ln;exports.createSink=re;exports.diag=h;exports.diagnosticsAt=zn;exports.discover=F;exports.equals=Q;exports.expand1=A;exports.format=b;exports.fromCapability=de;exports.groundVars=C;exports.guard=oe;exports.guardsFromCompiled=$e;exports.instantiate=tn;exports.instantiateLoose=V;exports.isScheme=O;exports.isSerializable=z;exports.join=Te;exports.joinAll=Xe;exports.lookup=P;exports.makeDiagnostic=E;exports.maxArgs=ye;exports.maxCallNesting=ue;exports.maxDepth=ce;exports.maxFunctionNesting=le;exports.maxNestingOf=_;exports.maxNodes=me;exports.memberCompletions=Vn;exports.memberDepth=pe;exports.normalizeUnion=k;exports.resolveNamed=un;exports.resolveScheme=pn;exports.resultType=fe;exports.rootScope=je;exports.s=i;exports.scopeAt=Wn;exports.scopeCompletions=qn;exports.substitute=N;exports.subtype=S;exports.typeAt=Un;exports.unify=x;exports.visibleNames=te;exports.withoutUndefined=q;
|
|
1
|
+
'use strict';var typeCore=require('@tslite/type-core'),core=require('@tslite/core'),capability=require('@tslite/capability'),codec=require('@tslite/codec');var $e=(e={})=>core.rootScope(e),T=(e,n)=>core.childScope(e,n),v=(e,n)=>core.lookup(e,n),pe=e=>core.visibleNames(e),wn=(e={},n={},t={},r={},s=new Set,a=new Set,o={})=>({scope:$e(e),types:n,schemes:t,accessors:r,asserters:s,matchers:a,modules:o}),En=(e,n)=>e.types[n],vn=(e,n)=>e.schemes[n];var Le={"unknown-name":"semantic","const-needs-init":"semantic","cannot-redeclare":"semantic","unknown-module":"semantic",unsupported:"semantic","forbidden-member":"semantic","not-assignable":"type","not-callable":"type","no-such-member":"type","not-object":"type","missing-argument":"type","excess-argument":"type","excess-property":"type","spread-argument":"type","props-mismatch":"type","no-matching-overload":"type","constraint-violation":"type","cast-unsound":"type","too-deep":"type","too-complex-union":"type","node-not-allowed":"capability","name-not-allowed":"capability","type-feature-not-allowed":"capability","any-not-allowed":"capability","too-large":"capability","wrong-result-type":"capability"},k=(e,n,t)=>({code:e,kind:Le[e],severity:"error",node:n,message:t}),B=(e,n,t,r="error")=>({code:e,kind:Le[e],severity:r,node:n,message:t}),S={notAssignable:(e,n,t,r={})=>{let s=typeCore.typeDiff(n,t,r).filter(o=>o.path.length>0),a=s.length?` ${typeCore.formatTypeDiff(s)}.`:"";return k("not-assignable",e,`Type '${typeCore.format(n)}' is not assignable to type '${typeCore.format(t)}'.${a}`)},unknownName:(e,n)=>k("unknown-name",e,`Cannot find name '${n}'.`),notCallable:(e,n)=>k("not-callable",e,`Type '${typeCore.format(n)}' is not callable.`),noSuchMember:(e,n,t)=>k("no-such-member",e,`Property '${t}' does not exist on type '${typeCore.format(n)}'.`),notObject:(e,n)=>k("not-object",e,`Type '${typeCore.format(n)}' has no members to access.`),constNeedsInit:e=>k("const-needs-init",e,"'const' declarations must be initialized."),missingArgument:(e,n,t)=>k("missing-argument",e,`Missing argument '${n}' of type '${typeCore.format(t)}'.`),unknownModule:(e,n)=>k("unknown-module",e,`Cannot find module '${n}' or its corresponding type declarations.`),cannotRedeclare:(e,n)=>k("cannot-redeclare",e,`Cannot redeclare block-scoped variable '${n}'.`),excessArgument:(e,n,t)=>k("excess-argument",e,`Expected ${n} argument${n===1?"":"s"}, but got ${t}.`),excessProperty:(e,n,t)=>k("excess-property",e,`Object literal may only specify known properties, and '${n}' does not exist in type '${typeCore.format(t)}'.`),spreadArgument:e=>k("spread-argument",e,"A spread argument must either have a tuple type or be passed to a rest parameter."),propsMismatch:(e,n,t)=>k("props-mismatch",e,`Payload is not compatible with the component props '${typeCore.format(n)}': ${t}.`),noMatchingOverload:(e,n,t)=>k("no-matching-overload",e,`No overload of '${typeCore.format(n)}' matches the arguments (${t.map(r=>typeCore.format(r)).join(", ")}).`),constraintViolation:(e,n,t,r)=>k("constraint-violation",e,`Type '${typeCore.format(t)}' does not satisfy the constraint '${n} extends ${typeCore.format(r)}'.`),unsupported:(e,n)=>k("unsupported",e,`${n} is not supported in this language.`),forbiddenMember:(e,n)=>k("forbidden-member",e,`'${n}' is not a member of the language \u2014 the JS runtime substrate (identity/inheritance) is not vocabulary here (FP / portable IR). Use a factory/operator via DI.`),castUnsound:(e,n,t)=>B("cast-unsound",e,`Conversion of type '${typeCore.format(n)}' to type '${typeCore.format(t)}' may be a mistake \u2014 neither sufficiently overlaps the other. Cast through 'unknown' first if intentional.`,"warning")};function Z(){let e=[];return {all:e,report(n){e.push(n);},hasErrors(){return e.some(n=>n.severity==="error")}}}function ce(e,n,t={}){return n.flatMap(r=>r(e,t))}function U(e,n){let t=r=>{n(r);for(let s of core.childrenOf(r))t(s);};t(e);}var Pn=e=>Array.isArray(e)?e:[e],Ve=["ArrowFunctionExpression","FunctionExpression","FunctionDeclaration"];function me(e,n="error"){return t=>{let r=[];return U(t,s=>{let a=capability.nodeViolation(s,e);a&&r.push(B("node-not-allowed",s,`'${a}' is not allowed by the capability profile.`,n));}),r}}function Ue(e,n="error"){let t=e.typeTier;return r=>{if(t==="author")return [];let s=[];return U(r,a=>{let o=a,i=o.type==="TSTypeAliasDeclaration"?o.id?.name:void 0;for(let l of [o.typeAnnotation,o.returnType]){if(!l)continue;let p=capability.typeFeatureViolations(typeCore.typeFeatures(l,i),t);p.length&&s.push(B("type-feature-not-allowed",a,`authoring type feature${p.length>1?"s":""} '${p.join("', '")}' requires capability tier 'author'.`,n));}}),s}}function N(e,n=new WeakSet){if(!e||typeof e!="object"||n.has(e))return false;switch(n.add(e),e.t){case "any":return true;case "object":return Object.values(e.props).some(t=>N(t.type,n))||!!e.index&&N(e.index.value,n);case "array":return N(e.items,n);case "tuple":return e.elements.some(t=>N(t,n));case "union":case "intersection":return e.of.some(t=>N(t,n));case "fn":return e.params.some(t=>N(t.type,n))||N(e.returns,n);case "overload":return e.signatures.some(t=>t.params.some(r=>N(r.type,n))||N(t.returns,n));case "keyof":return N(e.of,n);case "index":return N(e.obj,n)||N(e.key,n);case "mapped":return N(e.over,n)||N(e.body,n);case "conditional":return N(e.check,n)||N(e.extends,n)||N(e.then,n)||N(e.else,n);case "returnType":case "parameters":return N(e.fn,n);case "apply":return e.args.some(t=>N(t,n));default:return false}}function qe(e,n="error"){return t=>{if(!e.typeStrict)return [];let r=[];return U(t,s=>{let a=s;for(let o of [a.typeAnnotation,a.returnType])if(o&&N(o)){r.push(B("any-not-allowed",s,"'any' is not allowed under 'strict' \u2014 use 'unknown' + validated narrowing (assert/parse).",n));break}}),r}}function ye(e,n="error"){let t=new Set(e);return r=>{let s=[];return U(r,a=>{if(a.type!=="CallExpression")return;let o=a.callee;if(o.type!=="Identifier")s.push(B("name-not-allowed",o,"Only direct calls to allowed functions are permitted.",n));else {let i=o.name;t.has(i)||s.push(B("name-not-allowed",o,`Function '${i}' is not allowed here.`,n));}}),s}}function ee(e,n,t={}){let r=new Set(Pn(e)),s=t.severity??"error",a=[...r].join("/");return o=>{let i=[],l=(p,c)=>{let m=r.has(p.type),h=m?c+1:c;m&&h>n&&i.push(B("too-deep",p,`Nesting of ${a} exceeds ${n}${t.hint?` \u2014 ${t.hint}`:""}.`,s));for(let y of core.childrenOf(p))l(y,h);};return l(o,0),i}}var fe=(e=3,n="error")=>ee(Ve,e,{hint:"use a pipe instead of nesting functions",severity:n}),de=(e,n="error")=>ee("CallExpression",e,{hint:"use a pipe instead of nesting calls",severity:n}),he=(e,n="error")=>ee("MemberExpression",e,{severity:n});function ge(e,n="error"){return t=>{let r=[],s=(a,o)=>{if(o>e){r.push(B("too-deep",a,`Expression nesting exceeds ${e}.`,n));return}for(let i of core.childrenOf(a))s(i,o+1);};return s(t,0),r}}function Se(e,n="error"){return t=>{let r=0;return U(t,()=>{r++;}),r>e?[B("too-large",t,`Expression has ${r} nodes (max ${e}).`,n)]:[]}}function be(e,n="error"){return t=>{let r=[];return U(t,s=>{if(s.type==="CallExpression"){let a=s.arguments;a&&a.length>e&&r.push(B("too-large",s,`Call has ${a.length} arguments (max ${e}).`,n));}}),r}}function Ne(e,n={},t="error"){return (r,s)=>{let a=s.overlay?.get(r)?.type;return a?typeCore.subtype(a,e,n)?[]:[B("wrong-result-type",r,`Result type '${typeCore.format(a)}' is not assignable to the required '${typeCore.format(e)}'.`,t)]:[]}}function ne(e){let n=[me(e),Ue(e),qe(e)];return e.hostAllow!=="*"&&n.push(ye([...e.hostAllow])),n}function Fn(e){return ne(capability.compileProfile(e))}var J=e=>e.typeAnnotation,ke=e=>e.returnType,F=e=>e.type==="Identifier"?e.name:null,Ke=e=>{if(e.type==="VariableDeclaration"){let n=e.declarations[0];return n?F(n.id):null}return F(e)},z=e=>{if(e.computed)return null;let n=e.key;return n.type==="Identifier"?n.name:n.type==="Literal"?String(n.value??""):null};function _e(e){let n=r=>r&&r.type==="Literal"&&typeof r.value=="string"?r.value:null;if(e.length===1&&e[0].type==="ArrayExpression"){let r=[];for(let s of e[0].elements){let a=n(s);if(a===null)return null;r.push(a);}return r}let t=[];for(let r of e){let s=n(r);if(s===null)return null;t.push(s);}return t.length?t:null}function Be(e){if(e.type==="Identifier")return e.name;if(e.type==="MemberExpression"){let n=e;if(n.computed||n.property.type!=="Identifier")return null;let t=Be(n.object);return t===null?null:`${t}.${n.property.name}`}return null}function we(e){let n=e;if(n.regex||n.bigint)return typeCore.s.unknown;let t=n.value;return t===null?typeCore.s.null:t===void 0?typeCore.s.undefined:typeof t=="string"||typeof t=="number"||typeof t=="boolean"?{t:"literal",value:t,fresh:true}:typeCore.s.unknown}var q=e=>{let n=e.value;return n===null?typeCore.s.null:typeof n=="string"||typeof n=="number"||typeof n=="boolean"?typeCore.s.literal(n):we(e)},Ee=e=>e.type==="ArrowFunctionExpression",We=e=>e.t==="apply"&&e.name==="Promise"&&e.args.length===1,se=e=>We(e)?e.args[0]:e,X=e=>We(e)?e:typeCore.s.promise(e);function te(e){return e.t==="tuple"?true:e.t==="array"?te(e.items):e.t==="union"?e.of.some(te):false}function re(e){return e.t==="literal"?true:e.t==="union"?e.of.some(n=>re(n)):e.t==="var"?e.isConst===true||e.bound!==void 0&&re(e.bound):false}var j=(e,n)=>{let t=e;for(let r=0;r<50&&t.t==="apply";r++){let s=typeCore.expand1(t,n);if(s===t||s.t==="apply"&&s.name===t.name)break;t=s;}return t};function Je(e){let n=ke(e);return n?{t:"fn",params:e.params.map((r,s)=>({name:F(r)??`arg${s}`,type:J(r)??typeCore.s.unknown})),returns:e.async?X(n):n}:null}var M={then:{},else:{}},nn=new Set(["string","number","boolean","undefined","function","object"]),ze={string:typeCore.s.string,number:typeCore.s.number,boolean:typeCore.s.boolean,undefined:typeCore.s.undefined};function tn(e,n){switch(n){case "string":return e.t==="string"||e.t==="literal"&&typeof e.value=="string";case "number":return e.t==="number"||e.t==="literal"&&typeof e.value=="number";case "boolean":return e.t==="boolean"||e.t==="literal"&&typeof e.value=="boolean";case "undefined":return e.t==="undefined";case "function":return e.t==="fn"||e.t==="overload";case "object":return e.t==="object"||e.t==="array"||e.t==="tuple"||e.t==="null";default:return false}}var $n=typeCore.s.literal(true),Ln=typeCore.s.literal(false),x=e=>e.t==="union"?[...e.of]:e.t==="boolean"?[$n,Ln]:[e];function Xe(e,n){let t=e,r=n;return e.type==="UnaryExpression"&&t.operator==="typeof"&&t.argument.type==="Identifier"&&n.type==="Literal"&&typeof r.value=="string"?{name:t.argument.name,tag:r.value}:null}function Gn(e,n,t){if(e.t==="unknown"||e.t==="any")return n;let r=x(e).filter(s=>typeCore.subtype(s,n,t));return r.length?typeCore.normalizeUnion(r):n}function Vn(e,n,t){if(e.t==="unknown"||e.t==="any")return null;let r=x(e).filter(s=>!typeCore.subtype(s,n,t));return r.length?typeCore.normalizeUnion(r):null}function Un(e,n){if(!nn.has(n))return null;if(e.t==="unknown"||e.t==="any")return ze[n]??e;let t=x(e).filter(r=>tn(r,n));return t.length?typeCore.normalizeUnion(t):ze[n]??e}function qn(e,n){if(!nn.has(n)||e.t==="unknown"||e.t==="any")return null;let t=x(e).filter(r=>!tn(r,n));return t.length?typeCore.normalizeUnion(t):null}function Ye(e,n){if(e.type==="Identifier"&&n.type==="Literal"){let t=q(n);if(t.t==="literal"||t.t==="null")return {name:e.name,lit:t}}return null}function He(e,n){if(e.type==="MemberExpression"&&!e.computed&&!e.optional&&e.object.type==="Identifier"&&e.property.type==="Identifier"&&n.type==="Literal"){let t=q(n);if(t.t==="literal"||t.t==="null")return {name:e.object.name,prop:e.property.name,lit:t}}return null}function Qe(e,n,t,r,s){let a=x(e),o=l=>l.t==="object"?typeCore.ownProp(l.props,n)?.type:void 0,i=a.filter(l=>{let p=o(l);return r?!!p&&typeCore.subtype(t,p,s):!(p&&typeCore.subtype(p,t,s))});return i.length&&i.length<a.length?typeCore.normalizeUnion(i):null}function Ze(e,n,t){let r=x(e),s=o=>o.t==="object"&&(n in o.props||!!o.index),a=r.filter(o=>t?s(o):!s(o));return a.length&&a.length<r.length?typeCore.normalizeUnion(a):null}function Kn(e,n,t){return e.t==="unknown"||e.t==="any"||typeCore.subtype(n,e,t)?n:null}function _n(e,n,t){let r=x(e),s=r.filter(a=>!typeCore.equals(a,n,t));return s.length&&s.length<r.length?typeCore.normalizeUnion(s):null}var Wn=e=>e.t==="null"||e.t==="undefined",rn=e=>Wn(e)||e.t==="literal"&&!e.value,Jn=e=>{if(e.t==="unknown"||e.t==="any")return null;let n=x(e),t=n.filter(r=>!rn(r));return t.length&&t.length<n.length?typeCore.normalizeUnion(t):null},zn=e=>{let n=x(e),t=n.filter(rn);return t.length&&t.length<n.length?typeCore.normalizeUnion(t):null},en=e=>e.type==="Literal"&&e.value===null?"null":e.type==="Identifier"&&e.name==="undefined"?"undefined":null,O=(e,n,t)=>({then:n?{[e]:n}:{},else:t?{[e]:t}:{}}),Xn=e=>e==="==="||e==="=="||e==="!=="||e==="!=";function Q(e,n,t){if(e.type==="BinaryExpression"){let r=e;if(r.operator==="in"){let y=r.left,b=r.right;if(y.type==="Literal"&&typeof y.value=="string"&&b.type==="Identifier"){let g=b.name,E=v(n,g);if(!E)return M;let V=String(y.value);return O(g,Ze(E,V,true),Ze(E,V,false))}return M}if(!Xn(r.operator))return M;let s=r.operator==="!=="||r.operator==="!=",a=r.left,o=r.right,i=Xe(a,o)??Xe(o,a);if(i){let y=v(n,i.name);if(!y)return M;let b=Un(y,i.tag),g=qn(y,i.tag);return s?O(i.name,g,b):O(i.name,b,g)}let l=en(a),p=en(o),c=l?o:p?a:null;if((l||p)&&c?.type==="Identifier"){let y=c.name,b=v(n,y);if(!b)return M;let E=r.operator==="=="||r.operator==="!="?["null","undefined"]:[l??p],V=x(b),je=V.filter(le=>E.includes(le.t)),ie=V.filter(le=>!E.includes(le.t)),xe=je.length?typeCore.normalizeUnion(je):null,Me=ie.length&&ie.length<V.length?typeCore.normalizeUnion(ie):null;return s?O(y,Me,xe):O(y,xe,Me)}let m=Ye(a,o)??Ye(o,a);if(m){let y=v(n,m.name);if(!y)return M;let b=Kn(y,m.lit,t),g=_n(y,m.lit,t);return s?O(m.name,g,b):O(m.name,b,g)}let h=He(a,o)??He(o,a);if(h){let y=v(n,h.name);if(!y)return M;let b=Qe(y,h.prop,h.lit,true,t),g=Qe(y,h.prop,h.lit,false,t);return s?O(h.name,g,b):O(h.name,b,g)}return M}if(e.type==="UnaryExpression"&&e.operator==="!"){let r=Q(e.argument,n,t);return {then:r.else,else:r.then}}if(e.type==="CallExpression"){let r=Hn(e,n,t);if(r)return r}if(e.type==="Identifier"){let r=e.name,s=v(n,r);if(s)return O(r,Jn(s),zn(s))}return M}function Yn(e,n){if(e.t==="fn")return e.guard??null;if(e.t==="overload"){for(let t of e.signatures)if(t.guard&&t.params.length===n)return t.guard}return null}function Hn(e,n,t){let r=e.callee;if(r.type!=="Identifier")return null;let s=v(n,r.name);if(!s)return null;let a=Yn(s,e.arguments.length);if(!a)return null;let o=e.arguments[a.param];if(!o||o.type!=="Identifier")return null;let i=o.name,l=v(n,i);return l?O(i,Gn(l,a.type,t),Vn(l,a.type,t)):null}var _=(e,n)=>Object.keys(n).length?T(e,n):e;function Y(e){switch(e.type){case "ReturnStatement":case "ThrowStatement":return true;case "BlockStatement":{let n=e.body;return n.length>0&&Y(n[n.length-1])}case "IfStatement":{let n=e;return !!n.alternate&&Y(n.consequent)&&Y(n.alternate)}default:return false}}var yt=e=>{let n={};for(let t of Object.keys(e))n[t]={params:[],body:e[t]};return n};function ft(e){let n=[];return e.maxDepth!==void 0&&n.push(ge(e.maxDepth)),e.maxNodes!==void 0&&n.push(Se(e.maxNodes)),e.maxArgs!==void 0&&n.push(be(e.maxArgs)),e.maxFunctionNesting!==void 0&&n.push(fe(e.maxFunctionNesting)),e.maxCallNesting!==void 0&&n.push(de(e.maxCallNesting)),e.memberDepth!==void 0&&n.push(he(e.memberDepth)),n}function cn(e,n,t={}){let r={...yt(n.types),...n.schemes,...ht(e)},s={overlay:new WeakMap,sink:Z(),env:n,schemes:r,importNames:new Set},a=t.profile?capability.compileProfile(t.profile):void 0;a&&typeCore.configureTypeLimits(a.typeLimits);try{let o,i=gt(e,s);try{o=f(e,i,s);}catch(c){if(c instanceof typeCore.TypeEvalLimitError)s.sink.report(B("too-deep",e,c.message));else if(c instanceof typeCore.UnionTooComplexError)s.sink.report(B("too-complex-union",e,c.message));else throw c;o=typeCore.s.unknown;}let l=[];a&&l.push(...ne(a)),t.limits&&l.push(...ft(t.limits)),t.resultType&&l.push(Ne(t.resultType,r));let p=l.length?[...s.sink.all,...ce(e,l,{overlay:s.overlay})]:s.sink.all;return {type:o,overlay:s.overlay,diagnostics:p}}finally{a&&typeCore.resetTypeLimits();}}function dt(e,n,t={}){let r=cn(e,n,t),s={},a=new Map,o,i=p=>{let c=[];if(p.type==="VariableDeclaration")for(let m of p.declarations){let h=F(m.id),y=r.overlay.get(m);h&&y&&(s[h]=y.type,c.push(h));}else if(p.type==="FunctionDeclaration"){let m=p.id?.name,h=r.overlay.get(p);m&&h&&(s[m]=h.type,c.push(m));}return c};for(let p of e.body??[])if(p.type==="VariableDeclaration"||p.type==="FunctionDeclaration")i(p);else if(p.type==="ExportNamedDeclaration"){let c=p;if(c.declaration)for(let m of i(c.declaration))a.set(m,m);else for(let m of c.specifiers)a.set(m.exported.name,m.local.name);}else if(p.type==="ExportDefaultDeclaration"){let c=r.overlay.get(p.declaration);o=c?c.type:typeCore.s.unknown;}let l={};if(a.size||o!==void 0){for(let[p,c]of a)s[c]&&(l[p]={type:s[c]});o!==void 0&&(l.default={type:o});}else for(let p in s)l[p]={type:s[p]};return {type:{t:"object",props:l},diagnostics:r.diagnostics}}var ht=e=>{let n={};return core.walk(e,{TSTypeAliasDeclaration(t){let r=t;r.id?.name&&r.typeAnnotation&&(n[r.id.name]={params:r.typeParameters??[],body:r.typeAnnotation});}}),n};function gt(e,n){let t=n.env.modules,r={};core.walk(e,{ImportDeclaration(s){let a=s,o=a.source.value,i=typeof o=="string"?t?.[o]:void 0;if(!i){n.sink.report(S.unknownModule(a.source,String(o)));for(let l of a.specifiers)r[l.local.name]=typeCore.s.unknown;return}for(let l of a.specifiers){let p=l.local.name;if(p in r){n.sink.report(S.cannotRedeclare(l.local,p));continue}if(l.type==="ImportNamespaceSpecifier"){r[p]=i;continue}let c=l.type==="ImportSpecifier"?l.imported.name:"default",m=typeCore.discover(i,[c],n.schemes);m?r[p]=m.type:(n.sink.report(S.noSuchMember(l,i,c)),r[p]=typeCore.s.unknown);}}});for(let s in r)n.importNames.add(s);return Object.keys(r).length?T(n.env.scope,r):n.env.scope}var d=(e,n,t,r)=>(e.overlay.set(n,{type:t,scope:r}),t);function f(e,n,t,r){switch(e.type){case mn:return e.schema;case "JSXElement":case "JSXFragment":return d(t,e,f(core.desugarJSX(e,{emptyPropsAsObject:true}),n,t),n);case "Literal":return d(t,e,we(e),n);case "Identifier":{let s=e.name,a=v(n,s);return a===void 0?s==="undefined"?d(t,e,typeCore.s.undefined,n):(t.sink.report(S.unknownName(e,s)),d(t,e,typeCore.s.unknown,n)):d(t,e,a,n)}case "MemberExpression":return d(t,e,Nt(e,n,t),n);case "CallExpression":return d(t,e,Et(e,n,t,r),n);case "ArrowFunctionExpression":return Oe(e,n,t);case "FunctionDeclaration":return t.sink.report(S.unsupported(e,"function declaration (use 'const fn = () => \u2026')")),d(t,e,typeCore.s.unknown,n);case "FunctionExpression":return t.sink.report(S.unsupported(e,"anonymous function (use an arrow)")),d(t,e,typeCore.s.unknown,n);case "ThisExpression":return t.sink.report(S.unsupported(e,"'this'")),d(t,e,typeCore.s.unknown,n);case "BlockStatement":return d(t,e,Pe(e,n,t),n);case "ReturnStatement":{let s=e.argument;return d(t,e,s?f(s,n,t):typeCore.s.unknown,n)}case "IfStatement":return I(e,n,t),t.overlay.get(e)?.type??typeCore.s.unknown;case "ForStatement":case "WhileStatement":case "DoWhileStatement":case "ForOfStatement":case "ForInStatement":case "BreakStatement":case "ContinueStatement":case "ThrowStatement":case "TryStatement":case "SwitchStatement":return I(e,n,t),t.overlay.get(e)?.type??typeCore.s.unknown;case "AssignmentExpression":{let s=e;return f(s.left,n,t),d(t,e,f(s.right,n,t),n)}case "UpdateExpression":return f(e.argument,n,t),d(t,e,typeCore.s.number,n);case "ExpressionStatement":return d(t,e,f(e.expression,n,t),n);case "VariableDeclaration":return ae(e,n,t),d(t,e,typeCore.s.unknown,n);case "TSTypeAliasDeclaration":return d(t,e,typeCore.s.unknown,n);case "BinaryExpression":return d(t,e,xt(e,n,t),n);case "LogicalExpression":{let s=e,a=f(s.left,n,t),o=f(s.right,n,t);return d(t,e,Mt(s.operator,a,o),n)}case "UnaryExpression":return d(t,e,Gt(e,n,t),n);case "ConditionalExpression":{let s=e;f(s.test,n,t);let a=Q(s.test,n,t.schemes),o=f(s.consequent,_(n,a.then),t),i=f(s.alternate,_(n,a.else),t);return d(t,e,typeCore.normalizeUnion([o,i]),n)}case "ObjectExpression":return d(t,e,Vt(e,n,t),n);case "ArrayExpression":return d(t,e,gn(e,n,t),n);case "TemplateLiteral":{for(let s of e.expressions)f(s,n,t);return d(t,e,typeCore.s.string,n)}case "AwaitExpression":{let s=e.argument,a=s?f(s,n,t):typeCore.s.unknown;return d(t,e,se(a),n)}case "Program":return Ie(e.body,n,t,new Set(t.importNames)),d(t,e,typeCore.s.unknown,n);case "JsonExpression":return d(t,e,Ce(e.body,n,t,e),n);case "ChainExpression":return d(t,e,typeCore.normalizeUnion([f(e.expression,n,t),typeCore.s.undefined]),n);case "TSAsExpression":{let s=e,a=f(s.expression,n,t),o=s.typeAnnotation;return !typeCore.subtype(a,o,t.schemes)&&!typeCore.subtype(o,a,t.schemes)&&t.sink.report(S.castUnsound(e,a,o)),d(t,e,o,n)}default:return t.sink.report(S.unsupported(e,`'${e.type}'`)),d(t,e,typeCore.s.unknown,n)}}var St=new Set(["constructor","prototype","__proto__"]);function bt(e){if(!e.computed)return e.property.type==="Identifier"?e.property.name:null;let n=e.property;if(n.type==="Literal"){let t=n.value;if(typeof t=="string")return t}return null}function Nt(e,n,t){let r=f(e.object,n,t),s=bt(e);if(s!==null&&St.has(s))return t.sink.report(S.forbiddenMember(e,s)),typeCore.s.unknown;if(e.computed){let i=f(e.property,n,t),l=typeCore.resolveTypeOp(typeCore.s.index(r,i));return l.t!=="index"?l:(i.t==="literal"&&typeof i.value=="string"&&an(e,r,i.value,t),typeCore.s.unknown)}let a=e.property.name,o=typeCore.discover(r,[a],t.schemes);return o?o.type:(an(e,r,a,t),typeCore.s.unknown)}function an(e,n,t,r){let s=typeCore.isScheme(n,r.schemes)?typeCore.expand1(n,r.schemes):n;s.t==="object"||s.t==="array"||s.t==="tuple"||s.t==="union"?r.sink.report(S.noSuchMember(e,n,t)):s.t!=="any"&&s.t!=="unknown"&&r.sink.report(S.notObject(e,n));}function kt(e,n,t){if(!e||e.type!=="Identifier")return;let r=e.name;if(v(n,r)===void 0)return;let s=t.schemes[r];return s&&s.params.length===0?s.body:void 0}function Bt(e,n,t,r){let s=j(f(n[0],t,r),r.schemes),o=(s.t==="fn"?s:s.t==="overload"?s.signatures[0]:void 0)?.params[0]?.type,i=n.length>1?f(n[1],t,r):typeCore.s.undefined;if(o){let l=typeCore.typeDiff(i,o,r.schemes);l.length&&r.sink.report(S.propsMismatch(n[1]??e,o,typeCore.formatTypeDiff(l)));}return d(r,e,typeCore.s.boolean,t)}var mn="TSLiteSyntheticArg",wt=e=>({type:mn,schema:e});function yn(e,n,t){if(!e.some(a=>a.type==="SpreadElement"))return {nodes:[...e],spread:null};let r=[],s=null;for(let a of e){if(a.type!=="SpreadElement"){r.push(a);continue}let o=a.argument;if(o.type==="ArrayExpression"&&o.elements.every(l=>l&&l.type!=="SpreadElement")){for(let l of o.elements)r.push(l);continue}let i=j(f(o,n,t),t.schemes);if(i.t==="tuple")for(let l of i.elements)r.push(wt(l));else s={elem:i.t==="array"?i.items:typeCore.s.unknown,node:a};}return {nodes:r,spread:s}}function Et(e,n,t,r){let s=e.arguments,a=Be(e.callee);if(a){let p=t.env.accessors?.[a];if(p){let c=_e(s);if(c){let m=typeCore.discover(p,c,t.schemes);return m?m.type:(t.sink.report(S.noSuchMember(e,p,c.join("."))),typeCore.s.unknown)}return s.forEach(m=>f(m,n,t)),typeCore.s.unknown}}if(a&&t.env.asserters?.has(a)){let p=kt(s[0],n,t);for(let c=1;c<s.length;c++)f(s[c],n,t);return p??typeCore.s.unknown}if(a&&t.env.matchers?.has(a))return Bt(e,s,n,t);let o=f(e.callee,n,t);if(o.t==="any")return s.forEach(p=>f(p,n,t)),typeCore.s.any;if(o.t==="overload")return At(e,o,n,t,r);if(o.t!=="fn")return s.forEach(p=>f(p,n,t)),t.sink.report(S.notCallable(e,o)),typeCore.s.unknown;let i=yn(s,n,t),l=i.nodes.map(p=>fn(p,n,t));return dn(e,o,i.nodes,l,n,t,i.spread,r)}function fn(e,n,t){if(Ee(e))return typeCore.s.any;if(e.type!=="CallExpression")return f(e,n,t);let r=Z(),s=f(e,n,{...t,sink:r});return r.hasErrors()?typeCore.s.any:(r.all.forEach(a=>t.sink.report(a)),s)}function dn(e,n,t,r,s,a,o=null,i){let l=m=>{if(!i)return m;let h=typeCore.substitute(n.returns,m);if(h.t==="fn"&&i.t==="fn"){let y=m,b=Math.min(h.params.length,i.params.length);for(let g=0;g<b;g++)y=typeCore.unify(h.params[g].type,i.params[g].type,y)??y;return typeCore.unify(h.returns,i.returns,y)??y}return typeCore.unify(h,i,m)??m},p=l(typeCore.instantiateLoose(n,r).bindings);t.forEach((m,h)=>{if(Ee(m)){let y=typeCore.widenType(typeCore.substitute(n.params[h]?.type??typeCore.s.any,p));r[h]=Oe(m,s,a,y);}else if(m.type==="CallExpression"&&r[h].t==="any")r[h]=f(m,s,a,typeCore.substitute(n.params[h]?.type??typeCore.s.unknown,p));else if(m.type==="Literal"){let y=n.params[h]?.type??typeCore.s.unknown,b=y.t==="var"?y.bound?typeCore.substitute(y.bound,p):y:typeCore.substitute(y,p);re(b)&&(r[h]=d(a,m,q(m),s));}else if(m.type==="ArrayExpression"){let y=typeCore.substitute(n.params[h]?.type??typeCore.s.unknown,p);te(y)&&(r[h]=Sn(m,y,s,a));}});let c=l(typeCore.instantiateLoose(n,r).bindings);return Dt(e,n,c,a),Ot(e,n,r,c,a,t,o),t.forEach((m,h)=>{let y=n.params[h];m.type==="ObjectExpression"&&y&&!y.variadic&&Fe(m,typeCore.substitute(y.type,c),a);}),typeCore.widenInferred(typeCore.groundVars(typeCore.substitute(n.returns,c),a.schemes))}var on=new WeakMap;function vt(e){let n=on.get(e);if(n)return n;let t=new Map,r=new WeakSet;for(let s of e.params)w(s.type,t,r);return w(e.returns,t,r),on.set(e,t),t}function w(e,n,t){switch(e.t){case "var":e.bound&&!n.has(e.name)&&n.set(e.name,e.bound);return;case "array":w(e.items,n,t);return;case "union":for(let r of e.of)w(r,n,t);return;case "object":if(t.has(e))return;t.add(e);for(let r in e.props)w(e.props[r].type,n,t);return;case "fn":if(t.has(e))return;t.add(e);for(let r of e.params)w(r.type,n,t);w(e.returns,n,t);return;case "overload":for(let r of e.signatures){for(let s of r.params)w(s.type,n,t);w(r.returns,n,t);}return;case "apply":for(let r of e.args)w(r,n,t);return;case "keyof":w(e.of,n,t);return;case "index":w(e.obj,n,t),w(e.key,n,t);return;case "mapped":w(e.over,n,t),w(e.body,n,t);return;default:return}}function Dt(e,n,t,r){let s=vt(n);if(s.size!==0)for(let[a,o]of s){let i=t[a];if(!i)continue;let l=typeCore.substitute(o,t);typeCore.subtype(i,l,r.schemes)||r.sink.report(S.constraintViolation(e,a,i,l));}}function At(e,n,t,r,s){let a=yn(e.arguments,t,r),o=a.nodes,i=o.map(c=>fn(c,t,r)),l=c=>a.spread?Ct(c,o.length):Tt(c,o.length),p=n.signatures.find(c=>l(c)&&Rt(c,i,r));if(!p){let c=n.signatures.filter(l);c.length===1?p=c[0]:n.signatures.length===1&&(p=n.signatures[0]);}return p?dn(e,p,o,i,t,r,a.spread,s):(r.sink.report(S.noMatchingOverload(e,n,i)),typeCore.s.unknown)}function Ct(e,n){let t=0,r=false;for(let s of e.params)s.variadic?r=true:s.optional||t++;return n>=t&&(r||n<e.params.length)}function Tt(e,n){let t=0;for(let r of e.params){if(r.variadic)return n>=t;r.optional||t++;}return n>=t&&n<=e.params.length}function Rt(e,n,t){let{bindings:r}=typeCore.instantiateLoose(e,n);for(let s=0;s<e.params.length;s++){let a=e.params[s];if(a.variadic)return true;if(s>=n.length){if(!a.optional)return false;continue}if(!typeCore.subtype(n[s],typeCore.substitute(a.type,r),t.schemes))return false}return true}function Ot(e,n,t,r,s,a=e.arguments??[],o=null){let i=p=>a[p]??e;for(let p=0;p<n.params.length;p++){let c=n.params[p];if(c.variadic)break;let m=typeCore.substitute(c.type,r);if(p>=t.length){!c.optional&&!o&&s.sink.report(S.missingArgument(e,c.name,m));continue}typeCore.subtype(t[p],m,s.schemes)||s.sink.report(S.notAssignable(i(p),t[p],m,s.schemes));}let l=n.params.find(p=>p.variadic);if(o){let p=t.length,c=n.params.filter(m=>!m.optional&&!m.variadic).length;if(!(p>=c&&(l||p<n.params.length))){s.sink.report(S.spreadArgument(o.node));return}if(l){let m=typeCore.substitute(l.type,r),h=m.t==="array"?m.items:typeCore.s.unknown;typeCore.subtype(o.elem,h,s.schemes)||s.sink.report(S.notAssignable(o.node,o.elem,h,s.schemes));}return}!l&&t.length>n.params.length&&s.sink.report(S.excessArgument(i(n.params.length),n.params.length,t.length));}function L(e,n,t,r){let s=j(n,r.schemes);switch(e.type){case "Literal":{let o=q(e);return typeCore.subtype(o,n,r.schemes)||r.sink.report(S.notAssignable(e,o,n,r.schemes)),d(r,e,n,t)}case "ArrayExpression":{if(s.t==="array"){for(let o of e.elements){if(!o)continue;let i=o;i.type==="SpreadElement"?L(i.argument,n,t,r):L(i,s.items,t,r);}return d(r,e,n,t)}break}case "ObjectExpression":{if(s.t==="object"){let o={};for(let l of e.properties){let p=l;if(p.type==="SpreadElement"){f(p.argument,t,r);continue}let c=p,m=z(c),h=m!==null?typeCore.ownProp(s.props,m)?.type:void 0,y=h?L(c.value,h,t,r):f(c.value,t,r);m!==null&&(o[m]={type:y}),d(r,p,y,t);}let i={t:"object",props:o};return typeCore.subtype(i,n,r.schemes)||r.sink.report(S.notAssignable(e,i,n,r.schemes)),d(r,e,n,t)}break}case "ArrowFunctionExpression":{if(s.t==="fn"){let o=Oe(e,t,r,s);return typeCore.subtype(o,n,r.schemes)||r.sink.report(S.notAssignable(e,o,n,r.schemes)),d(r,e,n,t)}break}case "ConditionalExpression":{let o=e;return f(o.test,t,r),L(o.consequent,n,t,r),L(o.alternate,n,t,r),d(r,e,n,t)}}let a=f(e,t,r);return typeCore.subtype(a,n,r.schemes)||r.sink.report(S.notAssignable(e,a,n,r.schemes)),d(r,e,a,t)}function Oe(e,n,t,r){let s=r&&r.t==="fn"?r:void 0,a={},o=e.params.map((h,y)=>{let b=h,g=F(b),E=J(b)??s?.params[y]?.type??typeCore.s.unknown;return g?a[g]=E:b.type!=="Identifier"&&G(b,E,a,n,t),t.overlay.set(b,{type:E,scope:n}),{name:g??`arg${y}`,type:E}}),i=T(n,a),l=e.body,p=ke(e);if(l.type!=="BlockStatement"&&p){let h=e.async?se(p):p;L(l,h,i,t);let y=e.async?X(p):p;return d(t,e,{t:"fn",params:o,returns:y},n)}let c=l.type==="BlockStatement"?d(t,l,Pe(l,i,t,new Set(Object.keys(a))),i):f(l,i,t),m=e.async?X(c):c;if(p){let h=e.async?se(p):p,y=e.async?c:m;typeCore.subtype(y,h,t.schemes)||t.sink.report(S.notAssignable(l,m,p,t.schemes));let b=e.async?X(p):p;return d(t,e,{t:"fn",params:o,returns:b},n)}return d(t,e,{t:"fn",params:o,returns:typeCore.widenType(m)},n)}function W(e){switch(e.type){case "Identifier":return [e];case "ObjectPattern":return e.properties.flatMap(n=>n.type==="RestElement"?W(n.argument):W(n.value));case "ArrayPattern":return e.elements.flatMap(n=>n?n.type==="RestElement"?W(n.argument):W(n):[]);case "AssignmentPattern":return W(e.left);default:return []}}function hn(e){if(e.type==="VariableDeclaration")return e.declarations.flatMap(n=>W(n.id));if(e.type==="FunctionDeclaration"){let n=e.id;return n?[n]:[]}return e.type==="ExportNamedDeclaration"&&e.declaration?hn(e.declaration):[]}function Pe(e,n,t,r=new Set){let{returns:s}=Ie(e.body,n,t,r);return s.length?typeCore.normalizeUnion(s):typeCore.s.unknown}function Ie(e,n,t,r=new Set){let s=n,a=[];for(let o of e){let i=o;for(let l of hn(i))r.has(l.name)?t.sink.report(S.cannotRedeclare(l,l.name)):r.add(l.name);if(i.type==="VariableDeclaration")s=ae(i,s,t);else if(i.type!=="ImportDeclaration")if(i.type==="ExportNamedDeclaration"){let l=i;if(l.declaration?.type==="VariableDeclaration")s=ae(l.declaration,s,t);else if(l.declaration?.type==="FunctionDeclaration"){let p=f(l.declaration,s,t),c=F(l.declaration.id);c&&(s=T(s,{[c]:p}));}else for(let p of l.specifiers)v(s,p.local.name)===void 0&&t.sink.report(S.unknownName(p.local,p.local.name));}else if(i.type==="ExportDefaultDeclaration")f(i.declaration,s,t);else if(i.type==="FunctionDeclaration"){let l=f(i,s,t),p=F(i.id);p&&(s=T(s,{[p]:l}));}else if(i.type==="IfStatement"){a.push(...I(i,s,t));let l=i;!l.alternate&&Y(l.consequent)&&(s=_(s,Q(l.test,s,t.schemes).else));}else a.push(...I(i,s,t));}return {scope:s,returns:a}}function I(e,n,t){switch(e.type){case "ReturnStatement":{let r=e.argument,s=r?f(r,n,t):typeCore.s.unknown;return d(t,e,s,n),[s]}case "IfStatement":{let r=e;f(r.test,n,t);let s=Q(r.test,n,t.schemes),a=I(r.consequent,_(n,s.then),t);return r.alternate&&a.push(...I(r.alternate,_(n,s.else),t)),d(t,e,typeCore.s.unknown,n),a}case "BlockStatement":{let r=Pe(e,n,t);return d(t,e,r,n),r.t==="unknown"?[]:[r]}case "ForStatement":case "WhileStatement":case "DoWhileStatement":{let r=e,s=n;r.init&&(r.init.type==="VariableDeclaration"?s=ae(r.init,s,t):f(r.init,s,t)),r.test&&f(r.test,s,t),r.update&&f(r.update,s,t);let a=I(r.body,s,t);return d(t,e,typeCore.s.unknown,n),a}case "ForOfStatement":case "ForInStatement":{let r=e,s=f(r.right,n,t),a=e.type==="ForOfStatement"?s.t==="array"?s.items:typeCore.s.unknown:typeCore.s.string,o=Ke(r.left),i=o?T(n,{[o]:a}):n,l=I(r.body,i,t);return d(t,e,typeCore.s.unknown,n),l}case "BreakStatement":case "ContinueStatement":return d(t,e,typeCore.s.unknown,n),[];case "ThrowStatement":{let r=e.argument;return r&&f(r,n,t),d(t,e,typeCore.s.unknown,n),[]}case "TryStatement":{let r=e,s=I(r.block,n,t);if(r.handler){let a=r.handler.param,o=a?F(a):null,i=o?T(n,{[o]:typeCore.s.unknown}):n;s.push(...I(r.handler.body,i,t));}return r.finalizer&&s.push(...I(r.finalizer,n,t)),d(t,e,typeCore.s.unknown,n),s}case "SwitchStatement":{let r=e;f(r.discriminant,n,t);let s=n,a=[];for(let o of r.cases){o.test&&f(o.test,s,t);let i=Ie(o.consequent,s,t);s=i.scope,a.push(...i.returns);}return d(t,e,typeCore.s.unknown,n),a}default:return f(e,n,t),[]}}function Pt(e,n,t){let r=typeCore.discover(e,[n],t.schemes);return r?r.type:typeCore.s.unknown}function It(e,n){let t=typeCore.resolveTypeOp(typeCore.s.index(e,typeCore.s.literal(n)));return t.t==="index"?typeCore.s.unknown:t}function Ft(e,n){if(e.t!=="object")return e;let t={};for(let r in e.props)n.includes(r)||(t[r]=e.props[r]);return typeCore.s.object(t,e.index)}function jt(e,n){return e.t==="tuple"?typeCore.s.tuple(e.elements.slice(n)):e.t==="array"?e:typeCore.s.array(typeCore.s.unknown)}function G(e,n,t,r,s){switch(e.type){case "Identifier":{let a=J(e)??n;t[e.name]=a,s.overlay.set(e,{type:a,scope:r});return}case "AssignmentPattern":{let a=e,o=typeCore.widenType(f(a.right,r,s)),{type:i}=typeCore.withoutUndefined(n),l=i.t==="unknown"?o:typeCore.normalizeUnion([i,o]);G(a.left,l,t,r,s);return}case "ObjectPattern":{let a=[];for(let o of e.properties){if(o.type==="RestElement"){G(o.argument,Ft(n,a),t,r,s);continue}let i=o,l=z(i);l!=null&&a.push(l);let p=l!=null?Pt(n,l,s):typeCore.s.unknown;G(i.value,p,t,r,s);}return}case "ArrayPattern":{e.elements.forEach((a,o)=>{if(!a)return;let i=a;i.type==="RestElement"?G(i.argument,jt(n,o),t,r,s):G(i,It(n,o),t,r,s);});return}}}function Fe(e,n,t){let r=j(n,t.schemes),a=(r.t==="union"?r.of.map(o=>j(o,t.schemes)):[r]).filter(o=>o.t==="object"&&!o.index);if(a.length&&!a.some(o=>Object.keys(o.props).length===0))for(let o of e.properties){if(o.type==="SpreadElement")continue;let i=o;if(i.computed)continue;let l=z(i);if(l===null)continue;let p=a.filter(c=>l in c.props);if(!p.length){t.sink.report(S.excessProperty(i.key,l,n));continue}i.value.type==="ObjectExpression"&&Fe(i.value,p[0].props[l].type,t);}}function ae(e,n,t){let r={};for(let s of e.declarations){let a=s.id,o=F(a),i=J(a);if(!s.init){t.sink.report(S.constNeedsInit(s)),o&&(r[o]=i??typeCore.s.unknown);continue}let l=i??(s.init.type==="ArrowFunctionExpression"?Je(s.init):null),p=o&&l?T(n,{[o]:l}):n,c;i?(L(s.init,i,p,t),s.init.type==="ObjectExpression"&&Fe(s.init,i,t),c=i):c=f(s.init,p,t),d(t,s,c,n),o?r[o]=c:G(a,c,r,n,t);}return d(t,e,typeCore.s.unknown,n),T(n,r)}function xt(e,n,t){let r=f(e.left,n,t),s=f(e.right,n,t),a=e.operator;return a==="+"?typeCore.subtype(r,typeCore.s.string)||typeCore.subtype(s,typeCore.s.string)?typeCore.s.string:typeCore.s.number:$t.has(a)?typeCore.s.number:typeCore.s.boolean}var ln={string:typeCore.s.literal(""),number:typeCore.s.literal(0),boolean:typeCore.s.literal(false)},De=e=>e.t==="null"||e.t==="undefined";function Mt(e,n,t){if(n.t==="any"||n.t==="unknown")return typeCore.normalizeUnion([n,t]);let r=n.t==="union"?[...n.of]:n.t==="boolean"?[typeCore.s.literal(true),typeCore.s.literal(false)]:[n];if(e==="??")return typeCore.normalizeUnion([...r.filter(a=>!De(a)),t]);if(e==="||")return typeCore.normalizeUnion([...r.filter(a=>!De(a)&&!(a.t==="literal"&&!a.value)),t]);let s=r.flatMap(a=>De(a)?[a]:a.t==="literal"?a.value?[]:[a]:ln[a.t]?[ln[a.t]]:[]);return typeCore.normalizeUnion([...s,t])}var $t=new Set(["-","*","/","%","**","&","|","^","<<",">>",">>>"]),Lt=typeCore.s.union(["string","number","bigint","boolean","symbol","undefined","object","function"].map(e=>typeCore.s.literal(e)));function Gt(e,n,t){let r=f(e.argument,n,t);switch(e.operator){case "!":return r.t==="literal"?{t:"literal",value:!r.value,fresh:true}:typeCore.s.boolean;case "-":return r.t==="literal"&&typeof r.value=="number"?{t:"literal",value:-r.value,fresh:true}:typeCore.s.number;case "+":case "~":return typeCore.s.number;case "typeof":return Lt;case "delete":return typeCore.s.boolean;case "void":return typeCore.s.undefined;default:return typeCore.s.unknown}}function Vt(e,n,t){let r={},s,a=[],o=[],i=false,l=false;for(let p of e.properties){let c=p;if(c.type==="SpreadElement"){let g=j(f(c.argument,n,t),t.schemes);if(g.t==="object"){for(let E in g.props)r[E]=g.props[E];g.index&&(s={key:g.index.key,type:g.index.value});}continue}let m=c,h=f(m.value,n,t),y=typeCore.widen(h);if(d(t,c,h,n),m.computed){let g=j(f(m.key,n,t),t.schemes);g.t==="literal"&&typeof g.value=="string"?(r[g.value]={type:y},a.push(y)):g.t==="literal"&&typeof g.value=="number"?(r[String(g.value)]={type:y},a.push(y),o.push(y)):g.t==="string"?(i=true,a.push(y)):g.t==="number"&&(l=true,a.push(y),o.push(y));continue}let b=z(m);b!==null&&(r[b]={type:y},a.push(y),/^\d+$/.test(b)&&o.push(y));}return i?s={key:"string",type:typeCore.normalizeUnion(a)}:l&&(s={key:"number",type:typeCore.normalizeUnion(o)}),s?{t:"object",props:r,index:{key:s.key,value:s.type}}:{t:"object",props:r}}function gn(e,n,t){let r=[];for(let s of e.elements){if(!s)continue;let a=s;if(a.type==="SpreadElement"){let o=j(f(a.argument,n,t),t.schemes);o.t==="array"?r.push(o.items):o.t==="tuple"&&r.push(...o.elements);continue}r.push(typeCore.widen(f(a,n,t)));}return typeCore.s.array(r.length?typeCore.normalizeUnion(r):typeCore.s.unknown)}function Sn(e,n,t,r){let s=j(n,r.schemes),a=e.elements,o=a.every(l=>l&&l.type!=="SpreadElement"),i=(l,p)=>l.type==="ArrayExpression"?Sn(l,p,t,r):typeCore.widen(f(l,t,r));if(s.t==="tuple"&&o&&a.length===s.elements.length){let l=a.map((p,c)=>i(p,s.elements[c]));return d(r,e,{t:"tuple",elements:l},t)}if(s.t==="array"){let l=[];for(let p of a){if(!p)continue;let c=p;if(c.type==="SpreadElement"){f(c.argument,t,r);continue}l.push(i(c,s.items));}return d(r,e,typeCore.s.array(l.length?typeCore.normalizeUnion(l):typeCore.s.unknown),t)}return gn(e,t,r)}function Ce(e,n,t,r){if(e===null)return typeCore.s.null;switch(typeof e){case "string":return typeCore.s.string;case "number":return typeCore.s.number;case "boolean":return typeCore.s.boolean;case "object":break;default:return typeCore.s.unknown}if(Array.isArray(e)){let o=e.map(i=>Ce(i,n,t,r));return typeCore.s.array(o.length?typeCore.normalizeUnion(o):typeCore.s.unknown)}let s=e;if(core.AST_MARKER in s){let o;try{o=codec.fromJson(s);}catch{return t.sink.report(S.unsupported(r,`'#ast: ${String(s[core.AST_MARKER])}'`)),typeCore.s.unknown}return f(o,n,t)}let a={};for(let o of Object.keys(s))a[o]={type:Ce(s[o],n,t,r)};return {t:"object",props:a}}var Ut=(e,n)=>({...e,typeAnnotation:n}),qt=(e,n)=>({...e,returnType:n}),Kt=(e,n)=>({type:"TSAsExpression",expression:e,typeAnnotation:n});function Wt(e,n){return e.get(n)?.type}function Jt(e,n){return e.get(n)?.scope}function zt(e,n){let t=e.get(n)?.type;return t?typeCore.discover(t,[])?.completions??[]:[]}function Xt(e,n){let t=e.get(n)?.scope;return t?[...pe(t)].map(([r,s])=>({key:r,type:s,optional:false})):[]}function Yt(e,n){return e.filter(t=>t.node===n)}exports.FUNCTION_KINDS=Ve;exports.annotate=Ut;exports.annotateReturn=qt;exports.asExpression=Kt;exports.calleeAllowlist=ye;exports.capabilityNodes=me;exports.check=cn;exports.childScope=T;exports.createEnv=wn;exports.createSink=Z;exports.diag=S;exports.diagnosticsAt=Yt;exports.extractModuleType=dt;exports.fromCapability=Fn;exports.guard=ce;exports.guardsFromCompiled=ne;exports.lookup=v;exports.makeDiagnostic=B;exports.maxArgs=be;exports.maxCallNesting=de;exports.maxDepth=ge;exports.maxFunctionNesting=fe;exports.maxNestingOf=ee;exports.maxNodes=Se;exports.memberCompletions=zt;exports.memberDepth=he;exports.resolveNamed=En;exports.resolveScheme=vn;exports.resultType=Ne;exports.rootScope=$e;exports.scopeAt=Jt;exports.scopeCompletions=Xt;exports.typeAt=Wt;exports.visibleNames=pe;Object.keys(typeCore).forEach(function(k){if(k!=='default'&&!Object.prototype.hasOwnProperty.call(exports,k))Object.defineProperty(exports,k,{enumerable:true,get:function(){return typeCore[k]}})});
|
package/dist/index.d.cts
CHANGED
|
@@ -1,175 +1,8 @@
|
|
|
1
|
+
import { Schema, Schemes, TypeScheme, ObjectSchema, Completion } from '@tslite/type-core';
|
|
2
|
+
export * from '@tslite/type-core';
|
|
1
3
|
import { Scope as Scope$1, BaseNode, Node } from '@tslite/core';
|
|
2
4
|
import { CapabilityProfile, CompiledProfile } from '@tslite/capability';
|
|
3
5
|
|
|
4
|
-
/** Uma propriedade de um tipo objeto. */
|
|
5
|
-
interface Prop {
|
|
6
|
-
readonly type: Schema;
|
|
7
|
-
/** `true` quando a propriedade pode estar ausente (`{ x?: T }`). */
|
|
8
|
-
readonly optional?: boolean;
|
|
9
|
-
}
|
|
10
|
-
/** Um parâmetro de um tipo função. */
|
|
11
|
-
interface Param {
|
|
12
|
-
readonly name: string;
|
|
13
|
-
readonly type: Schema;
|
|
14
|
-
/** `true` quando o argumento pode ser omitido. */
|
|
15
|
-
readonly optional?: boolean;
|
|
16
|
-
/** `true` para o parâmetro rest (`...args: T[]`). */
|
|
17
|
-
readonly variadic?: boolean;
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Assinatura de **construção** de um tipo função (`new X(...)`). Separada da
|
|
21
|
-
* assinatura de chamada porque podem diferir (ex.: `Date()` → string, `new Date()`
|
|
22
|
-
* → Date). Só construtor **host** (DI) declara isso — a Linguagem não define
|
|
23
|
-
* construtores (D38).
|
|
24
|
-
*/
|
|
25
|
-
interface ConstructSig {
|
|
26
|
-
readonly params: readonly Param[];
|
|
27
|
-
readonly returns: Schema;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* O tipo de um valor na linguagem TSLite.
|
|
31
|
-
*
|
|
32
|
-
* O discriminador é `t`. Estruturas (object/array/union/fn) referenciam outros
|
|
33
|
-
* `Schema` recursivamente — inclusive de forma cíclica (ex.: `Node` que contém
|
|
34
|
-
* `Node[]`); as operações que percorrem `Schema` são cycle-safe.
|
|
35
|
-
*/
|
|
36
|
-
type Schema = {
|
|
37
|
-
readonly t: "any";
|
|
38
|
-
} | {
|
|
39
|
-
readonly t: "unknown";
|
|
40
|
-
} | {
|
|
41
|
-
readonly t: "string";
|
|
42
|
-
} | {
|
|
43
|
-
readonly t: "number";
|
|
44
|
-
} | {
|
|
45
|
-
readonly t: "boolean";
|
|
46
|
-
} | {
|
|
47
|
-
readonly t: "null";
|
|
48
|
-
} | {
|
|
49
|
-
readonly t: "undefined";
|
|
50
|
-
} | {
|
|
51
|
-
readonly t: "literal";
|
|
52
|
-
readonly value: string | number | boolean;
|
|
53
|
-
} | {
|
|
54
|
-
readonly t: "object";
|
|
55
|
-
readonly props: Readonly<Record<string, Prop>>;
|
|
56
|
-
} | {
|
|
57
|
-
readonly t: "array";
|
|
58
|
-
readonly items: Schema;
|
|
59
|
-
} | {
|
|
60
|
-
readonly t: "union";
|
|
61
|
-
readonly of: readonly Schema[];
|
|
62
|
-
} | {
|
|
63
|
-
readonly t: "fn";
|
|
64
|
-
readonly params: readonly Param[];
|
|
65
|
-
readonly returns: Schema;
|
|
66
|
-
/** Assinatura de `new X(...)` — presente só em construtor host (D38). */
|
|
67
|
-
readonly construct?: ConstructSig;
|
|
68
|
-
} | {
|
|
69
|
-
readonly t: "var";
|
|
70
|
-
readonly name: string;
|
|
71
|
-
} | {
|
|
72
|
-
readonly t: "apply";
|
|
73
|
-
readonly name: string;
|
|
74
|
-
readonly args: readonly Schema[];
|
|
75
|
-
};
|
|
76
|
-
type AnySchema = Extract<Schema, {
|
|
77
|
-
t: "any";
|
|
78
|
-
}>;
|
|
79
|
-
type UnknownSchema = Extract<Schema, {
|
|
80
|
-
t: "unknown";
|
|
81
|
-
}>;
|
|
82
|
-
type LiteralSchema = Extract<Schema, {
|
|
83
|
-
t: "literal";
|
|
84
|
-
}>;
|
|
85
|
-
type ObjectSchema = Extract<Schema, {
|
|
86
|
-
t: "object";
|
|
87
|
-
}>;
|
|
88
|
-
type ArraySchema = Extract<Schema, {
|
|
89
|
-
t: "array";
|
|
90
|
-
}>;
|
|
91
|
-
type UnionSchema = Extract<Schema, {
|
|
92
|
-
t: "union";
|
|
93
|
-
}>;
|
|
94
|
-
type FnSchema = Extract<Schema, {
|
|
95
|
-
t: "fn";
|
|
96
|
-
}>;
|
|
97
|
-
type VarSchema = Extract<Schema, {
|
|
98
|
-
t: "var";
|
|
99
|
-
}>;
|
|
100
|
-
type ApplySchema = Extract<Schema, {
|
|
101
|
-
t: "apply";
|
|
102
|
-
}>;
|
|
103
|
-
type ScalarSchema = Extract<Schema, {
|
|
104
|
-
t: "string" | "number" | "boolean" | "null" | "undefined";
|
|
105
|
-
}>;
|
|
106
|
-
declare const s: {
|
|
107
|
-
readonly any: Schema;
|
|
108
|
-
readonly unknown: Schema;
|
|
109
|
-
readonly string: Schema;
|
|
110
|
-
readonly number: Schema;
|
|
111
|
-
readonly boolean: Schema;
|
|
112
|
-
readonly null: Schema;
|
|
113
|
-
readonly undefined: Schema;
|
|
114
|
-
readonly literal: (value: string | number | boolean) => Schema;
|
|
115
|
-
readonly object: (props: Record<string, Prop>) => Schema;
|
|
116
|
-
readonly array: (items: Schema) => Schema;
|
|
117
|
-
readonly fn: (params: Param[], returns: Schema) => Schema;
|
|
118
|
-
/**
|
|
119
|
-
* Construtor host: `s.ctor(params, Instance)` → função **newável** que devolve
|
|
120
|
-
* `Instance` (tanto via `new` quanto via chamada, p/ simplicidade). O canal é a
|
|
121
|
-
* DI — a Linguagem instancia construtores host, não os define (D38).
|
|
122
|
-
*/
|
|
123
|
-
readonly ctor: (params: Param[], instance: Schema) => Schema;
|
|
124
|
-
readonly var: (name: string) => Schema;
|
|
125
|
-
/** Construtor de tipo aplicado: `apply("Map", [K, V])` ⇒ `Map<K, V>`. */
|
|
126
|
-
readonly apply: (name: string, args?: readonly Schema[]) => Schema;
|
|
127
|
-
/** Açúcar para `Promise<T>` — o que `await` desembrulha. */
|
|
128
|
-
readonly promise: (value: Schema) => Schema;
|
|
129
|
-
/**
|
|
130
|
-
* Constrói uma união achatando uniões aninhadas. Não deduplica nem colapsa
|
|
131
|
-
* união-de-um aqui (isso depende de igualdade estrutural — ver `normalizeUnion`
|
|
132
|
-
* quando `subtype` existir); apenas garante uma lista plana.
|
|
133
|
-
*/
|
|
134
|
-
readonly union: (of: readonly Schema[]) => Schema;
|
|
135
|
-
};
|
|
136
|
-
/**
|
|
137
|
-
* Separa `undefined` de um tipo: devolve o tipo **sem** `undefined` e se ele estava
|
|
138
|
-
* presente. Em posição de **propriedade**, `T | undefined` é uma propriedade
|
|
139
|
-
* **opcional** de tipo `T` — espelha o `JSON.stringify` (chave `undefined` some).
|
|
140
|
-
* Só mexe em `undefined`, nunca em `null` (que é valor JSON presente). Usado pelo
|
|
141
|
-
* `serializable` e pelo `toJsonSchema` (mesma regra dos dois lados).
|
|
142
|
-
*/
|
|
143
|
-
declare function withoutUndefined(t: Schema): {
|
|
144
|
-
type: Schema;
|
|
145
|
-
hadUndefined: boolean;
|
|
146
|
-
};
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* `true` quando `schema` descreve **dado puro** (sobrevive a `JSON.stringify`
|
|
150
|
-
* sem perda silenciosa). `fn` é o ponto-chave: uma função é dropada em silêncio
|
|
151
|
-
* pela serialização — por isso `false`.
|
|
152
|
-
*
|
|
153
|
-
* `apply` é **conservador** (`false`): sem registro de construtores-de-dado
|
|
154
|
-
* liberados, não dá pra garantir que `Foo<…>` (ou `Promise<T>`, `Map<K,V>`)
|
|
155
|
-
* vire JSON. `var` (forma desconhecida), `any`/`unknown` (sem garantia) → `false`.
|
|
156
|
-
*/
|
|
157
|
-
declare function isSerializable(schema: Schema, seen?: WeakSet<object>): boolean;
|
|
158
|
-
|
|
159
|
-
/** Renderiza `schema` como uma string no estilo TypeScript. */
|
|
160
|
-
declare function format(schema: Schema, seen?: WeakSet<object>): string;
|
|
161
|
-
|
|
162
|
-
/**
|
|
163
|
-
* Um *type scheme*: um tipo nomeado parametrizado, `type Pair<A, B> = body`.
|
|
164
|
-
* `params` são as variáveis de tipo (na ordem); `body` é o `Schema` que as usa
|
|
165
|
-
* via `var`. Um tipo nomeado não-genérico é só um scheme com `params: []`.
|
|
166
|
-
*/
|
|
167
|
-
interface TypeScheme {
|
|
168
|
-
readonly params: readonly string[];
|
|
169
|
-
readonly body: Schema;
|
|
170
|
-
}
|
|
171
|
-
/** Registro de type schemes por nome — consultado pela expansão (ver `expand`). */
|
|
172
|
-
type Schemes = Readonly<Record<string, TypeScheme>>;
|
|
173
6
|
/**
|
|
174
7
|
* Um nível de escopo léxico (nome → `Schema`), sobre o `Scope<T>` genérico do
|
|
175
8
|
* `core` — a mesma cadeia que o `analysis` usa, com o payload do eixo de tipos.
|
|
@@ -207,104 +40,61 @@ interface Env {
|
|
|
207
40
|
* sem `unknown` (o app declara o shape; o checker indexa). Default: nenhum.
|
|
208
41
|
*/
|
|
209
42
|
readonly accessors?: Readonly<Record<string, Schema>>;
|
|
43
|
+
/**
|
|
44
|
+
* **Asserters** (a fronteira sã): nomes de funções cujo retorno é o **tipo do
|
|
45
|
+
* schema nomeado** no 1º argumento. Ex.: com `parse` aqui, `parse(User, x)`
|
|
46
|
+
* tipa como `User` (e em runtime o `@tslite/validate` valida o valor). É o
|
|
47
|
+
* `parse()` estilo zod: fecha `unknown`/complexidade — o tipo "reseta" limpo
|
|
48
|
+
* na fronteira, **provado** em runtime (≠ `as`). Default: nenhum.
|
|
49
|
+
*/
|
|
50
|
+
readonly asserters?: ReadonlySet<string>;
|
|
51
|
+
/**
|
|
52
|
+
* **Matchers de props** (o diferencial): nomes de funções que checam, em
|
|
53
|
+
* edit-time, se um **payload** (saída de um serviço de automação / nocode) é
|
|
54
|
+
* **compatível com as props de um componente** react-like. Ex.: com
|
|
55
|
+
* `matchesProps` aqui, `matchesProps(Card, request)` extrai as props de `Card`
|
|
56
|
+
* (`(props) => Element`, agnóstico ao framework — Element é `apply` opaco) e
|
|
57
|
+
* verifica `request ≤ props` (campos a mais no request são OK; faltar/tipo-errado
|
|
58
|
+
* em prop obrigatória → diagnóstico `props-mismatch`). Retorna `boolean`. Default:
|
|
59
|
+
* nenhum.
|
|
60
|
+
*/
|
|
61
|
+
readonly matchers?: ReadonlySet<string>;
|
|
62
|
+
/**
|
|
63
|
+
* **Módulos** (a borda DI NOMEADA): especificador → o `object` Schema dos
|
|
64
|
+
* exports daquele módulo (`{ map: fn, filter: fn, …, default: … }`). É o D3
|
|
65
|
+
* estendido a módulos: `import { map } from "@x/ops"` liga `map` ao
|
|
66
|
+
* `modules["@x/ops"].props.map`. O checker **não resolve** o módulo (sem file
|
|
67
|
+
* system) — consome o tipo já provido; a *resolução* (qual módulo é o
|
|
68
|
+
* especificador) é da app (Proposal 005). Default: nenhum.
|
|
69
|
+
*/
|
|
70
|
+
readonly modules?: Readonly<Record<string, Schema>>;
|
|
210
71
|
}
|
|
211
72
|
/**
|
|
212
73
|
* Cria um `Env` a partir das variáveis injetadas, dos tipos nomeados, dos type
|
|
213
74
|
* schemes e dos acessores. Capability é separada (passe um `profile` ao `check`).
|
|
214
75
|
*/
|
|
215
|
-
declare const createEnv: (vars?: Record<string, Schema>, types?: Record<string, Schema>, schemes?: Record<string, TypeScheme>, accessors?: Record<string, Schema>) => Env;
|
|
76
|
+
declare const createEnv: (vars?: Record<string, Schema>, types?: Record<string, Schema>, schemes?: Record<string, TypeScheme>, accessors?: Record<string, Schema>, asserters?: ReadonlySet<string>, matchers?: ReadonlySet<string>, modules?: Record<string, Schema>) => Env;
|
|
216
77
|
/** Resolve um tipo nomeado (`type User = …`) declarado no ambiente. */
|
|
217
78
|
declare const resolveNamed: (env: Env, name: string) => Schema | undefined;
|
|
218
79
|
/** Resolve um type scheme (`type Pair<A, B> = …`) declarado no ambiente. */
|
|
219
80
|
declare const resolveScheme: (env: Env, name: string) => TypeScheme | undefined;
|
|
220
81
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
/** Igualdade estrutural: cada um é atribuível ao outro. */
|
|
224
|
-
declare function equals(a: Schema, b: Schema, schemes?: Schemes): boolean;
|
|
225
|
-
/**
|
|
226
|
-
* Normaliza uma união: achata, absorve `any`/`unknown`, deduplica e remove
|
|
227
|
-
* membros subsumidos por outro (`string | "x"` → `string`). Colapsa união de um
|
|
228
|
-
* membro no próprio membro. União vazia permanece vazia (renderiza `never`).
|
|
229
|
-
*/
|
|
230
|
-
declare function normalizeUnion(members: readonly Schema[]): Schema;
|
|
231
|
-
|
|
232
|
-
/**
|
|
233
|
-
* O supremo estrutural de `a` e `b`: o menor `Schema` ao qual ambos são
|
|
234
|
-
* atribuíveis. `unknown` é a unidade (sem-evidência); `any` é absorvente.
|
|
235
|
-
*/
|
|
236
|
-
declare function join(a: Schema, b: Schema): Schema;
|
|
237
|
-
/**
|
|
238
|
-
* Dobra uma lista de formas no seu supremo comum. Lista vazia → `never` (⊥, a
|
|
239
|
-
* identidade do supremo). Um membro → ele mesmo. É a operação do schema-reducer:
|
|
240
|
-
* `joinAll(amostras.map(inferValue))` descreve todas as amostras.
|
|
241
|
-
*/
|
|
242
|
-
declare function joinAll(members: readonly Schema[]): Schema;
|
|
243
|
-
|
|
244
|
-
/** Um membro que pode seguir a partir de um tipo (item de autocomplete). */
|
|
245
|
-
interface Completion {
|
|
246
|
-
/** Nome da propriedade, ou `"[]"` para o elemento de um array. */
|
|
247
|
-
readonly key: string;
|
|
248
|
-
readonly type: Schema;
|
|
249
|
-
readonly optional: boolean;
|
|
250
|
-
}
|
|
251
|
-
/** Resultado de navegar um path: o tipo final + o que pode seguir dele. */
|
|
252
|
-
interface Discovery {
|
|
253
|
-
readonly type: Schema;
|
|
254
|
-
readonly completions: readonly Completion[];
|
|
255
|
-
}
|
|
256
|
-
/**
|
|
257
|
-
* Navega `path` a partir de `schema`. Retorna o tipo alcançado e suas
|
|
258
|
-
* completions, ou `null` se algum segmento não existir no tipo. Path vazio
|
|
259
|
-
* devolve o próprio tipo e suas completions.
|
|
260
|
-
*/
|
|
261
|
-
declare function discover(schema: Schema, path: readonly string[], schemes?: Schemes): Discovery | null;
|
|
262
|
-
|
|
263
|
-
/** Ligações `nome da var → tipo` (o resultado de `unify`/aplicação de scheme). */
|
|
264
|
-
type Bindings = Readonly<Record<string, Schema>>;
|
|
265
|
-
/** Aplica `bindings` a `schema`, trocando cada `var` ligada pelo seu tipo. */
|
|
266
|
-
declare function substitute(schema: Schema, bindings: Bindings, seen?: WeakSet<object>): Schema;
|
|
267
|
-
|
|
268
|
-
/**
|
|
269
|
-
* Liga as `var`s de `pattern` aos tipos correspondentes em `actual`. Devolve as
|
|
270
|
-
* ligações estendidas, ou `null` se forem incompatíveis. `actual` que seja
|
|
271
|
-
* `any`/`unknown` não constrange vars (deixa-as livres).
|
|
272
|
-
*/
|
|
273
|
-
declare function unify(pattern: Schema, actual: Schema, bindings?: Bindings): Bindings | null;
|
|
274
|
-
/** Resultado de instanciar uma assinatura contra argumentos. */
|
|
275
|
-
interface Instantiation {
|
|
276
|
-
readonly returns: Schema;
|
|
277
|
-
readonly bindings: Bindings;
|
|
278
|
-
}
|
|
279
|
-
/**
|
|
280
|
-
* Instancia uma função genérica: unifica cada argumento contra o parâmetro
|
|
281
|
-
* correspondente (ligando as `var`s) e devolve o retorno já substituído.
|
|
282
|
-
* Falha (`null`) se algum argumento não unificar. Um parâmetro `variadic`
|
|
283
|
-
* absorve os argumentos restantes (cada um unifica contra o tipo do rest).
|
|
284
|
-
*/
|
|
285
|
-
declare function instantiate(sig: FnSchema, args: readonly Schema[]): Instantiation | null;
|
|
286
|
-
/**
|
|
287
|
-
* Versão tolerante de {@link instantiate} para o editor/checker: nunca falha —
|
|
288
|
-
* argumentos que não unificam são ignorados, e `var`s não ligadas permanecem
|
|
289
|
-
* (útil para aplicação parcial e enquanto o usuário ainda digita).
|
|
290
|
-
*/
|
|
291
|
-
declare function instantiateLoose(sig: FnSchema, args: readonly Schema[]): Instantiation;
|
|
292
|
-
/** Aterra as `var`s remanescentes em `unknown` (para exibição do resultado). */
|
|
293
|
-
declare function groundVars(schema: Schema, seen?: WeakSet<object>): Schema;
|
|
294
|
-
|
|
295
|
-
/** Há um scheme registrado para este `apply` (com aridade compatível)? */
|
|
296
|
-
declare function isScheme(t: Schema, schemes: Schemes): boolean;
|
|
82
|
+
type Severity = "error" | "warning";
|
|
83
|
+
type DiagnosticCode = "not-assignable" | "unknown-name" | "not-callable" | "no-such-member" | "not-object" | "const-needs-init" | "cannot-redeclare" | "unknown-module" | "missing-argument" | "excess-argument" | "excess-property" | "spread-argument" | "props-mismatch" | "no-matching-overload" | "constraint-violation" | "unsupported" | "forbidden-member" | "cast-unsound" | "node-not-allowed" | "name-not-allowed" | "type-feature-not-allowed" | "any-not-allowed" | "too-deep" | "too-complex-union" | "too-large" | "wrong-result-type";
|
|
297
84
|
/**
|
|
298
|
-
*
|
|
299
|
-
* `
|
|
300
|
-
*
|
|
85
|
+
* A **classe** do diagnóstico — espelha a divisão de passes do `tsc` (que nós
|
|
86
|
+
* fundimos num walk só): `semantic` é o que o **binder** do tsc pega (validade do
|
|
87
|
+
* programa, independe de tipos — nome inexistente, redeclaração, módulo, `const`
|
|
88
|
+
* sem init, recurso fora da Linguagem); `type` é o que o **checker** de tipos pega
|
|
89
|
+
* (relações/compatibilidade); `capability` é política/limite (feature gated, caps).
|
|
90
|
+
* O `kind` deriva do `code` (fonte única, mapa `KIND`) — o consumidor (editor/nocode)
|
|
91
|
+
* distingue "isto é programa inválido" de "isto é incompatibilidade de tipo".
|
|
301
92
|
*/
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
type Severity = "error" | "warning";
|
|
305
|
-
type DiagnosticCode = "not-assignable" | "unknown-name" | "not-callable" | "not-newable" | "no-such-member" | "not-object" | "const-needs-init" | "missing-argument" | "unsupported" | "cast-unsound" | "node-not-allowed" | "name-not-allowed" | "too-deep" | "too-large" | "wrong-result-type";
|
|
93
|
+
type DiagnosticKind = "semantic" | "type" | "capability";
|
|
306
94
|
interface Diagnostic {
|
|
307
95
|
readonly code: DiagnosticCode;
|
|
96
|
+
/** A classe do diagnóstico (deriva do `code`) — ver {@link DiagnosticKind}. */
|
|
97
|
+
readonly kind: DiagnosticKind;
|
|
308
98
|
readonly severity: Severity;
|
|
309
99
|
/** O nó culpado — identidade por referência. */
|
|
310
100
|
readonly node: BaseNode;
|
|
@@ -312,7 +102,8 @@ interface Diagnostic {
|
|
|
312
102
|
}
|
|
313
103
|
/**
|
|
314
104
|
* Builder genérico de diagnóstico (severidade configurável). Usado pelos
|
|
315
|
-
* guardrails, que têm seu próprio catálogo de mensagens em `guard`.
|
|
105
|
+
* guardrails, que têm seu próprio catálogo de mensagens em `guard`. O `kind`
|
|
106
|
+
* deriva do `code` (mesma fonte única).
|
|
316
107
|
*/
|
|
317
108
|
declare const makeDiagnostic: (code: DiagnosticCode, node: BaseNode, message: string, severity?: Severity) => Diagnostic;
|
|
318
109
|
/**
|
|
@@ -320,15 +111,23 @@ declare const makeDiagnostic: (code: DiagnosticCode, node: BaseNode, message: st
|
|
|
320
111
|
* por `format`.
|
|
321
112
|
*/
|
|
322
113
|
declare const diag: {
|
|
323
|
-
notAssignable: (node: BaseNode, actual: Schema, expected: Schema) => Diagnostic;
|
|
114
|
+
notAssignable: (node: BaseNode, actual: Schema, expected: Schema, schemes?: Schemes) => Diagnostic;
|
|
324
115
|
unknownName: (node: BaseNode, name: string) => Diagnostic;
|
|
325
116
|
notCallable: (node: BaseNode, type: Schema) => Diagnostic;
|
|
326
|
-
notNewable: (node: BaseNode, type: Schema) => Diagnostic;
|
|
327
117
|
noSuchMember: (node: BaseNode, type: Schema, key: string) => Diagnostic;
|
|
328
118
|
notObject: (node: BaseNode, type: Schema) => Diagnostic;
|
|
329
119
|
constNeedsInit: (node: BaseNode) => Diagnostic;
|
|
330
120
|
missingArgument: (node: BaseNode, name: string, expected: Schema) => Diagnostic;
|
|
121
|
+
unknownModule: (node: BaseNode, source: string) => Diagnostic;
|
|
122
|
+
cannotRedeclare: (node: BaseNode, name: string) => Diagnostic;
|
|
123
|
+
excessArgument: (node: BaseNode, expected: number, got: number) => Diagnostic;
|
|
124
|
+
excessProperty: (node: BaseNode, name: string, target: Schema) => Diagnostic;
|
|
125
|
+
spreadArgument: (node: BaseNode) => Diagnostic;
|
|
126
|
+
propsMismatch: (node: BaseNode, props: Schema, detail: string) => Diagnostic;
|
|
127
|
+
noMatchingOverload: (node: BaseNode, type: Schema, argTypes: readonly Schema[]) => Diagnostic;
|
|
128
|
+
constraintViolation: (node: BaseNode, name: string, actual: Schema, bound: Schema) => Diagnostic;
|
|
331
129
|
unsupported: (node: BaseNode, what: string) => Diagnostic;
|
|
130
|
+
forbiddenMember: (node: BaseNode, key: string) => Diagnostic;
|
|
332
131
|
/**
|
|
333
132
|
* Cast (`x as T`) entre tipos que não se sobrepõem em nenhum sentido. Warning
|
|
334
133
|
* (não erro): o cast é um escape-hatch explícito — `unknown`/`any` passam
|
|
@@ -398,6 +197,20 @@ interface CheckOptions {
|
|
|
398
197
|
readonly resultType?: Schema;
|
|
399
198
|
}
|
|
400
199
|
declare function check(node: Node, env: Env, opts?: CheckOptions): CheckResult;
|
|
200
|
+
/**
|
|
201
|
+
* Extrai o **tipo-superfície** de um módulo (o ".d.ts sem arquivo", o dual do import):
|
|
202
|
+
* roda o `check` e projeta os bindings de topo (`const`/`function`) num `object` Schema
|
|
203
|
+
* `{ nome: tipoInferido }`. É como o `tsc` faz o declaration emit — só que aqui o checker
|
|
204
|
+
* **já infere** os tipos (D5/D6 scope-flow), então é uma projeção do overlay, sem Babel
|
|
205
|
+
* nem serialização pra sintaxe. O resultado é exatamente o que outro módulo consome via
|
|
206
|
+
* `env.modules[especificador]` — os dois lados se fecham. (Filtragem por `export` explícito
|
|
207
|
+
* entra quando `export` for implementado; hoje projeta toda a superfície de topo — o caso
|
|
208
|
+
* "inferir o tipo de um algoritmo que não declarou tipos".)
|
|
209
|
+
*/
|
|
210
|
+
declare function extractModuleType(program: Node, env: Env, opts?: CheckOptions): {
|
|
211
|
+
type: ObjectSchema;
|
|
212
|
+
diagnostics: readonly Diagnostic[];
|
|
213
|
+
};
|
|
401
214
|
|
|
402
215
|
/** Contexto opcional de um guard (o overlay de tipos, p/ regras type-aware). */
|
|
403
216
|
interface GuardContext {
|
|
@@ -464,6 +277,8 @@ declare const annotate: <N extends BaseNode>(node: N, type: Schema) => N & {
|
|
|
464
277
|
declare const annotateReturn: <N extends BaseNode>(fn: N, type: Schema) => N & {
|
|
465
278
|
returnType: Schema;
|
|
466
279
|
};
|
|
280
|
+
/** Cast `x as T` — `{ expression, typeAnnotation }`; tipa a expressão, resulta `T`. */
|
|
281
|
+
declare const asExpression: (expression: BaseNode, type: Schema) => BaseNode;
|
|
467
282
|
|
|
468
283
|
/** O tipo inferido de `node`, ou `undefined` se o nó não foi tipado. */
|
|
469
284
|
declare function typeAt(overlay: TypeOverlay, node: BaseNode): Schema | undefined;
|
|
@@ -485,4 +300,4 @@ declare function scopeCompletions(overlay: TypeOverlay, node: BaseNode): readonl
|
|
|
485
300
|
/** Os diagnósticos que apontam para `node`. */
|
|
486
301
|
declare function diagnosticsAt(diagnostics: readonly Diagnostic[], node: BaseNode): readonly Diagnostic[];
|
|
487
302
|
|
|
488
|
-
export { type
|
|
303
|
+
export { type CheckOptions, type CheckResult, type Diagnostic, type DiagnosticCode, type DiagnosticKind, type DiagnosticSink, type Env, FUNCTION_KINDS, type Guard, type GuardContext, type Profile, type Scope, type Severity, type TypeOverlay, annotate, annotateReturn, asExpression, calleeAllowlist, capabilityNodes, check, childScope, createEnv, createSink, diag, diagnosticsAt, extractModuleType, fromCapability, guard, guardsFromCompiled, lookup, makeDiagnostic, maxArgs, maxCallNesting, maxDepth, maxFunctionNesting, maxNestingOf, maxNodes, memberCompletions, memberDepth, resolveNamed, resolveScheme, resultType, rootScope, scopeAt, scopeCompletions, typeAt, visibleNames };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,175 +1,8 @@
|
|
|
1
|
+
import { Schema, Schemes, TypeScheme, ObjectSchema, Completion } from '@tslite/type-core';
|
|
2
|
+
export * from '@tslite/type-core';
|
|
1
3
|
import { Scope as Scope$1, BaseNode, Node } from '@tslite/core';
|
|
2
4
|
import { CapabilityProfile, CompiledProfile } from '@tslite/capability';
|
|
3
5
|
|
|
4
|
-
/** Uma propriedade de um tipo objeto. */
|
|
5
|
-
interface Prop {
|
|
6
|
-
readonly type: Schema;
|
|
7
|
-
/** `true` quando a propriedade pode estar ausente (`{ x?: T }`). */
|
|
8
|
-
readonly optional?: boolean;
|
|
9
|
-
}
|
|
10
|
-
/** Um parâmetro de um tipo função. */
|
|
11
|
-
interface Param {
|
|
12
|
-
readonly name: string;
|
|
13
|
-
readonly type: Schema;
|
|
14
|
-
/** `true` quando o argumento pode ser omitido. */
|
|
15
|
-
readonly optional?: boolean;
|
|
16
|
-
/** `true` para o parâmetro rest (`...args: T[]`). */
|
|
17
|
-
readonly variadic?: boolean;
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Assinatura de **construção** de um tipo função (`new X(...)`). Separada da
|
|
21
|
-
* assinatura de chamada porque podem diferir (ex.: `Date()` → string, `new Date()`
|
|
22
|
-
* → Date). Só construtor **host** (DI) declara isso — a Linguagem não define
|
|
23
|
-
* construtores (D38).
|
|
24
|
-
*/
|
|
25
|
-
interface ConstructSig {
|
|
26
|
-
readonly params: readonly Param[];
|
|
27
|
-
readonly returns: Schema;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* O tipo de um valor na linguagem TSLite.
|
|
31
|
-
*
|
|
32
|
-
* O discriminador é `t`. Estruturas (object/array/union/fn) referenciam outros
|
|
33
|
-
* `Schema` recursivamente — inclusive de forma cíclica (ex.: `Node` que contém
|
|
34
|
-
* `Node[]`); as operações que percorrem `Schema` são cycle-safe.
|
|
35
|
-
*/
|
|
36
|
-
type Schema = {
|
|
37
|
-
readonly t: "any";
|
|
38
|
-
} | {
|
|
39
|
-
readonly t: "unknown";
|
|
40
|
-
} | {
|
|
41
|
-
readonly t: "string";
|
|
42
|
-
} | {
|
|
43
|
-
readonly t: "number";
|
|
44
|
-
} | {
|
|
45
|
-
readonly t: "boolean";
|
|
46
|
-
} | {
|
|
47
|
-
readonly t: "null";
|
|
48
|
-
} | {
|
|
49
|
-
readonly t: "undefined";
|
|
50
|
-
} | {
|
|
51
|
-
readonly t: "literal";
|
|
52
|
-
readonly value: string | number | boolean;
|
|
53
|
-
} | {
|
|
54
|
-
readonly t: "object";
|
|
55
|
-
readonly props: Readonly<Record<string, Prop>>;
|
|
56
|
-
} | {
|
|
57
|
-
readonly t: "array";
|
|
58
|
-
readonly items: Schema;
|
|
59
|
-
} | {
|
|
60
|
-
readonly t: "union";
|
|
61
|
-
readonly of: readonly Schema[];
|
|
62
|
-
} | {
|
|
63
|
-
readonly t: "fn";
|
|
64
|
-
readonly params: readonly Param[];
|
|
65
|
-
readonly returns: Schema;
|
|
66
|
-
/** Assinatura de `new X(...)` — presente só em construtor host (D38). */
|
|
67
|
-
readonly construct?: ConstructSig;
|
|
68
|
-
} | {
|
|
69
|
-
readonly t: "var";
|
|
70
|
-
readonly name: string;
|
|
71
|
-
} | {
|
|
72
|
-
readonly t: "apply";
|
|
73
|
-
readonly name: string;
|
|
74
|
-
readonly args: readonly Schema[];
|
|
75
|
-
};
|
|
76
|
-
type AnySchema = Extract<Schema, {
|
|
77
|
-
t: "any";
|
|
78
|
-
}>;
|
|
79
|
-
type UnknownSchema = Extract<Schema, {
|
|
80
|
-
t: "unknown";
|
|
81
|
-
}>;
|
|
82
|
-
type LiteralSchema = Extract<Schema, {
|
|
83
|
-
t: "literal";
|
|
84
|
-
}>;
|
|
85
|
-
type ObjectSchema = Extract<Schema, {
|
|
86
|
-
t: "object";
|
|
87
|
-
}>;
|
|
88
|
-
type ArraySchema = Extract<Schema, {
|
|
89
|
-
t: "array";
|
|
90
|
-
}>;
|
|
91
|
-
type UnionSchema = Extract<Schema, {
|
|
92
|
-
t: "union";
|
|
93
|
-
}>;
|
|
94
|
-
type FnSchema = Extract<Schema, {
|
|
95
|
-
t: "fn";
|
|
96
|
-
}>;
|
|
97
|
-
type VarSchema = Extract<Schema, {
|
|
98
|
-
t: "var";
|
|
99
|
-
}>;
|
|
100
|
-
type ApplySchema = Extract<Schema, {
|
|
101
|
-
t: "apply";
|
|
102
|
-
}>;
|
|
103
|
-
type ScalarSchema = Extract<Schema, {
|
|
104
|
-
t: "string" | "number" | "boolean" | "null" | "undefined";
|
|
105
|
-
}>;
|
|
106
|
-
declare const s: {
|
|
107
|
-
readonly any: Schema;
|
|
108
|
-
readonly unknown: Schema;
|
|
109
|
-
readonly string: Schema;
|
|
110
|
-
readonly number: Schema;
|
|
111
|
-
readonly boolean: Schema;
|
|
112
|
-
readonly null: Schema;
|
|
113
|
-
readonly undefined: Schema;
|
|
114
|
-
readonly literal: (value: string | number | boolean) => Schema;
|
|
115
|
-
readonly object: (props: Record<string, Prop>) => Schema;
|
|
116
|
-
readonly array: (items: Schema) => Schema;
|
|
117
|
-
readonly fn: (params: Param[], returns: Schema) => Schema;
|
|
118
|
-
/**
|
|
119
|
-
* Construtor host: `s.ctor(params, Instance)` → função **newável** que devolve
|
|
120
|
-
* `Instance` (tanto via `new` quanto via chamada, p/ simplicidade). O canal é a
|
|
121
|
-
* DI — a Linguagem instancia construtores host, não os define (D38).
|
|
122
|
-
*/
|
|
123
|
-
readonly ctor: (params: Param[], instance: Schema) => Schema;
|
|
124
|
-
readonly var: (name: string) => Schema;
|
|
125
|
-
/** Construtor de tipo aplicado: `apply("Map", [K, V])` ⇒ `Map<K, V>`. */
|
|
126
|
-
readonly apply: (name: string, args?: readonly Schema[]) => Schema;
|
|
127
|
-
/** Açúcar para `Promise<T>` — o que `await` desembrulha. */
|
|
128
|
-
readonly promise: (value: Schema) => Schema;
|
|
129
|
-
/**
|
|
130
|
-
* Constrói uma união achatando uniões aninhadas. Não deduplica nem colapsa
|
|
131
|
-
* união-de-um aqui (isso depende de igualdade estrutural — ver `normalizeUnion`
|
|
132
|
-
* quando `subtype` existir); apenas garante uma lista plana.
|
|
133
|
-
*/
|
|
134
|
-
readonly union: (of: readonly Schema[]) => Schema;
|
|
135
|
-
};
|
|
136
|
-
/**
|
|
137
|
-
* Separa `undefined` de um tipo: devolve o tipo **sem** `undefined` e se ele estava
|
|
138
|
-
* presente. Em posição de **propriedade**, `T | undefined` é uma propriedade
|
|
139
|
-
* **opcional** de tipo `T` — espelha o `JSON.stringify` (chave `undefined` some).
|
|
140
|
-
* Só mexe em `undefined`, nunca em `null` (que é valor JSON presente). Usado pelo
|
|
141
|
-
* `serializable` e pelo `toJsonSchema` (mesma regra dos dois lados).
|
|
142
|
-
*/
|
|
143
|
-
declare function withoutUndefined(t: Schema): {
|
|
144
|
-
type: Schema;
|
|
145
|
-
hadUndefined: boolean;
|
|
146
|
-
};
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* `true` quando `schema` descreve **dado puro** (sobrevive a `JSON.stringify`
|
|
150
|
-
* sem perda silenciosa). `fn` é o ponto-chave: uma função é dropada em silêncio
|
|
151
|
-
* pela serialização — por isso `false`.
|
|
152
|
-
*
|
|
153
|
-
* `apply` é **conservador** (`false`): sem registro de construtores-de-dado
|
|
154
|
-
* liberados, não dá pra garantir que `Foo<…>` (ou `Promise<T>`, `Map<K,V>`)
|
|
155
|
-
* vire JSON. `var` (forma desconhecida), `any`/`unknown` (sem garantia) → `false`.
|
|
156
|
-
*/
|
|
157
|
-
declare function isSerializable(schema: Schema, seen?: WeakSet<object>): boolean;
|
|
158
|
-
|
|
159
|
-
/** Renderiza `schema` como uma string no estilo TypeScript. */
|
|
160
|
-
declare function format(schema: Schema, seen?: WeakSet<object>): string;
|
|
161
|
-
|
|
162
|
-
/**
|
|
163
|
-
* Um *type scheme*: um tipo nomeado parametrizado, `type Pair<A, B> = body`.
|
|
164
|
-
* `params` são as variáveis de tipo (na ordem); `body` é o `Schema` que as usa
|
|
165
|
-
* via `var`. Um tipo nomeado não-genérico é só um scheme com `params: []`.
|
|
166
|
-
*/
|
|
167
|
-
interface TypeScheme {
|
|
168
|
-
readonly params: readonly string[];
|
|
169
|
-
readonly body: Schema;
|
|
170
|
-
}
|
|
171
|
-
/** Registro de type schemes por nome — consultado pela expansão (ver `expand`). */
|
|
172
|
-
type Schemes = Readonly<Record<string, TypeScheme>>;
|
|
173
6
|
/**
|
|
174
7
|
* Um nível de escopo léxico (nome → `Schema`), sobre o `Scope<T>` genérico do
|
|
175
8
|
* `core` — a mesma cadeia que o `analysis` usa, com o payload do eixo de tipos.
|
|
@@ -207,104 +40,61 @@ interface Env {
|
|
|
207
40
|
* sem `unknown` (o app declara o shape; o checker indexa). Default: nenhum.
|
|
208
41
|
*/
|
|
209
42
|
readonly accessors?: Readonly<Record<string, Schema>>;
|
|
43
|
+
/**
|
|
44
|
+
* **Asserters** (a fronteira sã): nomes de funções cujo retorno é o **tipo do
|
|
45
|
+
* schema nomeado** no 1º argumento. Ex.: com `parse` aqui, `parse(User, x)`
|
|
46
|
+
* tipa como `User` (e em runtime o `@tslite/validate` valida o valor). É o
|
|
47
|
+
* `parse()` estilo zod: fecha `unknown`/complexidade — o tipo "reseta" limpo
|
|
48
|
+
* na fronteira, **provado** em runtime (≠ `as`). Default: nenhum.
|
|
49
|
+
*/
|
|
50
|
+
readonly asserters?: ReadonlySet<string>;
|
|
51
|
+
/**
|
|
52
|
+
* **Matchers de props** (o diferencial): nomes de funções que checam, em
|
|
53
|
+
* edit-time, se um **payload** (saída de um serviço de automação / nocode) é
|
|
54
|
+
* **compatível com as props de um componente** react-like. Ex.: com
|
|
55
|
+
* `matchesProps` aqui, `matchesProps(Card, request)` extrai as props de `Card`
|
|
56
|
+
* (`(props) => Element`, agnóstico ao framework — Element é `apply` opaco) e
|
|
57
|
+
* verifica `request ≤ props` (campos a mais no request são OK; faltar/tipo-errado
|
|
58
|
+
* em prop obrigatória → diagnóstico `props-mismatch`). Retorna `boolean`. Default:
|
|
59
|
+
* nenhum.
|
|
60
|
+
*/
|
|
61
|
+
readonly matchers?: ReadonlySet<string>;
|
|
62
|
+
/**
|
|
63
|
+
* **Módulos** (a borda DI NOMEADA): especificador → o `object` Schema dos
|
|
64
|
+
* exports daquele módulo (`{ map: fn, filter: fn, …, default: … }`). É o D3
|
|
65
|
+
* estendido a módulos: `import { map } from "@x/ops"` liga `map` ao
|
|
66
|
+
* `modules["@x/ops"].props.map`. O checker **não resolve** o módulo (sem file
|
|
67
|
+
* system) — consome o tipo já provido; a *resolução* (qual módulo é o
|
|
68
|
+
* especificador) é da app (Proposal 005). Default: nenhum.
|
|
69
|
+
*/
|
|
70
|
+
readonly modules?: Readonly<Record<string, Schema>>;
|
|
210
71
|
}
|
|
211
72
|
/**
|
|
212
73
|
* Cria um `Env` a partir das variáveis injetadas, dos tipos nomeados, dos type
|
|
213
74
|
* schemes e dos acessores. Capability é separada (passe um `profile` ao `check`).
|
|
214
75
|
*/
|
|
215
|
-
declare const createEnv: (vars?: Record<string, Schema>, types?: Record<string, Schema>, schemes?: Record<string, TypeScheme>, accessors?: Record<string, Schema>) => Env;
|
|
76
|
+
declare const createEnv: (vars?: Record<string, Schema>, types?: Record<string, Schema>, schemes?: Record<string, TypeScheme>, accessors?: Record<string, Schema>, asserters?: ReadonlySet<string>, matchers?: ReadonlySet<string>, modules?: Record<string, Schema>) => Env;
|
|
216
77
|
/** Resolve um tipo nomeado (`type User = …`) declarado no ambiente. */
|
|
217
78
|
declare const resolveNamed: (env: Env, name: string) => Schema | undefined;
|
|
218
79
|
/** Resolve um type scheme (`type Pair<A, B> = …`) declarado no ambiente. */
|
|
219
80
|
declare const resolveScheme: (env: Env, name: string) => TypeScheme | undefined;
|
|
220
81
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
/** Igualdade estrutural: cada um é atribuível ao outro. */
|
|
224
|
-
declare function equals(a: Schema, b: Schema, schemes?: Schemes): boolean;
|
|
225
|
-
/**
|
|
226
|
-
* Normaliza uma união: achata, absorve `any`/`unknown`, deduplica e remove
|
|
227
|
-
* membros subsumidos por outro (`string | "x"` → `string`). Colapsa união de um
|
|
228
|
-
* membro no próprio membro. União vazia permanece vazia (renderiza `never`).
|
|
229
|
-
*/
|
|
230
|
-
declare function normalizeUnion(members: readonly Schema[]): Schema;
|
|
231
|
-
|
|
232
|
-
/**
|
|
233
|
-
* O supremo estrutural de `a` e `b`: o menor `Schema` ao qual ambos são
|
|
234
|
-
* atribuíveis. `unknown` é a unidade (sem-evidência); `any` é absorvente.
|
|
235
|
-
*/
|
|
236
|
-
declare function join(a: Schema, b: Schema): Schema;
|
|
237
|
-
/**
|
|
238
|
-
* Dobra uma lista de formas no seu supremo comum. Lista vazia → `never` (⊥, a
|
|
239
|
-
* identidade do supremo). Um membro → ele mesmo. É a operação do schema-reducer:
|
|
240
|
-
* `joinAll(amostras.map(inferValue))` descreve todas as amostras.
|
|
241
|
-
*/
|
|
242
|
-
declare function joinAll(members: readonly Schema[]): Schema;
|
|
243
|
-
|
|
244
|
-
/** Um membro que pode seguir a partir de um tipo (item de autocomplete). */
|
|
245
|
-
interface Completion {
|
|
246
|
-
/** Nome da propriedade, ou `"[]"` para o elemento de um array. */
|
|
247
|
-
readonly key: string;
|
|
248
|
-
readonly type: Schema;
|
|
249
|
-
readonly optional: boolean;
|
|
250
|
-
}
|
|
251
|
-
/** Resultado de navegar um path: o tipo final + o que pode seguir dele. */
|
|
252
|
-
interface Discovery {
|
|
253
|
-
readonly type: Schema;
|
|
254
|
-
readonly completions: readonly Completion[];
|
|
255
|
-
}
|
|
256
|
-
/**
|
|
257
|
-
* Navega `path` a partir de `schema`. Retorna o tipo alcançado e suas
|
|
258
|
-
* completions, ou `null` se algum segmento não existir no tipo. Path vazio
|
|
259
|
-
* devolve o próprio tipo e suas completions.
|
|
260
|
-
*/
|
|
261
|
-
declare function discover(schema: Schema, path: readonly string[], schemes?: Schemes): Discovery | null;
|
|
262
|
-
|
|
263
|
-
/** Ligações `nome da var → tipo` (o resultado de `unify`/aplicação de scheme). */
|
|
264
|
-
type Bindings = Readonly<Record<string, Schema>>;
|
|
265
|
-
/** Aplica `bindings` a `schema`, trocando cada `var` ligada pelo seu tipo. */
|
|
266
|
-
declare function substitute(schema: Schema, bindings: Bindings, seen?: WeakSet<object>): Schema;
|
|
267
|
-
|
|
268
|
-
/**
|
|
269
|
-
* Liga as `var`s de `pattern` aos tipos correspondentes em `actual`. Devolve as
|
|
270
|
-
* ligações estendidas, ou `null` se forem incompatíveis. `actual` que seja
|
|
271
|
-
* `any`/`unknown` não constrange vars (deixa-as livres).
|
|
272
|
-
*/
|
|
273
|
-
declare function unify(pattern: Schema, actual: Schema, bindings?: Bindings): Bindings | null;
|
|
274
|
-
/** Resultado de instanciar uma assinatura contra argumentos. */
|
|
275
|
-
interface Instantiation {
|
|
276
|
-
readonly returns: Schema;
|
|
277
|
-
readonly bindings: Bindings;
|
|
278
|
-
}
|
|
279
|
-
/**
|
|
280
|
-
* Instancia uma função genérica: unifica cada argumento contra o parâmetro
|
|
281
|
-
* correspondente (ligando as `var`s) e devolve o retorno já substituído.
|
|
282
|
-
* Falha (`null`) se algum argumento não unificar. Um parâmetro `variadic`
|
|
283
|
-
* absorve os argumentos restantes (cada um unifica contra o tipo do rest).
|
|
284
|
-
*/
|
|
285
|
-
declare function instantiate(sig: FnSchema, args: readonly Schema[]): Instantiation | null;
|
|
286
|
-
/**
|
|
287
|
-
* Versão tolerante de {@link instantiate} para o editor/checker: nunca falha —
|
|
288
|
-
* argumentos que não unificam são ignorados, e `var`s não ligadas permanecem
|
|
289
|
-
* (útil para aplicação parcial e enquanto o usuário ainda digita).
|
|
290
|
-
*/
|
|
291
|
-
declare function instantiateLoose(sig: FnSchema, args: readonly Schema[]): Instantiation;
|
|
292
|
-
/** Aterra as `var`s remanescentes em `unknown` (para exibição do resultado). */
|
|
293
|
-
declare function groundVars(schema: Schema, seen?: WeakSet<object>): Schema;
|
|
294
|
-
|
|
295
|
-
/** Há um scheme registrado para este `apply` (com aridade compatível)? */
|
|
296
|
-
declare function isScheme(t: Schema, schemes: Schemes): boolean;
|
|
82
|
+
type Severity = "error" | "warning";
|
|
83
|
+
type DiagnosticCode = "not-assignable" | "unknown-name" | "not-callable" | "no-such-member" | "not-object" | "const-needs-init" | "cannot-redeclare" | "unknown-module" | "missing-argument" | "excess-argument" | "excess-property" | "spread-argument" | "props-mismatch" | "no-matching-overload" | "constraint-violation" | "unsupported" | "forbidden-member" | "cast-unsound" | "node-not-allowed" | "name-not-allowed" | "type-feature-not-allowed" | "any-not-allowed" | "too-deep" | "too-complex-union" | "too-large" | "wrong-result-type";
|
|
297
84
|
/**
|
|
298
|
-
*
|
|
299
|
-
* `
|
|
300
|
-
*
|
|
85
|
+
* A **classe** do diagnóstico — espelha a divisão de passes do `tsc` (que nós
|
|
86
|
+
* fundimos num walk só): `semantic` é o que o **binder** do tsc pega (validade do
|
|
87
|
+
* programa, independe de tipos — nome inexistente, redeclaração, módulo, `const`
|
|
88
|
+
* sem init, recurso fora da Linguagem); `type` é o que o **checker** de tipos pega
|
|
89
|
+
* (relações/compatibilidade); `capability` é política/limite (feature gated, caps).
|
|
90
|
+
* O `kind` deriva do `code` (fonte única, mapa `KIND`) — o consumidor (editor/nocode)
|
|
91
|
+
* distingue "isto é programa inválido" de "isto é incompatibilidade de tipo".
|
|
301
92
|
*/
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
type Severity = "error" | "warning";
|
|
305
|
-
type DiagnosticCode = "not-assignable" | "unknown-name" | "not-callable" | "not-newable" | "no-such-member" | "not-object" | "const-needs-init" | "missing-argument" | "unsupported" | "cast-unsound" | "node-not-allowed" | "name-not-allowed" | "too-deep" | "too-large" | "wrong-result-type";
|
|
93
|
+
type DiagnosticKind = "semantic" | "type" | "capability";
|
|
306
94
|
interface Diagnostic {
|
|
307
95
|
readonly code: DiagnosticCode;
|
|
96
|
+
/** A classe do diagnóstico (deriva do `code`) — ver {@link DiagnosticKind}. */
|
|
97
|
+
readonly kind: DiagnosticKind;
|
|
308
98
|
readonly severity: Severity;
|
|
309
99
|
/** O nó culpado — identidade por referência. */
|
|
310
100
|
readonly node: BaseNode;
|
|
@@ -312,7 +102,8 @@ interface Diagnostic {
|
|
|
312
102
|
}
|
|
313
103
|
/**
|
|
314
104
|
* Builder genérico de diagnóstico (severidade configurável). Usado pelos
|
|
315
|
-
* guardrails, que têm seu próprio catálogo de mensagens em `guard`.
|
|
105
|
+
* guardrails, que têm seu próprio catálogo de mensagens em `guard`. O `kind`
|
|
106
|
+
* deriva do `code` (mesma fonte única).
|
|
316
107
|
*/
|
|
317
108
|
declare const makeDiagnostic: (code: DiagnosticCode, node: BaseNode, message: string, severity?: Severity) => Diagnostic;
|
|
318
109
|
/**
|
|
@@ -320,15 +111,23 @@ declare const makeDiagnostic: (code: DiagnosticCode, node: BaseNode, message: st
|
|
|
320
111
|
* por `format`.
|
|
321
112
|
*/
|
|
322
113
|
declare const diag: {
|
|
323
|
-
notAssignable: (node: BaseNode, actual: Schema, expected: Schema) => Diagnostic;
|
|
114
|
+
notAssignable: (node: BaseNode, actual: Schema, expected: Schema, schemes?: Schemes) => Diagnostic;
|
|
324
115
|
unknownName: (node: BaseNode, name: string) => Diagnostic;
|
|
325
116
|
notCallable: (node: BaseNode, type: Schema) => Diagnostic;
|
|
326
|
-
notNewable: (node: BaseNode, type: Schema) => Diagnostic;
|
|
327
117
|
noSuchMember: (node: BaseNode, type: Schema, key: string) => Diagnostic;
|
|
328
118
|
notObject: (node: BaseNode, type: Schema) => Diagnostic;
|
|
329
119
|
constNeedsInit: (node: BaseNode) => Diagnostic;
|
|
330
120
|
missingArgument: (node: BaseNode, name: string, expected: Schema) => Diagnostic;
|
|
121
|
+
unknownModule: (node: BaseNode, source: string) => Diagnostic;
|
|
122
|
+
cannotRedeclare: (node: BaseNode, name: string) => Diagnostic;
|
|
123
|
+
excessArgument: (node: BaseNode, expected: number, got: number) => Diagnostic;
|
|
124
|
+
excessProperty: (node: BaseNode, name: string, target: Schema) => Diagnostic;
|
|
125
|
+
spreadArgument: (node: BaseNode) => Diagnostic;
|
|
126
|
+
propsMismatch: (node: BaseNode, props: Schema, detail: string) => Diagnostic;
|
|
127
|
+
noMatchingOverload: (node: BaseNode, type: Schema, argTypes: readonly Schema[]) => Diagnostic;
|
|
128
|
+
constraintViolation: (node: BaseNode, name: string, actual: Schema, bound: Schema) => Diagnostic;
|
|
331
129
|
unsupported: (node: BaseNode, what: string) => Diagnostic;
|
|
130
|
+
forbiddenMember: (node: BaseNode, key: string) => Diagnostic;
|
|
332
131
|
/**
|
|
333
132
|
* Cast (`x as T`) entre tipos que não se sobrepõem em nenhum sentido. Warning
|
|
334
133
|
* (não erro): o cast é um escape-hatch explícito — `unknown`/`any` passam
|
|
@@ -398,6 +197,20 @@ interface CheckOptions {
|
|
|
398
197
|
readonly resultType?: Schema;
|
|
399
198
|
}
|
|
400
199
|
declare function check(node: Node, env: Env, opts?: CheckOptions): CheckResult;
|
|
200
|
+
/**
|
|
201
|
+
* Extrai o **tipo-superfície** de um módulo (o ".d.ts sem arquivo", o dual do import):
|
|
202
|
+
* roda o `check` e projeta os bindings de topo (`const`/`function`) num `object` Schema
|
|
203
|
+
* `{ nome: tipoInferido }`. É como o `tsc` faz o declaration emit — só que aqui o checker
|
|
204
|
+
* **já infere** os tipos (D5/D6 scope-flow), então é uma projeção do overlay, sem Babel
|
|
205
|
+
* nem serialização pra sintaxe. O resultado é exatamente o que outro módulo consome via
|
|
206
|
+
* `env.modules[especificador]` — os dois lados se fecham. (Filtragem por `export` explícito
|
|
207
|
+
* entra quando `export` for implementado; hoje projeta toda a superfície de topo — o caso
|
|
208
|
+
* "inferir o tipo de um algoritmo que não declarou tipos".)
|
|
209
|
+
*/
|
|
210
|
+
declare function extractModuleType(program: Node, env: Env, opts?: CheckOptions): {
|
|
211
|
+
type: ObjectSchema;
|
|
212
|
+
diagnostics: readonly Diagnostic[];
|
|
213
|
+
};
|
|
401
214
|
|
|
402
215
|
/** Contexto opcional de um guard (o overlay de tipos, p/ regras type-aware). */
|
|
403
216
|
interface GuardContext {
|
|
@@ -464,6 +277,8 @@ declare const annotate: <N extends BaseNode>(node: N, type: Schema) => N & {
|
|
|
464
277
|
declare const annotateReturn: <N extends BaseNode>(fn: N, type: Schema) => N & {
|
|
465
278
|
returnType: Schema;
|
|
466
279
|
};
|
|
280
|
+
/** Cast `x as T` — `{ expression, typeAnnotation }`; tipa a expressão, resulta `T`. */
|
|
281
|
+
declare const asExpression: (expression: BaseNode, type: Schema) => BaseNode;
|
|
467
282
|
|
|
468
283
|
/** O tipo inferido de `node`, ou `undefined` se o nó não foi tipado. */
|
|
469
284
|
declare function typeAt(overlay: TypeOverlay, node: BaseNode): Schema | undefined;
|
|
@@ -485,4 +300,4 @@ declare function scopeCompletions(overlay: TypeOverlay, node: BaseNode): readonl
|
|
|
485
300
|
/** Os diagnósticos que apontam para `node`. */
|
|
486
301
|
declare function diagnosticsAt(diagnostics: readonly Diagnostic[], node: BaseNode): readonly Diagnostic[];
|
|
487
302
|
|
|
488
|
-
export { type
|
|
303
|
+
export { type CheckOptions, type CheckResult, type Diagnostic, type DiagnosticCode, type DiagnosticKind, type DiagnosticSink, type Env, FUNCTION_KINDS, type Guard, type GuardContext, type Profile, type Scope, type Severity, type TypeOverlay, annotate, annotateReturn, asExpression, calleeAllowlist, capabilityNodes, check, childScope, createEnv, createSink, diag, diagnosticsAt, extractModuleType, fromCapability, guard, guardsFromCompiled, lookup, makeDiagnostic, maxArgs, maxCallNesting, maxDepth, maxFunctionNesting, maxNestingOf, maxNodes, memberCompletions, memberDepth, resolveNamed, resolveScheme, resultType, rootScope, scopeAt, scopeCompletions, typeAt, visibleNames };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {rootScope,childScope,lookup,visibleNames,walk,AST_MARKER,childrenOf}from'@tslite/core';import {compileProfile,nodeViolation}from'@tslite/capability';import {fromJson}from'@tslite/codec';var R=e=>Object.freeze(e),i={any:R({t:"any"}),unknown:R({t:"unknown"}),string:R({t:"string"}),number:R({t:"number"}),boolean:R({t:"boolean"}),null:R({t:"null"}),undefined:R({t:"undefined"}),literal:e=>({t:"literal",value:e}),object:e=>({t:"object",props:e}),array:e=>({t:"array",items:e}),fn:(e,n)=>({t:"fn",params:e,returns:n}),ctor:(e,n)=>({t:"fn",params:e,returns:n,construct:{params:e,returns:n}}),var:e=>({t:"var",name:e}),apply:(e,n=[])=>({t:"apply",name:e,args:n}),promise:e=>({t:"apply",name:"Promise",args:[e]}),union:e=>{let n=[];for(let t of e)t.t==="union"?n.push(...t.of):n.push(t);return {t:"union",of:n}}};function q(e){if(e.t==="undefined")return {type:{t:"union",of:[]},hadUndefined:true};if(e.t==="union"&&e.of.some(n=>n.t==="undefined")){let n=e.of.filter(t=>t.t!=="undefined");return {type:n.length===1?n[0]:{t:"union",of:n},hadUndefined:true}}return {type:e,hadUndefined:false}}function z(e,n=new WeakSet){switch(e.t){case "string":case "number":case "boolean":case "null":case "literal":return true;case "array":return n.has(e)?true:(n.add(e),z(q(e.items).type,n));case "object":return n.has(e)?true:(n.add(e),Object.values(e.props).every(t=>z(q(t.type).type,n)));case "union":return n.has(e)?true:(n.add(e),e.of.every(t=>z(t,n)));case "undefined":case "fn":case "var":case "apply":case "any":case "unknown":return false}}var _e=e=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e);function b(e,n=new WeakSet){switch(e.t){case "any":case "unknown":case "string":case "number":case "boolean":case "null":case "undefined":return e.t;case "var":return e.name;case "literal":return typeof e.value=="string"?JSON.stringify(e.value):String(e.value);case "array":{let t=b(e.items,n);return Je(e.items)?`(${t})[]`:`${t}[]`}case "union":{if(n.has(e))return "\u2026";n.add(e);let t=e.of.length===0?"never":e.of.map(r=>b(r,n)).join(" | ");return n.delete(e),t}case "object":{if(n.has(e))return "\u2026";n.add(e);let t=Object.entries(e.props),r=t.map(([a,o])=>`${_e(a)?a:JSON.stringify(a)}${o.optional?"?":""}: ${b(o.type,n)}`).join("; ");return n.delete(e),t.length===0?"{}":`{ ${r} }`}case "fn":{if(n.has(e))return "\u2026";n.add(e);let t=e.params.map(a=>{let o=a.variadic?"...":"",s=a.optional&&!a.variadic?"?":"";return `${o}${a.name}${s}: ${b(a.type,n)}`}).join(", "),r=b(e.returns,n);return n.delete(e),`(${t}) => ${r}`}case "apply":{if(n.has(e))return "\u2026";n.add(e);let t=e.args.length===0?e.name:`${e.name}<${e.args.map(r=>b(r,n)).join(", ")}>`;return n.delete(e),t}}}function Je(e){return e.t==="union"&&e.of.length>0||e.t==="fn"}function N(e,n,t=new WeakSet){switch(e.t){case "var":return n[e.name]??e;case "array":return {t:"array",items:N(e.items,n,t)};case "union":return {t:"union",of:e.of.map(r=>N(r,n,t))};case "object":{if(t.has(e))return e;t.add(e);let r={};for(let a in e.props){let o=e.props[a];r[a]={type:N(o.type,n,t),optional:o.optional};}return t.delete(e),{t:"object",props:r}}case "fn":{if(t.has(e))return e;t.add(e);let a={t:"fn",params:e.params.map(o=>({...o,type:N(o.type,n,t)})),returns:N(e.returns,n,t)};return t.delete(e),a}case "apply":return {t:"apply",name:e.name,args:e.args.map(r=>N(r,n,t))};default:return e}}function O(e,n){if(e.t!=="apply")return false;let t=n[e.name];return t!==void 0&&t.params.length===e.args.length}function A(e,n){if(e.t!=="apply")return e;let t=n[e.name];if(!t||t.params.length!==e.args.length)return e;let r={};return t.params.forEach((a,o)=>r[a]=e.args[o]),N(t.body,r)}function B(e){switch(e.t){case "literal":return `#${typeof e.value}:${String(e.value)}`;case "object":return `{${Object.keys(e.props).sort().map(n=>`${n}${e.props[n].optional?"?":""}:${B(e.props[n].type)}`).join(",")}}`;case "array":return `[${B(e.items)}]`;case "union":return `(${e.of.map(B).sort().join("|")})`;case "fn":return `(${e.params.map(n=>B(n.type)).join(",")})=>${B(e.returns)}`;case "var":return `v:${e.name}`;case "apply":return `${e.name}<${e.args.map(B).join(",")}>`;default:return e.t}}function S(e,n,t={}){return T(e,n,{seen:new WeakMap,exp:new Set,schemes:t})}function Q(e,n,t={}){return S(e,n,t)&&S(n,e,t)}function T(e,n,t){if(e.t==="any"||n.t==="any"||n.t==="unknown")return true;if(e.t==="unknown")return false;if(!(e.t==="apply"&&n.t==="apply"&&e.name===n.name&&e.args.length===n.args.length)&&(O(e,t.schemes)||O(n,t.schemes))){let o=`${B(e)}\u2264${B(n)}`;if(t.exp.has(o))return true;t.exp.add(o);let s=T(A(e,t.schemes),A(n,t.schemes),t);return t.exp.delete(o),s}let a=t.seen.get(e);if(a?.has(n))return true;if(a||(a=new WeakSet,t.seen.set(e,a)),a.add(n),e.t==="union")return e.of.every(o=>T(o,n,t));if(n.t==="union")return n.of.some(o=>T(e,o,t));switch(n.t){case "literal":return e.t==="literal"&&e.value===n.value;case "string":case "number":case "boolean":case "null":case "undefined":return e.t===n.t?true:e.t==="literal"&&He(e.value)===n.t;case "array":return e.t==="array"&&T(e.items,n.items,t);case "object":return e.t==="object"&&Ze(e,n,t);case "fn":return e.t==="fn"&&Ye(e,n,t);case "var":return e.t==="var"&&e.name===n.name;case "apply":return e.t==="apply"&&e.name===n.name&&e.args.length===n.args.length&&e.args.every((o,s)=>T(o,n.args[s],t))}}var He=e=>typeof e;function Ze(e,n,t){for(let r in n.props){let a=n.props[r],o=e.props[r];if(!o){if(!a.optional)return false;continue}if(o.optional&&!a.optional||!T(o.type,a.type,t))return false}return true}function Ye(e,n,t){if(!T(e.returns,n.returns,t))return false;for(let r=0;r<e.params.length;r++){let a=e.params[r];if(a.variadic)break;let o=n.params[r];if(!o){if(a.optional)continue;return false}if(!T(o.type,a.type,t))return false}return true}function k(e){let n=[];for(let r of e)r.t==="union"?n.push(...r.of):n.push(r);if(n.some(r=>r.t==="any"))return i.any;let t=[];for(let r of n)if(!t.some(a=>S(r,a))){for(let a=t.length-1;a>=0;a--)S(t[a],r)&&t.splice(a,1);t.push(r);}return t.length===1?t[0]:{t:"union",of:t}}var Qe=i.union([]);function Te(e,n){return X(e,n,new WeakMap)}function Xe(e){return e.reduce(Te,Qe)}function X(e,n,t){if(e.t==="any"||n.t==="any")return i.any;if(e===n)return e;let r=t.get(e)?.get(n);if(r)return r;if(e.t==="object"&&n.t==="object")return en(e,n,t);if(e.t==="array"&&n.t==="array"){let a={t:"array",items:i.unknown};return xe(t,e,n,a),a.items=X(e.items,n.items,t),a}return k([e,n])}function en(e,n,t){let r={t:"object",props:{}};xe(t,e,n,r);for(let a in e.props){let o=e.props[a],s=n.props[a];if(s){let l=X(o.type,s.type,t);r.props[a]=o.optional||s.optional?{type:l,optional:true}:{type:l};}else r.props[a]={type:o.type,optional:true};}for(let a in n.props)a in e.props||(r.props[a]={type:n.props[a].type,optional:true});return r}function xe(e,n,t,r){let a=e.get(n);a||(a=new WeakMap,e.set(n,a)),a.set(t,r);}function F(e,n,t={}){let r=e;for(let a of n){let o=ee(r,a,t);if(o===null)return null;r=o;}return {type:r,completions:ne(r,t)}}var nn=e=>e==="[]"||/^\d+$/.test(e);function ee(e,n,t,r=new Set){if(O(e,t)){let a=B(e);if(r.has(a))return null;r.add(a);let o=ee(A(e,t),n,t,r);return r.delete(a),o}switch(e.t){case "any":return e;case "object":return e.props[n]?.type??null;case "array":return nn(n)?e.items:null;case "union":{let a=e.of.map(o=>ee(o,n,t,r)).filter(o=>o!==null);return a.length?k(a):null}default:return null}}function ne(e,n,t=new WeakSet,r=new Set){if(O(e,n)){let a=B(e);if(r.has(a))return [];r.add(a);let o=ne(A(e,n),n,t,r);return r.delete(a),o}switch(e.t){case "object":return Object.entries(e.props).map(([a,o])=>({key:a,type:o.type,optional:!!o.optional}));case "array":return [{key:"[]",type:e.items,optional:false}];case "union":{if(t.has(e))return [];t.add(e);let a=[],o=new Set;for(let s of e.of)for(let l of ne(s,n,t,r))o.has(l.key)||(o.add(l.key),a.push(l));return t.delete(e),a}default:return []}}function x(e,n,t={}){if(e.t==="var"){let r=t[e.name];return r?S(n,r)||S(r,n)?t:null:{...t,[e.name]:n}}if(n.t==="any"||n.t==="unknown")return t;switch(e.t){case "array":return n.t==="array"?x(e.items,n.items,t):null;case "object":{if(n.t!=="object")return null;let r=t;for(let a in e.props){let o=e.props[a],s=n.props[a];if(!s){if(o.optional)continue;return null}if(r=x(o.type,s.type,r),r===null)return null}return r}case "fn":{if(n.t!=="fn")return null;let r=x(e.returns,n.returns,t);if(r===null)return null;let a=Math.min(e.params.length,n.params.length);for(let o=0;o<a;o++)if(r=x(e.params[o].type,n.params[o].type,r),r===null)return null;return r}case "apply":{if(n.t!=="apply"||n.name!==e.name||n.args.length!==e.args.length)return null;let r=t;for(let a=0;a<e.args.length;a++)if(r=x(e.args[a],n.args[a],r),r===null)return null;return r}default:return S(n,e)?t:null}}function tn(e,n){let t={};for(let r=0;r<e.params.length;r++){let a=e.params[r];if(a.variadic){for(let o=r;o<n.length;o++)if(t=x(a.type,n[o],t),t===null)return null;break}if(r>=n.length){if(a.optional)continue;return null}if(t=x(a.type,n[r],t),t===null)return null}return {returns:N(e.returns,t),bindings:t}}function V(e,n){let t={};for(let r=0;r<e.params.length&&r<n.length;r++){let a=e.params[r],o=x(a.type,n[r],t);o!==null&&(t=o);}return {returns:N(e.returns,t),bindings:t}}function C(e,n=new WeakSet){switch(e.t){case "var":return i.unknown;case "array":return {t:"array",items:C(e.items,n)};case "union":return {t:"union",of:e.of.map(t=>C(t,n))};case "object":{if(n.has(e))return e;n.add(e);let t={};for(let r in e.props){let a=e.props[r];t[r]={type:C(a.type,n),optional:a.optional};}return n.delete(e),{t:"object",props:t}}case "fn":{if(n.has(e))return e;n.add(e);let r={t:"fn",params:e.params.map(a=>({...a,type:C(a.type,n)})),returns:C(e.returns,n)};return n.delete(e),r}case "apply":return {t:"apply",name:e.name,args:e.args.map(t=>C(t,n))};default:return e}}var je=(e={})=>rootScope(e),j=(e,n)=>childScope(e,n),P=(e,n)=>lookup(e,n),te=e=>visibleNames(e),ln=(e={},n={},t={},r={})=>({scope:je(e),types:n,schemes:t,accessors:r}),un=(e,n)=>e.types[n],pn=(e,n)=>e.schemes[n];var D=(e,n,t)=>({code:e,severity:"error",node:n,message:t}),E=(e,n,t,r="error")=>({code:e,severity:r,node:n,message:t}),h={notAssignable:(e,n,t)=>D("not-assignable",e,`Type '${b(n)}' is not assignable to type '${b(t)}'.`),unknownName:(e,n)=>D("unknown-name",e,`Cannot find name '${n}'.`),notCallable:(e,n)=>D("not-callable",e,`Type '${b(n)}' is not callable.`),notNewable:(e,n)=>D("not-newable",e,`Type '${b(n)}' is not newable \u2014 only host constructors (with a construct signature) can be used with 'new'.`),noSuchMember:(e,n,t)=>D("no-such-member",e,`Property '${t}' does not exist on type '${b(n)}'.`),notObject:(e,n)=>D("not-object",e,`Type '${b(n)}' has no members to access.`),constNeedsInit:e=>D("const-needs-init",e,"'const' declarations must be initialized."),missingArgument:(e,n,t)=>D("missing-argument",e,`Missing argument '${n}' of type '${b(t)}'.`),unsupported:(e,n)=>D("unsupported",e,`${n} is not supported in this language.`),castUnsound:(e,n,t)=>E("cast-unsound",e,`Conversion of type '${b(n)}' to type '${b(t)}' may be a mistake \u2014 neither sufficiently overlaps the other. Cast through 'unknown' first if intentional.`,"warning")};function re(){let e=[];return {all:e,report(n){e.push(n);},hasErrors(){return e.some(n=>n.severity==="error")}}}function oe(e,n,t={}){return n.flatMap(r=>r(e,t))}function K(e,n){let t=r=>{n(r);for(let a of childrenOf(r))t(a);};t(e);}var mn=e=>Array.isArray(e)?e:[e],De=["ArrowFunctionExpression","FunctionExpression","FunctionDeclaration"];function se(e,n="error"){return t=>{let r=[];return K(t,a=>{let o=nodeViolation(a,e);o&&r.push(E("node-not-allowed",a,`'${o}' is not allowed by the capability profile.`,n));}),r}}function ie(e,n="error"){let t=new Set(e);return r=>{let a=[];return K(r,o=>{if(o.type!=="CallExpression")return;let s=o.callee;if(s.type!=="Identifier")a.push(E("name-not-allowed",s,"Only direct calls to allowed functions are permitted.",n));else {let l=s.name;t.has(l)||a.push(E("name-not-allowed",s,`Function '${l}' is not allowed here.`,n));}}),a}}function _(e,n,t={}){let r=new Set(mn(e)),a=t.severity??"error",o=[...r].join("/");return s=>{let l=[],m=(c,f)=>{let d=r.has(c.type),y=d?f+1:f;d&&y>n&&l.push(E("too-deep",c,`Nesting of ${o} exceeds ${n}${t.hint?` \u2014 ${t.hint}`:""}.`,a));for(let g of childrenOf(c))m(g,y);};return m(s,0),l}}var le=(e=3,n="error")=>_(De,e,{hint:"use a pipe instead of nesting functions",severity:n}),ue=(e,n="error")=>_("CallExpression",e,{hint:"use a pipe instead of nesting calls",severity:n}),pe=(e,n="error")=>_("MemberExpression",e,{severity:n});function ce(e,n="error"){return t=>{let r=[],a=(o,s)=>{if(s>e){r.push(E("too-deep",o,`Expression nesting exceeds ${e}.`,n));return}for(let l of childrenOf(o))a(l,s+1);};return a(t,0),r}}function me(e,n="error"){return t=>{let r=0;return K(t,()=>{r++;}),r>e?[E("too-large",t,`Expression has ${r} nodes (max ${e}).`,n)]:[]}}function ye(e,n="error"){return t=>{let r=[];return K(t,a=>{if(a.type==="CallExpression"){let o=a.arguments;o&&o.length>e&&r.push(E("too-large",a,`Call has ${o.length} arguments (max ${e}).`,n));}}),r}}function fe(e,n={},t="error"){return (r,a)=>{let o=a.overlay?.get(r)?.type;return o?S(o,e,n)?[]:[E("wrong-result-type",r,`Result type '${b(o)}' is not assignable to the required '${b(e)}'.`,t)]:[]}}function $e(e){let n=[se(e)];return e.hostAllow!=="*"&&n.push(ie([...e.hostAllow])),n}function de(e){return $e(compileProfile(e))}var Sn=e=>{let n={};for(let t of Object.keys(e))n[t]={params:[],body:e[t]};return n};function hn(e){let n=[];return e.maxDepth!==void 0&&n.push(ce(e.maxDepth)),e.maxNodes!==void 0&&n.push(me(e.maxNodes)),e.maxArgs!==void 0&&n.push(ye(e.maxArgs)),e.maxFunctionNesting!==void 0&&n.push(le(e.maxFunctionNesting)),e.maxCallNesting!==void 0&&n.push(ue(e.maxCallNesting)),e.memberDepth!==void 0&&n.push(pe(e.memberDepth)),n}function gn(e,n,t={}){let r={...Sn(n.types),...n.schemes,...bn(e)},a={overlay:new WeakMap,sink:re(),env:n,schemes:r},o=p(e,n.scope,a),s=[];t.profile&&s.push(...de(t.profile)),t.limits&&s.push(...hn(t.limits)),t.resultType&&s.push(fe(t.resultType,r));let l=s.length?[...a.sink.all,...oe(e,s,{overlay:a.overlay})]:a.sink.all;return {type:o,overlay:a.overlay,diagnostics:l}}var bn=e=>{let n={};return walk(e,{TSTypeAliasDeclaration(t){let r=t;r.id?.name&&r.typeAnnotation&&(n[r.id.name]={params:r.typeParameters??[],body:r.typeAnnotation});}}),n},ke=e=>e.typeAnnotation,Ie=e=>e.returnType,u=(e,n,t,r)=>(e.overlay.set(n,{type:t,scope:r}),t),Se=e=>e.type==="ArrowFunctionExpression",Le=e=>e.t==="apply"&&e.name==="Promise"&&e.args.length===1,he=e=>Le(e)?e.args[0]:e,J=e=>Le(e)?e:i.promise(e);function p(e,n,t){switch(e.type){case "Literal":return u(t,e,Ge(e),n);case "Identifier":{let r=e.name,a=P(n,r);return a===void 0?r==="undefined"?u(t,e,i.undefined,n):(t.sink.report(h.unknownName(e,r)),u(t,e,i.unknown,n)):u(t,e,a,n)}case "MemberExpression":return u(t,e,kn(e,n,t),n);case "CallExpression":return u(t,e,wn(e,n,t),n);case "NewExpression":return u(t,e,Bn(e,n,t),n);case "ArrowFunctionExpression":return Ne(e,n,t);case "FunctionDeclaration":return t.sink.report(h.unsupported(e,"function declaration (use 'const fn = () => \u2026')")),u(t,e,i.unknown,n);case "FunctionExpression":return t.sink.report(h.unsupported(e,"anonymous function (use an arrow)")),u(t,e,i.unknown,n);case "ThisExpression":return t.sink.report(h.unsupported(e,"'this'")),u(t,e,i.unknown,n);case "BlockStatement":return u(t,e,we(e,n,t),n);case "ReturnStatement":{let r=e.argument;return u(t,e,r?p(r,n,t):i.unknown,n)}case "IfStatement":return v(e,n,t),t.overlay.get(e)?.type??i.unknown;case "ForStatement":case "WhileStatement":case "DoWhileStatement":case "ForOfStatement":case "ForInStatement":case "BreakStatement":case "ContinueStatement":case "ThrowStatement":case "TryStatement":case "SwitchStatement":return v(e,n,t),t.overlay.get(e)?.type??i.unknown;case "AssignmentExpression":{let r=e;return p(r.left,n,t),u(t,e,p(r.right,n,t),n)}case "UpdateExpression":return p(e.argument,n,t),u(t,e,i.number,n);case "ExpressionStatement":return u(t,e,p(e.expression,n,t),n);case "VariableDeclaration":return Ee(e,n,t),u(t,e,i.unknown,n);case "TSTypeAliasDeclaration":return u(t,e,i.unknown,n);case "BinaryExpression":return u(t,e,On(e,n,t),n);case "LogicalExpression":{let r=e,a=p(r.left,n,t),o=p(r.right,n,t);return u(t,e,k([a,o]),n)}case "UnaryExpression":return u(t,e,Pn(e,n,t),n);case "ConditionalExpression":{let r=e;p(r.test,n,t);let a=p(r.consequent,n,t),o=p(r.alternate,n,t);return u(t,e,k([a,o]),n)}case "ObjectExpression":return u(t,e,In(e,n,t),n);case "ArrayExpression":return u(t,e,Ln(e,n,t),n);case "TemplateLiteral":{for(let r of e.expressions)p(r,n,t);return u(t,e,i.string,n)}case "AwaitExpression":{let r=e.argument,a=r?p(r,n,t):i.unknown;return u(t,e,he(a),n)}case "Program":return Be(e.body,n,t),u(t,e,i.unknown,n);case "JsonExpression":return u(t,e,be(e.body,n,t,e),n);case "ChainExpression":return u(t,e,k([p(e.expression,n,t),i.undefined]),n);case "TSAsExpression":{let r=e,a=p(r.expression,n,t),o=r.typeAnnotation;return !S(a,o,t.schemes)&&!S(o,a,t.schemes)&&t.sink.report(h.castUnsound(e,a,o)),u(t,e,o,n)}default:return t.sink.report(h.unsupported(e,`'${e.type}'`)),u(t,e,i.unknown,n)}}function Ge(e){let n=e;if(n.regex||n.bigint)return i.unknown;let t=n.value;if(t===null)return i.null;if(t===void 0)return i.undefined;switch(typeof t){case "string":return i.string;case "number":return i.number;case "boolean":return i.boolean;default:return i.unknown}}function kn(e,n,t){let r=p(e.object,n,t);if(e.computed){p(e.property,n,t);let s=F(r,["[]"],t.schemes);return s?s.type:i.unknown}let a=e.property.name,o=F(r,[a],t.schemes);return o?o.type:(r.t==="object"||r.t==="array"||r.t==="union"?t.sink.report(h.noSuchMember(e,r,a)):r.t!=="any"&&r.t!=="unknown"&&t.sink.report(h.notObject(e,r)),i.unknown)}function Nn(e){let n=r=>r&&r.type==="Literal"&&typeof r.value=="string"?r.value:null;if(e.length===1&&e[0].type==="ArrayExpression"){let r=[];for(let a of e[0].elements){let o=n(a);if(o===null)return null;r.push(o);}return r}let t=[];for(let r of e){let a=n(r);if(a===null)return null;t.push(a);}return t.length?t:null}function Me(e){if(e.type==="Identifier")return e.name;if(e.type==="MemberExpression"){let n=e;if(n.computed||n.property.type!=="Identifier")return null;let t=Me(n.object);return t===null?null:`${t}.${n.property.name}`}return null}function wn(e,n,t){let r=e.arguments,a=Me(e.callee);if(a){let f=t.env.accessors?.[a];if(f){let d=Nn(r);if(d){let y=F(f,d,t.schemes);return y?y.type:(t.sink.report(h.noSuchMember(e,f,d.join("."))),i.unknown)}return r.forEach(y=>p(y,n,t)),i.unknown}}let o=p(e.callee,n,t);if(o.t==="any")return r.forEach(f=>p(f,n,t)),i.any;if(o.t!=="fn")return r.forEach(f=>p(f,n,t)),t.sink.report(h.notCallable(e,o)),i.unknown;let s=o,l=r.map(f=>Se(f)?i.any:p(f,n,t)),m=V(s,l).bindings;r.forEach((f,d)=>{if(Se(f)){let y=N(s.params[d]?.type??i.any,m);l[d]=Ne(f,n,t,y);}});let{bindings:c}=V(s,l);return Ue(e,s,l,c,t),C(N(s.returns,c))}function Bn(e,n,t){let r=e.arguments,a=p(e.callee,n,t);if(a.t==="any")return r.forEach(c=>p(c,n,t)),i.any;let o=a.t==="fn"?a.construct:void 0;if(!o)return r.forEach(c=>p(c,n,t)),t.sink.report(h.notNewable(e,a)),i.unknown;let s={params:o.params,returns:o.returns},l=r.map(c=>Se(c)?i.any:p(c,n,t)),{bindings:m}=V(s,l);return Ue(e,s,l,m,t),C(N(o.returns,m))}function Ue(e,n,t,r,a){for(let o=0;o<n.params.length;o++){let s=n.params[o];if(s.variadic)break;let l=N(s.type,r);if(o>=t.length){s.optional||a.sink.report(h.missingArgument(e,s.name,l));continue}S(t[o],l,a.schemes)||a.sink.report(h.notAssignable(e.arguments[o],t[o],l));}}var We=e=>{let n=e.value;return n===null?i.null:typeof n=="string"||typeof n=="number"||typeof n=="boolean"?i.literal(n):Ge(e)},En=(e,n)=>{let t=e;for(let r=0;r<50&&t.t==="apply";r++){let a=A(t,n.schemes);if(a===t||a.t==="apply"&&a.name===t.name)break;t=a;}return t};function L(e,n,t,r){let a=En(n,r);switch(e.type){case "Literal":{let s=We(e);return S(s,n,r.schemes)||r.sink.report(h.notAssignable(e,s,n)),u(r,e,n,t)}case "ArrayExpression":{if(a.t==="array"){for(let s of e.elements){if(!s)continue;let l=s;l.type==="SpreadElement"?L(l.argument,n,t,r):L(l,a.items,t,r);}return u(r,e,n,t)}break}case "ObjectExpression":{if(a.t==="object"){let s={};for(let m of e.properties){let c=m;if(c.type==="SpreadElement"){p(c.argument,t,r);continue}let f=c,d=Ke(f),y=d!==null?a.props[d]?.type:void 0,g=y?L(f.value,y,t,r):p(f.value,t,r);d!==null&&(s[d]={type:g}),u(r,c,g,t);}let l={t:"object",props:s};return S(l,n,r.schemes)||r.sink.report(h.notAssignable(e,l,n)),u(r,e,n,t)}break}case "ArrowFunctionExpression":{if(a.t==="fn"){let s=Ne(e,t,r,a);return S(s,n,r.schemes)||r.sink.report(h.notAssignable(e,s,n)),u(r,e,n,t)}break}case "ConditionalExpression":{let s=e;return p(s.test,t,r),L(s.consequent,n,t,r),L(s.alternate,n,t,r),u(r,e,n,t)}}let o=p(e,t,r);return S(o,n,r.schemes)||r.sink.report(h.notAssignable(e,o,n)),u(r,e,o,t)}function vn(e){let n=Ie(e);return n?{t:"fn",params:e.params.map((r,a)=>({name:G(r)??`arg${a}`,type:ke(r)??i.unknown})),returns:e.async?J(n):n}:null}function Ne(e,n,t,r){let a=r&&r.t==="fn"?r:void 0,o={},s=e.params.map((y,g)=>{let w=y,M=G(w),$=ke(w)??a?.params[g]?.type??i.unknown;return M&&(o[M]=$),t.overlay.set(w,{type:$,scope:n}),{name:M??`arg${g}`,type:$}}),l=j(n,o),m=e.body,c=Ie(e);if(m.type!=="BlockStatement"&&c){let y=e.async?he(c):c;L(m,y,l,t);let g=e.async?J(c):c;return u(t,e,{t:"fn",params:s,returns:g},n)}let f=m.type==="BlockStatement"?u(t,m,we(m,l,t),l):p(m,l,t),d=e.async?J(f):f;if(c){let y=e.async?he(c):c,g=e.async?f:d;S(g,y,t.schemes)||t.sink.report(h.notAssignable(m,d,c));let w=e.async?J(c):c;return u(t,e,{t:"fn",params:s,returns:w},n)}return u(t,e,{t:"fn",params:s,returns:d},n)}function we(e,n,t){let{returns:r}=Be(e.body,n,t);return r.length?k(r):i.unknown}function Be(e,n,t){let r=n,a=[];for(let o of e){let s=o;if(s.type==="VariableDeclaration")r=Ee(s,r,t);else if(s.type==="FunctionDeclaration"){let l=p(s,r,t),m=G(s.id);m&&(r=j(r,{[m]:l}));}else if(s.type==="IfStatement"){a.push(...v(s,r,t));let l=s;!l.alternate&&H(l.consequent)&&(r=ge(r,ze(l.test,r,t.schemes).else));}else a.push(...v(s,r,t));}return {scope:r,returns:a}}var U={then:{},else:{}},Ve={string:i.string,number:i.number,boolean:i.boolean},W=e=>e.t==="union"?[...e.of]:[e];function Oe(e,n){let t=e,r=n;return e.type==="UnaryExpression"&&t.operator==="typeof"&&t.argument.type==="Identifier"&&n.type==="Literal"&&typeof r.value=="string"?{name:t.argument.name,tag:r.value}:null}function Cn(e,n){let t=Ve[n];if(!t)return null;if(e.t==="unknown"||e.t==="any")return t;let r=W(e).filter(a=>S(a,t));return r.length?k(r):t}function An(e,n){let t=Ve[n];if(!t||e.t==="unknown"||e.t==="any")return null;let r=W(e).filter(a=>!S(a,t));return r.length?k(r):null}function Fe(e,n){if(e.type==="Identifier"&&n.type==="Literal"){let t=We(n);if(t.t==="literal"||t.t==="null")return {name:e.name,lit:t}}return null}function Tn(e,n,t){return e.t==="unknown"||e.t==="any"||S(n,e,t)?n:null}function xn(e,n,t){let r=W(e),a=r.filter(o=>!Q(o,n,t));return a.length&&a.length<r.length?k(a):null}var qe=e=>e.t==="null"||e.t==="undefined",jn=e=>{if(e.t==="unknown"||e.t==="any")return null;let n=W(e),t=n.filter(r=>!qe(r));return t.length&&t.length<n.length?k(t):null},Dn=e=>{let n=W(e),t=n.filter(qe);return t.length&&t.length<n.length?k(t):null},Pe=e=>e.type==="Literal"&&e.value===null?"null":e.type==="Identifier"&&e.name==="undefined"?"undefined":null,I=(e,n,t)=>({then:n?{[e]:n}:{},else:t?{[e]:t}:{}}),$n=e=>e==="==="||e==="=="||e==="!=="||e==="!=";function ze(e,n,t){if(e.type==="BinaryExpression"){let r=e;if(!$n(r.operator))return U;let a=r.operator==="!=="||r.operator==="!=",o=r.left,s=r.right,l=Oe(o,s)??Oe(s,o);if(l){let y=P(n,l.name);if(!y)return U;let g=Cn(y,l.tag),w=An(y,l.tag);return a?I(l.name,w,g):I(l.name,g,w)}let m=Pe(o),c=Pe(s),f=m?s:c?o:null;if((m||c)&&f?.type==="Identifier"){let y=f.name,g=P(n,y);if(!g)return U;let M=r.operator==="=="||r.operator==="!="?["null","undefined"]:[m??c],$=W(g),ve=$.filter(Y=>M.includes(Y.t)),Z=$.filter(Y=>!M.includes(Y.t)),Ce=ve.length?k(ve):null,Ae=Z.length&&Z.length<$.length?k(Z):null;return a?I(y,Ae,Ce):I(y,Ce,Ae)}let d=Fe(o,s)??Fe(s,o);if(d){let y=P(n,d.name);if(!y)return U;let g=Tn(y,d.lit,t),w=xn(y,d.lit,t);return a?I(d.name,w,g):I(d.name,g,w)}return U}if(e.type==="Identifier"){let r=e.name,a=P(n,r);if(a)return I(r,jn(a),Dn(a))}return U}var ge=(e,n)=>Object.keys(n).length?j(e,n):e;function H(e){switch(e.type){case "ReturnStatement":case "ThrowStatement":return true;case "BlockStatement":{let n=e.body;return n.length>0&&H(n[n.length-1])}case "IfStatement":{let n=e;return !!n.alternate&&H(n.consequent)&&H(n.alternate)}default:return false}}function v(e,n,t){switch(e.type){case "ReturnStatement":{let r=e.argument,a=r?p(r,n,t):i.unknown;return u(t,e,a,n),[a]}case "IfStatement":{let r=e;p(r.test,n,t);let a=ze(r.test,n,t.schemes),o=v(r.consequent,ge(n,a.then),t);return r.alternate&&o.push(...v(r.alternate,ge(n,a.else),t)),u(t,e,i.unknown,n),o}case "BlockStatement":{let r=we(e,n,t);return u(t,e,r,n),r.t==="unknown"?[]:[r]}case "ForStatement":case "WhileStatement":case "DoWhileStatement":{let r=e,a=n;r.init&&(r.init.type==="VariableDeclaration"?a=Ee(r.init,a,t):p(r.init,a,t)),r.test&&p(r.test,a,t),r.update&&p(r.update,a,t);let o=v(r.body,a,t);return u(t,e,i.unknown,n),o}case "ForOfStatement":case "ForInStatement":{let r=e,a=p(r.right,n,t),o=e.type==="ForOfStatement"?a.t==="array"?a.items:i.unknown:i.string,s=Rn(r.left),l=s?j(n,{[s]:o}):n,m=v(r.body,l,t);return u(t,e,i.unknown,n),m}case "BreakStatement":case "ContinueStatement":return u(t,e,i.unknown,n),[];case "ThrowStatement":{let r=e.argument;return r&&p(r,n,t),u(t,e,i.unknown,n),[]}case "TryStatement":{let r=e,a=v(r.block,n,t);if(r.handler){let o=r.handler.param,s=o?G(o):null,l=s?j(n,{[s]:i.unknown}):n;a.push(...v(r.handler.body,l,t));}return r.finalizer&&a.push(...v(r.finalizer,n,t)),u(t,e,i.unknown,n),a}case "SwitchStatement":{let r=e;p(r.discriminant,n,t);let a=n,o=[];for(let s of r.cases){s.test&&p(s.test,a,t);let l=Be(s.consequent,a,t);a=l.scope,o.push(...l.returns);}return u(t,e,i.unknown,n),o}default:return p(e,n,t),[]}}var Rn=e=>{if(e.type==="VariableDeclaration"){let n=e.declarations[0];return n?G(n.id):null}return G(e)};function Ee(e,n,t){let r={};for(let a of e.declarations){let o=G(a.id),s=ke(a.id);if(!a.init){t.sink.report(h.constNeedsInit(a)),o&&(r[o]=s??i.unknown);continue}let l=s??(a.init.type==="ArrowFunctionExpression"?vn(a.init):null),m=o&&l?j(n,{[o]:l}):n,c;s?(L(a.init,s,m,t),c=s):c=p(a.init,m,t),u(t,a,c,n),o&&(r[o]=c);}return u(t,e,i.unknown,n),j(n,r)}function On(e,n,t){let r=p(e.left,n,t),a=p(e.right,n,t),o=e.operator;return o==="+"?S(r,i.string)||S(a,i.string)?i.string:i.number:Fn.has(o)?i.number:i.boolean}var Fn=new Set(["-","*","/","%","**","&","|","^","<<",">>",">>>"]);function Pn(e,n,t){switch(p(e.argument,n,t),e.operator){case "!":return i.boolean;case "-":case "+":case "~":return i.number;case "typeof":return i.string;case "delete":return i.boolean;case "void":return i.undefined;default:return i.unknown}}function In(e,n,t){let r={};for(let a of e.properties){let o=a;if(o.type==="SpreadElement"){p(o.argument,n,t);continue}let s=o,l=p(s.value,n,t),m=Ke(s);m!==null&&(r[m]={type:l}),u(t,o,l,n);}return {t:"object",props:r}}var Ke=e=>{if(e.computed)return null;let n=e.key;return n.type==="Identifier"?n.name:n.type==="Literal"?String(n.value??""):null};function Ln(e,n,t){let r=[];for(let a of e.elements){if(!a)continue;let o=a;if(o.type==="SpreadElement"){p(o.argument,n,t);continue}r.push(p(o,n,t));}return i.array(r.length?k(r):i.unknown)}function be(e,n,t,r){if(e===null)return i.null;switch(typeof e){case "string":return i.string;case "number":return i.number;case "boolean":return i.boolean;case "object":break;default:return i.unknown}if(Array.isArray(e)){let s=e.map(l=>be(l,n,t,r));return i.array(s.length?k(s):i.unknown)}let a=e;if(AST_MARKER in a){let s;try{s=fromJson(a);}catch{return t.sink.report(h.unsupported(r,`'#ast: ${String(a[AST_MARKER])}'`)),i.unknown}return p(s,n,t)}let o={};for(let s of Object.keys(a))o[s]={type:be(a[s],n,t,r)};return {t:"object",props:o}}var G=e=>e.type==="Identifier"?e.name:null;var Gn=(e,n)=>({...e,typeAnnotation:n}),Mn=(e,n)=>({...e,returnType:n});function Un(e,n){return e.get(n)?.type}function Wn(e,n){return e.get(n)?.scope}function Vn(e,n){let t=e.get(n)?.type;return t?F(t,[])?.completions??[]:[]}function qn(e,n){let t=e.get(n)?.scope;return t?[...te(t)].map(([r,a])=>({key:r,type:a,optional:false})):[]}function zn(e,n){return e.filter(t=>t.node===n)}export{De as FUNCTION_KINDS,Gn as annotate,Mn as annotateReturn,ie as calleeAllowlist,se as capabilityNodes,gn as check,j as childScope,ln as createEnv,re as createSink,h as diag,zn as diagnosticsAt,F as discover,Q as equals,A as expand1,b as format,de as fromCapability,C as groundVars,oe as guard,$e as guardsFromCompiled,tn as instantiate,V as instantiateLoose,O as isScheme,z as isSerializable,Te as join,Xe as joinAll,P as lookup,E as makeDiagnostic,ye as maxArgs,ue as maxCallNesting,ce as maxDepth,le as maxFunctionNesting,_ as maxNestingOf,me as maxNodes,Vn as memberCompletions,pe as memberDepth,k as normalizeUnion,un as resolveNamed,pn as resolveScheme,fe as resultType,je as rootScope,i as s,Wn as scopeAt,qn as scopeCompletions,N as substitute,S as subtype,Un as typeAt,x as unify,te as visibleNames,q as withoutUndefined};
|
|
1
|
+
import {s,format,typeDiff,formatTypeDiff,subtype,configureTypeLimits,TypeEvalLimitError,UnionTooComplexError,resetTypeLimits,discover,normalizeUnion,resolveTypeOp,isScheme,expand1,instantiateLoose,widenType,substitute,widenInferred,groundVars,withoutUndefined,widen,unify,ownProp,equals,typeFeatures}from'@tslite/type-core';export*from'@tslite/type-core';import {rootScope,childScope,lookup,visibleNames,walk,desugarJSX,AST_MARKER,childrenOf}from'@tslite/core';import {compileProfile,nodeViolation,typeFeatureViolations}from'@tslite/capability';import {fromJson}from'@tslite/codec';var $e=(e={})=>rootScope(e),T=(e,n)=>childScope(e,n),v=(e,n)=>lookup(e,n),pe=e=>visibleNames(e),wn=(e={},n={},t={},r={},s=new Set,a=new Set,o={})=>({scope:$e(e),types:n,schemes:t,accessors:r,asserters:s,matchers:a,modules:o}),En=(e,n)=>e.types[n],vn=(e,n)=>e.schemes[n];var Le={"unknown-name":"semantic","const-needs-init":"semantic","cannot-redeclare":"semantic","unknown-module":"semantic",unsupported:"semantic","forbidden-member":"semantic","not-assignable":"type","not-callable":"type","no-such-member":"type","not-object":"type","missing-argument":"type","excess-argument":"type","excess-property":"type","spread-argument":"type","props-mismatch":"type","no-matching-overload":"type","constraint-violation":"type","cast-unsound":"type","too-deep":"type","too-complex-union":"type","node-not-allowed":"capability","name-not-allowed":"capability","type-feature-not-allowed":"capability","any-not-allowed":"capability","too-large":"capability","wrong-result-type":"capability"},k=(e,n,t)=>({code:e,kind:Le[e],severity:"error",node:n,message:t}),B=(e,n,t,r="error")=>({code:e,kind:Le[e],severity:r,node:n,message:t}),S={notAssignable:(e,n,t,r={})=>{let s=typeDiff(n,t,r).filter(o=>o.path.length>0),a=s.length?` ${formatTypeDiff(s)}.`:"";return k("not-assignable",e,`Type '${format(n)}' is not assignable to type '${format(t)}'.${a}`)},unknownName:(e,n)=>k("unknown-name",e,`Cannot find name '${n}'.`),notCallable:(e,n)=>k("not-callable",e,`Type '${format(n)}' is not callable.`),noSuchMember:(e,n,t)=>k("no-such-member",e,`Property '${t}' does not exist on type '${format(n)}'.`),notObject:(e,n)=>k("not-object",e,`Type '${format(n)}' has no members to access.`),constNeedsInit:e=>k("const-needs-init",e,"'const' declarations must be initialized."),missingArgument:(e,n,t)=>k("missing-argument",e,`Missing argument '${n}' of type '${format(t)}'.`),unknownModule:(e,n)=>k("unknown-module",e,`Cannot find module '${n}' or its corresponding type declarations.`),cannotRedeclare:(e,n)=>k("cannot-redeclare",e,`Cannot redeclare block-scoped variable '${n}'.`),excessArgument:(e,n,t)=>k("excess-argument",e,`Expected ${n} argument${n===1?"":"s"}, but got ${t}.`),excessProperty:(e,n,t)=>k("excess-property",e,`Object literal may only specify known properties, and '${n}' does not exist in type '${format(t)}'.`),spreadArgument:e=>k("spread-argument",e,"A spread argument must either have a tuple type or be passed to a rest parameter."),propsMismatch:(e,n,t)=>k("props-mismatch",e,`Payload is not compatible with the component props '${format(n)}': ${t}.`),noMatchingOverload:(e,n,t)=>k("no-matching-overload",e,`No overload of '${format(n)}' matches the arguments (${t.map(r=>format(r)).join(", ")}).`),constraintViolation:(e,n,t,r)=>k("constraint-violation",e,`Type '${format(t)}' does not satisfy the constraint '${n} extends ${format(r)}'.`),unsupported:(e,n)=>k("unsupported",e,`${n} is not supported in this language.`),forbiddenMember:(e,n)=>k("forbidden-member",e,`'${n}' is not a member of the language \u2014 the JS runtime substrate (identity/inheritance) is not vocabulary here (FP / portable IR). Use a factory/operator via DI.`),castUnsound:(e,n,t)=>B("cast-unsound",e,`Conversion of type '${format(n)}' to type '${format(t)}' may be a mistake \u2014 neither sufficiently overlaps the other. Cast through 'unknown' first if intentional.`,"warning")};function Z(){let e=[];return {all:e,report(n){e.push(n);},hasErrors(){return e.some(n=>n.severity==="error")}}}function ce(e,n,t={}){return n.flatMap(r=>r(e,t))}function U(e,n){let t=r=>{n(r);for(let s of childrenOf(r))t(s);};t(e);}var Pn=e=>Array.isArray(e)?e:[e],Ve=["ArrowFunctionExpression","FunctionExpression","FunctionDeclaration"];function me(e,n="error"){return t=>{let r=[];return U(t,s=>{let a=nodeViolation(s,e);a&&r.push(B("node-not-allowed",s,`'${a}' is not allowed by the capability profile.`,n));}),r}}function Ue(e,n="error"){let t=e.typeTier;return r=>{if(t==="author")return [];let s=[];return U(r,a=>{let o=a,i=o.type==="TSTypeAliasDeclaration"?o.id?.name:void 0;for(let l of [o.typeAnnotation,o.returnType]){if(!l)continue;let p=typeFeatureViolations(typeFeatures(l,i),t);p.length&&s.push(B("type-feature-not-allowed",a,`authoring type feature${p.length>1?"s":""} '${p.join("', '")}' requires capability tier 'author'.`,n));}}),s}}function N(e,n=new WeakSet){if(!e||typeof e!="object"||n.has(e))return false;switch(n.add(e),e.t){case "any":return true;case "object":return Object.values(e.props).some(t=>N(t.type,n))||!!e.index&&N(e.index.value,n);case "array":return N(e.items,n);case "tuple":return e.elements.some(t=>N(t,n));case "union":case "intersection":return e.of.some(t=>N(t,n));case "fn":return e.params.some(t=>N(t.type,n))||N(e.returns,n);case "overload":return e.signatures.some(t=>t.params.some(r=>N(r.type,n))||N(t.returns,n));case "keyof":return N(e.of,n);case "index":return N(e.obj,n)||N(e.key,n);case "mapped":return N(e.over,n)||N(e.body,n);case "conditional":return N(e.check,n)||N(e.extends,n)||N(e.then,n)||N(e.else,n);case "returnType":case "parameters":return N(e.fn,n);case "apply":return e.args.some(t=>N(t,n));default:return false}}function qe(e,n="error"){return t=>{if(!e.typeStrict)return [];let r=[];return U(t,s=>{let a=s;for(let o of [a.typeAnnotation,a.returnType])if(o&&N(o)){r.push(B("any-not-allowed",s,"'any' is not allowed under 'strict' \u2014 use 'unknown' + validated narrowing (assert/parse).",n));break}}),r}}function ye(e,n="error"){let t=new Set(e);return r=>{let s=[];return U(r,a=>{if(a.type!=="CallExpression")return;let o=a.callee;if(o.type!=="Identifier")s.push(B("name-not-allowed",o,"Only direct calls to allowed functions are permitted.",n));else {let i=o.name;t.has(i)||s.push(B("name-not-allowed",o,`Function '${i}' is not allowed here.`,n));}}),s}}function ee(e,n,t={}){let r=new Set(Pn(e)),s=t.severity??"error",a=[...r].join("/");return o=>{let i=[],l=(p,c)=>{let m=r.has(p.type),h=m?c+1:c;m&&h>n&&i.push(B("too-deep",p,`Nesting of ${a} exceeds ${n}${t.hint?` \u2014 ${t.hint}`:""}.`,s));for(let y of childrenOf(p))l(y,h);};return l(o,0),i}}var fe=(e=3,n="error")=>ee(Ve,e,{hint:"use a pipe instead of nesting functions",severity:n}),de=(e,n="error")=>ee("CallExpression",e,{hint:"use a pipe instead of nesting calls",severity:n}),he=(e,n="error")=>ee("MemberExpression",e,{severity:n});function ge(e,n="error"){return t=>{let r=[],s=(a,o)=>{if(o>e){r.push(B("too-deep",a,`Expression nesting exceeds ${e}.`,n));return}for(let i of childrenOf(a))s(i,o+1);};return s(t,0),r}}function Se(e,n="error"){return t=>{let r=0;return U(t,()=>{r++;}),r>e?[B("too-large",t,`Expression has ${r} nodes (max ${e}).`,n)]:[]}}function be(e,n="error"){return t=>{let r=[];return U(t,s=>{if(s.type==="CallExpression"){let a=s.arguments;a&&a.length>e&&r.push(B("too-large",s,`Call has ${a.length} arguments (max ${e}).`,n));}}),r}}function Ne(e,n={},t="error"){return (r,s)=>{let a=s.overlay?.get(r)?.type;return a?subtype(a,e,n)?[]:[B("wrong-result-type",r,`Result type '${format(a)}' is not assignable to the required '${format(e)}'.`,t)]:[]}}function ne(e){let n=[me(e),Ue(e),qe(e)];return e.hostAllow!=="*"&&n.push(ye([...e.hostAllow])),n}function Fn(e){return ne(compileProfile(e))}var J=e=>e.typeAnnotation,ke=e=>e.returnType,F=e=>e.type==="Identifier"?e.name:null,Ke=e=>{if(e.type==="VariableDeclaration"){let n=e.declarations[0];return n?F(n.id):null}return F(e)},z=e=>{if(e.computed)return null;let n=e.key;return n.type==="Identifier"?n.name:n.type==="Literal"?String(n.value??""):null};function _e(e){let n=r=>r&&r.type==="Literal"&&typeof r.value=="string"?r.value:null;if(e.length===1&&e[0].type==="ArrayExpression"){let r=[];for(let s of e[0].elements){let a=n(s);if(a===null)return null;r.push(a);}return r}let t=[];for(let r of e){let s=n(r);if(s===null)return null;t.push(s);}return t.length?t:null}function Be(e){if(e.type==="Identifier")return e.name;if(e.type==="MemberExpression"){let n=e;if(n.computed||n.property.type!=="Identifier")return null;let t=Be(n.object);return t===null?null:`${t}.${n.property.name}`}return null}function we(e){let n=e;if(n.regex||n.bigint)return s.unknown;let t=n.value;return t===null?s.null:t===void 0?s.undefined:typeof t=="string"||typeof t=="number"||typeof t=="boolean"?{t:"literal",value:t,fresh:true}:s.unknown}var q=e=>{let n=e.value;return n===null?s.null:typeof n=="string"||typeof n=="number"||typeof n=="boolean"?s.literal(n):we(e)},Ee=e=>e.type==="ArrowFunctionExpression",We=e=>e.t==="apply"&&e.name==="Promise"&&e.args.length===1,se=e=>We(e)?e.args[0]:e,X=e=>We(e)?e:s.promise(e);function te(e){return e.t==="tuple"?true:e.t==="array"?te(e.items):e.t==="union"?e.of.some(te):false}function re(e){return e.t==="literal"?true:e.t==="union"?e.of.some(n=>re(n)):e.t==="var"?e.isConst===true||e.bound!==void 0&&re(e.bound):false}var j=(e,n)=>{let t=e;for(let r=0;r<50&&t.t==="apply";r++){let s=expand1(t,n);if(s===t||s.t==="apply"&&s.name===t.name)break;t=s;}return t};function Je(e){let n=ke(e);return n?{t:"fn",params:e.params.map((r,s$1)=>({name:F(r)??`arg${s$1}`,type:J(r)??s.unknown})),returns:e.async?X(n):n}:null}var M={then:{},else:{}},nn=new Set(["string","number","boolean","undefined","function","object"]),ze={string:s.string,number:s.number,boolean:s.boolean,undefined:s.undefined};function tn(e,n){switch(n){case "string":return e.t==="string"||e.t==="literal"&&typeof e.value=="string";case "number":return e.t==="number"||e.t==="literal"&&typeof e.value=="number";case "boolean":return e.t==="boolean"||e.t==="literal"&&typeof e.value=="boolean";case "undefined":return e.t==="undefined";case "function":return e.t==="fn"||e.t==="overload";case "object":return e.t==="object"||e.t==="array"||e.t==="tuple"||e.t==="null";default:return false}}var $n=s.literal(true),Ln=s.literal(false),x=e=>e.t==="union"?[...e.of]:e.t==="boolean"?[$n,Ln]:[e];function Xe(e,n){let t=e,r=n;return e.type==="UnaryExpression"&&t.operator==="typeof"&&t.argument.type==="Identifier"&&n.type==="Literal"&&typeof r.value=="string"?{name:t.argument.name,tag:r.value}:null}function Gn(e,n,t){if(e.t==="unknown"||e.t==="any")return n;let r=x(e).filter(s=>subtype(s,n,t));return r.length?normalizeUnion(r):n}function Vn(e,n,t){if(e.t==="unknown"||e.t==="any")return null;let r=x(e).filter(s=>!subtype(s,n,t));return r.length?normalizeUnion(r):null}function Un(e,n){if(!nn.has(n))return null;if(e.t==="unknown"||e.t==="any")return ze[n]??e;let t=x(e).filter(r=>tn(r,n));return t.length?normalizeUnion(t):ze[n]??e}function qn(e,n){if(!nn.has(n)||e.t==="unknown"||e.t==="any")return null;let t=x(e).filter(r=>!tn(r,n));return t.length?normalizeUnion(t):null}function Ye(e,n){if(e.type==="Identifier"&&n.type==="Literal"){let t=q(n);if(t.t==="literal"||t.t==="null")return {name:e.name,lit:t}}return null}function He(e,n){if(e.type==="MemberExpression"&&!e.computed&&!e.optional&&e.object.type==="Identifier"&&e.property.type==="Identifier"&&n.type==="Literal"){let t=q(n);if(t.t==="literal"||t.t==="null")return {name:e.object.name,prop:e.property.name,lit:t}}return null}function Qe(e,n,t,r,s){let a=x(e),o=l=>l.t==="object"?ownProp(l.props,n)?.type:void 0,i=a.filter(l=>{let p=o(l);return r?!!p&&subtype(t,p,s):!(p&&subtype(p,t,s))});return i.length&&i.length<a.length?normalizeUnion(i):null}function Ze(e,n,t){let r=x(e),s=o=>o.t==="object"&&(n in o.props||!!o.index),a=r.filter(o=>t?s(o):!s(o));return a.length&&a.length<r.length?normalizeUnion(a):null}function Kn(e,n,t){return e.t==="unknown"||e.t==="any"||subtype(n,e,t)?n:null}function _n(e,n,t){let r=x(e),s=r.filter(a=>!equals(a,n,t));return s.length&&s.length<r.length?normalizeUnion(s):null}var Wn=e=>e.t==="null"||e.t==="undefined",rn=e=>Wn(e)||e.t==="literal"&&!e.value,Jn=e=>{if(e.t==="unknown"||e.t==="any")return null;let n=x(e),t=n.filter(r=>!rn(r));return t.length&&t.length<n.length?normalizeUnion(t):null},zn=e=>{let n=x(e),t=n.filter(rn);return t.length&&t.length<n.length?normalizeUnion(t):null},en=e=>e.type==="Literal"&&e.value===null?"null":e.type==="Identifier"&&e.name==="undefined"?"undefined":null,O=(e,n,t)=>({then:n?{[e]:n}:{},else:t?{[e]:t}:{}}),Xn=e=>e==="==="||e==="=="||e==="!=="||e==="!=";function Q(e,n,t){if(e.type==="BinaryExpression"){let r=e;if(r.operator==="in"){let y=r.left,b=r.right;if(y.type==="Literal"&&typeof y.value=="string"&&b.type==="Identifier"){let g=b.name,E=v(n,g);if(!E)return M;let V=String(y.value);return O(g,Ze(E,V,true),Ze(E,V,false))}return M}if(!Xn(r.operator))return M;let s=r.operator==="!=="||r.operator==="!=",a=r.left,o=r.right,i=Xe(a,o)??Xe(o,a);if(i){let y=v(n,i.name);if(!y)return M;let b=Un(y,i.tag),g=qn(y,i.tag);return s?O(i.name,g,b):O(i.name,b,g)}let l=en(a),p=en(o),c=l?o:p?a:null;if((l||p)&&c?.type==="Identifier"){let y=c.name,b=v(n,y);if(!b)return M;let E=r.operator==="=="||r.operator==="!="?["null","undefined"]:[l??p],V=x(b),je=V.filter(le=>E.includes(le.t)),ie=V.filter(le=>!E.includes(le.t)),xe=je.length?normalizeUnion(je):null,Me=ie.length&&ie.length<V.length?normalizeUnion(ie):null;return s?O(y,Me,xe):O(y,xe,Me)}let m=Ye(a,o)??Ye(o,a);if(m){let y=v(n,m.name);if(!y)return M;let b=Kn(y,m.lit,t),g=_n(y,m.lit,t);return s?O(m.name,g,b):O(m.name,b,g)}let h=He(a,o)??He(o,a);if(h){let y=v(n,h.name);if(!y)return M;let b=Qe(y,h.prop,h.lit,true,t),g=Qe(y,h.prop,h.lit,false,t);return s?O(h.name,g,b):O(h.name,b,g)}return M}if(e.type==="UnaryExpression"&&e.operator==="!"){let r=Q(e.argument,n,t);return {then:r.else,else:r.then}}if(e.type==="CallExpression"){let r=Hn(e,n,t);if(r)return r}if(e.type==="Identifier"){let r=e.name,s=v(n,r);if(s)return O(r,Jn(s),zn(s))}return M}function Yn(e,n){if(e.t==="fn")return e.guard??null;if(e.t==="overload"){for(let t of e.signatures)if(t.guard&&t.params.length===n)return t.guard}return null}function Hn(e,n,t){let r=e.callee;if(r.type!=="Identifier")return null;let s=v(n,r.name);if(!s)return null;let a=Yn(s,e.arguments.length);if(!a)return null;let o=e.arguments[a.param];if(!o||o.type!=="Identifier")return null;let i=o.name,l=v(n,i);return l?O(i,Gn(l,a.type,t),Vn(l,a.type,t)):null}var _=(e,n)=>Object.keys(n).length?T(e,n):e;function Y(e){switch(e.type){case "ReturnStatement":case "ThrowStatement":return true;case "BlockStatement":{let n=e.body;return n.length>0&&Y(n[n.length-1])}case "IfStatement":{let n=e;return !!n.alternate&&Y(n.consequent)&&Y(n.alternate)}default:return false}}var yt=e=>{let n={};for(let t of Object.keys(e))n[t]={params:[],body:e[t]};return n};function ft(e){let n=[];return e.maxDepth!==void 0&&n.push(ge(e.maxDepth)),e.maxNodes!==void 0&&n.push(Se(e.maxNodes)),e.maxArgs!==void 0&&n.push(be(e.maxArgs)),e.maxFunctionNesting!==void 0&&n.push(fe(e.maxFunctionNesting)),e.maxCallNesting!==void 0&&n.push(de(e.maxCallNesting)),e.memberDepth!==void 0&&n.push(he(e.memberDepth)),n}function cn(e,n,t={}){let r={...yt(n.types),...n.schemes,...ht(e)},s$1={overlay:new WeakMap,sink:Z(),env:n,schemes:r,importNames:new Set},a=t.profile?compileProfile(t.profile):void 0;a&&configureTypeLimits(a.typeLimits);try{let o,i=gt(e,s$1);try{o=f(e,i,s$1);}catch(c){if(c instanceof TypeEvalLimitError)s$1.sink.report(B("too-deep",e,c.message));else if(c instanceof UnionTooComplexError)s$1.sink.report(B("too-complex-union",e,c.message));else throw c;o=s.unknown;}let l=[];a&&l.push(...ne(a)),t.limits&&l.push(...ft(t.limits)),t.resultType&&l.push(Ne(t.resultType,r));let p=l.length?[...s$1.sink.all,...ce(e,l,{overlay:s$1.overlay})]:s$1.sink.all;return {type:o,overlay:s$1.overlay,diagnostics:p}}finally{a&&resetTypeLimits();}}function dt(e,n,t={}){let r=cn(e,n,t),s$1={},a=new Map,o,i=p=>{let c=[];if(p.type==="VariableDeclaration")for(let m of p.declarations){let h=F(m.id),y=r.overlay.get(m);h&&y&&(s$1[h]=y.type,c.push(h));}else if(p.type==="FunctionDeclaration"){let m=p.id?.name,h=r.overlay.get(p);m&&h&&(s$1[m]=h.type,c.push(m));}return c};for(let p of e.body??[])if(p.type==="VariableDeclaration"||p.type==="FunctionDeclaration")i(p);else if(p.type==="ExportNamedDeclaration"){let c=p;if(c.declaration)for(let m of i(c.declaration))a.set(m,m);else for(let m of c.specifiers)a.set(m.exported.name,m.local.name);}else if(p.type==="ExportDefaultDeclaration"){let c=r.overlay.get(p.declaration);o=c?c.type:s.unknown;}let l={};if(a.size||o!==void 0){for(let[p,c]of a)s$1[c]&&(l[p]={type:s$1[c]});o!==void 0&&(l.default={type:o});}else for(let p in s$1)l[p]={type:s$1[p]};return {type:{t:"object",props:l},diagnostics:r.diagnostics}}var ht=e=>{let n={};return walk(e,{TSTypeAliasDeclaration(t){let r=t;r.id?.name&&r.typeAnnotation&&(n[r.id.name]={params:r.typeParameters??[],body:r.typeAnnotation});}}),n};function gt(e,n){let t=n.env.modules,r={};walk(e,{ImportDeclaration(s$1){let a=s$1,o=a.source.value,i=typeof o=="string"?t?.[o]:void 0;if(!i){n.sink.report(S.unknownModule(a.source,String(o)));for(let l of a.specifiers)r[l.local.name]=s.unknown;return}for(let l of a.specifiers){let p=l.local.name;if(p in r){n.sink.report(S.cannotRedeclare(l.local,p));continue}if(l.type==="ImportNamespaceSpecifier"){r[p]=i;continue}let c=l.type==="ImportSpecifier"?l.imported.name:"default",m=discover(i,[c],n.schemes);m?r[p]=m.type:(n.sink.report(S.noSuchMember(l,i,c)),r[p]=s.unknown);}}});for(let s in r)n.importNames.add(s);return Object.keys(r).length?T(n.env.scope,r):n.env.scope}var d=(e,n,t,r)=>(e.overlay.set(n,{type:t,scope:r}),t);function f(e,n,t,r){switch(e.type){case mn:return e.schema;case "JSXElement":case "JSXFragment":return d(t,e,f(desugarJSX(e,{emptyPropsAsObject:true}),n,t),n);case "Literal":return d(t,e,we(e),n);case "Identifier":{let s$1=e.name,a=v(n,s$1);return a===void 0?s$1==="undefined"?d(t,e,s.undefined,n):(t.sink.report(S.unknownName(e,s$1)),d(t,e,s.unknown,n)):d(t,e,a,n)}case "MemberExpression":return d(t,e,Nt(e,n,t),n);case "CallExpression":return d(t,e,Et(e,n,t,r),n);case "ArrowFunctionExpression":return Oe(e,n,t);case "FunctionDeclaration":return t.sink.report(S.unsupported(e,"function declaration (use 'const fn = () => \u2026')")),d(t,e,s.unknown,n);case "FunctionExpression":return t.sink.report(S.unsupported(e,"anonymous function (use an arrow)")),d(t,e,s.unknown,n);case "ThisExpression":return t.sink.report(S.unsupported(e,"'this'")),d(t,e,s.unknown,n);case "BlockStatement":return d(t,e,Pe(e,n,t),n);case "ReturnStatement":{let s$1=e.argument;return d(t,e,s$1?f(s$1,n,t):s.unknown,n)}case "IfStatement":return I(e,n,t),t.overlay.get(e)?.type??s.unknown;case "ForStatement":case "WhileStatement":case "DoWhileStatement":case "ForOfStatement":case "ForInStatement":case "BreakStatement":case "ContinueStatement":case "ThrowStatement":case "TryStatement":case "SwitchStatement":return I(e,n,t),t.overlay.get(e)?.type??s.unknown;case "AssignmentExpression":{let s=e;return f(s.left,n,t),d(t,e,f(s.right,n,t),n)}case "UpdateExpression":return f(e.argument,n,t),d(t,e,s.number,n);case "ExpressionStatement":return d(t,e,f(e.expression,n,t),n);case "VariableDeclaration":return ae(e,n,t),d(t,e,s.unknown,n);case "TSTypeAliasDeclaration":return d(t,e,s.unknown,n);case "BinaryExpression":return d(t,e,xt(e,n,t),n);case "LogicalExpression":{let s=e,a=f(s.left,n,t),o=f(s.right,n,t);return d(t,e,Mt(s.operator,a,o),n)}case "UnaryExpression":return d(t,e,Gt(e,n,t),n);case "ConditionalExpression":{let s=e;f(s.test,n,t);let a=Q(s.test,n,t.schemes),o=f(s.consequent,_(n,a.then),t),i=f(s.alternate,_(n,a.else),t);return d(t,e,normalizeUnion([o,i]),n)}case "ObjectExpression":return d(t,e,Vt(e,n,t),n);case "ArrayExpression":return d(t,e,gn(e,n,t),n);case "TemplateLiteral":{for(let s of e.expressions)f(s,n,t);return d(t,e,s.string,n)}case "AwaitExpression":{let s$1=e.argument,a=s$1?f(s$1,n,t):s.unknown;return d(t,e,se(a),n)}case "Program":return Ie(e.body,n,t,new Set(t.importNames)),d(t,e,s.unknown,n);case "JsonExpression":return d(t,e,Ce(e.body,n,t,e),n);case "ChainExpression":return d(t,e,normalizeUnion([f(e.expression,n,t),s.undefined]),n);case "TSAsExpression":{let s=e,a=f(s.expression,n,t),o=s.typeAnnotation;return !subtype(a,o,t.schemes)&&!subtype(o,a,t.schemes)&&t.sink.report(S.castUnsound(e,a,o)),d(t,e,o,n)}default:return t.sink.report(S.unsupported(e,`'${e.type}'`)),d(t,e,s.unknown,n)}}var St=new Set(["constructor","prototype","__proto__"]);function bt(e){if(!e.computed)return e.property.type==="Identifier"?e.property.name:null;let n=e.property;if(n.type==="Literal"){let t=n.value;if(typeof t=="string")return t}return null}function Nt(e,n,t){let r=f(e.object,n,t),s$1=bt(e);if(s$1!==null&&St.has(s$1))return t.sink.report(S.forbiddenMember(e,s$1)),s.unknown;if(e.computed){let i=f(e.property,n,t),l=resolveTypeOp(s.index(r,i));return l.t!=="index"?l:(i.t==="literal"&&typeof i.value=="string"&&an(e,r,i.value,t),s.unknown)}let a=e.property.name,o=discover(r,[a],t.schemes);return o?o.type:(an(e,r,a,t),s.unknown)}function an(e,n,t,r){let s=isScheme(n,r.schemes)?expand1(n,r.schemes):n;s.t==="object"||s.t==="array"||s.t==="tuple"||s.t==="union"?r.sink.report(S.noSuchMember(e,n,t)):s.t!=="any"&&s.t!=="unknown"&&r.sink.report(S.notObject(e,n));}function kt(e,n,t){if(!e||e.type!=="Identifier")return;let r=e.name;if(v(n,r)===void 0)return;let s=t.schemes[r];return s&&s.params.length===0?s.body:void 0}function Bt(e,n,t,r){let s$1=j(f(n[0],t,r),r.schemes),o=(s$1.t==="fn"?s$1:s$1.t==="overload"?s$1.signatures[0]:void 0)?.params[0]?.type,i=n.length>1?f(n[1],t,r):s.undefined;if(o){let l=typeDiff(i,o,r.schemes);l.length&&r.sink.report(S.propsMismatch(n[1]??e,o,formatTypeDiff(l)));}return d(r,e,s.boolean,t)}var mn="TSLiteSyntheticArg",wt=e=>({type:mn,schema:e});function yn(e,n,t){if(!e.some(a=>a.type==="SpreadElement"))return {nodes:[...e],spread:null};let r=[],s$1=null;for(let a of e){if(a.type!=="SpreadElement"){r.push(a);continue}let o=a.argument;if(o.type==="ArrayExpression"&&o.elements.every(l=>l&&l.type!=="SpreadElement")){for(let l of o.elements)r.push(l);continue}let i=j(f(o,n,t),t.schemes);if(i.t==="tuple")for(let l of i.elements)r.push(wt(l));else s$1={elem:i.t==="array"?i.items:s.unknown,node:a};}return {nodes:r,spread:s$1}}function Et(e,n,t,r){let s$1=e.arguments,a=Be(e.callee);if(a){let p=t.env.accessors?.[a];if(p){let c=_e(s$1);if(c){let m=discover(p,c,t.schemes);return m?m.type:(t.sink.report(S.noSuchMember(e,p,c.join("."))),s.unknown)}return s$1.forEach(m=>f(m,n,t)),s.unknown}}if(a&&t.env.asserters?.has(a)){let p=kt(s$1[0],n,t);for(let c=1;c<s$1.length;c++)f(s$1[c],n,t);return p??s.unknown}if(a&&t.env.matchers?.has(a))return Bt(e,s$1,n,t);let o=f(e.callee,n,t);if(o.t==="any")return s$1.forEach(p=>f(p,n,t)),s.any;if(o.t==="overload")return At(e,o,n,t,r);if(o.t!=="fn")return s$1.forEach(p=>f(p,n,t)),t.sink.report(S.notCallable(e,o)),s.unknown;let i=yn(s$1,n,t),l=i.nodes.map(p=>fn(p,n,t));return dn(e,o,i.nodes,l,n,t,i.spread,r)}function fn(e,n,t){if(Ee(e))return s.any;if(e.type!=="CallExpression")return f(e,n,t);let r=Z(),s$1=f(e,n,{...t,sink:r});return r.hasErrors()?s.any:(r.all.forEach(a=>t.sink.report(a)),s$1)}function dn(e,n,t,r,s$1,a,o=null,i){let l=m=>{if(!i)return m;let h=substitute(n.returns,m);if(h.t==="fn"&&i.t==="fn"){let y=m,b=Math.min(h.params.length,i.params.length);for(let g=0;g<b;g++)y=unify(h.params[g].type,i.params[g].type,y)??y;return unify(h.returns,i.returns,y)??y}return unify(h,i,m)??m},p=l(instantiateLoose(n,r).bindings);t.forEach((m,h)=>{if(Ee(m)){let y=widenType(substitute(n.params[h]?.type??s.any,p));r[h]=Oe(m,s$1,a,y);}else if(m.type==="CallExpression"&&r[h].t==="any")r[h]=f(m,s$1,a,substitute(n.params[h]?.type??s.unknown,p));else if(m.type==="Literal"){let y=n.params[h]?.type??s.unknown,b=y.t==="var"?y.bound?substitute(y.bound,p):y:substitute(y,p);re(b)&&(r[h]=d(a,m,q(m),s$1));}else if(m.type==="ArrayExpression"){let y=substitute(n.params[h]?.type??s.unknown,p);te(y)&&(r[h]=Sn(m,y,s$1,a));}});let c=l(instantiateLoose(n,r).bindings);return Dt(e,n,c,a),Ot(e,n,r,c,a,t,o),t.forEach((m,h)=>{let y=n.params[h];m.type==="ObjectExpression"&&y&&!y.variadic&&Fe(m,substitute(y.type,c),a);}),widenInferred(groundVars(substitute(n.returns,c),a.schemes))}var on=new WeakMap;function vt(e){let n=on.get(e);if(n)return n;let t=new Map,r=new WeakSet;for(let s of e.params)w(s.type,t,r);return w(e.returns,t,r),on.set(e,t),t}function w(e,n,t){switch(e.t){case "var":e.bound&&!n.has(e.name)&&n.set(e.name,e.bound);return;case "array":w(e.items,n,t);return;case "union":for(let r of e.of)w(r,n,t);return;case "object":if(t.has(e))return;t.add(e);for(let r in e.props)w(e.props[r].type,n,t);return;case "fn":if(t.has(e))return;t.add(e);for(let r of e.params)w(r.type,n,t);w(e.returns,n,t);return;case "overload":for(let r of e.signatures){for(let s of r.params)w(s.type,n,t);w(r.returns,n,t);}return;case "apply":for(let r of e.args)w(r,n,t);return;case "keyof":w(e.of,n,t);return;case "index":w(e.obj,n,t),w(e.key,n,t);return;case "mapped":w(e.over,n,t),w(e.body,n,t);return;default:return}}function Dt(e,n,t,r){let s=vt(n);if(s.size!==0)for(let[a,o]of s){let i=t[a];if(!i)continue;let l=substitute(o,t);subtype(i,l,r.schemes)||r.sink.report(S.constraintViolation(e,a,i,l));}}function At(e,n,t,r,s$1){let a=yn(e.arguments,t,r),o=a.nodes,i=o.map(c=>fn(c,t,r)),l=c=>a.spread?Ct(c,o.length):Tt(c,o.length),p=n.signatures.find(c=>l(c)&&Rt(c,i,r));if(!p){let c=n.signatures.filter(l);c.length===1?p=c[0]:n.signatures.length===1&&(p=n.signatures[0]);}return p?dn(e,p,o,i,t,r,a.spread,s$1):(r.sink.report(S.noMatchingOverload(e,n,i)),s.unknown)}function Ct(e,n){let t=0,r=false;for(let s of e.params)s.variadic?r=true:s.optional||t++;return n>=t&&(r||n<e.params.length)}function Tt(e,n){let t=0;for(let r of e.params){if(r.variadic)return n>=t;r.optional||t++;}return n>=t&&n<=e.params.length}function Rt(e,n,t){let{bindings:r}=instantiateLoose(e,n);for(let s=0;s<e.params.length;s++){let a=e.params[s];if(a.variadic)return true;if(s>=n.length){if(!a.optional)return false;continue}if(!subtype(n[s],substitute(a.type,r),t.schemes))return false}return true}function Ot(e,n,t,r,s$1,a=e.arguments??[],o=null){let i=p=>a[p]??e;for(let p=0;p<n.params.length;p++){let c=n.params[p];if(c.variadic)break;let m=substitute(c.type,r);if(p>=t.length){!c.optional&&!o&&s$1.sink.report(S.missingArgument(e,c.name,m));continue}subtype(t[p],m,s$1.schemes)||s$1.sink.report(S.notAssignable(i(p),t[p],m,s$1.schemes));}let l=n.params.find(p=>p.variadic);if(o){let p=t.length,c=n.params.filter(m=>!m.optional&&!m.variadic).length;if(!(p>=c&&(l||p<n.params.length))){s$1.sink.report(S.spreadArgument(o.node));return}if(l){let m=substitute(l.type,r),h=m.t==="array"?m.items:s.unknown;subtype(o.elem,h,s$1.schemes)||s$1.sink.report(S.notAssignable(o.node,o.elem,h,s$1.schemes));}return}!l&&t.length>n.params.length&&s$1.sink.report(S.excessArgument(i(n.params.length),n.params.length,t.length));}function L(e,n,t,r){let s=j(n,r.schemes);switch(e.type){case "Literal":{let o=q(e);return subtype(o,n,r.schemes)||r.sink.report(S.notAssignable(e,o,n,r.schemes)),d(r,e,n,t)}case "ArrayExpression":{if(s.t==="array"){for(let o of e.elements){if(!o)continue;let i=o;i.type==="SpreadElement"?L(i.argument,n,t,r):L(i,s.items,t,r);}return d(r,e,n,t)}break}case "ObjectExpression":{if(s.t==="object"){let o={};for(let l of e.properties){let p=l;if(p.type==="SpreadElement"){f(p.argument,t,r);continue}let c=p,m=z(c),h=m!==null?ownProp(s.props,m)?.type:void 0,y=h?L(c.value,h,t,r):f(c.value,t,r);m!==null&&(o[m]={type:y}),d(r,p,y,t);}let i={t:"object",props:o};return subtype(i,n,r.schemes)||r.sink.report(S.notAssignable(e,i,n,r.schemes)),d(r,e,n,t)}break}case "ArrowFunctionExpression":{if(s.t==="fn"){let o=Oe(e,t,r,s);return subtype(o,n,r.schemes)||r.sink.report(S.notAssignable(e,o,n,r.schemes)),d(r,e,n,t)}break}case "ConditionalExpression":{let o=e;return f(o.test,t,r),L(o.consequent,n,t,r),L(o.alternate,n,t,r),d(r,e,n,t)}}let a=f(e,t,r);return subtype(a,n,r.schemes)||r.sink.report(S.notAssignable(e,a,n,r.schemes)),d(r,e,a,t)}function Oe(e,n,t,r){let s$1=r&&r.t==="fn"?r:void 0,a={},o=e.params.map((h,y)=>{let b=h,g=F(b),E=J(b)??s$1?.params[y]?.type??s.unknown;return g?a[g]=E:b.type!=="Identifier"&&G(b,E,a,n,t),t.overlay.set(b,{type:E,scope:n}),{name:g??`arg${y}`,type:E}}),i=T(n,a),l=e.body,p=ke(e);if(l.type!=="BlockStatement"&&p){let h=e.async?se(p):p;L(l,h,i,t);let y=e.async?X(p):p;return d(t,e,{t:"fn",params:o,returns:y},n)}let c=l.type==="BlockStatement"?d(t,l,Pe(l,i,t,new Set(Object.keys(a))),i):f(l,i,t),m=e.async?X(c):c;if(p){let h=e.async?se(p):p,y=e.async?c:m;subtype(y,h,t.schemes)||t.sink.report(S.notAssignable(l,m,p,t.schemes));let b=e.async?X(p):p;return d(t,e,{t:"fn",params:o,returns:b},n)}return d(t,e,{t:"fn",params:o,returns:widenType(m)},n)}function W(e){switch(e.type){case "Identifier":return [e];case "ObjectPattern":return e.properties.flatMap(n=>n.type==="RestElement"?W(n.argument):W(n.value));case "ArrayPattern":return e.elements.flatMap(n=>n?n.type==="RestElement"?W(n.argument):W(n):[]);case "AssignmentPattern":return W(e.left);default:return []}}function hn(e){if(e.type==="VariableDeclaration")return e.declarations.flatMap(n=>W(n.id));if(e.type==="FunctionDeclaration"){let n=e.id;return n?[n]:[]}return e.type==="ExportNamedDeclaration"&&e.declaration?hn(e.declaration):[]}function Pe(e,n,t,r=new Set){let{returns:s$1}=Ie(e.body,n,t,r);return s$1.length?normalizeUnion(s$1):s.unknown}function Ie(e,n,t,r=new Set){let s=n,a=[];for(let o of e){let i=o;for(let l of hn(i))r.has(l.name)?t.sink.report(S.cannotRedeclare(l,l.name)):r.add(l.name);if(i.type==="VariableDeclaration")s=ae(i,s,t);else if(i.type!=="ImportDeclaration")if(i.type==="ExportNamedDeclaration"){let l=i;if(l.declaration?.type==="VariableDeclaration")s=ae(l.declaration,s,t);else if(l.declaration?.type==="FunctionDeclaration"){let p=f(l.declaration,s,t),c=F(l.declaration.id);c&&(s=T(s,{[c]:p}));}else for(let p of l.specifiers)v(s,p.local.name)===void 0&&t.sink.report(S.unknownName(p.local,p.local.name));}else if(i.type==="ExportDefaultDeclaration")f(i.declaration,s,t);else if(i.type==="FunctionDeclaration"){let l=f(i,s,t),p=F(i.id);p&&(s=T(s,{[p]:l}));}else if(i.type==="IfStatement"){a.push(...I(i,s,t));let l=i;!l.alternate&&Y(l.consequent)&&(s=_(s,Q(l.test,s,t.schemes).else));}else a.push(...I(i,s,t));}return {scope:s,returns:a}}function I(e,n,t){switch(e.type){case "ReturnStatement":{let r=e.argument,s$1=r?f(r,n,t):s.unknown;return d(t,e,s$1,n),[s$1]}case "IfStatement":{let r=e;f(r.test,n,t);let s$1=Q(r.test,n,t.schemes),a=I(r.consequent,_(n,s$1.then),t);return r.alternate&&a.push(...I(r.alternate,_(n,s$1.else),t)),d(t,e,s.unknown,n),a}case "BlockStatement":{let r=Pe(e,n,t);return d(t,e,r,n),r.t==="unknown"?[]:[r]}case "ForStatement":case "WhileStatement":case "DoWhileStatement":{let r=e,s$1=n;r.init&&(r.init.type==="VariableDeclaration"?s$1=ae(r.init,s$1,t):f(r.init,s$1,t)),r.test&&f(r.test,s$1,t),r.update&&f(r.update,s$1,t);let a=I(r.body,s$1,t);return d(t,e,s.unknown,n),a}case "ForOfStatement":case "ForInStatement":{let r=e,s$1=f(r.right,n,t),a=e.type==="ForOfStatement"?s$1.t==="array"?s$1.items:s.unknown:s.string,o=Ke(r.left),i=o?T(n,{[o]:a}):n,l=I(r.body,i,t);return d(t,e,s.unknown,n),l}case "BreakStatement":case "ContinueStatement":return d(t,e,s.unknown,n),[];case "ThrowStatement":{let r=e.argument;return r&&f(r,n,t),d(t,e,s.unknown,n),[]}case "TryStatement":{let r=e,s$1=I(r.block,n,t);if(r.handler){let a=r.handler.param,o=a?F(a):null,i=o?T(n,{[o]:s.unknown}):n;s$1.push(...I(r.handler.body,i,t));}return r.finalizer&&s$1.push(...I(r.finalizer,n,t)),d(t,e,s.unknown,n),s$1}case "SwitchStatement":{let r=e;f(r.discriminant,n,t);let s$1=n,a=[];for(let o of r.cases){o.test&&f(o.test,s$1,t);let i=Ie(o.consequent,s$1,t);s$1=i.scope,a.push(...i.returns);}return d(t,e,s.unknown,n),a}default:return f(e,n,t),[]}}function Pt(e,n,t){let r=discover(e,[n],t.schemes);return r?r.type:s.unknown}function It(e,n){let t=resolveTypeOp(s.index(e,s.literal(n)));return t.t==="index"?s.unknown:t}function Ft(e,n){if(e.t!=="object")return e;let t={};for(let r in e.props)n.includes(r)||(t[r]=e.props[r]);return s.object(t,e.index)}function jt(e,n){return e.t==="tuple"?s.tuple(e.elements.slice(n)):e.t==="array"?e:s.array(s.unknown)}function G(e,n,t,r,s$1){switch(e.type){case "Identifier":{let a=J(e)??n;t[e.name]=a,s$1.overlay.set(e,{type:a,scope:r});return}case "AssignmentPattern":{let a=e,o=widenType(f(a.right,r,s$1)),{type:i}=withoutUndefined(n),l=i.t==="unknown"?o:normalizeUnion([i,o]);G(a.left,l,t,r,s$1);return}case "ObjectPattern":{let a=[];for(let o of e.properties){if(o.type==="RestElement"){G(o.argument,Ft(n,a),t,r,s$1);continue}let i=o,l=z(i);l!=null&&a.push(l);let p=l!=null?Pt(n,l,s$1):s.unknown;G(i.value,p,t,r,s$1);}return}case "ArrayPattern":{e.elements.forEach((a,o)=>{if(!a)return;let i=a;i.type==="RestElement"?G(i.argument,jt(n,o),t,r,s$1):G(i,It(n,o),t,r,s$1);});return}}}function Fe(e,n,t){let r=j(n,t.schemes),a=(r.t==="union"?r.of.map(o=>j(o,t.schemes)):[r]).filter(o=>o.t==="object"&&!o.index);if(a.length&&!a.some(o=>Object.keys(o.props).length===0))for(let o of e.properties){if(o.type==="SpreadElement")continue;let i=o;if(i.computed)continue;let l=z(i);if(l===null)continue;let p=a.filter(c=>l in c.props);if(!p.length){t.sink.report(S.excessProperty(i.key,l,n));continue}i.value.type==="ObjectExpression"&&Fe(i.value,p[0].props[l].type,t);}}function ae(e,n,t){let r={};for(let s$1 of e.declarations){let a=s$1.id,o=F(a),i=J(a);if(!s$1.init){t.sink.report(S.constNeedsInit(s$1)),o&&(r[o]=i??s.unknown);continue}let l=i??(s$1.init.type==="ArrowFunctionExpression"?Je(s$1.init):null),p=o&&l?T(n,{[o]:l}):n,c;i?(L(s$1.init,i,p,t),s$1.init.type==="ObjectExpression"&&Fe(s$1.init,i,t),c=i):c=f(s$1.init,p,t),d(t,s$1,c,n),o?r[o]=c:G(a,c,r,n,t);}return d(t,e,s.unknown,n),T(n,r)}function xt(e,n,t){let r=f(e.left,n,t),s$1=f(e.right,n,t),a=e.operator;return a==="+"?subtype(r,s.string)||subtype(s$1,s.string)?s.string:s.number:$t.has(a)?s.number:s.boolean}var ln={string:s.literal(""),number:s.literal(0),boolean:s.literal(false)},De=e=>e.t==="null"||e.t==="undefined";function Mt(e,n,t){if(n.t==="any"||n.t==="unknown")return normalizeUnion([n,t]);let r=n.t==="union"?[...n.of]:n.t==="boolean"?[s.literal(true),s.literal(false)]:[n];if(e==="??")return normalizeUnion([...r.filter(a=>!De(a)),t]);if(e==="||")return normalizeUnion([...r.filter(a=>!De(a)&&!(a.t==="literal"&&!a.value)),t]);let s$1=r.flatMap(a=>De(a)?[a]:a.t==="literal"?a.value?[]:[a]:ln[a.t]?[ln[a.t]]:[]);return normalizeUnion([...s$1,t])}var $t=new Set(["-","*","/","%","**","&","|","^","<<",">>",">>>"]),Lt=s.union(["string","number","bigint","boolean","symbol","undefined","object","function"].map(e=>s.literal(e)));function Gt(e,n,t){let r=f(e.argument,n,t);switch(e.operator){case "!":return r.t==="literal"?{t:"literal",value:!r.value,fresh:true}:s.boolean;case "-":return r.t==="literal"&&typeof r.value=="number"?{t:"literal",value:-r.value,fresh:true}:s.number;case "+":case "~":return s.number;case "typeof":return Lt;case "delete":return s.boolean;case "void":return s.undefined;default:return s.unknown}}function Vt(e,n,t){let r={},s,a=[],o=[],i=false,l=false;for(let p of e.properties){let c=p;if(c.type==="SpreadElement"){let g=j(f(c.argument,n,t),t.schemes);if(g.t==="object"){for(let E in g.props)r[E]=g.props[E];g.index&&(s={key:g.index.key,type:g.index.value});}continue}let m=c,h=f(m.value,n,t),y=widen(h);if(d(t,c,h,n),m.computed){let g=j(f(m.key,n,t),t.schemes);g.t==="literal"&&typeof g.value=="string"?(r[g.value]={type:y},a.push(y)):g.t==="literal"&&typeof g.value=="number"?(r[String(g.value)]={type:y},a.push(y),o.push(y)):g.t==="string"?(i=true,a.push(y)):g.t==="number"&&(l=true,a.push(y),o.push(y));continue}let b=z(m);b!==null&&(r[b]={type:y},a.push(y),/^\d+$/.test(b)&&o.push(y));}return i?s={key:"string",type:normalizeUnion(a)}:l&&(s={key:"number",type:normalizeUnion(o)}),s?{t:"object",props:r,index:{key:s.key,value:s.type}}:{t:"object",props:r}}function gn(e,n,t){let r=[];for(let s of e.elements){if(!s)continue;let a=s;if(a.type==="SpreadElement"){let o=j(f(a.argument,n,t),t.schemes);o.t==="array"?r.push(o.items):o.t==="tuple"&&r.push(...o.elements);continue}r.push(widen(f(a,n,t)));}return s.array(r.length?normalizeUnion(r):s.unknown)}function Sn(e,n,t,r){let s$1=j(n,r.schemes),a=e.elements,o=a.every(l=>l&&l.type!=="SpreadElement"),i=(l,p)=>l.type==="ArrayExpression"?Sn(l,p,t,r):widen(f(l,t,r));if(s$1.t==="tuple"&&o&&a.length===s$1.elements.length){let l=a.map((p,c)=>i(p,s$1.elements[c]));return d(r,e,{t:"tuple",elements:l},t)}if(s$1.t==="array"){let l=[];for(let p of a){if(!p)continue;let c=p;if(c.type==="SpreadElement"){f(c.argument,t,r);continue}l.push(i(c,s$1.items));}return d(r,e,s.array(l.length?normalizeUnion(l):s.unknown),t)}return gn(e,t,r)}function Ce(e,n,t,r){if(e===null)return s.null;switch(typeof e){case "string":return s.string;case "number":return s.number;case "boolean":return s.boolean;case "object":break;default:return s.unknown}if(Array.isArray(e)){let o=e.map(i=>Ce(i,n,t,r));return s.array(o.length?normalizeUnion(o):s.unknown)}let s$1=e;if(AST_MARKER in s$1){let o;try{o=fromJson(s$1);}catch{return t.sink.report(S.unsupported(r,`'#ast: ${String(s$1[AST_MARKER])}'`)),s.unknown}return f(o,n,t)}let a={};for(let o of Object.keys(s$1))a[o]={type:Ce(s$1[o],n,t,r)};return {t:"object",props:a}}var Ut=(e,n)=>({...e,typeAnnotation:n}),qt=(e,n)=>({...e,returnType:n}),Kt=(e,n)=>({type:"TSAsExpression",expression:e,typeAnnotation:n});function Wt(e,n){return e.get(n)?.type}function Jt(e,n){return e.get(n)?.scope}function zt(e,n){let t=e.get(n)?.type;return t?discover(t,[])?.completions??[]:[]}function Xt(e,n){let t=e.get(n)?.scope;return t?[...pe(t)].map(([r,s])=>({key:r,type:s,optional:false})):[]}function Yt(e,n){return e.filter(t=>t.node===n)}export{Ve as FUNCTION_KINDS,Ut as annotate,qt as annotateReturn,Kt as asExpression,ye as calleeAllowlist,me as capabilityNodes,cn as check,T as childScope,wn as createEnv,Z as createSink,S as diag,Yt as diagnosticsAt,dt as extractModuleType,Fn as fromCapability,ce as guard,ne as guardsFromCompiled,v as lookup,B as makeDiagnostic,be as maxArgs,de as maxCallNesting,ge as maxDepth,fe as maxFunctionNesting,ee as maxNestingOf,Se as maxNodes,zt as memberCompletions,he as memberDepth,En as resolveNamed,vn as resolveScheme,Ne as resultType,$e as rootScope,Jt as scopeAt,Xt as scopeCompletions,Wt as typeAt,pe as visibleNames};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tslite/checker",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "TSLite type system — a structural type checker over the AST (the 'TypeScript of TSLite')",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -39,9 +39,13 @@
|
|
|
39
39
|
"access": "public"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@tslite/
|
|
42
|
+
"@tslite/core": "0.1.0",
|
|
43
43
|
"@tslite/codec": "0.1.0",
|
|
44
|
-
"@tslite/
|
|
44
|
+
"@tslite/capability": "0.1.0",
|
|
45
|
+
"@tslite/type-core": "0.2.0"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@tslite/parser": "0.1.0"
|
|
45
49
|
},
|
|
46
50
|
"scripts": {
|
|
47
51
|
"build": "tsup",
|
|
@@ -49,6 +53,7 @@
|
|
|
49
53
|
"test": "vitest run",
|
|
50
54
|
"test:watch": "vitest",
|
|
51
55
|
"test:coverage": "vitest run --coverage",
|
|
56
|
+
"bench": "vitest bench --run",
|
|
52
57
|
"typecheck": "tsc --noEmit",
|
|
53
58
|
"lint": "eslint src tests",
|
|
54
59
|
"lint:fix": "eslint src tests --fix",
|