runtime-compiler 4.2.2 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,77 +1,40 @@
1
- A code generation system.
1
+ A compile time evaluation system.
2
2
 
3
- # Usage
4
3
  ```ts
5
- import { IS_AOT, IS_BUILD } from 'runtime-compiler/env';
6
- import { evaluate } from 'runtime-compiler';
4
+ // src/index.mts
5
+ import evaluate from 'runtime-compiler';
7
6
 
8
- // Only log when building
9
- IS_BUILD && console.log('Building...');
7
+ const fib = (i) => (i < 2 ? i : fib(i - 1) + fib(i - 2));
8
+ export default evaluate(fib(12));
10
9
 
11
- // Only emit code if not in AOT mode
12
- const fn = evaluate<() => void>(IS_AOT || `return()=>console.log("Hi")`);
13
-
14
- // Run only when not in build mode
15
- IS_BUILD || fn();
16
- ```
17
-
18
- Build with `rolldown`:
19
- ```ts
20
- ...
10
+ // rolldown.config.mts
11
+ import { defineConfig } from 'rolldown';
21
12
  import rtc from 'runtime-compiler/rolldown';
22
13
 
23
14
  export default defineConfig({
24
- plugins: [rtc()]
15
+ input: 'src/index.mts',
16
+ experimental: {
17
+ nativeMagicString: true,
18
+ },
19
+ plugins: [rtc()],
25
20
  });
26
- ```
27
21
 
28
- Or Vite:
29
- ```ts
22
+ // or vite.config.mts
30
23
  import rtc from 'runtime-compiler/rolldown';
31
24
 
32
25
  export default defineConfig({
33
26
  // Only run this plugin on build
34
27
  build: {
35
28
  rolldownOptions: {
29
+ experimental: {
30
+ nativeMagicString: true,
31
+ },
36
32
  plugins: [rtc()]
37
33
  }
38
34
  }
39
35
  });
40
- ```
41
-
42
- If you have dependencies marked as external that uses `runtime-compiler`:
43
- ```ts
44
- // package: external-pkg
45
- import { IS_AOT } from 'runtime-compiler/env';
46
- import { evaluate } from 'runtime-compiler';
47
-
48
- export const fn = evaluate(IS_AOT || '()=>console.log("Hi")');
49
-
50
- // index.ts
51
- import { fn } from 'external-pkg';
52
- fn();
53
-
54
- // build
55
- export default {
56
- ...,
57
- external: ['external-pkg', ...],
58
- plugins: [
59
- rtc({
60
- // Chunks that import 'external-pkg' will output loader instead
61
- useLoader: (pkg) => pkg === 'external-pkg';
62
- });
63
- ]
64
- }
65
- ```
66
-
67
- ## Limitation
68
- Library code and startup code that uses `runtime-compiler` cannot be mixed together in the same chunk.
69
- ```ts
70
- import { IS_AOT } from 'runtime-compiler/env';
71
- import { evaluate } from 'runtime-compiler';
72
-
73
- const fn = evaluate<typeof console.log>(IS_AOT || `return console.log`)('Hi');
74
36
 
75
- // AOT build will break this export
76
- export const createFn = () => evaluate<typeof console.log>(IS_AOT || `return console.log`);
37
+ // dist/index.js
38
+ var fib_default = 144;
39
+ export { fib_default as default };
77
40
  ```
