@vizhub/runtime 0.7.0 → 2.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.
Files changed (43) hide show
  1. package/README.md +71 -21
  2. package/dist/build/build.d.ts.map +1 -1
  3. package/dist/build/determineRuntimeVersion.d.ts.map +1 -1
  4. package/dist/build/index.d.ts +1 -0
  5. package/dist/build/index.d.ts.map +1 -1
  6. package/dist/common/sucrasePlugin.d.ts +1 -1
  7. package/dist/common/sucrasePlugin.d.ts.map +1 -1
  8. package/dist/common/virtualFileSystem.d.ts +2 -1
  9. package/dist/common/virtualFileSystem.d.ts.map +1 -1
  10. package/dist/index.cjs +206 -1
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.ts +1 -1
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +540 -138
  15. package/dist/index.js.map +1 -1
  16. package/dist/orchestration/createRuntime.d.ts.map +1 -1
  17. package/dist/orchestration/types.d.ts.map +1 -1
  18. package/dist/slugCache-DqUp8B5A.js +350 -0
  19. package/dist/slugCache-DqUp8B5A.js.map +1 -0
  20. package/dist/slugCache-mB6V-shn.cjs +4 -0
  21. package/dist/slugCache-mB6V-shn.cjs.map +1 -0
  22. package/dist/test/fixtures/v4/index.d.ts +2 -0
  23. package/dist/test/fixtures/v4/index.d.ts.map +1 -1
  24. package/dist/test/fixtures/v4/jsScriptTagTypeModulesRelative.d.ts +6 -0
  25. package/dist/test/fixtures/v4/jsScriptTagTypeModulesRelative.d.ts.map +1 -0
  26. package/dist/test/fixtures/v4/reactJsx.d.ts +0 -1
  27. package/dist/test/fixtures/v4/reactJsx.d.ts.map +1 -1
  28. package/dist/test/fixtures/v4/reactJsxWithoutImport.d.ts +6 -0
  29. package/dist/test/fixtures/v4/reactJsxWithoutImport.d.ts.map +1 -0
  30. package/dist/test/testInBrowser.d.ts +1 -1
  31. package/dist/test/testInBrowser.d.ts.map +1 -1
  32. package/dist/v3/slugCache.d.ts.map +1 -1
  33. package/dist/v4/bundleModule.d.ts.map +1 -1
  34. package/dist/v4/catchAll.d.ts +8 -0
  35. package/dist/v4/catchAll.d.ts.map +1 -0
  36. package/dist/worker.cjs +1 -1
  37. package/dist/worker.cjs.map +1 -1
  38. package/dist/worker.js +7 -7
  39. package/package.json +3 -3
  40. package/dist/build-BAZMN_vU.cjs +0 -214
  41. package/dist/build-BAZMN_vU.cjs.map +0 -1
  42. package/dist/build-NWFvyYnC.js +0 -866
  43. package/dist/build-NWFvyYnC.js.map +0 -1
package/README.md CHANGED
@@ -23,14 +23,15 @@ The library automatically detects which runtime version to use based on the file
23
23
  | **Custom `index.html`** | ✅ | ✅ | ⬜️ | ✅ |
24
24
  | **Local ES Modules** | ⬜️ | ✅ | ✅ | ✅ |
25
25
  | **UMD Libraries** | ✅ | ✅ | ✅ | ⬜️ |
26
+ | **`package.json`** | ⬜️ | ✅ | ✅ | ⬜️ |
26
27
  | **ESM Libraries** | ⬜️ | ⬜️ | ⬜️ | ✅ |
27
28
  | **React JSX** | ⬜️ | ✅ | ⬜️ | ✅ |
28
- | **TypeScript** | ⬜️ | ⬜️ | ⬜️ | ✅ |
29
29
  | **Svelte** | ⬜️ | ⬜️ | ✅ | ⬜️ |
30
30
  | **Cross-Viz Imports** | ⬜️ | ⬜️ | ✅ | ⬜️ |
31
31
  | **Hot Reloading** | ⬜️ | ⬜️ | ✅ | ⬜️ |
32
32
  | **State Management** | ⬜️ | ⬜️ | ✅ | ⬜️ |
33
33
  | **Import from CSV** | ⬜️ | ⬜️ | ✅ | ⬜️ |
34
+ | **TypeScript** | ⬜️ | ⬜️ | ⬜️ | ✅ |
34
35
  | **`fetch` proxy** | ✅ | ✅ | ⬜️ | ✅ |
35
36
 
36
37
  ## V1 Runtime
@@ -132,10 +133,34 @@ export function render(element) {
132
133
  "d3": "7.8.5",
133
134
  "react": "18.2.0",
134
135
  "react-dom": "18.2.0"
136
+ },
137
+ "vizhub": {
138
+ "libraries": {
139
+ "d3": {
140
+ "global": "d3",
141
+ "path": "/dist/d3.min.js"
142
+ },
143
+ "react": {
144
+ "global": "React",
145
+ "path": "/umd/react.production.min.js"
146
+ },
147
+ "react-dom": {
148
+ "global": "ReactDOM",
149
+ "path": "/umd/react-dom.production.min.js"
150
+ }
151
+ }
135
152
  }
136
153
  }
137
154
  ```
138
155
 
156
+ The `vizhub` configuration in `package.json` specifies how external dependencies should be loaded:
157
+
158
+ - `libraries`: Maps package names to their UMD configuration
159
+ - `global`: The global variable name that the UMD bundle exposes
160
+ - `path`: The path to the UMD bundle within the package's CDN distribution
161
+
162
+ This configuration allows the V2 runtime to properly load and expose UMD bundles from CDNs like jsDelivr or unpkg. The runtime will automatically prefix the `path` with the appropriate CDN URL.
163
+
139
164
  V2 is ideal for more complex projects that require modular JavaScript and external dependencies that provide UMD builds. Note that the V2 runtime does not support ESM builds for external dependencies (see V4 if you need this).
140
165
 
141
166
  ## V3 Runtime
@@ -152,14 +177,22 @@ In V3 runtime:
152
177
  - Cross-viz imports allow you to import code from other viz instances
153
178
  - The runtime provides a built-in state management system
154
179
 
155
- ### State Management in V3
180
+ ### State Management and Hot Reloading in V3
156
181
 
157
- V3 runtime includes a built-in state management system via the [unidirectional-data-flow](https://www.npmjs.com/package/unidirectional-data-flow) package ([GitHub](https://github.com/vizhub-core/unidirectional-data-flow)). This provides React-like state management capabilities with:
182
+ V3 runtime includes a built-in state management system based on the [unidirectional-data-flow](https://www.npmjs.com/package/unidirectional-data-flow) package ([GitHub](https://github.com/vizhub-core/unidirectional-data-flow)). This provides React-like state management capabilities with:
158
183
 
159
- - A `main` entry point
184
+ - A `main` entry point that receives container and state management options
160
185
  - A minimal state management system based on `state` and `setState`
161
186
  - Similar semantics to React's `useState` hook: `const [state, setState] = useState({})`
162
187
  - Automatic re-rendering when state changes
188
+ - Hot module reloading that preserves state between updates
189
+
190
+ The hot reloading system will:
191
+
192
+ - Preserve state between code updates
193
+ - Re-execute the main function with the current state
194
+ - Only reload changed modules
195
+ - Maintain the visualization's current state (e.g. D3 selections, transitions)
163
196
 
164
197
  ### The Problem: Re-using D3 Rendering Logic Across Frameworks
165
198
 
@@ -218,42 +251,59 @@ As a VizHub user, you'll create an `index.html` file with import maps and ES mod
218
251
 
219
252
  ```html
220
253
  <!DOCTYPE html>
221
- <html>
254
+ <html lang="en">
222
255
  <head>
256
+ <meta charset="UTF-8" />
257
+ <title>React App</title>
223
258
  <script type="importmap">
224
259
  {
225
260
  "imports": {
226
- "utils": "./utils.js",
227
- "d3": "https://cdn.jsdelivr.net/npm/d3@7.8.5/+esm"
261
+ "react": "https://cdn.jsdelivr.net/npm/react@19.1.0/+esm",
262
+ "react/jsx-runtime": "https://cdn.jsdelivr.net/npm/react@19.1.0/jsx-runtime/+esm",
263
+ "react-dom/client": "https://cdn.jsdelivr.net/npm/react-dom@19.1.0/client/+esm"
228
264
  }
229
265
  }
230
266
  </script>
231
267
  </head>
232
268
  <body>
233
- <div id="app"></div>
234
- <script type="module" src="index.js"></script>
269
+ <div id="root"></div>
270
+ <script type="module" src="./index.tsx"></script>
235
271
  </body>
236
272
  </html>
237
273
  ```
238
274
 
239
- **index.js**
275
+ **index.tsx**
240
276
 
241
- ```javascript
242
- import { createApp } from "utils";
243
- import * as d3 from "d3";
277
+ ```typescript
278
+ import React, { useState, FC } from "react";
279
+ import { createRoot } from "react-dom/client";
244
280
 
245
- createApp(document.getElementById("app"));
246
- ```
281
+ interface CounterProps {}
247
282
 
