@mionjs/run-types 0.8.4-alpha.0 → 0.8.6
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/cjs/src/jitCompilers/json/toJsCode.cjs +34 -26
- package/.dist/cjs/src/jitCompilers/json/toJsCode.cjs.map +1 -1
- package/.dist/cjs/src/lib/jitFnCompiler.cjs +6 -4
- package/.dist/cjs/src/lib/jitFnCompiler.cjs.map +1 -1
- package/.dist/cjs/src/lib/jitFnCompiler.d.ts +2 -2
- package/.dist/cjs/src/nodes/function/function.cjs +22 -18
- package/.dist/cjs/src/nodes/function/function.cjs.map +1 -1
- package/.dist/cjs/src/nodes/function/function.d.ts +1 -0
- package/.dist/esm/src/jitCompilers/json/toJsCode.js +34 -26
- package/.dist/esm/src/jitCompilers/json/toJsCode.js.map +1 -1
- package/.dist/esm/src/lib/jitFnCompiler.d.ts +2 -2
- package/.dist/esm/src/lib/jitFnCompiler.js +6 -4
- package/.dist/esm/src/lib/jitFnCompiler.js.map +1 -1
- package/.dist/esm/src/nodes/function/function.d.ts +1 -0
- package/.dist/esm/src/nodes/function/function.js +22 -18
- package/.dist/esm/src/nodes/function/function.js.map +1 -1
- package/package.json +3 -3
|
@@ -6,14 +6,6 @@ const src_constants_functions = require("../../constants.functions.cjs");
|
|
|
6
6
|
const src_lib_utils = require("../../lib/utils.cjs");
|
|
7
7
|
const src_jitCompilers_json_stringifyJson = require("./stringifyJson.cjs");
|
|
8
8
|
const src_runTypesPureFns = require("../../run-types-pure-fns.cjs");
|
|
9
|
-
function getParentSiblingNames(srcMS) {
|
|
10
|
-
let parent = srcMS.parent;
|
|
11
|
-
if (parent?.kind === type.ReflectionKind.propertySignature) parent = parent.parent;
|
|
12
|
-
if (parent?.kind !== type.ReflectionKind.objectLiteral) return void 0;
|
|
13
|
-
const types = parent.types;
|
|
14
|
-
if (!types) return void 0;
|
|
15
|
-
return new Set(types.map((t) => t.name).filter((n) => n !== void 0));
|
|
16
|
-
}
|
|
17
9
|
function createToCodeCompiler() {
|
|
18
10
|
const fnID = src_constants_functions.JitFunctions.toJSCode.id;
|
|
19
11
|
const visitJsonStringify = src_jitCompilers_json_stringifyJson.createStringifyCompiler(fnID);
|
|
@@ -39,11 +31,14 @@ function createToCodeCompiler() {
|
|
|
39
31
|
if (isCompilingFnProp(rt, comp)) {
|
|
40
32
|
return { code: `'undefined'`, type: "E" };
|
|
41
33
|
} else if (isCompilingClosureFn(rt, comp)) {
|
|
34
|
+
const parentRef = getParentObjRef(srcMS, comp);
|
|
42
35
|
const isPureFn = rt.getChildVarName(comp) === "createPureFn";
|
|
43
|
-
const fnName = isPureFn ? `${
|
|
44
|
-
const fnCode = `${
|
|
45
|
-
const paramList = isPureFn ? `${
|
|
36
|
+
const fnName = isPureFn ? `${parentRef}.fnName` : `${parentRef}.jitFnHash`;
|
|
37
|
+
const fnCode = `${parentRef}.code`;
|
|
38
|
+
const paramList = isPureFn ? `${parentRef}.paramNames.join(',')` : `'utl'`;
|
|
46
39
|
const closureCode = `'function get_'+${fnName}+'('+${paramList}+'){'+${fnCode}+'}'`;
|
|
40
|
+
const isWrapped = parentRef !== comp.vλl;
|
|
41
|
+
if (isWrapped) return { code: closureCode, type: "E" };
|
|
47
42
|
return { code: `'${safeName}:'+${closureCode}${sep}`, type: "E" };
|
|
48
43
|
} else if (rt.src.subKind === src_constants_kind.ReflectionSubKind.params) {
|
|
49
44
|
const paramsCode = visitJsonStringify(rt, comp);
|
|
@@ -96,21 +91,6 @@ function createToCodeCompiler() {
|
|
|
96
91
|
return visitJsonStringify(runType, comp);
|
|
97
92
|
}
|
|
98
93
|
}
|
|
99
|
-
function isCompilingClosureFn(runType, comp) {
|
|
100
|
-
const childName = runType.getChildVarName(comp);
|
|
101
|
-
if (childName !== "createJitFn" && childName !== "createPureFn") return false;
|
|
102
|
-
const siblings = getParentSiblingNames(runType.src);
|
|
103
|
-
if (!siblings) return false;
|
|
104
|
-
if (!siblings.has("code")) return false;
|
|
105
|
-
if (childName === "createJitFn") return siblings.has("jitFnHash");
|
|
106
|
-
return siblings.has("bodyHash");
|
|
107
|
-
}
|
|
108
|
-
function isCompilingFnProp(runType, comp) {
|
|
109
|
-
if (runType.getChildVarName(comp) !== "fn") return false;
|
|
110
|
-
const siblings = getParentSiblingNames(runType.src);
|
|
111
|
-
if (!siblings) return false;
|
|
112
|
-
return siblings.has("code") && (siblings.has("createJitFn") || siblings.has("createPureFn"));
|
|
113
|
-
}
|
|
114
94
|
return compileToCode;
|
|
115
95
|
}
|
|
116
96
|
let lazyFn = void 0;
|
|
@@ -118,6 +98,34 @@ function emitToCode(runType, comp) {
|
|
|
118
98
|
if (!lazyFn) lazyFn = createToCodeCompiler();
|
|
119
99
|
return lazyFn(runType, comp);
|
|
120
100
|
}
|
|
101
|
+
function getParentSiblingNames(srcMS) {
|
|
102
|
+
let parent = srcMS.parent;
|
|
103
|
+
if (parent?.kind === type.ReflectionKind.propertySignature) parent = parent.parent;
|
|
104
|
+
if (parent?.kind !== type.ReflectionKind.objectLiteral) return void 0;
|
|
105
|
+
const types = parent.types;
|
|
106
|
+
if (!types) return void 0;
|
|
107
|
+
return new Set(types.map((t) => t.name).filter((n) => n !== void 0));
|
|
108
|
+
}
|
|
109
|
+
function isCompilingClosureFn(runType, comp) {
|
|
110
|
+
const childName = runType.getChildVarName(comp);
|
|
111
|
+
if (childName !== "createJitFn" && childName !== "createPureFn") return false;
|
|
112
|
+
const siblings = getParentSiblingNames(runType.src);
|
|
113
|
+
if (!siblings) return false;
|
|
114
|
+
if (childName === "createJitFn") return siblings.has("jitFnHash");
|
|
115
|
+
return siblings.has("bodyHash");
|
|
116
|
+
}
|
|
117
|
+
function isCompilingFnProp(runType, comp) {
|
|
118
|
+
if (runType.getChildVarName(comp) !== "fn") return false;
|
|
119
|
+
const siblings = getParentSiblingNames(runType.src);
|
|
120
|
+
if (!siblings) return false;
|
|
121
|
+
return siblings.has("createJitFn") && siblings.has("jitFnHash") || siblings.has("createPureFn") && siblings.has("bodyHash");
|
|
122
|
+
}
|
|
123
|
+
function getParentObjRef(_srcMS, comp) {
|
|
124
|
+
const stack = comp.stack;
|
|
125
|
+
const parentItem = stack[stack.length - 2];
|
|
126
|
+
if (parentItem && parentItem.vλl !== comp.vλl) return parentItem.vλl;
|
|
127
|
+
return comp.vλl;
|
|
128
|
+
}
|
|
121
129
|
exports.createToCodeCompiler = createToCodeCompiler;
|
|
122
130
|
exports.emitToCode = emitToCode;
|
|
123
131
|
//# sourceMappingURL=toJsCode.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toJsCode.cjs","sources":["../../../../../src/jitCompilers/json/toJsCode.ts"],"sourcesContent":["/* ########\n * 2025 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {JitCode} from '../../types.ts';\nimport type {BaseRunType} from '../../lib/baseRunTypes.ts';\nimport type {ClassRunType} from '../../nodes/collection/class.ts';\nimport type {MethodSignatureRunType} from '../../nodes/member/methodSignature.ts';\nimport type {IterableRunType} from '../../nodes/native/Iterable.ts';\nimport {ReflectionKind, type TypeMethodSignature, type TypeObjectLiteral, type TypePropertySignature} from '@deepkit/type';\nimport {ReflectionSubKind} from '../../constants.kind.ts';\nimport {JitFunctions} from '../../constants.functions.ts';\nimport {JitFnCompiler} from '../../lib/jitFnCompiler.ts';\nimport {isSafePropName} from '../../lib/utils.ts';\nimport {createStringifyCompiler, createStringifyIterable} from './stringifyJson.ts';\nimport {cpf_sanitizeCompiledFn} from '../../run-types-pure-fns.ts';\n\n/** Gets sibling property/method names from a MethodSignature's parent ObjectLiteral */\nfunction getParentSiblingNames(srcMS: TypeMethodSignature): Set<string | number | symbol> | undefined {\n let parent = srcMS.parent as any;\n // Handle deepkit bug where parent can be TypePropertySignature instead of TypeObjectLiteral\n if (parent?.kind === ReflectionKind.propertySignature) parent = parent.parent;\n if (parent?.kind !== ReflectionKind.objectLiteral) return undefined;\n const types = (parent as TypeObjectLiteral).types;\n if (!types) return undefined;\n return new Set(types.map((t: any) => t.name).filter((n: any) => n !== undefined));\n}\n\nexport function createToCodeCompiler() {\n const fnID = JitFunctions.toJSCode.id;\n const visitJsonStringify = createStringifyCompiler(fnID);\n const visitJsonStringifyIterable = createStringifyIterable(fnID);\n\n /**\n * Compiles jit code to generate JavaScript code from data structures that match a Type.\n * Process is similar to transform JS to JSON, but with few differences.\n *\n * 1 - jitFunctions and pureFunctions are emitted as src code\n * 2 - Some native classes are supported and initialized using the new operator, ie: new Map(<data>), new Set(<data>), new Date(<data>), etc...\n *\n * THIS IS MOSTLY USED INTERNALLY FOR AOT CODE GENERATION AND A VERY BASIC IMPLEMENTATION.\n * !!! NOT INTENDED FOR PUBLIC USE !!!\n */\n function compileToCode(runType: BaseRunType, comp: JitFnCompiler): JitCode {\n const src = runType.src;\n const kind = src.kind;\n\n switch (kind) {\n // ###################### ATOMIC RUNTYPES ######################\n case ReflectionKind.undefined:\n return {code: `'undefined'`, type: 'E'};\n case ReflectionKind.symbol:\n return {code: `'Symbol('+'\"'+${comp.vλl}.description+'\"'+')'`, type: 'E'};\n // ###################### MEMBER RUNTYPES ######################\n case ReflectionKind.methodSignature: {\n const rt = runType as MethodSignatureRunType;\n const srcMS = src as TypeMethodSignature;\n const accessor = srcMS.name;\n const name = String(accessor);\n const isSafe = isSafePropName(accessor);\n const safeName = isSafe ? name : JSON.stringify(name);\n const sep = rt.skipCommas ? '' : '+\",\"';\n if (isCompilingFnProp(rt, comp)) {\n // special case for JitFunctions/PureFunctions that we know should return undefined for fn param\n return {code: `'undefined'`, type: 'E'};\n } else if (isCompilingClosureFn(rt, comp)) {\n // special case for JitFunctions/PureFunctions where we generate the fn from the data instead of fn.toString()\n const isPureFn = rt.getChildVarName(comp) === 'createPureFn';\n const fnName = isPureFn ? `${comp.vλl}.fnName` : `${comp.vλl}.jitFnHash`;\n const fnCode = `${comp.vλl}.code`;\n const paramList = isPureFn ? `${comp.vλl}.paramNames.join(',')` : `'utl'`;\n const closureCode = `'function get_'+${fnName}+'('+${paramList}+'){'+${fnCode}+'}'`;\n return {code: `'${safeName}:'+${closureCode}${sep}`, type: 'E'};\n } else if (rt.src.subKind === ReflectionSubKind.params) {\n const paramsCode = visitJsonStringify(rt, comp);\n if (rt.isOptional())\n return {\n code: `(${comp.getChildVλl()} === undefined ? \"\" : '${safeName}:'+${paramsCode?.code}${sep})`,\n type: 'E',\n };\n return {code: `'${safeName}:'+${paramsCode?.code}${sep}`, type: 'E'};\n } else {\n const fnName = comp.addPureFunction(cpf_sanitizeCompiledFn);\n const parent = srcMS.parent as any as TypePropertySignature;\n\n // in some scenarios the parent is a propertySignature instead the Expected TypeObjectLiteral so we have to handle that\n // this seems to be a deepkit bug when using omit and then redefining the property @see SrcCodeJitCompiledFn type\n const isDuplicatedChild = parent?.kind === ReflectionKind.propertySignature && parent?.name === srcMS.name;\n if (isDuplicatedChild) return {code: `${fnName}(${comp.vλl}.toString())`, type: 'E'};\n const accessorCode = isSafe ? `.${safeName}` : `[${safeName}]`;\n const fnCode = `${fnName}(${comp.vλl}${accessorCode}.toString())`;\n if (rt.isOptional())\n return {code: `(${comp.getChildVλl()} === undefined ? \"\" : '${safeName}:'+${fnCode}${sep})`, type: 'E'};\n return {code: `'${safeName}:'+${fnCode}${sep}`, type: 'E'};\n }\n }\n case ReflectionKind.function:\n case ReflectionKind.method:\n case ReflectionKind.callSignature:\n if (runType.src.subKind === ReflectionSubKind.params) {\n return visitJsonStringify(runType, comp);\n } else {\n // TODO: we are relying in fn.toString() to generate code, this might not work properly in all js engines\n return {code: `${comp.vλl}.toString()`, type: 'E'};\n }\n // ###################### COLLECTION RUNTYPES ######################\n case ReflectionKind.class: {\n switch (runType.src.subKind) {\n case ReflectionSubKind.date:\n return {code: `'new Date('+${visitJsonStringify(runType, comp).code}+')'`, type: 'E'};\n case ReflectionSubKind.map: {\n return visitJsonStringifyIterable(runType as unknown as IterableRunType, comp, 'new Map(', ')');\n }\n case ReflectionSubKind.set: {\n return visitJsonStringifyIterable(runType as unknown as IterableRunType, comp, 'new Set(', ')');\n }\n case ReflectionSubKind.nonSerializable:\n throw new Error(`Can not generate code for Non Serializable types.`);\n default: {\n const rt = runType as unknown as ClassRunType;\n throw new Error(`Can not generate code for classes. Class: ${rt.getClassName()}`);\n }\n }\n }\n default:\n return visitJsonStringify(runType, comp);\n }\n }\n\n /** Detects if we're compiling a createJitFn or createPureFn closure by checking sibling properties */\n function isCompilingClosureFn(runType: MethodSignatureRunType, comp: JitFnCompiler): boolean {\n const childName = runType.getChildVarName(comp);\n if (childName !== 'createJitFn' && childName !== 'createPureFn') return false;\n const siblings = getParentSiblingNames(runType.src as TypeMethodSignature);\n if (!siblings) return false;\n if (!siblings.has('code')) return false;\n if (childName === 'createJitFn') return siblings.has('jitFnHash');\n return siblings.has('bodyHash'); // createPureFn\n }\n\n /** Detects if we're compiling the fn property of a JitCompiledFn or CompiledPureFunction */\n function isCompilingFnProp(runType: MethodSignatureRunType, comp: JitFnCompiler): boolean {\n if (runType.getChildVarName(comp) !== 'fn') return false;\n const siblings = getParentSiblingNames(runType.src as TypeMethodSignature);\n if (!siblings) return false;\n return siblings.has('code') && (siblings.has('createJitFn') || siblings.has('createPureFn'));\n }\n\n return compileToCode;\n}\n\n// lazy loading as this function wont be used often just for (AOT)\n// TODO move to async code loading (but this would need a big refactor of the router)\nlet lazyFn: undefined | ((runType: BaseRunType, comp: JitFnCompiler) => JitCode) = undefined;\nexport function emitToCode(runType: BaseRunType, comp: JitFnCompiler): JitCode {\n if (!lazyFn) lazyFn = createToCodeCompiler();\n return lazyFn(runType, comp);\n}\n"],"names":["ReflectionKind","JitFunctions","createStringifyCompiler","createStringifyIterable","isSafePropName","ReflectionSubKind","cpf_sanitizeCompiledFn"],"mappings":";;;;;;;;AAqBA,SAAS,sBAAsB,OAAuE;AAClG,MAAI,SAAS,MAAM;AAEnB,MAAI,QAAQ,SAASA,KAAAA,eAAe,4BAA4B,OAAO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W,sBAAsB,QAAQ,GAA0B;AACzE,QAAI,CAAC,SAAU,QAAO;AACtB,WAAO,SAAS,IAAI,MAAM,MAAM,SAAS,IAAI,aAAa,KAAK,SAAS,IAAI,cAAc;AAAA,EAC9F;AAEA,SAAO;AACX;AAIA,IAAI,SAA+E;AAC5E,SAAS,WAAW,SAAsB,MAA8B;AAC3E,MAAI,CAAC,OAAQ,UAAS,qBAAA;AACtB,SAAO,OAAO,SAAS,IAAI;AAC/B;;;"}
|
|
1
|
+
{"version":3,"file":"toJsCode.cjs","sources":["../../../../../src/jitCompilers/json/toJsCode.ts"],"sourcesContent":["/* ########\n * 2025 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {JitCode} from '../../types.ts';\nimport type {BaseRunType} from '../../lib/baseRunTypes.ts';\nimport type {ClassRunType} from '../../nodes/collection/class.ts';\nimport type {MethodSignatureRunType} from '../../nodes/member/methodSignature.ts';\nimport type {IterableRunType} from '../../nodes/native/Iterable.ts';\nimport {ReflectionKind, type TypeMethodSignature, type TypeObjectLiteral, type TypePropertySignature} from '@deepkit/type';\nimport {ReflectionSubKind} from '../../constants.kind.ts';\nimport {JitFunctions} from '../../constants.functions.ts';\nimport {JitFnCompiler} from '../../lib/jitFnCompiler.ts';\nimport {isSafePropName} from '../../lib/utils.ts';\nimport {createStringifyCompiler, createStringifyIterable} from './stringifyJson.ts';\nimport {cpf_sanitizeCompiledFn} from '../../run-types-pure-fns.ts';\n\nexport function createToCodeCompiler() {\n const fnID = JitFunctions.toJSCode.id;\n const visitJsonStringify = createStringifyCompiler(fnID);\n const visitJsonStringifyIterable = createStringifyIterable(fnID);\n\n /**\n * Compiles jit code to generate JavaScript code from data structures that match a Type.\n * Process is similar to transform JS to JSON, but with few differences.\n *\n * 1 - jitFunctions and pureFunctions are emitted as src code\n * 2 - Some native classes are supported and initialized using the new operator, ie: new Map(<data>), new Set(<data>), new Date(<data>), etc...\n *\n * THIS IS MOSTLY USED INTERNALLY FOR AOT CODE GENERATION AND A VERY BASIC IMPLEMENTATION.\n * !!! NOT INTENDED FOR PUBLIC USE !!!\n */\n function compileToCode(runType: BaseRunType, comp: JitFnCompiler): JitCode {\n const src = runType.src;\n const kind = src.kind;\n\n switch (kind) {\n // ###################### ATOMIC RUNTYPES ######################\n case ReflectionKind.undefined:\n return {code: `'undefined'`, type: 'E'};\n case ReflectionKind.symbol:\n return {code: `'Symbol('+'\"'+${comp.vλl}.description+'\"'+')'`, type: 'E'};\n // ###################### MEMBER RUNTYPES ######################\n case ReflectionKind.methodSignature: {\n const rt = runType as MethodSignatureRunType;\n const srcMS = src as TypeMethodSignature;\n const accessor = srcMS.name;\n const name = String(accessor);\n const isSafe = isSafePropName(accessor);\n const safeName = isSafe ? name : JSON.stringify(name);\n const sep = rt.skipCommas ? '' : '+\",\"';\n if (isCompilingFnProp(rt, comp)) {\n // special case for JitFunctions/PureFunctions that we know should return undefined for fn param\n return {code: `'undefined'`, type: 'E'};\n } else if (isCompilingClosureFn(rt, comp)) {\n // special case for JitFunctions/PureFunctions where we generate the fn from the data instead of fn.toString()\n // When using Pick/Omit, deepkit wraps methodSignature in a propertySignature,\n // so comp.vλl points to the fn value instead of the parent object. Use getParentObjRef to get the right ref.\n const parentRef = getParentObjRef(srcMS, comp);\n const isPureFn = rt.getChildVarName(comp) === 'createPureFn';\n const fnName = isPureFn ? `${parentRef}.fnName` : `${parentRef}.jitFnHash`;\n const fnCode = `${parentRef}.code`;\n const paramList = isPureFn ? `${parentRef}.paramNames.join(',')` : `'utl'`;\n const closureCode = `'function get_'+${fnName}+'('+${paramList}+'){'+${fnCode}+'}'`;\n // When wrapped in a propertySignature (Pick/Omit types), the outer handler already emits the property name\n const isWrapped = parentRef !== comp.vλl;\n if (isWrapped) return {code: closureCode, type: 'E'};\n return {code: `'${safeName}:'+${closureCode}${sep}`, type: 'E'};\n } else if (rt.src.subKind === ReflectionSubKind.params) {\n const paramsCode = visitJsonStringify(rt, comp);\n if (rt.isOptional())\n return {\n code: `(${comp.getChildVλl()} === undefined ? \"\" : '${safeName}:'+${paramsCode?.code}${sep})`,\n type: 'E',\n };\n return {code: `'${safeName}:'+${paramsCode?.code}${sep}`, type: 'E'};\n } else {\n const fnName = comp.addPureFunction(cpf_sanitizeCompiledFn);\n const parent = srcMS.parent as any as TypePropertySignature;\n\n // in some scenarios the parent is a propertySignature instead the Expected TypeObjectLiteral so we have to handle that\n // this seems to be a deepkit bug when using omit and then redefining the property @see SrcCodeJitCompiledFn type\n const isDuplicatedChild = parent?.kind === ReflectionKind.propertySignature && parent?.name === srcMS.name;\n if (isDuplicatedChild) return {code: `${fnName}(${comp.vλl}.toString())`, type: 'E'};\n const accessorCode = isSafe ? `.${safeName}` : `[${safeName}]`;\n const fnCode = `${fnName}(${comp.vλl}${accessorCode}.toString())`;\n if (rt.isOptional())\n return {code: `(${comp.getChildVλl()} === undefined ? \"\" : '${safeName}:'+${fnCode}${sep})`, type: 'E'};\n return {code: `'${safeName}:'+${fnCode}${sep}`, type: 'E'};\n }\n }\n case ReflectionKind.function:\n case ReflectionKind.method:\n case ReflectionKind.callSignature:\n if (runType.src.subKind === ReflectionSubKind.params) {\n return visitJsonStringify(runType, comp);\n } else {\n // TODO: we are relying in fn.toString() to generate code, this might not work properly in all js engines\n return {code: `${comp.vλl}.toString()`, type: 'E'};\n }\n // ###################### COLLECTION RUNTYPES ######################\n case ReflectionKind.class: {\n switch (runType.src.subKind) {\n case ReflectionSubKind.date:\n return {code: `'new Date('+${visitJsonStringify(runType, comp).code}+')'`, type: 'E'};\n case ReflectionSubKind.map: {\n return visitJsonStringifyIterable(runType as unknown as IterableRunType, comp, 'new Map(', ')');\n }\n case ReflectionSubKind.set: {\n return visitJsonStringifyIterable(runType as unknown as IterableRunType, comp, 'new Set(', ')');\n }\n case ReflectionSubKind.nonSerializable:\n throw new Error(`Can not generate code for Non Serializable types.`);\n default: {\n const rt = runType as unknown as ClassRunType;\n throw new Error(`Can not generate code for classes. Class: ${rt.getClassName()}`);\n }\n }\n }\n default:\n return visitJsonStringify(runType, comp);\n }\n }\n\n return compileToCode;\n}\n\n// lazy loading as this function wont be used often just for (AOT)\n// TODO move to async code loading (but this would need a big refactor of the router)\nlet lazyFn: undefined | ((runType: BaseRunType, comp: JitFnCompiler) => JitCode) = undefined;\nexport function emitToCode(runType: BaseRunType, comp: JitFnCompiler): JitCode {\n if (!lazyFn) lazyFn = createToCodeCompiler();\n return lazyFn(runType, comp);\n}\n\n/** Gets sibling property/method names from a MethodSignature's parent ObjectLiteral */\nfunction getParentSiblingNames(srcMS: TypeMethodSignature): Set<string | number | symbol> | undefined {\n let parent = srcMS.parent as any;\n // Handle deepkit bug where parent can be TypePropertySignature instead of TypeObjectLiteral\n if (parent?.kind === ReflectionKind.propertySignature) parent = parent.parent;\n if (parent?.kind !== ReflectionKind.objectLiteral) return undefined;\n const types = (parent as TypeObjectLiteral).types;\n if (!types) return undefined;\n return new Set(types.map((t: any) => t.name).filter((n: any) => n !== undefined));\n}\n\n/** Detects if we're compiling a createJitFn or createPureFn closure by checking sibling properties */\nfunction isCompilingClosureFn(runType: MethodSignatureRunType, comp: JitFnCompiler): boolean {\n const childName = runType.getChildVarName(comp);\n if (childName !== 'createJitFn' && childName !== 'createPureFn') return false;\n const siblings = getParentSiblingNames(runType.src as TypeMethodSignature);\n if (!siblings) return false;\n if (childName === 'createJitFn') return siblings.has('jitFnHash');\n return siblings.has('bodyHash'); // createPureFn\n}\n\n/** Detects if we're compiling the fn property of a JitCompiledFn or CompiledPureFunction */\nfunction isCompilingFnProp(runType: MethodSignatureRunType, comp: JitFnCompiler): boolean {\n if (runType.getChildVarName(comp) !== 'fn') return false;\n const siblings = getParentSiblingNames(runType.src as TypeMethodSignature);\n if (!siblings) return false;\n return (\n (siblings.has('createJitFn') && siblings.has('jitFnHash')) || (siblings.has('createPureFn') && siblings.has('bodyHash'))\n );\n}\n\n/**\n * Gets the runtime reference to the parent object that contains the methodSignature.\n * When using Pick/Omit, deepkit wraps methodSignature in a propertySignature,\n * causing comp.vλl to point to the fn value (e.g. `obj.createJitFn`) instead of the parent object (`obj`).\n * Detects this by comparing the current vλl with the previous stack item's vλl.\n * If they differ, we are inside a propertySignature wrapper and use the parent stack item's vλl.\n */\nfunction getParentObjRef(_srcMS: TypeMethodSignature, comp: JitFnCompiler): string {\n const stack = comp.stack;\n const parentItem = stack[stack.length - 2];\n if (parentItem && parentItem.vλl !== comp.vλl) return parentItem.vλl;\n return comp.vλl;\n}\n"],"names":["JitFunctions","createStringifyCompiler","createStringifyIterable","ReflectionKind","isSafePropName","ReflectionSubKind","cpf_sanitizeCompiledFn"],"mappings":";;;;;;;;AAoBO,SAAS,uBAAuB;AACnC,QAAM,OAAOA,qCAAa,SAAS;AACnC,QAAM,qBAAqBC,oCAAAA,wBAAwB,IAAI;AACvD,QAAM,6BAA6BC,oCAAAA,wBAAwB,IAAI;AAY/D,WAAS,cAAc,SAAsB,MAA8B;AACvE,UAAM,MAAM,QAAQ;AACpB,UAAM,OAAO,IAAI;AAEjB,YAAQ,MAAA;AAAA;AAAA,MAEJ,KAAKC,KAAAA,eAAe;AAChB,eAAO,EAAC,MAAM,eAAe,MAAM,IAAA;AAAA,MACvC,KAAKA,KAAAA,eAAe;AAChB,eAAO,EAAC,MAAM,iBAAiB,KAAK,GAAG,wBAAwB,MAAM,IAAA;AAAA;AAAA,MAEzE,KAAKA,KAAAA,eAAe,iBAAiB;AACjC,cAAM,KAAK;AACX,cAAM,QAAQ;AACd,cAAM,WAAW,MAAM;AACvB,cAAM,OAAO,OAAO,QAAQ;AAC5B,cAAM,SAASC,cAAAA,eAAe,QAAQ;AACtC,cAAM,WAAW,SAAS,OAAO,KAAK,UAAU,IAAI;AACpD,cAAM,MAAM,GAAG,aAAa,KAAK;AACjC,YAAI,kBAAkB,IAAI,IAAI,GAAG;AAE7B,iBAAO,EAAC,MAAM,eAAe,MAAM,IAAA;AAAA,QACvC,WAAW,qBAAqB,IAAI,IAAI,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O,OAAO,SAAS,IAAI;AAC/B;AAGA,SAAS,sBAAsB,OAAuE;AAClG,MAAI,SAAS,MAAM;AAEnB,MAAI,QAAQ,SAASF,KAAAA,eAAe,4BAA4B,OAAO;AACvE,MAAI,QAAQ,SAASA,oBAAe,cAAe,QAAO;AAC1D,QAAM,QAAS,OAA6B;AAC5C,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,IAAI,IAAI,MAAM,IAAI,CAAC,MAAW,EAAE,IAAI,EAAE,OAAO,CAAC,MAAW,MAAM,MAAS,CAAC;AACpF;AAGA,SAAS,qBAAqB,SAAiC,MAA8B;AACzF,QAAM,YAAY,QAAQ,gBAAgB,IAAI;AAC9C,MAAI,cAAc,iBAAiB,cAAc,eAAgB,QAAO;AACxE,QAAM,WAAW,sBAAsB,QAAQ,GAA0B;AACzE,MAAI,CAAC,SAAU,QAAO;AACtB,MAAI,cAAc,cAAe,QAAO,SAAS,IAAI,WAAW;AAChE,SAAO,SAAS,IAAI,UAAU;AAClC;AAGA,SAAS,kBAAkB,SAAiC,MAA8B;AACtF,MAAI,QAAQ,gBAAgB,IAAI,MAAM,KAAM,QAAO;AACnD,QAAM,WAAW,sBAAsB,QAAQ,GAA0B;AACzE,MAAI,CAAC,SAAU,QAAO;AACtB,SACK,SAAS,IAAI,aAAa,KAAK,SAAS,IAAI,WAAW,KAAO,SAAS,IAAI,cAAc,KAAK,SAAS,IAAI,UAAU;AAE9H;AASA,SAAS,gBAAgB,QAA6B,MAA6B;AAC/E,QAAM,QAAQ,KAAK;AACnB,QAAM,aAAa,MAAM,MAAM,SAAS,CAAC;AACzC,MAAI,cAAc,WAAW,QAAQ,KAAK,YAAY,WAAW;AACjE,SAAO,KAAK;AAChB;;;"}
|
|
@@ -59,8 +59,8 @@ class BaseFnCompiler {
|
|
|
59
59
|
*/
|
|
60
60
|
isNoop = false;
|
|
61
61
|
/** The list of all jit functions that are used by this function and it's children. */
|
|
62
|
-
jitDependencies
|
|
63
|
-
pureFnDependencies
|
|
62
|
+
jitDependencies;
|
|
63
|
+
pureFnDependencies;
|
|
64
64
|
/** The list of types being compiled.*/
|
|
65
65
|
stack = [];
|
|
66
66
|
popItem;
|
|
@@ -181,7 +181,8 @@ ${fnCode}`);
|
|
|
181
181
|
}
|
|
182
182
|
updateDependencies(childComp) {
|
|
183
183
|
if (childComp.isNoop) return;
|
|
184
|
-
if (this.jitDependencies
|
|
184
|
+
if (this.jitDependencies?.includes(childComp.jitFnHash)) return;
|
|
185
|
+
if (!this.jitDependencies) this.jitDependencies = [];
|
|
185
186
|
this.jitDependencies.push(childComp.jitFnHash);
|
|
186
187
|
}
|
|
187
188
|
removeFromJitCache() {
|
|
@@ -498,7 +499,8 @@ ${fnCode}`);
|
|
|
498
499
|
`Pure function with name ${fnName} can not be added as jit dependency in namespace ${namespace}, be sure to register the pure function first by calling getJitUtils().addPureFn()`
|
|
499
500
|
);
|
|
500
501
|
const key = `${namespace}::${fnName}`;
|
|
501
|
-
if (this.pureFnDependencies
|
|
502
|
+
if (this.pureFnDependencies?.includes(key)) return;
|
|
503
|
+
if (!this.pureFnDependencies) this.pureFnDependencies = [];
|
|
502
504
|
this.pureFnDependencies.push(key);
|
|
503
505
|
}
|
|
504
506
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jitFnCompiler.cjs","sources":["../../../../src/lib/jitFnCompiler.ts"],"sourcesContent":["/* ########\n * 2024 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {JitCompiledFn, JitCompiledFnData, JitFnArgs, JITUtils, CompiledPureFunction} from '@mionjs/core';\nimport {MAX_STACK_DEPTH, getJitUtils, quickHash} from '@mionjs/core';\nimport type {TypeFunction} from '@deepkit/type';\nimport type {Mutable, JitFnID, StrNumber, JitCode, RunTypeOptions, JitCompilerOpts, RunTypeChildAccessor} from '../types.ts';\nimport type {BaseRunType} from './baseRunTypes.ts';\nimport type {BaseRunTypeFormat} from './baseRunTypeFormat.ts';\nimport {getReflectionName, type AnyKindName} from '../constants.kind.ts';\nimport {maxStackErrorMessage, JIT_STACK_TRACE_MESSAGE} from '../constants.ts';\nimport {type CodeType, CodeTypes, jitErrorArgs, type JitFnSettings} from '../constants.functions.ts';\nimport {getJITFnName, getJitFnSettings} from './jitFnsRegistry.ts';\nimport {JitFunctions} from '../constants.functions.ts';\nimport {isChildAccessorType, isFunctionParamsRunType, isJitErrorsCompiler} from './guards.ts';\nimport {addFullStop, getJitFnArgCallVarName, toLiteral, toLiteralInContext} from './utils.ts';\nimport {getRunTypeFormat} from './formats.ts';\nimport {emitJsonStringify} from '../jitCompilers/json/stringifyJson.ts';\nimport {emitToBinary} from '../jitCompilers/binary/toBinary.ts';\nimport {emitFromBinary} from '../jitCompilers/binary/fromBinary.ts';\nimport {emitToCode} from '../jitCompilers/json/toJsCode.ts';\nimport {createJitFunction, getJITFnHash} from './createJitFunction.ts';\nimport {cpf_newRunTypeErr, cpf_formatErr} from '../run-types-pure-fns.ts';\n\nconst RB = CodeTypes.returnBlock;\nconst S = CodeTypes.statement;\nconst E = CodeTypes.expression;\n\nexport type StackItem = {\n /** current compile stack full variable accessor */\n vλl: string;\n /** current compile stack variable accessor */\n rt: BaseRunType;\n /** if should call a dependency instead inline code, then this would contain the id of the dependency to call */\n dependencyId?: string;\n staticPath?: StrNumber[];\n};\n\nexport type JitCompilerLike = BaseFnCompiler | JitCompiledFnData;\n\n/**\n * Program to compile a Jit function to be used at runtime.\n * These jit functions are used to validate, serialize, deserialize, etc... based on runTypes.\n */\nexport class BaseFnCompiler<FnArgsNames extends JitFnArgs = JitFnArgs, ID extends JitFnID = any>\n implements JitCompiledFnData, JitCompilerOpts\n{\n // !!! DO NOT MODIFY METHOD WITHOUT REVIEWING JIT CODE INVOCATIONS!!!\n /** The Jit Generated function once the compilation is finished */\n readonly fn: ((...args: any[]) => any) | undefined;\n readonly createJitFn: ((utl: JITUtils) => (...args: any[]) => any) | undefined;\n private isCompiled = false;\n\n constructor(\n public readonly rootType: BaseRunType,\n // the id of the function to be compiled (isType, typeErrors, prepareForJson, restoreFromJson, etc)\n public readonly fnID: ID,\n jitFnSettings: JitFnSettings,\n public readonly parentCompiler?: BaseFnCompiler,\n jitFnHash?: string,\n typeID?: StrNumber,\n public readonly opts: RunTypeOptions = {}\n ) {\n this.typeName = this.rootType.getTypeName();\n this.jitFnHash = jitFnHash || getJITFnHash(this.fnID, this.rootType, opts);\n this.typeID = typeID || this.rootType.getTypeID();\n this.args = {...jitFnSettings.jitArgs} as FnArgsNames;\n this.defaultParamValues = {...jitFnSettings.jitDefaultArgs} as FnArgsNames;\n this.returnName = jitFnSettings.returnName;\n if (this.args.vλl) this.vλl = this.args.vλl;\n // At the time of adding this compiler to the jit cache, the fn is undefined which is technically not allowed\n // but this prevents issues with circular types and loading order of jit dependencies\n getJitUtils().addToJitCache(this as JitCompiledFn);\n validateCompilerOptions(opts);\n }\n readonly typeName: string;\n readonly typeID: StrNumber;\n readonly jitFnHash: string;\n readonly args: FnArgsNames;\n readonly defaultParamValues: FnArgsNames;\n readonly returnName: string;\n\n /** Alternative arguments to use when calling a child function */\n readonly childrenCallArgs: Partial<Record<JitFnID, Partial<JitFnArgs>>> = {};\n\n /** Code for the jit function. after the operation has been compiled */\n readonly code: string = '';\n /** Code for the context function enclosing the jit function.\n * This can be used to initialize constant or some other things that will be required across all invocation.\n * By default this contains constants for the direct dependencies of the jit function.\n * */\n readonly contextCodeItems = new Map<string, string>();\n /**\n * This flag is set to true when the result of a jit compilation is a no operation (empty function).\n * Some jit compiled functions could execute no operations (ie: string, boolean and numbers does not require prepareForJson/restoreFromJson)\n */\n readonly isNoop?: boolean = false;\n /** The list of all jit functions that are used by this function and it's children. */\n readonly jitDependencies: Array<string> = [];\n readonly pureFnDependencies: Array<string> = [];\n /** The list of types being compiled.*/\n readonly stack: StackItem[] = [];\n popItem: StackItem | undefined;\n /** shorthand for this.length */\n get length() {\n return this.stack.length;\n }\n get totalLength() {\n if (this.parentCompiler) return this.stack.length + this.parentCompiler.totalLength;\n return this.stack.length;\n }\n /** The variable name for the current item in the stack. */\n vλl: string = '';\n getNestLevel(rt: BaseRunType<any>): number {\n let index = -1;\n this.stack.forEach((item, i) => {\n if (item.rt === rt) index = i;\n if (item.rt.src.id && item.rt.src.id === rt.src.id) index = i;\n });\n if (index !== -1) return index;\n const fromParent = this.parentCompiler?.getNestLevel(rt);\n if (fromParent && fromParent !== -1) return fromParent;\n return -1; // not found\n }\n private varNameindex: Map<BaseRunType<any> | number, number> = new Map();\n getLocalVarName(prefix: string, rt: BaseRunType<any>): string {\n const key = rt.src.id || rt; // duplicated elements might have same index (that means they are the same deepkit type)\n const index = this.varNameindex.get(key);\n if (index !== undefined) return `${prefix}${index}`;\n const newIndex = this.varNameindex.size;\n this.varNameindex.set(key, newIndex);\n return `${prefix}${newIndex}`;\n }\n /**\n * The path to the current item in the stack,\n * This path can contain prop names array indexes or event literal variable values, ie: if parsing an array the path item would be the name if the index variable.\n * This is used to generate the correct code to access the value at runtime of the current item in the stack.\n * ie: if parsing the tuple ['A','B','C'] and the current item is 'B', the path would [1] as is the index of the item in the stack.\n * ie: if parsing the object {a: {b: {c: 'C'}}} and the current item is 'b', the path would ['a','b'] as is the path to the item in the stack.\n * At runtime this path gets combined with the runtime pλth variable to generate the correct path to access the value\n * */\n private _accessPathLiterals: StrNumber[] = [];\n /** push new item to the stack, returns true if new child is already in the stack (is circular type) */\n pushStack(newChild: BaseRunType): void {\n const totalLength = this.stack.length + this.totalLength;\n if (totalLength > MAX_STACK_DEPTH) throw new Error(maxStackErrorMessage);\n if (this.stack.length === 0) {\n if (newChild !== this.rootType) throw new Error('rootType should be the first item in the stack');\n newChild.getTypeID(); // ensures the constants are generated in correct order\n }\n this.vλl = getStackVλl(this);\n // static path must be called before pushing the new item\n if (isJitErrorsCompiler(this)) this._accessPathLiterals = getAccessPath(this);\n const newStackItem: StackItem = {vλl: this.vλl, rt: newChild, staticPath: this._accessPathLiterals};\n this.stack.push(newStackItem);\n }\n popStack(resultCode: JitCode): void | ((...args: any[]) => any) {\n if (resultCode?.code) (this as Mutable<BaseFnCompiler>).code = resultCode.code;\n this.popItem = this.stack.pop();\n const item = this.stack[this.stack.length - 1];\n this.vλl = item?.vλl || this.args.vλl;\n if (isJitErrorsCompiler(this)) this._accessPathLiterals = item?.staticPath || [];\n }\n siplePushStack(newChild: BaseRunType): void {\n const newStackItem: StackItem = {vλl: this.vλl, rt: newChild, staticPath: this._accessPathLiterals};\n this.stack.push(newStackItem);\n }\n simplePopStack(): void {\n this.popItem = this.stack.pop();\n }\n createJitFunction(overrideCode?: string): (...args: any[]) => any {\n try {\n if (overrideCode) {\n (this as Mutable<BaseFnCompiler>).code = overrideCode;\n this.isCompiled = false;\n }\n this.handleFunctionReturn();\n return createJitFunction(this); // add the compiled function to jit cache\n } catch (e: any) {\n const fnName = getJITFnName(this.fnID);\n const fnCode = ` Code:\\nfunction ${fnName}(){${this.code}}`;\n const name = `(${this.rootType.getTypeName()}:${this.rootType.getTypeID()})`;\n const typeString = `Type: ${this.rootType.stringify()}`;\n throw new Error(`Error building ${fnName} JIT function for type ${name}: ${e?.message} \\n${typeString} \\n${fnCode}`);\n }\n }\n /** Returns a copy of the access pat for current stack item */\n getAccessPath(): StrNumber[] {\n return [...this._accessPathLiterals];\n }\n\n getAccessPathArgs(): string {\n return this._accessPathLiterals.join(',');\n }\n getAccessPathLength(): number {\n return this._accessPathLiterals.length;\n }\n getAccessPathArgsForFnCall(): {args: string; length: number} {\n return {args: this.getAccessPathArgs(), length: this.getAccessPathLength()};\n }\n getCurrentStackItem(): StackItem {\n const item = this.stack[this.stack.length - 1];\n if (!item) throw new Error('Compiler stack is empty, no current item');\n return item;\n }\n getChildVλl(): string {\n const parent = this.getCurrentStackItem();\n if (!parent) return this.args.vλl;\n const rt = parent.rt;\n if (!isChildAccessorType(rt)) throw new Error(`cant get child var name from ${rt.getKindName()}`);\n if (rt.skipSettingAccessor?.()) return parent.vλl;\n return parent.vλl + (rt.useArrayAccessor() ? `[${rt.getChildLiteral(this)}]` : `.${rt.getChildVarName(this)}`);\n }\n shouldCallDependency(): boolean {\n const stackItem = this.getCurrentStackItem();\n return !stackItem.rt.isJitInlined() && this.stack.length > 1;\n }\n updateDependencies(childComp: JitCompiledFnData): void {\n if (childComp.isNoop) return; // noop functions are not added to dependencies as shouldn't be used inside jit code neither\n if (this.jitDependencies.includes(childComp.jitFnHash)) return;\n this.jitDependencies.push(childComp.jitFnHash);\n }\n removeFromJitCache(): void {\n getJitUtils().removeFromJitCache(this as JitCompiledFn);\n }\n getStackTrace(): string {\n const separator = '.';\n const parentTrace = this.parentCompiler ? this.parentCompiler.getStackTrace() + separator : JIT_STACK_TRACE_MESSAGE;\n const lastParentItem = this.parentCompiler?.getCurrentStackItem();\n const filteredStack = lastParentItem ? this.stack.filter((item) => item.rt !== lastParentItem?.rt) : this.stack;\n return parentTrace + filteredStack.map((item) => this.getTypeTraceInfo(item.rt)).join(separator);\n }\n hasStackTrace(errorMessage: string) {\n return errorMessage.includes(JIT_STACK_TRACE_MESSAGE);\n }\n\n /** Set a context code item */\n setContextItem(key: string, value: string): void {\n this.contextCodeItems.set(key, value);\n }\n\n /** Get a context code item */\n getContextItem(key: string): string | undefined {\n return this.contextCodeItems.get(key);\n }\n\n /** Check if a context code item exists */\n hasContextItem(key: string): boolean {\n return this.contextCodeItems.has(key);\n }\n\n /** Get all context code items values */\n getContextItemValues(): string[] {\n return Array.from(this.contextCodeItems.values());\n }\n\n setChildrenCallArgs(fnID: string, args: Partial<JitFnArgs>): void {\n this.childrenCallArgs[fnID] = args;\n }\n\n getChildrenCallArgs(fnID: string): Partial<JitFnArgs> | undefined {\n return this.childrenCallArgs[fnID];\n }\n\n /**\n * Compiles the current function.\n * This function handles the logic to determine if the operation should be compiled and code should be inlined, or called as a dependency.\n * Note current JitCompiler operation might be different from the passed operation id.\n * ie: typeErrors might want to compile isType to generate the part of the code that checks for the type.\n * @param comp current jit compiler operation\n * @param fnID operation id\n * @returns\n */\n compile(rt: BaseRunType | undefined, expectedCType: CodeType, fnID: JitFnID): JitCode {\n if (!rt) return {code: undefined, type: expectedCType};\n let jCode: JitCode;\n this.pushStack(rt);\n if (this.shouldCallDependency()) {\n const compiledOp = rt.createJitCompiledFunction(fnID, this, this.opts);\n jCode = this.callDependency(rt, compiledOp);\n this.updateDependencies(compiledOp);\n } else {\n // prettier-ignore\n switch (fnID) {\n case JitFunctions.isType.id:\n jCode = this.compileFormatter(rt, fnID, rt.emitIsType(this, expectedCType), expectedCType, '&&'); break;\n case JitFunctions.typeErrors.id:\n jCode = this.compileFormatter(rt, fnID, rt.emitTypeErrors(this as any, expectedCType), expectedCType, ';'); break;\n case JitFunctions.prepareForJson.id:\n jCode = this.compileFormatter(rt, fnID,rt.emitPrepareForJson(this, expectedCType), expectedCType, ';'); break;\n case JitFunctions.restoreFromJson.id:\n jCode = this.compileFormatter(rt, fnID,rt.emitRestoreFromJson(this, expectedCType), expectedCType, ';'); break;\n case JitFunctions.stringifyJson.id:\n jCode = this.compileFormatter(rt, fnID,emitJsonStringify(rt, this), expectedCType, ';'); break;\n case JitFunctions.toBinary.id:\n jCode = this.compileFormatter(rt, fnID,emitToBinary(rt, this as any), expectedCType, ';'); break;\n case JitFunctions.fromBinary.id:\n jCode = this.compileFormatter(rt, fnID,emitFromBinary(rt, this as any), expectedCType, ';'); break;\n case JitFunctions.toJSCode.id:\n jCode =this.compileFormatter(rt, fnID, emitToCode(rt, this), expectedCType, ';'); break;\n case JitFunctions.unknownKeyErrors.id:\n jCode = rt.emitUnknownKeyErrors(this as any, expectedCType); break;\n case JitFunctions.hasUnknownKeys.id:\n jCode = rt.emitHasUnknownKeys(this, expectedCType); break;\n case JitFunctions.stripUnknownKeys.id:\n jCode = rt.emitStripUnknownKeys(this, expectedCType); break;\n case JitFunctions.unknownKeysToUndefined.id:\n jCode = rt.emitUnknownKeysToUndefined(this, expectedCType); break;\n case JitFunctions.format.id:\n jCode = {code: undefined, type: E}; break;\n default:\n throw new Error(`Unknown compile operation: ${fnID}`);\n }\n if (jCode?.code) {\n // endure the child code type is compatible with the parent code type.\n // ie: a code statement can not be interpolated within an expression\n const compatibleCode = this.handleCodeInterpolation(rt, jCode, expectedCType);\n jCode = {code: compatibleCode, type: jCode.type};\n }\n }\n this.popStack(jCode);\n return jCode;\n }\n\n private compileFormatter(\n rt: BaseRunType,\n fnID: JitFnID,\n childJCode: JitCode,\n expectedCType: CodeType,\n separator: ';' | '&&'\n ): JitCode {\n const expectedCT = childJCode.code ? childJCode.type : expectedCType;\n const typeFormatter = getRunTypeFormat(rt);\n if (!typeFormatter) return childJCode;\n let jitCode: JitCode | undefined = undefined;\n const formatterCode = typeFormatter.compileFormat(fnID, this, rt);\n // Check if the formatter code can be embedded AND is compatible with the function ID\n const canEmbed = typeFormatter.canEmbedFormatterCode(fnID, rt);\n const codeHasReturn = formatterCode.type === RB;\n\n // For isType and similar functions that are expressions, we need to ensure\n // the formatter code is also an expression or has a return statement\n const isCompatible = formatterCode.type === expectedCT;\n if (canEmbed && isCompatible && !codeHasReturn) {\n jitCode = formatterCode;\n } else {\n // Otherwise, create a separate function\n const compiled = typeFormatter.createJitCompiledFormatter(fnID, rt, this, undefined, undefined, undefined, this.opts);\n if (!compiled.isNoop) {\n this.updateDependencies(compiled);\n jitCode = this.callDependency(rt, compiled);\n }\n }\n if (!jitCode?.code) return childJCode;\n const shouldReplace = getJitFnSettings(fnID).formatShouldReplaceJitCode;\n const joiner = separator === '&&' ? ' && ' : '; ';\n if (shouldReplace) {\n return jitCode;\n }\n const finalCode = childJCode?.code ? childJCode.code + joiner + jitCode.code : jitCode.code;\n return {code: finalCode, type: expectedCT};\n }\n\n private callDependency(rt: BaseRunType, dependencyComp: JitCompiledFn): JitCode {\n if (dependencyComp.isNoop) return {code: '', type: E}; // we don't need to call noop functions\n const isErrorCall =\n dependencyComp.fnID === JitFunctions.typeErrors.id || dependencyComp.fnID === JitFunctions.unknownKeyErrors.id;\n\n // Use the dependency's args, not the current compiler's args\n const depArgs = getJitFnSettings(dependencyComp.fnID as JitFnID).jitArgs;\n const callArgsCode = Object.keys(depArgs)\n .map((key) => getJitFnArgCallVarName(this, rt, dependencyComp.fnID as JitFnID, key))\n .join(',');\n const isSelf = this.jitFnHash === dependencyComp.jitFnHash;\n const varName = dependencyComp.jitFnHash;\n // call local variable instead directly calling jitUtils to avoid lookups.\n // ie function context (local variable created when compiling the function): const abc = jitUtils.getJIT('abc);\n // ie calling context variable: abc.fn();\n // if operation is the same as the current operation we can call the function directly\n\n const callCode = isSelf ? `${varName}(${callArgsCode})` : `${varName}.fn(${callArgsCode})`;\n if (!isSelf) this.setContextItem(varName, `const ${varName} = utl.getJIT(${toLiteral(varName)})`);\n if (isErrorCall) {\n const pathArgs = this.getAccessPathArgs();\n const pathLength = this.getAccessPathLength();\n if (!pathLength) return {code: callCode, type: 'E'};\n // increase and decrease the static path before and after calling the dependency function\n // TODO, maybe we can improve performance by using something else than push and splice\n return {\n code: `${jitErrorArgs.pλth}.push(${pathArgs}); ${callCode}; ${jitErrorArgs.pλth}.splice(-${pathLength});`,\n type: 'S',\n };\n }\n return {code: callCode, type: 'E'};\n }\n\n /** Check if root type is a FunctionParamsRunType with no children (empty params) */\n private isEmptyFunctionParams(): boolean {\n if (!isFunctionParamsRunType(this.rootType)) return false;\n return this.rootType.getChildRunTypes().length === 0;\n }\n\n /**\n * Set the isNoop flag based on the code of the operation.\n * must be called before function gets compiled.\n * The isNoop flag is used to avoid calling the function when the result of compilation is an empty function.\n */\n private handleFunctionReturn(): void {\n if (this.isCompiled) return;\n let isNoop = false;\n // trims code and transforms multiple whitespaces into a single one, does not affect new lines as those can be significant\n let code = this.code.replace(/[ \\t]+/g, ' ').replace(/;+/g, ';');\n // For functions with no params, all validation/serialization functions are noop\n const isEmptyParams = this.isEmptyFunctionParams();\n switch (this.fnID) {\n case JitFunctions.isType.id:\n isNoop = isEmptyParams || !this.code || this.code === 'true' || this.code === 'return true';\n if (isNoop) code = `return true`; // if code is a noop, we still need to return true\n break;\n case JitFunctions.hasUnknownKeys.id:\n isNoop = !this.code || this.code === 'false' || this.code === 'return false';\n if (isNoop) code = `return false`; // if code is a noop, we still need return false\n break;\n case JitFunctions.prepareForJson.id:\n case JitFunctions.restoreFromJson.id:\n case JitFunctions.stripUnknownKeys.id:\n case JitFunctions.unknownKeysToUndefined.id:\n isNoop = isEmptyParams || !this.code || this.code === this.args.vλl || this.code === `return ${this.args.vλl}`;\n if (isNoop) code = `return ${this.args.vλl}`; // if code is a noop, we need to return the value\n break;\n case JitFunctions.typeErrors.id:\n case JitFunctions.unknownKeyErrors.id:\n isNoop = isEmptyParams || !this.code || this.code === this.args.εrr || this.code === `return ${this.args.εrr}`;\n if (isNoop) code = `return ${this.args.εrr}`; // if code is a noop, we need to return the error array\n break;\n case JitFunctions.format.id:\n isNoop = !this.code || this.code === this.args.vλl || this.code === `return ${this.args.vλl}`;\n if (isNoop) code = `return ${this.args.vλl}`; // if code is a noop, we need to return the value\n break;\n }\n (this as Mutable<BaseFnCompiler>).isNoop = isNoop;\n (this as Mutable<BaseFnCompiler>).code = code;\n this.isCompiled = true;\n }\n\n /** Ensures the child code type is compatible with the parent code type */\n private handleCodeInterpolation(rt: BaseRunType, childJCode: JitCode, parentCodeType: CodeType): string {\n const code = childJCode.code || '';\n const childCodeType = childJCode.type;\n const isRoot = this.length === 1;\n // root code must ensure values are returned\n if (isRoot) {\n // prettier-ignore\n switch (childCodeType) {\n case E: return `return ${code}`;\n case S: return `${addFullStop(code)} return ${this.returnName}`;\n case RB: return code;\n }\n }\n switch (true) {\n case parentCodeType === E && childCodeType === E:\n return code;\n case parentCodeType === E && childCodeType === S:\n return this.callSelfInvokingFunction(childJCode);\n case parentCodeType === E && childCodeType === RB:\n return this.callSelfInvokingFunction(childJCode);\n case parentCodeType === S && childCodeType === E:\n return code; // no need for full stop, parent should handle it\n case parentCodeType === S && childCodeType === S:\n return addFullStop(code);\n case parentCodeType === S && childCodeType === RB:\n return this.callSelfInvokingFunction(childJCode);\n case parentCodeType === RB && childCodeType === E:\n throw new Error('Expected an block code but got an expression, rt should not happen as would be useless code.');\n case parentCodeType === RB && childCodeType === S:\n return addFullStop(code);\n case parentCodeType === RB && childCodeType === RB:\n return `${addFullStop(code)} return ${this.returnName}`;\n default:\n throw new Error(`Unexpected code type (expected: ${parentCodeType}, got: ${childCodeType})`);\n }\n }\n\n /**\n * If code should be an expression, but code has return a statement, we need to wrap it in a self invoking function to avoid syntax errors\n * IMPORTANT TODO, WE CAN IMPROVE PERF QUITE A BIT BY CREATING A NEW FUNCTION IN CONTEXT INSTEAD SELF INVOkING\n * TODO: we could create a new function and cache instead a self invoking function a performance is same but code is not repeated\n * IE: this.selfInvoke(code), rt will create a new function in context and call that function instead of self invoking\n * rt is specially for atomic types as we can be sure there are no references to children types inside the code block\n */\n private callSelfInvokingFunction(jCode: JitCode): string {\n if (jCode.type === E) throw new Error('Javascript expressions never need to be wrapped in a self invoking function.');\n if (!jCode.code) return '';\n const code = jCode.code.trim();\n const isSelfInvoking = code.startsWith('(function()') && code.endsWith(')()');\n if (isSelfInvoking) return code;\n const addReturn = jCode.type !== RB;\n const returnCode = addReturn ? `return ` : '';\n return `(function(){${returnCode}${jCode.code}})()`;\n }\n\n getTypeTraceInfo(rt: BaseRunType): string {\n if (rt.getFamily() === 'C') return rt.src.typeName || getReflectionName(rt);\n if (rt.getFamily() === 'F') return String((rt.src as TypeFunction).name) || getReflectionName(rt);\n if (rt.getFamily() === 'M') {\n const rtChild = rt as any as RunTypeChildAccessor;\n const isRunTypeChildAccessor = !!rtChild.getChildVarName;\n if (!isRunTypeChildAccessor) return getReflectionName(rt);\n return String(rtChild.getChildVarName(this));\n }\n return getReflectionName(rt);\n }\n\n // ########## Compile Methods shorthands ##########\n\n compileIsType(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.isType.id);\n }\n compileTypeErrors(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.typeErrors.id);\n }\n compilePrepareForJson(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.prepareForJson.id);\n }\n compileRestoreFromJson(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.restoreFromJson.id);\n }\n compileJsonStringify(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.stringifyJson.id);\n }\n compileToBinary(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.toBinary.id);\n }\n compileFromBinary(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.fromBinary.id);\n }\n compileUnknownKeyErrors(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.unknownKeyErrors.id);\n }\n compileHasUnknownKeys(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.hasUnknownKeys.id);\n }\n compileStripUnknownKeys(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.stripUnknownKeys.id);\n }\n compileUnknownKeysToUndefined(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.unknownKeysToUndefined.id);\n }\n\n // ################### Pure Functions Operations ###################\n\n addPureFunction(compiledPureFn: CompiledPureFunction): string {\n const {namespace, fnName} = compiledPureFn;\n const varName = quickHash(fnName, 8);\n if (this.hasContextItem(varName)) return varName;\n this.addPureFnDependency(compiledPureFn);\n // Add context code for the pure function and params\n const pureFunctionCode = `const ${varName} = utl.getPureFn(${toLiteral(namespace)}, ${toLiteral(fnName)})`;\n this.setContextItem(varName, pureFunctionCode);\n return varName;\n }\n\n addPureFnDependency(compiledPureFn: CompiledPureFunction): void {\n const {namespace, fnName} = compiledPureFn;\n if (!getJitUtils().hasPureFn(namespace, fnName))\n throw new Error(\n `Pure function with name ${fnName} can not be added as jit dependency in namespace ${namespace}, be sure to register the pure function first by calling getJitUtils().addPureFn()`\n );\n // Store as \"namespace::fnName\" format (using :: to avoid conflicts with : in names)\n const key = `${namespace}::${fnName}`;\n if (this.pureFnDependencies.includes(key)) return;\n this.pureFnDependencies.push(key);\n }\n}\n\n// ################### Compile Operations ###################\n\nexport class JitFnCompiler<ID extends JitFnID = any> extends BaseFnCompiler<JitFnArgs, ID> {\n constructor(\n rt: BaseRunType,\n fnID: ID,\n parentCompiler?: BaseFnCompiler,\n jitFnHash?: string,\n typeID?: StrNumber,\n opts: RunTypeOptions = {}\n ) {\n const fnSettings = getJitFnSettings(fnID);\n super(rt, fnID, fnSettings, parentCompiler, jitFnHash, typeID, opts);\n }\n}\n\nexport class JitErrorsFnCompiler<ID extends JitFnID = any> extends BaseFnCompiler<typeof jitErrorArgs, ID> {\n constructor(\n rt: BaseRunType,\n fnID: ID,\n parentCompiler?: BaseFnCompiler,\n jitFnHash?: string,\n typeID?: StrNumber,\n opts: RunTypeOptions = {}\n ) {\n const fnSettings = getJitFnSettings(fnID);\n super(rt, fnID, fnSettings, parentCompiler, jitFnHash, typeID, opts);\n }\n callJitErr(expected: AnyKindName | BaseRunType<any>): string {\n // TODO: most of the time jit path is an empty array, so a new array is created every time\n // this can be optimized by adding it to the compiler context, or maybe make the param optional in jitUtils.err\n return this.callJitErrWithPath(expected);\n }\n /**\n * This is used when we add an extra item to the path,\n * for extra info, ie union items, maps keys, etc...\n * This is because we don't want the item int the real path as it is not part of the runtime path of an object.\n * but we still want to add that info to process the error.\n * ie: type AorBList = ({a: string} | {b: string})[];\n * we want the error to contain the info if it is union item a or b, but the path to the the doesn't have that info is just list[index]\n * */\n callJitErrWithPath(exp: AnyKindName | BaseRunType<any>, extraPathLiteral?: StrNumber): string {\n const args = this._getJitErrorArgs(exp);\n const accessPath = this.getAccessPathLiteral(extraPathLiteral);\n if (accessPath) args.push(accessPath);\n const errFn = this.addPureFunction(cpf_newRunTypeErr);\n return `${errFn}(${args.join(',')})`;\n }\n callJitFormatErr(\n expected: AnyKindName | BaseRunType<any>,\n formatter: BaseRunTypeFormat<any>,\n paramName: string,\n paramValue: string | number | boolean | bigint,\n extraPathLiteral?: StrNumber\n ): string {\n // jitUtil.formatErr function arguments =>\n\n // pλth: StrNumber[],\n // εrr: RunTypeError[],\n // expected: string,\n\n // fmtName: string,\n // paramName: string,\n // paramVal: StrNumber,\n // fmtPath: StrNumber[],\n // accessPath?: StrNumber[],\n // fmtAccessPath?: StrNumber[]\n\n const typeErrArgs = this._getJitErrorArgs(expected);\n const fmtName = toLiteralInContext(this, formatter.getFormatName());\n const pName = toLiteralInContext(this, paramName);\n const pVal = toLiteralInContext(this, paramValue);\n const fmtPath = toLiteralInContext(this, formatter.getFormatPath());\n const formatArgs = [fmtName, pName, pVal, fmtPath];\n const optionalArgs: string[] = [];\n const accessPath = this.getAccessPathLiteral(extraPathLiteral);\n const formatAccessPath = this.getFormatAccessPathLiteral(formatter);\n if (!accessPath && formatAccessPath) optionalArgs.push('undefined');\n if (accessPath) optionalArgs.push(accessPath);\n if (formatAccessPath) optionalArgs.push(formatAccessPath);\n const formatErrFn = this.addPureFunction(cpf_formatErr);\n return `${formatErrFn}(${[...typeErrArgs, ...formatArgs, ...optionalArgs].join(',')})`;\n }\n\n private _getJitErrorArgs(exp: AnyKindName | BaseRunType<any>): string[] {\n // jitUtil.err function arguments =>\n // pλth: StrNumber[],\n // εrr: RunTypeError[],\n // expected: string,\n const path = this.args.pλth;\n const err = this.args.εrr;\n const expected = typeof exp === 'string' ? toLiteral(exp) : toLiteral(exp.getKindName());\n return [path, err, expected];\n }\n\n getAccessPathLiteral(extraPathLiteral?: StrNumber): string {\n const accessPath = this.getAccessPath();\n if (extraPathLiteral) accessPath.push(extraPathLiteral);\n return accessPath.length ? `[${accessPath.join(',')}]` : '';\n }\n\n getFormatAccessPathLiteral(formatter: BaseRunTypeFormat<any>): string {\n const formatExtraPathLiteral = formatter.getFormatExtraPathLiteral();\n return formatExtraPathLiteral ? `[${formatExtraPathLiteral}]` : '';\n }\n}\n\n/**\n * This is an special compiler for mock Function as mock is not technically a jit compiled function\n * but still needs to be created to reuse all jit functionality.\n */\nexport class MockJitCompiler extends BaseFnCompiler<JitFnArgs, 'mock'> {\n constructor(rt: BaseRunType, opts: RunTypeOptions, parentCompiler?: BaseFnCompiler, jitFnHash?: string, typeID?: StrNumber) {\n super(rt, JitFunctions.mock.id, JitFunctions.mock, parentCompiler, jitFnHash, typeID, opts);\n }\n}\n\n// ################### Compiler Creation ###################\n\nexport function createJitCompiler(\n rt: BaseRunType,\n fnID: JitFnID,\n parent?: BaseFnCompiler,\n jitFnHash?: string,\n typeID?: StrNumber,\n opts: RunTypeOptions = {}\n): BaseFnCompiler {\n switch (fnID) {\n case JitFunctions.isType.id:\n case JitFunctions.prepareForJson.id:\n case JitFunctions.restoreFromJson.id:\n case JitFunctions.stringifyJson.id:\n case JitFunctions.hasUnknownKeys.id:\n case JitFunctions.stripUnknownKeys.id:\n case JitFunctions.unknownKeysToUndefined.id:\n case JitFunctions.format.id:\n case JitFunctions.toJSCode.id:\n case JitFunctions.toBinary.id:\n case JitFunctions.fromBinary.id:\n return new JitFnCompiler(rt, fnID, parent, jitFnHash, typeID, opts);\n case JitFunctions.typeErrors.id:\n case JitFunctions.unknownKeyErrors.id:\n return new JitErrorsFnCompiler(rt, fnID, parent, jitFnHash, typeID, opts);\n case JitFunctions.mock.id:\n return new MockJitCompiler(rt, opts, parent, jitFnHash, typeID);\n default:\n throw new Error(`Unknown compile operation: ${fnID}`);\n }\n}\n\nexport function printClosure(fnWithContext: string, functionName: string): string {\n return `function get_${functionName}(utl){${fnWithContext}}`;\n}\n\n// ################### utils ###################\n\nfunction getStackVλl(comp: BaseFnCompiler): string {\n let vλl: string = comp.args.vλl;\n for (let i = 0; i < comp.stack.length; i++) {\n const rt = comp.stack[i].rt;\n const custom = rt.getCustomVλl(comp);\n if (custom && custom.isStandalone) {\n vλl = custom.vλl;\n } else if (custom) {\n vλl += custom.useArrayAccessor ? `[${custom.vλl}]` : `.${custom.vλl}`;\n } else if (isChildAccessorType(rt) && !rt.skipSettingAccessor?.()) {\n vλl += rt.useArrayAccessor() ? `[${rt.getChildLiteral(comp)}]` : `.${rt.getChildVarName(comp)}`;\n }\n }\n return vλl;\n}\nfunction getAccessPath(comp: BaseFnCompiler): StrNumber[] {\n const path: StrNumber[] = [];\n const rtName: any = [];\n for (let i = 0; i < comp.stack.length; i++) {\n const rt = comp.stack[i].rt;\n const pathItem = rt.getStaticPathLiteral(comp);\n if (pathItem) {\n path.push(pathItem);\n } else if (isChildAccessorType(rt) && !rt.skipSettingAccessor?.()) {\n path.push(rt.getChildLiteral(comp));\n }\n rtName.push({path: [...path], name: rt.constructor.name});\n }\n return path;\n}\n\nfunction validateCompilerOptions(opts: RunTypeOptions): void {\n if (opts.paramsSlice) {\n const start = opts.paramsSlice?.start;\n const end = opts.paramsSlice?.end;\n if (start && start < 0) {\n throw new Error(`paramsSlice.start must be greater than 0`);\n }\n if (end && end < 0) {\n throw new Error(`paramsSlice.end must be greater than 0`);\n }\n if (end && start && end <= start) {\n throw new Error(`paramsSlice.end must be greater than paramsSlice.start`);\n }\n }\n}\n"],"names":["CodeTypes","getJITFnHash","getJitUtils","MAX_STACK_DEPTH","maxStackErrorMessage","isJitErrorsCompiler","createJitFunction","getJITFnName","isChildAccessorType","JIT_STACK_TRACE_MESSAGE","JitFunctions","emitJsonStringify","emitToBinary","emitFromBinary","emitToCode","getRunTypeFormat","getJitFnSettings","getJitFnArgCallVarName","toLiteral","jitErrorArgs","isFunctionParamsRunType","addFullStop","getReflectionName","quickHash","cpf_newRunTypeErr","toLiteralInContext","cpf_formatErr"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,KAAKA,wBAAAA,UAAU;AACrB,MAAM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,OAAO,GAAG;AAAA,IACvE,WAAWF,eAAAA,oBAAoB,EAAE,KAAK,CAAC,GAAG,yBAAyB;AAC/D,aAAO,GAAG,iBAAA,IAAqB,IAAI,GAAG,gBAAgB,IAAI,CAAC,MAAM,IAAI,GAAG,gBAAgB,IAAI,CAAC;AAAA,IACjG;AAAA,EACJ;AACA,SAAO;AACX;AACA,SAAS,cAAc,MAAmC;AACtD,QAAM,OAAoB,CAAA;AAC1B,QAAM,SAAc,CAAA;AACpB,WAAS,IAAI,GAAG,IAAI,KAAK,MAAM,QAAQ,KAAK;AACxC,UAAM,KAAK,KAAK,MAAM,CAAC,EAAE;AACzB,UAAM,WAAW,GAAG,qBAAqB,IAAI;AAC7C,QAAI,UAAU;AACV,WAAK,KAAK,QAAQ;AAAA,IACtB,WAAWA,eAAAA,oBAAoB,EAAE,KAAK,CAAC,GAAG,yBAAyB;AAC/D,WAAK,KAAK,GAAG,gBAAgB,IAAI,CAAC;AAAA,IACtC;AACA,WAAO,KAAK,EAAC,MAAM,CAAC,GAAG,IAAI,GAAG,MAAM,GAAG,YAAY,MAAK;AAAA,EAC5D;AACA,SAAO;AACX;AAEA,SAAS,wBAAwB,MAA4B;AACzD,MAAI,KAAK,aAAa;AAClB,UAAM,QAAQ,KAAK,aAAa;AAChC,UAAM,MAAM,KAAK,aAAa;AAC9B,QAAI,SAAS,QAAQ,GAAG;AACpB,YAAM,IAAI,MAAM,0CAA0C;AAAA,IAC9D;AACA,QAAI,OAAO,MAAM,GAAG;AAChB,YAAM,IAAI,MAAM,wCAAwC;AAAA,IAC5D;AACA,QAAI,OAAO,SAAS,OAAO,OAAO;AAC9B,YAAM,IAAI,MAAM,wDAAwD;AAAA,IAC5E;AAAA,EACJ;AACJ;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"jitFnCompiler.cjs","sources":["../../../../src/lib/jitFnCompiler.ts"],"sourcesContent":["/* ########\n * 2024 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {JitCompiledFn, JitCompiledFnData, JitFnArgs, JITUtils, CompiledPureFunction} from '@mionjs/core';\nimport {MAX_STACK_DEPTH, getJitUtils, quickHash} from '@mionjs/core';\nimport type {TypeFunction} from '@deepkit/type';\nimport type {Mutable, JitFnID, StrNumber, JitCode, RunTypeOptions, JitCompilerOpts, RunTypeChildAccessor} from '../types.ts';\nimport type {BaseRunType} from './baseRunTypes.ts';\nimport type {BaseRunTypeFormat} from './baseRunTypeFormat.ts';\nimport {getReflectionName, type AnyKindName} from '../constants.kind.ts';\nimport {maxStackErrorMessage, JIT_STACK_TRACE_MESSAGE} from '../constants.ts';\nimport {type CodeType, CodeTypes, jitErrorArgs, type JitFnSettings} from '../constants.functions.ts';\nimport {getJITFnName, getJitFnSettings} from './jitFnsRegistry.ts';\nimport {JitFunctions} from '../constants.functions.ts';\nimport {isChildAccessorType, isFunctionParamsRunType, isJitErrorsCompiler} from './guards.ts';\nimport {addFullStop, getJitFnArgCallVarName, toLiteral, toLiteralInContext} from './utils.ts';\nimport {getRunTypeFormat} from './formats.ts';\nimport {emitJsonStringify} from '../jitCompilers/json/stringifyJson.ts';\nimport {emitToBinary} from '../jitCompilers/binary/toBinary.ts';\nimport {emitFromBinary} from '../jitCompilers/binary/fromBinary.ts';\nimport {emitToCode} from '../jitCompilers/json/toJsCode.ts';\nimport {createJitFunction, getJITFnHash} from './createJitFunction.ts';\nimport {cpf_newRunTypeErr, cpf_formatErr} from '../run-types-pure-fns.ts';\n\nconst RB = CodeTypes.returnBlock;\nconst S = CodeTypes.statement;\nconst E = CodeTypes.expression;\n\nexport type StackItem = {\n /** current compile stack full variable accessor */\n vλl: string;\n /** current compile stack variable accessor */\n rt: BaseRunType;\n /** if should call a dependency instead inline code, then this would contain the id of the dependency to call */\n dependencyId?: string;\n staticPath?: StrNumber[];\n};\n\nexport type JitCompilerLike = BaseFnCompiler | JitCompiledFnData;\n\n/**\n * Program to compile a Jit function to be used at runtime.\n * These jit functions are used to validate, serialize, deserialize, etc... based on runTypes.\n */\nexport class BaseFnCompiler<FnArgsNames extends JitFnArgs = JitFnArgs, ID extends JitFnID = any>\n implements JitCompiledFnData, JitCompilerOpts\n{\n // !!! DO NOT MODIFY METHOD WITHOUT REVIEWING JIT CODE INVOCATIONS!!!\n /** The Jit Generated function once the compilation is finished */\n readonly fn: ((...args: any[]) => any) | undefined;\n readonly createJitFn: ((utl: JITUtils) => (...args: any[]) => any) | undefined;\n private isCompiled = false;\n\n constructor(\n public readonly rootType: BaseRunType,\n // the id of the function to be compiled (isType, typeErrors, prepareForJson, restoreFromJson, etc)\n public readonly fnID: ID,\n jitFnSettings: JitFnSettings,\n public readonly parentCompiler?: BaseFnCompiler,\n jitFnHash?: string,\n typeID?: StrNumber,\n public readonly opts: RunTypeOptions = {}\n ) {\n this.typeName = this.rootType.getTypeName();\n this.jitFnHash = jitFnHash || getJITFnHash(this.fnID, this.rootType, opts);\n this.typeID = typeID || this.rootType.getTypeID();\n this.args = {...jitFnSettings.jitArgs} as FnArgsNames;\n this.defaultParamValues = {...jitFnSettings.jitDefaultArgs} as FnArgsNames;\n this.returnName = jitFnSettings.returnName;\n if (this.args.vλl) this.vλl = this.args.vλl;\n // At the time of adding this compiler to the jit cache, the fn is undefined which is technically not allowed\n // but this prevents issues with circular types and loading order of jit dependencies\n getJitUtils().addToJitCache(this as JitCompiledFn);\n validateCompilerOptions(opts);\n }\n readonly typeName: string;\n readonly typeID: StrNumber;\n readonly jitFnHash: string;\n readonly args: FnArgsNames;\n readonly defaultParamValues: FnArgsNames;\n readonly returnName: string;\n\n /** Alternative arguments to use when calling a child function */\n readonly childrenCallArgs: Partial<Record<JitFnID, Partial<JitFnArgs>>> = {};\n\n /** Code for the jit function. after the operation has been compiled */\n readonly code: string = '';\n /** Code for the context function enclosing the jit function.\n * This can be used to initialize constant or some other things that will be required across all invocation.\n * By default this contains constants for the direct dependencies of the jit function.\n * */\n readonly contextCodeItems = new Map<string, string>();\n /**\n * This flag is set to true when the result of a jit compilation is a no operation (empty function).\n * Some jit compiled functions could execute no operations (ie: string, boolean and numbers does not require prepareForJson/restoreFromJson)\n */\n readonly isNoop?: boolean = false;\n /** The list of all jit functions that are used by this function and it's children. */\n readonly jitDependencies: Array<string> | undefined;\n readonly pureFnDependencies: Array<string> | undefined;\n /** The list of types being compiled.*/\n readonly stack: StackItem[] = [];\n popItem: StackItem | undefined;\n /** shorthand for this.length */\n get length() {\n return this.stack.length;\n }\n get totalLength() {\n if (this.parentCompiler) return this.stack.length + this.parentCompiler.totalLength;\n return this.stack.length;\n }\n /** The variable name for the current item in the stack. */\n vλl: string = '';\n getNestLevel(rt: BaseRunType<any>): number {\n let index = -1;\n this.stack.forEach((item, i) => {\n if (item.rt === rt) index = i;\n if (item.rt.src.id && item.rt.src.id === rt.src.id) index = i;\n });\n if (index !== -1) return index;\n const fromParent = this.parentCompiler?.getNestLevel(rt);\n if (fromParent && fromParent !== -1) return fromParent;\n return -1; // not found\n }\n private varNameindex: Map<BaseRunType<any> | number, number> = new Map();\n getLocalVarName(prefix: string, rt: BaseRunType<any>): string {\n const key = rt.src.id || rt; // duplicated elements might have same index (that means they are the same deepkit type)\n const index = this.varNameindex.get(key);\n if (index !== undefined) return `${prefix}${index}`;\n const newIndex = this.varNameindex.size;\n this.varNameindex.set(key, newIndex);\n return `${prefix}${newIndex}`;\n }\n /**\n * The path to the current item in the stack,\n * This path can contain prop names array indexes or event literal variable values, ie: if parsing an array the path item would be the name if the index variable.\n * This is used to generate the correct code to access the value at runtime of the current item in the stack.\n * ie: if parsing the tuple ['A','B','C'] and the current item is 'B', the path would [1] as is the index of the item in the stack.\n * ie: if parsing the object {a: {b: {c: 'C'}}} and the current item is 'b', the path would ['a','b'] as is the path to the item in the stack.\n * At runtime this path gets combined with the runtime pλth variable to generate the correct path to access the value\n * */\n private _accessPathLiterals: StrNumber[] = [];\n /** push new item to the stack, returns true if new child is already in the stack (is circular type) */\n pushStack(newChild: BaseRunType): void {\n const totalLength = this.stack.length + this.totalLength;\n if (totalLength > MAX_STACK_DEPTH) throw new Error(maxStackErrorMessage);\n if (this.stack.length === 0) {\n if (newChild !== this.rootType) throw new Error('rootType should be the first item in the stack');\n newChild.getTypeID(); // ensures the constants are generated in correct order\n }\n this.vλl = getStackVλl(this);\n // static path must be called before pushing the new item\n if (isJitErrorsCompiler(this)) this._accessPathLiterals = getAccessPath(this);\n const newStackItem: StackItem = {vλl: this.vλl, rt: newChild, staticPath: this._accessPathLiterals};\n this.stack.push(newStackItem);\n }\n popStack(resultCode: JitCode): void | ((...args: any[]) => any) {\n if (resultCode?.code) (this as Mutable<BaseFnCompiler>).code = resultCode.code;\n this.popItem = this.stack.pop();\n const item = this.stack[this.stack.length - 1];\n this.vλl = item?.vλl || this.args.vλl;\n if (isJitErrorsCompiler(this)) this._accessPathLiterals = item?.staticPath || [];\n }\n siplePushStack(newChild: BaseRunType): void {\n const newStackItem: StackItem = {vλl: this.vλl, rt: newChild, staticPath: this._accessPathLiterals};\n this.stack.push(newStackItem);\n }\n simplePopStack(): void {\n this.popItem = this.stack.pop();\n }\n createJitFunction(overrideCode?: string): (...args: any[]) => any {\n try {\n if (overrideCode) {\n (this as Mutable<BaseFnCompiler>).code = overrideCode;\n this.isCompiled = false;\n }\n this.handleFunctionReturn();\n return createJitFunction(this); // add the compiled function to jit cache\n } catch (e: any) {\n const fnName = getJITFnName(this.fnID);\n const fnCode = ` Code:\\nfunction ${fnName}(){${this.code}}`;\n const name = `(${this.rootType.getTypeName()}:${this.rootType.getTypeID()})`;\n const typeString = `Type: ${this.rootType.stringify()}`;\n throw new Error(`Error building ${fnName} JIT function for type ${name}: ${e?.message} \\n${typeString} \\n${fnCode}`);\n }\n }\n /** Returns a copy of the access pat for current stack item */\n getAccessPath(): StrNumber[] {\n return [...this._accessPathLiterals];\n }\n\n getAccessPathArgs(): string {\n return this._accessPathLiterals.join(',');\n }\n getAccessPathLength(): number {\n return this._accessPathLiterals.length;\n }\n getAccessPathArgsForFnCall(): {args: string; length: number} {\n return {args: this.getAccessPathArgs(), length: this.getAccessPathLength()};\n }\n getCurrentStackItem(): StackItem {\n const item = this.stack[this.stack.length - 1];\n if (!item) throw new Error('Compiler stack is empty, no current item');\n return item;\n }\n getChildVλl(): string {\n const parent = this.getCurrentStackItem();\n if (!parent) return this.args.vλl;\n const rt = parent.rt;\n if (!isChildAccessorType(rt)) throw new Error(`cant get child var name from ${rt.getKindName()}`);\n if (rt.skipSettingAccessor?.()) return parent.vλl;\n return parent.vλl + (rt.useArrayAccessor() ? `[${rt.getChildLiteral(this)}]` : `.${rt.getChildVarName(this)}`);\n }\n shouldCallDependency(): boolean {\n const stackItem = this.getCurrentStackItem();\n return !stackItem.rt.isJitInlined() && this.stack.length > 1;\n }\n updateDependencies(childComp: JitCompiledFnData): void {\n if (childComp.isNoop) return; // noop functions are not added to dependencies as shouldn't be used inside jit code neither\n if (this.jitDependencies?.includes(childComp.jitFnHash)) return;\n if (!this.jitDependencies) (this as Mutable<this>).jitDependencies = [];\n this.jitDependencies!.push(childComp.jitFnHash);\n }\n removeFromJitCache(): void {\n getJitUtils().removeFromJitCache(this as JitCompiledFn);\n }\n getStackTrace(): string {\n const separator = '.';\n const parentTrace = this.parentCompiler ? this.parentCompiler.getStackTrace() + separator : JIT_STACK_TRACE_MESSAGE;\n const lastParentItem = this.parentCompiler?.getCurrentStackItem();\n const filteredStack = lastParentItem ? this.stack.filter((item) => item.rt !== lastParentItem?.rt) : this.stack;\n return parentTrace + filteredStack.map((item) => this.getTypeTraceInfo(item.rt)).join(separator);\n }\n hasStackTrace(errorMessage: string) {\n return errorMessage.includes(JIT_STACK_TRACE_MESSAGE);\n }\n\n /** Set a context code item */\n setContextItem(key: string, value: string): void {\n this.contextCodeItems.set(key, value);\n }\n\n /** Get a context code item */\n getContextItem(key: string): string | undefined {\n return this.contextCodeItems.get(key);\n }\n\n /** Check if a context code item exists */\n hasContextItem(key: string): boolean {\n return this.contextCodeItems.has(key);\n }\n\n /** Get all context code items values */\n getContextItemValues(): string[] {\n return Array.from(this.contextCodeItems.values());\n }\n\n setChildrenCallArgs(fnID: string, args: Partial<JitFnArgs>): void {\n this.childrenCallArgs[fnID] = args;\n }\n\n getChildrenCallArgs(fnID: string): Partial<JitFnArgs> | undefined {\n return this.childrenCallArgs[fnID];\n }\n\n /**\n * Compiles the current function.\n * This function handles the logic to determine if the operation should be compiled and code should be inlined, or called as a dependency.\n * Note current JitCompiler operation might be different from the passed operation id.\n * ie: typeErrors might want to compile isType to generate the part of the code that checks for the type.\n * @param comp current jit compiler operation\n * @param fnID operation id\n * @returns\n */\n compile(rt: BaseRunType | undefined, expectedCType: CodeType, fnID: JitFnID): JitCode {\n if (!rt) return {code: undefined, type: expectedCType};\n let jCode: JitCode;\n this.pushStack(rt);\n if (this.shouldCallDependency()) {\n const compiledOp = rt.createJitCompiledFunction(fnID, this, this.opts);\n jCode = this.callDependency(rt, compiledOp);\n this.updateDependencies(compiledOp);\n } else {\n // prettier-ignore\n switch (fnID) {\n case JitFunctions.isType.id:\n jCode = this.compileFormatter(rt, fnID, rt.emitIsType(this, expectedCType), expectedCType, '&&'); break;\n case JitFunctions.typeErrors.id:\n jCode = this.compileFormatter(rt, fnID, rt.emitTypeErrors(this as any, expectedCType), expectedCType, ';'); break;\n case JitFunctions.prepareForJson.id:\n jCode = this.compileFormatter(rt, fnID,rt.emitPrepareForJson(this, expectedCType), expectedCType, ';'); break;\n case JitFunctions.restoreFromJson.id:\n jCode = this.compileFormatter(rt, fnID,rt.emitRestoreFromJson(this, expectedCType), expectedCType, ';'); break;\n case JitFunctions.stringifyJson.id:\n jCode = this.compileFormatter(rt, fnID,emitJsonStringify(rt, this), expectedCType, ';'); break;\n case JitFunctions.toBinary.id:\n jCode = this.compileFormatter(rt, fnID,emitToBinary(rt, this as any), expectedCType, ';'); break;\n case JitFunctions.fromBinary.id:\n jCode = this.compileFormatter(rt, fnID,emitFromBinary(rt, this as any), expectedCType, ';'); break;\n case JitFunctions.toJSCode.id:\n jCode =this.compileFormatter(rt, fnID, emitToCode(rt, this), expectedCType, ';'); break;\n case JitFunctions.unknownKeyErrors.id:\n jCode = rt.emitUnknownKeyErrors(this as any, expectedCType); break;\n case JitFunctions.hasUnknownKeys.id:\n jCode = rt.emitHasUnknownKeys(this, expectedCType); break;\n case JitFunctions.stripUnknownKeys.id:\n jCode = rt.emitStripUnknownKeys(this, expectedCType); break;\n case JitFunctions.unknownKeysToUndefined.id:\n jCode = rt.emitUnknownKeysToUndefined(this, expectedCType); break;\n case JitFunctions.format.id:\n jCode = {code: undefined, type: E}; break;\n default:\n throw new Error(`Unknown compile operation: ${fnID}`);\n }\n if (jCode?.code) {\n // endure the child code type is compatible with the parent code type.\n // ie: a code statement can not be interpolated within an expression\n const compatibleCode = this.handleCodeInterpolation(rt, jCode, expectedCType);\n jCode = {code: compatibleCode, type: jCode.type};\n }\n }\n this.popStack(jCode);\n return jCode;\n }\n\n private compileFormatter(\n rt: BaseRunType,\n fnID: JitFnID,\n childJCode: JitCode,\n expectedCType: CodeType,\n separator: ';' | '&&'\n ): JitCode {\n const expectedCT = childJCode.code ? childJCode.type : expectedCType;\n const typeFormatter = getRunTypeFormat(rt);\n if (!typeFormatter) return childJCode;\n let jitCode: JitCode | undefined = undefined;\n const formatterCode = typeFormatter.compileFormat(fnID, this, rt);\n // Check if the formatter code can be embedded AND is compatible with the function ID\n const canEmbed = typeFormatter.canEmbedFormatterCode(fnID, rt);\n const codeHasReturn = formatterCode.type === RB;\n\n // For isType and similar functions that are expressions, we need to ensure\n // the formatter code is also an expression or has a return statement\n const isCompatible = formatterCode.type === expectedCT;\n if (canEmbed && isCompatible && !codeHasReturn) {\n jitCode = formatterCode;\n } else {\n // Otherwise, create a separate function\n const compiled = typeFormatter.createJitCompiledFormatter(fnID, rt, this, undefined, undefined, undefined, this.opts);\n if (!compiled.isNoop) {\n this.updateDependencies(compiled);\n jitCode = this.callDependency(rt, compiled);\n }\n }\n if (!jitCode?.code) return childJCode;\n const shouldReplace = getJitFnSettings(fnID).formatShouldReplaceJitCode;\n const joiner = separator === '&&' ? ' && ' : '; ';\n if (shouldReplace) {\n return jitCode;\n }\n const finalCode = childJCode?.code ? childJCode.code + joiner + jitCode.code : jitCode.code;\n return {code: finalCode, type: expectedCT};\n }\n\n private callDependency(rt: BaseRunType, dependencyComp: JitCompiledFn): JitCode {\n if (dependencyComp.isNoop) return {code: '', type: E}; // we don't need to call noop functions\n const isErrorCall =\n dependencyComp.fnID === JitFunctions.typeErrors.id || dependencyComp.fnID === JitFunctions.unknownKeyErrors.id;\n\n // Use the dependency's args, not the current compiler's args\n const depArgs = getJitFnSettings(dependencyComp.fnID as JitFnID).jitArgs;\n const callArgsCode = Object.keys(depArgs)\n .map((key) => getJitFnArgCallVarName(this, rt, dependencyComp.fnID as JitFnID, key))\n .join(',');\n const isSelf = this.jitFnHash === dependencyComp.jitFnHash;\n const varName = dependencyComp.jitFnHash;\n // call local variable instead directly calling jitUtils to avoid lookups.\n // ie function context (local variable created when compiling the function): const abc = jitUtils.getJIT('abc);\n // ie calling context variable: abc.fn();\n // if operation is the same as the current operation we can call the function directly\n\n const callCode = isSelf ? `${varName}(${callArgsCode})` : `${varName}.fn(${callArgsCode})`;\n if (!isSelf) this.setContextItem(varName, `const ${varName} = utl.getJIT(${toLiteral(varName)})`);\n if (isErrorCall) {\n const pathArgs = this.getAccessPathArgs();\n const pathLength = this.getAccessPathLength();\n if (!pathLength) return {code: callCode, type: 'E'};\n // increase and decrease the static path before and after calling the dependency function\n // TODO, maybe we can improve performance by using something else than push and splice\n return {\n code: `${jitErrorArgs.pλth}.push(${pathArgs}); ${callCode}; ${jitErrorArgs.pλth}.splice(-${pathLength});`,\n type: 'S',\n };\n }\n return {code: callCode, type: 'E'};\n }\n\n /** Check if root type is a FunctionParamsRunType with no children (empty params) */\n private isEmptyFunctionParams(): boolean {\n if (!isFunctionParamsRunType(this.rootType)) return false;\n return this.rootType.getChildRunTypes().length === 0;\n }\n\n /**\n * Set the isNoop flag based on the code of the operation.\n * must be called before function gets compiled.\n * The isNoop flag is used to avoid calling the function when the result of compilation is an empty function.\n */\n private handleFunctionReturn(): void {\n if (this.isCompiled) return;\n let isNoop = false;\n // trims code and transforms multiple whitespaces into a single one, does not affect new lines as those can be significant\n let code = this.code.replace(/[ \\t]+/g, ' ').replace(/;+/g, ';');\n // For functions with no params, all validation/serialization functions are noop\n const isEmptyParams = this.isEmptyFunctionParams();\n switch (this.fnID) {\n case JitFunctions.isType.id:\n isNoop = isEmptyParams || !this.code || this.code === 'true' || this.code === 'return true';\n if (isNoop) code = `return true`; // if code is a noop, we still need to return true\n break;\n case JitFunctions.hasUnknownKeys.id:\n isNoop = !this.code || this.code === 'false' || this.code === 'return false';\n if (isNoop) code = `return false`; // if code is a noop, we still need return false\n break;\n case JitFunctions.prepareForJson.id:\n case JitFunctions.restoreFromJson.id:\n case JitFunctions.stripUnknownKeys.id:\n case JitFunctions.unknownKeysToUndefined.id:\n isNoop = isEmptyParams || !this.code || this.code === this.args.vλl || this.code === `return ${this.args.vλl}`;\n if (isNoop) code = `return ${this.args.vλl}`; // if code is a noop, we need to return the value\n break;\n case JitFunctions.typeErrors.id:\n case JitFunctions.unknownKeyErrors.id:\n isNoop = isEmptyParams || !this.code || this.code === this.args.εrr || this.code === `return ${this.args.εrr}`;\n if (isNoop) code = `return ${this.args.εrr}`; // if code is a noop, we need to return the error array\n break;\n case JitFunctions.format.id:\n isNoop = !this.code || this.code === this.args.vλl || this.code === `return ${this.args.vλl}`;\n if (isNoop) code = `return ${this.args.vλl}`; // if code is a noop, we need to return the value\n break;\n }\n (this as Mutable<BaseFnCompiler>).isNoop = isNoop;\n (this as Mutable<BaseFnCompiler>).code = code;\n this.isCompiled = true;\n }\n\n /** Ensures the child code type is compatible with the parent code type */\n private handleCodeInterpolation(rt: BaseRunType, childJCode: JitCode, parentCodeType: CodeType): string {\n const code = childJCode.code || '';\n const childCodeType = childJCode.type;\n const isRoot = this.length === 1;\n // root code must ensure values are returned\n if (isRoot) {\n // prettier-ignore\n switch (childCodeType) {\n case E: return `return ${code}`;\n case S: return `${addFullStop(code)} return ${this.returnName}`;\n case RB: return code;\n }\n }\n switch (true) {\n case parentCodeType === E && childCodeType === E:\n return code;\n case parentCodeType === E && childCodeType === S:\n return this.callSelfInvokingFunction(childJCode);\n case parentCodeType === E && childCodeType === RB:\n return this.callSelfInvokingFunction(childJCode);\n case parentCodeType === S && childCodeType === E:\n return code; // no need for full stop, parent should handle it\n case parentCodeType === S && childCodeType === S:\n return addFullStop(code);\n case parentCodeType === S && childCodeType === RB:\n return this.callSelfInvokingFunction(childJCode);\n case parentCodeType === RB && childCodeType === E:\n throw new Error('Expected an block code but got an expression, rt should not happen as would be useless code.');\n case parentCodeType === RB && childCodeType === S:\n return addFullStop(code);\n case parentCodeType === RB && childCodeType === RB:\n return `${addFullStop(code)} return ${this.returnName}`;\n default:\n throw new Error(`Unexpected code type (expected: ${parentCodeType}, got: ${childCodeType})`);\n }\n }\n\n /**\n * If code should be an expression, but code has return a statement, we need to wrap it in a self invoking function to avoid syntax errors\n * IMPORTANT TODO, WE CAN IMPROVE PERF QUITE A BIT BY CREATING A NEW FUNCTION IN CONTEXT INSTEAD SELF INVOkING\n * TODO: we could create a new function and cache instead a self invoking function a performance is same but code is not repeated\n * IE: this.selfInvoke(code), rt will create a new function in context and call that function instead of self invoking\n * rt is specially for atomic types as we can be sure there are no references to children types inside the code block\n */\n private callSelfInvokingFunction(jCode: JitCode): string {\n if (jCode.type === E) throw new Error('Javascript expressions never need to be wrapped in a self invoking function.');\n if (!jCode.code) return '';\n const code = jCode.code.trim();\n const isSelfInvoking = code.startsWith('(function()') && code.endsWith(')()');\n if (isSelfInvoking) return code;\n const addReturn = jCode.type !== RB;\n const returnCode = addReturn ? `return ` : '';\n return `(function(){${returnCode}${jCode.code}})()`;\n }\n\n getTypeTraceInfo(rt: BaseRunType): string {\n if (rt.getFamily() === 'C') return rt.src.typeName || getReflectionName(rt);\n if (rt.getFamily() === 'F') return String((rt.src as TypeFunction).name) || getReflectionName(rt);\n if (rt.getFamily() === 'M') {\n const rtChild = rt as any as RunTypeChildAccessor;\n const isRunTypeChildAccessor = !!rtChild.getChildVarName;\n if (!isRunTypeChildAccessor) return getReflectionName(rt);\n return String(rtChild.getChildVarName(this));\n }\n return getReflectionName(rt);\n }\n\n // ########## Compile Methods shorthands ##########\n\n compileIsType(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.isType.id);\n }\n compileTypeErrors(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.typeErrors.id);\n }\n compilePrepareForJson(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.prepareForJson.id);\n }\n compileRestoreFromJson(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.restoreFromJson.id);\n }\n compileJsonStringify(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.stringifyJson.id);\n }\n compileToBinary(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.toBinary.id);\n }\n compileFromBinary(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.fromBinary.id);\n }\n compileUnknownKeyErrors(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.unknownKeyErrors.id);\n }\n compileHasUnknownKeys(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.hasUnknownKeys.id);\n }\n compileStripUnknownKeys(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.stripUnknownKeys.id);\n }\n compileUnknownKeysToUndefined(rt: BaseRunType | undefined, expectedCType: CodeType): JitCode {\n return this.compile(rt, expectedCType, JitFunctions.unknownKeysToUndefined.id);\n }\n\n // ################### Pure Functions Operations ###################\n\n addPureFunction(compiledPureFn: CompiledPureFunction): string {\n const {namespace, fnName} = compiledPureFn;\n const varName = quickHash(fnName, 8);\n if (this.hasContextItem(varName)) return varName;\n this.addPureFnDependency(compiledPureFn);\n // Add context code for the pure function and params\n const pureFunctionCode = `const ${varName} = utl.getPureFn(${toLiteral(namespace)}, ${toLiteral(fnName)})`;\n this.setContextItem(varName, pureFunctionCode);\n return varName;\n }\n\n addPureFnDependency(compiledPureFn: CompiledPureFunction): void {\n const {namespace, fnName} = compiledPureFn;\n if (!getJitUtils().hasPureFn(namespace, fnName))\n throw new Error(\n `Pure function with name ${fnName} can not be added as jit dependency in namespace ${namespace}, be sure to register the pure function first by calling getJitUtils().addPureFn()`\n );\n // Store as \"namespace::fnName\" format (using :: to avoid conflicts with : in names)\n const key = `${namespace}::${fnName}`;\n if (this.pureFnDependencies?.includes(key)) return;\n if (!this.pureFnDependencies) (this as Mutable<this>).pureFnDependencies = [];\n this.pureFnDependencies!.push(key);\n }\n}\n\n// ################### Compile Operations ###################\n\nexport class JitFnCompiler<ID extends JitFnID = any> extends BaseFnCompiler<JitFnArgs, ID> {\n constructor(\n rt: BaseRunType,\n fnID: ID,\n parentCompiler?: BaseFnCompiler,\n jitFnHash?: string,\n typeID?: StrNumber,\n opts: RunTypeOptions = {}\n ) {\n const fnSettings = getJitFnSettings(fnID);\n super(rt, fnID, fnSettings, parentCompiler, jitFnHash, typeID, opts);\n }\n}\n\nexport class JitErrorsFnCompiler<ID extends JitFnID = any> extends BaseFnCompiler<typeof jitErrorArgs, ID> {\n constructor(\n rt: BaseRunType,\n fnID: ID,\n parentCompiler?: BaseFnCompiler,\n jitFnHash?: string,\n typeID?: StrNumber,\n opts: RunTypeOptions = {}\n ) {\n const fnSettings = getJitFnSettings(fnID);\n super(rt, fnID, fnSettings, parentCompiler, jitFnHash, typeID, opts);\n }\n callJitErr(expected: AnyKindName | BaseRunType<any>): string {\n // TODO: most of the time jit path is an empty array, so a new array is created every time\n // this can be optimized by adding it to the compiler context, or maybe make the param optional in jitUtils.err\n return this.callJitErrWithPath(expected);\n }\n /**\n * This is used when we add an extra item to the path,\n * for extra info, ie union items, maps keys, etc...\n * This is because we don't want the item int the real path as it is not part of the runtime path of an object.\n * but we still want to add that info to process the error.\n * ie: type AorBList = ({a: string} | {b: string})[];\n * we want the error to contain the info if it is union item a or b, but the path to the the doesn't have that info is just list[index]\n * */\n callJitErrWithPath(exp: AnyKindName | BaseRunType<any>, extraPathLiteral?: StrNumber): string {\n const args = this._getJitErrorArgs(exp);\n const accessPath = this.getAccessPathLiteral(extraPathLiteral);\n if (accessPath) args.push(accessPath);\n const errFn = this.addPureFunction(cpf_newRunTypeErr);\n return `${errFn}(${args.join(',')})`;\n }\n callJitFormatErr(\n expected: AnyKindName | BaseRunType<any>,\n formatter: BaseRunTypeFormat<any>,\n paramName: string,\n paramValue: string | number | boolean | bigint,\n extraPathLiteral?: StrNumber\n ): string {\n // jitUtil.formatErr function arguments =>\n\n // pλth: StrNumber[],\n // εrr: RunTypeError[],\n // expected: string,\n\n // fmtName: string,\n // paramName: string,\n // paramVal: StrNumber,\n // fmtPath: StrNumber[],\n // accessPath?: StrNumber[],\n // fmtAccessPath?: StrNumber[]\n\n const typeErrArgs = this._getJitErrorArgs(expected);\n const fmtName = toLiteralInContext(this, formatter.getFormatName());\n const pName = toLiteralInContext(this, paramName);\n const pVal = toLiteralInContext(this, paramValue);\n const fmtPath = toLiteralInContext(this, formatter.getFormatPath());\n const formatArgs = [fmtName, pName, pVal, fmtPath];\n const optionalArgs: string[] = [];\n const accessPath = this.getAccessPathLiteral(extraPathLiteral);\n const formatAccessPath = this.getFormatAccessPathLiteral(formatter);\n if (!accessPath && formatAccessPath) optionalArgs.push('undefined');\n if (accessPath) optionalArgs.push(accessPath);\n if (formatAccessPath) optionalArgs.push(formatAccessPath);\n const formatErrFn = this.addPureFunction(cpf_formatErr);\n return `${formatErrFn}(${[...typeErrArgs, ...formatArgs, ...optionalArgs].join(',')})`;\n }\n\n private _getJitErrorArgs(exp: AnyKindName | BaseRunType<any>): string[] {\n // jitUtil.err function arguments =>\n // pλth: StrNumber[],\n // εrr: RunTypeError[],\n // expected: string,\n const path = this.args.pλth;\n const err = this.args.εrr;\n const expected = typeof exp === 'string' ? toLiteral(exp) : toLiteral(exp.getKindName());\n return [path, err, expected];\n }\n\n getAccessPathLiteral(extraPathLiteral?: StrNumber): string {\n const accessPath = this.getAccessPath();\n if (extraPathLiteral) accessPath.push(extraPathLiteral);\n return accessPath.length ? `[${accessPath.join(',')}]` : '';\n }\n\n getFormatAccessPathLiteral(formatter: BaseRunTypeFormat<any>): string {\n const formatExtraPathLiteral = formatter.getFormatExtraPathLiteral();\n return formatExtraPathLiteral ? `[${formatExtraPathLiteral}]` : '';\n }\n}\n\n/**\n * This is an special compiler for mock Function as mock is not technically a jit compiled function\n * but still needs to be created to reuse all jit functionality.\n */\nexport class MockJitCompiler extends BaseFnCompiler<JitFnArgs, 'mock'> {\n constructor(rt: BaseRunType, opts: RunTypeOptions, parentCompiler?: BaseFnCompiler, jitFnHash?: string, typeID?: StrNumber) {\n super(rt, JitFunctions.mock.id, JitFunctions.mock, parentCompiler, jitFnHash, typeID, opts);\n }\n}\n\n// ################### Compiler Creation ###################\n\nexport function createJitCompiler(\n rt: BaseRunType,\n fnID: JitFnID,\n parent?: BaseFnCompiler,\n jitFnHash?: string,\n typeID?: StrNumber,\n opts: RunTypeOptions = {}\n): BaseFnCompiler {\n switch (fnID) {\n case JitFunctions.isType.id:\n case JitFunctions.prepareForJson.id:\n case JitFunctions.restoreFromJson.id:\n case JitFunctions.stringifyJson.id:\n case JitFunctions.hasUnknownKeys.id:\n case JitFunctions.stripUnknownKeys.id:\n case JitFunctions.unknownKeysToUndefined.id:\n case JitFunctions.format.id:\n case JitFunctions.toJSCode.id:\n case JitFunctions.toBinary.id:\n case JitFunctions.fromBinary.id:\n return new JitFnCompiler(rt, fnID, parent, jitFnHash, typeID, opts);\n case JitFunctions.typeErrors.id:\n case JitFunctions.unknownKeyErrors.id:\n return new JitErrorsFnCompiler(rt, fnID, parent, jitFnHash, typeID, opts);\n case JitFunctions.mock.id:\n return new MockJitCompiler(rt, opts, parent, jitFnHash, typeID);\n default:\n throw new Error(`Unknown compile operation: ${fnID}`);\n }\n}\n\nexport function printClosure(fnWithContext: string, functionName: string): string {\n return `function get_${functionName}(utl){${fnWithContext}}`;\n}\n\n// ################### utils ###################\n\nfunction getStackVλl(comp: BaseFnCompiler): string {\n let vλl: string = comp.args.vλl;\n for (let i = 0; i < comp.stack.length; i++) {\n const rt = comp.stack[i].rt;\n const custom = rt.getCustomVλl(comp);\n if (custom && custom.isStandalone) {\n vλl = custom.vλl;\n } else if (custom) {\n vλl += custom.useArrayAccessor ? `[${custom.vλl}]` : `.${custom.vλl}`;\n } else if (isChildAccessorType(rt) && !rt.skipSettingAccessor?.()) {\n vλl += rt.useArrayAccessor() ? `[${rt.getChildLiteral(comp)}]` : `.${rt.getChildVarName(comp)}`;\n }\n }\n return vλl;\n}\nfunction getAccessPath(comp: BaseFnCompiler): StrNumber[] {\n const path: StrNumber[] = [];\n const rtName: any = [];\n for (let i = 0; i < comp.stack.length; i++) {\n const rt = comp.stack[i].rt;\n const pathItem = rt.getStaticPathLiteral(comp);\n if (pathItem) {\n path.push(pathItem);\n } else if (isChildAccessorType(rt) && !rt.skipSettingAccessor?.()) {\n path.push(rt.getChildLiteral(comp));\n }\n rtName.push({path: [...path], name: rt.constructor.name});\n }\n return path;\n}\n\nfunction validateCompilerOptions(opts: RunTypeOptions): void {\n if (opts.paramsSlice) {\n const start = opts.paramsSlice?.start;\n const end = opts.paramsSlice?.end;\n if (start && start < 0) {\n throw new Error(`paramsSlice.start must be greater than 0`);\n }\n if (end && end < 0) {\n throw new Error(`paramsSlice.end must be greater than 0`);\n }\n if (end && start && end <= start) {\n throw new Error(`paramsSlice.end must be greater than paramsSlice.start`);\n }\n }\n}\n"],"names":["CodeTypes","getJITFnHash","getJitUtils","MAX_STACK_DEPTH","maxStackErrorMessage","isJitErrorsCompiler","createJitFunction","getJITFnName","isChildAccessorType","JIT_STACK_TRACE_MESSAGE","JitFunctions","emitJsonStringify","emitToBinary","emitFromBinary","emitToCode","getRunTypeFormat","getJitFnSettings","getJitFnArgCallVarName","toLiteral","jitErrorArgs","isFunctionParamsRunType","addFullStop","getReflectionName","quickHash","cpf_newRunTypeErr","toLiteralInContext","cpf_formatErr"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,KAAKA,wBAAAA,UAAU;AACrB,MAAM,IAAIA,wBAAAA,UAAU;AACpB,MAAM,IAAIA,wBAAAA,UAAU;AAkBb,MAAM,eAEb;AAAA,EAOI,YACoB,UAEA,MAChB,eACgB,gBAChB,WACA,QACgB,OAAuB,IACzC;AARkB,SAAA,WAAA;AAEA,SAAA,OAAA;AAEA,SAAA,iBAAA;AAGA,SAAA,OAAA;AAEhB,SAAK,WAAW,KAAK,SAAS,YAAA;AAC9B,SAAK,YAAY,aAAaC,0BAAAA,aAAa,KAAK,MAAM,KAAK,UAAU,IAAI;AACzE,SAAK,SAAS,UAAU,KAAK,SAAS,UAAA;AACtC,SAAK,OAAO,EAAC,GAAG,cAAc,QAAA;AAC9B,SAAK,qBAAqB,EAAC,GAAG,cAAc,eAAA;AAC5C,SAAK,aAAa,cAAc;AAChC,QAAI,KAAK,KAAK,IAAK,MAAK,MAAM,KAAK,KAAK;AAGxCC,qBAAA,EAAc,cAAc,IAAqB;AACjD,4BAAwB,IAAI;AAAA,EAChC;AAAA;AAAA;AAAA,EAzBS;AAAA,EACA;AAAA,EACD,aAAa;AAAA,EAwBZ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA,mBAAiE,CAAA;AAAA;AAAA,EAGjE,OAAe;AAAA;AAAA;AAAA;AAAA;AAAA,EAKf,uCAAuB,IAAA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AK,aAAa;AAClB,UAAM,QAAQ,KAAK,aAAa;AAChC,UAAM,MAAM,KAAK,aAAa;AAC9B,QAAI,SAAS,QAAQ,GAAG;AACpB,YAAM,IAAI,MAAM,0CAA0C;AAAA,IAC9D;AACA,QAAI,OAAO,MAAM,GAAG;AAChB,YAAM,IAAI,MAAM,wCAAwC;AAAA,IAC5D;AACA,QAAI,OAAO,SAAS,OAAO,OAAO;AAC9B,YAAM,IAAI,MAAM,wDAAwD;AAAA,IAC5E;AAAA,EACJ;AACJ;;;;;;;"}
|
|
@@ -30,8 +30,8 @@ export declare class BaseFnCompiler<FnArgsNames extends JitFnArgs = JitFnArgs, I
|
|
|
30
30
|
readonly code: string;
|
|
31
31
|
readonly contextCodeItems: Map<string, string>;
|
|
32
32
|
readonly isNoop?: boolean;
|
|
33
|
-
readonly jitDependencies: Array<string
|
|
34
|
-
readonly pureFnDependencies: Array<string
|
|
33
|
+
readonly jitDependencies: Array<string> | undefined;
|
|
34
|
+
readonly pureFnDependencies: Array<string> | undefined;
|
|
35
35
|
readonly stack: StackItem[];
|
|
36
36
|
popItem: StackItem | undefined;
|
|
37
37
|
get length(): number;
|
|
@@ -57,23 +57,7 @@ class FunctionRunType extends src_lib_baseRunTypes.BaseRunType {
|
|
|
57
57
|
return this.createJitCompiledReturnFunction(jitFn).fn;
|
|
58
58
|
}
|
|
59
59
|
createJitCompiledReturnFunction(jitFn, opts) {
|
|
60
|
-
|
|
61
|
-
while (true) {
|
|
62
|
-
if (src_lib_guards.isAnyFunctionRunType(currentType)) {
|
|
63
|
-
const returnType = currentType.getReturnType();
|
|
64
|
-
if (src_lib_guards.isPromiseRunType(returnType) || src_lib_guards.isFunctionRunType(returnType)) {
|
|
65
|
-
currentType = returnType;
|
|
66
|
-
continue;
|
|
67
|
-
}
|
|
68
|
-
return returnType.createJitCompiledFunction(jitFn.id, void 0, opts);
|
|
69
|
-
}
|
|
70
|
-
const memberType = currentType.getMemberType();
|
|
71
|
-
if (src_lib_guards.isPromiseRunType(memberType) || src_lib_guards.isFunctionRunType(memberType)) {
|
|
72
|
-
currentType = memberType;
|
|
73
|
-
continue;
|
|
74
|
-
}
|
|
75
|
-
return memberType.createJitCompiledFunction(jitFn.id, void 0, opts);
|
|
76
|
-
}
|
|
60
|
+
return this.getResolvedReturnType().createJitCompiledFunction(jitFn.id, void 0, opts);
|
|
77
61
|
}
|
|
78
62
|
// ######## JIT functions (all throw error) ########
|
|
79
63
|
// can't know the types of the run type function parameters, neither the return type, so only compare function name and length
|
|
@@ -117,6 +101,26 @@ class FunctionRunType extends src_lib_baseRunTypes.BaseRunType {
|
|
|
117
101
|
getReturnType() {
|
|
118
102
|
return this.src.return._rt;
|
|
119
103
|
}
|
|
104
|
+
/** returns the inner run-type when the handler returns Promise<T> (or nested Promise/function-return chains), or the plain return type otherwise */
|
|
105
|
+
getResolvedReturnType() {
|
|
106
|
+
let currentType = this;
|
|
107
|
+
while (true) {
|
|
108
|
+
if (src_lib_guards.isAnyFunctionRunType(currentType)) {
|
|
109
|
+
const returnType = currentType.getReturnType();
|
|
110
|
+
if (src_lib_guards.isPromiseRunType(returnType) || src_lib_guards.isFunctionRunType(returnType)) {
|
|
111
|
+
currentType = returnType;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
return returnType;
|
|
115
|
+
}
|
|
116
|
+
const memberType = currentType.getMemberType();
|
|
117
|
+
if (src_lib_guards.isPromiseRunType(memberType) || src_lib_guards.isFunctionRunType(memberType)) {
|
|
118
|
+
currentType = memberType;
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
return memberType;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
120
124
|
getParameters() {
|
|
121
125
|
return this.parameterRunTypes;
|
|
122
126
|
}
|
|
@@ -149,7 +153,7 @@ class FunctionRunType extends src_lib_baseRunTypes.BaseRunType {
|
|
|
149
153
|
}
|
|
150
154
|
static __type = [() => type.__ΩTypeFunction, "CallType", () => src_lib_baseRunTypes.BaseRunType, () => src_nodes_collection_functionParams.FunctionParamsRunType, "parameterRunTypes", function() {
|
|
151
155
|
return new src_nodes_collection_functionParams.FunctionParamsRunType();
|
|
152
|
-
}, () => src_lib_jitFnCompiler.JitFnCompiler, "comp", "skipJit", "SrcType", "deepkitType", "onCreated", "F", "getFamily", "getFnName", "JitFn", "jitFn", "RunTypeOptions", "opts", "args", "", "createJitParamsFunction", () => core.__ΩJitCompiledFn, "createJitCompiledParamsFunction", "createJitReturnFunction", () => core.__ΩJitCompiledFn, "createJitCompiledReturnFunction", () => src_lib_jitFnCompiler.JitFnCompiler, "JitCode", "emitIsType", () => src_lib_jitFnCompiler.JitErrorsFnCompiler, "emitTypeErrors", "emitPrepareForJson", "emitRestoreFromJson", "emitHasUnknownKeys", "emitUnknownKeyErrors", "emitStripUnknownKeys", "emitUnknownKeysToUndefined", () => src_lib_baseRunTypes.BaseRunType, "getReturnType", () => src_nodes_collection_functionParams.FunctionParamsRunType, "getParameters", "getParameterNames", "hasReturnData", "isAsync", "returnIsPromise", "ctx", "mockReturn", "mockParams", "FunctionRunType", 'n!c"Pe"!7#P7$3%>&PP7\'2()0)P"w*2+$0,P.-0.PP&\'J0/P"w021"w2238P"@24"/506P"w021"w2238n708P"w021P"@24"/509P"w021"w2238n:0;PP7<2("w=0>PP7?2("w=0@P"w=0AP"w=0BP"w=0CP"w=0DP"w=0EP"w=
|
|
156
|
+
}, () => src_lib_jitFnCompiler.JitFnCompiler, "comp", "skipJit", "SrcType", "deepkitType", "onCreated", "F", "getFamily", "getFnName", "JitFn", "jitFn", "RunTypeOptions", "opts", "args", "", "createJitParamsFunction", () => core.__ΩJitCompiledFn, "createJitCompiledParamsFunction", "createJitReturnFunction", () => core.__ΩJitCompiledFn, "createJitCompiledReturnFunction", () => src_lib_jitFnCompiler.JitFnCompiler, "JitCode", "emitIsType", () => src_lib_jitFnCompiler.JitErrorsFnCompiler, "emitTypeErrors", "emitPrepareForJson", "emitRestoreFromJson", "emitHasUnknownKeys", "emitUnknownKeyErrors", "emitStripUnknownKeys", "emitUnknownKeysToUndefined", () => src_lib_baseRunTypes.BaseRunType, "getReturnType", () => src_lib_baseRunTypes.BaseRunType, "getResolvedReturnType", () => src_nodes_collection_functionParams.FunctionParamsRunType, "getParameters", "getParameterNames", "hasReturnData", "isAsync", "returnIsPromise", "ctx", "mockReturn", "mockParams", "FunctionRunType", 'n!c"Pe"!7#P7$3%>&PP7\'2()0)P"w*2+$0,P.-0.PP&\'J0/P"w021"w2238P"@24"/506P"w021"w2238n708P"w021P"@24"/509P"w021"w2238n:0;PP7<2("w=0>PP7?2("w=0@P"w=0AP"w=0BP"w=0CP"w=0DP"w=0EP"w=0FPP7G0HPP7I0JPP7K0LP"w2238&F0MP)0NP)0OP)0PP"w22Q8"`0RP"w22Q8"F`0S5e!!6"wT'];
|
|
153
157
|
}
|
|
154
158
|
exports.FunctionRunType = FunctionRunType;
|
|
155
159
|
//# sourceMappingURL=function.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"function.cjs","sources":["../../../../../src/nodes/function/function.ts"],"sourcesContent":["/* ########\n * 2024 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\nimport type {AnyFunction, SrcType, JitFn, JitCode, RunTypeOptions} from '../../types.ts';\nimport {ReflectionKind, TypeFunction} from '@deepkit/type';\nimport {BaseRunType} from '../../lib/baseRunTypes.ts';\nimport {isAnyFunctionRunType, isFunctionRunType, isPromiseRunType} from '../../lib/guards.ts';\nimport {JitFnCompiler, JitErrorsFnCompiler} from '../../lib/jitFnCompiler.ts';\nimport {PromiseRunType} from '../native/promise.ts';\nimport {ReflectionSubKind} from '../../constants.kind.ts';\nimport {FunctionParamsRunType} from '../collection/functionParams.ts';\nimport {JitCompiledFn} from '@mionjs/core';\nimport {registerJitFunctionCompiler} from '../../lib/jitFnsRegistry.ts';\nimport {JitFunctions} from '../../constants.functions.ts';\n\nexport class FunctionRunType<CallType extends AnyFunction = TypeFunction> extends BaseRunType<CallType> {\n // parameterRunTypes.src must be set after FunctionRunType creation\n parameterRunTypes: FunctionParamsRunType = new FunctionParamsRunType();\n skipJit(comp: JitFnCompiler): boolean {\n if (!comp) return true;\n return comp.fnID !== JitFunctions.toJSCode.id;\n }\n onCreated(deepkitType: SrcType): void {\n // here we are mapping parameters from TypeParameter[] to TypeTuple as TupleRunType() is the same functionality as ParameterRunType[]\n super.onCreated(deepkitType);\n // Create a synthetic type for parameters with its own subKind\n // Explicitly exclude _typeId and _formatId so the params type gets its own cached IDs\n const paramsType = {...deepkitType, subKind: ReflectionSubKind.params} as any;\n delete paramsType._typeId;\n delete paramsType._formatId;\n this.parameterRunTypes.onCreated(paramsType);\n }\n getFamily(): 'F' {\n return 'F';\n }\n getFnName(): string | number {\n const name = (this.src as TypeFunction).name;\n if (!name) return '';\n if (typeof name === 'symbol') return name.toString();\n return name;\n }\n createJitParamsFunction(jitFn: JitFn, opts?: RunTypeOptions): (...args: any[]) => any {\n return this.createJitCompiledParamsFunction(jitFn, opts).fn;\n }\n createJitCompiledParamsFunction(jitFn: JitFn, opts?: RunTypeOptions): JitCompiledFn {\n const start = opts?.paramsSlice?.start;\n const end = opts?.paramsSlice?.end;\n if (start && end) {\n if (start < 0 || end > this.parameterRunTypes.getChildRunTypes().length)\n throw new Error(`Invalid paramsSlice, start: ${start}, end: ${end}.`);\n if (end <= start) throw new Error(`Invalid paramsSlice, start: ${start}, end: ${end}`);\n }\n return this.parameterRunTypes.createJitCompiledFunction(jitFn.id, undefined, opts);\n }\n createJitReturnFunction(jitFn: JitFn): (...args: any[]) => any {\n return this.createJitCompiledReturnFunction(jitFn).fn;\n }\n\n createJitCompiledReturnFunction(jitFn: JitFn, opts?: RunTypeOptions): JitCompiledFn {\n let currentType: PromiseRunType | FunctionRunType<any> = this; // eslint-disable-line @typescript-eslint/no-this-alias\n // iterate over the return type chain until we reach a non-function non-promise type\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (isAnyFunctionRunType(currentType)) {\n const returnType = currentType.getReturnType();\n if (isPromiseRunType(returnType) || isFunctionRunType(returnType)) {\n currentType = returnType;\n continue;\n }\n return returnType.createJitCompiledFunction(jitFn.id, undefined, opts);\n }\n const memberType = currentType.getMemberType();\n if (isPromiseRunType(memberType) || isFunctionRunType(memberType)) {\n currentType = memberType;\n continue;\n }\n return memberType.createJitCompiledFunction(jitFn.id, undefined, opts);\n }\n }\n\n // ######## JIT functions (all throw error) ########\n\n // can't know the types of the run type function parameters, neither the return type, so only compare function name and length\n emitIsType(comp: JitFnCompiler): JitCode {\n const minLength = this.parameterRunTypes.totalRequiredParams(comp);\n const totalParams = this.parameterRunTypes.getParamRunTypes(comp).length;\n const hasOptional = totalParams > minLength;\n const maxLength =\n this.parameterRunTypes.hasRestParameter(comp) || !hasOptional ? '' : ` && ${comp.vλl}.length <= ${totalParams}`;\n return {code: `(typeof ${comp.vλl} === 'function' && ${comp.vλl}.length >= ${minLength} ${maxLength})`, type: 'E'};\n }\n emitTypeErrors(comp: JitErrorsFnCompiler): JitCode {\n return {code: `if (!(${this.emitIsType(comp).code})) ${comp.callJitErr(this)};`, type: 'S'};\n }\n /**\n * json encode a function\n */\n emitPrepareForJson(): JitCode {\n throw new Error(`Compile function PrepareForJson not supported, call compileParams or compileReturn instead.`);\n }\n emitRestoreFromJson(): JitCode {\n throw new Error(`Compile function RestoreFromJson not supported, call compileParams or compileReturn instead.`);\n }\n emitHasUnknownKeys(): JitCode {\n return {code: '', type: 'E'};\n }\n emitUnknownKeyErrors(): JitCode {\n return {code: '', type: 'S'};\n }\n emitStripUnknownKeys(): JitCode {\n return {code: '', type: 'S'};\n }\n emitUnknownKeysToUndefined(): JitCode {\n return {code: '', type: 'S'};\n }\n\n // TODO: paramsSlice has been removed as options are not jet passed when building the run type. maybe we can pass it to the JitCompileOperation instead\n // constructor() {\n // const start = opts?.paramsSlice?.start;\n // const end = opts?.paramsSlice?.end;\n // parameterRunTypes = src.parameters.slice(start, end).map((p) => visitor(p, parents, opts)) as ParameterRunType[];\n // }\n getReturnType(): BaseRunType {\n return (this.src.return as SrcType)._rt as BaseRunType;\n }\n getParameters(): FunctionParamsRunType {\n return this.parameterRunTypes;\n }\n getParameterNames(opts?: RunTypeOptions): string[] {\n const start = opts?.paramsSlice?.start;\n const end = opts?.paramsSlice?.end;\n if (start || end) {\n return this.src.parameters.slice(start, end).map((p) => p.name);\n }\n return this.src.parameters.map((p) => p.name);\n }\n hasReturnData(): boolean {\n const returnKind = this.getReturnType().src.kind;\n return (\n returnKind !== ReflectionKind.void && returnKind !== ReflectionKind.never && returnKind !== ReflectionKind.undefined\n );\n }\n isAsync(): boolean {\n const returnKind = this.getReturnType().src.kind;\n return (\n returnKind === ReflectionKind.promise || returnKind === ReflectionKind.any || returnKind === ReflectionKind.unknown\n );\n }\n returnIsPromise(): boolean {\n return isPromiseRunType(this.getReturnType());\n }\n async mockReturn(ctx?: RunTypeOptions): Promise<any> {\n await registerJitFunctionCompiler(JitFunctions.mock);\n return this.getReturnType().mockType(ctx);\n }\n async mockParams(ctx?: RunTypeOptions): Promise<any[]> {\n await registerJitFunctionCompiler(JitFunctions.mock);\n return this.parameterRunTypes.mockType(ctx);\n }\n}\n"],"names":["BaseRunType","FunctionParamsRunType","JitFunctions","ReflectionSubKind","isAnyFunctionRunType","isPromiseRunType","isFunctionRunType","ReflectionKind","registerJitFunctionCompiler","__ΩTypeFunction","JitFnCompiler","__ΩJitCompiledFn","JitErrorsFnCompiler"],"mappings":";;;;;;;;;;;;;;;AAkBM,MAAO,wBAAqEA,qBAAAA,YAAqB;AAAA;AAAA,EAEnG,oBAA2C,IAAIC,oCAAAA,sBAAA;AAAA,EAC/C,QAAQ,MAAmB;AACvB,QAAI,CAAC;AAAM,aAAO;AAClB,WAAO,KAAK,SAASC,wBAAAA,aAAa,SAAS;AAAA,EAC/C;AAAA,EACA,UAAU,aAAoB;AAE1B,UAAM,UAAU,WAAW;AAG3B,UAAM,aAAa,EAAC,GAAG,aAAa,SAAS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AA,2BAAA,MAAAC,uBAAA,mCAAA,2BAAA,MAAAA,KAAAA,kBAAA,mCAAA,MAAAD,sBAAAA,eAAA,WAAA,cAAA,MAAAE,2CAAA,kBAAA,sBAAA,uBAAA,sBAAA,wBAAA,wBAAA,8BAAA,MAAAZ,qBAAAA,aAAA,iBAAA,MAAAC,2DAAA,iBAAA,qBAAA,iBAAA,WAAA,mBAAA,OAAA,cAAA,cAAA,mBAAA,qPAAA;;;"}
|
|
1
|
+
{"version":3,"file":"function.cjs","sources":["../../../../../src/nodes/function/function.ts"],"sourcesContent":["/* ########\n * 2024 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\nimport type {AnyFunction, SrcType, JitFn, JitCode, RunTypeOptions} from '../../types.ts';\nimport {ReflectionKind, TypeFunction} from '@deepkit/type';\nimport {BaseRunType} from '../../lib/baseRunTypes.ts';\nimport {isAnyFunctionRunType, isFunctionRunType, isPromiseRunType} from '../../lib/guards.ts';\nimport {JitFnCompiler, JitErrorsFnCompiler} from '../../lib/jitFnCompiler.ts';\nimport {PromiseRunType} from '../native/promise.ts';\nimport {ReflectionSubKind} from '../../constants.kind.ts';\nimport {FunctionParamsRunType} from '../collection/functionParams.ts';\nimport {JitCompiledFn} from '@mionjs/core';\nimport {registerJitFunctionCompiler} from '../../lib/jitFnsRegistry.ts';\nimport {JitFunctions} from '../../constants.functions.ts';\n\nexport class FunctionRunType<CallType extends AnyFunction = TypeFunction> extends BaseRunType<CallType> {\n // parameterRunTypes.src must be set after FunctionRunType creation\n parameterRunTypes: FunctionParamsRunType = new FunctionParamsRunType();\n skipJit(comp: JitFnCompiler): boolean {\n if (!comp) return true;\n return comp.fnID !== JitFunctions.toJSCode.id;\n }\n onCreated(deepkitType: SrcType): void {\n // here we are mapping parameters from TypeParameter[] to TypeTuple as TupleRunType() is the same functionality as ParameterRunType[]\n super.onCreated(deepkitType);\n // Create a synthetic type for parameters with its own subKind\n // Explicitly exclude _typeId and _formatId so the params type gets its own cached IDs\n const paramsType = {...deepkitType, subKind: ReflectionSubKind.params} as any;\n delete paramsType._typeId;\n delete paramsType._formatId;\n this.parameterRunTypes.onCreated(paramsType);\n }\n getFamily(): 'F' {\n return 'F';\n }\n getFnName(): string | number {\n const name = (this.src as TypeFunction).name;\n if (!name) return '';\n if (typeof name === 'symbol') return name.toString();\n return name;\n }\n createJitParamsFunction(jitFn: JitFn, opts?: RunTypeOptions): (...args: any[]) => any {\n return this.createJitCompiledParamsFunction(jitFn, opts).fn;\n }\n createJitCompiledParamsFunction(jitFn: JitFn, opts?: RunTypeOptions): JitCompiledFn {\n const start = opts?.paramsSlice?.start;\n const end = opts?.paramsSlice?.end;\n if (start && end) {\n if (start < 0 || end > this.parameterRunTypes.getChildRunTypes().length)\n throw new Error(`Invalid paramsSlice, start: ${start}, end: ${end}.`);\n if (end <= start) throw new Error(`Invalid paramsSlice, start: ${start}, end: ${end}`);\n }\n return this.parameterRunTypes.createJitCompiledFunction(jitFn.id, undefined, opts);\n }\n createJitReturnFunction(jitFn: JitFn): (...args: any[]) => any {\n return this.createJitCompiledReturnFunction(jitFn).fn;\n }\n\n createJitCompiledReturnFunction(jitFn: JitFn, opts?: RunTypeOptions): JitCompiledFn {\n return this.getResolvedReturnType().createJitCompiledFunction(jitFn.id, undefined, opts);\n }\n\n // ######## JIT functions (all throw error) ########\n\n // can't know the types of the run type function parameters, neither the return type, so only compare function name and length\n emitIsType(comp: JitFnCompiler): JitCode {\n const minLength = this.parameterRunTypes.totalRequiredParams(comp);\n const totalParams = this.parameterRunTypes.getParamRunTypes(comp).length;\n const hasOptional = totalParams > minLength;\n const maxLength =\n this.parameterRunTypes.hasRestParameter(comp) || !hasOptional ? '' : ` && ${comp.vλl}.length <= ${totalParams}`;\n return {code: `(typeof ${comp.vλl} === 'function' && ${comp.vλl}.length >= ${minLength} ${maxLength})`, type: 'E'};\n }\n emitTypeErrors(comp: JitErrorsFnCompiler): JitCode {\n return {code: `if (!(${this.emitIsType(comp).code})) ${comp.callJitErr(this)};`, type: 'S'};\n }\n /**\n * json encode a function\n */\n emitPrepareForJson(): JitCode {\n throw new Error(`Compile function PrepareForJson not supported, call compileParams or compileReturn instead.`);\n }\n emitRestoreFromJson(): JitCode {\n throw new Error(`Compile function RestoreFromJson not supported, call compileParams or compileReturn instead.`);\n }\n emitHasUnknownKeys(): JitCode {\n return {code: '', type: 'E'};\n }\n emitUnknownKeyErrors(): JitCode {\n return {code: '', type: 'S'};\n }\n emitStripUnknownKeys(): JitCode {\n return {code: '', type: 'S'};\n }\n emitUnknownKeysToUndefined(): JitCode {\n return {code: '', type: 'S'};\n }\n\n // TODO: paramsSlice has been removed as options are not jet passed when building the run type. maybe we can pass it to the JitCompileOperation instead\n // constructor() {\n // const start = opts?.paramsSlice?.start;\n // const end = opts?.paramsSlice?.end;\n // parameterRunTypes = src.parameters.slice(start, end).map((p) => visitor(p, parents, opts)) as ParameterRunType[];\n // }\n getReturnType(): BaseRunType {\n return (this.src.return as SrcType)._rt as BaseRunType;\n }\n /** returns the inner run-type when the handler returns Promise<T> (or nested Promise/function-return chains), or the plain return type otherwise */\n getResolvedReturnType(): BaseRunType {\n let currentType: PromiseRunType | FunctionRunType<any> = this; // eslint-disable-line @typescript-eslint/no-this-alias\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (isAnyFunctionRunType(currentType)) {\n const returnType = currentType.getReturnType();\n if (isPromiseRunType(returnType) || isFunctionRunType(returnType)) {\n currentType = returnType;\n continue;\n }\n return returnType;\n }\n const memberType = currentType.getMemberType();\n if (isPromiseRunType(memberType) || isFunctionRunType(memberType)) {\n currentType = memberType;\n continue;\n }\n return memberType;\n }\n }\n getParameters(): FunctionParamsRunType {\n return this.parameterRunTypes;\n }\n getParameterNames(opts?: RunTypeOptions): string[] {\n const start = opts?.paramsSlice?.start;\n const end = opts?.paramsSlice?.end;\n if (start || end) {\n return this.src.parameters.slice(start, end).map((p) => p.name);\n }\n return this.src.parameters.map((p) => p.name);\n }\n hasReturnData(): boolean {\n const returnKind = this.getReturnType().src.kind;\n return (\n returnKind !== ReflectionKind.void && returnKind !== ReflectionKind.never && returnKind !== ReflectionKind.undefined\n );\n }\n isAsync(): boolean {\n const returnKind = this.getReturnType().src.kind;\n return (\n returnKind === ReflectionKind.promise || returnKind === ReflectionKind.any || returnKind === ReflectionKind.unknown\n );\n }\n returnIsPromise(): boolean {\n return isPromiseRunType(this.getReturnType());\n }\n async mockReturn(ctx?: RunTypeOptions): Promise<any> {\n await registerJitFunctionCompiler(JitFunctions.mock);\n return this.getReturnType().mockType(ctx);\n }\n async mockParams(ctx?: RunTypeOptions): Promise<any[]> {\n await registerJitFunctionCompiler(JitFunctions.mock);\n return this.parameterRunTypes.mockType(ctx);\n }\n}\n"],"names":["BaseRunType","FunctionParamsRunType","JitFunctions","ReflectionSubKind","isAnyFunctionRunType","isPromiseRunType","isFunctionRunType","ReflectionKind","registerJitFunctionCompiler","__ΩTypeFunction","JitFnCompiler","__ΩJitCompiledFn","JitErrorsFnCompiler"],"mappings":";;;;;;;;;;;;;;;AAkBM,MAAO,wBAAqEA,qBAAAA,YAAqB;AAAA;AAAA,EAEnG,oBAA2C,IAAIC,oCAAAA,sBAAA;AAAA,EAC/C,QAAQ,MAAmB;AACvB,QAAI,CAAC;AAAM,aAAO;AAClB,WAAO,KAAK,SAASC,wBAAAA,aAAa,SAAS;AAAA,EAC/C;AAAA,EACA,UAAU,aAAoB;AAE1B,UAAM,UAAU,WAAW;AAG3B,UAAM,aAAa,EAAC,GAAG,aAAa,SAASC,mBAAAA,kBAAkB,OAAA;AAC/D,WAAO,WAAW;AAClB,WAAO,WAAW;AAClB,SAAK,kBAAkB,UAAU,UAAU;AAAA,EAC/C;AAAA,EACA,YAAS;AACL,WAAO;AAAA,EACX;AAAA,EACA,YAAS;AACL,UAAM,OAAQ,KAAK,IAAqB;AACxC,QAAI,CAAC;AAAM,aAAO;AAClB,QAAI,OAAO,SAAS;AAAU,aAAO,KAAK,SAAA;A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