package/build.d.mts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/build.mjs ADDED
@@ -0,0 +1,34 @@
1
+ import uneval from "uneval";
2
+ import process from "node:process";
3
+ import { parentPort } from "node:worker_threads";
4
+ process.on("beforeExit", () => {
5
+ artifacts.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]);
6
+ parentPort.postMessage(artifacts);
7
+ });
8
+ const artifacts = [];
9
+ const options = { custom: (value) => {
10
+ if (typeof value === "function") {
11
+ let str = "" + value;
12
+ // classes
13
+ if (str.startsWith("class ")) throw new Error("Cannot serialize classes!");
14
+ // class methods
15
+ if (!Object.hasOwn(value, "prototype") && !str.includes("=>", 1)) str = "function " + str;
16
+ return str;
17
+ }
18
+ } };
19
+ /**
20
+ * @internal
21
+ */
22
+ export default (value) => {
23
+ const pos = /:([0-9]+):([0-9]+)/.exec(new Error().stack.split("\n", 3)[2]);
24
+ try {
25
+ artifacts.push([
26
+ +pos[1] - 1,
27
+ +pos[2] - 1,
28
+ uneval(value, options)
29
+ ]);
30
+ } catch (e) {
31
+ console.error(e);
32
+ }
33
+ return value;
34
+ };
package/evaluate.d.mts ADDED
@@ -0,0 +1,5 @@
1
+ import type { __rtcpl_content__ } from "./index.mts";
2
+ export declare const evaluate: (code: string) => Promise<[startIdx: number, endIdx: number, value: string][]>;
3
+ export declare const update: (magicString: {
4
+ update(start: number, end: number, str: string): any;
5
+ }, code: string, artifacts: typeof __rtcpl_content__) => void;
package/evaluate.mjs ADDED
@@ -0,0 +1,31 @@
1
+ import { Worker } from "node:worker_threads";
2
+ export const evaluate = (code) => new Promise((res, rej) => {
3
+ const worker = new Worker(code + "\n\n;import{__rtcpl_content__}from\"runtime-compiler\";import{parentPort as __rtcpl_port__}from\"node:worker_threads\";__rtcpl_port__.postMessage(__rtcpl_content__)", { eval: true });
4
+ worker.once("message", (msg) => {
5
+ res(msg);
6
+ worker.terminate();
7
+ });
8
+ worker.once("error", rej);
9
+ });
10
+ export const update = (magicString, code, artifacts) => {
11
+ artifacts.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]);
12
+ for (let entryIdx = 0, currentLine = 0, eolIdx = 0; entryIdx < artifacts.length; entryIdx++) {
13
+ // Infer actual position of the call in the code string
14
+ const entry = artifacts[entryIdx], entryLine = entry[0];
15
+ while (currentLine < entryLine) {
16
+ eolIdx = code.indexOf("\n", eolIdx) + 1;
17
+ currentLine++;
18
+ }
19
+ // find entry end
20
+ let entryStart = eolIdx + entry[1], entryEnd = entryStart, stack = 1;
21
+ // first start of call
22
+ while (code[entryEnd++] !== "(");
23
+ // find end of call
24
+ while (true) {
25
+ const cur = code[entryEnd++];
26
+ if (cur === "(") stack++;
27
+ else if (cur === ")" && --stack == 0) break;
28
+ }
29
+ magicString.update(entryStart, entryEnd, `(${entry[2]})`);
30
+ }
31
+ };
package/index.d.mts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Serialize the value at build time and replace the call with the serialized value at runtime.
3
+ * @example
4
+ * // input source file
5
+ * import evaluate from 'runtime-compiler';
6
+ *
7
+ * const fib = (i: number): number => (i < 2 ? i : fib(i - 1) + fib(i - 2));
8
+ * export default evaluate(fib(12));
9
+ *
10
+ * // compiled & minified to
11
+ * var e=144;export{e as default};
12
+ */
13
+ declare const evaluate: <T>(v: T) => T;
14
+ export default evaluate;
package/index.mjs ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Serialize the value at build time and replace the call with the serialized value at runtime.
3
+ * @example
4
+ * // input source file
5
+ * import evaluate from 'runtime-compiler';
6
+ *
7
+ * const fib = (i: number): number => (i < 2 ? i : fib(i - 1) + fib(i - 2));
8
+ * export default evaluate(fib(12));
9
+ *
10
+ * // compiled & minified to
11
+ * var e=144;export{e as default};
12
+ */
13
+ const evaluate = (v) => v;
14
+ export default evaluate;
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name":"runtime-compiler","version":"4.2.2","description":"A code generation system.","keywords":["rolldown-plugin","vite-plugin"],"homepage":"","license":"MIT","repository":"re-utils/runtime-compiler","type":"module","exports":{"./*":"./*.js",".":"./index.js","./env":"./env/index.js"}}
1
+ {"type":"module","version":"5.0.0","description":"A compile time evaluation system.","keywords":["rolldown-plugin"],"homepage":"","repository":"","exports":{".":"./index.mjs","./*":"./*.mjs"},"sideEffects":false,"dependencies":{"uneval":"^0.5.1"},"name":"runtime-compiler"}
package/rolldown.d.mts ADDED
@@ -0,0 +1,5 @@
1
+ import type { Plugin } from "rolldown";
2
+ declare const rtc: (options?: {
3
+ evaluate?: boolean;
4
+ }) => Plugin;
5
+ export default rtc;
package/rolldown.mjs ADDED
@@ -0,0 +1,70 @@
1
+ import { evaluate } from "./utils.mjs";
2
+ import { Visitor } from "rolldown/utils";
3
+ // sync parse & overwrite calls to evaluate() with the evaluated value
4
+ let _artifacts, _cur_artifacts_idx, _ms, _fn_name, VISIT_STOP = Symbol(), visitor = new Visitor({ CallExpression(node) {
5
+ while (_cur_artifacts_idx < _artifacts.length && node.start > _artifacts[_cur_artifacts_idx][0]) _cur_artifacts_idx++;
6
+ // stop ast tranverse if out of bound
7
+ if (_artifacts.length === _cur_artifacts_idx) throw VISIT_STOP;
8
+ const artifact = _artifacts[_cur_artifacts_idx];
9
+ if (artifact[0] === node.start) {
10
+ const { callee } = node;
11
+ if (callee.type === "Identifier" && callee.name === _fn_name) _ms.update(node.start, node.end, `(${artifact[2]})`);
12
+ }
13
+ } });
14
+ const rtc = (options) => ({
15
+ name: "rolldown-plugin-runtime-compiler",
16
+ resolveId: {
17
+ order: "pre",
18
+ filter: { id: /^runtime-compiler$/ },
19
+ handler: () => ({
20
+ id: "runtime-compiler/build",
21
+ external: "absolute"
22
+ })
23
+ },
24
+ async renderChunk(code, chunk, _, meta) {
25
+ const importIdx = chunk.imports.indexOf("runtime-compiler/build");
26
+ if (importIdx === -1) return null;
27
+ const ms = meta.magicString;
28
+ if (ms == null) {
29
+ this.warn("This plugin requires Rolldown native MagicString support!");
30
+ return null;
31
+ }
32
+ // remove runtime-compiler/build import
33
+ let fn_name;
34
+ chunk.imports.splice(importIdx, 1);
35
+ ms.replace(/import (.*) from.?.runtime-compiler\/build./, (_, $1) => `const ${fn_name = $1}=v=>v`);
36
+ // apply artifacts
37
+ if (options?.evaluate !== false) {
38
+ this.debug(`evaluating chunk "${chunk.fileName}" in a worker`);
39
+ let time = performance.now();
40
+ const artifacts = await evaluate(code);
41
+ time = performance.now() - time;
42
+ this.debug(`evaluated chunk "${chunk.fileName}" in ${time.toFixed(2)}ms`);
43
+ this.debug(`replace chunk "${chunk.fileName}" evaluate() calls with evaluated values`);
44
+ time = performance.now();
45
+ // Infer actual start positions of the call expressions in the code string
46
+ for (let entryIdx = 0, currentLine = 0, eolIdx = 0; entryIdx < artifacts.length; entryIdx++) {
47
+ const entry = artifacts[entryIdx], entryLine = entry[0];
48
+ while (currentLine < entryLine) {
49
+ eolIdx = code.indexOf("\n", eolIdx) + 1;
50
+ currentLine++;
51
+ }
52
+ entry[0] = eolIdx + entry[1];
53
+ }
54
+ try {
55
+ _artifacts = artifacts;
56
+ _cur_artifacts_idx = 0;
57
+ _ms = ms;
58
+ _fn_name = fn_name;
59
+ visitor.visit(this.parse(code));
60
+ } catch (e) {
61
+ // visit stops
62
+ if (e !== VISIT_STOP) throw e;
63
+ }
64
+ time = performance.now() - time;
65
+ this.debug(`replace "${chunk.fileName}" evaluate() calls in ${time.toFixed(2)}ms`);
66
+ }
67
+ return { code: ms };
68
+ }
69
+ });
70
+ export default rtc;
package/utils.d.mts ADDED
@@ -0,0 +1,2 @@
1
+ export type Artifacts = [startLine: number, startPos: number, value: string][];
2
+ export declare const evaluate: (code: string) => Promise<Artifacts>;
package/utils.mjs ADDED
@@ -0,0 +1,9 @@
1
+ import { Worker } from "node:worker_threads";
2
+ export const evaluate = (code) => new Promise((res, rej) => {
3
+ const worker = new Worker(code, { eval: true });
4
+ worker.once("message", (msg) => {
5
+ res(msg);
6
+ worker.terminate();
7
+ });
8
+ worker.once("error", rej);
9
+ });
package/build.d.ts DELETED
@@ -1,12 +0,0 @@
1
- /**
2
- * Requires code to not bundle "runtime-compiler/env" and "runtime-compiler"
3
- */
4
- export declare const runInWorker: (code: string) => Promise<string>;
5
- /**
6
- * Requires code to not bundle `runtime-compiler/env` and `runtime-compiler`
7
- *
8
- * @example
9
- * writeFileSync('preload.js', compile(await runInWorker(code)));
10
- * code = 'import"./preload.js";' + code;
11
- */
12
- export declare const compile: (codes: string) => string;
package/build.js DELETED
@@ -1 +0,0 @@
1
- import{Worker}from"node:worker_threads";let workerOptions={eval:!0};export const runInWorker=code=>new Promise((res,rej)=>{let worker=new Worker(`import"runtime-compiler/env/build";${code};\nimport{__rtcpl_ct__}from"runtime-compiler";import{parentPort as __rtcpl_pp__}from"node:worker_threads";process.on('beforeExit',()=>__rtcpl_pp__.postMessage(__rtcpl_ct__))`,workerOptions);worker.once("message",msg=>{res(msg);worker.terminate()});worker.once("error",rej)});export const compile=codes=>`import"runtime-compiler/env/aot";import{__rtcpl_aot_fns__ as a}from"runtime-compiler";a.push(${codes})`;
package/env/aot.js DELETED
@@ -1 +0,0 @@
1
- import{__rtcpl_aot__}from"./index.js";__rtcpl_aot__();
package/env/build.js DELETED
@@ -1 +0,0 @@
1
- import{__rtcpl_build__}from"./index.js";__rtcpl_build__();
package/env/index.d.ts DELETED
@@ -1,3 +0,0 @@
1
- export declare let IS_JIT: boolean;
2
- export declare let IS_BUILD: boolean;
3
- export declare let IS_AOT: boolean;
package/env/index.js DELETED
@@ -1 +0,0 @@
1
- export let IS_JIT=!0;export let IS_BUILD=!1;export let IS_AOT=!1;export const __rtcpl_build__=()=>{IS_JIT=!1;IS_BUILD=!0;IS_AOT=!1};export const __rtcpl_aot__=()=>{IS_JIT=!1;IS_BUILD=!1;IS_AOT=!0};
package/index.d.ts DELETED
@@ -1,8 +0,0 @@
1
- export type Ref<T> = number & {
2
- "~": T;
3
- };
4
- export declare const ref: <T>(value: T) => Ref<T>;
5
- export declare const createRef: <T>() => Ref<T>;
6
- export declare let evaluate: <T>(content?: any) => T;
7
- export declare let evaluateAsync: <T>(content?: any) => Promise<T>;
8
- export declare const deref: <T>(id: Ref<T>) => T;
package/index.js DELETED
@@ -1 +0,0 @@
1
- import{IS_AOT,IS_BUILD}from"./env/index.js";let __rtcpl_r__=[];export const ref=value=>__rtcpl_r__.push(value)-1;export const createRef=()=>__rtcpl_r__.push(void 0)-1;export let __rtcpl_ct__="";export let evaluate=IS_AOT?()=>__rtcpl_aot_fns__.pop()(__rtcpl_r__):IS_BUILD?content=>{if("string"!=typeof content)throw new Error("Expected a string for content in JIT & BUILD mode");content=`$=>{${content}}`;__rtcpl_ct__=content+","+__rtcpl_ct__;return(0,eval)('"use strict";'+content)(__rtcpl_r__)}:content=>{if("string"!=typeof content)throw new Error("Expected a string for content in JIT & BUILD mode");return(0,eval)(`"use strict";$=>{${content}}`)(__rtcpl_r__)};export let evaluateAsync=IS_AOT?evaluate:IS_BUILD?content=>{if("string"!=typeof content)throw new Error("Expected a string for content in JIT & BUILD mode");content=`async $=>{${content}}`;__rtcpl_ct__=content+","+__rtcpl_ct__;return(0,eval)('"use strict";'+content)(__rtcpl_r__)}:content=>{if("string"!=typeof content)throw new Error("Expected a string for content in JIT & BUILD mode");return(0,eval)(`"use strict";async $=>{${content}}`)(__rtcpl_r__)};export const __rtcpl_aot_fns__=[];export const deref=id=>__rtcpl_r__[id];
package/rolldown.d.ts DELETED
@@ -1,17 +0,0 @@
1
- import type { Plugin } from "rolldown";
2
- type RenderChunk = Exclude<Plugin["renderChunk"] & {}, (...args: any[]) => any>;
3
- declare const _default: (options?: {
4
- /**
5
- * Function to check whether this external dependency uses `runtime-compiler` without bundling.
6
- */
7
- useLoader?: (importName: string) => boolean;
8
- /**
9
- * Choose what chunk to run `renderChunk`.
10
- */
11
- filter?: RenderChunk["filter"];
12
- /**
13
- * Choose the order to run `renderChunk`. Defaults to `pre`.
14
- */
15
- order?: RenderChunk["order"];
16
- }) => Plugin;
17
- export default _default;
package/rolldown.js DELETED
@@ -1 +0,0 @@
1
- import{runInWorker,compile}from"./build.js";export const parseImportBindings=(code,start,end)=>{let startSpecs=code.indexOf("{",start),endSpecs=code.lastIndexOf("}",end);if(-1===start&&-1===end)throw new Error("Only named imports is supported");let bindings=[];for(let i=0,specifiers=code.slice(startSpecs+1,endSpecs-1).split(",");i<specifiers.length;i++){let specifier=specifiers[i].trim();if(""===specifier)continue;let parts=specifier.split(" as ",2);if(1===parts.length){let name=parts[0].trim();bindings.push({name,alias:name})}else bindings.push({name:parts[0].trim(),alias:parts[1].trim()})}return{bindings,start,end}};let EMPTY_IMPORT={bindings:[],start:0,end:0};export default((options={})=>({name:"rolldown-plugin-runtime-compiler",resolveId:{filter:{id:/^runtime-compiler(?:$|\/env$)/},handler:()=>!1},renderChunk:{filter:options.filter,order:options.order??"pre",async handler(code,chunk){let{imports}=chunk,useLoader=options.useLoader&&imports.some(options.useLoader),envImport=null;{let envImportIdx=imports.indexOf("runtime-compiler/env");-1===envImportIdx?envImport=EMPTY_IMPORT:imports.splice(envImportIdx,1)}let globalsImport=null;if(useLoader)globalsImport=EMPTY_IMPORT;else{let globalsImportIdx=imports.indexOf("runtime-compiler");if(-1===globalsImportIdx){if(envImport===EMPTY_IMPORT)return null;globalsImport=EMPTY_IMPORT}else imports.splice(globalsImportIdx,1)}for(let start=0,eol=code.indexOf("\n");eol>-1&&(null==envImport||null==globalsImport);eol=code.indexOf("\n",start=eol+1))code.startsWith("import",start)&&(null==envImport&&code.endsWith('"runtime-compiler/env";',eol)?envImport=parseImportBindings(code,start,eol):null==globalsImport&&code.endsWith('"runtime-compiler";',eol)&&(globalsImport=parseImportBindings(code,start,eol)));let codes=await runInWorker(code);if(useLoader){let fileName=chunk.fileName+"-rtc-aot-loader.js";this.emitFile({type:"prebuilt-chunk",code:compile(codes),fileName});let aotCode="import"+JSON.stringify(fileName)+";";for(let i=0,{bindings}=envImport;i<bindings.length;i++){let{name,alias}=bindings[i];aotCode+="IS_AOT"===name?`const ${alias}=true;`:"IS_BUILD"===name||"IS_JIT"===name?`const ${alias}=false;`:""}return aotCode+code.slice(0,envImport.start)+code.slice(envImport.end)}{let aotCode=`const __rtcpl_r__=[],__rtcpl_aot_fns__=[${codes}]`;for(let i=0,{bindings}=envImport;i<bindings.length;i++){let{name,alias}=bindings[i];aotCode+="IS_AOT"===name?`,${alias}=true`:"IS_BUILD"===name||"IS_JIT"===name?`,${alias}=false`:""}for(let i=0,{bindings}=globalsImport;i<bindings.length;i++){let{name,alias}=bindings[i];aotCode+="deref"===name?`,${alias}=i=>__rtcpl_r__[i]`:"evaluate"===name||"evaluateAsync"===name?`,${alias}=()=>__rtcpl_aot_fns__.pop()(__rtcpl_r__)`:"createRef"===name?`,${alias}=()=>__rtcpl_r__.push(undefined)-1`:"ref"===name?`,${alias}=v=>__rtcpl_r__.push(v)-1`:""}return aotCode+";"+(envImport.start<globalsImport.start?code.slice(0,envImport.start)+code.slice(envImport.end,globalsImport.start)+code.slice(globalsImport.end):code.slice(0,globalsImport.start)+code.slice(globalsImport.end,envImport.start)+code.slice(envImport.end))}}}}));