runtime-compiler 4.0.4 → 4.1.1

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
@@ -3,7 +3,7 @@ A code generation system.
3
3
  # Usage
4
4
  ```ts
5
5
  import { IS_AOT, IS_BUILD } from 'runtime-compiler/env';
6
- import { evaluate } from 'runtime-compiler/globals';
6
+ import { evaluate } from 'runtime-compiler';
7
7
 
8
8
  // Only log when building
9
9
  IS_BUILD && console.log('Building...');
@@ -15,18 +15,50 @@ const fn = evaluate<() => void>(IS_AOT || `return()=>console.log("Hi")`);
15
15
  IS_BUILD || fn();
16
16
  ```
17
17
 
18
- Build with `rolldown` or `vite`:
18
+ Build with `rolldown`:
19
19
  ```ts
20
20
  ...
21
- import rtc from 'runtime-compiler/build/rolldown';
21
+ import rtc from 'runtime-compiler/rolldown';
22
22
 
23
23
  export default defineConfig({
24
- ...,
25
- plugins: [
26
- ...,
27
- rtc()
28
- ]
24
+ plugins: [rtc()]
29
25
  });
30
26
  ```
31
27
 
32
- You only need to build when the target runtime doesn't allow `eval()`.
28
+ Or Vite:
29
+ ```ts
30
+ import rtc from 'runtime-compiler/rolldown';
31
+
32
+ export default defineConfig({
33
+ // Only run this plugin on build
34
+ build: {
35
+ rolldownOptions: {
36
+ plugins: [rtc()]
37
+ }
38
+ }
39
+ });
40
+ ```
41
+
42
+ If you have dependencies marked as external that uses `runtime-compiler`:
43
+ ```ts
44
+ // package: external-pkg
45
+ import { evaluate } from 'runtime-compiler';
46
+
47
+
48
+ rtc({
49
+ // Return true if the package uses 'runtime-compiler' at startup time without pre-building.
50
+ useLoader: (externalPkg) => ...
51
+ });
52
+ ```
53
+
54
+ ## Limitation
55
+ Library code and startup code that uses `runtime-compiler` cannot be mixed together in the same bundle.
56
+ ```ts
57
+ import { IS_AOT } from 'runtime-compiler/env';
58
+ import { evaluate } from 'runtime-compiler';
59
+
60
+ const fn = evaluate<typeof console.log>(IS_AOT || `return console.log`)('Hi');
61
+
62
+ // AOT build will break this export
63
+ export const createFn = () => evaluate<typeof console.log>(IS_AOT || `return console.log`);
64
+ ```
package/build.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export declare const getPromiseResolvers: (res: any, rej: any) => void;
2
+ /**
3
+ * Requires code to not bundle "runtime-compiler/env" and "runtime-compiler"
4
+ */
5
+ export declare const runInWorker: (code: string) => Promise<string>;
6
+ /**
7
+ * Requires code to not bundle `runtime-compiler/env` and `runtime-compiler`
8
+ *
9
+ * @example
10
+ * writeFileSync('preload.js', compile(await runInWorker(code)));
11
+ * code = 'import"./preload.js";' + code;
12
+ */
13
+ export declare const compile: (codes: string) => string;
package/build.js ADDED
@@ -0,0 +1 @@
1
+ import{Worker}from"node:worker_threads";let curRes,curRej;export const getPromiseResolvers=(res,rej)=>{curRes=res;curRej=rej};let workerOptions={eval:!0};export const runInWorker=code=>{let p=new Promise(getPromiseResolvers),worker=new Worker(`import"runtime-compiler/env/build";${code};\nimport{__rtcpl_ct__}from"runtime-compiler";import{parentPort as __rtcpl_pp__}from"node:worker_threads";__rtcpl_pp__.postMessage(__rtcpl_ct__);throw 0`,workerOptions);worker.once("message",curRes);worker.once("error",curRej);return p};export const compile=codes=>`import"runtime-compiler/env/aot";import{__rtcpl_aot_fns__ as a}from"runtime-compiler";a.push(${codes})`;
@@ -1,7 +1,8 @@
1
1
  export type Ref<T> = number & {
2
2
  "~": T;
3
3
  };
4
- export declare const importRef: <T>(value: T) => Ref<T>;
4
+ export declare const ref: <T>(value: T) => Ref<T>;
5
5
  export declare const createRef: <T>() => Ref<T>;
6
6
  export declare let evaluate: <T>(content?: string | boolean | null | undefined) => T;
7
+ export declare let evaluateAsync: <T>(content?: string | boolean | null | undefined) => Promise<T>;
7
8
  export declare const deref: <T>(id: Ref<T>) => T;
