@tslite/type-core 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 -0
- package/dist/index.d.cts +473 -0
- package/dist/index.d.ts +473 -0
- package/dist/index.js +1 -0
- package/package.json +54 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var O=e=>Object.freeze(e),c={any:O({t:"any"}),unknown:O({t:"unknown"}),string:O({t:"string"}),number:O({t:"number"}),boolean:O({t:"boolean"}),null:O({t:"null"}),undefined:O({t:"undefined"}),void:O({t:"void"}),literal:e=>({t:"literal",value:e}),object:(e,t)=>({t:"object",props:e,...t?{index:t}:{}}),record:(e,t="string")=>({t:"object",props:{},index:{key:t,value:e}}),array:e=>({t:"array",items:e}),tuple:(e,t)=>({t:"tuple",elements:e,...t&&t.some(n=>n!=="req")?{flags:t}:{}}),fn:(e,t)=>({t:"fn",params:e,returns:t}),guard:(e,t,n=0)=>({t:"fn",params:e,returns:{t:"boolean"},guard:{param:n,type:t}}),overload:e=>({t:"overload",signatures:e}),keyof:e=>({t:"keyof",of:e}),index:(e,t)=>({t:"index",obj:e,key:t}),mapped:(e,t,n,r=false)=>({t:"mapped",key:e,over:t,body:n,optional:r}),conditional:(e,t,n,r,o)=>({t:"conditional",check:e,extends:t,then:n,else:r,...o&&o.length?{infer:o}:{}}),intersection:e=>({t:"intersection",of:e}),and:(e,t)=>({t:"intersection",of:[e,t]}),returnType:e=>({t:"returnType",fn:e}),parameters:e=>({t:"parameters",fn:e}),var:(e,t,n)=>({t:"var",name:e,bound:t,isConst:n}),apply:(e,t=[])=>({t:"apply",name:e,args:t}),promise:e=>({t:"apply",name:"Promise",args:[e]}),union:e=>{let t=[];for(let n of e)n.t==="union"?t.push(...n.of):t.push(n);return {t:"union",of:t}}};function h(e){return e.t==="keyof"?ae(e.of)??e:e.t==="index"?J(e.obj,e.key)??e:e.t==="returnType"?xe(e.fn)??e:e.t==="parameters"?ke(e.fn)??e:e}var re={t:"union",of:[]},ge=e=>e.t==="union"&&e.of.length===0;function xe(e){return e.t==="fn"?e.returns:e.t==="overload"&&e.signatures.length>0?e.signatures[e.signatures.length-1].returns:null}function ve(e){if(e.t==="undefined")return e;let t=e.t==="union"?e.of:[e];return t.some(n=>n.t==="undefined")?e:{t:"union",of:[...t,{t:"undefined"}]}}function ke(e){let t=e.t==="fn"?e:e.t==="overload"&&e.signatures.length>0?e.signatures[e.signatures.length-1]:null;if(!t)return null;let n=[],r=[];for(let o of t.params)o.variadic?(n.push(o.type.t==="array"?o.type.items:o.type),r.push("rest")):o.optional?(n.push(ve(o.type)),r.push("optional")):(n.push(o.type),r.push("req"));return c.tuple(n,r)}var oe=e=>e.t==="literal"?typeof e.value:e.t==="string"||e.t==="number"||e.t==="boolean"?e.t:null;function ie(e,t){return e.t==="literal"&&t.t==="literal"?e.value===t.value:e.t==="literal"&&(t.t==="string"||t.t==="number"||t.t==="boolean")?typeof e.value===t.t:e.t===t.t&&(e.t==="string"||e.t==="number"||e.t==="boolean")}function j(e){let t=[],n=o=>{let i=h(o);i.t==="intersection"?i.of.forEach(n):t.push(i);};e.of.forEach(n);let r=[];for(let o of t){if(o.t==="any")return c.any;if(ge(o))return re;if(o.t!=="unknown"){if(oe(o)){let i=false;for(let a=r.length-1;a>=0;a--){let l=r[a];if(oe(l)){if(ie(l,o)){i=true;break}if(ie(o,l))r.splice(a,1);else return re}}if(i)continue}else if(r.some(i=>i===o))continue;r.push(o);}}return r.length===0?c.unknown:r.length===1?r[0]:{t:"intersection",of:r}}function ae(e){if(e.t==="union"){let n=e.of.map(ae);return n.some(r=>r===null)?null:be(n)}if(e.t!=="object")return null;let t=Object.keys(e.props).map(n=>c.literal(n));return e.index&&t.push(e.index.key==="number"?c.number:c.string),t.length===0?{t:"union",of:[]}:t.length===1?t[0]:{t:"union",of:t}}function be(e){let t=i=>i.t==="literal"&&typeof i.value=="string"?[i.value]:i.t==="union"?i.of.flatMap(t):[],n=e.filter(i=>i.t!=="string"&&i.t!=="number").map(t);if(n.length===0)return e[0];let r=n[0].filter(i=>n.every(a=>a.includes(i))),o=[...new Set(r)].map(i=>c.literal(i));return o.length===0?{t:"union",of:[]}:o.length===1?o[0]:{t:"union",of:o}}function J(e,t){if(e=h(e),t=h(t),t.t==="union"){let n=t.of.map(r=>J(e,r));return n.some(r=>r===null)?null:{t:"union",of:n}}if(e.t==="intersection"){let n=[];for(let r of e.of){let o=J(h(r),t);if(o===null)return null;o.t!=="undefined"&&n.push(o);}return n.length===0?c.undefined:n.length===1?n[0]:j({of:n})}if(e.t==="object"){if(t.t==="literal"&&(typeof t.value=="string"||typeof t.value=="number")){let n=M(e.props,String(t.value));return n?n.optional?{t:"union",of:[n.type,{t:"undefined"}]}:n.type:typeof t.value=="number"&&e.index?.key==="number"||e.index?.key==="string"?e.index.value:c.undefined}if(e.index?.key==="string"&&t.t==="string"||e.index?.key==="number"&&(t.t==="number"||t.t==="literal"&&typeof t.value=="number"))return e.index.value}if(e.t==="tuple"){let n=e.flags?.findIndex(r=>r!=="req")??-1;if(n>=0){if(t.t==="literal"&&typeof t.value=="number")return t.value<n?e.elements[t.value]??c.undefined:e.elements.length?{t:"union",of:e.elements.slice(n)}:c.undefined;if(t.t==="number")return e.elements.length?{t:"union",of:e.elements}:c.undefined}else {if(t.t==="literal"&&typeof t.value=="number")return e.elements[t.value]??c.undefined;if(t.t==="number")return e.elements.length?{t:"union",of:e.elements}:c.undefined}}return e.t==="array"&&(t.t==="number"||t.t==="literal"&&typeof t.value=="number")?e.items:null}var je=Object.prototype.hasOwnProperty,M=(e,t)=>je.call(e,t)?e[t]:void 0;function B(e){if(e.t==="undefined")return {type:{t:"union",of:[]},hadUndefined:true};if(e.t==="union"&&e.of.some(t=>t.t==="undefined")){let t=e.of.filter(n=>n.t!=="undefined");return {type:t.length===1?t[0]:{t:"union",of:t},hadUndefined:true}}return {type:e,hadUndefined:false}}var K=(e,t)=>e.flags?.[t]??"req",ue=e=>e==="rest"||e==="variadic",Te=e=>!!e.flags?.some(ue),U=e=>e.flags?.findIndex(ue)??-1,we=e=>{if(!e.flags)return e.elements.length;let t=e.flags.findIndex(n=>n!=="req");return t<0?e.elements.length:t};function A(e,t){let n=[],r=[],o=(i,a)=>{n.push(i),r.push(a);};for(let i=0;i<e.length;i++){let a=e[i],l=t[i]??"req";if(l!=="variadic"){o(a,l);continue}if(a.t==="tuple"){let u=a;for(let d=0;d<u.elements.length;d++)o(u.elements[d],K(u,d));}else a.t==="array"?o(a.items,"rest"):a.t==="any"?o(a,"rest"):o(a,"variadic");}return c.tuple(n,r)}function le(e){let t=U(e);return t<0?{prefix:e.elements,rest:null,suffix:[]}:{prefix:e.elements.slice(0,t),rest:e.elements[t],suffix:e.elements.slice(t+1)}}function pe(e,t,n){let r=le(e),o=le(t);if(o.rest===null){if(r.rest!==null)return false;let i=we(t);return e.elements.length<i||e.elements.length>t.elements.length?false:e.elements.every((a,l)=>n(a,t.elements[l]))}if(r.rest===null){let i=r.prefix;if(i.length<o.prefix.length+o.suffix.length)return false;for(let a=0;a<o.prefix.length;a++)if(!n(i[a],o.prefix[a]))return false;for(let a=0;a<o.suffix.length;a++)if(!n(i[i.length-o.suffix.length+a],o.suffix[a]))return false;for(let a=o.prefix.length;a<i.length-o.suffix.length;a++)if(!n(i[a],o.rest))return false;return true}if(r.prefix.length>=o.prefix.length&&r.suffix.length>=o.suffix.length){for(let i=0;i<o.prefix.length;i++)if(!n(r.prefix[i],o.prefix[i]))return false;for(let i=o.prefix.length;i<r.prefix.length;i++)if(!n(r.prefix[i],o.rest))return false;if(!n(r.rest,o.rest))return false;for(let i=0;i<o.suffix.length;i++)if(!n(r.suffix[r.suffix.length-o.suffix.length+i],o.suffix[i]))return false;for(let i=0;i<r.suffix.length-o.suffix.length;i++)if(!n(r.suffix[i],o.rest))return false;return true}return false}function N(e,t,n){if(e.t==="array")return e;if(e.t==="tuple"){let r=e,o=r.elements.length,i=r.elements.slice(t,o-n),a=(r.flags??r.elements.map(()=>"req")).slice(t,o-n);return c.tuple(i,a)}return c.tuple([])}function s(e,t,n=new WeakSet){if(e.t!=="keyof"&&e.t!=="index"&&e.t!=="mapped"&&e.t!=="intersection"&&e.t!=="returnType"&&e.t!=="parameters"&&!$e(F(e),t))return e;switch(e.t){case "var":{let r=t[e.name];return r||(e.bound?{t:"var",name:e.name,bound:s(e.bound,t,n)}:e)}case "array":return {t:"array",items:s(e.items,t,n)};case "tuple":{let r=e.elements.map(o=>s(o,t,n));return e.flags?A(r,e.flags):{t:"tuple",elements:r}}case "union":return {t:"union",of:e.of.map(r=>s(r,t,n))};case "object":{if(n.has(e))return e;n.add(e);let r={};for(let i in e.props){let a=e.props[i];r[i]={type:s(a.type,t,n),optional:a.optional};}let o=e.index?{key:e.index.key,value:s(e.index.value,t,n)}:void 0;return n.delete(e),o?{t:"object",props:r,index:o}:{t:"object",props:r}}case "fn":{if(n.has(e))return e;n.add(e);let o={t:"fn",params:e.params.map(i=>({...i,type:s(i.type,t,n)})),returns:s(e.returns,t,n),...e.guard&&{guard:{param:e.guard.param,type:s(e.guard.type,t,n)}}};return n.delete(e),o}case "apply":return {t:"apply",name:e.name,args:e.args.map(r=>s(r,t,n))};case "keyof":return h({t:"keyof",of:s(e.of,t,n)});case "index":return h({t:"index",obj:s(e.obj,t,n),key:s(e.key,t,n)});case "mapped":{let r={};for(let i in t)i!==e.key&&(r[i]=t[i]);let o={t:"mapped",key:e.key,over:s(e.over,t,n),body:s(e.body,r,n),optional:e.optional};return V(o)??o}case "conditional":{if(e.check.t==="var"){let o=e.check.name,i=t[o],a=i?h(i):void 0,l=a?.t==="union"?a.of:a?.t==="boolean"?[c.literal(true),c.literal(false)]:null;if(l)return {t:"union",of:l.map(u=>s(e,{...t,[o]:u},n))}}let r=e.infer?.length?Object.fromEntries(Object.entries(t).filter(([o])=>!e.infer.includes(o))):t;return {t:"conditional",check:s(e.check,t,n),extends:s(e.extends,r,n),then:s(e.then,r,n),else:s(e.else,r,n),...e.infer?{infer:e.infer}:{}}}case "intersection":return j({of:e.of.map(r=>s(r,t,n))});case "returnType":return h({t:"returnType",fn:s(e.fn,t,n)});case "parameters":return h({t:"parameters",fn:s(e.fn,t,n)});default:return e}}var Ee=new Set,fe=new WeakMap;function F(e){let t=fe.get(e);if(t)return t;let n=new Set;y(e,n,new WeakSet);let r=n.size===0?Ee:n;return fe.set(e,r),r}function y(e,t,n){switch(e.t){case "var":t.add(e.name),e.bound&&y(e.bound,t,n);return;case "array":y(e.items,t,n);return;case "tuple":for(let r of e.elements)y(r,t,n);return;case "union":for(let r of e.of)y(r,t,n);return;case "object":if(n.has(e))return;n.add(e);for(let r in e.props)y(e.props[r].type,t,n);e.index&&y(e.index.value,t,n);return;case "fn":if(n.has(e))return;n.add(e);for(let r of e.params)y(r.type,t,n);y(e.returns,t,n),e.guard&&y(e.guard.type,t,n);return;case "overload":for(let r of e.signatures){for(let o of r.params)y(o.type,t,n);y(r.returns,t,n);}return;case "apply":for(let r of e.args)y(r,t,n);return;case "keyof":y(e.of,t,n);return;case "index":y(e.obj,t,n),y(e.key,t,n);return;case "mapped":y(e.over,t,n),y(e.body,t,n);return;case "conditional":{if(y(e.check,t,n),!e.infer?.length){y(e.extends,t,n),y(e.then,t,n),y(e.else,t,n);return}let r=new Set;y(e.extends,r,n),y(e.then,r,n),y(e.else,r,n);for(let o of r)e.infer.includes(o)||t.add(o);return}case "intersection":for(let r of e.of)y(r,t,n);return;case "returnType":case "parameters":y(e.fn,t,n);return;default:return}}function $e(e,t){if(e.size===0)return false;for(let n of e)if(n in t)return true;return false}function V(e){let t=h(e.over);if(t.t==="string"||t.t==="number")return {t:"object",props:{},index:{key:t.t,value:s(e.body,{[e.key]:t})}};let n=Ie(t);if(n===null)return null;let r={};for(let o of n)r[o]={type:s(e.body,{[e.key]:c.literal(o)}),optional:e.optional};return {t:"object",props:r}}function Ie(e){if(e.t==="literal"&&typeof e.value=="string")return [e.value];if(e.t==="union"){let t=[];for(let n of e.of)if(n.t==="literal"&&typeof n.value=="string")t.push(n.value);else return null;return t}return null}function E(e,t){if(e.t!=="apply")return false;let n=t[e.name];return n!==void 0&&n.params.length===e.args.length}function $(e,t){if(e.t!=="apply")return e;let n=t[e.name];if(!n||n.params.length!==e.args.length)return e;let r={};return n.params.forEach((o,i)=>r[o]=e.args[i]),s(n.body,r)}function g(e){switch(e.t){case "literal":return `#${typeof e.value}:${String(e.value)}`;case "object":{let t=Object.keys(e.props).sort().map(r=>`${r}${e.props[r].optional?"?":""}:${g(e.props[r].type)}`).join(","),n=e.index?`,[${e.index.key}]:${g(e.index.value)}`:"";return `{${t}${n}}`}case "array":return `[${g(e.items)}]`;case "tuple":return `#tuple(${e.elements.map(g).join(",")})`;case "union":return `(${e.of.map(g).sort().join("|")})`;case "fn":return `(${e.params.map(t=>g(t.type)).join(",")})=>${e.guard?`is${e.guard.param}:${g(e.guard.type)}`:g(e.returns)}`;case "var":return `v:${e.name}`;case "apply":return `${e.name}<${e.args.map(g).join(",")}>`;case "intersection":return `&(${e.of.map(g).sort().join("&")})`;case "returnType":return `RT<${g(e.fn)}>`;default:return e.t}}var Oe=1e3,Y={maxTypeDepth:1e3,maxUnionMembers:1e3,maxOverloadSignatures:200},D=Y;function Me(e){D={...Y,...e};}function Pe(){D=Y;}function R(){return D}var P=class extends Error{constructor(t=D.maxTypeDepth){super(`type evaluation exceeded the depth limit (${t}) \u2014 the type is excessively deep or possibly infinite`),this.name="TypeEvalLimitError";}},C=class extends Error{constructor(t,n=D.maxUnionMembers){super(`union type is too complex to represent (${t} members exceeds limit ${n})`),this.name="UnionTooComplexError";}};var Q=(e,t)=>({seen:new WeakMap,exp:new Set,schemes:e,depth:0,explain:t});function w(e,t,n){return e.explain?.out.push({path:[...e.explain.path],actual:t,expected:n,kind:"type"}),false}function Le(e,t,n={}){let r=[];return !p(e,t,Q(n,{path:[],out:r}))&&r.length===0&&r.push({path:[],actual:e,expected:t,kind:"type"}),r}var Z=new WeakMap;function v(e,t,n={}){if(e===t)return true;if(Object.keys(n).length>0)return p(e,t,Q(n));let r=Z.get(e)?.get(t);if(r!==void 0)return r;let o=p(e,t,Q(n)),i=Z.get(e);return i||Z.set(e,i=new WeakMap),i.set(t,o),o}function We(e,t,n={}){return v(e,t,n)&&v(t,e,n)}function q(e,t){return e.infer?.length||F(e.check).size>0||F(e.extends).size>0?null:v(e.check,e.extends,t)?e.then:e.else}function z(e,t,n=0){if(n>50)return e;let r=h(e);if(r!==e)return z(r,t,n+1);if(e.t==="conditional"){let o=q(e,t.schemes);if(o)return z(o,t,n+1)}return E(e,t.schemes)?z($(e,t.schemes),t,n+1):e.t==="union"?k(e.of.map(o=>z(o,t,n+1))):e}function p(e,t,n){if(n.depth>=R().maxTypeDepth)throw new P;n.depth++;try{return Be(e,t,n)}finally{n.depth--;}}function X(e,t,n,r){if(!n.explain)return p(e,t,n);n.explain.path.push(r);try{return p(e,t,n)}finally{n.explain.path.pop();}}function Be(e,t,n){if(e.t==="any"||t.t==="any"||t.t==="unknown")return true;if(e.t==="unknown")return w(n,e,t);let r=h(e);if(r!==e)return p(r,t,n);let o=h(t);if(o!==t)return p(e,o,n);if(e.t==="mapped"){let l=V({...e,over:z(e.over,n)});if(l)return p(l,t,n)}if(t.t==="mapped"){let l=V({...t,over:z(t.over,n)});if(l)return p(e,l,n)}if(e.t==="conditional"){let l=q(e,n.schemes);if(l)return p(l,t,n)}if(t.t==="conditional"){let l=q(t,n.schemes);if(l)return p(e,l,n)}if(t.t==="intersection"){let l=j(t);return l.t!=="intersection"?p(e,l,n):l.of.every(u=>p(e,u,n))}if(e.t==="intersection"){let l=j(e);if(l.t!=="intersection")return p(l,t,n);if(l.of.some(u=>p(u,t,n)))return true;if(t.t==="object"){let u=Re(l.of);if(u)return p(u,t,n)}return false}if(!(e.t==="apply"&&t.t==="apply"&&e.name===t.name&&e.args.length===t.args.length)&&(E(e,n.schemes)||E(t,n.schemes))){let l=`${g(e)}\u2264${g(t)}`;if(n.exp.has(l))return true;n.exp.add(l);let u=p($(e,n.schemes),$(t,n.schemes),n);return n.exp.delete(l),u}let a=n.seen.get(e);if(a?.has(t))return true;if(a||(a=new WeakSet,n.seen.set(e,a)),a.add(t),e.t==="union")return e.of.every(l=>p(l,t,n));if(e.t==="boolean"&&t.t==="union")return p(c.literal(true),t,n)&&p(c.literal(false),t,n);if(t.t==="union")return t.of.some(l=>p(e,l,n));if(t.t==="overload")return t.signatures.every(l=>p(e,l,n));if(e.t==="overload")return e.signatures.some(l=>p(l,t,n));switch(t.t){case "literal":return e.t==="literal"&&e.value===t.value?true:w(n,e,t);case "string":case "number":case "boolean":case "null":case "undefined":return e.t===t.t||e.t==="literal"&&Fe(e.value)===t.t?true:w(n,e,t);case "void":return e.t==="void"||e.t==="undefined"?true:w(n,e,t);case "array":return e.t==="array"?p(e.items,t.items,n):e.t==="tuple"?e.elements.every(l=>p(l,t.items,n)):w(n,e,t);case "tuple":{if(e.t!=="tuple")return w(n,e,t);if(!e.flags&&!t.flags){if(e.elements.length!==t.elements.length)return w(n,e,t);for(let l=0;l<e.elements.length;l++)if(!X(e.elements[l],t.elements[l],n,String(l)))return false;return true}return pe(e,t,(l,u)=>p(l,u,n))}case "object":return e.t==="object"?ze(e,t,n):Object.keys(t.props).length===0&&!t.index?e.t!=="null"&&e.t!=="undefined"&&e.t!=="void"?true:w(n,e,t):e.t==="array"&&t.index&&Object.values(t.props).every(l=>l.optional)&&p(e.items,t.index.value,n)?true:w(n,e,t);case "fn":return e.t==="fn"?Ue(e,t,n):w(n,e,t);case "var":return e.t==="var"&&e.name===t.name;case "keyof":return e.t==="keyof"&&p(e.of,t.of,n)&&p(t.of,e.of,n);case "index":return e.t==="index"&&p(e.obj,t.obj,n)&&p(t.obj,e.obj,n)&&p(e.key,t.key,n)&&p(t.key,e.key,n);case "mapped":return e.t==="mapped"&&e.key===t.key&&!!e.optional==!!t.optional&&p(e.over,t.over,n)&&p(t.over,e.over,n)&&p(e.body,t.body,n)&&p(t.body,e.body,n);case "conditional":return e.t==="conditional"&&p(e.check,t.check,n)&&p(t.check,e.check,n)&&p(e.extends,t.extends,n)&&p(t.extends,e.extends,n)&&p(e.then,t.then,n)&&p(e.else,t.else,n);case "apply":return e.t==="apply"&&e.name===t.name&&e.args.length===t.args.length&&e.args.every((l,u)=>p(l,t.args[u],n));case "returnType":return e.t==="returnType"&&p(e.fn,t.fn,n)&&p(t.fn,e.fn,n);case "parameters":return e.t==="parameters"&&p(e.fn,t.fn,n)&&p(t.fn,e.fn,n)}}var Fe=e=>typeof e;function Re(e){let t=[];for(let i of e){let a=h(i);if(a.t!=="object")return null;t.push(a);}let n=new Set;for(let i of t)for(let a in i.props)n.add(a);let r={};for(let i of n){let a=[],l=true;for(let u of t){let d=u.props[i];d?(a.push(d.type),d.optional||(l=false)):u.index?.key==="string"&&(a.push(u.index.value),l=false);}r[i]={type:j({of:a}),optional:l};}let o;for(let i of t)i.index&&(o=o?{key:o.key,value:j({of:[o.value,i.index.value]})}:i.index);return o?{t:"object",props:r,index:o}:{t:"object",props:r}}function ze(e,t,n){let r=false;for(let o in t.props)if(!(t.props[o].optional||M(e.props,o))){if(!n.explain)return false;n.explain.out.push({path:[...n.explain.path,o],expected:t.props[o].type,kind:"missing"}),r=true;}if(r)return false;for(let o in t.props){let i=t.props[o],a=M(e.props,o);if(a&&(a.optional&&!i.optional||!X(a.type,i.type,n,o)))return false}if(t.index){for(let o in e.props)if(!X(e.props[o].type,t.index.value,n,o))return false;if(e.index&&!p(e.index.value,t.index.value,n))return false}return true}function Ue(e,t,n){if(t.returns.t!=="void"&&t.returns.t!=="any"&&!p(e.returns,t.returns,n))return false;for(let r=0;r<e.params.length;r++){let o=e.params[r];if(o.variadic)break;let i=t.params[r];if(!i){if(o.optional)continue;return false}if(!p(i.type,o.type,n))return false}return !(t.guard&&(!e.guard||e.guard.param!==t.guard.param||!p(e.guard.type,t.guard.type,n)))}function k(e){let t=[];for(let o of e)o.t==="union"?t.push(...o.of):t.push(o);let n=R().maxUnionMembers;if(t.length>n)throw new C(t.length,n);if(t.some(o=>o.t==="any"))return c.any;let r=[];for(let o of t)if(!r.some(i=>v(o,i))){for(let i=r.length-1;i>=0;i--)v(r[i],o)&&r.splice(i,1);r.push(o);}if(r.some(o=>o.t==="literal"&&o.value===true)&&r.some(o=>o.t==="literal"&&o.value===false)){let o=r.filter(i=>!(i.t==="boolean"||i.t==="literal"&&typeof i.value=="boolean"));o.push(c.boolean),r.length=0,r.push(...o);}return r.length===1?r[0]:{t:"union",of:r}}function Ae(e,t){let n=new Set,r=new WeakSet,o=i=>{if(!r.has(i))switch(r.add(i),i.t){case "keyof":n.add("keyof"),o(i.of);break;case "index":n.add("indexed"),o(i.obj),o(i.key);break;case "mapped":n.add("mapped"),o(i.over),o(i.body);break;case "conditional":n.add("conditional"),i.infer?.length&&n.add("infer"),o(i.check),o(i.extends),o(i.then),o(i.else);break;case "returnType":n.add("returnType"),o(i.fn);break;case "parameters":n.add("parameters"),o(i.fn);break;case "tuple":n.add("tuple"),i.flags?.some(a=>a!=="req")&&n.add("variadic"),i.elements.forEach(o);break;case "intersection":n.add("intersection"),i.of.forEach(o);break;case "overload":n.add("overload");for(let a of i.signatures){for(let l of a.params)o(l.type);o(a.returns);}break;case "object":for(let a in i.props)o(i.props[a].type);i.index&&o(i.index.value);break;case "array":o(i.items);break;case "union":i.of.forEach(o);break;case "fn":for(let a of i.params)o(a.type);o(i.returns),i.guard&&o(i.guard.type);break;case "var":i.bound&&o(i.bound);break;case "apply":t&&i.name===t&&n.add("recursion"),i.args.forEach(o);break}};return o(e),n}var ce=e=>typeof e=="string"?c.string:typeof e=="number"?c.number:c.boolean;function ee(e){return e.t==="literal"&&e.fresh?ce(e.value):e}function Ce(e){return b(e,new WeakSet)}function De(e){switch(e.t){case "array":return {t:"array",items:b(e.items,new WeakSet)};case "tuple":return {t:"tuple",elements:e.elements.map(t=>b(t,new WeakSet)),...e.flags?{flags:e.flags}:{}};case "object":return se(e,new WeakSet);case "fn":case "overload":return b(e,new WeakSet);default:return e}}function b(e,t){if(e.t==="literal")return e.fresh?ce(e.value):e;if(t.has(e))return e;switch(e.t){case "array":return t.add(e),{t:"array",items:b(e.items,t)};case "tuple":return t.add(e),{t:"tuple",elements:e.elements.map(n=>b(n,t)),...e.flags?{flags:e.flags}:{}};case "object":return t.add(e),se(e,t);case "apply":return t.add(e),{t:"apply",name:e.name,args:e.args.map(n=>b(n,t))};case "fn":return t.add(e),{t:"fn",params:e.params.map(n=>({...n,type:b(n.type,t)})),returns:b(e.returns,t),...e.guard?{guard:{param:e.guard.param,type:b(e.guard.type,t)}}:{}};case "overload":return t.add(e),{t:"overload",signatures:e.signatures.map(n=>b(n,t))};default:return e}}function se(e,t){let n={};for(let o in e.props)n[o]={type:b(e.props[o].type,t),optional:e.props[o].optional};let r=e.index?{key:e.index.key,value:b(e.index.value,t)}:void 0;return r?{t:"object",props:n,index:r}:{t:"object",props:n}}var de=e=>e.t==="literal"?typeof e.value:e.t==="string"||e.t==="number"||e.t==="boolean"?e.t:null;function qe(e,t){if(v(t,e))return e;if(v(e,t))return t;let n=de(e),r=de(t);return !n||!r||n===r?k([e,t]):null}function x(e,t,n={}){if(e.t==="var"){let r=n[e.name];if(!r)return {...n,[e.name]:t};if(t.t==="any"||t.t==="unknown")return n;let o=qe(r,t);return o?{...n,[e.name]:o}:n}if(t.t==="any"||t.t==="unknown")return n;switch(e.t){case "array":return t.t==="array"?x(e.items,t.items,n):null;case "tuple":{let r=e,o=U(r);if(o<0){if(t.t!=="tuple"||t.elements.length!==r.elements.length)return null;let f=n;for(let W=0;W<r.elements.length;W++)if(f=x(r.elements[W],t.elements[W],f),f===null)return null;return f}let i=o,a=r.elements.length-o-1,l=K(r,o),u=f=>l==="variadic"?f:f.t==="tuple"?f.elements.length?k(f.elements):c.unknown:f.t==="array"?f.items:f,d=n,m=(f,W)=>{d!==null&&(d=x(f,W,d));};if(t.t==="tuple"){if(t.elements.length<i+a)return null;for(let f=0;f<i;f++)m(r.elements[f],t.elements[f]);for(let f=0;f<a;f++)m(r.elements[o+1+f],t.elements[t.elements.length-a+f]);return d!==null&&(d=x(r.elements[o],u(N(t,i,a)),d)),d}if(t.t==="array"){for(let f=0;f<i;f++)m(r.elements[f],t.items);for(let f=0;f<a;f++)m(r.elements[o+1+f],t.items);return d!==null&&(d=x(r.elements[o],u(t),d)),d}return null}case "object":{if(t.t!=="object")return null;let r=n;for(let o in e.props){let i=e.props[o],a=t.props[o];if(!a){if(i.optional)continue;return null}if(r=x(i.type,a.type,r),r===null)return null}return r}case "fn":{if(t.t!=="fn")return null;let r=x(e.returns,t.returns,n);if(r===null)return null;let o=Math.min(e.params.length,t.params.length);for(let i=0;i<o;i++)if(r=x(e.params[i].type,t.params[i].type,r),r===null)return null;return e.guard&&t.guard&&(r=x(e.guard.type,t.guard.type,r)),r}case "apply":{if(t.t!=="apply"||t.name!==e.name||t.args.length!==e.args.length)return null;let r=n;for(let o=0;o<e.args.length;o++)if(r=x(e.args[o],t.args[o],r),r===null)return null;return r}default:return v(t,e)?n:null}}var me="@rev",te=e=>e.t==="mapped"&&e.over.t==="keyof"&&e.over.of.t==="var";function I(e,t,n){if(e.t==="index"&&e.obj.t==="var"&&e.obj.name===t&&e.key.t==="var"&&e.key.name===n)return c.var(me);switch(e.t){case "array":return {t:"array",items:I(e.items,t,n)};case "tuple":return {t:"tuple",elements:e.elements.map(r=>I(r,t,n)),...e.flags?{flags:e.flags}:{}};case "union":return {t:"union",of:e.of.map(r=>I(r,t,n))};case "fn":return {t:"fn",params:e.params.map(r=>({...r,type:I(r.type,t,n)})),returns:I(e.returns,t,n)};case "apply":return {t:"apply",name:e.name,args:e.args.map(r=>I(r,t,n))};case "returnType":return {t:"returnType",fn:I(e.fn,t,n)};case "object":{let r={};for(let o in e.props)r[o]={type:I(e.props[o].type,t,n),optional:e.props[o].optional};return e.index?{t:"object",props:r,index:{key:e.index.key,value:I(e.index.value,t,n)}}:{t:"object",props:r}}default:return e}}function _e(e,t,n){if(e.over.t!=="keyof"||e.over.of.t!=="var")return null;let r=e.over.of.name;if(n[r])return null;let o={};for(let i in t.props){let a=I(e.body,r,e.key),l=x(a,t.props[i].type,{})?.[me];o[i]={type:l?ee(l):c.unknown,optional:t.props[i].optional};}return {...n,[r]:{t:"object",props:o}}}function ye(e,t,n){let r=n;for(let o=0;o<e.length&&o<t.length;o++){let i=e[o].type,a=t[o];if(te(i)&&a.t==="object"){let l=_e(i,a,r);l&&(r=l);}}return r}function Ke(e,t){let n={};for(let o=0;o<e.params.length;o++){let i=e.params[o];if(i.variadic){for(let a=o;a<t.length;a++)if(n=x(i.type,t[a],n),n===null)return null;break}if(o>=t.length){if(i.optional)continue;return null}if(!te(i.type)&&(n=x(i.type,t[o],n),n===null))return null}let r=ye(e.params,t,n);return {returns:s(e.returns,r),bindings:r}}function Ne(e,t){let n={};for(let r=0;r<e.params.length&&r<t.length;r++){let o=e.params[r];if(te(o.type))continue;let i=x(o.type,t[r],n);i!==null&&(n=i);}return n=ye(e.params,t,n),{returns:s(e.returns,n),bindings:n}}function T(e,t,n,r,o){if(e.t==="var"&&n.has(e.name)){let i=o.get(e.name);i||o.set(e.name,i={co:[],contra:[]}),(r?i.contra:i.co).push(t);return}if(!(t.t==="any"||t.t==="unknown"))switch(e.t){case "array":t.t==="array"&&T(e.items,t.items,n,r,o);return;case "tuple":{let i=e,a=U(i);if(a<0){t.t==="tuple"&&t.elements.length===i.elements.length&&i.elements.forEach((m,f)=>T(m,t.elements[f],n,r,o));return}let l=a,u=i.elements.length-a-1,d=m=>T(i.elements[a],m,n,r,o);if(t.t==="tuple"){let m=t;if(m.elements.length<l+u)return;for(let f=0;f<l;f++)T(i.elements[f],m.elements[f],n,r,o);for(let f=0;f<u;f++)T(i.elements[a+1+f],m.elements[m.elements.length-u+f],n,r,o);d(N(m,l,u));}else if(t.t==="array"){for(let m=0;m<l;m++)T(i.elements[m],t.items,n,r,o);for(let m=0;m<u;m++)T(i.elements[a+1+m],t.items,n,r,o);d(t);}return}case "fn":t.t==="fn"&&(e.params.forEach((i,a)=>{let l=t.params[a];l&&T(i.type,l.type,n,!r,o);}),T(e.returns,t.returns,n,r,o));return;case "object":if(t.t==="object")for(let i in e.props)t.props[i]&&T(e.props[i].type,t.props[i].type,n,r,o);return;case "apply":t.t==="apply"&&t.name===e.name&&t.args.length===e.args.length&&e.args.forEach((i,a)=>T(i,t.args[a],n,r,o));return;default:return}}function Ve(e,t){if(e.length===1)return e[0];let r=e.flatMap(o=>o.t==="union"?[...o.of]:[o]).filter(o=>e.every(i=>v(o,i,t)));return k(r)}var Ye=e=>e.t==="union"&&e.of.length===0;function Ge(e,t){let n={};for(let[r,{co:o,contra:i}]of e){let a=o.length?k(o):void 0,l=i.length?Ve(i,t):void 0,u=a??l;a&&l&&(u=!Ye(a)&&a.t!=="any"&&v(a,l,t)?a:l),u&&(n[r]=u);}return n}function He(e,t={},n=0){if(!e.infer?.length||F(e.check).size>0)return null;let r=new Map;T(e.extends,e.check,new Set(e.infer),false,r);let o=Ge(r,t),i=new WeakSet,a=G(s(e.extends,o),t,i,n);return v(e.check,a,t)?G(s(e.then,o),t,i,n):G(s(e.else,o),t,i,n)}function G(e,t={},n=new WeakSet,r=0){let o=r,i=R().maxTypeDepth,a=l=>{switch(l.t){case "var":return c.unknown;case "array":return {t:"array",items:a(l.items)};case "tuple":{let u=l.elements.map(a);return l.flags?A(u,l.flags):{t:"tuple",elements:u}}case "union":return {t:"union",of:l.of.map(a)};case "object":{if(n.has(l))return l;n.add(l);let u={};for(let m in l.props){let f=l.props[m];u[m]={type:a(f.type),optional:f.optional};}let d=l.index?{key:l.index.key,value:a(l.index.value)}:void 0;return n.delete(l),d?{t:"object",props:u,index:d}:{t:"object",props:u}}case "fn":{if(n.has(l))return l;n.add(l);let d={t:"fn",params:l.params.map(m=>({...m,type:a(m.type)})),returns:a(l.returns),...l.guard&&{guard:{param:l.guard.param,type:a(l.guard.type)}}};return n.delete(l),d}case "apply":{if(E(l,t)){let u=$(l,t);if(u.t==="conditional"){if(o>=i)throw new P;o++;try{let d=a(u);if(d.t!=="conditional")return d}finally{o--;}}}return {t:"apply",name:l.name,args:l.args.map(a)}}case "conditional":{let u=l.infer?.length?He(l,t,o):q(l,t);return u?a(u):{t:"conditional",check:a(l.check),extends:a(l.extends),then:a(l.then),else:a(l.else),...l.infer?{infer:l.infer}:{}}}case "intersection":return j({of:l.of.map(a)});case "returnType":return h({t:"returnType",fn:a(l.fn)});default:return l}};return a(e)}var Je=c.union([]);function Se(e,t){return ne(e,t,new WeakMap)}function Ze(e){return e.reduce(Se,Je)}function ne(e,t,n){if(e.t==="any"||t.t==="any")return c.any;if(e===t)return e;let r=n.get(e)?.get(t);if(r)return r;if(e.t==="object"&&t.t==="object")return Qe(e,t,n);if(e.t==="array"&&t.t==="array"){let o={t:"array",items:c.unknown};return he(n,e,t,o),o.items=ne(e.items,t.items,n),o}return k([e,t])}function Qe(e,t,n){let r={t:"object",props:{}};he(n,e,t,r);for(let o in e.props){let i=e.props[o],a=t.props[o];if(a){let l=ne(i.type,a.type,n);r.props[o]=i.optional||a.optional?{type:l,optional:true}:{type:l};}else r.props[o]={type:i.type,optional:true};}for(let o in t.props)o in e.props||(r.props[o]={type:t.props[o].type,optional:true});return r}function he(e,t,n,r){let o=e.get(t);o||(o=new WeakMap,e.set(t,o)),o.set(n,r);}var Xe=e=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e);function S(e,t=new WeakSet){switch(e.t){case "any":case "unknown":case "string":case "number":case "boolean":case "null":case "undefined":case "void":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 n=S(e.items,t);return et(e.items)?`(${n})[]`:`${n}[]`}case "tuple":return `[${e.elements.map((r,o)=>{let i=e.flags?.[o]??"req",a=S(r,t),l=r.t==="union"?`(${a})`:a;return i==="rest"?`...${l}[]`:i==="variadic"?`...${a}`:i==="optional"?`${l}?`:a}).join(", ")}]`;case "union":{if(t.has(e))return "\u2026";t.add(e);let n=e.of.length===0?"never":e.of.map(r=>S(r,t)).join(" | ");return t.delete(e),n}case "object":{if(t.has(e))return "\u2026";t.add(e);let n=Object.entries(e.props).map(([r,o])=>`${Xe(r)?r:JSON.stringify(r)}${o.optional?"?":""}: ${S(o.type,t)}`);return e.index&&n.push(`[k: ${e.index.key}]: ${S(e.index.value,t)}`),t.delete(e),n.length===0?"{}":`{ ${n.join("; ")} }`}case "fn":{if(t.has(e))return "\u2026";t.add(e);let n=e.params.map(o=>{let i=o.variadic?"...":"",a=o.optional&&!o.variadic?"?":"";return `${i}${o.name}${a}: ${S(o.type,t)}`}).join(", "),r=e.guard?`${e.params[e.guard.param]?.name??`arg${e.guard.param}`} is ${S(e.guard.type,t)}`:S(e.returns,t);return t.delete(e),`(${n}) => ${r}`}case "apply":{if(t.has(e))return "\u2026";t.add(e);let n=e.args.length===0?e.name:`${e.name}<${e.args.map(r=>S(r,t)).join(", ")}>`;return t.delete(e),n}case "overload":{if(t.has(e))return "\u2026";t.add(e);let n=e.signatures.map(r=>S(r,t)).join(" & ");return t.delete(e),n}case "keyof":return `keyof ${S(e.of,t)}`;case "index":return `${S(e.obj,t)}[${S(e.key,t)}]`;case "mapped":{if(t.has(e))return "\u2026";t.add(e);let n=e.optional?"?":"",r=`{ [${e.key} in ${S(e.over,t)}]${n}: ${S(e.body,t)} }`;return t.delete(e),r}case "conditional":{if(t.has(e))return "\u2026";t.add(e);let n=`${S(e.check,t)} extends ${S(e.extends,t)} ? ${S(e.then,t)} : ${S(e.else,t)}`;return t.delete(e),n}case "intersection":return e.of.map(n=>n.t==="union"&&n.of.length>0?`(${S(n,t)})`:S(n,t)).join(" & ");case "returnType":return `ReturnType<${S(e.fn,t)}>`;case "parameters":return `Parameters<${S(e.fn,t)}>`}}function et(e){return e.t==="union"&&e.of.length>0||e.t==="fn"}function tt(e){if(e.length===0)return "value";let t=e[e.length-1];if(/^\d+$/.test(t)){let n=e.slice(0,-1);return n.length?`property '${n.join(".")}' at position ${t}`:`position ${t}`}return `property '${e.join(".")}'`}function nt(e){let t=e.filter(n=>n.kind==="missing");if(t.length&&t.length===e.length){let n=t.map(r=>`'${r.path.join(".")}'`).join(", ");return t.length===1?`property ${n} is missing`:`properties ${n} are missing`}return e.map(n=>`${tt(n.path)}: expected '${S(n.expected)}', got '${S(n.actual)}'`).join("; ")}function L(e,t=new WeakSet){switch(e.t){case "string":case "number":case "boolean":case "null":case "literal":return true;case "array":return t.has(e)?true:(t.add(e),L(B(e.items).type,t));case "tuple":return t.has(e)?true:(t.add(e),e.elements.every(n=>L(B(n).type,t)));case "object":{if(t.has(e))return true;t.add(e);let n=Object.values(e.props).every(o=>L(B(o.type).type,t)),r=!e.index||L(B(e.index.value).type,t);return n&&r}case "union":return t.has(e)?true:(t.add(e),e.of.every(n=>L(n,t)));case "intersection":return t.has(e)?true:(t.add(e),e.of.every(n=>L(n,t)));case "undefined":case "void":case "fn":case "overload":case "keyof":case "index":case "mapped":case "conditional":case "returnType":case "parameters":case "var":case "apply":case "any":case "unknown":return false}}function rt(e,t,n={}){let r=e;for(let o of t){let i=_(r,o,n);if(i===null)return null;r=i;}return {type:r,completions:H(r,n)}}var ot=e=>e==="[]"||/^\d+$/.test(e);function _(e,t,n,r=new Set){if(E(e,n)){let i=g(e);if(r.has(i))return null;r.add(i);let a=_($(e,n),t,n,r);return r.delete(i),a}let o=h(e);if(o!==e)return _(o,t,n,r);switch(e.t){case "any":return e;case "object":{let i=M(e.props,t);return i?i.optional?k([i.type,{t:"undefined"}]):i.type:e.index?.key==="string"?e.index.value:null}case "array":return ot(t)?e.items:null;case "tuple":{let i=e.flags?.findIndex(u=>u!=="req")??-1,a=Number(t);if(!(Number.isInteger(a)&&a>=0))return null;if(i<0)return a<e.elements.length?e.elements[a]:null;if(a<i)return e.elements[a];let l=e.elements.slice(i);return l.length?k(l):null}case "union":{let i=e.of.map(a=>_(a,t,n,r)).filter(a=>a!==null);return i.length?k(i):null}case "intersection":{let i=e.of.map(a=>_(a,t,n,r)).filter(a=>a!==null);return i.length?j({of:i}):null}default:return null}}function H(e,t,n=new WeakSet,r=new Set){if(E(e,t)){let i=g(e);if(r.has(i))return [];r.add(i);let a=H($(e,t),t,n,r);return r.delete(i),a}let o=h(e);if(o!==e)return H(o,t,n,r);switch(e.t){case "object":return Object.entries(e.props).map(([i,a])=>({key:i,type:a.type,optional:!!a.optional}));case "array":return [{key:"[]",type:e.items,optional:false}];case "tuple":return e.elements.map((i,a)=>({key:String(a),type:i,optional:false}));case "union":case "intersection":{if(n.has(e))return [];n.add(e);let i=[],a=new Set;for(let l of e.of)for(let u of H(l,t,n,r))a.has(u.key)||(a.add(u.key),i.push(u));return n.delete(e),i}default:return []}}exports.DEFAULT_TYPE_LIMITS=Y;exports.TYPE_EVAL_DEPTH_LIMIT=Oe;exports.TypeEvalLimitError=P;exports.UnionTooComplexError=C;exports.configureTypeLimits=Me;exports.discover=rt;exports.equals=We;exports.expand1=$;exports.flagAt=K;exports.format=S;exports.formatTypeDiff=nt;exports.groundVars=G;exports.instantiate=Ke;exports.instantiateLoose=Ne;exports.isScheme=E;exports.isSerializable=L;exports.isVariadicTuple=Te;exports.join=Se;exports.joinAll=Ze;exports.normalizeTuple=A;exports.normalizeUnion=k;exports.ownProp=M;exports.resetTypeLimits=Pe;exports.resolveTypeOp=h;exports.restIndex=U;exports.s=c;exports.sliceTuple=N;exports.substitute=s;exports.subtype=v;exports.typeDiff=Le;exports.typeFeatures=Ae;exports.typeLimits=R;exports.unify=x;exports.widen=ee;exports.widenInferred=De;exports.widenType=Ce;exports.withoutUndefined=B;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
/** Uma propriedade de um tipo objeto. */
|
|
2
|
+
interface Prop {
|
|
3
|
+
readonly type: Schema;
|
|
4
|
+
/** `true` quando a propriedade pode estar ausente (`{ x?: T }`). */
|
|
5
|
+
readonly optional?: boolean;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Assinatura de índice de um objeto — `{ [k: string]: V }` (a forma de `Record<K, V>`).
|
|
9
|
+
* Coexiste com props nomeadas (`{ a: number; [k: string]: unknown }`), como no TS.
|
|
10
|
+
* O domínio da chave é só `string`/`number` (o que o TS permite).
|
|
11
|
+
*/
|
|
12
|
+
interface IndexSig {
|
|
13
|
+
readonly key: "string" | "number";
|
|
14
|
+
readonly value: Schema;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Flag de um elemento de tupla (espelha o `ElementFlags` do tsc):
|
|
18
|
+
* - `req` — elemento posicional normal (`A` em `[A, B]`);
|
|
19
|
+
* - `optional` — `A?` (pode estar ausente; `[A, B?]`); só TRAILING, posicional;
|
|
20
|
+
* - `rest` — `...T[]` (cauda de array); o tipo do elemento é o do array;
|
|
21
|
+
* - `variadic` — `...T` (spread de uma tupla/var); após `normalizeTuple` só var
|
|
22
|
+
* genérica fica `variadic` (tupla concreta é espalhada; array vira `rest`).
|
|
23
|
+
*/
|
|
24
|
+
type ElementFlag = "req" | "optional" | "rest" | "variadic";
|
|
25
|
+
/** Um parâmetro de um tipo função. */
|
|
26
|
+
interface Param {
|
|
27
|
+
readonly name: string;
|
|
28
|
+
readonly type: Schema;
|
|
29
|
+
/** `true` quando o argumento pode ser omitido. */
|
|
30
|
+
readonly optional?: boolean;
|
|
31
|
+
/** `true` para o parâmetro rest (`...args: T[]`). */
|
|
32
|
+
readonly variadic?: boolean;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Type predicate `(v) => v is S` — quando a fn devolve `true`, o argumento na
|
|
36
|
+
* posição `param` é estreitado para `type` (S). `returns` da fn continua `boolean`
|
|
37
|
+
* (é o que roda); o `guard` é a info de narrowing. `filter`/`find` inferem S dele;
|
|
38
|
+
* `if (g(x))` estreita `x` (D13). Covariante em `type`.
|
|
39
|
+
*/
|
|
40
|
+
interface GuardSig {
|
|
41
|
+
readonly param: number;
|
|
42
|
+
readonly type: Schema;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* O tipo de um valor na linguagem TSLite.
|
|
46
|
+
*
|
|
47
|
+
* O discriminador é `t`. Estruturas (object/array/union/fn) referenciam outros
|
|
48
|
+
* `Schema` recursivamente — inclusive de forma cíclica (ex.: `Node` que contém
|
|
49
|
+
* `Node[]`); as operações que percorrem `Schema` são cycle-safe.
|
|
50
|
+
*/
|
|
51
|
+
type Schema = {
|
|
52
|
+
readonly t: "any";
|
|
53
|
+
} | {
|
|
54
|
+
readonly t: "unknown";
|
|
55
|
+
} | {
|
|
56
|
+
readonly t: "string";
|
|
57
|
+
} | {
|
|
58
|
+
readonly t: "number";
|
|
59
|
+
} | {
|
|
60
|
+
readonly t: "boolean";
|
|
61
|
+
} | {
|
|
62
|
+
readonly t: "null";
|
|
63
|
+
} | {
|
|
64
|
+
readonly t: "undefined";
|
|
65
|
+
} | {
|
|
66
|
+
readonly t: "void";
|
|
67
|
+
} | {
|
|
68
|
+
readonly t: "literal";
|
|
69
|
+
readonly value: string | number | boolean;
|
|
70
|
+
/**
|
|
71
|
+
* `fresh` = literal "fresco" de uma EXPRESSÃO de valor (`1`, `"x"`) — alarga
|
|
72
|
+
* pra base em posição de membro (array/object/tupla) ou inferido num `T[]`,
|
|
73
|
+
* mas preserva no topo (`const x = 1` → `1`; `id(1)` → `1`). Literal de
|
|
74
|
+
* `keyof`/declarado é NÃO-fresh → nunca alarga. Transparente p/ subtype/equals.
|
|
75
|
+
*/
|
|
76
|
+
readonly fresh?: boolean;
|
|
77
|
+
} | {
|
|
78
|
+
readonly t: "object";
|
|
79
|
+
readonly props: Readonly<Record<string, Prop>>;
|
|
80
|
+
/** Assinatura de índice (`Record<K, V>`); coexiste com `props`. Ausente = objeto fechado. */
|
|
81
|
+
readonly index?: IndexSig;
|
|
82
|
+
} | {
|
|
83
|
+
readonly t: "array";
|
|
84
|
+
readonly items: Schema;
|
|
85
|
+
} | {
|
|
86
|
+
readonly t: "tuple";
|
|
87
|
+
readonly elements: readonly Schema[];
|
|
88
|
+
readonly flags?: readonly ElementFlag[];
|
|
89
|
+
} | {
|
|
90
|
+
readonly t: "union";
|
|
91
|
+
readonly of: readonly Schema[];
|
|
92
|
+
} | {
|
|
93
|
+
readonly t: "fn";
|
|
94
|
+
readonly params: readonly Param[];
|
|
95
|
+
readonly returns: Schema;
|
|
96
|
+
/** Type predicate `(v) => v is S` — narrowing (ver `GuardSig`). */
|
|
97
|
+
readonly guard?: GuardSig;
|
|
98
|
+
} | {
|
|
99
|
+
readonly t: "overload";
|
|
100
|
+
readonly signatures: readonly {
|
|
101
|
+
readonly t: "fn";
|
|
102
|
+
readonly params: readonly Param[];
|
|
103
|
+
readonly returns: Schema;
|
|
104
|
+
readonly guard?: GuardSig;
|
|
105
|
+
}[];
|
|
106
|
+
} | {
|
|
107
|
+
readonly t: "keyof";
|
|
108
|
+
readonly of: Schema;
|
|
109
|
+
} | {
|
|
110
|
+
readonly t: "index";
|
|
111
|
+
readonly obj: Schema;
|
|
112
|
+
readonly key: Schema;
|
|
113
|
+
} | {
|
|
114
|
+
readonly t: "mapped";
|
|
115
|
+
readonly key: string;
|
|
116
|
+
readonly over: Schema;
|
|
117
|
+
readonly body: Schema;
|
|
118
|
+
readonly optional?: boolean;
|
|
119
|
+
} | {
|
|
120
|
+
readonly t: "conditional";
|
|
121
|
+
readonly check: Schema;
|
|
122
|
+
readonly extends: Schema;
|
|
123
|
+
readonly then: Schema;
|
|
124
|
+
readonly else: Schema;
|
|
125
|
+
readonly infer?: readonly string[];
|
|
126
|
+
} | {
|
|
127
|
+
readonly t: "intersection";
|
|
128
|
+
readonly of: readonly Schema[];
|
|
129
|
+
} | {
|
|
130
|
+
readonly t: "returnType";
|
|
131
|
+
readonly fn: Schema;
|
|
132
|
+
} | {
|
|
133
|
+
readonly t: "parameters";
|
|
134
|
+
readonly fn: Schema;
|
|
135
|
+
} | {
|
|
136
|
+
readonly t: "var";
|
|
137
|
+
readonly name: string;
|
|
138
|
+
readonly bound?: Schema;
|
|
139
|
+
readonly isConst?: boolean;
|
|
140
|
+
} | {
|
|
141
|
+
readonly t: "apply";
|
|
142
|
+
readonly name: string;
|
|
143
|
+
readonly args: readonly Schema[];
|
|
144
|
+
};
|
|
145
|
+
type AnySchema = Extract<Schema, {
|
|
146
|
+
t: "any";
|
|
147
|
+
}>;
|
|
148
|
+
type UnknownSchema = Extract<Schema, {
|
|
149
|
+
t: "unknown";
|
|
150
|
+
}>;
|
|
151
|
+
type LiteralSchema = Extract<Schema, {
|
|
152
|
+
t: "literal";
|
|
153
|
+
}>;
|
|
154
|
+
type ObjectSchema = Extract<Schema, {
|
|
155
|
+
t: "object";
|
|
156
|
+
}>;
|
|
157
|
+
type ArraySchema = Extract<Schema, {
|
|
158
|
+
t: "array";
|
|
159
|
+
}>;
|
|
160
|
+
type TupleSchema = Extract<Schema, {
|
|
161
|
+
t: "tuple";
|
|
162
|
+
}>;
|
|
163
|
+
type UnionSchema = Extract<Schema, {
|
|
164
|
+
t: "union";
|
|
165
|
+
}>;
|
|
166
|
+
type FnSchema = Extract<Schema, {
|
|
167
|
+
t: "fn";
|
|
168
|
+
}>;
|
|
169
|
+
type OverloadSchema = Extract<Schema, {
|
|
170
|
+
t: "overload";
|
|
171
|
+
}>;
|
|
172
|
+
type KeyofSchema = Extract<Schema, {
|
|
173
|
+
t: "keyof";
|
|
174
|
+
}>;
|
|
175
|
+
type IndexSchema = Extract<Schema, {
|
|
176
|
+
t: "index";
|
|
177
|
+
}>;
|
|
178
|
+
type MappedSchema = Extract<Schema, {
|
|
179
|
+
t: "mapped";
|
|
180
|
+
}>;
|
|
181
|
+
type VarSchema = Extract<Schema, {
|
|
182
|
+
t: "var";
|
|
183
|
+
}>;
|
|
184
|
+
type ApplySchema = Extract<Schema, {
|
|
185
|
+
t: "apply";
|
|
186
|
+
}>;
|
|
187
|
+
type ScalarSchema = Extract<Schema, {
|
|
188
|
+
t: "string" | "number" | "boolean" | "null" | "undefined";
|
|
189
|
+
}>;
|
|
190
|
+
/**
|
|
191
|
+
* Um *type scheme*: um tipo nomeado parametrizado, `type Pair<A, B> = body`.
|
|
192
|
+
* `params` são as variáveis de tipo (na ordem); `body` é o `Schema` que as usa
|
|
193
|
+
* via `var`. Um tipo nomeado não-genérico é só um scheme com `params: []`.
|
|
194
|
+
*/
|
|
195
|
+
interface TypeScheme {
|
|
196
|
+
readonly params: readonly string[];
|
|
197
|
+
readonly body: Schema;
|
|
198
|
+
}
|
|
199
|
+
/** Registro de type schemes por nome — consultado pela expansão (ver `expand`). */
|
|
200
|
+
type Schemes = Readonly<Record<string, TypeScheme>>;
|
|
201
|
+
declare const s: {
|
|
202
|
+
readonly any: Schema;
|
|
203
|
+
readonly unknown: Schema;
|
|
204
|
+
readonly string: Schema;
|
|
205
|
+
readonly number: Schema;
|
|
206
|
+
readonly boolean: Schema;
|
|
207
|
+
readonly null: Schema;
|
|
208
|
+
readonly undefined: Schema;
|
|
209
|
+
readonly void: Schema;
|
|
210
|
+
readonly literal: (value: string | number | boolean) => Schema;
|
|
211
|
+
readonly object: (props: Record<string, Prop>, index?: IndexSig) => Schema;
|
|
212
|
+
/** `Record<K, V>` — objeto só com assinatura de índice `{ [k: K]: V }`. */
|
|
213
|
+
readonly record: (value: Schema, key?: "string" | "number") => Schema;
|
|
214
|
+
readonly array: (items: Schema) => Schema;
|
|
215
|
+
/** Tupla fixa `[A, B]` — comprimento e posições conhecidos. */
|
|
216
|
+
readonly tuple: (elements: readonly Schema[], flags?: readonly ElementFlag[]) => Schema;
|
|
217
|
+
readonly fn: (params: Param[], returns: Schema) => Schema;
|
|
218
|
+
/** Type predicate `(…) => v is S` — fn que devolve `boolean` e estreita o param `i`. */
|
|
219
|
+
readonly guard: (params: Param[], type: Schema, param?: number) => Schema;
|
|
220
|
+
/**
|
|
221
|
+
* Overload: o mesmo valor com várias assinaturas de chamada (a 1ª que casa
|
|
222
|
+
* vence). Ex. Ramda `add`: `[(a,b)=>number, (a)=>(b)=>number]`.
|
|
223
|
+
*/
|
|
224
|
+
readonly overload: (signatures: FnSchema[]) => Schema;
|
|
225
|
+
/** `keyof T` — a união (de literais) das chaves de `T`. Resolve quando `T` é concreto. */
|
|
226
|
+
readonly keyof: (of: Schema) => Schema;
|
|
227
|
+
/** `T[K]` — acesso indexado. Resolve quando `T` é objeto/array e `K` é literal/união. */
|
|
228
|
+
readonly index: (obj: Schema, key: Schema) => Schema;
|
|
229
|
+
/** `{ [key in over]?: body }` — mapped type. Resolve quando `over` dá chaves literais. */
|
|
230
|
+
readonly mapped: (key: string, over: Schema, body: Schema, optional?: boolean) => Schema;
|
|
231
|
+
/** `check extends ext ? then : els` — conditional. `infer` = os nomes dos `infer U`
|
|
232
|
+
* introduzidos no `ext` (as posições são `var(U)`); resolve via `unify` (ver
|
|
233
|
+
* `resolveConditional`). Sem `infer` → conditional simples (discriminante concreto). */
|
|
234
|
+
readonly conditional: (check: Schema, ext: Schema, then: Schema, els: Schema, infer?: readonly string[]) => Schema;
|
|
235
|
+
/** `A & B` — interseção. Funde objetos concretos; lazy com `var`. */
|
|
236
|
+
readonly intersection: (of: readonly Schema[]) => Schema;
|
|
237
|
+
/** Açúcar para `A & B` (dois membros). */
|
|
238
|
+
readonly and: (a: Schema, b: Schema) => Schema;
|
|
239
|
+
/** `ReturnType<F>` — o retorno de uma `fn`. Resolve quando `F` é concreto. */
|
|
240
|
+
readonly returnType: (fn: Schema) => Schema;
|
|
241
|
+
readonly parameters: (fn: Schema) => Schema;
|
|
242
|
+
readonly var: (name: string, bound?: Schema, isConst?: boolean) => Schema;
|
|
243
|
+
/** Construtor de tipo aplicado: `apply("Map", [K, V])` ⇒ `Map<K, V>`. */
|
|
244
|
+
readonly apply: (name: string, args?: readonly Schema[]) => Schema;
|
|
245
|
+
/** Açúcar para `Promise<T>` — o que `await` desembrulha. */
|
|
246
|
+
readonly promise: (value: Schema) => Schema;
|
|
247
|
+
/**
|
|
248
|
+
* Constrói uma união achatando uniões aninhadas. Não deduplica nem colapsa
|
|
249
|
+
* união-de-um aqui (isso depende de igualdade estrutural — ver `normalizeUnion`
|
|
250
|
+
* quando `subtype` existir); apenas garante uma lista plana.
|
|
251
|
+
*/
|
|
252
|
+
readonly union: (of: readonly Schema[]) => Schema;
|
|
253
|
+
};
|
|
254
|
+
/** Resolve um `keyof`/`index` um nível quando possível; senão, devolve `t` como está. */
|
|
255
|
+
declare function resolveTypeOp(t: Schema): Schema;
|
|
256
|
+
declare const ownProp: (props: Readonly<Record<string, Prop>>, key: string) => Prop | undefined;
|
|
257
|
+
/**
|
|
258
|
+
* Separa `undefined` de um tipo: devolve o tipo **sem** `undefined` e se ele estava
|
|
259
|
+
* presente. Em posição de **propriedade**, `T | undefined` é uma propriedade
|
|
260
|
+
* **opcional** de tipo `T` — espelha o `JSON.stringify` (chave `undefined` some).
|
|
261
|
+
* Só mexe em `undefined`, nunca em `null` (que é valor JSON presente). Usado pelo
|
|
262
|
+
* `serializable` e pelo `toJsonSchema` (mesma regra dos dois lados).
|
|
263
|
+
*/
|
|
264
|
+
declare function withoutUndefined(t: Schema): {
|
|
265
|
+
type: Schema;
|
|
266
|
+
hadUndefined: boolean;
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
/** A flag do elemento `i` de uma tupla (ausente = `req`). */
|
|
270
|
+
declare const flagAt: (t: TupleSchema, i: number) => ElementFlag;
|
|
271
|
+
/** A tupla tem algum elemento `rest`/`variadic`? (senão é fixa, TC19; `optional` NÃO conta). */
|
|
272
|
+
declare const isVariadicTuple: (t: TupleSchema) => boolean;
|
|
273
|
+
/** O índice do (único) elemento `rest`/`variadic`, ou -1 (sem rest; `optional` é posicional). */
|
|
274
|
+
declare const restIndex: (t: TupleSchema) => number;
|
|
275
|
+
/**
|
|
276
|
+
* Normaliza uma tupla variadic (espelha `createNormalizedTupleType`): um elemento
|
|
277
|
+
* `variadic` cujo tipo é
|
|
278
|
+
* - uma TUPLA concreta → é espalhado (seus elementos + flags entram no lugar);
|
|
279
|
+
* - um ARRAY `T[]` → vira um `rest` de `T`;
|
|
280
|
+
* - `any` → vira `rest` de `any`;
|
|
281
|
+
* - uma var genérica (ou outro) → **fica** `variadic`.
|
|
282
|
+
* Assim, depois de normalizar, só var genérica permanece `variadic`. Reconstrói via
|
|
283
|
+
* `s.tuple` (que dropa `flags` se tudo virar `req` → tupla fixa de volta).
|
|
284
|
+
*/
|
|
285
|
+
declare function normalizeTuple(elements: readonly Schema[], flags: readonly ElementFlag[]): Schema;
|
|
286
|
+
/**
|
|
287
|
+
* Fatia o "miolo" de uma tupla/array entre um prefixo fixo (`start` elementos) e um
|
|
288
|
+
* sufixo fixo (`end` elementos) — o que sobra pro elemento `variadic`/`rest` na
|
|
289
|
+
* inferência (`[H, ...R]` contra `[A, B, C]` → R = `[B, C]`). Espelha o `sliceTupleType`
|
|
290
|
+
* do tsc. Para um array `T[]` o miolo é `T[]` (cauda aberta).
|
|
291
|
+
*/
|
|
292
|
+
declare function sliceTuple(source: Schema, start: number, end: number): Schema;
|
|
293
|
+
|
|
294
|
+
type IncompatibilityKind = "missing" | "type";
|
|
295
|
+
/** Um ponto de incompatibilidade entre `actual` e `expected`. */
|
|
296
|
+
interface Incompatibility {
|
|
297
|
+
/** Caminho até o ponto: `[]` = raiz, `["count"]`, `["user","name"]`. */
|
|
298
|
+
readonly path: readonly string[];
|
|
299
|
+
/** O tipo esperado naquele ponto. */
|
|
300
|
+
readonly expected: Schema;
|
|
301
|
+
/** O tipo que veio — ausente quando `kind === "missing"` (a prop não existe). */
|
|
302
|
+
readonly actual?: Schema;
|
|
303
|
+
readonly kind: IncompatibilityKind;
|
|
304
|
+
}
|
|
305
|
+
/** Renderiza um `typeDiff` numa frase legível (o feedback que brilha). Missing
|
|
306
|
+
* são AGREGADOS (como o tsc: "missing the following properties: a, b, c"). */
|
|
307
|
+
declare function formatTypeDiff(incs: readonly Incompatibility[]): string;
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* `typeDiff(a, b)` — POR QUE `a ⊄ b`: lista de incompatibilidades com caminho +
|
|
311
|
+
* razão (≅ a elaboração do tsc). É o `subtype` em **modo elaboração** (uma fonte de
|
|
312
|
+
* verdade, sem walk paralelo — a lição do `propertiesRelatedTo`). Caminho FRIO: roda
|
|
313
|
+
* só ao reportar; NÃO usa o relation cache. `[]` = compatível.
|
|
314
|
+
*/
|
|
315
|
+
declare function typeDiff(a: Schema, b: Schema, schemes?: Schemes): Incompatibility[];
|
|
316
|
+
/** `true` se um valor de tipo `a` pode ser usado onde se espera `b`. */
|
|
317
|
+
declare function subtype(a: Schema, b: Schema, schemes?: Schemes): boolean;
|
|
318
|
+
/** Igualdade estrutural: cada um é atribuível ao outro. */
|
|
319
|
+
declare function equals(a: Schema, b: Schema, schemes?: Schemes): boolean;
|
|
320
|
+
/**
|
|
321
|
+
* Normaliza uma união: achata, absorve `any`/`unknown`, deduplica e remove
|
|
322
|
+
* membros subsumidos por outro (`string | "x"` → `string`). Colapsa união de um
|
|
323
|
+
* membro no próprio membro. União vazia permanece vazia (renderiza `never`).
|
|
324
|
+
*/
|
|
325
|
+
declare function normalizeUnion(members: readonly Schema[]): Schema;
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Profundidade máxima de recursão na avaliação de tipo. Generoso p/ qualquer tipo
|
|
329
|
+
* real (dado nocode raramente passa de dezenas de níveis), baixo o suficiente p/
|
|
330
|
+
* abortar **antes** do stack overflow do V8. É o **default** — o profile pode
|
|
331
|
+
* apertar/afrouxar via {@link configureTypeLimits} (Proposal 003).
|
|
332
|
+
*/
|
|
333
|
+
declare const TYPE_EVAL_DEPTH_LIMIT = 1000;
|
|
334
|
+
/** Os tetos de avaliação de tipo (Proposal 003). `maxTypeDepth` ↔ TS2589;
|
|
335
|
+
* `maxUnionMembers` ↔ TS2590; `maxOverloadSignatures` p/ previsibilidade. */
|
|
336
|
+
interface TypeEvalLimits {
|
|
337
|
+
readonly maxTypeDepth: number;
|
|
338
|
+
readonly maxUnionMembers: number;
|
|
339
|
+
readonly maxOverloadSignatures: number;
|
|
340
|
+
}
|
|
341
|
+
/** Default standalone (quando o type-core roda sem profile — infer/jsonschema).
|
|
342
|
+
* Folgado de propósito: não deve disparar em uso normal. */
|
|
343
|
+
declare const DEFAULT_TYPE_LIMITS: TypeEvalLimits;
|
|
344
|
+
/** Configura os tetos globais (o checker chama no início de `check()` a partir do
|
|
345
|
+
* profile). Mescla sobre o default. Resetar com {@link resetTypeLimits} no finally. */
|
|
346
|
+
declare function configureTypeLimits(limits: Partial<TypeEvalLimits>): void;
|
|
347
|
+
/** Volta aos defaults (chamado no `finally` do consumidor). */
|
|
348
|
+
declare function resetTypeLimits(): void;
|
|
349
|
+
/** Os tetos ativos no momento (lido pela álgebra: `subtype`/`normalizeUnion`). */
|
|
350
|
+
declare function typeLimits(): TypeEvalLimits;
|
|
351
|
+
/** Lançado quando a avaliação de tipo excede a profundidade (`maxTypeDepth`). */
|
|
352
|
+
declare class TypeEvalLimitError extends Error {
|
|
353
|
+
constructor(depth?: number);
|
|
354
|
+
}
|
|
355
|
+
/** Lançado quando uma união excede `maxUnionMembers` (fiel ao TS2590 do tsc:
|
|
356
|
+
* "Expression produces a union type that is too complex to represent"). */
|
|
357
|
+
declare class UnionTooComplexError extends Error {
|
|
358
|
+
constructor(count: number, limit?: number);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** As features de tipo gateadas presentes em `schema` (recursivo, cycle-safe).
|
|
362
|
+
* `recursionName` (o nome do alias sendo autorado) liga a detecção de `recursion`. */
|
|
363
|
+
declare function typeFeatures(schema: Schema, recursionName?: string): Set<string>;
|
|
364
|
+
|
|
365
|
+
/** Ligações `nome da var → tipo` (o resultado de `unify`/aplicação de scheme). */
|
|
366
|
+
type Bindings = Readonly<Record<string, Schema>>;
|
|
367
|
+
/** Aplica `bindings` a `schema`, trocando cada `var` ligada pelo seu tipo. */
|
|
368
|
+
declare function substitute(schema: Schema, bindings: Bindings, seen?: WeakSet<object>): Schema;
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Liga as `var`s de `pattern` aos tipos correspondentes em `actual`. Devolve as
|
|
372
|
+
* ligações estendidas, ou `null` se forem incompatíveis. `actual` que seja
|
|
373
|
+
* `any`/`unknown` não constrange vars (deixa-as livres).
|
|
374
|
+
*/
|
|
375
|
+
declare function unify(pattern: Schema, actual: Schema, bindings?: Bindings): Bindings | null;
|
|
376
|
+
/** Resultado de instanciar uma assinatura contra argumentos. */
|
|
377
|
+
interface Instantiation {
|
|
378
|
+
readonly returns: Schema;
|
|
379
|
+
readonly bindings: Bindings;
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Instancia uma função genérica: unifica cada argumento contra o parâmetro
|
|
383
|
+
* correspondente (ligando as `var`s) e devolve o retorno já substituído.
|
|
384
|
+
* Falha (`null`) se algum argumento não unificar. Um parâmetro `variadic`
|
|
385
|
+
* absorve os argumentos restantes (cada um unifica contra o tipo do rest).
|
|
386
|
+
*/
|
|
387
|
+
declare function instantiate(sig: FnSchema, args: readonly Schema[]): Instantiation | null;
|
|
388
|
+
/**
|
|
389
|
+
* Versão tolerante de {@link instantiate} para o editor/checker: nunca falha —
|
|
390
|
+
* argumentos que não unificam são ignorados, e `var`s não ligadas permanecem
|
|
391
|
+
* (útil para aplicação parcial e enquanto o usuário ainda digita).
|
|
392
|
+
*/
|
|
393
|
+
declare function instantiateLoose(sig: FnSchema, args: readonly Schema[]): Instantiation;
|
|
394
|
+
/**
|
|
395
|
+
* Aterra as `var`s remanescentes em `unknown` (para exibição do resultado). Resolve
|
|
396
|
+
* de passagem um `conditional` cujo discriminante já é ground → o tipo do resultado
|
|
397
|
+
* sai concreto (ex.: `ReturnType<F>` aplicado vira o retorno real). `schemes` é
|
|
398
|
+
* preciso pra resolver conditionals que checam contra type aliases.
|
|
399
|
+
*/
|
|
400
|
+
declare function groundVars(schema: Schema, schemes?: Schemes, seen?: WeakSet<object>, depth0?: number): Schema;
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* O supremo estrutural de `a` e `b`: o menor `Schema` ao qual ambos são
|
|
404
|
+
* atribuíveis. `unknown` é a unidade (sem-evidência); `any` é absorvente.
|
|
405
|
+
*/
|
|
406
|
+
declare function join(a: Schema, b: Schema): Schema;
|
|
407
|
+
/**
|
|
408
|
+
* Dobra uma lista de formas no seu supremo comum. Lista vazia → `never` (⊥, a
|
|
409
|
+
* identidade do supremo). Um membro → ele mesmo. É a operação do schema-reducer:
|
|
410
|
+
* `joinAll(amostras.map(inferValue))` descreve todas as amostras.
|
|
411
|
+
*/
|
|
412
|
+
declare function joinAll(members: readonly Schema[]): Schema;
|
|
413
|
+
|
|
414
|
+
/** Há um scheme registrado para este `apply` (com aridade compatível)? */
|
|
415
|
+
declare function isScheme(t: Schema, schemes: Schemes): boolean;
|
|
416
|
+
/**
|
|
417
|
+
* Expande **um nível**: `apply(name, args)` com scheme registrado vira
|
|
418
|
+
* `substitute(body, { param_i → args_i })`. Qualquer outro tipo (ou `apply` opaco)
|
|
419
|
+
* é devolvido intacto.
|
|
420
|
+
*/
|
|
421
|
+
declare function expand1(t: Schema, schemes: Schemes): Schema;
|
|
422
|
+
|
|
423
|
+
/** Alarga um literal FRESH pra sua base; mantém não-fresh e não-literais. Raso —
|
|
424
|
+
* usado por elemento na CONSTRUÇÃO de array/object/tupla literal (no checker). */
|
|
425
|
+
declare function widen(t: Schema): Schema;
|
|
426
|
+
/**
|
|
427
|
+
* Widening TOTAL (`getWidenedType` do TS): alarga todo literal fresh, **inclusive
|
|
428
|
+
* o do topo**. É a regra do **retorno de função** (`() => 1` → `() => number`;
|
|
429
|
+
* `async () => 1` → `Promise<number>`). Literal não-fresh (keyof) é mantido.
|
|
430
|
+
*/
|
|
431
|
+
declare function widenType(t: Schema): Schema;
|
|
432
|
+
/**
|
|
433
|
+
* A regra de widening do TS para o RESULTADO (const / retorno de chamada): alarga
|
|
434
|
+
* literais fresh em posição de **membro** (aninhados), mas mantém um literal fresh
|
|
435
|
+
* no **topo**. `id(1)` → `1`; `wrap(1)` (`T[]`) → `number[]`; `keys` (`keyof T`) →
|
|
436
|
+
* mantém (não-fresh).
|
|
437
|
+
*/
|
|
438
|
+
declare function widenInferred(t: Schema): Schema;
|
|
439
|
+
|
|
440
|
+
/** Renderiza `schema` como uma string no estilo TypeScript. */
|
|
441
|
+
declare function format(schema: Schema, seen?: WeakSet<object>): string;
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* `true` quando `schema` descreve **dado puro** (sobrevive a `JSON.stringify`
|
|
445
|
+
* sem perda silenciosa). `fn` é o ponto-chave: uma função é dropada em silêncio
|
|
446
|
+
* pela serialização — por isso `false`.
|
|
447
|
+
*
|
|
448
|
+
* `apply` é **conservador** (`false`): sem registro de construtores-de-dado
|
|
449
|
+
* liberados, não dá pra garantir que `Foo<…>` (ou `Promise<T>`, `Map<K,V>`)
|
|
450
|
+
* vire JSON. `var` (forma desconhecida), `any`/`unknown` (sem garantia) → `false`.
|
|
451
|
+
*/
|
|
452
|
+
declare function isSerializable(schema: Schema, seen?: WeakSet<object>): boolean;
|
|
453
|
+
|
|
454
|
+
/** Um membro que pode seguir a partir de um tipo (item de autocomplete). */
|
|
455
|
+
interface Completion {
|
|
456
|
+
/** Nome da propriedade, ou `"[]"` para o elemento de um array. */
|
|
457
|
+
readonly key: string;
|
|
458
|
+
readonly type: Schema;
|
|
459
|
+
readonly optional: boolean;
|
|
460
|
+
}
|
|
461
|
+
/** Resultado de navegar um path: o tipo final + o que pode seguir dele. */
|
|
462
|
+
interface Discovery {
|
|
463
|
+
readonly type: Schema;
|
|
464
|
+
readonly completions: readonly Completion[];
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Navega `path` a partir de `schema`. Retorna o tipo alcançado e suas
|
|
468
|
+
* completions, ou `null` se algum segmento não existir no tipo. Path vazio
|
|
469
|
+
* devolve o próprio tipo e suas completions.
|
|
470
|
+
*/
|
|
471
|
+
declare function discover(schema: Schema, path: readonly string[], schemes?: Schemes): Discovery | null;
|
|
472
|
+
|
|
473
|
+
export { type AnySchema, type ApplySchema, type ArraySchema, type Bindings, type Completion, DEFAULT_TYPE_LIMITS, type Discovery, type ElementFlag, type FnSchema, type GuardSig, type Incompatibility, type IncompatibilityKind, type IndexSchema, type Instantiation, type KeyofSchema, type LiteralSchema, type MappedSchema, type ObjectSchema, type OverloadSchema, type Param, type Prop, type ScalarSchema, type Schema, type Schemes, TYPE_EVAL_DEPTH_LIMIT, type TupleSchema, TypeEvalLimitError, type TypeEvalLimits, type TypeScheme, type UnionSchema, UnionTooComplexError, type UnknownSchema, type VarSchema, configureTypeLimits, discover, equals, expand1, flagAt, format, formatTypeDiff, groundVars, instantiate, instantiateLoose, isScheme, isSerializable, isVariadicTuple, join, joinAll, normalizeTuple, normalizeUnion, ownProp, resetTypeLimits, resolveTypeOp, restIndex, s, sliceTuple, substitute, subtype, typeDiff, typeFeatures, typeLimits, unify, widen, widenInferred, widenType, withoutUndefined };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
/** Uma propriedade de um tipo objeto. */
|
|
2
|
+
interface Prop {
|
|
3
|
+
readonly type: Schema;
|
|
4
|
+
/** `true` quando a propriedade pode estar ausente (`{ x?: T }`). */
|
|
5
|
+
readonly optional?: boolean;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Assinatura de índice de um objeto — `{ [k: string]: V }` (a forma de `Record<K, V>`).
|
|
9
|
+
* Coexiste com props nomeadas (`{ a: number; [k: string]: unknown }`), como no TS.
|
|
10
|
+
* O domínio da chave é só `string`/`number` (o que o TS permite).
|
|
11
|
+
*/
|
|
12
|
+
interface IndexSig {
|
|
13
|
+
readonly key: "string" | "number";
|
|
14
|
+
readonly value: Schema;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Flag de um elemento de tupla (espelha o `ElementFlags` do tsc):
|
|
18
|
+
* - `req` — elemento posicional normal (`A` em `[A, B]`);
|
|
19
|
+
* - `optional` — `A?` (pode estar ausente; `[A, B?]`); só TRAILING, posicional;
|
|
20
|
+
* - `rest` — `...T[]` (cauda de array); o tipo do elemento é o do array;
|
|
21
|
+
* - `variadic` — `...T` (spread de uma tupla/var); após `normalizeTuple` só var
|
|
22
|
+
* genérica fica `variadic` (tupla concreta é espalhada; array vira `rest`).
|
|
23
|
+
*/
|
|
24
|
+
type ElementFlag = "req" | "optional" | "rest" | "variadic";
|
|
25
|
+
/** Um parâmetro de um tipo função. */
|
|
26
|
+
interface Param {
|
|
27
|
+
readonly name: string;
|
|
28
|
+
readonly type: Schema;
|
|
29
|
+
/** `true` quando o argumento pode ser omitido. */
|
|
30
|
+
readonly optional?: boolean;
|
|
31
|
+
/** `true` para o parâmetro rest (`...args: T[]`). */
|
|
32
|
+
readonly variadic?: boolean;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Type predicate `(v) => v is S` — quando a fn devolve `true`, o argumento na
|
|
36
|
+
* posição `param` é estreitado para `type` (S). `returns` da fn continua `boolean`
|
|
37
|
+
* (é o que roda); o `guard` é a info de narrowing. `filter`/`find` inferem S dele;
|
|
38
|
+
* `if (g(x))` estreita `x` (D13). Covariante em `type`.
|
|
39
|
+
*/
|
|
40
|
+
interface GuardSig {
|
|
41
|
+
readonly param: number;
|
|
42
|
+
readonly type: Schema;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* O tipo de um valor na linguagem TSLite.
|
|
46
|
+
*
|
|
47
|
+
* O discriminador é `t`. Estruturas (object/array/union/fn) referenciam outros
|
|
48
|
+
* `Schema` recursivamente — inclusive de forma cíclica (ex.: `Node` que contém
|
|
49
|
+
* `Node[]`); as operações que percorrem `Schema` são cycle-safe.
|
|
50
|
+
*/
|
|
51
|
+
type Schema = {
|
|
52
|
+
readonly t: "any";
|
|
53
|
+
} | {
|
|
54
|
+
readonly t: "unknown";
|
|
55
|
+
} | {
|
|
56
|
+
readonly t: "string";
|
|
57
|
+
} | {
|
|
58
|
+
readonly t: "number";
|
|
59
|
+
} | {
|
|
60
|
+
readonly t: "boolean";
|
|
61
|
+
} | {
|
|
62
|
+
readonly t: "null";
|
|
63
|
+
} | {
|
|
64
|
+
readonly t: "undefined";
|
|
65
|
+
} | {
|
|
66
|
+
readonly t: "void";
|
|
67
|
+
} | {
|
|
68
|
+
readonly t: "literal";
|
|
69
|
+
readonly value: string | number | boolean;
|
|
70
|
+
/**
|
|
71
|
+
* `fresh` = literal "fresco" de uma EXPRESSÃO de valor (`1`, `"x"`) — alarga
|
|
72
|
+
* pra base em posição de membro (array/object/tupla) ou inferido num `T[]`,
|
|
73
|
+
* mas preserva no topo (`const x = 1` → `1`; `id(1)` → `1`). Literal de
|
|
74
|
+
* `keyof`/declarado é NÃO-fresh → nunca alarga. Transparente p/ subtype/equals.
|
|
75
|
+
*/
|
|
76
|
+
readonly fresh?: boolean;
|
|
77
|
+
} | {
|
|
78
|
+
readonly t: "object";
|
|
79
|
+
readonly props: Readonly<Record<string, Prop>>;
|
|
80
|
+
/** Assinatura de índice (`Record<K, V>`); coexiste com `props`. Ausente = objeto fechado. */
|
|
81
|
+
readonly index?: IndexSig;
|
|
82
|
+
} | {
|
|
83
|
+
readonly t: "array";
|
|
84
|
+
readonly items: Schema;
|
|
85
|
+
} | {
|
|
86
|
+
readonly t: "tuple";
|
|
87
|
+
readonly elements: readonly Schema[];
|
|
88
|
+
readonly flags?: readonly ElementFlag[];
|
|
89
|
+
} | {
|
|
90
|
+
readonly t: "union";
|
|
91
|
+
readonly of: readonly Schema[];
|
|
92
|
+
} | {
|
|
93
|
+
readonly t: "fn";
|
|
94
|
+
readonly params: readonly Param[];
|
|
95
|
+
readonly returns: Schema;
|
|
96
|
+
/** Type predicate `(v) => v is S` — narrowing (ver `GuardSig`). */
|
|
97
|
+
readonly guard?: GuardSig;
|
|
98
|
+
} | {
|
|
99
|
+
readonly t: "overload";
|
|
100
|
+
readonly signatures: readonly {
|
|
101
|
+
readonly t: "fn";
|
|
102
|
+
readonly params: readonly Param[];
|
|
103
|
+
readonly returns: Schema;
|
|
104
|
+
readonly guard?: GuardSig;
|
|
105
|
+
}[];
|
|
106
|
+
} | {
|
|
107
|
+
readonly t: "keyof";
|
|
108
|
+
readonly of: Schema;
|
|
109
|
+
} | {
|
|
110
|
+
readonly t: "index";
|
|
111
|
+
readonly obj: Schema;
|
|
112
|
+
readonly key: Schema;
|
|
113
|
+
} | {
|
|
114
|
+
readonly t: "mapped";
|
|
115
|
+
readonly key: string;
|
|
116
|
+
readonly over: Schema;
|
|
117
|
+
readonly body: Schema;
|
|
118
|
+
readonly optional?: boolean;
|
|
119
|
+
} | {
|
|
120
|
+
readonly t: "conditional";
|
|
121
|
+
readonly check: Schema;
|
|
122
|
+
readonly extends: Schema;
|
|
123
|
+
readonly then: Schema;
|
|
124
|
+
readonly else: Schema;
|
|
125
|
+
readonly infer?: readonly string[];
|
|
126
|
+
} | {
|
|
127
|
+
readonly t: "intersection";
|
|
128
|
+
readonly of: readonly Schema[];
|
|
129
|
+
} | {
|
|
130
|
+
readonly t: "returnType";
|
|
131
|
+
readonly fn: Schema;
|
|
132
|
+
} | {
|
|
133
|
+
readonly t: "parameters";
|
|
134
|
+
readonly fn: Schema;
|
|
135
|
+
} | {
|
|
136
|
+
readonly t: "var";
|
|
137
|
+
readonly name: string;
|
|
138
|
+
readonly bound?: Schema;
|
|
139
|
+
readonly isConst?: boolean;
|
|
140
|
+
} | {
|
|
141
|
+
readonly t: "apply";
|
|
142
|
+
readonly name: string;
|
|
143
|
+
readonly args: readonly Schema[];
|
|
144
|
+
};
|
|
145
|
+
type AnySchema = Extract<Schema, {
|
|
146
|
+
t: "any";
|
|
147
|
+
}>;
|
|
148
|
+
type UnknownSchema = Extract<Schema, {
|
|
149
|
+
t: "unknown";
|
|
150
|
+
}>;
|
|
151
|
+
type LiteralSchema = Extract<Schema, {
|
|
152
|
+
t: "literal";
|
|
153
|
+
}>;
|
|
154
|
+
type ObjectSchema = Extract<Schema, {
|
|
155
|
+
t: "object";
|
|
156
|
+
}>;
|
|
157
|
+
type ArraySchema = Extract<Schema, {
|
|
158
|
+
t: "array";
|
|
159
|
+
}>;
|
|
160
|
+
type TupleSchema = Extract<Schema, {
|
|
161
|
+
t: "tuple";
|
|
162
|
+
}>;
|
|
163
|
+
type UnionSchema = Extract<Schema, {
|
|
164
|
+
t: "union";
|
|
165
|
+
}>;
|
|
166
|
+
type FnSchema = Extract<Schema, {
|
|
167
|
+
t: "fn";
|
|
168
|
+
}>;
|
|
169
|
+
type OverloadSchema = Extract<Schema, {
|
|
170
|
+
t: "overload";
|
|
171
|
+
}>;
|
|
172
|
+
type KeyofSchema = Extract<Schema, {
|
|
173
|
+
t: "keyof";
|
|
174
|
+
}>;
|
|
175
|
+
type IndexSchema = Extract<Schema, {
|
|
176
|
+
t: "index";
|
|
177
|
+
}>;
|
|
178
|
+
type MappedSchema = Extract<Schema, {
|
|
179
|
+
t: "mapped";
|
|
180
|
+
}>;
|
|
181
|
+
type VarSchema = Extract<Schema, {
|
|
182
|
+
t: "var";
|
|
183
|
+
}>;
|
|
184
|
+
type ApplySchema = Extract<Schema, {
|
|
185
|
+
t: "apply";
|
|
186
|
+
}>;
|
|
187
|
+
type ScalarSchema = Extract<Schema, {
|
|
188
|
+
t: "string" | "number" | "boolean" | "null" | "undefined";
|
|
189
|
+
}>;
|
|
190
|
+
/**
|
|
191
|
+
* Um *type scheme*: um tipo nomeado parametrizado, `type Pair<A, B> = body`.
|
|
192
|
+
* `params` são as variáveis de tipo (na ordem); `body` é o `Schema` que as usa
|
|
193
|
+
* via `var`. Um tipo nomeado não-genérico é só um scheme com `params: []`.
|
|
194
|
+
*/
|
|
195
|
+
interface TypeScheme {
|
|
196
|
+
readonly params: readonly string[];
|
|
197
|
+
readonly body: Schema;
|
|
198
|
+
}
|
|
199
|
+
/** Registro de type schemes por nome — consultado pela expansão (ver `expand`). */
|
|
200
|
+
type Schemes = Readonly<Record<string, TypeScheme>>;
|
|
201
|
+
declare const s: {
|
|
202
|
+
readonly any: Schema;
|
|
203
|
+
readonly unknown: Schema;
|
|
204
|
+
readonly string: Schema;
|
|
205
|
+
readonly number: Schema;
|
|
206
|
+
readonly boolean: Schema;
|
|
207
|
+
readonly null: Schema;
|
|
208
|
+
readonly undefined: Schema;
|
|
209
|
+
readonly void: Schema;
|
|
210
|
+
readonly literal: (value: string | number | boolean) => Schema;
|
|
211
|
+
readonly object: (props: Record<string, Prop>, index?: IndexSig) => Schema;
|
|
212
|
+
/** `Record<K, V>` — objeto só com assinatura de índice `{ [k: K]: V }`. */
|
|
213
|
+
readonly record: (value: Schema, key?: "string" | "number") => Schema;
|
|
214
|
+
readonly array: (items: Schema) => Schema;
|
|
215
|
+
/** Tupla fixa `[A, B]` — comprimento e posições conhecidos. */
|
|
216
|
+
readonly tuple: (elements: readonly Schema[], flags?: readonly ElementFlag[]) => Schema;
|
|
217
|
+
readonly fn: (params: Param[], returns: Schema) => Schema;
|
|
218
|
+
/** Type predicate `(…) => v is S` — fn que devolve `boolean` e estreita o param `i`. */
|
|
219
|
+
readonly guard: (params: Param[], type: Schema, param?: number) => Schema;
|
|
220
|
+
/**
|
|
221
|
+
* Overload: o mesmo valor com várias assinaturas de chamada (a 1ª que casa
|
|
222
|
+
* vence). Ex. Ramda `add`: `[(a,b)=>number, (a)=>(b)=>number]`.
|
|
223
|
+
*/
|
|
224
|
+
readonly overload: (signatures: FnSchema[]) => Schema;
|
|
225
|
+
/** `keyof T` — a união (de literais) das chaves de `T`. Resolve quando `T` é concreto. */
|
|
226
|
+
readonly keyof: (of: Schema) => Schema;
|
|
227
|
+
/** `T[K]` — acesso indexado. Resolve quando `T` é objeto/array e `K` é literal/união. */
|
|
228
|
+
readonly index: (obj: Schema, key: Schema) => Schema;
|
|
229
|
+
/** `{ [key in over]?: body }` — mapped type. Resolve quando `over` dá chaves literais. */
|
|
230
|
+
readonly mapped: (key: string, over: Schema, body: Schema, optional?: boolean) => Schema;
|
|
231
|
+
/** `check extends ext ? then : els` — conditional. `infer` = os nomes dos `infer U`
|
|
232
|
+
* introduzidos no `ext` (as posições são `var(U)`); resolve via `unify` (ver
|
|
233
|
+
* `resolveConditional`). Sem `infer` → conditional simples (discriminante concreto). */
|
|
234
|
+
readonly conditional: (check: Schema, ext: Schema, then: Schema, els: Schema, infer?: readonly string[]) => Schema;
|
|
235
|
+
/** `A & B` — interseção. Funde objetos concretos; lazy com `var`. */
|
|
236
|
+
readonly intersection: (of: readonly Schema[]) => Schema;
|
|
237
|
+
/** Açúcar para `A & B` (dois membros). */
|
|
238
|
+
readonly and: (a: Schema, b: Schema) => Schema;
|
|
239
|
+
/** `ReturnType<F>` — o retorno de uma `fn`. Resolve quando `F` é concreto. */
|
|
240
|
+
readonly returnType: (fn: Schema) => Schema;
|
|
241
|
+
readonly parameters: (fn: Schema) => Schema;
|
|
242
|
+
readonly var: (name: string, bound?: Schema, isConst?: boolean) => Schema;
|
|
243
|
+
/** Construtor de tipo aplicado: `apply("Map", [K, V])` ⇒ `Map<K, V>`. */
|
|
244
|
+
readonly apply: (name: string, args?: readonly Schema[]) => Schema;
|
|
245
|
+
/** Açúcar para `Promise<T>` — o que `await` desembrulha. */
|
|
246
|
+
readonly promise: (value: Schema) => Schema;
|
|
247
|
+
/**
|
|
248
|
+
* Constrói uma união achatando uniões aninhadas. Não deduplica nem colapsa
|
|
249
|
+
* união-de-um aqui (isso depende de igualdade estrutural — ver `normalizeUnion`
|
|
250
|
+
* quando `subtype` existir); apenas garante uma lista plana.
|
|
251
|
+
*/
|
|
252
|
+
readonly union: (of: readonly Schema[]) => Schema;
|
|
253
|
+
};
|
|
254
|
+
/** Resolve um `keyof`/`index` um nível quando possível; senão, devolve `t` como está. */
|
|
255
|
+
declare function resolveTypeOp(t: Schema): Schema;
|
|
256
|
+
declare const ownProp: (props: Readonly<Record<string, Prop>>, key: string) => Prop | undefined;
|
|
257
|
+
/**
|
|
258
|
+
* Separa `undefined` de um tipo: devolve o tipo **sem** `undefined` e se ele estava
|
|
259
|
+
* presente. Em posição de **propriedade**, `T | undefined` é uma propriedade
|
|
260
|
+
* **opcional** de tipo `T` — espelha o `JSON.stringify` (chave `undefined` some).
|
|
261
|
+
* Só mexe em `undefined`, nunca em `null` (que é valor JSON presente). Usado pelo
|
|
262
|
+
* `serializable` e pelo `toJsonSchema` (mesma regra dos dois lados).
|
|
263
|
+
*/
|
|
264
|
+
declare function withoutUndefined(t: Schema): {
|
|
265
|
+
type: Schema;
|
|
266
|
+
hadUndefined: boolean;
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
/** A flag do elemento `i` de uma tupla (ausente = `req`). */
|
|
270
|
+
declare const flagAt: (t: TupleSchema, i: number) => ElementFlag;
|
|
271
|
+
/** A tupla tem algum elemento `rest`/`variadic`? (senão é fixa, TC19; `optional` NÃO conta). */
|
|
272
|
+
declare const isVariadicTuple: (t: TupleSchema) => boolean;
|
|
273
|
+
/** O índice do (único) elemento `rest`/`variadic`, ou -1 (sem rest; `optional` é posicional). */
|
|
274
|
+
declare const restIndex: (t: TupleSchema) => number;
|
|
275
|
+
/**
|
|
276
|
+
* Normaliza uma tupla variadic (espelha `createNormalizedTupleType`): um elemento
|
|
277
|
+
* `variadic` cujo tipo é
|
|
278
|
+
* - uma TUPLA concreta → é espalhado (seus elementos + flags entram no lugar);
|
|
279
|
+
* - um ARRAY `T[]` → vira um `rest` de `T`;
|
|
280
|
+
* - `any` → vira `rest` de `any`;
|
|
281
|
+
* - uma var genérica (ou outro) → **fica** `variadic`.
|
|
282
|
+
* Assim, depois de normalizar, só var genérica permanece `variadic`. Reconstrói via
|
|
283
|
+
* `s.tuple` (que dropa `flags` se tudo virar `req` → tupla fixa de volta).
|
|
284
|
+
*/
|
|
285
|
+
declare function normalizeTuple(elements: readonly Schema[], flags: readonly ElementFlag[]): Schema;
|
|
286
|
+
/**
|
|
287
|
+
* Fatia o "miolo" de uma tupla/array entre um prefixo fixo (`start` elementos) e um
|
|
288
|
+
* sufixo fixo (`end` elementos) — o que sobra pro elemento `variadic`/`rest` na
|
|
289
|
+
* inferência (`[H, ...R]` contra `[A, B, C]` → R = `[B, C]`). Espelha o `sliceTupleType`
|
|
290
|
+
* do tsc. Para um array `T[]` o miolo é `T[]` (cauda aberta).
|
|
291
|
+
*/
|
|
292
|
+
declare function sliceTuple(source: Schema, start: number, end: number): Schema;
|
|
293
|
+
|
|
294
|
+
type IncompatibilityKind = "missing" | "type";
|
|
295
|
+
/** Um ponto de incompatibilidade entre `actual` e `expected`. */
|
|
296
|
+
interface Incompatibility {
|
|
297
|
+
/** Caminho até o ponto: `[]` = raiz, `["count"]`, `["user","name"]`. */
|
|
298
|
+
readonly path: readonly string[];
|
|
299
|
+
/** O tipo esperado naquele ponto. */
|
|
300
|
+
readonly expected: Schema;
|
|
301
|
+
/** O tipo que veio — ausente quando `kind === "missing"` (a prop não existe). */
|
|
302
|
+
readonly actual?: Schema;
|
|
303
|
+
readonly kind: IncompatibilityKind;
|
|
304
|
+
}
|
|
305
|
+
/** Renderiza um `typeDiff` numa frase legível (o feedback que brilha). Missing
|
|
306
|
+
* são AGREGADOS (como o tsc: "missing the following properties: a, b, c"). */
|
|
307
|
+
declare function formatTypeDiff(incs: readonly Incompatibility[]): string;
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* `typeDiff(a, b)` — POR QUE `a ⊄ b`: lista de incompatibilidades com caminho +
|
|
311
|
+
* razão (≅ a elaboração do tsc). É o `subtype` em **modo elaboração** (uma fonte de
|
|
312
|
+
* verdade, sem walk paralelo — a lição do `propertiesRelatedTo`). Caminho FRIO: roda
|
|
313
|
+
* só ao reportar; NÃO usa o relation cache. `[]` = compatível.
|
|
314
|
+
*/
|
|
315
|
+
declare function typeDiff(a: Schema, b: Schema, schemes?: Schemes): Incompatibility[];
|
|
316
|
+
/** `true` se um valor de tipo `a` pode ser usado onde se espera `b`. */
|
|
317
|
+
declare function subtype(a: Schema, b: Schema, schemes?: Schemes): boolean;
|
|
318
|
+
/** Igualdade estrutural: cada um é atribuível ao outro. */
|
|
319
|
+
declare function equals(a: Schema, b: Schema, schemes?: Schemes): boolean;
|
|
320
|
+
/**
|
|
321
|
+
* Normaliza uma união: achata, absorve `any`/`unknown`, deduplica e remove
|
|
322
|
+
* membros subsumidos por outro (`string | "x"` → `string`). Colapsa união de um
|
|
323
|
+
* membro no próprio membro. União vazia permanece vazia (renderiza `never`).
|
|
324
|
+
*/
|
|
325
|
+
declare function normalizeUnion(members: readonly Schema[]): Schema;
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Profundidade máxima de recursão na avaliação de tipo. Generoso p/ qualquer tipo
|
|
329
|
+
* real (dado nocode raramente passa de dezenas de níveis), baixo o suficiente p/
|
|
330
|
+
* abortar **antes** do stack overflow do V8. É o **default** — o profile pode
|
|
331
|
+
* apertar/afrouxar via {@link configureTypeLimits} (Proposal 003).
|
|
332
|
+
*/
|
|
333
|
+
declare const TYPE_EVAL_DEPTH_LIMIT = 1000;
|
|
334
|
+
/** Os tetos de avaliação de tipo (Proposal 003). `maxTypeDepth` ↔ TS2589;
|
|
335
|
+
* `maxUnionMembers` ↔ TS2590; `maxOverloadSignatures` p/ previsibilidade. */
|
|
336
|
+
interface TypeEvalLimits {
|
|
337
|
+
readonly maxTypeDepth: number;
|
|
338
|
+
readonly maxUnionMembers: number;
|
|
339
|
+
readonly maxOverloadSignatures: number;
|
|
340
|
+
}
|
|
341
|
+
/** Default standalone (quando o type-core roda sem profile — infer/jsonschema).
|
|
342
|
+
* Folgado de propósito: não deve disparar em uso normal. */
|
|
343
|
+
declare const DEFAULT_TYPE_LIMITS: TypeEvalLimits;
|
|
344
|
+
/** Configura os tetos globais (o checker chama no início de `check()` a partir do
|
|
345
|
+
* profile). Mescla sobre o default. Resetar com {@link resetTypeLimits} no finally. */
|
|
346
|
+
declare function configureTypeLimits(limits: Partial<TypeEvalLimits>): void;
|
|
347
|
+
/** Volta aos defaults (chamado no `finally` do consumidor). */
|
|
348
|
+
declare function resetTypeLimits(): void;
|
|
349
|
+
/** Os tetos ativos no momento (lido pela álgebra: `subtype`/`normalizeUnion`). */
|
|
350
|
+
declare function typeLimits(): TypeEvalLimits;
|
|
351
|
+
/** Lançado quando a avaliação de tipo excede a profundidade (`maxTypeDepth`). */
|
|
352
|
+
declare class TypeEvalLimitError extends Error {
|
|
353
|
+
constructor(depth?: number);
|
|
354
|
+
}
|
|
355
|
+
/** Lançado quando uma união excede `maxUnionMembers` (fiel ao TS2590 do tsc:
|
|
356
|
+
* "Expression produces a union type that is too complex to represent"). */
|
|
357
|
+
declare class UnionTooComplexError extends Error {
|
|
358
|
+
constructor(count: number, limit?: number);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** As features de tipo gateadas presentes em `schema` (recursivo, cycle-safe).
|
|
362
|
+
* `recursionName` (o nome do alias sendo autorado) liga a detecção de `recursion`. */
|
|
363
|
+
declare function typeFeatures(schema: Schema, recursionName?: string): Set<string>;
|
|
364
|
+
|
|
365
|
+
/** Ligações `nome da var → tipo` (o resultado de `unify`/aplicação de scheme). */
|
|
366
|
+
type Bindings = Readonly<Record<string, Schema>>;
|
|
367
|
+
/** Aplica `bindings` a `schema`, trocando cada `var` ligada pelo seu tipo. */
|
|
368
|
+
declare function substitute(schema: Schema, bindings: Bindings, seen?: WeakSet<object>): Schema;
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Liga as `var`s de `pattern` aos tipos correspondentes em `actual`. Devolve as
|
|
372
|
+
* ligações estendidas, ou `null` se forem incompatíveis. `actual` que seja
|
|
373
|
+
* `any`/`unknown` não constrange vars (deixa-as livres).
|
|
374
|
+
*/
|
|
375
|
+
declare function unify(pattern: Schema, actual: Schema, bindings?: Bindings): Bindings | null;
|
|
376
|
+
/** Resultado de instanciar uma assinatura contra argumentos. */
|
|
377
|
+
interface Instantiation {
|
|
378
|
+
readonly returns: Schema;
|
|
379
|
+
readonly bindings: Bindings;
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Instancia uma função genérica: unifica cada argumento contra o parâmetro
|
|
383
|
+
* correspondente (ligando as `var`s) e devolve o retorno já substituído.
|
|
384
|
+
* Falha (`null`) se algum argumento não unificar. Um parâmetro `variadic`
|
|
385
|
+
* absorve os argumentos restantes (cada um unifica contra o tipo do rest).
|
|
386
|
+
*/
|
|
387
|
+
declare function instantiate(sig: FnSchema, args: readonly Schema[]): Instantiation | null;
|
|
388
|
+
/**
|
|
389
|
+
* Versão tolerante de {@link instantiate} para o editor/checker: nunca falha —
|
|
390
|
+
* argumentos que não unificam são ignorados, e `var`s não ligadas permanecem
|
|
391
|
+
* (útil para aplicação parcial e enquanto o usuário ainda digita).
|
|
392
|
+
*/
|
|
393
|
+
declare function instantiateLoose(sig: FnSchema, args: readonly Schema[]): Instantiation;
|
|
394
|
+
/**
|
|
395
|
+
* Aterra as `var`s remanescentes em `unknown` (para exibição do resultado). Resolve
|
|
396
|
+
* de passagem um `conditional` cujo discriminante já é ground → o tipo do resultado
|
|
397
|
+
* sai concreto (ex.: `ReturnType<F>` aplicado vira o retorno real). `schemes` é
|
|
398
|
+
* preciso pra resolver conditionals que checam contra type aliases.
|
|
399
|
+
*/
|
|
400
|
+
declare function groundVars(schema: Schema, schemes?: Schemes, seen?: WeakSet<object>, depth0?: number): Schema;
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* O supremo estrutural de `a` e `b`: o menor `Schema` ao qual ambos são
|
|
404
|
+
* atribuíveis. `unknown` é a unidade (sem-evidência); `any` é absorvente.
|
|
405
|
+
*/
|
|
406
|
+
declare function join(a: Schema, b: Schema): Schema;
|
|
407
|
+
/**
|
|
408
|
+
* Dobra uma lista de formas no seu supremo comum. Lista vazia → `never` (⊥, a
|
|
409
|
+
* identidade do supremo). Um membro → ele mesmo. É a operação do schema-reducer:
|
|
410
|
+
* `joinAll(amostras.map(inferValue))` descreve todas as amostras.
|
|
411
|
+
*/
|
|
412
|
+
declare function joinAll(members: readonly Schema[]): Schema;
|
|
413
|
+
|
|
414
|
+
/** Há um scheme registrado para este `apply` (com aridade compatível)? */
|
|
415
|
+
declare function isScheme(t: Schema, schemes: Schemes): boolean;
|
|
416
|
+
/**
|
|
417
|
+
* Expande **um nível**: `apply(name, args)` com scheme registrado vira
|
|
418
|
+
* `substitute(body, { param_i → args_i })`. Qualquer outro tipo (ou `apply` opaco)
|
|
419
|
+
* é devolvido intacto.
|
|
420
|
+
*/
|
|
421
|
+
declare function expand1(t: Schema, schemes: Schemes): Schema;
|
|
422
|
+
|
|
423
|
+
/** Alarga um literal FRESH pra sua base; mantém não-fresh e não-literais. Raso —
|
|
424
|
+
* usado por elemento na CONSTRUÇÃO de array/object/tupla literal (no checker). */
|
|
425
|
+
declare function widen(t: Schema): Schema;
|
|
426
|
+
/**
|
|
427
|
+
* Widening TOTAL (`getWidenedType` do TS): alarga todo literal fresh, **inclusive
|
|
428
|
+
* o do topo**. É a regra do **retorno de função** (`() => 1` → `() => number`;
|
|
429
|
+
* `async () => 1` → `Promise<number>`). Literal não-fresh (keyof) é mantido.
|
|
430
|
+
*/
|
|
431
|
+
declare function widenType(t: Schema): Schema;
|
|
432
|
+
/**
|
|
433
|
+
* A regra de widening do TS para o RESULTADO (const / retorno de chamada): alarga
|
|
434
|
+
* literais fresh em posição de **membro** (aninhados), mas mantém um literal fresh
|
|
435
|
+
* no **topo**. `id(1)` → `1`; `wrap(1)` (`T[]`) → `number[]`; `keys` (`keyof T`) →
|
|
436
|
+
* mantém (não-fresh).
|
|
437
|
+
*/
|
|
438
|
+
declare function widenInferred(t: Schema): Schema;
|
|
439
|
+
|
|
440
|
+
/** Renderiza `schema` como uma string no estilo TypeScript. */
|
|
441
|
+
declare function format(schema: Schema, seen?: WeakSet<object>): string;
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* `true` quando `schema` descreve **dado puro** (sobrevive a `JSON.stringify`
|
|
445
|
+
* sem perda silenciosa). `fn` é o ponto-chave: uma função é dropada em silêncio
|
|
446
|
+
* pela serialização — por isso `false`.
|
|
447
|
+
*
|
|
448
|
+
* `apply` é **conservador** (`false`): sem registro de construtores-de-dado
|
|
449
|
+
* liberados, não dá pra garantir que `Foo<…>` (ou `Promise<T>`, `Map<K,V>`)
|
|
450
|
+
* vire JSON. `var` (forma desconhecida), `any`/`unknown` (sem garantia) → `false`.
|
|
451
|
+
*/
|
|
452
|
+
declare function isSerializable(schema: Schema, seen?: WeakSet<object>): boolean;
|
|
453
|
+
|
|
454
|
+
/** Um membro que pode seguir a partir de um tipo (item de autocomplete). */
|
|
455
|
+
interface Completion {
|
|
456
|
+
/** Nome da propriedade, ou `"[]"` para o elemento de um array. */
|
|
457
|
+
readonly key: string;
|
|
458
|
+
readonly type: Schema;
|
|
459
|
+
readonly optional: boolean;
|
|
460
|
+
}
|
|
461
|
+
/** Resultado de navegar um path: o tipo final + o que pode seguir dele. */
|
|
462
|
+
interface Discovery {
|
|
463
|
+
readonly type: Schema;
|
|
464
|
+
readonly completions: readonly Completion[];
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Navega `path` a partir de `schema`. Retorna o tipo alcançado e suas
|
|
468
|
+
* completions, ou `null` se algum segmento não existir no tipo. Path vazio
|
|
469
|
+
* devolve o próprio tipo e suas completions.
|
|
470
|
+
*/
|
|
471
|
+
declare function discover(schema: Schema, path: readonly string[], schemes?: Schemes): Discovery | null;
|
|
472
|
+
|
|
473
|
+
export { type AnySchema, type ApplySchema, type ArraySchema, type Bindings, type Completion, DEFAULT_TYPE_LIMITS, type Discovery, type ElementFlag, type FnSchema, type GuardSig, type Incompatibility, type IncompatibilityKind, type IndexSchema, type Instantiation, type KeyofSchema, type LiteralSchema, type MappedSchema, type ObjectSchema, type OverloadSchema, type Param, type Prop, type ScalarSchema, type Schema, type Schemes, TYPE_EVAL_DEPTH_LIMIT, type TupleSchema, TypeEvalLimitError, type TypeEvalLimits, type TypeScheme, type UnionSchema, UnionTooComplexError, type UnknownSchema, type VarSchema, configureTypeLimits, discover, equals, expand1, flagAt, format, formatTypeDiff, groundVars, instantiate, instantiateLoose, isScheme, isSerializable, isVariadicTuple, join, joinAll, normalizeTuple, normalizeUnion, ownProp, resetTypeLimits, resolveTypeOp, restIndex, s, sliceTuple, substitute, subtype, typeDiff, typeFeatures, typeLimits, unify, widen, widenInferred, widenType, withoutUndefined };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var O=e=>Object.freeze(e),c={any:O({t:"any"}),unknown:O({t:"unknown"}),string:O({t:"string"}),number:O({t:"number"}),boolean:O({t:"boolean"}),null:O({t:"null"}),undefined:O({t:"undefined"}),void:O({t:"void"}),literal:e=>({t:"literal",value:e}),object:(e,t)=>({t:"object",props:e,...t?{index:t}:{}}),record:(e,t="string")=>({t:"object",props:{},index:{key:t,value:e}}),array:e=>({t:"array",items:e}),tuple:(e,t)=>({t:"tuple",elements:e,...t&&t.some(n=>n!=="req")?{flags:t}:{}}),fn:(e,t)=>({t:"fn",params:e,returns:t}),guard:(e,t,n=0)=>({t:"fn",params:e,returns:{t:"boolean"},guard:{param:n,type:t}}),overload:e=>({t:"overload",signatures:e}),keyof:e=>({t:"keyof",of:e}),index:(e,t)=>({t:"index",obj:e,key:t}),mapped:(e,t,n,r=false)=>({t:"mapped",key:e,over:t,body:n,optional:r}),conditional:(e,t,n,r,o)=>({t:"conditional",check:e,extends:t,then:n,else:r,...o&&o.length?{infer:o}:{}}),intersection:e=>({t:"intersection",of:e}),and:(e,t)=>({t:"intersection",of:[e,t]}),returnType:e=>({t:"returnType",fn:e}),parameters:e=>({t:"parameters",fn:e}),var:(e,t,n)=>({t:"var",name:e,bound:t,isConst:n}),apply:(e,t=[])=>({t:"apply",name:e,args:t}),promise:e=>({t:"apply",name:"Promise",args:[e]}),union:e=>{let t=[];for(let n of e)n.t==="union"?t.push(...n.of):t.push(n);return {t:"union",of:t}}};function h(e){return e.t==="keyof"?ae(e.of)??e:e.t==="index"?J(e.obj,e.key)??e:e.t==="returnType"?xe(e.fn)??e:e.t==="parameters"?ke(e.fn)??e:e}var re={t:"union",of:[]},ge=e=>e.t==="union"&&e.of.length===0;function xe(e){return e.t==="fn"?e.returns:e.t==="overload"&&e.signatures.length>0?e.signatures[e.signatures.length-1].returns:null}function ve(e){if(e.t==="undefined")return e;let t=e.t==="union"?e.of:[e];return t.some(n=>n.t==="undefined")?e:{t:"union",of:[...t,{t:"undefined"}]}}function ke(e){let t=e.t==="fn"?e:e.t==="overload"&&e.signatures.length>0?e.signatures[e.signatures.length-1]:null;if(!t)return null;let n=[],r=[];for(let o of t.params)o.variadic?(n.push(o.type.t==="array"?o.type.items:o.type),r.push("rest")):o.optional?(n.push(ve(o.type)),r.push("optional")):(n.push(o.type),r.push("req"));return c.tuple(n,r)}var oe=e=>e.t==="literal"?typeof e.value:e.t==="string"||e.t==="number"||e.t==="boolean"?e.t:null;function ie(e,t){return e.t==="literal"&&t.t==="literal"?e.value===t.value:e.t==="literal"&&(t.t==="string"||t.t==="number"||t.t==="boolean")?typeof e.value===t.t:e.t===t.t&&(e.t==="string"||e.t==="number"||e.t==="boolean")}function j(e){let t=[],n=o=>{let i=h(o);i.t==="intersection"?i.of.forEach(n):t.push(i);};e.of.forEach(n);let r=[];for(let o of t){if(o.t==="any")return c.any;if(ge(o))return re;if(o.t!=="unknown"){if(oe(o)){let i=false;for(let a=r.length-1;a>=0;a--){let l=r[a];if(oe(l)){if(ie(l,o)){i=true;break}if(ie(o,l))r.splice(a,1);else return re}}if(i)continue}else if(r.some(i=>i===o))continue;r.push(o);}}return r.length===0?c.unknown:r.length===1?r[0]:{t:"intersection",of:r}}function ae(e){if(e.t==="union"){let n=e.of.map(ae);return n.some(r=>r===null)?null:be(n)}if(e.t!=="object")return null;let t=Object.keys(e.props).map(n=>c.literal(n));return e.index&&t.push(e.index.key==="number"?c.number:c.string),t.length===0?{t:"union",of:[]}:t.length===1?t[0]:{t:"union",of:t}}function be(e){let t=i=>i.t==="literal"&&typeof i.value=="string"?[i.value]:i.t==="union"?i.of.flatMap(t):[],n=e.filter(i=>i.t!=="string"&&i.t!=="number").map(t);if(n.length===0)return e[0];let r=n[0].filter(i=>n.every(a=>a.includes(i))),o=[...new Set(r)].map(i=>c.literal(i));return o.length===0?{t:"union",of:[]}:o.length===1?o[0]:{t:"union",of:o}}function J(e,t){if(e=h(e),t=h(t),t.t==="union"){let n=t.of.map(r=>J(e,r));return n.some(r=>r===null)?null:{t:"union",of:n}}if(e.t==="intersection"){let n=[];for(let r of e.of){let o=J(h(r),t);if(o===null)return null;o.t!=="undefined"&&n.push(o);}return n.length===0?c.undefined:n.length===1?n[0]:j({of:n})}if(e.t==="object"){if(t.t==="literal"&&(typeof t.value=="string"||typeof t.value=="number")){let n=M(e.props,String(t.value));return n?n.optional?{t:"union",of:[n.type,{t:"undefined"}]}:n.type:typeof t.value=="number"&&e.index?.key==="number"||e.index?.key==="string"?e.index.value:c.undefined}if(e.index?.key==="string"&&t.t==="string"||e.index?.key==="number"&&(t.t==="number"||t.t==="literal"&&typeof t.value=="number"))return e.index.value}if(e.t==="tuple"){let n=e.flags?.findIndex(r=>r!=="req")??-1;if(n>=0){if(t.t==="literal"&&typeof t.value=="number")return t.value<n?e.elements[t.value]??c.undefined:e.elements.length?{t:"union",of:e.elements.slice(n)}:c.undefined;if(t.t==="number")return e.elements.length?{t:"union",of:e.elements}:c.undefined}else {if(t.t==="literal"&&typeof t.value=="number")return e.elements[t.value]??c.undefined;if(t.t==="number")return e.elements.length?{t:"union",of:e.elements}:c.undefined}}return e.t==="array"&&(t.t==="number"||t.t==="literal"&&typeof t.value=="number")?e.items:null}var je=Object.prototype.hasOwnProperty,M=(e,t)=>je.call(e,t)?e[t]:void 0;function B(e){if(e.t==="undefined")return {type:{t:"union",of:[]},hadUndefined:true};if(e.t==="union"&&e.of.some(t=>t.t==="undefined")){let t=e.of.filter(n=>n.t!=="undefined");return {type:t.length===1?t[0]:{t:"union",of:t},hadUndefined:true}}return {type:e,hadUndefined:false}}var K=(e,t)=>e.flags?.[t]??"req",ue=e=>e==="rest"||e==="variadic",Te=e=>!!e.flags?.some(ue),U=e=>e.flags?.findIndex(ue)??-1,we=e=>{if(!e.flags)return e.elements.length;let t=e.flags.findIndex(n=>n!=="req");return t<0?e.elements.length:t};function A(e,t){let n=[],r=[],o=(i,a)=>{n.push(i),r.push(a);};for(let i=0;i<e.length;i++){let a=e[i],l=t[i]??"req";if(l!=="variadic"){o(a,l);continue}if(a.t==="tuple"){let u=a;for(let d=0;d<u.elements.length;d++)o(u.elements[d],K(u,d));}else a.t==="array"?o(a.items,"rest"):a.t==="any"?o(a,"rest"):o(a,"variadic");}return c.tuple(n,r)}function le(e){let t=U(e);return t<0?{prefix:e.elements,rest:null,suffix:[]}:{prefix:e.elements.slice(0,t),rest:e.elements[t],suffix:e.elements.slice(t+1)}}function pe(e,t,n){let r=le(e),o=le(t);if(o.rest===null){if(r.rest!==null)return false;let i=we(t);return e.elements.length<i||e.elements.length>t.elements.length?false:e.elements.every((a,l)=>n(a,t.elements[l]))}if(r.rest===null){let i=r.prefix;if(i.length<o.prefix.length+o.suffix.length)return false;for(let a=0;a<o.prefix.length;a++)if(!n(i[a],o.prefix[a]))return false;for(let a=0;a<o.suffix.length;a++)if(!n(i[i.length-o.suffix.length+a],o.suffix[a]))return false;for(let a=o.prefix.length;a<i.length-o.suffix.length;a++)if(!n(i[a],o.rest))return false;return true}if(r.prefix.length>=o.prefix.length&&r.suffix.length>=o.suffix.length){for(let i=0;i<o.prefix.length;i++)if(!n(r.prefix[i],o.prefix[i]))return false;for(let i=o.prefix.length;i<r.prefix.length;i++)if(!n(r.prefix[i],o.rest))return false;if(!n(r.rest,o.rest))return false;for(let i=0;i<o.suffix.length;i++)if(!n(r.suffix[r.suffix.length-o.suffix.length+i],o.suffix[i]))return false;for(let i=0;i<r.suffix.length-o.suffix.length;i++)if(!n(r.suffix[i],o.rest))return false;return true}return false}function N(e,t,n){if(e.t==="array")return e;if(e.t==="tuple"){let r=e,o=r.elements.length,i=r.elements.slice(t,o-n),a=(r.flags??r.elements.map(()=>"req")).slice(t,o-n);return c.tuple(i,a)}return c.tuple([])}function s(e,t,n=new WeakSet){if(e.t!=="keyof"&&e.t!=="index"&&e.t!=="mapped"&&e.t!=="intersection"&&e.t!=="returnType"&&e.t!=="parameters"&&!$e(F(e),t))return e;switch(e.t){case "var":{let r=t[e.name];return r||(e.bound?{t:"var",name:e.name,bound:s(e.bound,t,n)}:e)}case "array":return {t:"array",items:s(e.items,t,n)};case "tuple":{let r=e.elements.map(o=>s(o,t,n));return e.flags?A(r,e.flags):{t:"tuple",elements:r}}case "union":return {t:"union",of:e.of.map(r=>s(r,t,n))};case "object":{if(n.has(e))return e;n.add(e);let r={};for(let i in e.props){let a=e.props[i];r[i]={type:s(a.type,t,n),optional:a.optional};}let o=e.index?{key:e.index.key,value:s(e.index.value,t,n)}:void 0;return n.delete(e),o?{t:"object",props:r,index:o}:{t:"object",props:r}}case "fn":{if(n.has(e))return e;n.add(e);let o={t:"fn",params:e.params.map(i=>({...i,type:s(i.type,t,n)})),returns:s(e.returns,t,n),...e.guard&&{guard:{param:e.guard.param,type:s(e.guard.type,t,n)}}};return n.delete(e),o}case "apply":return {t:"apply",name:e.name,args:e.args.map(r=>s(r,t,n))};case "keyof":return h({t:"keyof",of:s(e.of,t,n)});case "index":return h({t:"index",obj:s(e.obj,t,n),key:s(e.key,t,n)});case "mapped":{let r={};for(let i in t)i!==e.key&&(r[i]=t[i]);let o={t:"mapped",key:e.key,over:s(e.over,t,n),body:s(e.body,r,n),optional:e.optional};return V(o)??o}case "conditional":{if(e.check.t==="var"){let o=e.check.name,i=t[o],a=i?h(i):void 0,l=a?.t==="union"?a.of:a?.t==="boolean"?[c.literal(true),c.literal(false)]:null;if(l)return {t:"union",of:l.map(u=>s(e,{...t,[o]:u},n))}}let r=e.infer?.length?Object.fromEntries(Object.entries(t).filter(([o])=>!e.infer.includes(o))):t;return {t:"conditional",check:s(e.check,t,n),extends:s(e.extends,r,n),then:s(e.then,r,n),else:s(e.else,r,n),...e.infer?{infer:e.infer}:{}}}case "intersection":return j({of:e.of.map(r=>s(r,t,n))});case "returnType":return h({t:"returnType",fn:s(e.fn,t,n)});case "parameters":return h({t:"parameters",fn:s(e.fn,t,n)});default:return e}}var Ee=new Set,fe=new WeakMap;function F(e){let t=fe.get(e);if(t)return t;let n=new Set;y(e,n,new WeakSet);let r=n.size===0?Ee:n;return fe.set(e,r),r}function y(e,t,n){switch(e.t){case "var":t.add(e.name),e.bound&&y(e.bound,t,n);return;case "array":y(e.items,t,n);return;case "tuple":for(let r of e.elements)y(r,t,n);return;case "union":for(let r of e.of)y(r,t,n);return;case "object":if(n.has(e))return;n.add(e);for(let r in e.props)y(e.props[r].type,t,n);e.index&&y(e.index.value,t,n);return;case "fn":if(n.has(e))return;n.add(e);for(let r of e.params)y(r.type,t,n);y(e.returns,t,n),e.guard&&y(e.guard.type,t,n);return;case "overload":for(let r of e.signatures){for(let o of r.params)y(o.type,t,n);y(r.returns,t,n);}return;case "apply":for(let r of e.args)y(r,t,n);return;case "keyof":y(e.of,t,n);return;case "index":y(e.obj,t,n),y(e.key,t,n);return;case "mapped":y(e.over,t,n),y(e.body,t,n);return;case "conditional":{if(y(e.check,t,n),!e.infer?.length){y(e.extends,t,n),y(e.then,t,n),y(e.else,t,n);return}let r=new Set;y(e.extends,r,n),y(e.then,r,n),y(e.else,r,n);for(let o of r)e.infer.includes(o)||t.add(o);return}case "intersection":for(let r of e.of)y(r,t,n);return;case "returnType":case "parameters":y(e.fn,t,n);return;default:return}}function $e(e,t){if(e.size===0)return false;for(let n of e)if(n in t)return true;return false}function V(e){let t=h(e.over);if(t.t==="string"||t.t==="number")return {t:"object",props:{},index:{key:t.t,value:s(e.body,{[e.key]:t})}};let n=Ie(t);if(n===null)return null;let r={};for(let o of n)r[o]={type:s(e.body,{[e.key]:c.literal(o)}),optional:e.optional};return {t:"object",props:r}}function Ie(e){if(e.t==="literal"&&typeof e.value=="string")return [e.value];if(e.t==="union"){let t=[];for(let n of e.of)if(n.t==="literal"&&typeof n.value=="string")t.push(n.value);else return null;return t}return null}function E(e,t){if(e.t!=="apply")return false;let n=t[e.name];return n!==void 0&&n.params.length===e.args.length}function $(e,t){if(e.t!=="apply")return e;let n=t[e.name];if(!n||n.params.length!==e.args.length)return e;let r={};return n.params.forEach((o,i)=>r[o]=e.args[i]),s(n.body,r)}function g(e){switch(e.t){case "literal":return `#${typeof e.value}:${String(e.value)}`;case "object":{let t=Object.keys(e.props).sort().map(r=>`${r}${e.props[r].optional?"?":""}:${g(e.props[r].type)}`).join(","),n=e.index?`,[${e.index.key}]:${g(e.index.value)}`:"";return `{${t}${n}}`}case "array":return `[${g(e.items)}]`;case "tuple":return `#tuple(${e.elements.map(g).join(",")})`;case "union":return `(${e.of.map(g).sort().join("|")})`;case "fn":return `(${e.params.map(t=>g(t.type)).join(",")})=>${e.guard?`is${e.guard.param}:${g(e.guard.type)}`:g(e.returns)}`;case "var":return `v:${e.name}`;case "apply":return `${e.name}<${e.args.map(g).join(",")}>`;case "intersection":return `&(${e.of.map(g).sort().join("&")})`;case "returnType":return `RT<${g(e.fn)}>`;default:return e.t}}var Oe=1e3,Y={maxTypeDepth:1e3,maxUnionMembers:1e3,maxOverloadSignatures:200},D=Y;function Me(e){D={...Y,...e};}function Pe(){D=Y;}function R(){return D}var P=class extends Error{constructor(t=D.maxTypeDepth){super(`type evaluation exceeded the depth limit (${t}) \u2014 the type is excessively deep or possibly infinite`),this.name="TypeEvalLimitError";}},C=class extends Error{constructor(t,n=D.maxUnionMembers){super(`union type is too complex to represent (${t} members exceeds limit ${n})`),this.name="UnionTooComplexError";}};var Q=(e,t)=>({seen:new WeakMap,exp:new Set,schemes:e,depth:0,explain:t});function w(e,t,n){return e.explain?.out.push({path:[...e.explain.path],actual:t,expected:n,kind:"type"}),false}function Le(e,t,n={}){let r=[];return !p(e,t,Q(n,{path:[],out:r}))&&r.length===0&&r.push({path:[],actual:e,expected:t,kind:"type"}),r}var Z=new WeakMap;function v(e,t,n={}){if(e===t)return true;if(Object.keys(n).length>0)return p(e,t,Q(n));let r=Z.get(e)?.get(t);if(r!==void 0)return r;let o=p(e,t,Q(n)),i=Z.get(e);return i||Z.set(e,i=new WeakMap),i.set(t,o),o}function We(e,t,n={}){return v(e,t,n)&&v(t,e,n)}function q(e,t){return e.infer?.length||F(e.check).size>0||F(e.extends).size>0?null:v(e.check,e.extends,t)?e.then:e.else}function z(e,t,n=0){if(n>50)return e;let r=h(e);if(r!==e)return z(r,t,n+1);if(e.t==="conditional"){let o=q(e,t.schemes);if(o)return z(o,t,n+1)}return E(e,t.schemes)?z($(e,t.schemes),t,n+1):e.t==="union"?k(e.of.map(o=>z(o,t,n+1))):e}function p(e,t,n){if(n.depth>=R().maxTypeDepth)throw new P;n.depth++;try{return Be(e,t,n)}finally{n.depth--;}}function X(e,t,n,r){if(!n.explain)return p(e,t,n);n.explain.path.push(r);try{return p(e,t,n)}finally{n.explain.path.pop();}}function Be(e,t,n){if(e.t==="any"||t.t==="any"||t.t==="unknown")return true;if(e.t==="unknown")return w(n,e,t);let r=h(e);if(r!==e)return p(r,t,n);let o=h(t);if(o!==t)return p(e,o,n);if(e.t==="mapped"){let l=V({...e,over:z(e.over,n)});if(l)return p(l,t,n)}if(t.t==="mapped"){let l=V({...t,over:z(t.over,n)});if(l)return p(e,l,n)}if(e.t==="conditional"){let l=q(e,n.schemes);if(l)return p(l,t,n)}if(t.t==="conditional"){let l=q(t,n.schemes);if(l)return p(e,l,n)}if(t.t==="intersection"){let l=j(t);return l.t!=="intersection"?p(e,l,n):l.of.every(u=>p(e,u,n))}if(e.t==="intersection"){let l=j(e);if(l.t!=="intersection")return p(l,t,n);if(l.of.some(u=>p(u,t,n)))return true;if(t.t==="object"){let u=Re(l.of);if(u)return p(u,t,n)}return false}if(!(e.t==="apply"&&t.t==="apply"&&e.name===t.name&&e.args.length===t.args.length)&&(E(e,n.schemes)||E(t,n.schemes))){let l=`${g(e)}\u2264${g(t)}`;if(n.exp.has(l))return true;n.exp.add(l);let u=p($(e,n.schemes),$(t,n.schemes),n);return n.exp.delete(l),u}let a=n.seen.get(e);if(a?.has(t))return true;if(a||(a=new WeakSet,n.seen.set(e,a)),a.add(t),e.t==="union")return e.of.every(l=>p(l,t,n));if(e.t==="boolean"&&t.t==="union")return p(c.literal(true),t,n)&&p(c.literal(false),t,n);if(t.t==="union")return t.of.some(l=>p(e,l,n));if(t.t==="overload")return t.signatures.every(l=>p(e,l,n));if(e.t==="overload")return e.signatures.some(l=>p(l,t,n));switch(t.t){case "literal":return e.t==="literal"&&e.value===t.value?true:w(n,e,t);case "string":case "number":case "boolean":case "null":case "undefined":return e.t===t.t||e.t==="literal"&&Fe(e.value)===t.t?true:w(n,e,t);case "void":return e.t==="void"||e.t==="undefined"?true:w(n,e,t);case "array":return e.t==="array"?p(e.items,t.items,n):e.t==="tuple"?e.elements.every(l=>p(l,t.items,n)):w(n,e,t);case "tuple":{if(e.t!=="tuple")return w(n,e,t);if(!e.flags&&!t.flags){if(e.elements.length!==t.elements.length)return w(n,e,t);for(let l=0;l<e.elements.length;l++)if(!X(e.elements[l],t.elements[l],n,String(l)))return false;return true}return pe(e,t,(l,u)=>p(l,u,n))}case "object":return e.t==="object"?ze(e,t,n):Object.keys(t.props).length===0&&!t.index?e.t!=="null"&&e.t!=="undefined"&&e.t!=="void"?true:w(n,e,t):e.t==="array"&&t.index&&Object.values(t.props).every(l=>l.optional)&&p(e.items,t.index.value,n)?true:w(n,e,t);case "fn":return e.t==="fn"?Ue(e,t,n):w(n,e,t);case "var":return e.t==="var"&&e.name===t.name;case "keyof":return e.t==="keyof"&&p(e.of,t.of,n)&&p(t.of,e.of,n);case "index":return e.t==="index"&&p(e.obj,t.obj,n)&&p(t.obj,e.obj,n)&&p(e.key,t.key,n)&&p(t.key,e.key,n);case "mapped":return e.t==="mapped"&&e.key===t.key&&!!e.optional==!!t.optional&&p(e.over,t.over,n)&&p(t.over,e.over,n)&&p(e.body,t.body,n)&&p(t.body,e.body,n);case "conditional":return e.t==="conditional"&&p(e.check,t.check,n)&&p(t.check,e.check,n)&&p(e.extends,t.extends,n)&&p(t.extends,e.extends,n)&&p(e.then,t.then,n)&&p(e.else,t.else,n);case "apply":return e.t==="apply"&&e.name===t.name&&e.args.length===t.args.length&&e.args.every((l,u)=>p(l,t.args[u],n));case "returnType":return e.t==="returnType"&&p(e.fn,t.fn,n)&&p(t.fn,e.fn,n);case "parameters":return e.t==="parameters"&&p(e.fn,t.fn,n)&&p(t.fn,e.fn,n)}}var Fe=e=>typeof e;function Re(e){let t=[];for(let i of e){let a=h(i);if(a.t!=="object")return null;t.push(a);}let n=new Set;for(let i of t)for(let a in i.props)n.add(a);let r={};for(let i of n){let a=[],l=true;for(let u of t){let d=u.props[i];d?(a.push(d.type),d.optional||(l=false)):u.index?.key==="string"&&(a.push(u.index.value),l=false);}r[i]={type:j({of:a}),optional:l};}let o;for(let i of t)i.index&&(o=o?{key:o.key,value:j({of:[o.value,i.index.value]})}:i.index);return o?{t:"object",props:r,index:o}:{t:"object",props:r}}function ze(e,t,n){let r=false;for(let o in t.props)if(!(t.props[o].optional||M(e.props,o))){if(!n.explain)return false;n.explain.out.push({path:[...n.explain.path,o],expected:t.props[o].type,kind:"missing"}),r=true;}if(r)return false;for(let o in t.props){let i=t.props[o],a=M(e.props,o);if(a&&(a.optional&&!i.optional||!X(a.type,i.type,n,o)))return false}if(t.index){for(let o in e.props)if(!X(e.props[o].type,t.index.value,n,o))return false;if(e.index&&!p(e.index.value,t.index.value,n))return false}return true}function Ue(e,t,n){if(t.returns.t!=="void"&&t.returns.t!=="any"&&!p(e.returns,t.returns,n))return false;for(let r=0;r<e.params.length;r++){let o=e.params[r];if(o.variadic)break;let i=t.params[r];if(!i){if(o.optional)continue;return false}if(!p(i.type,o.type,n))return false}return !(t.guard&&(!e.guard||e.guard.param!==t.guard.param||!p(e.guard.type,t.guard.type,n)))}function k(e){let t=[];for(let o of e)o.t==="union"?t.push(...o.of):t.push(o);let n=R().maxUnionMembers;if(t.length>n)throw new C(t.length,n);if(t.some(o=>o.t==="any"))return c.any;let r=[];for(let o of t)if(!r.some(i=>v(o,i))){for(let i=r.length-1;i>=0;i--)v(r[i],o)&&r.splice(i,1);r.push(o);}if(r.some(o=>o.t==="literal"&&o.value===true)&&r.some(o=>o.t==="literal"&&o.value===false)){let o=r.filter(i=>!(i.t==="boolean"||i.t==="literal"&&typeof i.value=="boolean"));o.push(c.boolean),r.length=0,r.push(...o);}return r.length===1?r[0]:{t:"union",of:r}}function Ae(e,t){let n=new Set,r=new WeakSet,o=i=>{if(!r.has(i))switch(r.add(i),i.t){case "keyof":n.add("keyof"),o(i.of);break;case "index":n.add("indexed"),o(i.obj),o(i.key);break;case "mapped":n.add("mapped"),o(i.over),o(i.body);break;case "conditional":n.add("conditional"),i.infer?.length&&n.add("infer"),o(i.check),o(i.extends),o(i.then),o(i.else);break;case "returnType":n.add("returnType"),o(i.fn);break;case "parameters":n.add("parameters"),o(i.fn);break;case "tuple":n.add("tuple"),i.flags?.some(a=>a!=="req")&&n.add("variadic"),i.elements.forEach(o);break;case "intersection":n.add("intersection"),i.of.forEach(o);break;case "overload":n.add("overload");for(let a of i.signatures){for(let l of a.params)o(l.type);o(a.returns);}break;case "object":for(let a in i.props)o(i.props[a].type);i.index&&o(i.index.value);break;case "array":o(i.items);break;case "union":i.of.forEach(o);break;case "fn":for(let a of i.params)o(a.type);o(i.returns),i.guard&&o(i.guard.type);break;case "var":i.bound&&o(i.bound);break;case "apply":t&&i.name===t&&n.add("recursion"),i.args.forEach(o);break}};return o(e),n}var ce=e=>typeof e=="string"?c.string:typeof e=="number"?c.number:c.boolean;function ee(e){return e.t==="literal"&&e.fresh?ce(e.value):e}function Ce(e){return b(e,new WeakSet)}function De(e){switch(e.t){case "array":return {t:"array",items:b(e.items,new WeakSet)};case "tuple":return {t:"tuple",elements:e.elements.map(t=>b(t,new WeakSet)),...e.flags?{flags:e.flags}:{}};case "object":return se(e,new WeakSet);case "fn":case "overload":return b(e,new WeakSet);default:return e}}function b(e,t){if(e.t==="literal")return e.fresh?ce(e.value):e;if(t.has(e))return e;switch(e.t){case "array":return t.add(e),{t:"array",items:b(e.items,t)};case "tuple":return t.add(e),{t:"tuple",elements:e.elements.map(n=>b(n,t)),...e.flags?{flags:e.flags}:{}};case "object":return t.add(e),se(e,t);case "apply":return t.add(e),{t:"apply",name:e.name,args:e.args.map(n=>b(n,t))};case "fn":return t.add(e),{t:"fn",params:e.params.map(n=>({...n,type:b(n.type,t)})),returns:b(e.returns,t),...e.guard?{guard:{param:e.guard.param,type:b(e.guard.type,t)}}:{}};case "overload":return t.add(e),{t:"overload",signatures:e.signatures.map(n=>b(n,t))};default:return e}}function se(e,t){let n={};for(let o in e.props)n[o]={type:b(e.props[o].type,t),optional:e.props[o].optional};let r=e.index?{key:e.index.key,value:b(e.index.value,t)}:void 0;return r?{t:"object",props:n,index:r}:{t:"object",props:n}}var de=e=>e.t==="literal"?typeof e.value:e.t==="string"||e.t==="number"||e.t==="boolean"?e.t:null;function qe(e,t){if(v(t,e))return e;if(v(e,t))return t;let n=de(e),r=de(t);return !n||!r||n===r?k([e,t]):null}function x(e,t,n={}){if(e.t==="var"){let r=n[e.name];if(!r)return {...n,[e.name]:t};if(t.t==="any"||t.t==="unknown")return n;let o=qe(r,t);return o?{...n,[e.name]:o}:n}if(t.t==="any"||t.t==="unknown")return n;switch(e.t){case "array":return t.t==="array"?x(e.items,t.items,n):null;case "tuple":{let r=e,o=U(r);if(o<0){if(t.t!=="tuple"||t.elements.length!==r.elements.length)return null;let f=n;for(let W=0;W<r.elements.length;W++)if(f=x(r.elements[W],t.elements[W],f),f===null)return null;return f}let i=o,a=r.elements.length-o-1,l=K(r,o),u=f=>l==="variadic"?f:f.t==="tuple"?f.elements.length?k(f.elements):c.unknown:f.t==="array"?f.items:f,d=n,m=(f,W)=>{d!==null&&(d=x(f,W,d));};if(t.t==="tuple"){if(t.elements.length<i+a)return null;for(let f=0;f<i;f++)m(r.elements[f],t.elements[f]);for(let f=0;f<a;f++)m(r.elements[o+1+f],t.elements[t.elements.length-a+f]);return d!==null&&(d=x(r.elements[o],u(N(t,i,a)),d)),d}if(t.t==="array"){for(let f=0;f<i;f++)m(r.elements[f],t.items);for(let f=0;f<a;f++)m(r.elements[o+1+f],t.items);return d!==null&&(d=x(r.elements[o],u(t),d)),d}return null}case "object":{if(t.t!=="object")return null;let r=n;for(let o in e.props){let i=e.props[o],a=t.props[o];if(!a){if(i.optional)continue;return null}if(r=x(i.type,a.type,r),r===null)return null}return r}case "fn":{if(t.t!=="fn")return null;let r=x(e.returns,t.returns,n);if(r===null)return null;let o=Math.min(e.params.length,t.params.length);for(let i=0;i<o;i++)if(r=x(e.params[i].type,t.params[i].type,r),r===null)return null;return e.guard&&t.guard&&(r=x(e.guard.type,t.guard.type,r)),r}case "apply":{if(t.t!=="apply"||t.name!==e.name||t.args.length!==e.args.length)return null;let r=n;for(let o=0;o<e.args.length;o++)if(r=x(e.args[o],t.args[o],r),r===null)return null;return r}default:return v(t,e)?n:null}}var me="@rev",te=e=>e.t==="mapped"&&e.over.t==="keyof"&&e.over.of.t==="var";function I(e,t,n){if(e.t==="index"&&e.obj.t==="var"&&e.obj.name===t&&e.key.t==="var"&&e.key.name===n)return c.var(me);switch(e.t){case "array":return {t:"array",items:I(e.items,t,n)};case "tuple":return {t:"tuple",elements:e.elements.map(r=>I(r,t,n)),...e.flags?{flags:e.flags}:{}};case "union":return {t:"union",of:e.of.map(r=>I(r,t,n))};case "fn":return {t:"fn",params:e.params.map(r=>({...r,type:I(r.type,t,n)})),returns:I(e.returns,t,n)};case "apply":return {t:"apply",name:e.name,args:e.args.map(r=>I(r,t,n))};case "returnType":return {t:"returnType",fn:I(e.fn,t,n)};case "object":{let r={};for(let o in e.props)r[o]={type:I(e.props[o].type,t,n),optional:e.props[o].optional};return e.index?{t:"object",props:r,index:{key:e.index.key,value:I(e.index.value,t,n)}}:{t:"object",props:r}}default:return e}}function _e(e,t,n){if(e.over.t!=="keyof"||e.over.of.t!=="var")return null;let r=e.over.of.name;if(n[r])return null;let o={};for(let i in t.props){let a=I(e.body,r,e.key),l=x(a,t.props[i].type,{})?.[me];o[i]={type:l?ee(l):c.unknown,optional:t.props[i].optional};}return {...n,[r]:{t:"object",props:o}}}function ye(e,t,n){let r=n;for(let o=0;o<e.length&&o<t.length;o++){let i=e[o].type,a=t[o];if(te(i)&&a.t==="object"){let l=_e(i,a,r);l&&(r=l);}}return r}function Ke(e,t){let n={};for(let o=0;o<e.params.length;o++){let i=e.params[o];if(i.variadic){for(let a=o;a<t.length;a++)if(n=x(i.type,t[a],n),n===null)return null;break}if(o>=t.length){if(i.optional)continue;return null}if(!te(i.type)&&(n=x(i.type,t[o],n),n===null))return null}let r=ye(e.params,t,n);return {returns:s(e.returns,r),bindings:r}}function Ne(e,t){let n={};for(let r=0;r<e.params.length&&r<t.length;r++){let o=e.params[r];if(te(o.type))continue;let i=x(o.type,t[r],n);i!==null&&(n=i);}return n=ye(e.params,t,n),{returns:s(e.returns,n),bindings:n}}function T(e,t,n,r,o){if(e.t==="var"&&n.has(e.name)){let i=o.get(e.name);i||o.set(e.name,i={co:[],contra:[]}),(r?i.contra:i.co).push(t);return}if(!(t.t==="any"||t.t==="unknown"))switch(e.t){case "array":t.t==="array"&&T(e.items,t.items,n,r,o);return;case "tuple":{let i=e,a=U(i);if(a<0){t.t==="tuple"&&t.elements.length===i.elements.length&&i.elements.forEach((m,f)=>T(m,t.elements[f],n,r,o));return}let l=a,u=i.elements.length-a-1,d=m=>T(i.elements[a],m,n,r,o);if(t.t==="tuple"){let m=t;if(m.elements.length<l+u)return;for(let f=0;f<l;f++)T(i.elements[f],m.elements[f],n,r,o);for(let f=0;f<u;f++)T(i.elements[a+1+f],m.elements[m.elements.length-u+f],n,r,o);d(N(m,l,u));}else if(t.t==="array"){for(let m=0;m<l;m++)T(i.elements[m],t.items,n,r,o);for(let m=0;m<u;m++)T(i.elements[a+1+m],t.items,n,r,o);d(t);}return}case "fn":t.t==="fn"&&(e.params.forEach((i,a)=>{let l=t.params[a];l&&T(i.type,l.type,n,!r,o);}),T(e.returns,t.returns,n,r,o));return;case "object":if(t.t==="object")for(let i in e.props)t.props[i]&&T(e.props[i].type,t.props[i].type,n,r,o);return;case "apply":t.t==="apply"&&t.name===e.name&&t.args.length===e.args.length&&e.args.forEach((i,a)=>T(i,t.args[a],n,r,o));return;default:return}}function Ve(e,t){if(e.length===1)return e[0];let r=e.flatMap(o=>o.t==="union"?[...o.of]:[o]).filter(o=>e.every(i=>v(o,i,t)));return k(r)}var Ye=e=>e.t==="union"&&e.of.length===0;function Ge(e,t){let n={};for(let[r,{co:o,contra:i}]of e){let a=o.length?k(o):void 0,l=i.length?Ve(i,t):void 0,u=a??l;a&&l&&(u=!Ye(a)&&a.t!=="any"&&v(a,l,t)?a:l),u&&(n[r]=u);}return n}function He(e,t={},n=0){if(!e.infer?.length||F(e.check).size>0)return null;let r=new Map;T(e.extends,e.check,new Set(e.infer),false,r);let o=Ge(r,t),i=new WeakSet,a=G(s(e.extends,o),t,i,n);return v(e.check,a,t)?G(s(e.then,o),t,i,n):G(s(e.else,o),t,i,n)}function G(e,t={},n=new WeakSet,r=0){let o=r,i=R().maxTypeDepth,a=l=>{switch(l.t){case "var":return c.unknown;case "array":return {t:"array",items:a(l.items)};case "tuple":{let u=l.elements.map(a);return l.flags?A(u,l.flags):{t:"tuple",elements:u}}case "union":return {t:"union",of:l.of.map(a)};case "object":{if(n.has(l))return l;n.add(l);let u={};for(let m in l.props){let f=l.props[m];u[m]={type:a(f.type),optional:f.optional};}let d=l.index?{key:l.index.key,value:a(l.index.value)}:void 0;return n.delete(l),d?{t:"object",props:u,index:d}:{t:"object",props:u}}case "fn":{if(n.has(l))return l;n.add(l);let d={t:"fn",params:l.params.map(m=>({...m,type:a(m.type)})),returns:a(l.returns),...l.guard&&{guard:{param:l.guard.param,type:a(l.guard.type)}}};return n.delete(l),d}case "apply":{if(E(l,t)){let u=$(l,t);if(u.t==="conditional"){if(o>=i)throw new P;o++;try{let d=a(u);if(d.t!=="conditional")return d}finally{o--;}}}return {t:"apply",name:l.name,args:l.args.map(a)}}case "conditional":{let u=l.infer?.length?He(l,t,o):q(l,t);return u?a(u):{t:"conditional",check:a(l.check),extends:a(l.extends),then:a(l.then),else:a(l.else),...l.infer?{infer:l.infer}:{}}}case "intersection":return j({of:l.of.map(a)});case "returnType":return h({t:"returnType",fn:a(l.fn)});default:return l}};return a(e)}var Je=c.union([]);function Se(e,t){return ne(e,t,new WeakMap)}function Ze(e){return e.reduce(Se,Je)}function ne(e,t,n){if(e.t==="any"||t.t==="any")return c.any;if(e===t)return e;let r=n.get(e)?.get(t);if(r)return r;if(e.t==="object"&&t.t==="object")return Qe(e,t,n);if(e.t==="array"&&t.t==="array"){let o={t:"array",items:c.unknown};return he(n,e,t,o),o.items=ne(e.items,t.items,n),o}return k([e,t])}function Qe(e,t,n){let r={t:"object",props:{}};he(n,e,t,r);for(let o in e.props){let i=e.props[o],a=t.props[o];if(a){let l=ne(i.type,a.type,n);r.props[o]=i.optional||a.optional?{type:l,optional:true}:{type:l};}else r.props[o]={type:i.type,optional:true};}for(let o in t.props)o in e.props||(r.props[o]={type:t.props[o].type,optional:true});return r}function he(e,t,n,r){let o=e.get(t);o||(o=new WeakMap,e.set(t,o)),o.set(n,r);}var Xe=e=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e);function S(e,t=new WeakSet){switch(e.t){case "any":case "unknown":case "string":case "number":case "boolean":case "null":case "undefined":case "void":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 n=S(e.items,t);return et(e.items)?`(${n})[]`:`${n}[]`}case "tuple":return `[${e.elements.map((r,o)=>{let i=e.flags?.[o]??"req",a=S(r,t),l=r.t==="union"?`(${a})`:a;return i==="rest"?`...${l}[]`:i==="variadic"?`...${a}`:i==="optional"?`${l}?`:a}).join(", ")}]`;case "union":{if(t.has(e))return "\u2026";t.add(e);let n=e.of.length===0?"never":e.of.map(r=>S(r,t)).join(" | ");return t.delete(e),n}case "object":{if(t.has(e))return "\u2026";t.add(e);let n=Object.entries(e.props).map(([r,o])=>`${Xe(r)?r:JSON.stringify(r)}${o.optional?"?":""}: ${S(o.type,t)}`);return e.index&&n.push(`[k: ${e.index.key}]: ${S(e.index.value,t)}`),t.delete(e),n.length===0?"{}":`{ ${n.join("; ")} }`}case "fn":{if(t.has(e))return "\u2026";t.add(e);let n=e.params.map(o=>{let i=o.variadic?"...":"",a=o.optional&&!o.variadic?"?":"";return `${i}${o.name}${a}: ${S(o.type,t)}`}).join(", "),r=e.guard?`${e.params[e.guard.param]?.name??`arg${e.guard.param}`} is ${S(e.guard.type,t)}`:S(e.returns,t);return t.delete(e),`(${n}) => ${r}`}case "apply":{if(t.has(e))return "\u2026";t.add(e);let n=e.args.length===0?e.name:`${e.name}<${e.args.map(r=>S(r,t)).join(", ")}>`;return t.delete(e),n}case "overload":{if(t.has(e))return "\u2026";t.add(e);let n=e.signatures.map(r=>S(r,t)).join(" & ");return t.delete(e),n}case "keyof":return `keyof ${S(e.of,t)}`;case "index":return `${S(e.obj,t)}[${S(e.key,t)}]`;case "mapped":{if(t.has(e))return "\u2026";t.add(e);let n=e.optional?"?":"",r=`{ [${e.key} in ${S(e.over,t)}]${n}: ${S(e.body,t)} }`;return t.delete(e),r}case "conditional":{if(t.has(e))return "\u2026";t.add(e);let n=`${S(e.check,t)} extends ${S(e.extends,t)} ? ${S(e.then,t)} : ${S(e.else,t)}`;return t.delete(e),n}case "intersection":return e.of.map(n=>n.t==="union"&&n.of.length>0?`(${S(n,t)})`:S(n,t)).join(" & ");case "returnType":return `ReturnType<${S(e.fn,t)}>`;case "parameters":return `Parameters<${S(e.fn,t)}>`}}function et(e){return e.t==="union"&&e.of.length>0||e.t==="fn"}function tt(e){if(e.length===0)return "value";let t=e[e.length-1];if(/^\d+$/.test(t)){let n=e.slice(0,-1);return n.length?`property '${n.join(".")}' at position ${t}`:`position ${t}`}return `property '${e.join(".")}'`}function nt(e){let t=e.filter(n=>n.kind==="missing");if(t.length&&t.length===e.length){let n=t.map(r=>`'${r.path.join(".")}'`).join(", ");return t.length===1?`property ${n} is missing`:`properties ${n} are missing`}return e.map(n=>`${tt(n.path)}: expected '${S(n.expected)}', got '${S(n.actual)}'`).join("; ")}function L(e,t=new WeakSet){switch(e.t){case "string":case "number":case "boolean":case "null":case "literal":return true;case "array":return t.has(e)?true:(t.add(e),L(B(e.items).type,t));case "tuple":return t.has(e)?true:(t.add(e),e.elements.every(n=>L(B(n).type,t)));case "object":{if(t.has(e))return true;t.add(e);let n=Object.values(e.props).every(o=>L(B(o.type).type,t)),r=!e.index||L(B(e.index.value).type,t);return n&&r}case "union":return t.has(e)?true:(t.add(e),e.of.every(n=>L(n,t)));case "intersection":return t.has(e)?true:(t.add(e),e.of.every(n=>L(n,t)));case "undefined":case "void":case "fn":case "overload":case "keyof":case "index":case "mapped":case "conditional":case "returnType":case "parameters":case "var":case "apply":case "any":case "unknown":return false}}function rt(e,t,n={}){let r=e;for(let o of t){let i=_(r,o,n);if(i===null)return null;r=i;}return {type:r,completions:H(r,n)}}var ot=e=>e==="[]"||/^\d+$/.test(e);function _(e,t,n,r=new Set){if(E(e,n)){let i=g(e);if(r.has(i))return null;r.add(i);let a=_($(e,n),t,n,r);return r.delete(i),a}let o=h(e);if(o!==e)return _(o,t,n,r);switch(e.t){case "any":return e;case "object":{let i=M(e.props,t);return i?i.optional?k([i.type,{t:"undefined"}]):i.type:e.index?.key==="string"?e.index.value:null}case "array":return ot(t)?e.items:null;case "tuple":{let i=e.flags?.findIndex(u=>u!=="req")??-1,a=Number(t);if(!(Number.isInteger(a)&&a>=0))return null;if(i<0)return a<e.elements.length?e.elements[a]:null;if(a<i)return e.elements[a];let l=e.elements.slice(i);return l.length?k(l):null}case "union":{let i=e.of.map(a=>_(a,t,n,r)).filter(a=>a!==null);return i.length?k(i):null}case "intersection":{let i=e.of.map(a=>_(a,t,n,r)).filter(a=>a!==null);return i.length?j({of:i}):null}default:return null}}function H(e,t,n=new WeakSet,r=new Set){if(E(e,t)){let i=g(e);if(r.has(i))return [];r.add(i);let a=H($(e,t),t,n,r);return r.delete(i),a}let o=h(e);if(o!==e)return H(o,t,n,r);switch(e.t){case "object":return Object.entries(e.props).map(([i,a])=>({key:i,type:a.type,optional:!!a.optional}));case "array":return [{key:"[]",type:e.items,optional:false}];case "tuple":return e.elements.map((i,a)=>({key:String(a),type:i,optional:false}));case "union":case "intersection":{if(n.has(e))return [];n.add(e);let i=[],a=new Set;for(let l of e.of)for(let u of H(l,t,n,r))a.has(u.key)||(a.add(u.key),i.push(u));return n.delete(e),i}default:return []}}export{Y as DEFAULT_TYPE_LIMITS,Oe as TYPE_EVAL_DEPTH_LIMIT,P as TypeEvalLimitError,C as UnionTooComplexError,Me as configureTypeLimits,rt as discover,We as equals,$ as expand1,K as flagAt,S as format,nt as formatTypeDiff,G as groundVars,Ke as instantiate,Ne as instantiateLoose,E as isScheme,L as isSerializable,Te as isVariadicTuple,Se as join,Ze as joinAll,A as normalizeTuple,k as normalizeUnion,M as ownProp,Pe as resetTypeLimits,h as resolveTypeOp,U as restIndex,c as s,N as sliceTuple,s as substitute,v as subtype,Le as typeDiff,Ae as typeFeatures,R as typeLimits,x as unify,ee as widen,De as widenInferred,Ce as widenType,B as withoutUndefined};
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tslite/type-core",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "TSLite type-core — o vocabulário Schema + a álgebra de tipos (subtype, unify, format, discover, …), puro e sem dependências. Compartilhado por checker, jsonschema, infer, validate.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"require": "./dist/index.cjs"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/andersondrosa/tslite.git",
|
|
26
|
+
"directory": "packages/type-core"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"schema",
|
|
30
|
+
"types",
|
|
31
|
+
"subtype",
|
|
32
|
+
"unify",
|
|
33
|
+
"structural",
|
|
34
|
+
"typescript"
|
|
35
|
+
],
|
|
36
|
+
"author": "Anderson D. Rosa <andersondrosa@outlook.com>",
|
|
37
|
+
"license": "MIT",
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsup",
|
|
43
|
+
"dev": "tsup --watch",
|
|
44
|
+
"test": "vitest run",
|
|
45
|
+
"test:watch": "vitest",
|
|
46
|
+
"test:coverage": "vitest run --coverage",
|
|
47
|
+
"typecheck": "tsc --noEmit",
|
|
48
|
+
"lint": "eslint src tests",
|
|
49
|
+
"lint:fix": "eslint src tests --fix",
|
|
50
|
+
"clean": "rm -rf dist",
|
|
51
|
+
"format": "prettier --write \"src/**/*.ts\"",
|
|
52
|
+
"format:check": "prettier --check \"src/**/*.ts\""
|
|
53
|
+
}
|
|
54
|
+
}
|