@@ -8,11 +8,18 @@ export const main = async (
88 pkg : { name : string ; version : string } ,
99 options ?: Parameters < typeof DefaultRubyVM > [ 1 ] ,
1010) => {
11+ const scriptEnv = deriveEnv ( document . currentScript ) ;
1112 const response = fetch (
1213 `https://cdn.jsdelivr.net/npm/${ pkg . name } @${ pkg . version } /dist/ruby+stdlib.wasm` ,
1314 ) ;
1415 const module = await compileWebAssemblyModule ( response ) ;
15- const { vm } = await DefaultRubyVM ( module , options ) ;
16+ const { vm } = await DefaultRubyVM ( module , {
17+ ...options ,
18+ env : {
19+ ...scriptEnv ,
20+ ...options ?. env ,
21+ } ,
22+ } ) ;
1623 await mainWithRubyVM ( vm ) ;
1724} ;
1825
@@ -24,12 +31,18 @@ export const componentMain = async (
2431 options : {
2532 instantiate : RubyComponentInstantiator ;
2633 wasip2 : any ;
34+ env ?: Record < string , string > | undefined ;
2735 }
2836) => {
37+ const scriptEnv = deriveEnv ( document . currentScript ) ;
2938 const componentUrl = `https://cdn.jsdelivr.net/npm/${ pkg . name } @${ pkg . version } /dist/component` ;
3039 const fetchComponentFile = ( relativePath : string ) => fetch ( `${ componentUrl } /${ relativePath } ` ) ;
3140 const { vm } = await RubyVM . instantiateComponent ( {
3241 ...options ,
42+ env : {
43+ ...scriptEnv ,
44+ ...options . env ,
45+ } ,
3346 getCoreModule : ( relativePath : string ) => {
3447 const response = fetchComponentFile ( relativePath ) ;
3548 return compileWebAssemblyModule ( response ) ;
@@ -90,6 +103,34 @@ const deriveEvalStyle = (tag: Element): "async" | "sync" => {
90103 return rawEvalStyle ;
91104} ;
92105
106+ const deriveEnv = ( tag : Element | null ) : Record < string , string > => {
107+ const rawEnv = tag ?. getAttribute ( "data-env" ) ;
108+ if ( ! rawEnv ) {
109+ return { } ;
110+ }
111+
112+ const trimmedEnv = rawEnv . trim ( ) ;
113+ if ( ! trimmedEnv ) {
114+ return { } ;
115+ }
116+
117+ return trimmedEnv
118+ . split ( / \s + / )
119+ . reduce < Record < string , string > > ( ( env , entry ) => {
120+ const delimiterIndex = entry . indexOf ( "=" ) ;
121+ if ( delimiterIndex <= 0 ) {
122+ console . warn (
123+ `data-env entry must be in the KEY=value format. ${ entry } is ignored.` ,
124+ ) ;
125+ return env ;
126+ }
127+
128+ // Only the first "=" separates key and value so values can contain "=".
129+ env [ entry . slice ( 0 , delimiterIndex ) ] = entry . slice ( delimiterIndex + 1 ) ;
130+ return env ;
131+ } , { } ) ;
132+ } ;
133+
93134const loadScriptAsync = async (
94135 tag : Element ,
95136) : Promise < { scriptContent : string ; evalStyle : "async" | "sync" } | null > => {
0 commit comments