package/index.js ADDED
@@ -0,0 +1 @@
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){content=`$=>{${content}}`;__rtcpl_ct__=content+","+__rtcpl_ct__;return(0,eval)(content)(__rtcpl_r__)}__rtcpl_ct__="$=>{},"+__rtcpl_ct__}:content=>{if("string"==typeof content)return(0,eval)(`$=>{${content}}`)(__rtcpl_r__)};export let evaluateAsync=IS_AOT?_=>__rtcpl_aot_fns__.pop()(__rtcpl_r__):IS_BUILD?async content=>{if("string"==typeof content){content=`async $=>{${content}}`;__rtcpl_ct__=content+","+__rtcpl_ct__;return(0,eval)(content)(__rtcpl_r__)}__rtcpl_ct__="async $=>{},"+__rtcpl_ct__}:async content=>{if("string"==typeof content)return(0,eval)(`async $=>{${content}}`)(__rtcpl_r__)};export const __rtcpl_aot_fns__=[];export const deref=id=>__rtcpl_r__[id];
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name":"runtime-compiler","version":"4.0.4","description":"A code generation system.","keywords":[],"homepage":"","license":"MIT","repository":"","type":"module","exports":{"./*":"./*.js","./build":"./build/index.js","./env":"./env/index.js"}}
1
+ {"name":"runtime-compiler","version":"4.1.1","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"}}
package/rolldown.d.ts ADDED
@@ -0,0 +1,17 @@
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`.
14
+ */
15
+ order?: RenderChunk["order"];
16
+ }) => Plugin;
17
+ export default _default;
package/rolldown.js ADDED
@@ -0,0 +1 @@
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 replacement 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))}}}}));
package/build/index.d.ts DELETED
@@ -1,9 +0,0 @@
1
- export declare const getPromiseResolvers: (res: any, rej: any) => void;
2
- /**
3
- * Requires code to not bundle "runtime-compiler/env" and "runtime-compiler/globals"
4
- */
5
- export declare const runInWorker: (code: string) => Promise<string[]>;
6
- /**
7
- * Requires code to not bundle "runtime-compiler/env" and "runtime-compiler/globals"
8
- */
9
- export declare const compile: (code: string) => Promise<string>;
package/build/index.js DELETED
@@ -1 +0,0 @@
1
- import{Worker}from"node:worker_threads";let curRes,curRej;export const getPromiseResolvers=(res,rej)=>{curRes=res;curRej=rej};let workerOptions={eval:!0};export const runInWorker=code=>{let p=new Promise(getPromiseResolvers),worker=new Worker(`import"runtime-compiler/env/build";${code};\nimport{__rtcpl_ct__}from"runtime-compiler/globals";import{parentPort as __rtcpl_pp__}from"node:worker_threads";__rtcpl_pp__.postMessage(__rtcpl_ct__)`,workerOptions);worker.once("message",curRes);worker.once("error",curRej);return p};export const compile=async code=>{let str='import"runtime-compiler/env/aot";import{__rtcpl_aot_fns__}from"runtime-compiler/globals";__rtcpl_aot_fns__.push(';for(let codes=await runInWorker(code),i=codes.length-1;i>-1;i--)str+=`$=>{${codes[i]}},`;return str+");"+code};
@@ -1,3 +0,0 @@
1
- import type { Plugin } from "rolldown";
2
- declare const _default: () => Plugin;
3
- export default _default;
package/build/rolldown.js DELETED
@@ -1 +0,0 @@
1
- import{runInWorker}from"./index.js";let parseImportBindings=(code,start,end)=>{let startSpecs=code.indexOf("{",start),endSpecs=code.lastIndexOf("}",end);if(-1===start&&-1===end)throw new Error("Only named imports replacement 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}};export default(()=>({name:"rolldown-plugin-runtime-compiler",resolveId:{filter:{id:/^runtime-compiler\/(?:env|globals)$/},handler:()=>!1},renderChunk:async(code,{imports})=>{let globalsImportIdx=imports.indexOf("runtime-compiler/globals");if(-1===globalsImportIdx)return null;imports.splice(globalsImportIdx);let envImportIdx=imports.indexOf("runtime-compiler/env"),envImport=null,globalsImport=null;-1===envImportIdx?envImport={bindings:[],start:0,end:0}:imports.splice(envImportIdx,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)&&(code.endsWith('"runtime-compiler/env";',eol)?envImport=parseImportBindings(code,start,eol):code.endsWith('"runtime-compiler/globals";',eol)&&(globalsImport=parseImportBindings(code,start,eol)));let aotCode="const __rtcpl_r__=[],__rtcpl_aot_fns__=[";for(let codes=await runInWorker(code),i=codes.length-1;i>-1;i--)aotCode+=`$=>{${codes[i]}},`;aotCode+="]";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?`,${alias}=(_)=>__rtcpl_aot_fns__.pop()(__rtcpl_r__)`:"createRef"===name?`,${alias}=()=>__rtcpl_r__.push(undefined)-1`:"importRef"===name?`,${alias}=v=>__rtcpl_r__.push(v)-1`:""}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));return{code:aotCode}}}));
package/globals.js DELETED
@@ -1 +0,0 @@
1
- import{IS_AOT,IS_BUILD}from"./env/index.js";let __rtcpl_r__=[];export const importRef=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){__rtcpl_ct__.push(content);return(0,eval)(`$=>{${content}}`)(__rtcpl_r__)}__rtcpl_ct__.push("")}:content=>{if("string"==typeof content)return(0,eval)(`$=>{${content}}`)(__rtcpl_r__)};export const __rtcpl_aot_fns__=[];export const deref=id=>__rtcpl_r__[id];
package/utils.d.ts DELETED
@@ -1,8 +0,0 @@
1
- export type Expr<T> = string & {
2
- "~": T;
3
- };
4
- export type Id<T> = Expr<T> & {
5
- "~id": 0;
6
- };
7
- export declare const toExpr: <T>(str: string) => Expr<T>;
8
- export declare const toId: <T>(str: string | Expr<T>) => Id<T>;
package/utils.js DELETED
@@ -1 +0,0 @@
1
- export const toExpr=str=>str;export const toId=toExpr;