@vizhub/runtime 0.5.0 → 0.6.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/dist/build-DU4cyBtp.js +855 -0
- package/dist/build-DU4cyBtp.js.map +1 -0
- package/dist/build-DkIslKFi.cjs +214 -0
- package/dist/build-DkIslKFi.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +34 -33
- package/dist/worker.cjs +1 -8
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.js +51 -346
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/createVizContent-BOSPq-Jv.cjs +0 -207
- package/dist/createVizContent-BOSPq-Jv.cjs.map +0 -1
- package/dist/createVizContent-DjJF2PT_.js +0 -565
- package/dist/createVizContent-DjJF2PT_.js.map +0 -1
package/dist/index.cjs
CHANGED
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./build-DkIslKFi.cjs"),q=t=>async n=>{const o=c.generateRequestId();return new Promise(d=>{const u=r=>{r.data.type==="invalidateVizCacheResponse"&&r.data.requestId===o&&(t.removeEventListener("message",u),d())};t.addEventListener("message",u),t.postMessage({type:"invalidateVizCacheRequest",changedVizIds:n,requestId:o})})},S=({worker:t,setBuildErrorMessage:n})=>({files:o,enableSourcemap:d})=>{const u=c.generateRequestId();return new Promise(r=>{const s=h=>{const p=h.data;if(p.type==="buildResponse"){t.removeEventListener("message",s);const v=p.buildResult,f=p.error;f?n==null||n(f):n==null||n(null),r(v)}};t.addEventListener("message",s);const l={type:"buildRequest",files:o,enableSourcemap:d,requestId:u};t.postMessage(l)})},R="IDLE",y="ENQUEUED",C="PENDING_CLEAN",I="PENDING_DIRTY",b=({iframe:t,worker:n,setBuildErrorMessage:o,getLatestContent:d,resolveSlugKey:u,writeFile:r})=>{let s=R,l=null;const h=S({worker:n,setBuildErrorMessage:o}),p=({data:i})=>{if(i.type==="contentRequest"&&d){const{vizId:e}=i;d(e).then(a=>{n.postMessage({type:"contentResponse",vizId:e,content:a})})}else if(i.type==="resolveSlugRequest"&&u){const{slugKey:e,requestId:a}=i;u(e).then(m=>{n.postMessage({type:"resolveSlugResponse",slugKey:e,vizId:m,requestId:a})})}};n.addEventListener("message",p);const v=i=>{const e=i.data;(e.type==="runDone"||e.type==="runError")&&e.type==="runError"&&o&&o(e.error.message),e.type==="writeFile"&&r&&e.fileName&&e.content&&r(e.fileName,e.content)};window.addEventListener("message",v);const f=()=>{n.removeEventListener("message",p),window.removeEventListener("message",v)},g=async({files:i,enableHotReloading:e=!1,enableSourcemap:a=!1})=>{s=C;const m=await h({files:i,enableSourcemap:a});if(!m)return;const{html:D,js:w,css:N}=m;if(console.clear(),e){if(N){const E={type:"runCSS",css:N};if(!t.contentWindow)throw new Error("iframe.contentWindow is null - this should never happen");t.contentWindow.postMessage(E,window.location.origin)}if(w){const E={type:"runJS",js:w};if(!t.contentWindow)throw new Error("iframe.contentWindow is null - this should never happen");t.contentWindow.postMessage(E,window.location.origin)}}else t.srcdoc=D||"";s===I?(requestAnimationFrame(()=>{if(!l)throw new Error("latestFiles is not defined and state is PENDING_DIRTY - this should never happen");g({files:l,enableHotReloading:e,enableSourcemap:a})}),s=y):s=R},L=({files:i,enableHotReloading:e=!1,enableSourcemap:a=!1})=>{if(l=null,s===R)s=y,g({files:i,enableHotReloading:e,enableSourcemap:a});else if(s===C)l=i,s=I;else if(s===I)l=i;else if(s===y)l=i;else throw new Error(`Unexpected state: ${s}`)};return{invalidateVizCache:q(n),run:L,cleanup:f}},V=({rawMessage:t,vizId:n})=>{const o=new RegExp(n,"g");return t==null?void 0:t.replace(o,".")};exports.build=c.build;exports.computeBundleJSV3=c.computeBundleJSV3;exports.createSlugCache=c.createSlugCache;exports.createVizCache=c.createVizCache;exports.createVizContent=c.createVizContent;exports.svelteCompilerUrl=c.svelteCompilerUrl;exports.v3Build=c.v3Build;exports.cleanRollupErrorMessage=V;exports.createRuntime=b;
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
@@ -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 } 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 }: {\n files: FileCollection;\n enableSourcemap: boolean;\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 (data.type === \"buildResponse\") {\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 };\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?: (vizId: VizId) => Promise<VizContent>;\n resolveSlugKey?: (slugKey: string) => Promise<VizId>;\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 (\n data.type === \"resolveSlugRequest\" &&\n resolveSlugKey\n ) {\n const { slugKey, requestId } = data;\n\n resolveSlugKey(slugKey).then((vizId) => {\n worker.postMessage({\n type: \"resolveSlugResponse\",\n slugKey,\n vizId,\n requestId,\n });\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 }: {\n files: FileCollection;\n enableHotReloading?: boolean;\n enableSourcemap?: boolean;\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 });\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 return;\n }\n\n DEBUG && console.log(\"[runtime] update: after build\");\n\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(\"[runtime] js: \", js?.substring(0, 200));\n\n DEBUG &&\n console.log(\n \"[runtime] css: \",\n css?.substring(0, 200),\n );\n\n // Clear the console before each run.\n 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 // 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 });\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 }: {\n files: FileCollection;\n enableHotReloading?: boolean;\n enableSourcemap?: boolean;\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 });\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","buildListener","data","buildResult","error","message","IDLE","ENQUEUED","PENDING_CLEAN","PENDING_DIRTY","createRuntime","iframe","getLatestContent","resolveSlugKey","writeFile","state","latestFiles","build","workerListener","vizId","content","slugKey","windowListener","event","cleanup","update","enableHotReloading","html","js","css","runCSSMessage","runJSMessage","run","cleanRollupErrorMessage","rawMessage","regex"],"mappings":"mIAGaA,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,CACF,IAGwC,CACtC,MAAMR,EAAYC,EAAAA,kBAAkB,EACpC,OAAO,IAAI,QACRC,GAAY,CACL,MAAAO,EAAiBL,GAAoB,CACzC,MAAMM,EAA2BN,EAAE,KAC/B,GAAAM,EAAK,OAAS,gBAAiB,CAC1BZ,EAAA,oBACL,UACAW,CACF,EAEA,MAAME,EACJD,EAAK,YACDE,EAA4BF,EAAK,MAEnCE,EACFN,GAAA,MAAAA,EAAuBM,GAEvBN,GAAA,MAAAA,EAAuB,MAGzBJ,EAAQS,CAAW,CAAA,CAEvB,EAEOb,EAAA,iBAAiB,UAAWW,CAAa,EAEhD,MAAMI,EAA8B,CAClC,KAAM,eACN,MAAAN,EACA,gBAAAC,EACA,UAAAR,CACF,EACAF,EAAO,YAAYe,CAAO,CAAA,CAE9B,CACF,ECpCIC,EAAO,OAIPC,EAAW,WAIXC,EAAgB,gBAKhBC,EAAgB,gBAgCTC,EAAgB,CAAC,CAC5B,OAAAC,EACA,OAAArB,EACA,qBAAAQ,EACA,i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AQ,IAAI,OAAOhB,EAAO,GAAG,EAC5B,OAAAe,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/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 } 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 }: {\n files: FileCollection;\n enableSourcemap: boolean;\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 (data.type === \"buildResponse\") {\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 };\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?: (vizId: VizId) => Promise<VizContent>;\n resolveSlugKey?: (slugKey: string) => Promise<VizId>;\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 (\n data.type === \"resolveSlugRequest\" &&\n resolveSlugKey\n ) {\n const { slugKey, requestId } = data;\n\n resolveSlugKey(slugKey).then((vizId) => {\n worker.postMessage({\n type: \"resolveSlugResponse\",\n slugKey,\n vizId,\n requestId,\n });\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 }: {\n files: FileCollection;\n enableHotReloading?: boolean;\n enableSourcemap?: boolean;\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 });\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 return;\n }\n\n DEBUG && console.log(\"[runtime] update: after build\");\n\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(\"[runtime] js: \", js?.substring(0, 200));\n\n DEBUG &&\n console.log(\n \"[runtime] css: \",\n css?.substring(0, 200),\n );\n\n // Clear the console before each run.\n 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 // 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 });\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 }: {\n files: FileCollection;\n enableHotReloading?: boolean;\n enableSourcemap?: boolean;\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 });\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","buildListener","data","buildResult","error","message","IDLE","ENQUEUED","PENDING_CLEAN","PENDING_DIRTY","createRuntime","iframe","getLatestContent","resolveSlugKey","writeFile","state","latestFiles","build","workerListener","vizId","content","slugKey","windowListener","event","cleanup","update","enableHotReloading","html","js","css","runCSSMessage","runJSMess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 @@
|
|
1
1
|
export { createRuntime } from "./orchestration/createRuntime";
|
2
|
+
export { build } from "./build";
|
2
3
|
export type { VizHubRuntime } from "./orchestration/types";
|
3
4
|
export { v3Build, computeBundleJSV3, createVizCache, createSlugCache, svelteCompilerUrl, cleanRollupErrorMessage, createVizContent, } from "./v3";
|
4
5
|
export type { VizCache, SlugCache, SvelteCompiler, } from "./v3";
|
package/dist/index.d.ts.map
CHANGED
@@ -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,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,MAAM,SAAS,CAAC;AAChC,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"}
|
package/dist/index.js
CHANGED
@@ -1,13 +1,13 @@
|
|
1
|
-
import { g as D } from "./
|
2
|
-
import {
|
1
|
+
import { g as D } from "./build-DU4cyBtp.js";
|
2
|
+
import { b as W, c as x, d as G, a as _, e as A, s as F, v as J } from "./build-DU4cyBtp.js";
|
3
3
|
const q = (t) => async (n) => {
|
4
4
|
const i = D();
|
5
|
-
return new Promise((
|
6
|
-
const l = (
|
7
|
-
|
5
|
+
return new Promise((d) => {
|
6
|
+
const l = (u) => {
|
7
|
+
u.data.type === "invalidateVizCacheResponse" && u.data.requestId === i && (t.removeEventListener(
|
8
8
|
"message",
|
9
9
|
l
|
10
|
-
),
|
10
|
+
), d());
|
11
11
|
};
|
12
12
|
t.addEventListener(
|
13
13
|
"message",
|
@@ -23,50 +23,50 @@ const q = (t) => async (n) => {
|
|
23
23
|
setBuildErrorMessage: n
|
24
24
|
}) => ({
|
25
25
|
files: i,
|
26
|
-
enableSourcemap:
|
26
|
+
enableSourcemap: d
|
27
27
|
}) => {
|
28
28
|
const l = D();
|
29
29
|
return new Promise(
|
30
|
-
(
|
30
|
+
(u) => {
|
31
31
|
const s = (m) => {
|
32
|
-
const
|
33
|
-
if (
|
32
|
+
const p = m.data;
|
33
|
+
if (p.type === "buildResponse") {
|
34
34
|
t.removeEventListener(
|
35
35
|
"message",
|
36
36
|
s
|
37
37
|
);
|
38
|
-
const
|
39
|
-
f ? n == null || n(f) : n == null || n(null),
|
38
|
+
const r = p.buildResult, f = p.error;
|
39
|
+
f ? n == null || n(f) : n == null || n(null), u(r);
|
40
40
|
}
|
41
41
|
};
|
42
42
|
t.addEventListener("message", s);
|
43
43
|
const c = {
|
44
44
|
type: "buildRequest",
|
45
45
|
files: i,
|
46
|
-
enableSourcemap:
|
46
|
+
enableSourcemap: d,
|
47
47
|
requestId: l
|
48
48
|
};
|
49
49
|
t.postMessage(c);
|
50
50
|
}
|
51
51
|
);
|
52
|
-
}, E = "IDLE", I = "ENQUEUED", L = "PENDING_CLEAN", R = "PENDING_DIRTY",
|
52
|
+
}, E = "IDLE", I = "ENQUEUED", L = "PENDING_CLEAN", R = "PENDING_DIRTY", z = ({
|
53
53
|
iframe: t,
|
54
54
|
worker: n,
|
55
55
|
setBuildErrorMessage: i,
|
56
|
-
getLatestContent:
|
56
|
+
getLatestContent: d,
|
57
57
|
resolveSlugKey: l,
|
58
|
-
writeFile:
|
58
|
+
writeFile: u
|
59
59
|
}) => {
|
60
60
|
let s = E, c = null;
|
61
61
|
const m = S({
|
62
62
|
worker: n,
|
63
63
|
setBuildErrorMessage: i
|
64
|
-
}),
|
64
|
+
}), p = ({
|
65
65
|
data: o
|
66
66
|
}) => {
|
67
|
-
if (o.type === "contentRequest" &&
|
67
|
+
if (o.type === "contentRequest" && d) {
|
68
68
|
const { vizId: e } = o;
|
69
|
-
|
69
|
+
d(e).then((a) => {
|
70
70
|
n.postMessage({
|
71
71
|
type: "contentResponse",
|
72
72
|
vizId: e,
|
@@ -85,14 +85,14 @@ const q = (t) => async (n) => {
|
|
85
85
|
});
|
86
86
|
}
|
87
87
|
};
|
88
|
-
n.addEventListener("message",
|
89
|
-
const
|
88
|
+
n.addEventListener("message", p);
|
89
|
+
const r = (o) => {
|
90
90
|
const e = o.data;
|
91
|
-
(e.type === "runDone" || e.type === "runError") && e.type === "runError" && i && i(e.error.message), e.type === "writeFile" &&
|
91
|
+
(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);
|
92
92
|
};
|
93
|
-
window.addEventListener("message",
|
93
|
+
window.addEventListener("message", r);
|
94
94
|
const f = () => {
|
95
|
-
n.removeEventListener("message",
|
95
|
+
n.removeEventListener("message", p), window.removeEventListener("message", r);
|
96
96
|
}, w = async ({
|
97
97
|
files: o,
|
98
98
|
enableHotReloading: e = !1,
|
@@ -173,7 +173,7 @@ const q = (t) => async (n) => {
|
|
173
173
|
run: g,
|
174
174
|
cleanup: f
|
175
175
|
};
|
176
|
-
},
|
176
|
+
}, P = ({
|
177
177
|
rawMessage: t,
|
178
178
|
vizId: n
|
179
179
|
}) => {
|
@@ -181,13 +181,14 @@ const q = (t) => async (n) => {
|
|
181
181
|
return t == null ? void 0 : t.replace(i, ".");
|
182
182
|
};
|
183
183
|
export {
|
184
|
-
|
185
|
-
|
186
|
-
|
187
|
-
|
188
|
-
G as
|
189
|
-
_ as
|
190
|
-
A as
|
191
|
-
F as
|
184
|
+
W as build,
|
185
|
+
P as cleanRollupErrorMessage,
|
186
|
+
x as computeBundleJSV3,
|
187
|
+
z as createRuntime,
|
188
|
+
G as createSlugCache,
|
189
|
+
_ as createVizCache,
|
190
|
+
A as createVizContent,
|
191
|
+
F as svelteCompilerUrl,
|
192
|
+
J as v3Build
|
192
193
|
};
|
193
194
|
//# sourceMappingURL=index.js.map
|
package/dist/worker.cjs
CHANGED
@@ -1,9 +1,2 @@
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
2
|
-
`);n=b(n,"</head>",c+`
|
3
|
-
`)}if(e["bundle.js"]!==void 0||e["index.js"]!==void 0){const r='<script src="bundle.js"><\/script>',c=/<script\b[^>]*\bsrc=["']bundle\.js["'][^>]*>\s*<\/script>/gi,s=[...n.matchAll(c)];s.length===1&&(()=>{const d=s[0].index??-1;if(d===-1)return!1;const l=n.search(/<body\b[^>]*>/i),p=n.search(/<\/body>/i);return l!==-1&&p!==-1&&d>l&&d<p})()||(n=n.replace(c,""),n=b(n,"</body>",r))}return/^\s*<!DOCTYPE/i.test(n)?n:`<!DOCTYPE html>${n}`},C=t=>{const e=t["index.html"];return!e&&!t["index.js"]&&!t["bundle.js"]?"":S(e||"<!DOCTYPE html><html><head></head><body></body></html>",t)},x=t=>{let e=t.replace(/^\.\//,"");return e=e.replace(/\/+/g,"/"),e=e.replace(/\/$/,""),e},j=(t,e)=>{const n=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=e.split("/"),o=n?n.split("/"):[];for(const r of i)r===".."?o.pop():r!=="."&&r!==""&&o.push(r);return o.join("/")},y=t=>({name:"virtual-file-system",resolveId(e,n){if(e.startsWith("./")||e.startsWith("../")){const o=x(n?j(n,e):e);if(t[o])return o;const r=[".js",".jsx",".ts",".tsx"];for(const c of r){const s=o+c;if(t[s])return s}}if(t[e])return e;const i=[".js",".jsx",".ts",".tsx"];for(const o of i){const r=e+o;if(t[r])return r}return null},load(e){return t[e]?t[e]:null}}),M=async({files:t,rollup:e,enableSourcemap:n=!0})=>{if(!t["index.js"])throw new Error("Missing index.js");const o={input:"./index.js",plugins:[y(t),u.sucrasePlugin()],onwarn(d,l){d.code!=="UNRESOLVED_IMPORT"&&l(d)}},r={format:"iife",sourcemap:n},c=u.packageJSON(t);if(c){const d=u.getGlobals(c);d&&(o.external=Object.keys(d),r.globals=d)}const s=await e(o),{output:a}=await s.generate(r);return a[0].code},$=async({files:t,rollup:e,enableSourcemap:n})=>({...t,"bundle.js":await M({files:t,rollup:e,enableSourcemap:n}),"index.html":C(t)}),P=t=>{const e=[],n=/<script\b([^>]*)>[\s\S]*?<\/script>/gi;let i;for(;(i=n.exec(t))!==null;){const o=i[1];if(!/\btype\s*=\s*["']module["']/i.test(o))continue;const r=o.match(/\bsrc\s*=\s*["']([^"']+)["']/i);r&&e.push(r[1])}return e},q=async({entryPoint:t,files:e,rollup:n,enableSourcemap:i=!0})=>{const o={input:`./${t}`,plugins:[y(e),u.sucrasePlugin()],external:s=>e[s]?!1:!s.startsWith("./"),onwarn(s,a){a(s)}},r=await n(o),{output:c}=await r.generate({format:"es",sourcemap:i});return c[0].code},g=(t,e)=>new RegExp(`<${e}\\b`,"i").test(t)&&new RegExp(`</${e}>`,"i").test(t),O=t=>{const e=t.trim();return g(e,"html")&&g(e,"head")&&g(e,"body")?e:`<html><head></head><body>${e}</body></html>`},T=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),I=(t,e,n)=>t.replace(new RegExp(e,"i"),`${n}${e}`),k=t=>{const e=u.dependencies(t);if(Object.keys(e).length===0)return null;const n=u.getConfiguredLibraries(t),i={};for(const[o,r]of Object.entries(e))i[o]=u.dependencySource({name:o,version:r},n);return JSON.stringify({imports:i},null,2)},B=(t,e)=>{if(!t["index.html"])return"";let n=O(t["index.html"]);e.forEach((o,r)=>{const c=new RegExp(`<script\\b[^>]*\\bsrc=["']${T(r)}["'][^>]*>[^<]*<\/script>`,"gi");n=n.replace(c,`<script type="module">
|
4
|
-
${o}
|
5
|
-
<\/script>`)});const i=k(t);if(i&&!/<script\b[^>]*type=["']importmap["'][^>]*>/i.test(n)){const r=`<script type="importmap">
|
6
|
-
${i}
|
7
|
-
<\/script>
|
8
|
-
`;n=I(n,"</head>",r)}return/^\s*<!DOCTYPE/i.test(n)?n:`<!DOCTYPE html>${n}`},V=async({files:t,rollup:e,enableSourcemap:n=!0})=>{const i=t["index.html"]||"",o=P(i);if(o.length===0)return t;const r=new Map;for(const s of o){const a=await q({entryPoint:s,files:t,rollup:e,enableSourcemap:n});r.set(s,a)}const c=B(t,r);return{...t,"index.html":c}},z=async({files:t,rollup:e,enableSourcemap:n=!0,vizCache:i,vizId:o,slugCache:r,getSvelteCompiler:c})=>{var a;if(!t&&!i)throw new Error("Either files or vizCache is required");if(!t&&i&&!o)throw new Error("vizId is required when using vizCache");if(!t&&i&&o&&(t=f.vizFilesToFileCollection((a=await i.get(o))==null?void 0:a.files)),!t)throw new Error("Upable to extract viz files");const s=v(t);if(s==="v1")return{html:h.magicSandbox(t)};if(s==="v2"){if(!e)throw new Error("Rollup is required for v2 runtime");return{html:h.magicSandbox(await $({files:t,rollup:e,enableSourcemap:n}))}}if(s==="v3"){if(!e)throw new Error("Rollup is required for v3 runtime");if(!i&&!o){const d=u.createVizContent(t);o=d.id,i=u.createVizCache({initialContents:[d],handleCacheMiss:async()=>{throw new Error("Cache miss handler not implemented")}})}if(!i)throw new Error("vizCache is required for v3 runtime");if(!o)throw new Error("vizId is required for v3 runtime");return await u.v3Build({files:t,rollup:e,vizCache:i,vizId:o,slugCache:r,getSvelteCompiler:c})}if(s==="v4"){if(!e)throw new Error("Rollup is required for v4 runtime");return{html:h.magicSandbox(await V({files:t,rollup:e,enableSourcemap:n}))}}throw new Error(`Unsupported runtime version: ${s}`)},J=()=>{const t=async()=>{const r=await fetch(u.svelteCompilerUrl).then(c=>c.text());return(0,eval)(r),self.svelte.compile},e=new Map,n=new Map,i=u.createVizCache({initialContents:[],handleCacheMiss:async r=>(postMessage({type:"contentRequest",vizId:r}),new Promise(s=>{e.set(r,s)}))}),o=u.createSlugCache({initialMappings:{},handleCacheMiss:async r=>{const c=u.generateRequestId();return postMessage({type:"resolveSlugRequest",slugKey:r,requestId:c}),new Promise(a=>{n.set(c,a)})}});addEventListener("message",async r=>{const c=r.data;switch(c.type){case"buildRequest":{const{files:s,enableSourcemap:a,requestId:d}=c;try{const p={type:"buildResponse",buildResult:await z({files:s,enableSourcemap:a,rollup:w.rollup,getSvelteCompiler:t,slugCache:o}),requestId:d};postMessage(p)}catch(l){const p={type:"buildResponse",error:""+l,requestId:d};postMessage(p)}break}case"contentResponse":{const s=e.get(c.vizId);s&&(s(c.content),e.delete(c.vizId));break}case"invalidateVizCacheRequest":{const{changedVizIds:s}=c;for(const a of s)i.invalidate(a);postMessage({type:"invalidateVizCacheResponse"});break}case"resolveSlugResponse":{const s=n.get(c.requestId);s&&(s(c.vizId),n.delete(c.requestId));break}}})};exports.initWorker=J;
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@rollup/browser");require("@vizhub/viz-utils");require("sucrase");const o=require("./build-DkIslKFi.cjs"),v=()=>{const u=async()=>{const t=await fetch(o.svelteCompilerUrl).then(e=>e.text());return(0,eval)(t),self.svelte.compile},a=new Map,r=new Map,d=o.createVizCache({initialContents:[],handleCacheMiss:async t=>(postMessage({type:"contentRequest",vizId:t}),new Promise(s=>{a.set(t,s)}))}),p=o.createSlugCache({initialMappings:{},handleCacheMiss:async t=>{const e=o.generateRequestId();return postMessage({type:"resolveSlugRequest",slugKey:t,requestId:e}),new Promise(n=>{r.set(e,n)})}});addEventListener("message",async t=>{const e=t.data;switch(e.type){case"buildRequest":{const{files:s,enableSourcemap:n,requestId:c}=e;try{const i={type:"buildResponse",buildResult:await o.build({files:s,enableSourcemap:n,rollup:g.rollup,getSvelteCompiler:u,slugCache:p}),requestId:c};postMessage(i)}catch(l){const i={type:"buildResponse",error:""+l,requestId:c};postMessage(i)}break}case"contentResponse":{const s=a.get(e.vizId);s&&(s(e.content),a.delete(e.vizId));break}case"invalidateVizCacheRequest":{const{changedVizIds:s}=e;for(const n of s)d.invalidate(n);postMessage({type:"invalidateVizCacheResponse"});break}case"resolveSlugResponse":{const s=r.get(e.requestId);s&&(s(e.vizId),r.delete(e.requestId));break}}})};exports.initWorker=v;
|
9
2
|
//# sourceMappingURL=worker.cjs.map
|
package/dist/worker.cjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"worker.cjs","sources":["../src/build/determineRuntimeVersion.ts","../src/v2/getComputedIndexHtml.ts","../src/common/virtualFileSystem.ts","../src/v2/computeBundleJSV2.ts","../src/v2/v2Build.ts","../src/v4/extractEntryPoints.ts","../src/v4/bundleModule.ts","../src/v4/stringUtils.ts","../src/v4/importMap.ts","../src/v4/updateHTML.ts","../src/v4/index.ts","../src/build/build.ts","../src/orchestration/worker.ts"],"sourcesContent":["import { FileCollection } from \"@vizhub/viz-types\";\nimport { runtimeVersion } from \"./types\";\n\nexport const determineRuntimeVersion = (\n files: FileCollection,\n): runtimeVersion | null => {\n if (Object.keys(files).length === 0) {\n return null;\n }\n\n const hasIndexHTML = \"index.html\" in files;\n\n const hasIndexJS = \"index.js\" in files;\n const hasIndexJSX = \"index.jsx\" in files;\n\n if (hasIndexHTML) {\n const hasModuleScript =\n files[\"index.html\"].includes('type=\"module\"');\n if (hasModuleScript) {\n return \"v4\";\n }\n\n if (hasIndexJS || hasIndexJSX) {\n return \"v2\";\n }\n return \"v1\";\n }\n\n if (!hasIndexHTML && hasIndexJS) {\n return \"v3\";\n }\n\n return null;\n};\n","import { FileCollection } from \"@vizhub/viz-types\";\nimport {\n dependencies,\n getConfiguredLibraries,\n dependencySource,\n} from \"../common/packageJson\";\n\nconst DEBUG = false;\n\n/* ------------------------------------------------------------------ */\n/* tiny helpers */\n/* ------------------------------------------------------------------ */\n\nconst hasTagPair = (html: string, tag: string) =>\n new RegExp(`<${tag}\\\\b`, \"i\").test(html) &&\n new RegExp(`</${tag}>`, \"i\").test(html);\n\n/** Make sure we have a complete <html><head></head><body></body> skeleton. */\nconst normaliseSkeleton = (raw: string): string => {\n const trimmed = raw.trim();\n\n // If it already contains a *complete* html‑head‑body trio we keep it.\n if (\n hasTagPair(trimmed, \"html\") &&\n hasTagPair(trimmed, \"head\") &&\n hasTagPair(trimmed, \"body\")\n )\n return trimmed;\n\n // Otherwise wrap whatever is there inside a fresh skeleton.\n return `<html><head></head><body>${trimmed}</body></html>`;\n};\n\n/** Remove every script whose src matches the supplied RegExp (global & i). */\nconst stripScripts = (\n html: string,\n srcPattern: RegExp,\n): string =>\n html.replace(\n new RegExp(\n `<script[^>]*src=[\"'][^\"']*${srcPattern.source}[^\"']*[\"'][^>]*>\\\\s*</script>`,\n \"gi\",\n ),\n \"\",\n );\n\n/** Inject markup just before a closing tag (</head> or </body>). */\nconst injectBeforeClose = (\n html: string,\n closing: \"</head>\" | \"</body>\",\n markup: string,\n) =>\n html.replace(\n new RegExp(closing, \"i\"),\n `${markup}${closing}`,\n );\n\n/* ------------------------------------------------------------------ */\n/* core logic */\n/* ------------------------------------------------------------------ */\n\nconst injectScripts = (\n template: string,\n files: FileCollection,\n): string => {\n let html = normaliseSkeleton(template);\n\n /* -------------------- dependencies from package.json ------------ */\n const deps = Object.entries(dependencies(files)) as [\n string,\n string,\n ][];\n\n if (deps.length) {\n const libraries = getConfiguredLibraries(files);\n\n // Remove any previous dependency scripts\n deps.forEach(([name]) => {\n html = stripScripts(html, new RegExp(`${name}@`));\n });\n\n // Build & inject new ones (order preserved)\n const depMarkup = deps\n .map(([name, version]) =>\n dependencySource({ name, version }, libraries),\n )\n .map((src) => `<script src=\"${src}\"></script>`)\n .join(\"\\n\");\n\n html = injectBeforeClose(\n html,\n \"</head>\",\n depMarkup + \"\\n\",\n );\n }\n\n /* -------------------- ensure exactly ONE bundle.js -------------- */\n const needBundle =\n files[\"bundle.js\"] !== undefined ||\n files[\"index.js\"] !== undefined;\n\n if (needBundle) {\n const bundleTag = `<script src=\"bundle.js\"></script>`; // **no newline – keeps test #3 exact**\n\n // How many bundle.js scripts are already there & where?\n const bundleRe =\n /<script\\b[^>]*\\bsrc=[\"']bundle\\.js[\"'][^>]*>\\s*<\\/script>/gi;\n const matches = [...html.matchAll(bundleRe)];\n\n const oneInBody =\n matches.length === 1 &&\n (() => {\n const idx = matches[0].index ?? -1;\n if (idx === -1) return false;\n const bodyOpen = html.search(/<body\\b[^>]*>/i);\n const bodyClose = html.search(/<\\/body>/i);\n return (\n bodyOpen !== -1 &&\n bodyClose !== -1 &&\n idx > bodyOpen &&\n idx < bodyClose\n );\n })();\n\n if (!oneInBody) {\n // wipe them all, then inject a clean one at the end of <body>\n html = html.replace(bundleRe, \"\");\n html = injectBeforeClose(html, \"</body>\", bundleTag);\n }\n }\n\n /* -------------------- make sure <!DOCTYPE html> ----------------- */\n return /^\\s*<!DOCTYPE/i.test(html)\n ? html\n : `<!DOCTYPE html>${html}`;\n};\n\n/* ------------------------------------------------------------------ */\n/* public API */\n/* ------------------------------------------------------------------ */\n\nexport const getComputedIndexHtml = (\n files: FileCollection,\n): string => {\n const htmlTemplate = files[\"index.html\"];\n\n // No html and no JS – nothing to do.\n if (\n !htmlTemplate &&\n !files[\"index.js\"] &&\n !files[\"bundle.js\"]\n ) {\n DEBUG &&\n console.log(\n \"[getComputedIndexHtml] No index.html file found\",\n );\n return \"\";\n }\n\n const template =\n htmlTemplate ||\n \"<!DOCTYPE html><html><head></head><body></body></html>\";\n\n const result = injectScripts(template, files);\n\n DEBUG &&\n console.log(\"[getComputedIndexHtml] indexHtml\", result);\n\n return result;\n};\n","import { FileCollection } from \"@vizhub/viz-types\";\nimport { Plugin } from \"rollup\";\n\nconst normalizePath = (filepath: string): string => {\n // Remove leading ./\n let normalized = filepath.replace(/^\\.\\//, \"\");\n // Replace multiple slashes with single slash\n normalized = normalized.replace(/\\/+/g, \"/\");\n // Remove trailing slash\n normalized = normalized.replace(/\\/$/, \"\");\n return normalized;\n};\n\nconst joinPaths = (\n base: string,\n relative: string,\n): string => {\n // Get directory name of base path\n const baseDir = base.includes(\"/\")\n ? base.slice(0, base.lastIndexOf(\"/\"))\n : \"\";\n\n // Handle .. by removing one directory level\n const parts = relative.split(\"/\");\n const resultParts: string[] = baseDir\n ? baseDir.split(\"/\")\n : [];\n\n for (const part of parts) {\n if (part === \"..\") {\n resultParts.pop();\n } else if (part !== \".\" && part !== \"\") {\n resultParts.push(part);\n }\n }\n\n return resultParts.join(\"/\");\n};\n\nexport const virtualFileSystem = (\n files: FileCollection,\n): Plugin => {\n return {\n name: \"virtual-file-system\",\n\n resolveId(source: string, importer?: string) {\n // Handle relative paths\n if (\n source.startsWith(\"./\") ||\n source.startsWith(\"../\")\n ) {\n const resolvedPath = importer\n ? normalizePath(joinPaths(importer, source))\n : normalizePath(source);\n\n // Try exact match first\n if (files[resolvedPath]) {\n return resolvedPath;\n }\n\n // Try with extensions if no exact match is found\n const extensions = [\".js\", \".jsx\", \".ts\", \".tsx\"];\n for (const ext of extensions) {\n const pathWithExt = resolvedPath + ext;\n if (files[pathWithExt]) {\n return pathWithExt;\n }\n }\n }\n\n // Handle bare module imports\n if (files[source]) {\n return source;\n }\n\n // Try bare imports with extensions\n const extensions = [\".js\", \".jsx\", \".ts\", \".tsx\"];\n for (const ext of extensions) {\n const pathWithExt = source + ext;\n if (files[pathWithExt]) {\n return pathWithExt;\n }\n }\n\n return null;\n },\n\n load(id: string) {\n // Return the contents if the file exists in our virtual system\n if (files[id]) {\n return files[id];\n }\n\n return null;\n },\n };\n};\n","import type {\n RollupBuild,\n RollupOptions,\n OutputOptions,\n} from \"rollup\";\nimport { FileCollection } from \"@vizhub/viz-types\";\nimport { virtualFileSystem } from \"../common/virtualFileSystem.js\";\nimport { sucrasePlugin } from \"../common/sucrasePlugin.js\";\nimport {\n getGlobals,\n packageJSON,\n} from \"../common/packageJson.js\";\n\nexport const computeBundleJSV2 = async ({\n files,\n rollup,\n enableSourcemap = true,\n}: {\n files: FileCollection;\n rollup: (options: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n}): Promise<string> => {\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: [virtualFileSystem(files), sucrasePlugin()],\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: \"iife\",\n sourcemap: enableSourcemap,\n };\n\n const pkg = packageJSON(files);\n\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 output[0].code;\n};\n","import type { RollupBuild, RollupOptions } from \"rollup\";\nimport { FileCollection } from \"@vizhub/viz-types\";\nimport { getComputedIndexHtml } from \"./getComputedIndexHtml\";\nimport { computeBundleJSV2 } from \"./computeBundleJSV2\";\n\nexport const v2Build = async ({\n files,\n rollup,\n enableSourcemap,\n}: {\n files: FileCollection;\n rollup: (options: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n}): Promise<FileCollection> => ({\n ...files,\n \"bundle.js\": await computeBundleJSV2({\n files,\n rollup,\n enableSourcemap,\n }),\n \"index.html\": getComputedIndexHtml(files),\n});\n","/**\n * Extract module script entry points from index.html\n */\nexport const extractModuleEntryPoints = (\n html: string,\n): string[] => {\n const entryPoints: string[] = [];\n const scriptTag = /<script\\b([^>]*)>[\\s\\S]*?<\\/script>/gi;\n let m: RegExpExecArray | null;\n\n while ((m = scriptTag.exec(html)) !== null) {\n const attrs = m[1];\n if (!/\\btype\\s*=\\s*[\"']module[\"']/i.test(attrs))\n continue;\n const srcMatch = attrs.match(\n /\\bsrc\\s*=\\s*[\"']([^\"']+)[\"']/i,\n );\n if (srcMatch) entryPoints.push(srcMatch[1]);\n }\n return entryPoints;\n};\n","import type {\n RollupBuild,\n RollupOptions,\n OutputOptions,\n} from \"rollup\";\nimport { FileCollection } from \"@vizhub/viz-types\";\nimport { virtualFileSystem } from \"..//common/virtualFileSystem.js\";\nimport { sucrasePlugin } from \"..//common/sucrasePlugin.js\";\nimport { dependencies } from \"../common/packageJson.js\";\n\n/**\n * Bundle a single ES module entry point\n */\nexport const bundleESModule = async ({\n entryPoint,\n files,\n rollup,\n enableSourcemap = true,\n}: {\n entryPoint: string;\n files: FileCollection;\n rollup: (o: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n}): Promise<string> => {\n const inputOptions: RollupOptions = {\n input: `./${entryPoint}`,\n plugins: [virtualFileSystem(files), sucrasePlugin()],\n external: (source: string) => {\n // Handle strings resolved by `virtualFileSystem`.\n if (files[source]) return false;\n // Handle external dependencies, e.g. from import maps.\n return !source.startsWith(\"./\");\n },\n onwarn(w, warn) {\n // if (w.code === \"UNRESOLVED_IMPORT\") return; // quiet noisy warnings\n warn(w);\n },\n };\n\n const bundle = await rollup(inputOptions);\n const { output } = await bundle.generate({\n format: \"es\",\n sourcemap: enableSourcemap,\n } as OutputOptions);\n\n return output[0].code;\n};\n","/**\n * Does the html already contain a <tag>…</tag> pair?\n */\nexport const hasTagPair = (html: string, tag: string) =>\n new RegExp(`<${tag}\\\\b`, \"i\").test(html) &&\n new RegExp(`</${tag}>`, \"i\").test(html);\n\n/**\n * Ensure <html><head></head><body></body> skeleton exists.\n */\nexport const normaliseSkeleton = (raw: string): string => {\n const trimmed = raw.trim();\n\n if (\n hasTagPair(trimmed, \"html\") &&\n hasTagPair(trimmed, \"head\") &&\n hasTagPair(trimmed, \"body\")\n )\n return trimmed;\n\n return `<html><head></head><body>${trimmed}</body></html>`;\n};\n\n/**\n * Escape characters so they can appear literally inside a RegExp.\n */\nexport const escapeRegExp = (s: string) =>\n s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/**\n * Inject markup immediately before </head> or </body>.\n */\nexport const injectBeforeClose = (\n html: string,\n closing: \"</head>\" | \"</body>\",\n markup: string,\n) =>\n html.replace(\n new RegExp(closing, \"i\"),\n `${markup}${closing}`,\n );\n","import { FileCollection } from \"@vizhub/viz-types\";\nimport {\n dependencies,\n getConfiguredLibraries,\n dependencySource,\n} from \"../common/packageJson.js\";\n\n/**\n * Generate an import map for all dependencies\n */\nexport const generateImportMap = (\n files: FileCollection,\n): string | null => {\n const deps = dependencies(files);\n if (Object.keys(deps).length === 0) return null;\n\n const libraries = getConfiguredLibraries(files);\n const imports: Record<string, string> = {};\n\n for (const [name, version] of Object.entries(deps)) {\n imports[name] = dependencySource(\n { name, version },\n libraries,\n );\n }\n return JSON.stringify({ imports }, null, 2);\n};\n","import { FileCollection } from \"@vizhub/viz-types\";\nimport {\n normaliseSkeleton,\n escapeRegExp,\n injectBeforeClose,\n} from \"./stringUtils.js\";\nimport { generateImportMap } from \"./importMap.js\";\n\n/**\n * Update HTML to include import map and bundled modules\n */\nexport const updateHTML = (\n files: FileCollection,\n bundled: Map<string, string>,\n): string => {\n if (!files[\"index.html\"]) return \"\";\n\n let html = normaliseSkeleton(files[\"index.html\"]);\n\n // Replace each <script src=\"…\"> with inline module\n bundled.forEach((code, src) => {\n const tagRe = new RegExp(\n `<script\\\\b[^>]*\\\\bsrc=[\"']${escapeRegExp(src)}[\"'][^>]*>[^<]*</script>`,\n \"gi\",\n );\n html = html.replace(\n tagRe,\n `<script type=\"module\">\\n${code}\\n</script>`,\n );\n });\n\n // Add <script type=\"importmap\"> if needed\n const importMapJson = generateImportMap(files);\n if (importMapJson) {\n const already =\n /<script\\b[^>]*type=[\"']importmap[\"'][^>]*>/i.test(\n html,\n );\n\n if (!already) {\n const importMapTag = `<script type=\"importmap\">\\n${importMapJson}\\n</script>\\n`;\n html = injectBeforeClose(\n html,\n \"</head>\",\n importMapTag,\n );\n }\n }\n\n // Ensure <!DOCTYPE html>\n return /^\\s*<!DOCTYPE/i.test(html)\n ? html\n : `<!DOCTYPE html>${html}`;\n};\n","import type { RollupBuild, RollupOptions } from \"rollup\";\nimport { FileCollection } from \"@vizhub/viz-types\";\nimport { extractModuleEntryPoints } from \"./extractEntryPoints.js\";\nimport { bundleESModule } from \"./bundleModule.js\";\nimport { updateHTML } from \"./updateHTML.js\";\n\nconst DEBUG = false;\n\n/**\n * Build for v4 runtime\n */\nexport const v4Build = async ({\n files,\n rollup,\n enableSourcemap = true,\n}: {\n files: FileCollection;\n rollup: (o: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n}): Promise<FileCollection> => {\n const html = files[\"index.html\"] || \"\";\n const entryPoints = extractModuleEntryPoints(html);\n\n if (entryPoints.length === 0) {\n DEBUG &&\n console.log(\"[v4Build] No module entry points found\");\n return files; // nothing to bundle\n }\n\n const bundled = new Map<string, string>();\n for (const entry of entryPoints) {\n const code = await bundleESModule({\n entryPoint: entry,\n files,\n rollup,\n enableSourcemap,\n });\n bundled.set(entry, code);\n }\n\n const updatedHTML = updateHTML(files, bundled);\n\n return {\n ...files,\n \"index.html\": updatedHTML,\n };\n};\n\n// Export the extractModuleEntryPoints function for external use\nexport { extractModuleEntryPoints };\n","import { magicSandbox } from \"magic-sandbox\";\nimport { FileCollection } from \"@vizhub/viz-types\";\nimport type { RollupBuild, RollupOptions } from \"rollup\";\nimport {\n createVizCache,\n createVizContent,\n SlugCache,\n SvelteCompiler,\n v3Build,\n VizCache,\n} from \"../v3\";\nimport { BuildResult } from \"./types\";\nimport { vizFilesToFileCollection } from \"@vizhub/viz-utils\";\nimport { determineRuntimeVersion } from \"./determineRuntimeVersion\";\nimport { v2Build } from \"../v2\";\nimport { v4Build } from \"../v4\";\n\nconst DEBUG = false;\n\n// Builds the given files.\nexport const build = async ({\n files,\n rollup,\n enableSourcemap = true,\n vizCache,\n vizId,\n slugCache,\n getSvelteCompiler,\n}: {\n // Only required for v1 and v2 runtime\n // For v3, EITHER files OR vizCache is required\n files?: FileCollection;\n\n // Only required for v2 and v3 runtime\n rollup?: (options: RollupOptions) => Promise<RollupBuild>;\n\n // True to enable sourcemaps, which help with\n // tracing runtime errors back to source code,\n // including specific source files and line numbers.\n // When true, there is additional overhead\n // for generating the sourcemaps, and the generated bundle\n // is larger.\n enableSourcemap?: boolean;\n\n // Only required for v3 runtime\n // For v3, EITHER files OR vizCache is required\n vizCache?: VizCache;\n\n // Only required for v3 runtime\n vizId?: string;\n\n // Only required for v3 runtime\n slugCache?: SlugCache;\n\n // Only required for v3 runtime\n getSvelteCompiler?: () => Promise<SvelteCompiler>;\n}): Promise<BuildResult> => {\n DEBUG &&\n console.log(\n \"[build] files:\",\n files\n ? JSON.stringify(files).substring(0, 100)\n : undefined,\n );\n DEBUG && console.log(\"[build] vizCache:\", vizCache);\n DEBUG && console.log(\"[build] vizId:\", vizId);\n\n if (!files && !vizCache) {\n throw new Error(\"Either files or vizCache is required\");\n }\n\n if (!files && vizCache && !vizId) {\n throw new Error(\n \"vizId is required when using vizCache\",\n );\n }\n\n if (!files && vizCache && vizId) {\n files = vizFilesToFileCollection(\n (await vizCache.get(vizId))?.files,\n );\n }\n\n if (!files) {\n throw new Error(\"Upable to extract viz files\");\n }\n\n const version = determineRuntimeVersion(files);\n DEBUG && console.log(\"[build] version:\", version);\n if (version === \"v1\") {\n return {\n html: magicSandbox(files),\n };\n }\n if (version === \"v2\") {\n if (!rollup) {\n throw new Error(\"Rollup is required for v2 runtime\");\n }\n return {\n html: magicSandbox(\n await v2Build({ files, rollup, enableSourcemap }),\n ),\n };\n }\n if (version === \"v3\") {\n if (!rollup) {\n throw new Error(\"Rollup is required for v3 runtime\");\n }\n\n // We set up a \"fake\" viz cache.\n // It's needed because of the way the CSS import resolution works.\n if (!vizCache && !vizId) {\n const vizContent = createVizContent(files);\n vizId = vizContent.id;\n vizCache = createVizCache({\n initialContents: [vizContent],\n handleCacheMiss: async () => {\n throw new Error(\n \"Cache miss handler not implemented\",\n );\n },\n });\n }\n\n if (!vizCache) {\n throw new Error(\n \"vizCache is required for v3 runtime\",\n );\n }\n\n if (!vizId) {\n throw new Error(\"vizId is required for v3 runtime\");\n }\n\n return await v3Build({\n files,\n rollup,\n vizCache,\n vizId,\n slugCache,\n getSvelteCompiler,\n });\n }\n\n if (version === \"v4\") {\n if (!rollup) {\n throw new Error(\"Rollup is required for v4 runtime\");\n }\n DEBUG &&\n console.log(\"[build] v4Build\", {\n files,\n rollup,\n enableSourcemap,\n });\n return {\n html: magicSandbox(\n await v4Build({ files, rollup, enableSourcemap }),\n ),\n };\n }\n\n throw new Error(\n `Unsupported runtime version: ${version}`,\n );\n};\n","import { rollup } from \"@rollup/browser\";\nimport { VizContent, VizId } from \"@vizhub/viz-types\";\nimport type { RollupBuild, RollupOptions } from \"rollup\";\nimport {\n svelteCompilerUrl,\n createVizCache,\n createSlugCache,\n} from \"../v3\";\nimport { generateRequestId } from \"./generateRequestId\";\nimport { BuildWorkerMessage } from \"./types\";\nimport { build } from \"../build\";\n\n// Flag for debugging\nconst DEBUG = false;\n\nexport const initWorker = () => {\n DEBUG && console.log(\"[worker] initializing...\");\n // Inspired by\n // https://github.com/sveltejs/sites/blob/master/packages/repl/src/lib/workers/bundler/index.js#L44\n // unpkg doesn't set the correct MIME type for .cjs files\n // https://github.com/mjackson/unpkg/issues/355\n const getSvelteCompiler = async () => {\n const compiler = await fetch(svelteCompilerUrl).then(\n (r) => r.text(),\n );\n (0, eval)(compiler);\n\n // @ts-ignore\n return self.svelte.compile;\n };\n\n // Tracks pending promises for 'contentResponse' messages\n const pendingContentResponsePromises = new Map();\n\n // Tracks pending promises for 'resolveSlugResponse' messages\n const pendingResolveSlugResponsePromises = new Map();\n\n // Create a viz cache that's backed by the main thread\n const vizCache = createVizCache({\n initialContents: [],\n handleCacheMiss: async (\n vizId: VizId,\n ): Promise<VizContent> => {\n const message = {\n type: \"contentRequest\",\n vizId,\n };\n\n if (DEBUG) {\n console.log(\n \"[worker] sending content request message to main thread\",\n message,\n );\n }\n postMessage(message);\n\n return new Promise((resolve) => {\n pendingContentResponsePromises.set(vizId, resolve);\n });\n },\n });\n\n // Create a slug cache that's backed by the main thread\n const slugCache = createSlugCache({\n initialMappings: {},\n handleCacheMiss: async (slug) => {\n const requestId = generateRequestId();\n const message = {\n type: \"resolveSlugRequest\",\n slugKey: slug,\n requestId,\n };\n\n if (DEBUG) {\n console.log(\n \"[worker] sending resolve slug request message to main thread\",\n message,\n );\n }\n postMessage(message);\n\n return new Promise((resolve) => {\n pendingResolveSlugResponsePromises.set(\n requestId,\n resolve,\n );\n });\n },\n });\n\n // Handle messages from the main thread\n addEventListener(\"message\", async (event) => {\n const data: BuildWorkerMessage = event.data;\n\n DEBUG &&\n console.log(\n \"[worker] received message:\",\n JSON.stringify(data, null, 2).substring(0, 1000),\n );\n\n switch (data.type) {\n case \"buildRequest\": {\n const { files, enableSourcemap, requestId } = data;\n\n try {\n // Build HTML from the files\n const buildResult = await build({\n files,\n enableSourcemap,\n rollup: rollup as (\n options: RollupOptions,\n ) => Promise<RollupBuild>,\n getSvelteCompiler,\n // vizCache,\n slugCache,\n });\n const message: BuildWorkerMessage = {\n type: \"buildResponse\",\n buildResult,\n requestId,\n };\n // Send the built HTML back to the main thread\n postMessage(message);\n } catch (error) {\n DEBUG &&\n console.log(\"[worker] build error:\", error);\n\n const message: BuildWorkerMessage = {\n type: \"buildResponse\",\n error: \"\" + error,\n requestId,\n };\n\n // Send the error back to the main thread\n postMessage(message);\n }\n break;\n }\n\n case \"contentResponse\": {\n // Resolve pending promises for content snapshots\n const resolver = pendingContentResponsePromises.get(\n data.vizId,\n );\n if (resolver) {\n resolver(data.content);\n pendingContentResponsePromises.delete(data.vizId);\n }\n break;\n }\n\n case \"invalidateVizCacheRequest\": {\n if (DEBUG) {\n console.log(\n \"[worker] received invalidateVizCacheRequest\",\n data,\n );\n }\n const { changedVizIds } = data;\n\n // Invalidate the viz cache for the changed vizzes\n for (const vizId of changedVizIds) {\n vizCache.invalidate(vizId);\n }\n\n postMessage({\n type: \"invalidateVizCacheResponse\",\n });\n break;\n }\n\n case \"resolveSlugResponse\": {\n // Resolve pending promises for slug resolution\n const resolver =\n pendingResolveSlugResponsePromises.get(\n data.requestId,\n );\n if (resolver) {\n resolver(data.vizId);\n pendingResolveSlugResponsePromises.delete(\n data.requestId,\n );\n }\n break;\n }\n }\n });\n};\n"],"names":["determineRuntimeVersion","files","hasIndexHTML","hasIndexJS","hasIndexJSX","hasTagPair","html","tag","normaliseSkeleton","raw","trimmed","stripScripts","srcPattern","injectBeforeClose","closing","markup","injectScripts","template","deps","dependencies","libraries","getConfiguredLibraries","name","depMarkup","version","dependencySource","src","bundleTag","bundleRe","matches","idx","bodyOpen","bodyClose","getComputedIndexHtml","htmlTemplate","normalizePath","filepath","normalized","joinPaths","base","relative","baseDir","parts","resultParts","part","virtualFileSystem","source","importer","resolvedPath","extensions","ext","pathWithExt","id","computeBundleJSV2","rollup","enableSourcemap","inputOptions","sucrasePlugin","warning","warn","outputOptions","pkg","packageJSON","globals","getGlobals","bundle","output","v2Build","extractModuleEntryPoints","entryPoints","scriptTag","m","attrs","srcMatch","bundleESModule","entryPoint","w","escapeRegExp","s","generateImportMap","imports","updateHTML","bundled","code","tagRe","importMapJson","importMapTag","v4Build","entry","updatedHTML","build","vizCache","vizId","slugCache","getSvelteCompiler","vizFilesToFileCollection","_a","magicSandbox","vizContent","createVizContent","createVizCache","v3Build","initWorker","compiler","svelteCompilerUrl","r","pendingContentResponsePromises","pendingResolveSlugResponsePromises","resolve","createSlugCache","slug","requestId","generateRequestId","event","data","message","error","resolver","changedVizIds"],"mappings":"mPAGaA,EACXC,GAC0B,CAC1B,GAAI,OAAO,KAAKA,CAAK,EAAE,SAAW,EACzB,OAAA,KAGT,MAA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,YAAA,CACV,KAAM,4BAAA,CACP,EACD,KAAA,CAGF,IAAK,sBAAuB,CAE1B,MAAMyB,EACJV,EAAmC,IACjCO,EAAK,SACP,EACEG,IACFA,EAASH,EAAK,KAAK,EACgBP,EAAA,OACjCO,EAAK,SACP,GAEF,KAAA,CACF,CACF,CACD,CACH"}
|
1
|
+
{"version":3,"file":"worker.cjs","sources":["../src/orchestration/worker.ts"],"sourcesContent":["import { rollup } from \"@rollup/browser\";\nimport { VizContent, VizId } from \"@vizhub/viz-types\";\nimport type { RollupBuild, RollupOptions } from \"rollup\";\nimport {\n svelteCompilerUrl,\n createVizCache,\n createSlugCache,\n} from \"../v3\";\nimport { generateRequestId } from \"./generateRequestId\";\nimport { BuildWorkerMessage } from \"./types\";\nimport { build } from \"../build\";\n\n// Flag for debugging\nconst DEBUG = false;\n\nexport const initWorker = () => {\n DEBUG && console.log(\"[worker] initializing...\");\n // Inspired by\n // https://github.com/sveltejs/sites/blob/master/packages/repl/src/lib/workers/bundler/index.js#L44\n // unpkg doesn't set the correct MIME type for .cjs files\n // https://github.com/mjackson/unpkg/issues/355\n const getSvelteCompiler = async () => {\n const compiler = await fetch(svelteCompilerUrl).then(\n (r) => r.text(),\n );\n (0, eval)(compiler);\n\n // @ts-ignore\n return self.svelte.compile;\n };\n\n // Tracks pending promises for 'contentResponse' messages\n const pendingContentResponsePromises = new Map();\n\n // Tracks pending promises for 'resolveSlugResponse' messages\n const pendingResolveSlugResponsePromises = new Map();\n\n // Create a viz cache that's backed by the main thread\n const vizCache = createVizCache({\n initialContents: [],\n handleCacheMiss: async (\n vizId: VizId,\n ): Promise<VizContent> => {\n const message = {\n type: \"contentRequest\",\n vizId,\n };\n\n if (DEBUG) {\n console.log(\n \"[worker] sending content request message to main thread\",\n message,\n );\n }\n postMessage(message);\n\n return new Promise((resolve) => {\n pendingContentResponsePromises.set(vizId, resolve);\n });\n },\n });\n\n // Create a slug cache that's backed by the main thread\n const slugCache = createSlugCache({\n initialMappings: {},\n handleCacheMiss: async (slug) => {\n const requestId = generateRequestId();\n const message = {\n type: \"resolveSlugRequest\",\n slugKey: slug,\n requestId,\n };\n\n if (DEBUG) {\n console.log(\n \"[worker] sending resolve slug request message to main thread\",\n message,\n );\n }\n postMessage(message);\n\n return new Promise((resolve) => {\n pendingResolveSlugResponsePromises.set(\n requestId,\n resolve,\n );\n });\n },\n });\n\n // Handle messages from the main thread\n addEventListener(\"message\", async (event) => {\n const data: BuildWorkerMessage = event.data;\n\n DEBUG &&\n console.log(\n \"[worker] received message:\",\n JSON.stringify(data, null, 2).substring(0, 1000),\n );\n\n switch (data.type) {\n case \"buildRequest\": {\n const { files, enableSourcemap, requestId } = data;\n\n try {\n // Build HTML from the files\n const buildResult = await build({\n files,\n enableSourcemap,\n rollup: rollup as (\n options: RollupOptions,\n ) => Promise<RollupBuild>,\n getSvelteCompiler,\n // vizCache,\n slugCache,\n });\n const message: BuildWorkerMessage = {\n type: \"buildResponse\",\n buildResult,\n requestId,\n };\n // Send the built HTML back to the main thread\n postMessage(message);\n } catch (error) {\n DEBUG &&\n console.log(\"[worker] build error:\", error);\n\n const message: BuildWorkerMessage = {\n type: \"buildResponse\",\n error: \"\" + error,\n requestId,\n };\n\n // Send the error back to the main thread\n postMessage(message);\n }\n break;\n }\n\n case \"contentResponse\": {\n // Resolve pending promises for content snapshots\n const resolver = pendingContentResponsePromises.get(\n data.vizId,\n );\n if (resolver) {\n resolver(data.content);\n pendingContentResponsePromises.delete(data.vizId);\n }\n break;\n }\n\n case \"invalidateVizCacheRequest\": {\n if (DEBUG) {\n console.log(\n \"[worker] received invalidateVizCacheRequest\",\n data,\n );\n }\n const { changedVizIds } = data;\n\n // Invalidate the viz cache for the changed vizzes\n for (const vizId of changedVizIds) {\n vizCache.invalidate(vizId);\n }\n\n postMessage({\n type: \"invalidateVizCacheResponse\",\n });\n break;\n }\n\n case \"resolveSlugResponse\": {\n // Resolve pending promises for slug resolution\n const resolver =\n pendingResolveSlugResponsePromises.get(\n data.requestId,\n );\n if (resolver) {\n resolver(data.vizId);\n pendingResolveSlugResponsePromises.delete(\n data.requestId,\n );\n }\n break;\n }\n }\n });\n};\n"],"names":["initWorker","getSvelteCompiler","compiler","svelteCompilerUrl","r","pendingContentResponsePromises","pendingResolveSlugResponsePromises","vizCache","createVizCache","vizId","resolve","slugCache","createSlugCache","slug","requestId","generateRequestId","event","data","files","enableSourcemap","message","build","rollup","error","resolver","changedVizIds"],"mappings":"2MAeaA,EAAa,IAAM,CAM9B,MAAMC,EAAoB,SAAY,CACpC,MAAMC,EAAW,MAAM,MAAMC,EAAAA,iBAAiB,EAAE,KAC7CC,GAAMA,EAAE,KAAK,CAChB,EACC,SAAG,MAAMF,CAAQ,EAGX,KAAK,OAAO,OACrB,EAGMG,MAAqC,IAGrCC,MAAyC,IAGzCC,EAAWC,EAAAA,eAAe,CAC9B,gBAAiB,CAAC,EAClB,gBAAiB,MACfC,IAaA,YAXgB,CACd,KAAM,iBACN,MAAAA,CACF,CAQmB,EAEZ,IAAI,QAASC,GAAY,CACCL,EAAA,IAAII,EAAOC,CAAO,CAAA,CAClD,EACH,CACD,EAGKC,EAAYC,EAAAA,gBAAgB,CAChC,gBAAiB,CAAC,EAClB,gBAAiB,MAAOC,GAAS,CAC/B,MAAMC,EAAYC,EAAAA,kBAAkB,EAapC,mBAZgB,CACd,KAAM,qBACN,QAASF,EACT,UAAAC,CACF,CAQmB,EAEZ,IAAI,QAASJ,GAAY,CACKJ,EAAA,IACjCQ,EACAJ,CACF,CAAA,CACD,CAAA,CACH,CACD,EAGgB,iBAAA,UAAW,MAAOM,GAAU,CAC3C,MAAMC,EAA2BD,EAAM,KAQvC,OAAQC,EAAK,KAAM,CACjB,IAAK,eAAgB,CACnB,KAAM,CAAE,MAAAC,EAAO,gBAAAC,EAAiB,UAAAL,CAAc,EAAAG,EAE1C,GAAA,CAYF,MAAMG,EAA8B,CAClC,KAAM,gBACN,YAZkB,MAAMC,QAAM,CAC9B,MAAAH,EACA,gBAAA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