248
- **utils.js**
283
+ const Counter: FC<CounterProps> = () => {
284
+ const [count, setCount] = useState<number>(0);
249
285
 
250
- ```javascript
251
- export function createApp(element) {
252
- element.innerHTML = "<h1>Hello from V4 runtime!</h1>";
253
- }
286
+ return (
287
+ <div>
288
+ <h1>Counter: {count}</h1>
289
+ <button onClick={() => setCount(count + 1)}>
290
+ Increment
291
+ </button>
292
+ </div>
293
+ );
294
+ };
295
+
296
+ const root = createRoot(document.getElementById("root")!);
297
+ root.render(<Counter />);
254
298
  ```
255
299
 
256
- V4 is ideal for modern browsers with native ES module support and when you want direct control over module resolution.
300
+ V4 is ideal for modern browsers with native ES module support, TypeScript development, and when you want direct control over module resolution. It supports:
301
+
302
+ - TypeScript with full type checking
303
+ - React with modern ESM builds
304
+ - Import maps for direct CDN dependencies
305
+ - Native ES modules without bundling
306
+ - Local module imports with relative paths
257
307
 
258
308
  ## Key Features
259
309
 
@@ -1 +1 @@
1
- {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/build/build.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACzD,OAAO,EAGL,SAAS,EACT,cAAc,EAEd,QAAQ,EACT,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAYtC,eAAO,MAAM,KAAK,GAAU,oFAQzB;IAGD,KAAK,CAAC,EAAE,cAAc,CAAC;IAGvB,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;IAQ1D,eAAe,CAAC,EAAE,OAAO,CAAC;IAI1B,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAGpB,KAAK,CAAC,EAAE,MAAM,CAAC;IAGf,SAAS,CAAC,EAAE,SAAS,CAAC;IAGtB,iBAAiB,CAAC,EAAE,MAAM,OAAO,CAAC,cAAc,CAAC,CAAC;CACnD,KAAG,OAAO,CAAC,WAAW,CA8GtB,CAAC"}
1
+ {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/build/build.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACzD,OAAO,EAGL,SAAS,EACT,cAAc,EAEd,QAAQ,EACT,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAUtC,eAAO,MAAM,KAAK,GAAU,oFAQzB;IAGD,KAAK,CAAC,EAAE,cAAc,CAAC;IAGvB,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;IAQ1D,eAAe,CAAC,EAAE,OAAO,CAAC;IAI1B,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAGpB,KAAK,CAAC,EAAE,MAAM,CAAC;IAGf,SAAS,CAAC,EAAE,SAAS,CAAC;IAGtB,iBAAiB,CAAC,EAAE,MAAM,OAAO,CAAC,cAAc,CAAC,CAAC;CACnD,KAAG,OAAO,CAAC,WAAW,CAmItB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"determineRuntimeVersion.d.ts","sourceRoot":"","sources":["../../src/build/determineRuntimeVersion.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC,eAAO,MAAM,uBAAuB,GAClC,OAAO,cAAc,KACpB,cAAc,GAAG,IA4BnB,CAAC"}
1
+ {"version":3,"file":"determineRuntimeVersion.d.ts","sourceRoot":"","sources":["../../src/build/determineRuntimeVersion.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC,eAAO,MAAM,uBAAuB,GAClC,OAAO,cAAc,KACpB,cAAc,GAAG,IA2BnB,CAAC"}
@@ -1,3 +1,4 @@
1
1
  export { build } from "./build";
2
+ export { determineRuntimeVersion } from "./determineRuntimeVersion";
2
3
  export type { BuildResult, runtimeVersion } from "./types";
3
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/build/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,YAAY,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/build/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,YAAY,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC"}
@@ -1,3 +1,3 @@
1
1
  import type { Plugin } from "rollup";
2
- export declare function sucrasePlugin(): Plugin;
2
+ export declare function sucrasePlugin(additionalOptions?: {}): Plugin;
3
3
  //# sourceMappingURL=sucrasePlugin.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sucrasePlugin.d.ts","sourceRoot":"","sources":["../../src/common/sucrasePlugin.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,wBAAgB,aAAa,IAAI,MAAM,CAwBtC"}
1
+ {"version":3,"file":"sucrasePlugin.d.ts","sourceRoot":"","sources":["../../src/common/sucrasePlugin.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,wBAAgB,aAAa,CAC3B,iBAAiB,KAAK,GACrB,MAAM,CA2BR"}
@@ -1,4 +1,5 @@
1
1
  import { FileCollection } from "@vizhub/viz-types";
2
- import { Plugin } from "rollup";
2
+ import type { Plugin } from "rollup";
3
+ export declare const VIRTUAL_PREFIX = "\0virtual:";
3
4
  export declare const virtualFileSystem: (files: FileCollection) => Plugin;
4
5
  //# sourceMappingURL=virtualFileSystem.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"virtualFileSystem.d.ts","sourceRoot":"","sources":["../../src/common/virtualFileSystem.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAsChC,eAAO,MAAM,iBAAiB,GAC5B,OAAO,cAAc,KACpB,MAuDF,CAAC"}
1
+ {"version":3,"file":"virtualFileSystem.d.ts","sourceRoot":"","sources":["../../src/common/virtualFileSystem.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,eAAO,MAAM,cAAc,eAAe,CAAC;AAsC3C,eAAO,MAAM,iBAAiB,GAC5B,OAAO,cAAc,KACpB,MAgEF,CAAC"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,207 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./build-BAZMN_vU.cjs"),S=n=>async t=>{const i=a.generateRequestId();return new Promise(v=>{const d=u=>{u.data.type==="invalidateVizCacheResponse"&&u.data.requestId===i&&(n.removeEventListener("message",d),v())};n.addEventListener("message",d),n.postMessage({type:"invalidateVizCacheRequest",changedVizIds:t,requestId:i})})},b=({worker:n,setBuildErrorMessage:t})=>({files:i,enableSourcemap:v,vizId:d})=>{const u=a.generateRequestId();return new Promise(s=>{const c=f=>{const p=f.data;if(p.type==="buildResponse"&&p.requestId===u){n.removeEventListener("message",c);const R=p.buildResult,m=p.error;m?t==null||t(m):t==null||t(null),s(R)}};n.addEventListener("message",c);const E={type:"buildRequest",files:i,enableSourcemap:v,requestId:u,vizId:d};n.postMessage(E)})},y="IDLE",I="ENQUEUED",L="PENDING_CLEAN",N="PENDING_DIRTY",V=({iframe:n,worker:t,setBuildErrorMessage:i,getLatestContent:v,resolveSlugKey:d,writeFile:u})=>{let s=y,c=null;const E=b({worker:t,setBuildErrorMessage:i}),f=({data:o})=>{if(o.type==="contentRequest"&&v){const{vizId:e}=o;v(e).then(l=>{t.postMessage({type:"contentResponse",vizId:e,content:l})})}else if(o.type==="resolveSlugRequest"){const{slugKey:e,requestId:l}=o;if(d)d(e).then(r=>{const h={type:"resolveSlugResponse",vizId:r,requestId:l};t.postMessage(h)});else{const r={type:"resolveSlugResponse",vizId:null,requestId:l};t.postMessage(r)}}};t.addEventListener("message",f);const p=o=>{const e=o.data;(e.type==="runDone"||e.type==="runError")&&e.type==="runError"&&i&&i(e.error.message),e.type==="writeFile"&&u&&e.fileName&&e.content&&u(e.fileName,e.content)};window.addEventListener("message",p);const R=()=>{t.removeEventListener("message",f),window.removeEventListener("message",p)},m=async({files:o,enableHotReloading:e=!1,enableSourcemap:l=!1,vizId:r})=>{s=L;const h=await E({files:o,enableSourcemap:l,vizId:r});if(h){const{html:D,js:w,css:C}=h;if(console.clear(),e){if(C){const g={type:"runCSS",css:C};if(!n.contentWindow)throw new Error("iframe.contentWindow is null - this should never happen");n.contentWindow.postMessage(g,window.location.origin)}if(w){const g={type:"runJS",js:w};if(!n.contentWindow)throw new Error("iframe.contentWindow is null - this should never happen");n.contentWindow.postMessage(g,window.location.origin)}}else n.srcdoc=D||""}s===N?(requestAnimationFrame(()=>{if(!c)throw new Error("latestFiles is not defined and state is PENDING_DIRTY - this should never happen");m({files:c,enableHotReloading:e,enableSourcemap:l,vizId:r})}),s=I):s=y},q=({files:o,enableHotReloading:e=!1,enableSourcemap:l=!1,vizId:r=void 0})=>{if(c=null,s===y)s=I,m({files:o,enableHotReloading:e,enableSourcemap:l,vizId:r});else if(s===L)c=o,s=N;else if(s===N)c=o;else if(s===I)c=o;else throw new Error(`Unexpected state: ${s}`)};return{invalidateVizCache:S(t),run:q,cleanup:R}},z=({rawMessage:n,vizId:t})=>{const i=new RegExp(t,"g");return n==null?void 0:n.replace(i,".")};exports.build=a.build;exports.computeBundleJSV3=a.computeBundleJSV3;exports.createSlugCache=a.createSlugCache;exports.createVizCache=a.createVizCache;exports.createVizContent=a.createVizContent;exports.svelteCompilerUrl=a.svelteCompilerUrl;exports.v3Build=a.v3Build;exports.cleanRollupErrorMessage=z;exports.createRuntime=V;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("./slugCache-mB6V-shn.cjs"),I=require("@vizhub/viz-utils"),O=e=>async t=>{const s=u.generateRequestId();return new Promise(i=>{const r=o=>{o.data.type==="invalidateVizCacheResponse"&&o.data.requestId===s&&(e.removeEventListener("message",r),i())};e.addEventListener("message",r),e.postMessage({type:"invalidateVizCacheRequest",changedVizIds:t,requestId:s})})},z=({worker:e,setBuildErrorMessage:t})=>({files:s,enableSourcemap:i,vizId:r})=>{const o=u.generateRequestId();return new Promise(c=>{const a=v=>{const f=v.data;if(f.type==="buildResponse"&&f.requestId===o){e.removeEventListener("message",a);const w=f.buildResult,h=f.error;h?t==null||t(h):t==null||t(null),c(w)}};e.addEventListener("message",a);const d={type:"buildRequest",files:s,enableSourcemap:i,requestId:o,vizId:r};e.postMessage(d)})},C="IDLE",x="ENQUEUED",j="PENDING_CLEAN",R="PENDING_DIRTY",F=({iframe:e,worker:t,setBuildErrorMessage:s,getLatestContent:i,resolveSlugKey:r,writeFile:o})=>{let c=C,a=null;const d=z({worker:t,setBuildErrorMessage:s}),v=({data:l})=>{if(l.type==="contentRequest"&&i){const{vizId:n}=l;i(n).then(p=>{t.postMessage({type:"contentResponse",vizId:n,content:p})})}else if(l.type==="resolveSlugRequest"){const{slugKey:n,requestId:p}=l;if(r)r(n).then(m=>{const g={type:"resolveSlugResponse",vizId:m,requestId:p};t.postMessage(g)});else{const m={type:"resolveSlugResponse",vizId:null,requestId:p};t.postMessage(m)}}};t.addEventListener("message",v);const f=l=>{const n=l.data;(n.type==="runDone"||n.type==="runError")&&n.type==="runError"&&s&&s(n.error.message),n.type==="writeFile"&&o&&n.fileName&&n.content&&o(n.fileName,n.content)};window.addEventListener("message",f);const w=()=>{t.removeEventListener("message",v),window.removeEventListener("message",f)},h=async({files:l,enableHotReloading:n=!1,enableSourcemap:p=!1,vizId:m})=>{c=j;const g=await d({files:l,enableSourcemap:p,vizId:m});if(g){const{html:E,js:N,css:b}=g;if(console.clear(),n){if(b){const S={type:"runCSS",css:b};if(!e.contentWindow)throw new Error("iframe.contentWindow is null - this should never happen");e.contentWindow.postMessage(S,window.location.origin)}if(N){const S={type:"runJS",js:N};if(!e.contentWindow)throw new Error("iframe.contentWindow is null - this should never happen");e.contentWindow.postMessage(S,window.location.origin)}}else e.srcdoc=E||""}c===R?(requestAnimationFrame(()=>{if(!a)throw new Error("latestFiles is not defined and state is PENDING_DIRTY - this should never happen");h({files:a,enableHotReloading:n,enableSourcemap:p,vizId:m})}),c=x):c=C},y=({files:l,enableHotReloading:n=!1,enableSourcemap:p=!1,vizId:m=void 0})=>{if(a=null,c===C)c=x,h({files:l,enableHotReloading:n,enableSourcemap:p,vizId:m});else if(c===j)a=l,c=R;else if(c===R)a=l;else if(c===x)a=l;else throw new Error(`Unexpected state: ${c}`)};return{invalidateVizCache:O(t),run:y,cleanup:w}},V=`var EOL = {},
2
+ EOF = {},
3
+ QUOTE = 34,
4
+ NEWLINE = 10,
5
+ RETURN = 13;
6
+
7
+ function objectConverter(columns) {
8
+ return new Function(
9
+ 'd',
10
+ 'return {' +
11
+ columns
12
+ .map(function (name, i) {
13
+ return (
14
+ JSON.stringify(name) + ': d[' + i + '] || ""'
15
+ );
16
+ })
17
+ .join(',') +
18
+ '}',
19
+ );
20
+ }
21
+
22
+ function customConverter(columns, f) {
23
+ var object = objectConverter(columns);
24
+ return function (row, i) {
25
+ return f(object(row), i, columns);
26
+ };
27
+ }
28
+
29
+ function dsv(delimiter) {
30
+ var DELIMITER = delimiter.charCodeAt(0);
31
+
32
+ function parse(text, f) {
33
+ var convert,
34
+ columns,
35
+ rows = parseRows(text, function (row, i) {
36
+ if (convert) return convert(row, i - 1);
37
+ (columns = row),
38
+ (convert = f
39
+ ? customConverter(row, f)
40
+ : objectConverter(row));
41
+ });
42
+ rows.columns = columns || [];
43
+ return rows;
44
+ }
45
+
46
+ function parseRows(text, f) {
47
+ var rows = [], // output rows
48
+ N = text.length,
49
+ I = 0, // current character index
50
+ n = 0, // current line number
51
+ t, // current token
52
+ eof = N <= 0, // current token followed by EOF?
53
+ eol = false; // current token followed by EOL?
54
+
55
+ // Strip the trailing newline.
56
+ if (text.charCodeAt(N - 1) === NEWLINE) --N;
57
+ if (text.charCodeAt(N - 1) === RETURN) --N;
58
+
59
+ function token() {
60
+ if (eof) return EOF;
61
+ if (eol) return (eol = false), EOL;
62
+
63
+ // Unescape quotes.
64
+ var i,
65
+ j = I,
66
+ c;
67
+ if (text.charCodeAt(j) === QUOTE) {
68
+ while (
69
+ (I++ < N && text.charCodeAt(I) !== QUOTE) ||
70
+ text.charCodeAt(++I) === QUOTE
71
+ );
72
+ if ((i = I) >= N) eof = true;
73
+ else if ((c = text.charCodeAt(I++)) === NEWLINE)
74
+ eol = true;
75
+ else if (c === RETURN) {
76
+ eol = true;
77
+ if (text.charCodeAt(I) === NEWLINE) ++I;
78
+ }
79
+ return text.slice(j + 1, i - 1).replace(/""/g, '"');
80
+ }
81
+
82
+ // Find next delimiter or newline.
83
+ while (I < N) {
84
+ if ((c = text.charCodeAt((i = I++))) === NEWLINE)
85
+ eol = true;
86
+ else if (c === RETURN) {
87
+ eol = true;
88
+ if (text.charCodeAt(I) === NEWLINE) ++I;
89
+ } else if (c !== DELIMITER) continue;
90
+ return text.slice(j, i);
91
+ }
92
+
93
+ // Return last token before EOF.
94
+ return (eof = true), text.slice(j, N);
95
+ }
96
+
97
+ while ((t = token()) !== EOF) {
98
+ var row = [];
99
+ while (t !== EOL && t !== EOF)
100
+ row.push(t), (t = token());
101
+ if (f && (row = f(row, n++)) == null) continue;
102
+ rows.push(row);
103
+ }
104
+
105
+ return rows;
106
+ }
107
+
108
+ return {
109
+ parse: parse,
110
+ };
111
+ }
112
+
113
+ var csv = dsv(',');
114
+
115
+ var csvParse = csv.parse;
116
+
117
+ var tsv = dsv(' ');
118
+
119
+ var tsvParse = tsv.parse;
120
+
121
+ export { csvParse, tsvParse };`,T=e=>e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),D=()=>({name:"transformDSV",transform:async(e,t)=>{const{fileName:s}=u.parseId(t),i=s.endsWith(".csv"),r=s.endsWith(".tsv");if(i||r)return{code:`
122
+ ${V}
123
+ const data = ${i?"csvParse":"tsvParse"}(\`${T(e)}\`);
124
+ export default data;
125
+ `,map:{mappings:""}}}}),W=e=>{const t=/^@([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_-]+)$/,s=e.match(t);return s?{userName:s[1],idOrSlug:s[2]}:null},$=({vizId:e,slugCache:t})=>({name:"vizResolve",resolveId:async(s,i)=>{if(s.startsWith("./")&&!(i!=null&&i.startsWith("https://"))){let o=s.substring(2);if(!o.endsWith(".js")&&!o.endsWith(".css")&&!o.endsWith(".csv")&&!o.endsWith(".svelte")&&(o+=".js"),i){const{vizId:c,fileName:a}=u.parseId(i),d=a.split("/").slice(0,-1).join("/"),v=d?`${d}/${o}`:o;return`${c}/${v}`}return e+"/"+o}const r=W(s);if(r){let o;if(I.isVizId(r.idOrSlug))o=r.idOrSlug;else{if(!t)throw new Error("slugCache is required to import by slug in v3 runtime");o=await t.get(`${r.userName}/${r.idOrSlug}`)}return o+"/index.js"}}}),P=({vizCache:e,trackCSSImport:t,vizId:s,files:i})=>({name:"vizLoad",load:async r=>{const o=u.parseId(r),c=o.vizId,a=o.fileName;if(a.endsWith(".css"))return t(r),"";let d=null;if(c===s&&i)d=i[a]||null;else{const v=await e.get(c);d=I.getFileText(v,a)}if(d===null)throw new Error(`Imported file "${a}" not found.`);return d}}),L=async({files:e,rollup:t,enableSourcemap:s=!0,vizCache:i,vizId:r,slugCache:o,getSvelteCompiler:c})=>{const a=new Set,d=n=>{a.add(n)};if(!e["index.js"])throw new Error("Missing index.js");const f={input:"./index.js",plugins:[...r?[$({vizId:r,slugCache:o})]:[],D(),u.sucrasePlugin(),u.transformSvelte({getSvelteCompiler:c}),...i?[P({vizCache:i,trackCSSImport:d,vizId:r,files:e})]:[]],onwarn(n,p){n.code!=="UNRESOLVED_IMPORT"&&p(n)}},w={format:"umd",name:"Viz",sourcemap:!!s,compact:!0},h=u.packageJSON(e);if(h){const n=u.getGlobals(h);n&&(f.external=Object.keys(n),w.globals=n)}const y=await t(f),{output:l}=await y.generate(w);return{src:l[0].code,cssFiles:Array.from(a)}};function U(){return Math.random().toString().slice(2,7)}const A=({cdn:e,src:t,styles:s})=>{const r=`viz-container-${U()}`;return`<!DOCTYPE html>
126
+ <html>
127
+ <head>
128
+ <meta charset="utf-8">${e}${s}
129
+ <style>
130
+ body {
131
+ margin: 0;
132
+ overflow: hidden;
133
+ }
134
+ #${r} {
135
+ height: 100vh;
136
+ }
137
+ </style>
138
+ </head>
139
+ <body>
140
+ <div id="${r}"></div>
141
+ <script id="injected-script">${t}<\/script>
142
+ <script>
143
+ (() => {
144
+ let cleanup;
145
+ const render = () => {
146
+ const container = document.getElementById('${r}');
147
+ typeof cleanup === 'function' && cleanup();
148
+ cleanup = Viz.main(container, { state: window.state, setState, writeFile });
149
+ };
150
+ const setState = (next) => {
151
+ window.state = next(window.state);
152
+ render();
153
+ };
154
+ const writeFile = (fileName, content) => {
155
+ parent.postMessage({ type: 'writeFile', fileName, content }, "*");
156
+ };
157
+ const run = () => {
158
+ try {
159
+ setState((state) => state || {});
160
+ } catch (error) {
161
+ console.error(error);
162
+ parent.postMessage({ type: 'runError', error }, "*");
163
+ }
164
+ }
165
+ run();
166
+ const runJS = (src) => {
167
+ document.getElementById('injected-script')?.remove();
168
+ const script = document.createElement('script');
169
+ script.textContent = src;
170
+ script.id = 'injected-script';
171
+ document.body.appendChild(script);
172
+ run();
173
+ };
174
+ const runCSS = (css) => {
175
+ let style = document.getElementById('injected-style');
176
+ if (!style) {
177
+ style = document.createElement('style');
178
+ style.type = 'text/css';
179
+ style.id = 'injected-style';
180
+ document.head.appendChild(style);
181
+ }
182
+ style.textContent = css;
183
+ };
184
+ onmessage = (message) => {
185
+ switch (message.data.type) {
186
+ case 'runJS':
187
+ runJS(message.data.js);
188
+ parent.postMessage({ type: 'runDone' }, "*");
189
+ break;
190
+ case 'runCSS':
191
+ runCSS(message.data.css);
192
+ break;
193
+ case 'ping':
194
+ parent.postMessage({ type: 'pong' }, "*");
195
+ break;
196
+ default:
197
+ break;
198
+ }
199
+ }
200
+ })();
201
+ <\/script>
202
+ </body>
203
+ </html>`},q=async({files:e,rollup:t,enableSourcemap:s=!0,vizCache:i,vizId:r,slugCache:o,getSvelteCompiler:c})=>{const{src:a,cssFiles:d}=await L({files:e,rollup:t,enableSourcemap:s,vizCache:i,vizId:r,slugCache:o,getSvelteCompiler:c});let v=[];if(d.length>0)for(let l=0;l<d.length;l++){const n=d[l],p=u.parseId(n),m=p.vizId,g=p.fileName;let E=null;if(m===r&&e)E=e[g]||null;else{const N=await i.get(m);E=I.getFileText(N,g)}E&&v.push(E)}const f=v.join(`
204
+ `),w=`
205
+ <style id="injected-style">${f}</style>`;let h="";const y=Object.entries(u.dependencies(e));if(y.length>0){const l=u.getConfiguredLibraries(e);h=y.map(([n,p],m)=>{const g=u.dependencySource({name:n,version:p},l);return`${m>0?" ":`
206
+ `}<script src="${g}"><\/script>`}).join("")}return{html:A({cdn:h,src:a,styles:w}),css:f,js:a}},J=({rawMessage:e,vizId:t})=>{const s=new RegExp(t,"g");return e==null?void 0:e.replace(s,".")},k=(e,t="Sample Content for Exporting",s=I.generateVizId())=>({id:s,files:I.fileCollectionToVizFiles(e),title:t});exports.build=u.build;exports.createSlugCache=u.createSlugCache;exports.createVizCache=u.createVizCache;exports.determineRuntimeVersion=u.determineRuntimeVersion;exports.svelteCompilerUrl=u.svelteCompilerUrl;exports.cleanRollupErrorMessage=J;exports.computeBundleJSV3=L;exports.createRuntime=F;exports.createVizContent=k;exports.v3Build=q;
2
207
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/orchestration/setupInvalidateVizCache.ts","../src/orchestration/setupBuild.ts","../src/orchestration/createRuntime.ts","../src/v3/cleanRollupErrorMessage.ts"],"sourcesContent":["import { VizId } from \"@vizhub/viz-types\";\nimport { generateRequestId } from \"./generateRequestId\";\n\nexport const setupInvalidateVizCache =\n (worker: Worker) =>\n async (changedVizIds: Array<VizId>): Promise<void> => {\n const requestId = generateRequestId();\n return new Promise<void>((resolve) => {\n const invalidateListener = (e: MessageEvent) => {\n if (\n e.data.type === \"invalidateVizCacheResponse\" &&\n e.data.requestId === requestId\n ) {\n worker.removeEventListener(\n \"message\",\n invalidateListener,\n );\n resolve();\n }\n };\n worker.addEventListener(\n \"message\",\n invalidateListener,\n );\n\n worker.postMessage({\n type: \"invalidateVizCacheRequest\",\n changedVizIds,\n requestId,\n });\n });\n };\n","import { FileCollection, VizId } from \"@vizhub/viz-types\";\nimport { generateRequestId } from \"./generateRequestId\";\nimport { BuildWorkerMessage } from \"./types\";\nimport { BuildResult } from \"../build/types\";\n\nexport const setupBuild =\n ({\n worker,\n setBuildErrorMessage,\n }: {\n worker: Worker;\n setBuildErrorMessage?: (error: string | null) => void;\n }) =>\n ({\n files,\n enableSourcemap,\n vizId,\n }: {\n files: FileCollection;\n enableSourcemap: boolean;\n vizId?: VizId;\n }): Promise<BuildResult | undefined> => {\n const requestId = generateRequestId();\n return new Promise<BuildResult | undefined>(\n (resolve) => {\n const buildListener = (e: MessageEvent) => {\n const data: BuildWorkerMessage = e.data;\n if (\n data.type === \"buildResponse\" &&\n data.requestId === requestId\n ) {\n worker.removeEventListener(\n \"message\",\n buildListener,\n );\n\n const buildResult: BuildResult | undefined =\n data.buildResult;\n const error: string | undefined = data.error;\n\n if (error) {\n setBuildErrorMessage?.(error);\n } else {\n setBuildErrorMessage?.(null);\n }\n\n resolve(buildResult);\n }\n };\n\n worker.addEventListener(\"message\", buildListener);\n\n const message: BuildWorkerMessage = {\n type: \"buildRequest\",\n files,\n enableSourcemap,\n requestId,\n vizId,\n };\n worker.postMessage(message);\n },\n );\n };\n","import {\n FileCollection,\n VizContent,\n VizId,\n} from \"@vizhub/viz-types\";\n\nimport { setupInvalidateVizCache } from \"./setupInvalidateVizCache\";\nimport { setupBuild } from \"./setupBuild\";\nimport {\n BuildWorkerMessage,\n VizHubRuntime,\n WindowMessage,\n} from \"./types\";\n\n// Flag for debugging.\nconst DEBUG = false;\n\n// State constants:\n\n// Nothing happening.\nconst IDLE = \"IDLE\";\n\n// An update has been enqueued\n// via requestAnimationFrame.\nconst ENQUEUED = \"ENQUEUED\";\n\n// An update (build and run) is pending,\n// and the files have not changed.\nconst PENDING_CLEAN = \"PENDING_CLEAN\";\n\n// An update (build and run) is pending,\n// and the files have changed\n// while this run is taking place.\nconst PENDING_DIRTY = \"PENDING_DIRTY\";\n\n// Valid State Transitions:\n//\n// * IDLE --> ENQUEUED\n// When the system is idle and files are changed.\n//\n// * ENQUEUED --> PENDING_CLEAN\n// When the pending changes run.\n//\n// * PENDING_CLEAN --> IDLE\n// When the pending update finishes running\n// and files were not changed in the mean time.\n//\n// * PENDING_CLEAN --> PENDING_DIRTY\n// When files are changed while an update is pending.\n//\n// * PENDING_DIRTY --> ENQUEUED\n// When the pending update finishes running\n// and files were changed in the mean time.\n//\n// When a build error happens, the state is set to IDLE.\n// This is to prevent a build error from causing\n// the whole system to stop working.\n\n// Creates an instance of the VizHub Runtime Environment.\n// This is the main entry point for the runtime, for use\n// by front end applications.\n// It sets up the iframe and worker, and handles messages\n// between them.\n// For server-side rendering where only a build is required,\n// just use the build function directly.\nexport const createRuntime = ({\n iframe,\n worker,\n setBuildErrorMessage,\n getLatestContent,\n resolveSlugKey,\n writeFile,\n}: {\n iframe: HTMLIFrameElement;\n worker: Worker;\n setBuildErrorMessage?: (error: string | null) => void;\n getLatestContent?: (\n vizId: VizId,\n ) => Promise<VizContent | null>;\n resolveSlugKey?: (\n slugKey: string,\n ) => Promise<VizId | null>;\n writeFile?: (fileName: string, content: string) => void;\n}): VizHubRuntime => {\n // Track the current state of the runtime\n let state:\n | typeof IDLE\n | typeof ENQUEUED\n | typeof PENDING_CLEAN\n | typeof PENDING_DIRTY = IDLE;\n\n // When a run is requested while the state is PENDING_CLEAN\n // or PENDING_DIRTY, we need to wait for the pending build to finish,\n // so until the build finishes, we use `latestFiles` to stash the latest files.\n let latestFiles: FileCollection | null = null;\n\n const build = setupBuild({\n worker,\n setBuildErrorMessage,\n });\n\n // Pending promise resolvers\n let pendingRunPromise: (() => void) | null = null;\n\n // This runs when the build worker sends a message.\n const workerListener: (e: MessageEvent) => void = ({\n data,\n }: {\n data: BuildWorkerMessage;\n }) => {\n if (\n data.type === \"contentRequest\" &&\n getLatestContent\n ) {\n const { vizId } = data;\n\n getLatestContent(vizId).then((content) => {\n worker.postMessage({\n type: \"contentResponse\",\n vizId,\n content,\n });\n });\n } else if (data.type === \"resolveSlugRequest\") {\n DEBUG &&\n console.log(\n \"[worker] resolveSlugRequest\",\n JSON.stringify(data, null, 2),\n );\n const { slugKey, requestId } = data;\n\n if (resolveSlugKey) {\n DEBUG &&\n console.log(\n \"[worker] resolveSlugRequest: resolving slug key\",\n slugKey,\n );\n resolveSlugKey(slugKey).then(\n (vizId: VizId | null) => {\n DEBUG &&\n console.log(\n \"[worker] resolveSlugRequest: resolved slug key\",\n slugKey,\n \"to vizId\",\n vizId,\n );\n const message: BuildWorkerMessage = {\n type: \"resolveSlugResponse\",\n vizId,\n requestId,\n };\n worker.postMessage(message);\n },\n );\n } else {\n DEBUG &&\n console.log(\n \"[worker] resolveSlugRequest: no slug resolver, returning null\",\n JSON.stringify(data, null, 2),\n );\n // If we don't have a slug resolver, we just\n // send back the slug key as the vizId.\n const message: BuildWorkerMessage = {\n type: \"resolveSlugResponse\",\n vizId: null,\n requestId,\n };\n worker.postMessage(message);\n }\n }\n };\n\n worker.addEventListener(\"message\", workerListener);\n\n // Handle messages from the iframe\n const windowListener = (event: MessageEvent) => {\n const data = event.data;\n\n if (\n data.type === \"runDone\" ||\n data.type === \"runError\"\n ) {\n if (pendingRunPromise) {\n pendingRunPromise();\n pendingRunPromise = null;\n }\n\n if (data.type === \"runError\") {\n setBuildErrorMessage &&\n setBuildErrorMessage(data.error.message);\n }\n }\n\n if (data.type === \"writeFile\" && writeFile) {\n if (data.fileName && data.content) {\n writeFile(data.fileName, data.content);\n }\n }\n };\n\n // This runs when the IFrame sends a message.\n window.addEventListener(\"message\", windowListener);\n\n const cleanup = () => {\n worker.removeEventListener(\"message\", workerListener);\n window.removeEventListener(\"message\", windowListener);\n };\n\n const update = async ({\n files,\n enableHotReloading = false,\n enableSourcemap = false,\n vizId,\n }: {\n files: FileCollection;\n enableHotReloading?: boolean;\n enableSourcemap?: boolean;\n vizId?: VizId;\n }) => {\n state = PENDING_CLEAN;\n\n DEBUG && console.log(\"[runtime] update: before build\");\n\n // Build the code\n const buildResult = await build({\n files,\n enableSourcemap,\n vizId,\n });\n\n // In this case, the build failed\n // and in the meantime the callback `setBuildErrorMessage`\n // was called.\n if (!buildResult) {\n DEBUG &&\n console.log(\"[runtime] update: build failed\");\n }\n\n DEBUG && console.log(\"[runtime] update: after build\");\n\n if (buildResult) {\n const { html, js, css } = buildResult;\n\n DEBUG &&\n console.log(\n \"[runtime] enableHotReloading\",\n enableHotReloading,\n );\n\n DEBUG &&\n console.log(\n \"[runtime] html: \",\n html?.substring(0, 200),\n );\n\n DEBUG &&\n console.log(\n \"[runtime] js: \",\n js?.substring(0, 200),\n );\n\n DEBUG &&\n console.log(\n \"[runtime] css: \",\n css?.substring(0, 200),\n );\n\n // Clear the console before each run.\n !DEBUG && console.clear();\n\n // If `enableHotReloading` is true, we also need to\n // check that `js` is defined, since the desired behavior\n // is that only if we are using the v3 runtime, then\n // the hot reloading actually happens, and _only_ the v3 build\n // outputs `js`, so the guard for `js` is really just\n // checking that we are on v3.\n if (enableHotReloading) {\n if (css) {\n const runCSSMessage: WindowMessage = {\n type: \"runCSS\",\n css,\n };\n if (!iframe.contentWindow) {\n throw new Error(\n \"iframe.contentWindow is null - this should never happen\",\n );\n }\n iframe.contentWindow.postMessage(\n runCSSMessage,\n window.location.origin,\n );\n }\n if (js) {\n const runJSMessage: WindowMessage = {\n type: \"runJS\",\n js,\n };\n if (!iframe.contentWindow) {\n throw new Error(\n \"iframe.contentWindow is null - this should never happen\",\n );\n }\n iframe.contentWindow.postMessage(\n runJSMessage,\n window.location.origin,\n );\n }\n } else {\n iframe.srcdoc = html || \"\";\n }\n }\n\n // TypeScript can't comprehend that `state`\n // may change during the await calls above.\n // @ts-ignore\n if (state === PENDING_DIRTY) {\n requestAnimationFrame(() => {\n if (!latestFiles) {\n throw new Error(\n \"latestFiles is not defined and state is PENDING_DIRTY - this should never happen\",\n );\n }\n update({\n files: latestFiles,\n enableHotReloading,\n enableSourcemap,\n vizId,\n });\n });\n state = ENQUEUED;\n } else {\n state = IDLE;\n }\n };\n\n // Handle code changes\n\n const run = ({\n files,\n enableHotReloading = false,\n enableSourcemap = false,\n vizId = undefined,\n }: {\n files: FileCollection;\n enableHotReloading?: boolean;\n enableSourcemap?: boolean;\n vizId?: VizId;\n }) => {\n DEBUG && console.log(\"[runtime] run\");\n latestFiles = null;\n if (state === IDLE) {\n DEBUG && console.log(\"[runtime] run: IDLE\");\n state = ENQUEUED;\n update({\n files,\n enableHotReloading,\n enableSourcemap,\n vizId,\n });\n } else if (state === PENDING_CLEAN) {\n DEBUG && console.log(\"[runtime] run: PENDING_CLEAN\");\n latestFiles = files;\n state = PENDING_DIRTY;\n } else if (state === PENDING_DIRTY) {\n DEBUG && console.log(\"[runtime] run: PENDING_DIRTY\");\n latestFiles = files;\n } else if (state === ENQUEUED) {\n DEBUG && console.log(\"[runtime] run: ENQUEUED\");\n latestFiles = files;\n } else {\n throw new Error(`Unexpected state: ${state}`);\n }\n };\n\n return {\n invalidateVizCache: setupInvalidateVizCache(worker),\n run,\n cleanup,\n };\n};\n","// We want to remove the vizId from the error message\n// to make it more user-friendly.\n// Example error message before and after:\n// Before: \"7f0b69fcb754479699172d1887817027/index.js (14:8): Expected ';', '}' or <eof>\"\n// After: \"./index.js (14:8): Expected ';', '}' or <eof>\"\nexport const cleanRollupErrorMessage = ({\n rawMessage,\n vizId,\n}: {\n rawMessage: string;\n vizId: string;\n}) => {\n const regex = new RegExp(vizId, \"g\");\n return rawMessage?.replace(regex, \".\");\n};\n"],"names":["setupInvalidateVizCache","worker","changedVizIds","requestId","generateRequestId","resolve","invalidateListener","e","setupBuild","setBuildErrorMessage","files","enableSourcemap","vizId","buildListener","data","buildResult","error","message","IDLE","ENQUEUED","PENDING_CLEAN","PENDING_DIRTY","createRuntime","iframe","getLatestContent","resolveSlugKey","writeFile","state","latestFiles","build","workerListener","content","slugKey","windowListener","event","cleanup","update","enableHotReloading","html","js","css","runCSSMessage","runJSMessage","run","cleanRollupErrorMessage","rawMessage","regex"],"mappings":"wHAGaA,EACVC,GACD,MAAOC,GAA+C,CACpD,MAAMC,EAAYC,EAAAA,kBAAkB,EAC7B,OAAA,IAAI,QAAeC,GAAY,CAC9B,MAAAC,EAAsBC,GAAoB,CAE5CA,EAAE,KAAK,OAAS,8BAChBA,EAAE,KAAK,YAAcJ,IAEdF,EAAA,oBACL,UACAK,CACF,EACQD,EAAA,EAEZ,EACOJ,EAAA,iBACL,UACAK,CACF,EAEAL,EAAO,YAAY,CACjB,KAAM,4BACN,cAAAC,EACA,UAAAC,CAAA,CACD,CAAA,CACF,CACH,EC1BWK,EACX,CAAC,CACC,OAAAP,EACA,qBAAAQ,CACF,IAIA,CAAC,CACC,MAAAC,EACA,gBAAAC,EACA,MAAAC,CACF,IAIwC,CACtC,MAAMT,EAAYC,EAAAA,kBAAkB,EACpC,OAAO,IAAI,QACRC,GAAY,CACL,MAAAQ,EAAiBN,GAAoB,CACzC,MAAMO,EAA2BP,EAAE,KACnC,GACEO,EAAK,OAAS,iBACdA,EAAK,YAAcX,EACnB,CACOF,EAAA,oBACL,UACAY,CACF,EAEA,MAAME,EACJD,EAAK,YACDE,EAA4BF,EAAK,MAEnCE,EACFP,GAAA,MAAAA,EAAuBO,GAEvBP,GAAA,MAAAA,EAAu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AM,CAAC,CACX,MAAAjC,EACA,mBAAA2B,EAAqB,GACrB,gBAAA1B,EAAkB,GAClB,MAAAC,EAAQ,MAAA,IAMJ,CAGJ,GADcgB,EAAA,KACVD,IAAUT,EAEJS,EAAAR,EACDiB,EAAA,CACL,MAAA1B,EACA,mBAAA2B,EACA,gBAAA1B,EACA,MAAAC,CAAA,CACD,UACQe,IAAUP,EAELQ,EAAAlB,EACNiB,EAAAN,UACCM,IAAUN,EAELO,EAAAlB,UACLiB,IAAUR,EAELS,EAAAlB,MAEd,OAAM,IAAI,MAAM,qBAAqBiB,CAAK,EAAE,CAEhD,EAEO,MAAA,CACL,mBAAoB3B,EAAwBC,CAAM,EAClD,IAAA0C,EACA,QAAAR,CACF,CACF,ECtXaS,EAA0B,CAAC,CACtC,WAAAC,EACA,MAAAjC,CACF,IAGM,CACJ,MAAMkC,EAAQ,IAAI,OAAOlC,EAAO,GAAG,EAC5B,OAAAiC,GAAA,YAAAA,EAAY,QAAQC,EAAO,IACpC"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/orchestration/setupInvalidateVizCache.ts","../src/orchestration/setupBuild.ts","../src/orchestration/createRuntime.ts","../src/v3/transformDSV/dsvParseSrc.ts","../src/v3/transformDSV/index.ts","../src/v3/extractVizImport.ts","../src/v3/vizResolve.ts","../src/v3/vizLoad.ts","../src/v3/computeBundleJSV3.ts","../src/v3/htmlTemplate.ts","../src/v3/v3Build.ts","../src/v3/cleanRollupErrorMessage.ts","../src/v3/createVizContent.ts"],"sourcesContent":["import { VizId } from \"@vizhub/viz-types\";\nimport { generateRequestId } from \"./generateRequestId\";\n\nexport const setupInvalidateVizCache =\n (worker: Worker) =>\n async (changedVizIds: Array<VizId>): Promise<void> => {\n const requestId = generateRequestId();\n return new Promise<void>((resolve) => {\n const invalidateListener = (e: MessageEvent) => {\n if (\n e.data.type === \"invalidateVizCacheResponse\" &&\n e.data.requestId === requestId\n ) {\n worker.removeEventListener(\n \"message\",\n invalidateListener,\n );\n resolve();\n }\n };\n worker.addEventListener(\n \"message\",\n invalidateListener,\n );\n\n worker.postMessage({\n type: \"invalidateVizCacheRequest\",\n changedVizIds,\n requestId,\n });\n });\n };\n","import { FileCollection, VizId } from \"@vizhub/viz-types\";\nimport { generateRequestId } from \"./generateRequestId\";\nimport { BuildWorkerMessage } from \"./types\";\nimport { BuildResult } from \"../build/types\";\n\nexport const setupBuild =\n ({\n worker,\n setBuildErrorMessage,\n }: {\n worker: Worker;\n setBuildErrorMessage?: (error: string | null) => void;\n }) =>\n ({\n files,\n enableSourcemap,\n vizId,\n }: {\n files: FileCollection;\n enableSourcemap: boolean;\n vizId?: VizId;\n }): Promise<BuildResult | undefined> => {\n const requestId = generateRequestId();\n return new Promise<BuildResult | undefined>(\n (resolve) => {\n const buildListener = (e: MessageEvent) => {\n const data: BuildWorkerMessage = e.data;\n if (\n data.type === \"buildResponse\" &&\n data.requestId === requestId\n ) {\n worker.removeEventListener(\n \"message\",\n buildListener,\n );\n\n const buildResult: BuildResult | undefined =\n data.buildResult;\n const error: string | undefined = data.error;\n\n if (error) {\n setBuildErrorMessage?.(error);\n } else {\n setBuildErrorMessage?.(null);\n }\n\n resolve(buildResult);\n }\n };\n\n worker.addEventListener(\"message\", buildListener);\n\n const message: BuildWorkerMessage = {\n type: \"buildRequest\",\n files,\n enableSourcemap,\n requestId,\n vizId,\n };\n worker.postMessage(message);\n },\n );\n };\n","import {\n FileCollection,\n VizContent,\n VizId,\n} from \"@vizhub/viz-types\";\n\nimport { setupInvalidateVizCache } from \"./setupInvalidateVizCache\";\nimport { setupBuild } from \"./setupBuild\";\nimport {\n BuildWorkerMessage,\n VizHubRuntime,\n WindowMessage,\n} from \"./types\";\n\n// Flag for debugging.\nconst DEBUG = false;\n\n// State constants:\n\n// Nothing happening.\nconst IDLE = \"IDLE\";\n\n// An update has been enqueued\n// via requestAnimationFrame.\nconst ENQUEUED = \"ENQUEUED\";\n\n// An update (build and run) is pending,\n// and the files have not changed.\nconst PENDING_CLEAN = \"PENDING_CLEAN\";\n\n// An update (build and run) is pending,\n// and the files have changed\n// while this run is taking place.\nconst PENDING_DIRTY = \"PENDING_DIRTY\";\n\n// Valid State Transitions:\n//\n// * IDLE --> ENQUEUED\n// When the system is idle and files are changed.\n//\n// * ENQUEUED --> PENDING_CLEAN\n// When the pending changes run.\n//\n// * PENDING_CLEAN --> IDLE\n// When the pending update finishes running\n// and files were not changed in the mean time.\n//\n// * PENDING_CLEAN --> PENDING_DIRTY\n// When files are changed while an update is pending.\n//\n// * PENDING_DIRTY --> ENQUEUED\n// When the pending update finishes running\n// and files were changed in the mean time.\n//\n// When a build error happens, the state is set to IDLE.\n// This is to prevent a build error from causing\n// the whole system to stop working.\n\n// Creates an instance of the VizHub Runtime Environment.\n// This is the main entry point for the runtime, for use\n// by front end applications.\n// It sets up the iframe and worker, and handles messages\n// between them.\n// For server-side rendering where only a build is required,\n// just use the build function directly.\nexport const createRuntime = ({\n iframe,\n worker,\n setBuildErrorMessage,\n getLatestContent,\n resolveSlugKey,\n writeFile,\n}: {\n iframe: HTMLIFrameElement;\n worker: Worker;\n setBuildErrorMessage?: (error: string | null) => void;\n getLatestContent?: (\n vizId: VizId,\n ) => Promise<VizContent | null>;\n resolveSlugKey?: (\n slugKey: string,\n ) => Promise<VizId | null>;\n writeFile?: (fileName: string, content: string) => void;\n}): VizHubRuntime => {\n // Track the current state of the runtime\n let state:\n | typeof IDLE\n | typeof ENQUEUED\n | typeof PENDING_CLEAN\n | typeof PENDING_DIRTY = IDLE;\n\n // When a run is requested while the state is PENDING_CLEAN\n // or PENDING_DIRTY, we need to wait for the pending build to finish,\n // so until the build finishes, we use `latestFiles` to stash the latest files.\n let latestFiles: FileCollection | null = null;\n\n const build = setupBuild({\n worker,\n setBuildErrorMessage,\n });\n\n // Pending promise resolvers\n let pendingRunPromise: (() => void) | null = null;\n\n // This runs when the build worker sends a message.\n const workerListener: (e: MessageEvent) => void = ({\n data,\n }: {\n data: BuildWorkerMessage;\n }) => {\n if (\n data.type === \"contentRequest\" &&\n getLatestContent\n ) {\n DEBUG &&\n console.log(\n \"[worker] contentRequest\",\n JSON.stringify(data, null, 2),\n );\n const { vizId } = data;\n\n getLatestContent(vizId).then((content) => {\n worker.postMessage({\n type: \"contentResponse\",\n vizId,\n content,\n });\n });\n } else if (data.type === \"resolveSlugRequest\") {\n DEBUG &&\n console.log(\n \"[worker] resolveSlugRequest\",\n JSON.stringify(data, null, 2),\n );\n const { slugKey, requestId } = data;\n\n if (resolveSlugKey) {\n DEBUG &&\n console.log(\n \"[worker] resolveSlugRequest: resolving slug key\",\n slugKey,\n );\n resolveSlugKey(slugKey).then(\n (vizId: VizId | null) => {\n DEBUG &&\n console.log(\n \"[worker] resolveSlugRequest: resolved slug key\",\n slugKey,\n \"to vizId\",\n vizId,\n );\n const message: BuildWorkerMessage = {\n type: \"resolveSlugResponse\",\n vizId,\n requestId,\n };\n worker.postMessage(message);\n },\n );\n } else {\n DEBUG &&\n console.log(\n \"[worker] resolveSlugRequest: no slug resolver, returning null\",\n JSON.stringify(data, null, 2),\n );\n // If we don't have a slug resolver, we just\n // send back the slug key as the vizId.\n const message: BuildWorkerMessage = {\n type: \"resolveSlugResponse\",\n vizId: null,\n requestId,\n };\n worker.postMessage(message);\n }\n }\n };\n\n worker.addEventListener(\"message\", workerListener);\n\n // Handle messages from the iframe\n const windowListener = (event: MessageEvent) => {\n const data = event.data;\n\n if (\n data.type === \"runDone\" ||\n data.type === \"runError\"\n ) {\n if (pendingRunPromise) {\n pendingRunPromise();\n pendingRunPromise = null;\n }\n\n if (data.type === \"runError\") {\n setBuildErrorMessage &&\n setBuildErrorMessage(data.error.message);\n }\n }\n\n if (data.type === \"writeFile\" && writeFile) {\n if (data.fileName && data.content) {\n writeFile(data.fileName, data.content);\n }\n }\n };\n\n // This runs when the IFrame sends a message.\n window.addEventListener(\"message\", windowListener);\n\n const cleanup = () => {\n worker.removeEventListener(\"message\", workerListener);\n window.removeEventListener(\"message\", windowListener);\n };\n\n const update = async ({\n files,\n enableHotReloading = false,\n enableSourcemap = false,\n vizId,\n }: {\n files: FileCollection;\n enableHotReloading?: boolean;\n enableSourcemap?: boolean;\n vizId?: VizId;\n }) => {\n state = PENDING_CLEAN;\n\n DEBUG && console.log(\"[runtime] update: before build\");\n\n // Build the code\n const buildResult = await build({\n files,\n enableSourcemap,\n vizId,\n });\n\n // In this case, the build failed\n // and in the meantime the callback `setBuildErrorMessage`\n // was called.\n if (!buildResult) {\n DEBUG &&\n console.log(\"[runtime] update: build failed\");\n }\n\n DEBUG && console.log(\"[runtime] update: after build\");\n\n if (buildResult) {\n const { html, js, css } = buildResult;\n\n DEBUG &&\n console.log(\n \"[runtime] enableHotReloading\",\n enableHotReloading,\n );\n\n DEBUG &&\n console.log(\n \"[runtime] html: \",\n html?.substring(0, 200),\n );\n\n DEBUG &&\n console.log(\n \"[runtime] js: \",\n js?.substring(0, 200),\n );\n\n DEBUG &&\n console.log(\n \"[runtime] css: \",\n css?.substring(0, 200),\n );\n\n // Clear the console before each run.\n !DEBUG && console.clear();\n\n // If `enableHotReloading` is true, we also need to\n // check that `js` is defined, since the desired behavior\n // is that only if we are using the v3 runtime, then\n // the hot reloading actually happens, and _only_ the v3 build\n // outputs `js`, so the guard for `js` is really just\n // checking that we are on v3.\n if (enableHotReloading) {\n if (css) {\n const runCSSMessage: WindowMessage = {\n type: \"runCSS\",\n css,\n };\n if (!iframe.contentWindow) {\n throw new Error(\n \"iframe.contentWindow is null - this should never happen\",\n );\n }\n iframe.contentWindow.postMessage(\n runCSSMessage,\n window.location.origin,\n );\n }\n if (js) {\n const runJSMessage: WindowMessage = {\n type: \"runJS\",\n js,\n };\n if (!iframe.contentWindow) {\n throw new Error(\n \"iframe.contentWindow is null - this should never happen\",\n );\n }\n iframe.contentWindow.postMessage(\n runJSMessage,\n window.location.origin,\n );\n }\n } else {\n iframe.srcdoc = html || \"\";\n }\n }\n\n // TypeScript can't comprehend that `state`\n // may change during the await calls above.\n // @ts-ignore\n if (state === PENDING_DIRTY) {\n requestAnimationFrame(() => {\n if (!latestFiles) {\n throw new Error(\n \"latestFiles is not defined and state is PENDING_DIRTY - this should never happen\",\n );\n }\n update({\n files: latestFiles,\n enableHotReloading,\n enableSourcemap,\n vizId,\n });\n });\n state = ENQUEUED;\n } else {\n state = IDLE;\n }\n };\n\n // Handle code changes\n\n const run = ({\n files,\n enableHotReloading = false,\n enableSourcemap = false,\n vizId = undefined,\n }: {\n files: FileCollection;\n enableHotReloading?: boolean;\n enableSourcemap?: boolean;\n vizId?: VizId;\n }) => {\n DEBUG && console.log(\"[runtime] run\");\n latestFiles = null;\n if (state === IDLE) {\n DEBUG && console.log(\"[runtime] run: IDLE\");\n state = ENQUEUED;\n update({\n files,\n enableHotReloading,\n enableSourcemap,\n vizId,\n });\n } else if (state === PENDING_CLEAN) {\n DEBUG && console.log(\"[runtime] run: PENDING_CLEAN\");\n latestFiles = files;\n state = PENDING_DIRTY;\n } else if (state === PENDING_DIRTY) {\n DEBUG && console.log(\"[runtime] run: PENDING_DIRTY\");\n latestFiles = files;\n } else if (state === ENQUEUED) {\n DEBUG && console.log(\"[runtime] run: ENQUEUED\");\n latestFiles = files;\n } else {\n throw new Error(`Unexpected state: ${state}`);\n }\n };\n\n return {\n invalidateVizCache: setupInvalidateVizCache(worker),\n run,\n cleanup,\n };\n};\n","export const dsvParseSrc = `var EOL = {},\n EOF = {},\n QUOTE = 34,\n NEWLINE = 10,\n RETURN = 13;\n\nfunction objectConverter(columns) {\n return new Function(\n 'd',\n 'return {' +\n columns\n .map(function (name, i) {\n return (\n JSON.stringify(name) + ': d[' + i + '] || \"\"'\n );\n })\n .join(',') +\n '}',\n );\n}\n\nfunction customConverter(columns, f) {\n var object = objectConverter(columns);\n return function (row, i) {\n return f(object(row), i, columns);\n };\n}\n\nfunction dsv(delimiter) {\n var DELIMITER = delimiter.charCodeAt(0);\n\n function parse(text, f) {\n var convert,\n columns,\n rows = parseRows(text, function (row, i) {\n if (convert) return convert(row, i - 1);\n (columns = row),\n (convert = f\n ? customConverter(row, f)\n : objectConverter(row));\n });\n rows.columns = columns || [];\n return rows;\n }\n\n function parseRows(text, f) {\n var rows = [], // output rows\n N = text.length,\n I = 0, // current character index\n n = 0, // current line number\n t, // current token\n eof = N <= 0, // current token followed by EOF?\n eol = false; // current token followed by EOL?\n\n // Strip the trailing newline.\n if (text.charCodeAt(N - 1) === NEWLINE) --N;\n if (text.charCodeAt(N - 1) === RETURN) --N;\n\n function token() {\n if (eof) return EOF;\n if (eol) return (eol = false), EOL;\n\n // Unescape quotes.\n var i,\n j = I,\n c;\n if (text.charCodeAt(j) === QUOTE) {\n while (\n (I++ < N && text.charCodeAt(I) !== QUOTE) ||\n text.charCodeAt(++I) === QUOTE\n );\n if ((i = I) >= N) eof = true;\n else if ((c = text.charCodeAt(I++)) === NEWLINE)\n eol = true;\n else if (c === RETURN) {\n eol = true;\n if (text.charCodeAt(I) === NEWLINE) ++I;\n }\n return text.slice(j + 1, i - 1).replace(/\"\"/g, '\"');\n }\n\n // Find next delimiter or newline.\n while (I < N) {\n if ((c = text.charCodeAt((i = I++))) === NEWLINE)\n eol = true;\n else if (c === RETURN) {\n eol = true;\n if (text.charCodeAt(I) === NEWLINE) ++I;\n } else if (c !== DELIMITER) continue;\n return text.slice(j, i);\n }\n\n // Return last token before EOF.\n return (eof = true), text.slice(j, N);\n }\n\n while ((t = token()) !== EOF) {\n var row = [];\n while (t !== EOL && t !== EOF)\n row.push(t), (t = token());\n if (f && (row = f(row, n++)) == null) continue;\n rows.push(row);\n }\n\n return rows;\n }\n\n return {\n parse: parse,\n };\n}\n\nvar csv = dsv(',');\n\nvar csvParse = csv.parse;\n\nvar tsv = dsv('\\t');\n\nvar tsvParse = tsv.parse;\n\nexport { csvParse, tsvParse };`;\n","import { InputPluginOption } from \"rollup\";\nimport type { ResolvedVizFileId } from \"../types\";\nimport { parseId } from \"../parseId\";\nimport { dsvParseSrc } from \"./dsvParseSrc.js\";\n\nconst DEBUG = false;\n\n// Escape backticks in a string so that it can be\n// used in a template literal. Also need to escape backslashes.\nconst escapeBackticks = (str: string) =>\n // str.replace(/`/g, '\\\\`');\n str.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\");\n\n// Responsible for loading CSV and TSV files, which are\n// in general called Delimiter-Separated Values (DSV).\nexport const transformDSV = (): InputPluginOption => ({\n name: \"transformDSV\",\n\n // `id` here is of the form\n // `{vizId}/{fileName}`\n transform: async (\n text: string,\n id: ResolvedVizFileId,\n ) => {\n DEBUG && console.log(\"[transformDSV]: load() \" + id);\n const { vizId, fileName } = parseId(id);\n\n DEBUG &&\n console.log(\" [transformDSV] vizId: \" + vizId);\n DEBUG &&\n console.log(\" [transformDSV] fileName: \" + fileName);\n const isCSV = fileName.endsWith(\".csv\");\n const isTSV = fileName.endsWith(\".tsv\");\n if (isCSV || isTSV) {\n DEBUG &&\n console.log(\n \" [transformDSV] tracking DSV import for \" +\n id,\n );\n\n const parseFunction = isCSV ? \"csvParse\" : \"tsvParse\";\n\n return {\n code: `\n ${dsvParseSrc}\n const data = ${parseFunction}(\\`${escapeBackticks(text)}\\`);\n export default data;\n `,\n map: { mappings: \"\" },\n };\n }\n return undefined;\n },\n});\n","import { VizId } from \"@vizhub/viz-types\";\n\nexport type VizImport = {\n userName: string;\n idOrSlug: VizId | string;\n};\n\nexport const extractVizImport = (\n str: string,\n): VizImport | null => {\n // Updated regular expression pattern\n // Username: Alphanumeric characters, including underscores and hyphens\n // ID: Alphanumeric characters, including underscores, hyphens, and possibly other special characters\n const pattern = /^@([a-zA-Z0-9_-]+)\\/([a-zA-Z0-9_-]+)$/;\n const match = str.match(pattern);\n\n if (match) {\n // Extract the username and id\n return {\n userName: match[1],\n idOrSlug: match[2],\n };\n } else {\n // Return null if the string does not match\n return null;\n }\n};\n\n// // Example usages\n// const result1 = extractDetails(\"@curran/21f72bf74ef04ea0b9c9b82aaaec859a\");\n// console.log(result1); // { username: \"curran\", id: \"21f72bf74ef04ea0b9c9b82aaaec859a\" }\n\n// const result2 = extractDetails(\"@curran/scatter-plot\");\n// console.log(result2); // { username: \"curran\", id: \"scatter-plot\" }\n","// A custom Rollup plugin to:\n// * Implement a virtual file system\n// * Support importing across vizzes\n// Unified Rollup plugin for virtual file system and viz imports\n// Combines functionalities of 'virtual' and 'importFromViz' plugins\nimport { InputPluginOption } from \"rollup\";\nimport { VizId } from \"@vizhub/viz-types\";\nimport { isVizId } from \"@vizhub/viz-utils\";\nimport { extractVizImport } from \"./extractVizImport.js\";\nimport type { ResolvedVizFileId } from \"./types.js\";\nimport { parseId } from \"./parseId\";\nimport { SlugCache } from \"./slugCache.js\";\n\nconst debug = false;\n\nexport const vizResolve = ({\n vizId,\n slugCache,\n}: {\n vizId: VizId;\n slugCache?: SlugCache;\n}): InputPluginOption => ({\n name: \"vizResolve\",\n resolveId: async (\n id: string,\n importer: string | undefined,\n ): Promise<ResolvedVizFileId | undefined> => {\n if (debug) {\n console.log(\"[vizIdResolve] resolveId() \" + id);\n console.log(\" importer: \" + importer);\n }\n\n // Handle virtual file system resolution\n // .e.g. `import { foo } from './foo.js'`\n // .e.g. `import { foo } from './foo'`\n if (\n id.startsWith(\"./\") &&\n !importer?.startsWith(\"https://\")\n ) {\n let fileName = id.substring(2);\n\n // Handle CSS files\n // e.g. `import './styles.css'`\n // Handle JS files\n // e.g. `import { foo } from './foo.js'`\n // e.g. `import { foo } from './foo'`\n if (\n !fileName.endsWith(\".js\") &&\n !fileName.endsWith(\".css\") &&\n !fileName.endsWith(\".csv\") &&\n !fileName.endsWith(\".svelte\")\n ) {\n fileName += \".js\";\n }\n\n // const js = (name: string) =>\n // name.endsWith('.js') ? name : name + '.js';\n\n // If there is an importer, then the file is not part of\n // the entry point, so it should be resolved relative\n // to the importer's directory\n if (importer) {\n const {\n vizId: importerVizId,\n fileName: importerFileName,\n } = parseId(importer);\n // Get the directory of the importing file\n const importerDir = importerFileName\n .split(\"/\")\n .slice(0, -1)\n .join(\"/\");\n // Combine the directory with the imported file name\n const resolvedFileName = importerDir\n ? `${importerDir}/${fileName}`\n : fileName;\n return `${importerVizId}/${resolvedFileName}`;\n }\n return vizId + \"/\" + fileName;\n }\n\n // Handle viz import resolution\n // e.g. `import { foo } from '@curran/98e6d6509a1e407897d4f238a330efec'`\n // e.g. `import { foo } from '@curran/scatter-plot'`\n const vizImport = extractVizImport(id);\n if (vizImport) {\n let vizId: VizId;\n if (isVizId(vizImport.idOrSlug)) {\n vizId = vizImport.idOrSlug;\n } else {\n if (!slugCache) {\n throw new Error(\n \"slugCache is required to import by slug in v3 runtime\",\n );\n }\n\n vizId = await slugCache.get(\n `${vizImport.userName}/${vizImport.idOrSlug}`,\n );\n }\n return vizId + \"/index.js\";\n }\n\n // If neither condition is met, return undefined.\n return undefined;\n },\n});\n","import { InputPluginOption } from \"rollup\";\nimport {\n FileCollection,\n VizContent,\n VizId,\n} from \"@vizhub/viz-types\";\nimport { getFileText } from \"@vizhub/viz-utils\";\nimport type { ResolvedVizFileId } from \"./types\";\nimport { parseId } from \"./parseId\";\nimport { VizCache } from \"./vizCache.js\";\n\nconst debug = false;\n\n// Responsible for loading all imports and\n// tracking which CSS files are imported.\n// Throws an error if a file is imported but not found.\nexport const vizLoad = ({\n vizCache,\n trackCSSImport,\n vizId,\n files,\n}: {\n vizCache: VizCache;\n trackCSSImport: (cssFile: ResolvedVizFileId) => void;\n vizId?: VizId;\n files?: FileCollection;\n}): InputPluginOption => ({\n name: \"vizLoad\",\n\n // `id` here is of the form\n // `{vizId}/{fileName}`\n load: async (id: ResolvedVizFileId) => {\n if (debug) {\n console.log(\"[vizLoadCSS]: load() \" + id);\n }\n\n const parsedId = parseId(id);\n const parsedVizId = parsedId.vizId;\n const parsedFileName = parsedId.fileName;\n\n if (debug) {\n console.log(\" [vizLoadCSS] vizId: \" + parsedVizId);\n console.log(\n \" [vizLoadCSS] fileName: \" + parsedFileName,\n );\n }\n\n // For CSS imports, all we need to do here is\n // keep track of them so they can be injected\n // into the IFrame later.\n if (parsedFileName.endsWith(\".css\")) {\n if (debug) {\n console.log(\n \" [vizResolve] tracking CSS import for \" + id,\n );\n }\n // The import is tracked here so that it can be\n // injected into the IFrame later, external to the\n // Rollup build.\n trackCSSImport(id);\n // TODO consider using Rollup's `emitFile` to emit a CSS file.\n return \"\";\n }\n\n // If we are resolving to the root vizId, we can\n // use the files object directly.\n // Otherwise, we need to get the content from the vizCache.\n // This makes it so the vizCache is _only_ used for\n // resolving cross-viz imports.\n let fileText: string | null = null;\n if (parsedVizId === vizId && files) {\n fileText = files[parsedFileName] || null;\n } else {\n const content = await vizCache.get(parsedVizId);\n fileText = getFileText(content, parsedFileName);\n }\n\n // If a file is imported but not found, throw an error.\n if (fileText === null) {\n throw new Error(\n `Imported file \"${parsedFileName}\" not found.`,\n );\n // TODO ideally show username/slug instead of vizId\n // `Imported file \"${fileName}\" not found in viz ${vizId}`,\n // `Imported file \"${fileName}\" not found.`,\n // );\n }\n\n return fileText;\n },\n});\n","import { sucrasePlugin } from \"../common/sucrasePlugin\";\nimport type {\n RollupBuild,\n RollupOptions,\n OutputOptions,\n} from \"rollup\";\nimport { FileCollection, VizId } from \"@vizhub/viz-types\";\nimport {\n getGlobals,\n packageJSON,\n} from \"../common/packageJson.js\";\nimport { transformDSV } from \"./transformDSV/index.js\";\nimport { vizResolve } from \"./vizResolve.js\";\nimport { VizCache } from \"./vizCache.js\";\nimport { vizLoad } from \"./vizLoad.js\";\nimport { SlugCache } from \"./slugCache.js\";\nimport {\n SvelteCompiler,\n transformSvelte,\n} from \"./transformSvelte.js\";\n\nexport const computeBundleJSV3 = async ({\n files,\n rollup,\n enableSourcemap = true,\n vizCache,\n vizId,\n slugCache,\n getSvelteCompiler,\n}: {\n files: FileCollection;\n rollup: (options: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n vizCache?: VizCache;\n vizId?: VizId;\n slugCache?: SlugCache;\n getSvelteCompiler?: () => Promise<SvelteCompiler>;\n}): Promise<{ src: string; cssFiles: string[] }> => {\n // Track CSS imports\n const cssFilesSet = new Set<string>();\n const trackCSSImport = (cssFile: string) => {\n cssFilesSet.add(cssFile);\n };\n const indexJSContent = files[\"index.js\"];\n if (!indexJSContent) {\n throw new Error(\"Missing index.js\");\n }\n\n const inputOptions: RollupOptions = {\n input: \"./index.js\",\n plugins: [\n ...(vizId ? [vizResolve({ vizId, slugCache })] : []),\n transformDSV(),\n sucrasePlugin(),\n transformSvelte({ getSvelteCompiler }),\n ...(vizCache\n ? [\n vizLoad({\n vizCache,\n trackCSSImport,\n vizId,\n files,\n }),\n ]\n : []),\n ],\n onwarn(warning, warn) {\n // Suppress \"treating module as external dependency\" warnings\n if (warning.code === \"UNRESOLVED_IMPORT\") return;\n warn(warning);\n },\n };\n\n const outputOptions: OutputOptions = {\n format: \"umd\",\n name: \"Viz\",\n sourcemap: enableSourcemap ? true : false,\n compact: true,\n };\n\n const pkg = packageJSON(files);\n if (pkg) {\n const globals = getGlobals(pkg);\n if (globals) {\n inputOptions.external = Object.keys(globals);\n outputOptions.globals = globals;\n }\n }\n\n const bundle = await rollup(inputOptions);\n\n const { output } = await bundle.generate(outputOptions);\n return {\n src: output[0].code,\n cssFiles: Array.from(cssFilesSet),\n };\n};\n","function randomDigits() {\n return Math.random().toString().slice(2, 7);\n}\n\nexport const htmlTemplate = ({\n cdn,\n src,\n styles,\n}: {\n cdn: string;\n src: string;\n styles: string;\n}) => {\n // Random container id to avoid conflicts and guarantee\n // the code is portable.\n const containerSuffix = randomDigits();\n\n const vizContainerId = `viz-container-${containerSuffix}`;\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">${cdn}${styles}\n <style>\n body {\n margin: 0;\n overflow: hidden;\n }\n #${vizContainerId} {\n height: 100vh;\n }\n </style>\n</head>\n<body>\n <div id=\"${vizContainerId}\"></div>\n <script id=\"injected-script\">${src}</script>\n <script>\n (() => {\n let cleanup;\n const render = () => {\n const container = document.getElementById('${vizContainerId}');\n typeof cleanup === 'function' && cleanup();\n cleanup = Viz.main(container, { state: window.state, setState, writeFile });\n };\n const setState = (next) => {\n window.state = next(window.state);\n render();\n };\n const writeFile = (fileName, content) => {\n parent.postMessage({ type: 'writeFile', fileName, content }, \"*\");\n };\n const run = () => {\n try {\n setState((state) => state || {});\n } catch (error) {\n console.error(error);\n parent.postMessage({ type: 'runError', error }, \"*\");\n }\n }\n run();\n const runJS = (src) => {\n document.getElementById('injected-script')?.remove();\n const script = document.createElement('script');\n script.textContent = src;\n script.id = 'injected-script';\n document.body.appendChild(script);\n run();\n };\n const runCSS = (css) => {\n let style = document.getElementById('injected-style');\n if (!style) {\n style = document.createElement('style');\n style.type = 'text/css';\n style.id = 'injected-style';\n document.head.appendChild(style);\n }\n style.textContent = css;\n };\n onmessage = (message) => {\n switch (message.data.type) {\n case 'runJS':\n runJS(message.data.js);\n parent.postMessage({ type: 'runDone' }, \"*\");\n break;\n case 'runCSS':\n runCSS(message.data.css);\n break;\n case 'ping':\n parent.postMessage({ type: 'pong' }, \"*\");\n break;\n default:\n break;\n }\n }\n })();\n </script>\n</body>\n</html>`;\n};\n","import { RollupBuild, RollupOptions } from \"rollup\";\nimport { getFileText } from \"@vizhub/viz-utils\";\nimport { computeBundleJSV3 } from \"./computeBundleJSV3\";\nimport { htmlTemplate } from \"./htmlTemplate\";\nimport { VizCache } from \"./vizCache.js\";\nimport {\n FileCollection,\n VizContent,\n VizId,\n} from \"@vizhub/viz-types\";\nimport { parseId } from \"./parseId.js\";\nimport { ResolvedVizFileId } from \"./types.js\";\nimport { SlugCache } from \"./slugCache.js\";\nimport { SvelteCompiler } from \"./transformSvelte.js\";\nimport {\n dependencies,\n getConfiguredLibraries,\n dependencySource,\n} from \"../common/packageJson\";\nimport { BuildResult } from \"../build/types\";\n\nexport const v3Build = async ({\n files,\n rollup,\n enableSourcemap = true,\n vizCache,\n vizId,\n slugCache,\n getSvelteCompiler,\n}: {\n files: FileCollection;\n rollup: (options: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n vizCache: VizCache;\n vizId: VizId;\n slugCache?: SlugCache;\n getSvelteCompiler?: () => Promise<SvelteCompiler>;\n}): Promise<BuildResult> => {\n const { src, cssFiles } = await computeBundleJSV3({\n files,\n rollup,\n enableSourcemap,\n vizCache,\n vizId,\n slugCache,\n getSvelteCompiler,\n });\n\n // Generate CSS styles from imported CSS files\n let cssFileTextArray: string[] = [];\n\n // Inject CSS files.\n if (cssFiles.length > 0) {\n for (let i = 0; i < cssFiles.length; i++) {\n const id: ResolvedVizFileId = cssFiles[i];\n\n const parsedId = parseId(id);\n const parsedVizId = parsedId.vizId;\n const parsedFileName = parsedId.fileName;\n\n // If we are resolving to the root vizId, we can\n // use the files object directly.\n // Otherwise, we need to get the content from the vizCache.\n // This makes it so the vizCache is _only_ used for\n // resolving cross-viz imports.\n let fileText: string | null = null;\n if (parsedVizId === vizId && files) {\n fileText = files[parsedFileName] || null;\n } else {\n const content = await vizCache.get(parsedVizId);\n fileText = getFileText(content, parsedFileName);\n }\n if (fileText) {\n cssFileTextArray.push(fileText);\n }\n }\n }\n\n // The concatenated CSS text.\n const css = cssFileTextArray.join(\"\\n\");\n\n const styles = `\\n <style id=\"injected-style\">${css}</style>`;\n // Generate CDN script tags for dependencies\n let cdn = \"\";\n const deps: [string, string][] = Object.entries(\n dependencies(files),\n );\n if (deps.length > 0) {\n const libraries = getConfiguredLibraries(files);\n cdn = deps\n .map(([name, version], i) => {\n const dependencySrc = dependencySource(\n { name, version },\n libraries,\n );\n const indent = i > 0 ? \" \" : \"\\n \";\n return `${indent}<script src=\"${dependencySrc}\"></script>`;\n })\n .join(\"\");\n }\n\n return {\n html: htmlTemplate({ cdn, src, styles }),\n css,\n js: src,\n };\n};\n","// We want to remove the vizId from the error message\n// to make it more user-friendly.\n// Example error message before and after:\n// Before: \"7f0b69fcb754479699172d1887817027/index.js (14:8): Expected ';', '}' or <eof>\"\n// After: \"./index.js (14:8): Expected ';', '}' or <eof>\"\nexport const cleanRollupErrorMessage = ({\n rawMessage,\n vizId,\n}: {\n rawMessage: string;\n vizId: string;\n}) => {\n const regex = new RegExp(vizId, \"g\");\n return rawMessage?.replace(regex, \".\");\n};\n","import {\n FileCollection,\n VizContent,\n} from \"@vizhub/viz-types\";\nimport {\n fileCollectionToVizFiles,\n generateVizId,\n} from \"@vizhub/viz-utils\";\n\n/**\n * Creates a VizContent object with the given files\n * @param files An object with file names as keys and file content as values\n * @param title Optional title for the content\n * @returns A VizContent object with randomly generated IDs\n */\nexport const createVizContent = (\n files: FileCollection,\n title = \"Sample Content for Exporting\",\n id = generateVizId(),\n): VizContent => {\n return {\n id,\n files: fileCollectionToVizFiles(files),\n title,\n };\n};\n"],"names":["setupInvalidateVizCache","worker","changedVizIds","requestId","generateRequestId","resolve","invalidateListener","e","setupBuild","setBuildErrorMessage","files","enableSourcemap","vizId","buildListener","data","buildResult","error","message","IDLE","ENQUEUED","PENDING_CLEAN","PENDING_DIRTY","createRuntime","iframe","getLatestContent","resolveSlugKey","writeFile","state","latestFiles","build","workerListener","content","slugKey","windowListener","event","cleanup","update","enableHotReloading","html","js","css","runCSSMessage","runJSMessage","run","dsvParseSrc","escapeBackticks","str","transformDSV","text","id","fileName","parseId","isCSV","isTSV","extractVizImport","pattern","match","vizResolve","slugCache","importer","importerVizId","importerFileName","importerDir","resolvedFileName","vizImport","isVizId","vizLoad","vizCache","trackCSSImport","parsedId","parsedVizId","parsedFileName","fileText","getFileText","computeBundleJSV3","rollup","getSvelteCompiler","cssFilesSet","cssFile","inputOptions","sucrasePlugin","transformSvelte","warning","warn","outputOptions","pkg","packageJSON","globals","getGlobals","bundle","output","randomDigits","htmlTemplate","cdn","src","styles","vizContainerId","v3Build","cssFiles","cssFileTextArray","i","deps","dependencies","libraries","getConfiguredLibraries","name","version","dependencySrc","dependencySource","cleanRollupErrorMessage","rawMessage","regex","createVizContent","title","generateVizId","fileCollectionToVizFiles"],"mappings":"2JAGaA,EACVC,GACD,MAAOC,GAA+C,CACpD,MAAMC,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,GAAA,YAAAA,EAAY,QAAQC,EAAO,IACpC,ECCaC,EAAmB,CAC9BtG,EACAuG,EAAQ,+BACRhE,EAAKiE,EAAAA,mBAEE,CACL,GAAAjE,EACA,MAAOkE,2BAAyBzG,CAAK,EACrC,MAAAuG,CACF"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createRuntime } from "./orchestration/createRuntime";
2
- export { build } from "./build";
2
+ export { build, determineRuntimeVersion } from "./build";
3
3
  export type { BuildResult, runtimeVersion } from "./build";
4
4
  export type { VizHubRuntime } from "./orchestration/types";
5
5
  export { v3Build, computeBundleJSV3, createVizCache, createSlugCache, svelteCompilerUrl, cleanRollupErrorMessage, createVizContent, } from "./v3";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9D,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,YAAY,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAC3D,YAAY,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EACL,OAAO,EACP,iBAAiB,EACjB,cAAc,EACd,eAAe,EACf,iBAAiB,EACjB,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,MAAM,CAAC;AAEd,YAAY,EACV,QAAQ,EACR,SAAS,EACT,cAAc,GACf,MAAM,MAAM,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9D,OAAO,EAAE,KAAK,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAC;AACzD,YAAY,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAC3D,YAAY,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EACL,OAAO,EACP,iBAAiB,EACjB,cAAc,EACd,eAAe,EACf,iBAAiB,EACjB,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,MAAM,CAAC;AAEd,YAAY,EACV,QAAQ,EACR,SAAS,EACT,cAAc,GACf,MAAM,MAAM,CAAC"}