diff --git a/README.md b/README.md index d282dae15b..f7ff14e719 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,10 @@ Run `Deepnote: Preview App` from the Command Palette, or right-click a folder in - A run keeps going until its notebook finishes, even after you close the preview. Reloading or closing the VS Code window stops it. - Each run's results are saved as a `.snapshot.deepnote` file in VS Code's storage for the workspace, outside the project, and are cleared the first time the app preview starts after the window reloads. - `appData()` answers from that notebook's last successful `run()`: the first JSON object the run displayed (an `application/json` output), the first agent block's answer, and when the run started. Until a run succeeds, it rejects with Deepnote's message. A copy of each notebook's last successful run is saved in the same storage and kept when the window reloads, so `appData()` still answers after a reload. +- `dataframe(name, { pageIndex, pageSize })` pages through the frame stored under that name in `deepnote_dataframes//` in the app's project folder, the folder of the `.deepnote` file nearest at or above the app folder. Pages and values match Deepnote's, but the preview does not apply Deepnote's limits on how much one page may hold. + - When the preview finds no project for the app folder (no `.deepnote` file at or above it, or the nearest folder with one holds files of more than one project), `dataframe()` rejects with Deepnote's `Reload the page to read dataframes.` Reloading does not change that: add or move the `.deepnote` file, then run `Deepnote: Preview App` again. + - The deepnote-toolkit version the extension installs does not store frames there yet: `store_dataframe(df, name)` writes them to `/work/deepnote_dataframes/`, which every project shares. The preview reads a frame from there when the project folder has none under that name. + - Reading a frame that deepnote-toolkit compressed with zstd needs an editor whose Node.js has zstd (22.15 or later). - Previewing needs a trusted workspace and the desktop app. ### Database integrations diff --git a/package-lock.json b/package-lock.json index b36a33f535..a422f03f08 100644 --- a/package-lock.json +++ b/package-lock.json @@ -40,6 +40,7 @@ "@vscode/jupyter-ipywidgets8": "^1.0.9", "@vscode/python-extension": "^1.0.4", "ansi-to-html": "^0.6.7", + "apache-arrow": "^21.2.0", "bootstrap": "^5.0.0", "bootstrap-less": "^3.3.8", "clsx": "^2.1.1", @@ -10488,6 +10489,36 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/apache-arrow": { + "version": "21.2.0", + "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-21.2.0.tgz", + "integrity": "sha512-Hxe6Agq26gQOM954qpzYSllJBPJl+e16U5CkfuMUhLrNba+5nKkttIVlflaovN6oaTratqMGAO8H5u/aNhmHWQ==", + "license": "Apache-2.0", + "dependencies": { + "@types/node": "^25.2.0", + "flatbuffers": "^25.1.24", + "json-with-bigint": "^3.5.3", + "tslib": "^2.6.2" + }, + "bin": { + "arrow2csv": "bin/arrow2csv.js" + } + }, + "node_modules/apache-arrow/node_modules/@types/node": { + "version": "25.9.9", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.9.tgz", + "integrity": "sha512-b4e2xxj/yMeT2hNlD6x7zNFiQK2Dlmkb9CQ6v3/1G2RezKN4YS2lcEv8lzGm1mhs4f2lM4yNAMI/zUDBZBBt7w==", + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/apache-arrow/node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "license": "MIT" + }, "node_modules/append-transform": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/append-transform/-/append-transform-2.0.0.tgz", @@ -17051,6 +17082,12 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, "node_modules/flatted": { "version": "3.4.4", "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", @@ -20242,7 +20279,6 @@ "version": "3.5.7", "resolved": "https://registry.npmjs.org/json-with-bigint/-/json-with-bigint-3.5.7.tgz", "integrity": "sha512-7ei3MdAI5+fJPVnKlW77TKNKwQ5ppSzWvhPuSuINT/GYW9ZOC1eRKOuhV9yHG5aEsUPj9BBx5JIekkmoLHxZOw==", - "dev": true, "license": "MIT" }, "node_modules/json2csv": { diff --git a/package.json b/package.json index 04db110b5e..f980554c27 100644 --- a/package.json +++ b/package.json @@ -2818,6 +2818,7 @@ "@vscode/jupyter-ipywidgets8": "^1.0.9", "@vscode/python-extension": "^1.0.4", "ansi-to-html": "^0.6.7", + "apache-arrow": "^21.2.0", "bootstrap": "^5.0.0", "bootstrap-less": "^3.3.8", "clsx": "^2.1.1", diff --git a/resources/appPreview/v1.js b/resources/appPreview/v1.js index 228c561c22..0c2bb31b47 100644 --- a/resources/appPreview/v1.js +++ b/resources/appPreview/v1.js @@ -1,12 +1,12 @@ -(()=>{"use strict";let e;var t={},n={};function r(e){var o=n[e];if(void 0!==o)return o.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,r),a.exports}r.rv=()=>"1.3.14",r.ruid="bundler=rspack@1.3.14";let o="static-",a="deepnote-static-files-api-token-response";RegExp("^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\.");let i=document.currentScript,l=i instanceof HTMLScriptElement&&i.src?new URL(i.src).origin:null;function s(e){l&&window.parent.postMessage(e,l)}function c(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;try{return JSON.stringify(e)??String(e)}catch{return"[Unserializable value]"}}function u(e){if(!e||e.type!==a||"string"!=typeof e.token||"string"!=typeof e.apiOrigin||"number"!=typeof e.expiresAtSeconds||!Number.isFinite(e.expiresAtSeconds))return null;try{let t=new URL(e.apiOrigin);if("https:"!==t.protocol&&"http:"!==t.protocol)return null;return{token:e.token,apiOrigin:t.origin,expiresAtMs:1e3*e.expiresAtSeconds}}catch{return null}}let d=new Set(["success","error","internal_error","stopped"]);async function f(e){await new Promise(t=>setTimeout(t,e))}let m=["pointerdown","pointerup","mousedown","mouseup"];function p(e){let t=e.target;return t instanceof SVGElement?t.ownerSVGElement??t:t instanceof HTMLElement?t:null}function g(e){e.preventDefault(),e.stopImmediatePropagation()}let h="[modern-screenshot]",w="undefined"!=typeof window,y=w&&"Worker"in window,b=w&&"atob"in window,v=w?window.navigator?.userAgent:"",E=v.includes("Chrome"),S=v.includes("AppleWebKit")&&!E,x=v.includes("Firefox"),A=e=>e&&"__CONTEXT__"in e,k=e=>"CSSFontFaceRule"===e.constructor.name,C=e=>"CSSImportRule"===e.constructor.name,N=e=>"CSSLayerBlockRule"===e.constructor.name,T=e=>1===e.nodeType,$=e=>"object"==typeof e.className,D=e=>"image"===e.tagName,L=e=>"use"===e.tagName,R=e=>T(e)&&void 0!==e.style&&!$(e),P=e=>8===e.nodeType,F=e=>3===e.nodeType,M=e=>"IMG"===e.tagName,I=e=>"VIDEO"===e.tagName,_=e=>"CANVAS"===e.tagName,B=e=>"TEXTAREA"===e.tagName,U=e=>"INPUT"===e.tagName,O=e=>"STYLE"===e.tagName,j=e=>"SCRIPT"===e.tagName,W=e=>"SELECT"===e.tagName,z=e=>"SLOT"===e.tagName,q=e=>"IFRAME"===e.tagName,V=(...e)=>console.warn(h,...e),H=e=>e.startsWith("data:");function X(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(w&&e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i)||!w)return e;let n=G().implementation.createHTMLDocument(),r=n.createElement("base"),o=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(o),t&&(r.href=t),o.href=e,o.href}function G(e){return(e&&T(e)?e?.ownerDocument:e)??window.document}let J="http://www.w3.org/2000/svg";function Y(e,t,n){let r=G(n).createElementNS(J,"svg");return r.setAttributeNS(null,"width",e.toString()),r.setAttributeNS(null,"height",t.toString()),r.setAttributeNS(null,"viewBox",`0 0 ${e} ${t}`),r}function K(e,t){let n=new XMLSerializer().serializeToString(e);return t&&(n=n.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu,"")),`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n)}`}async function Q(e,t="image/png",n=1){try{return await new Promise((r,o)=>{e.toBlob(e=>{e?r(e):o(Error("Blob is null"))},t,n)})}catch(r){if(b)return function(e){let[t,n]=e.split(","),r=t.match(/data:(.+);/)?.[1]??void 0,o=window.atob(n),a=o.length,i=new Uint8Array(a);for(let e=0;e{let o=new FileReader;o.onload=()=>n(o.result),o.onerror=()=>r(o.error),o.onabort=()=>r(Error(`Failed read blob to ${t}`)),"dataUrl"===t?o.readAsDataURL(e):"arrayBuffer"===t&&o.readAsArrayBuffer(e)})}let ee=e=>Z(e,"dataUrl"),et=e=>Z(e,"arrayBuffer");function en(e,t){let n=G(t).createElement("img");return n.decoding="sync",n.loading="eager",n.src=e,n}function er(e,t){return new Promise(n=>{let{timeout:r,ownerDocument:o,onError:a,onWarn:i}=t??{},l="string"==typeof e?en(e,G(o)):e,s=null,c=null;function u(){n(l),s&&clearTimeout(s),c?.()}if(r&&(s=setTimeout(u,r)),I(l)){let e=l.currentSrc||l.src;if(!e)return l.poster?er(l.poster,t).then(n):u();if(l.readyState>=2)return u();let r=t=>{i?.("Failed video load",e,t),a?.(t),u()};c=()=>{l.removeEventListener("loadeddata",u),l.removeEventListener("error",r)},l.addEventListener("loadeddata",u,{once:!0}),l.addEventListener("error",r,{once:!0})}else{let e=D(l)?l.href.baseVal:l.currentSrc||l.src;if(!e)return u();let t=async()=>{if(M(l)&&"decode"in l)try{await l.decode()}catch(t){i?.("Failed to decode image, trying to render anyway",l.dataset.originalSrc||e,t)}u()},n=t=>{i?.("Failed image load",l.dataset.originalSrc||e,t),u()};if(M(l)&&l.complete)return t();c=()=>{l.removeEventListener("load",t),l.removeEventListener("error",n)},l.addEventListener("load",t,{once:!0}),l.addEventListener("error",n,{once:!0})}})}async function eo(e,t){R(e)&&(M(e)||I(e)?await er(e,t):await Promise.all(["img","video"].flatMap(n=>Array.from(e.querySelectorAll(n)).map(e=>er(e,t)))))}let ea=function(){let e=0,t=()=>`0000${(1679616*Math.random()|0).toString(36)}`.slice(-4);return()=>(e+=1,`u${t()}${e}`)}();function ei(e){return e?.split(",").map(e=>e.trim().replace(/"|'/g,"").toLowerCase()).filter(Boolean)}let el=0;async function es(e,t){return A(e)?e:ec(e,{...t,autoDestruct:!0})}async function ec(e,t){let{scale:n=1,workerUrl:r,workerNumber:o=1}=t||{},a=!!t?.debug,i=t?.features??!0,l=e.ownerDocument??(w?window.document:void 0),s=e.ownerDocument?.defaultView??(w?window:void 0),c=new Map,u={width:0,height:0,quality:1,type:"image/png",scale:n,backgroundColor:null,style:null,filter:null,maximumCanvasSize:0,timeout:3e4,progress:null,debug:a,fetch:{requestInit:{cache:t?.fetch?.bypassingCache?"no-cache":"force-cache"},placeholderImage:"data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",bypassingCache:!1,...t?.fetch},fetchFn:null,font:{},drawImageInterval:100,workerUrl:null,workerNumber:o,onCloneEachNode:null,onCloneNode:null,onEmbedNode:null,onCreateForeignObjectSvg:null,includeStyleProperties:null,autoDestruct:!1,...t,__CONTEXT__:!0,log:function(e){let t=`${h}[#${el}]`;return el++,{time:n=>e&&console.time(`${t} ${n}`),timeEnd:n=>e&&console.timeEnd(`${t} ${n}`),warn:(...t)=>e&&V(...t)}}(a),node:e,ownerDocument:l,ownerWindow:s,dpi:1===n?null:96*n,svgStyleElement:eu(l),svgDefsElement:l?.createElementNS(J,"defs"),svgStyles:new Map,defaultComputedStyles:new Map,workers:[...Array.from({length:y&&r&&o?o:0})].map(()=>{try{let e=new Worker(r);return e.onmessage=async e=>{let{url:t,result:n}=e.data;n?c.get(t)?.resolve?.(n):c.get(t)?.reject?.(Error(`Error receiving message from worker: ${t}`))},e.onmessageerror=e=>{let{url:t}=e.data;c.get(t)?.reject?.(Error(`Error receiving message from worker: ${t}`))},e}catch(e){return u.log.warn("Failed to new Worker",e),null}}).filter(Boolean),fontFamilies:new Map,fontCssTexts:new Map,acceptOfImage:`${[function(e){let t=e?.createElement?.("canvas");return t&&(t.height=t.width=1),!!t&&"toDataURL"in t&&!!t.toDataURL("image/webp").includes("image/webp")}(l)&&"image/webp","image/svg+xml","image/*","*/*"].filter(Boolean).join(",")};q=0.8`,requests:c,drawImageCount:0,tasks:[],features:i,isEnable:e=>"restoreScrollPosition"===e?"boolean"!=typeof i&&(i[e]??!1):"boolean"==typeof i?i:i[e]??!0,shadowRoots:[]};u.log.time("wait until load"),await eo(e,{timeout:u.timeout,onWarn:u.log.warn}),u.log.timeEnd("wait until load");let{width:d,height:f}=function(e,t){let{width:n,height:r}=t;if(T(e)&&(!n||!r)){let t=e.getBoundingClientRect();n=n||t.width||Number(e.getAttribute("width"))||0,r=r||t.height||Number(e.getAttribute("height"))||0}return{width:n,height:r}}(e,u);return u.width=d,u.height=f,u}function eu(e){if(!e)return;let t=e.createElement("style"),n=t.ownerDocument.createTextNode(` +(()=>{"use strict";let e;var t={},n={};function r(e){var o=n[e];if(void 0!==o)return o.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,r),a.exports}r.rv=()=>"1.3.14",r.ruid="bundler=rspack@1.3.14";let o=e=>{let t=parseInt(e,10);if(!isNaN(t))return 1e3*t;let n=new Date(e).getTime();return isNaN(n)?null:Math.max(0,n-Date.now())},a=e=>{let t=e.headers.get("Retry-After");return t?o(t):null},i="static-",l="deepnote-static-files-api-token-response";RegExp("^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\.");let s=document.currentScript,c=s instanceof HTMLScriptElement&&s.src?new URL(s.src).origin:null;function u(e){c&&window.parent.postMessage(e,c)}function d(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;try{return JSON.stringify(e)??String(e)}catch{return"[Unserializable value]"}}function f(e){if(!e||e.type!==l||"string"!=typeof e.token||"string"!=typeof e.apiOrigin||"number"!=typeof e.expiresAtSeconds||!Number.isFinite(e.expiresAtSeconds))return null;try{let t=new URL(e.apiOrigin);if("https:"!==t.protocol&&"http:"!==t.protocol)return null;return{token:e.token,apiOrigin:t.origin,expiresAtMs:1e3*e.expiresAtSeconds,projectId:"string"==typeof e.projectId?e.projectId:null}}catch{return null}}let p=new Set(["success","error","internal_error","stopped"]);async function m(e){await new Promise(t=>setTimeout(t,e))}let g=["pointerdown","pointerup","mousedown","mouseup"];function h(e){let t=e.target;return t instanceof SVGElement?t.ownerSVGElement??t:t instanceof HTMLElement?t:null}function w(e){e.preventDefault(),e.stopImmediatePropagation()}let y="[modern-screenshot]",b="undefined"!=typeof window,v=b&&"Worker"in window,E=b&&"atob"in window,S=b?window.navigator?.userAgent:"",x=S.includes("Chrome"),A=S.includes("AppleWebKit")&&!x,k=S.includes("Firefox"),C=e=>e&&"__CONTEXT__"in e,N=e=>"CSSFontFaceRule"===e.constructor.name,T=e=>"CSSImportRule"===e.constructor.name,$=e=>"CSSLayerBlockRule"===e.constructor.name,D=e=>1===e.nodeType,L=e=>"object"==typeof e.className,R=e=>"image"===e.tagName,P=e=>"use"===e.tagName,I=e=>D(e)&&void 0!==e.style&&!L(e),F=e=>8===e.nodeType,M=e=>3===e.nodeType,_=e=>"IMG"===e.tagName,U=e=>"VIDEO"===e.tagName,B=e=>"CANVAS"===e.tagName,j=e=>"TEXTAREA"===e.tagName,O=e=>"INPUT"===e.tagName,z=e=>"STYLE"===e.tagName,W=e=>"SCRIPT"===e.tagName,q=e=>"SELECT"===e.tagName,V=e=>"SLOT"===e.tagName,H=e=>"IFRAME"===e.tagName,X=(...e)=>console.warn(y,...e),G=e=>e.startsWith("data:");function J(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(b&&e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i)||!b)return e;let n=Y().implementation.createHTMLDocument(),r=n.createElement("base"),o=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(o),t&&(r.href=t),o.href=e,o.href}function Y(e){return(e&&D(e)?e?.ownerDocument:e)??window.document}let K="http://www.w3.org/2000/svg";function Q(e,t,n){let r=Y(n).createElementNS(K,"svg");return r.setAttributeNS(null,"width",e.toString()),r.setAttributeNS(null,"height",t.toString()),r.setAttributeNS(null,"viewBox",`0 0 ${e} ${t}`),r}function Z(e,t){let n=new XMLSerializer().serializeToString(e);return t&&(n=n.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu,"")),`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n)}`}async function ee(e,t="image/png",n=1){try{return await new Promise((r,o)=>{e.toBlob(e=>{e?r(e):o(Error("Blob is null"))},t,n)})}catch(r){if(E)return function(e){let[t,n]=e.split(","),r=t.match(/data:(.+);/)?.[1]??void 0,o=window.atob(n),a=o.length,i=new Uint8Array(a);for(let e=0;e{let o=new FileReader;o.onload=()=>n(o.result),o.onerror=()=>r(o.error),o.onabort=()=>r(Error(`Failed read blob to ${t}`)),"dataUrl"===t?o.readAsDataURL(e):"arrayBuffer"===t&&o.readAsArrayBuffer(e)})}let en=e=>et(e,"dataUrl"),er=e=>et(e,"arrayBuffer");function eo(e,t){let n=Y(t).createElement("img");return n.decoding="sync",n.loading="eager",n.src=e,n}function ea(e,t){return new Promise(n=>{let{timeout:r,ownerDocument:o,onError:a,onWarn:i}=t??{},l="string"==typeof e?eo(e,Y(o)):e,s=null,c=null;function u(){n(l),s&&clearTimeout(s),c?.()}if(r&&(s=setTimeout(u,r)),U(l)){let e=l.currentSrc||l.src;if(!e)return l.poster?ea(l.poster,t).then(n):u();if(l.readyState>=2)return u();let r=t=>{i?.("Failed video load",e,t),a?.(t),u()};c=()=>{l.removeEventListener("loadeddata",u),l.removeEventListener("error",r)},l.addEventListener("loadeddata",u,{once:!0}),l.addEventListener("error",r,{once:!0})}else{let e=R(l)?l.href.baseVal:l.currentSrc||l.src;if(!e)return u();let t=async()=>{if(_(l)&&"decode"in l)try{await l.decode()}catch(t){i?.("Failed to decode image, trying to render anyway",l.dataset.originalSrc||e,t)}u()},n=t=>{i?.("Failed image load",l.dataset.originalSrc||e,t),u()};if(_(l)&&l.complete)return t();c=()=>{l.removeEventListener("load",t),l.removeEventListener("error",n)},l.addEventListener("load",t,{once:!0}),l.addEventListener("error",n,{once:!0})}})}async function ei(e,t){I(e)&&(_(e)||U(e)?await ea(e,t):await Promise.all(["img","video"].flatMap(n=>Array.from(e.querySelectorAll(n)).map(e=>ea(e,t)))))}let el=function(){let e=0,t=()=>`0000${(1679616*Math.random()|0).toString(36)}`.slice(-4);return()=>(e+=1,`u${t()}${e}`)}();function es(e){return e?.split(",").map(e=>e.trim().replace(/"|'/g,"").toLowerCase()).filter(Boolean)}let ec=0;async function eu(e,t){return C(e)?e:ed(e,{...t,autoDestruct:!0})}async function ed(e,t){let{scale:n=1,workerUrl:r,workerNumber:o=1}=t||{},a=!!t?.debug,i=t?.features??!0,l=e.ownerDocument??(b?window.document:void 0),s=e.ownerDocument?.defaultView??(b?window:void 0),c=new Map,u={width:0,height:0,quality:1,type:"image/png",scale:n,backgroundColor:null,style:null,filter:null,maximumCanvasSize:0,timeout:3e4,progress:null,debug:a,fetch:{requestInit:{cache:t?.fetch?.bypassingCache?"no-cache":"force-cache"},placeholderImage:"data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",bypassingCache:!1,...t?.fetch},fetchFn:null,font:{},drawImageInterval:100,workerUrl:null,workerNumber:o,onCloneEachNode:null,onCloneNode:null,onEmbedNode:null,onCreateForeignObjectSvg:null,includeStyleProperties:null,autoDestruct:!1,...t,__CONTEXT__:!0,log:function(e){let t=`${y}[#${ec}]`;return ec++,{time:n=>e&&console.time(`${t} ${n}`),timeEnd:n=>e&&console.timeEnd(`${t} ${n}`),warn:(...t)=>e&&X(...t)}}(a),node:e,ownerDocument:l,ownerWindow:s,dpi:1===n?null:96*n,svgStyleElement:ef(l),svgDefsElement:l?.createElementNS(K,"defs"),svgStyles:new Map,defaultComputedStyles:new Map,workers:[...Array.from({length:v&&r&&o?o:0})].map(()=>{try{let e=new Worker(r);return e.onmessage=async e=>{let{url:t,result:n}=e.data;n?c.get(t)?.resolve?.(n):c.get(t)?.reject?.(Error(`Error receiving message from worker: ${t}`))},e.onmessageerror=e=>{let{url:t}=e.data;c.get(t)?.reject?.(Error(`Error receiving message from worker: ${t}`))},e}catch(e){return u.log.warn("Failed to new Worker",e),null}}).filter(Boolean),fontFamilies:new Map,fontCssTexts:new Map,acceptOfImage:`${[function(e){let t=e?.createElement?.("canvas");return t&&(t.height=t.width=1),!!t&&"toDataURL"in t&&!!t.toDataURL("image/webp").includes("image/webp")}(l)&&"image/webp","image/svg+xml","image/*","*/*"].filter(Boolean).join(",")};q=0.8`,requests:c,drawImageCount:0,tasks:[],features:i,isEnable:e=>"restoreScrollPosition"===e?"boolean"!=typeof i&&(i[e]??!1):"boolean"==typeof i?i:i[e]??!0,shadowRoots:[]};u.log.time("wait until load"),await ei(e,{timeout:u.timeout,onWarn:u.log.warn}),u.log.timeEnd("wait until load");let{width:d,height:f}=function(e,t){let{width:n,height:r}=t;if(D(e)&&(!n||!r)){let t=e.getBoundingClientRect();n=n||t.width||Number(e.getAttribute("width"))||0,r=r||t.height||Number(e.getAttribute("height"))||0}return{width:n,height:r}}(e,u);return u.width=d,u.height=f,u}function ef(e){if(!e)return;let t=e.createElement("style"),n=t.ownerDocument.createTextNode(` .______background-clip--text { background-clip: text; -webkit-background-clip: text; } -`);return t.appendChild(n),t}async function ed(e,t){let{log:n,timeout:r,drawImageCount:o,drawImageInterval:a}=t;n.time("image to canvas");let i=await er(e,{timeout:r,onWarn:t.log.warn}),{canvas:l,context2d:s}=function(e,t){let{width:n,height:r,scale:o,backgroundColor:a,maximumCanvasSize:i}=t,l=e.createElement("canvas");l.width=Math.floor(n*o),l.height=Math.floor(r*o),l.style.width=`${n}px`,l.style.height=`${r}px`,i&&(l.width>i||l.height>i)&&(l.width>i&&l.height>i?l.width>l.height?(l.height*=i/l.width,l.width=i):(l.width*=i/l.height,l.height=i):l.width>i?(l.height*=i/l.width,l.width=i):(l.width*=i/l.height,l.height=i));let s=l.getContext("2d");return s&&a&&(s.fillStyle=a,s.fillRect(0,0,l.width,l.height)),{canvas:l,context2d:s}}(e.ownerDocument,t),c=()=>{try{s?.drawImage(i,0,0,l.width,l.height)}catch(e){t.log.warn("Failed to drawImage",e)}};if(c(),t.isEnable("fixSvgXmlDecode"))for(let e=0;e{setTimeout(()=>{s?.clearRect(0,0,l.width,l.height),c(),t()},e+a)});return t.drawImageCount=0,n.timeEnd("image to canvas"),l}function ef(e,t){if(e.ownerDocument)try{let t=e.toDataURL();if("data:,"!==t)return en(t,e.ownerDocument)}catch(e){t.log.warn("Failed to clone canvas",e)}let n=e.cloneNode(!1),r=e.getContext("2d"),o=n.getContext("2d");try{r&&o&&o.putImageData(r.getImageData(0,0,e.width,e.height),0,0)}catch(e){t.log.warn("Failed to clone canvas",e)}return n}async function em(e,t){if(e.ownerDocument&&!e.currentSrc&&e.poster)return en(e.poster,e.ownerDocument);let n=e.cloneNode(!1);n.crossOrigin="anonymous",e.currentSrc&&e.currentSrc!==e.src&&(n.src=e.currentSrc);let r=n.ownerDocument;if(r){let o=!0;if(await er(n,{onError:()=>o=!1,onWarn:t.log.warn}),!o)return e.poster?en(e.poster,e.ownerDocument):n;n.currentTime=e.currentTime,await new Promise(e=>{n.addEventListener("seeked",e,{once:!0})});let a=r.createElement("canvas");a.width=e.offsetWidth,a.height=e.offsetHeight;try{let e=a.getContext("2d");e&&e.drawImage(n,0,0,a.width,a.height)}catch(r){if(t.log.warn("Failed to clone video",r),e.poster)return en(e.poster,e.ownerDocument);return n}return ef(a,t)}return n}let ep=["width","height","-webkit-text-fill-color"],eg=["stroke","fill"];function eh(e,t,n){let r,o,{defaultComputedStyles:a}=n,i=e.nodeName.toLowerCase(),l=$(e)&&"svg"!==i,s=l?eg.map(t=>[t,e.getAttribute(t)]).filter(([,e])=>null!==e):[],c=[l&&"svg",i,s.map((e,t)=>`${e}=${t}`).join(","),t].filter(Boolean).join(":");if(a.has(c))return a.get(c);let u=function(e){let t=e.sandbox;if(!t){let{ownerDocument:n}=e;try{n&&((t=n.createElement("iframe")).id=`__SANDBOX__${ea()}`,t.width="0",t.height="0",t.style.visibility="hidden",t.style.position="fixed",n.body.appendChild(t),t.srcdoc='',e.sandbox=t)}catch(t){e.log.warn("Failed to getSandBox",t)}}return t}(n),d=u?.contentWindow;if(!d)return new Map;let f=d?.document;l?(o=(r=f.createElementNS(J,"svg")).ownerDocument.createElementNS(r.namespaceURI,i),s.forEach(([e,t])=>{o.setAttributeNS(null,e,t)}),r.appendChild(o)):r=o=f.createElement(i),o.textContent=" ",f.body.appendChild(r);let m=d.getComputedStyle(o,t),p=new Map;for(let e=m.length,t=0;tr.set(t,e));function i(n){let i=e.getPropertyValue(n),l=e.getPropertyPriority(n),s=n.lastIndexOf("-"),c=s>-1?n.substring(0,s):void 0;if(c){let e=a.get(c);e||(e=new Map,a.set(c,e)),e.set(n,[i,l])}(t.get(n)!==i||l)&&(c?o.push(c):r.set(n,[i,l]))}return r}let ey=["::before","::after"],eb=["::-webkit-scrollbar","::-webkit-scrollbar-button","::-webkit-scrollbar-thumb","::-webkit-scrollbar-track","::-webkit-scrollbar-track-piece","::-webkit-scrollbar-corner","::-webkit-resizer"],ev=new Set(["symbol"]);async function eE(e,t,n,r,o){if(T(n)&&(O(n)||j(n))||r.filter&&!r.filter(n))return;ev.has(t.nodeName)||ev.has(n.nodeName)?r.currentParentNodeStyle=void 0:r.currentParentNodeStyle=r.currentNodeStyle;let a=await eA(n,r,!1,o);r.isEnable("restoreScrollPosition")&&function(e,t){if(!R(e)||!R(t))return;let{scrollTop:n,scrollLeft:r}=e;if(!n&&!r)return;let{transform:o}=t.style,a=new DOMMatrix(o),{a:i,b:l,c:s,d:c}=a;a.a=1,a.b=0,a.c=0,a.d=1,a.translateSelf(-r,-n),a.a=i,a.b=l,a.c=s,a.d=c,t.style.transform=a.toString()}(e,a),t.appendChild(a)}async function eS(e,t,n,r){let o=e.firstChild;T(e)&&e.shadowRoot&&(o=e.shadowRoot?.firstChild,n.shadowRoots.push(e.shadowRoot));for(let a=o;a;a=a.nextSibling)if(!P(a))if(T(a)&&z(a)&&"function"==typeof a.assignedNodes){let o=a.assignedNodes();for(let a=0;a{c.delete(t)});let u=ew(s,c,a);u.delete("transition-property"),u.delete("all"),u.delete("d"),u.delete("content"),n&&(u.delete("position"),u.delete("margin-top"),u.delete("margin-right"),u.delete("margin-bottom"),u.delete("margin-left"),u.delete("margin-block-start"),u.delete("margin-block-end"),u.delete("margin-inline-start"),u.delete("margin-inline-end"),u.set("box-sizing",["border-box",""])),u.get("background-clip")?.[0]==="text"&&t.classList.add("______background-clip--text"),E&&(u.has("font-kerning")||u.set("font-kerning",["normal",""]),(u.get("overflow-x")?.[0]==="hidden"||u.get("overflow-y")?.[0]==="hidden")&&u.get("text-overflow")?.[0]==="ellipsis"&&e.scrollWidth===e.clientWidth&&u.set("text-overflow",["clip",""]));for(let e=l.length,t=0;t{l.setProperty(n,e,t)}),u}(e,r,n,t);n&&function(e,t){let{backgroundColor:n,width:r,height:o,style:a}=t,i=e.style;if(n&&i.setProperty("background-color",n,"important"),r&&i.setProperty("width",`${r}px`,"important"),o&&i.setProperty("height",`${o}px`,"important"),a)for(let e in a)i[e]=a[e]}(r,t);let a=!1;if(t.isEnable("copyScrollbar")){let t=[o.get("overflow-x")?.[0],o.get("overflow-y")?.[0]];a=t.includes("scroll")||(t.includes("auto")||t.includes("overlay"))&&(e.scrollHeight>e.clientHeight||e.scrollWidth>e.clientWidth)}let u=o.get("text-transform")?.[0],d=ei(o.get("font-family")?.[0]),f=d?e=>{"uppercase"===u?e=e.toUpperCase():"lowercase"===u?e=e.toLowerCase():"capitalize"===u&&(e=e[0].toUpperCase()+e.substring(1)),d.forEach(t=>{let n=i.get(t);n||i.set(t,n=new Set),e.split("").forEach(e=>n.add(e))})}:void 0;var s=a;let{ownerWindow:m,svgStyleElement:p,svgStyles:g,currentNodeStyle:h}=t;function c(n){let o=m.getComputedStyle(e,n),a=o.getPropertyValue("content");if(!a||"none"===a)return;f?.(a),a=a.replace(/(')|(")|(counter\(.+\))/g,"");let i=[ea()],l=eh(e,n,t);h?.forEach((e,t)=>{l.delete(t)});let s=ew(o,l,t.includeStyleProperties);s.delete("content"),s.delete("-webkit-locale"),s.get("background-clip")?.[0]==="text"&&r.classList.add("______background-clip--text");let c=[`content: '${a}';`];if(s.forEach(([e,t],n)=>{c.push(`${n}: ${e}${t?" !important":""};`)}),1===c.length)return;try{r.className=[r.className,...i].join(" ")}catch(e){t.log.warn("Failed to copyPseudoClass",e);return}let u=c.join("\n "),d=g.get(u);d||(d=[],g.set(u,d)),d.push(`.${i[0]}${n}`)}return p&&m&&(ey.forEach(c),s&&eb.forEach(c)),(B(e)||U(e)||W(e))&&r.setAttribute("value",e.value),I(e)||await eS(e,r,t,f),await l?.(r),r}let u=e.cloneNode(!1);return await eS(e,u,t),await l?.(u),u}function ek(e,t){let{url:n,requestType:r="text",responseType:o="text",imageDom:a}=t,i=n,{timeout:l,acceptOfImage:s,requests:c,fetchFn:u,fetch:{requestInit:d,bypassingCache:f,placeholderImage:m},font:p,workers:g,fontFamilies:h}=e;"image"===r&&(S||x)&&e.drawImageCount++;let w=c.get(n);if(!w){f&&f instanceof RegExp&&f.test(i)&&(i+=(/\?/.test(i)?"&":"?")+new Date().getTime());let t=r.startsWith("font")&&p&&p.minify,y=new Set;t&&r.split(";")[1].split(",").forEach(e=>{h.has(e)&&h.get(e).forEach(e=>y.add(e))});let b=t&&y.size,v={url:i,timeout:l,responseType:b?"arrayBuffer":o,headers:"image"===r?{accept:s}:void 0,...d};(w={type:r,resolve:void 0,reject:void 0,response:null}).response=(async()=>{if(u&&"image"===r){let e=await u(n);if(e)return e}if(!S&&n.startsWith("http")&&g.length)return new Promise((e,t)=>{g[c.size&g.length-1].postMessage({rawUrl:n,...v}),w.resolve=e,w.reject=t});let{url:e,timeout:t,responseType:o,...a}=v,i=new AbortController,l=t?setTimeout(()=>i.abort(),t):void 0;return fetch(e,{signal:i.signal,...a}).then(e=>{if(!e.ok)throw Error("Failed fetch, not 2xx response",{cause:e});switch(o){case"arrayBuffer":return e.arrayBuffer();case"dataUrl":return e.blob().then(ee);default:return e.text()}}).finally(()=>clearTimeout(l))})().catch(t=>{if(c.delete(n),"image"===r&&m)return e.log.warn("Failed to fetch image base64, trying to use placeholder image",i),"string"==typeof m?m:m(a);throw t}),c.set(n,w)}return w.response}async function eC(e,t,n,r){if(!eN(e))return e;for(let[o,a]of function(e,t){let n=[];return e.replace(eT,(e,r,o)=>(n.push([o,X(o,t)]),e)),n.filter(([e])=>!H(e))}(e,t))try{let t=await ek(n,{url:a,requestType:r?"image":"text",responseType:"dataUrl"});e=e.replace(function(e){let t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}(o),`$1${t}$3`)}catch(e){n.log.warn("Failed to fetch css data url",o,e)}return e}function eN(e){return/url\((['"]?)([^'"]+?)\1\)/.test(e)}let eT=/url\((['"]?)([^'"]+?)\1\)/g,e$=["background-image","border-image-source","-webkit-border-image","-webkit-mask-image","list-style-image"];async function eD(e,t){let{ownerDocument:n,svgStyleElement:r,fontFamilies:o,fontCssTexts:a,tasks:i,font:l}=t;if(n&&r&&o.size)if(l&&l.cssText){let e=eM(l.cssText,t);r.appendChild(n.createTextNode(`${e} -`))}else{let e=Array.from(n.styleSheets).filter(e=>{try{return"cssRules"in e&&!!e.cssRules.length}catch(n){return t.log.warn(`Error while reading CSS rules from ${e.href}`,n),!1}}),l=n.implementation.createHTMLDocument(""),s=l.createElement("style");l.head.appendChild(s);let c=s.sheet;await Promise.all(e.flatMap(e=>Array.from(e.cssRules).map(async e=>{if(C(e)){let n=e.href,r="";try{r=await ek(t,{url:n,requestType:"text",responseType:"text"})}catch(e){t.log.warn(`Error fetch remote css import from ${n}`,e)}for(let e of function(e){if(null==e)return[];let t=[],n=e.replace(eL,"");for(;;){let e=eR.exec(n);if(!e)break;t.push(e[0])}n=n.replace(eR,"");let r=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,o=RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let e=r.exec(n);if(e)o.lastIndex=r.lastIndex;else if(e=o.exec(n))r.lastIndex=o.lastIndex;else break;t.push(e[0])}return t}(r.replace(eT,(e,t,r)=>e.replace(r,X(r,n)))))try{c.insertRule(e,c.cssRules.length)}catch(n){t.log.warn("Error inserting rule from remote css import",{rule:e,error:n})}}}))),c.cssRules.length&&e.push(c);let u=[];e.forEach(e=>{!function e(t,n=[]){for(let r of Array.from(t))N(r)?n.push(...e(r.cssRules)):"cssRules"in r?e(r.cssRules,n):n.push(r);return n}(e.cssRules,u)}),u.filter(e=>k(e)&&eN(e.style.getPropertyValue("src"))&&ei(e.style.getPropertyValue("font-family"))?.some(e=>o.has(e))).forEach(e=>{let o=a.get(e.cssText);o?r.appendChild(n.createTextNode(`${o} -`)):i.push(eC(e.cssText,e.parentStyleSheet?e.parentStyleSheet.href:null,t).then(o=>{o=eM(o,t),a.set(e.cssText,o),r.appendChild(n.createTextNode(`${o} -`))}))})}}let eL=/(\/\*[\s\S]*?\*\/)/g,eR=/((@.*?keyframes [\s\S]*?){([\s\S]*?}\s*?)})/gi,eP=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,eF=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function eM(e,t){let{font:n}=t,r=n?n?.preferredFormat:void 0;return r?e.replace(eF,e=>{for(;;){let[t,,n]=eP.exec(e)||[];if(!n)return"";if(n===r)return`src: ${t};`}}):e}let eI=/\bx?link:?href\s*=\s*["'](?!data:)[^"']+["']/i;async function e_(e,t){var n;let r=await es(e,t);if(T(r.node)&&$(r.node)&&(n=r.node,!eI.test(n.innerHTML)))return r.node;let{ownerDocument:o,log:a,tasks:i,svgStyleElement:l,svgDefsElement:s,svgStyles:c,font:u,progress:d,autoDestruct:f,onCloneNode:m,onEmbedNode:p,onCreateForeignObjectSvg:g}=r;a.time("clone node");let h=await eA(r.node,r,!0);if(l&&o){let e="";c.forEach((t,n)=>{e+=`${t.join(",\n")} { +`);return t.appendChild(n),t}async function ep(e,t){let{log:n,timeout:r,drawImageCount:o,drawImageInterval:a}=t;n.time("image to canvas");let i=await ea(e,{timeout:r,onWarn:t.log.warn}),{canvas:l,context2d:s}=function(e,t){let{width:n,height:r,scale:o,backgroundColor:a,maximumCanvasSize:i}=t,l=e.createElement("canvas");l.width=Math.floor(n*o),l.height=Math.floor(r*o),l.style.width=`${n}px`,l.style.height=`${r}px`,i&&(l.width>i||l.height>i)&&(l.width>i&&l.height>i?l.width>l.height?(l.height*=i/l.width,l.width=i):(l.width*=i/l.height,l.height=i):l.width>i?(l.height*=i/l.width,l.width=i):(l.width*=i/l.height,l.height=i));let s=l.getContext("2d");return s&&a&&(s.fillStyle=a,s.fillRect(0,0,l.width,l.height)),{canvas:l,context2d:s}}(e.ownerDocument,t),c=()=>{try{s?.drawImage(i,0,0,l.width,l.height)}catch(e){t.log.warn("Failed to drawImage",e)}};if(c(),t.isEnable("fixSvgXmlDecode"))for(let e=0;e{setTimeout(()=>{s?.clearRect(0,0,l.width,l.height),c(),t()},e+a)});return t.drawImageCount=0,n.timeEnd("image to canvas"),l}function em(e,t){if(e.ownerDocument)try{let t=e.toDataURL();if("data:,"!==t)return eo(t,e.ownerDocument)}catch(e){t.log.warn("Failed to clone canvas",e)}let n=e.cloneNode(!1),r=e.getContext("2d"),o=n.getContext("2d");try{r&&o&&o.putImageData(r.getImageData(0,0,e.width,e.height),0,0)}catch(e){t.log.warn("Failed to clone canvas",e)}return n}async function eg(e,t){if(e.ownerDocument&&!e.currentSrc&&e.poster)return eo(e.poster,e.ownerDocument);let n=e.cloneNode(!1);n.crossOrigin="anonymous",e.currentSrc&&e.currentSrc!==e.src&&(n.src=e.currentSrc);let r=n.ownerDocument;if(r){let o=!0;if(await ea(n,{onError:()=>o=!1,onWarn:t.log.warn}),!o)return e.poster?eo(e.poster,e.ownerDocument):n;n.currentTime=e.currentTime,await new Promise(e=>{n.addEventListener("seeked",e,{once:!0})});let a=r.createElement("canvas");a.width=e.offsetWidth,a.height=e.offsetHeight;try{let e=a.getContext("2d");e&&e.drawImage(n,0,0,a.width,a.height)}catch(r){if(t.log.warn("Failed to clone video",r),e.poster)return eo(e.poster,e.ownerDocument);return n}return em(a,t)}return n}let eh=["width","height","-webkit-text-fill-color"],ew=["stroke","fill"];function ey(e,t,n){let r,o,{defaultComputedStyles:a}=n,i=e.nodeName.toLowerCase(),l=L(e)&&"svg"!==i,s=l?ew.map(t=>[t,e.getAttribute(t)]).filter(([,e])=>null!==e):[],c=[l&&"svg",i,s.map((e,t)=>`${e}=${t}`).join(","),t].filter(Boolean).join(":");if(a.has(c))return a.get(c);let u=function(e){let t=e.sandbox;if(!t){let{ownerDocument:n}=e;try{n&&((t=n.createElement("iframe")).id=`__SANDBOX__${el()}`,t.width="0",t.height="0",t.style.visibility="hidden",t.style.position="fixed",n.body.appendChild(t),t.srcdoc='',e.sandbox=t)}catch(t){e.log.warn("Failed to getSandBox",t)}}return t}(n),d=u?.contentWindow;if(!d)return new Map;let f=d?.document;l?(o=(r=f.createElementNS(K,"svg")).ownerDocument.createElementNS(r.namespaceURI,i),s.forEach(([e,t])=>{o.setAttributeNS(null,e,t)}),r.appendChild(o)):r=o=f.createElement(i),o.textContent=" ",f.body.appendChild(r);let p=d.getComputedStyle(o,t),m=new Map;for(let e=p.length,t=0;tr.set(t,e));function i(n){let i=e.getPropertyValue(n),l=e.getPropertyPriority(n),s=n.lastIndexOf("-"),c=s>-1?n.substring(0,s):void 0;if(c){let e=a.get(c);e||(e=new Map,a.set(c,e)),e.set(n,[i,l])}(t.get(n)!==i||l)&&(c?o.push(c):r.set(n,[i,l]))}return r}let ev=["::before","::after"],eE=["::-webkit-scrollbar","::-webkit-scrollbar-button","::-webkit-scrollbar-thumb","::-webkit-scrollbar-track","::-webkit-scrollbar-track-piece","::-webkit-scrollbar-corner","::-webkit-resizer"],eS=new Set(["symbol"]);async function ex(e,t,n,r,o){if(D(n)&&(z(n)||W(n))||r.filter&&!r.filter(n))return;eS.has(t.nodeName)||eS.has(n.nodeName)?r.currentParentNodeStyle=void 0:r.currentParentNodeStyle=r.currentNodeStyle;let a=await eC(n,r,!1,o);r.isEnable("restoreScrollPosition")&&function(e,t){if(!I(e)||!I(t))return;let{scrollTop:n,scrollLeft:r}=e;if(!n&&!r)return;let{transform:o}=t.style,a=new DOMMatrix(o),{a:i,b:l,c:s,d:c}=a;a.a=1,a.b=0,a.c=0,a.d=1,a.translateSelf(-r,-n),a.a=i,a.b=l,a.c=s,a.d=c,t.style.transform=a.toString()}(e,a),t.appendChild(a)}async function eA(e,t,n,r){let o=e.firstChild;D(e)&&e.shadowRoot&&(o=e.shadowRoot?.firstChild,n.shadowRoots.push(e.shadowRoot));for(let a=o;a;a=a.nextSibling)if(!F(a))if(D(a)&&V(a)&&"function"==typeof a.assignedNodes){let o=a.assignedNodes();for(let a=0;a{c.delete(t)});let u=eb(s,c,a);u.delete("transition-property"),u.delete("all"),u.delete("d"),u.delete("content"),n&&(u.delete("position"),u.delete("margin-top"),u.delete("margin-right"),u.delete("margin-bottom"),u.delete("margin-left"),u.delete("margin-block-start"),u.delete("margin-block-end"),u.delete("margin-inline-start"),u.delete("margin-inline-end"),u.set("box-sizing",["border-box",""])),u.get("background-clip")?.[0]==="text"&&t.classList.add("______background-clip--text"),x&&(u.has("font-kerning")||u.set("font-kerning",["normal",""]),(u.get("overflow-x")?.[0]==="hidden"||u.get("overflow-y")?.[0]==="hidden")&&u.get("text-overflow")?.[0]==="ellipsis"&&e.scrollWidth===e.clientWidth&&u.set("text-overflow",["clip",""]));for(let e=l.length,t=0;t{l.setProperty(n,e,t)}),u}(e,r,n,t);n&&function(e,t){let{backgroundColor:n,width:r,height:o,style:a}=t,i=e.style;if(n&&i.setProperty("background-color",n,"important"),r&&i.setProperty("width",`${r}px`,"important"),o&&i.setProperty("height",`${o}px`,"important"),a)for(let e in a)i[e]=a[e]}(r,t);let a=!1;if(t.isEnable("copyScrollbar")){let t=[o.get("overflow-x")?.[0],o.get("overflow-y")?.[0]];a=t.includes("scroll")||(t.includes("auto")||t.includes("overlay"))&&(e.scrollHeight>e.clientHeight||e.scrollWidth>e.clientWidth)}let u=o.get("text-transform")?.[0],d=es(o.get("font-family")?.[0]),f=d?e=>{"uppercase"===u?e=e.toUpperCase():"lowercase"===u?e=e.toLowerCase():"capitalize"===u&&(e=e[0].toUpperCase()+e.substring(1)),d.forEach(t=>{let n=i.get(t);n||i.set(t,n=new Set),e.split("").forEach(e=>n.add(e))})}:void 0;var s=a;let{ownerWindow:p,svgStyleElement:m,svgStyles:g,currentNodeStyle:h}=t;function c(n){let o=p.getComputedStyle(e,n),a=o.getPropertyValue("content");if(!a||"none"===a)return;f?.(a),a=a.replace(/(')|(")|(counter\(.+\))/g,"");let i=[el()],l=ey(e,n,t);h?.forEach((e,t)=>{l.delete(t)});let s=eb(o,l,t.includeStyleProperties);s.delete("content"),s.delete("-webkit-locale"),s.get("background-clip")?.[0]==="text"&&r.classList.add("______background-clip--text");let c=[`content: '${a}';`];if(s.forEach(([e,t],n)=>{c.push(`${n}: ${e}${t?" !important":""};`)}),1===c.length)return;try{r.className=[r.className,...i].join(" ")}catch(e){t.log.warn("Failed to copyPseudoClass",e);return}let u=c.join("\n "),d=g.get(u);d||(d=[],g.set(u,d)),d.push(`.${i[0]}${n}`)}return m&&p&&(ev.forEach(c),s&&eE.forEach(c)),(j(e)||O(e)||q(e))&&r.setAttribute("value",e.value),U(e)||await eA(e,r,t,f),await l?.(r),r}let u=e.cloneNode(!1);return await eA(e,u,t),await l?.(u),u}function eN(e,t){let{url:n,requestType:r="text",responseType:o="text",imageDom:a}=t,i=n,{timeout:l,acceptOfImage:s,requests:c,fetchFn:u,fetch:{requestInit:d,bypassingCache:f,placeholderImage:p},font:m,workers:g,fontFamilies:h}=e;"image"===r&&(A||k)&&e.drawImageCount++;let w=c.get(n);if(!w){f&&f instanceof RegExp&&f.test(i)&&(i+=(/\?/.test(i)?"&":"?")+new Date().getTime());let t=r.startsWith("font")&&m&&m.minify,y=new Set;t&&r.split(";")[1].split(",").forEach(e=>{h.has(e)&&h.get(e).forEach(e=>y.add(e))});let b=t&&y.size,v={url:i,timeout:l,responseType:b?"arrayBuffer":o,headers:"image"===r?{accept:s}:void 0,...d};(w={type:r,resolve:void 0,reject:void 0,response:null}).response=(async()=>{if(u&&"image"===r){let e=await u(n);if(e)return e}if(!A&&n.startsWith("http")&&g.length)return new Promise((e,t)=>{g[c.size&g.length-1].postMessage({rawUrl:n,...v}),w.resolve=e,w.reject=t});let{url:e,timeout:t,responseType:o,...a}=v,i=new AbortController,l=t?setTimeout(()=>i.abort(),t):void 0;return fetch(e,{signal:i.signal,...a}).then(e=>{if(!e.ok)throw Error("Failed fetch, not 2xx response",{cause:e});switch(o){case"arrayBuffer":return e.arrayBuffer();case"dataUrl":return e.blob().then(en);default:return e.text()}}).finally(()=>clearTimeout(l))})().catch(t=>{if(c.delete(n),"image"===r&&p)return e.log.warn("Failed to fetch image base64, trying to use placeholder image",i),"string"==typeof p?p:p(a);throw t}),c.set(n,w)}return w.response}async function eT(e,t,n,r){if(!e$(e))return e;for(let[o,a]of function(e,t){let n=[];return e.replace(eD,(e,r,o)=>(n.push([o,J(o,t)]),e)),n.filter(([e])=>!G(e))}(e,t))try{let t=await eN(n,{url:a,requestType:r?"image":"text",responseType:"dataUrl"});e=e.replace(function(e){let t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}(o),`$1${t}$3`)}catch(e){n.log.warn("Failed to fetch css data url",o,e)}return e}function e$(e){return/url\((['"]?)([^'"]+?)\1\)/.test(e)}let eD=/url\((['"]?)([^'"]+?)\1\)/g,eL=["background-image","border-image-source","-webkit-border-image","-webkit-mask-image","list-style-image"];async function eR(e,t){let{ownerDocument:n,svgStyleElement:r,fontFamilies:o,fontCssTexts:a,tasks:i,font:l}=t;if(n&&r&&o.size)if(l&&l.cssText){let e=e_(l.cssText,t);r.appendChild(n.createTextNode(`${e} +`))}else{let e=Array.from(n.styleSheets).filter(e=>{try{return"cssRules"in e&&!!e.cssRules.length}catch(n){return t.log.warn(`Error while reading CSS rules from ${e.href}`,n),!1}}),l=n.implementation.createHTMLDocument(""),s=l.createElement("style");l.head.appendChild(s);let c=s.sheet;await Promise.all(e.flatMap(e=>Array.from(e.cssRules).map(async e=>{if(T(e)){let n=e.href,r="";try{r=await eN(t,{url:n,requestType:"text",responseType:"text"})}catch(e){t.log.warn(`Error fetch remote css import from ${n}`,e)}for(let e of function(e){if(null==e)return[];let t=[],n=e.replace(eP,"");for(;;){let e=eI.exec(n);if(!e)break;t.push(e[0])}n=n.replace(eI,"");let r=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,o=RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let e=r.exec(n);if(e)o.lastIndex=r.lastIndex;else if(e=o.exec(n))r.lastIndex=o.lastIndex;else break;t.push(e[0])}return t}(r.replace(eD,(e,t,r)=>e.replace(r,J(r,n)))))try{c.insertRule(e,c.cssRules.length)}catch(n){t.log.warn("Error inserting rule from remote css import",{rule:e,error:n})}}}))),c.cssRules.length&&e.push(c);let u=[];e.forEach(e=>{!function e(t,n=[]){for(let r of Array.from(t))$(r)?n.push(...e(r.cssRules)):"cssRules"in r?e(r.cssRules,n):n.push(r);return n}(e.cssRules,u)}),u.filter(e=>N(e)&&e$(e.style.getPropertyValue("src"))&&es(e.style.getPropertyValue("font-family"))?.some(e=>o.has(e))).forEach(e=>{let o=a.get(e.cssText);o?r.appendChild(n.createTextNode(`${o} +`)):i.push(eT(e.cssText,e.parentStyleSheet?e.parentStyleSheet.href:null,t).then(o=>{o=e_(o,t),a.set(e.cssText,o),r.appendChild(n.createTextNode(`${o} +`))}))})}}let eP=/(\/\*[\s\S]*?\*\/)/g,eI=/((@.*?keyframes [\s\S]*?){([\s\S]*?}\s*?)})/gi,eF=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,eM=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function e_(e,t){let{font:n}=t,r=n?n?.preferredFormat:void 0;return r?e.replace(eM,e=>{for(;;){let[t,,n]=eF.exec(e)||[];if(!n)return"";if(n===r)return`src: ${t};`}}):e}let eU=/\bx?link:?href\s*=\s*["'](?!data:)[^"']+["']/i;async function eB(e,t){var n;let r=await eu(e,t);if(D(r.node)&&L(r.node)&&(n=r.node,!eU.test(n.innerHTML)))return r.node;let{ownerDocument:o,log:a,tasks:i,svgStyleElement:l,svgDefsElement:s,svgStyles:c,font:u,progress:d,autoDestruct:f,onCloneNode:p,onEmbedNode:m,onCreateForeignObjectSvg:g}=r;a.time("clone node");let h=await eC(r.node,r,!0);if(l&&o){let e="";c.forEach((t,n)=>{e+=`${t.join(",\n")} { ${n} } -`}),l.appendChild(o.createTextNode(e))}a.timeEnd("clone node"),await m?.(h),!1!==u&&T(h)&&(a.time("embed web font"),await eD(h,r),a.timeEnd("embed web font")),a.time("embed node"),function e(t,n){var r;let{tasks:o}=n;T(t)&&((M(t)||D(t))&&o.push(...function(e,t){if(M(e)){let n=e.currentSrc||e.src;if(!H(n))return[ek(t,{url:n,imageDom:e,requestType:"image",responseType:"dataUrl"}).then(t=>{t&&(e.srcset="",e.dataset.originalSrc=n,e.src=t||"")})];(S||x)&&t.drawImageCount++}else if($(e)&&!H(e.href.baseVal)){let n=e.href.baseVal;return[ek(t,{url:n,imageDom:e,requestType:"image",responseType:"dataUrl"}).then(t=>{t&&(e.dataset.originalSrc=n,e.href.baseVal=t||"")})]}return[]}(t,n)),L(t)&&o.push(...function(e,t){let{ownerDocument:n,svgDefsElement:r}=t,o=e.getAttribute("href")??e.getAttribute("xlink:href");if(!o)return[];let[a,i]=o.split("#");if(i){let o=`#${i}`,l=t.shadowRoots.reduce((e,t)=>e??t.querySelector(`svg ${o}`),n?.querySelector(`svg ${o}`));if(a&&e.setAttribute("href",o),r?.querySelector(o))return[];if(l)r?.appendChild(l.cloneNode(!0));else if(a)return[ek(t,{url:a,responseType:"text"}).then(e=>{r?.insertAdjacentHTML("beforeend",e)})]}return[]}(t,n))),R(t)&&o.push(...(r=t.style,e$.map(e=>{let t=r.getPropertyValue(e);return t&&"none"!==t?((S||x)&&n.drawImageCount++,eC(t,null,n,!0).then(n=>{n&&t!==n&&r.setProperty(e,n,r.getPropertyPriority(e))})):null}).filter(Boolean))),t.childNodes.forEach(t=>{e(t,n)})}(h,r);let w=i.length,y=0,b=async()=>{for(;;){let e=i.pop();if(!e)break;try{await e}catch(e){r.log.warn("Failed to run task",e)}d?.(++y,w)}};d?.(y,w),await Promise.all([...Array.from({length:4})].map(b)),a.timeEnd("embed node"),await p?.(h);let v=function(e,t){let{width:n,height:r}=t,o=Y(n,r,e.ownerDocument),a=o.ownerDocument.createElementNS(o.namespaceURI,"foreignObject");return a.setAttributeNS(null,"x","0%"),a.setAttributeNS(null,"y","0%"),a.setAttributeNS(null,"width","100%"),a.setAttributeNS(null,"height","100%"),a.append(e),o.appendChild(a),o}(h,r);return s&&v.insertBefore(s,v.children[0]),l&&v.insertBefore(l,v.children[0]),f&&function(e){if(e.ownerDocument=void 0,e.ownerWindow=void 0,e.svgStyleElement=void 0,e.svgDefsElement=void 0,e.svgStyles.clear(),e.defaultComputedStyles.clear(),e.sandbox){try{e.sandbox.remove()}catch(t){e.log.warn("Failed to destroyContext",t)}e.sandbox=void 0}e.workers=[],e.fontFamilies.clear(),e.fontCssTexts.clear(),e.requests.clear(),e.tasks=[],e.shadowRoots=[]}(r),await g?.(v),v}async function eB(e,t){let n=await es(e,t),r=await e_(n),o=K(r,n.isEnable("removeControlCharacter"));n.autoDestruct||(n.svgStyleElement=eu(n.ownerDocument),n.svgDefsElement=n.ownerDocument?.createElementNS(J,"defs"),n.svgStyles.clear());let a=en(o,r.ownerDocument);return await ed(a,n)}async function eU(t,n){let r=await es(t,n),{log:o,type:a,quality:i,dpi:l}=r,s=await eB(r);o.time("canvas to blob");let c=await Q(s,a,i);if(["image/png","image/jpeg"].includes(a)&&l){var u,d;let t=new Uint8Array(await et(c.slice(0,33)));return"image/png"===a?t=function(t,n,r=!1){let o=new Uint8Array(13);n*=39.3701,o[0]=112,o[1]=72,o[2]=89,o[3]=115,o[4]=n>>>24,o[5]=n>>>16,o[6]=n>>>8,o[7]=255&n,o[8]=o[4],o[9]=o[5],o[10]=o[6],o[11]=o[7],o[12]=1;let a=function(t){let n=-1;e||(e=function(){let e=new Int32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=1&n?0xedb88320^n>>>1:n>>>1;e[t]=n}return e}());for(let r=0;r>>8;return -1^n}(o),i=new Uint8Array(4);if(i[0]=a>>>24,i[1]=a>>>16,i[2]=a>>>8,i[3]=255&a,r){let e=function(e){let t=e.length-1;for(let n=t;n>=4;n--)if(9===e[n-4]&&112===e[n-3]&&72===e[n-2]&&89===e[n-1]&&115===e[n])return n-3;return 0}(t);return t.set(o,e),t.set(i,e+13),t}{let e=new Uint8Array(4);e[0]=0,e[1]=0,e[2]=0,e[3]=9;let n=new Uint8Array(54);return n.set(t,0),n.set(e,33),n.set(o,37),n.set(i,50),n}}(t,l):"image/jpeg"===a&&(u=t,d=l,u[13]=1,u[14]=d>>8,u[15]=255&d,u[16]=d>>8,u[17]=255&d,t=u),o.timeEnd("canvas to blob"),new Blob([t,c.slice(33)],{type:a})}return o.timeEnd("canvas to blob"),c}async function eO(e,t){let n=await es(e,t),{log:r,quality:o,type:a,dpi:i}=n,l=await eB(n);r.time("canvas to data url");let s=l.toDataURL(a,o);return["image/png","image/jpeg"].includes(a),r.timeEnd("canvas to data url"),s}async function ej(){"complete"!==document.readyState&&await new Promise(e=>window.addEventListener("load",e,{once:!0})),await document.fonts.ready;let e=window.innerWidth;return eU(document.body,{width:e,height:Math.round(e/1.6),scale:640/e,type:"image/png",backgroundColor:function(){for(let e of[document.body,document.documentElement]){let t=getComputedStyle(e).backgroundColor;if("transparent"!==t&&"rgba(0, 0, 0, 0)"!==t)return t}return"#ffffff"}()})}window.Deepnote={connect:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{ensureAuth:t,invalidateAuth:n}=function(e){let t=null,n=null;async function r(){try{let e=await fetch("/__deepnote/api-token",{method:"POST",headers:t?{authorization:`Bearer ${t.token}`}:{}});return 200===e.status?u({...await e.json(),type:a}):null}catch{return null}}async function o(){return new Promise((r,o)=>{let a=setTimeout(()=>{window.removeEventListener("message",i),o(Error("Could not reach Deepnote. Open the app from its Deepnote link and make sure API access is allowed for this app.")),e.onAuthExpired&&e.onAuthExpired()},8e3);function i(e){if(e.source!==window.parent||e.origin!==l)return;let o=u(e.data);o&&(clearTimeout(a),window.removeEventListener("message",i),n=null,t=o,r(o))}window.addEventListener("message",i),s({type:"deepnote-static-files-api-token-request"})})}async function i(){return n??=(async()=>{let e=window.parent===window.top&&window.location.ancestorOrigins?.[0]===l?null:await r();return e?(n=null,t=e,e):o()})()}return{ensureAuth:async function(){return t&&Date.now(){t=null}}}(e);async function r(e,r){let{token:o,apiOrigin:a}=await t(),i=await fetch(a+e,{...r,headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},signal:AbortSignal.timeout(3e4)});if(!i.ok){401===i.status&&n();let e=await i.json().catch(()=>null);throw Error(e?.message||`Request failed with status ${i.status}`)}return i.json()}async function o(e){let{notebook:t}=await r(`/v2/notebooks/${e}`);return t.inputs??[]}async function i(e){return r(`/v2/notebooks/${e}/app-data`)}async function c(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=await r("/v2/runs",{method:"POST",body:JSON.stringify({notebookId:e,inputs:t,detachedRunStorageMode:"readonly"})}),a=Date.now()+(n.timeoutMs??12e5),i=0;for(;;){let{run:e}=await r(`/v2/runs/${o.runId}`);if("success"===e.status&&"unavailable"===e.snapshotStatus)throw Error("The notebook finished, but Deepnote could not save its results. Check run history and try again.");let t="success"===e.status&&null==e.snapshotBlocks&&i<15&&Date.now()(function(e,t){for(let n of e.snapshotBlocks??[])for(let e of n.outputs){let n=e.data?.["application/json"];if(n&&(!t||n.schema===t))return n}return null})(e,t)};if(Date.now()>=a)throw Error(`Run ${o.runId} did not finish in time.`);t&&(i+=1),n.onProgress&&n.onProgress(e,t?"storing-result":"executing"),await f(2e3)}}return{notebook:e=>({inputs:()=>o(e),appData:()=>i(e),run:(t,n)=>c(e,t,n)})}}},window.parent!==window&&window.addEventListener("message",async e=>{if(e.source!==window.parent||e.data?.type!=="deepnote-static-files-app-preview-request")return;let t=e.ports[0];if(!t)return;let n=await ej().catch(e=>(console.warn("Deepnote could not capture the app preview.",e),null));t.postMessage(n),t.close()}),function(){if(window.parent===window)return;let e=new Set;function t(t,n,r){let o=`${t}|${n}|${r}`;e.has(o)||e.size>=10||(e.add(o),s({type:"deepnote-static-files-app-error",message:t.slice(0,500),line:n,source:r}))}window.addEventListener("error",e=>{if(e instanceof ErrorEvent)return void t(e.error?c(e.error):e.message,e.lineno||null,e.filename?e.filename.split(/[?#]/)[0]??null:null);let n=e.target;if(n instanceof HTMLScriptElement||n instanceof HTMLLinkElement){let e=n instanceof HTMLScriptElement?n.src:n.href;t(`Failed to load ${e.split(/[?#]/)[0]}`,null,null)}},!0),window.addEventListener("unhandledrejection",e=>{t(`Unhandled promise rejection: ${c(e.reason)}`,null,null)});let n=console.error;console.error=function(){for(var e=arguments.length,r=Array(e),o=0;os({type:"deepnote-static-files-app-ready",ready:e});r(!0),window.addEventListener("pagehide",()=>r(!1)),window.addEventListener("pageshow",e=>{e.persisted&&r(!0)})}(),function(){let e=null;function t(t){e&&(e.element.style.outline=e.outline,e.element.style.outlineOffset=e.outlineOffset,""===e.element.getAttribute("style")&&e.element.removeAttribute("style")),e=t?{element:t,outline:t.style.outline,outlineOffset:t.style.outlineOffset}:null,t&&(t.style.outline="2px solid #146efe",t.style.outlineOffset="-2px")}function n(e){t(p(e))}function r(e){g(e);let n=p(e);n&&(o(),t(null),s({type:"deepnote-static-files-app-pick",html:function(e){let t=e.cloneNode(!1);for(let n of e.childNodes){let e=n instanceof Element&&n.childElementCount>0,r=n.cloneNode(!e);e&&(r.textContent="..."),t.append(r)}return t.outerHTML}(n)}),t(n))}function o(){for(let e of(document.removeEventListener("mouseover",n,!0),document.removeEventListener("click",r,!0),m))document.removeEventListener(e,g,!0)}window.addEventListener("message",e=>{if(e.source===window.parent&&e.origin===l){if(e.data?.type==="deepnote-static-files-app-pick-start")return void function(){for(let e of(document.addEventListener("mouseover",n,!0),document.addEventListener("click",r,!0),m))document.addEventListener(e,g,!0)}();e.data?.type==="deepnote-static-files-app-pick-stop"&&(o(),t(null))}})}()})(); \ No newline at end of file +`}),l.appendChild(o.createTextNode(e))}a.timeEnd("clone node"),await p?.(h),!1!==u&&D(h)&&(a.time("embed web font"),await eR(h,r),a.timeEnd("embed web font")),a.time("embed node"),function e(t,n){var r;let{tasks:o}=n;D(t)&&((_(t)||R(t))&&o.push(...function(e,t){if(_(e)){let n=e.currentSrc||e.src;if(!G(n))return[eN(t,{url:n,imageDom:e,requestType:"image",responseType:"dataUrl"}).then(t=>{t&&(e.srcset="",e.dataset.originalSrc=n,e.src=t||"")})];(A||k)&&t.drawImageCount++}else if(L(e)&&!G(e.href.baseVal)){let n=e.href.baseVal;return[eN(t,{url:n,imageDom:e,requestType:"image",responseType:"dataUrl"}).then(t=>{t&&(e.dataset.originalSrc=n,e.href.baseVal=t||"")})]}return[]}(t,n)),P(t)&&o.push(...function(e,t){let{ownerDocument:n,svgDefsElement:r}=t,o=e.getAttribute("href")??e.getAttribute("xlink:href");if(!o)return[];let[a,i]=o.split("#");if(i){let o=`#${i}`,l=t.shadowRoots.reduce((e,t)=>e??t.querySelector(`svg ${o}`),n?.querySelector(`svg ${o}`));if(a&&e.setAttribute("href",o),r?.querySelector(o))return[];if(l)r?.appendChild(l.cloneNode(!0));else if(a)return[eN(t,{url:a,responseType:"text"}).then(e=>{r?.insertAdjacentHTML("beforeend",e)})]}return[]}(t,n))),I(t)&&o.push(...(r=t.style,eL.map(e=>{let t=r.getPropertyValue(e);return t&&"none"!==t?((A||k)&&n.drawImageCount++,eT(t,null,n,!0).then(n=>{n&&t!==n&&r.setProperty(e,n,r.getPropertyPriority(e))})):null}).filter(Boolean))),t.childNodes.forEach(t=>{e(t,n)})}(h,r);let w=i.length,y=0,b=async()=>{for(;;){let e=i.pop();if(!e)break;try{await e}catch(e){r.log.warn("Failed to run task",e)}d?.(++y,w)}};d?.(y,w),await Promise.all([...Array.from({length:4})].map(b)),a.timeEnd("embed node"),await m?.(h);let v=function(e,t){let{width:n,height:r}=t,o=Q(n,r,e.ownerDocument),a=o.ownerDocument.createElementNS(o.namespaceURI,"foreignObject");return a.setAttributeNS(null,"x","0%"),a.setAttributeNS(null,"y","0%"),a.setAttributeNS(null,"width","100%"),a.setAttributeNS(null,"height","100%"),a.append(e),o.appendChild(a),o}(h,r);return s&&v.insertBefore(s,v.children[0]),l&&v.insertBefore(l,v.children[0]),f&&function(e){if(e.ownerDocument=void 0,e.ownerWindow=void 0,e.svgStyleElement=void 0,e.svgDefsElement=void 0,e.svgStyles.clear(),e.defaultComputedStyles.clear(),e.sandbox){try{e.sandbox.remove()}catch(t){e.log.warn("Failed to destroyContext",t)}e.sandbox=void 0}e.workers=[],e.fontFamilies.clear(),e.fontCssTexts.clear(),e.requests.clear(),e.tasks=[],e.shadowRoots=[]}(r),await g?.(v),v}async function ej(e,t){let n=await eu(e,t),r=await eB(n),o=Z(r,n.isEnable("removeControlCharacter"));n.autoDestruct||(n.svgStyleElement=ef(n.ownerDocument),n.svgDefsElement=n.ownerDocument?.createElementNS(K,"defs"),n.svgStyles.clear());let a=eo(o,r.ownerDocument);return await ep(a,n)}async function eO(t,n){let r=await eu(t,n),{log:o,type:a,quality:i,dpi:l}=r,s=await ej(r);o.time("canvas to blob");let c=await ee(s,a,i);if(["image/png","image/jpeg"].includes(a)&&l){var u,d;let t=new Uint8Array(await er(c.slice(0,33)));return"image/png"===a?t=function(t,n,r=!1){let o=new Uint8Array(13);n*=39.3701,o[0]=112,o[1]=72,o[2]=89,o[3]=115,o[4]=n>>>24,o[5]=n>>>16,o[6]=n>>>8,o[7]=255&n,o[8]=o[4],o[9]=o[5],o[10]=o[6],o[11]=o[7],o[12]=1;let a=function(t){let n=-1;e||(e=function(){let e=new Int32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=1&n?0xedb88320^n>>>1:n>>>1;e[t]=n}return e}());for(let r=0;r>>8;return -1^n}(o),i=new Uint8Array(4);if(i[0]=a>>>24,i[1]=a>>>16,i[2]=a>>>8,i[3]=255&a,r){let e=function(e){let t=e.length-1;for(let n=t;n>=4;n--)if(9===e[n-4]&&112===e[n-3]&&72===e[n-2]&&89===e[n-1]&&115===e[n])return n-3;return 0}(t);return t.set(o,e),t.set(i,e+13),t}{let e=new Uint8Array(4);e[0]=0,e[1]=0,e[2]=0,e[3]=9;let n=new Uint8Array(54);return n.set(t,0),n.set(e,33),n.set(o,37),n.set(i,50),n}}(t,l):"image/jpeg"===a&&(u=t,d=l,u[13]=1,u[14]=d>>8,u[15]=255&d,u[16]=d>>8,u[17]=255&d,t=u),o.timeEnd("canvas to blob"),new Blob([t,c.slice(33)],{type:a})}return o.timeEnd("canvas to blob"),c}async function ez(e,t){let n=await eu(e,t),{log:r,quality:o,type:a,dpi:i}=n,l=await ej(n);r.time("canvas to data url");let s=l.toDataURL(a,o);return["image/png","image/jpeg"].includes(a),r.timeEnd("canvas to data url"),s}async function eW(){"complete"!==document.readyState&&await new Promise(e=>window.addEventListener("load",e,{once:!0})),await document.fonts.ready;let e=window.innerWidth;return eO(document.body,{width:e,height:Math.round(e/1.6),scale:640/e,type:"image/png",backgroundColor:function(){for(let e of[document.body,document.documentElement]){let t=getComputedStyle(e).backgroundColor;if("transparent"!==t&&"rgba(0, 0, 0, 0)"!==t)return t}return"#ffffff"}()})}window.Deepnote={connect:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{ensureAuth:t,invalidateAuth:n}=function(e){let t=null,n=null;async function r(e){try{let n=await fetch("/__deepnote/api-token",{method:"POST",headers:{...t?{authorization:`Bearer ${t.token}`}:{},...e.isEmbedded?{"x-deepnote-embedded":"1"}:{}}});return 200===n.status?f({...await n.json(),type:l}):null}catch{return null}}async function o(){return new Promise((r,o)=>{let a=setTimeout(()=>{window.removeEventListener("message",i),o(Error("Could not reach Deepnote. Open the app from its Deepnote link and make sure API access is allowed for this app.")),e.onAuthExpired&&e.onAuthExpired()},8e3);function i(e){if(e.source!==window.parent||e.origin!==c)return;let o=f(e.data);o&&(clearTimeout(a),window.removeEventListener("message",i),n=null,t=o,r(o))}window.addEventListener("message",i),u({type:"deepnote-static-files-api-token-request"})})}async function a(){return n??=(async()=>{let e=window.parent===window.top&&window.location.ancestorOrigins?.[0]===c,a=window.parent!==window.top,i=e?null:await r({isEmbedded:a});return i?(n=null,t=i,i):o()})()}return{ensureAuth:async function(){return t&&Date.now(){t=null}}}(e);async function r(e,o){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,{token:l,apiOrigin:s}=await t(),c=await fetch(s+e,{...o,headers:{authorization:`Bearer ${l}`,"content-type":"application/json"},signal:AbortSignal.timeout(3e4)}),u=429===c.status&&i>0?a(c)??1e3:null;if(null!==u&&u<=5e3)return await m(u),r(e,o,i-1);if(!c.ok){401===c.status&&n();let e=await c.json().catch(()=>null);throw Error(e?.message||`Request failed with status ${c.status}`)}return c.json()}async function o(e){let{notebook:t}=await r(`/v2/notebooks/${e}`);return t.inputs??[]}async function i(e){return r(`/v2/notebooks/${e}/app-data`)}async function s(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=await r("/v2/runs",{method:"POST",body:JSON.stringify({notebookId:e,inputs:t,detachedRunStorageMode:"readonly"})}),a=Date.now()+(n.timeoutMs??12e5),i=0;for(;;){let{run:e}=await r(`/v2/runs/${o.runId}`);if("success"===e.status&&"unavailable"===e.snapshotStatus)throw Error("The notebook finished, but Deepnote could not save its results. Check run history and try again.");let t="success"===e.status&&null==e.snapshotBlocks&&i<15&&Date.now()(function(e,t){for(let n of e.snapshotBlocks??[])for(let e of n.outputs){let n=e.data?.["application/json"];if(n&&(!t||n.schema===t))return n}return null})(e,t)};if(Date.now()>=a)throw Error(`Run ${o.runId} did not finish in time.`);t&&(i+=1),n.onProgress&&n.onProgress(e,t?"storing-result":"executing"),await m(2e3)}}return{dataframe:async function(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{projectId:o}=await t();if(null===o)throw Error("Reload the page to read dataframes.");let a=new URLSearchParams;void 0!==n.pageIndex&&a.set("pageIndex",String(n.pageIndex)),void 0!==n.pageSize&&a.set("pageSize",String(n.pageSize));let i=a.toString(),l=`/v2/projects/${o}/dataframes/${encodeURIComponent(e)}`;return r(i?`${l}?${i}`:l,void 0,3)},notebook:e=>({inputs:()=>o(e),appData:()=>i(e),run:(t,n)=>s(e,t,n)})}}},window.parent!==window&&window.addEventListener("message",async e=>{if(e.source!==window.parent||e.data?.type!=="deepnote-static-files-app-preview-request")return;let t=e.ports[0];if(!t)return;let n=await eW().catch(e=>(console.warn("Deepnote could not capture the app preview.",e),null));t.postMessage(n),t.close()}),function(){if(window.parent===window)return;let e=new Set;function t(t,n,r){let o=`${t}|${n}|${r}`;e.has(o)||e.size>=10||(e.add(o),u({type:"deepnote-static-files-app-error",message:t.slice(0,500),line:n,source:r}))}window.addEventListener("error",e=>{if(e instanceof ErrorEvent)return void t(e.error?d(e.error):e.message,e.lineno||null,e.filename?e.filename.split(/[?#]/)[0]??null:null);let n=e.target;if(n instanceof HTMLScriptElement||n instanceof HTMLLinkElement){let e=n instanceof HTMLScriptElement?n.src:n.href;t(`Failed to load ${e.split(/[?#]/)[0]}`,null,null)}},!0),window.addEventListener("unhandledrejection",e=>{t(`Unhandled promise rejection: ${d(e.reason)}`,null,null)});let n=console.error;console.error=function(){for(var e=arguments.length,r=Array(e),o=0;ou({type:"deepnote-static-files-app-ready",ready:e});r(!0),window.addEventListener("pagehide",()=>r(!1)),window.addEventListener("pageshow",e=>{e.persisted&&r(!0)})}(),function(){let e=null;function t(t){e&&(e.element.style.outline=e.outline,e.element.style.outlineOffset=e.outlineOffset,""===e.element.getAttribute("style")&&e.element.removeAttribute("style")),e=t?{element:t,outline:t.style.outline,outlineOffset:t.style.outlineOffset}:null,t&&(t.style.outline="2px solid #146efe",t.style.outlineOffset="-2px")}function n(e){t(h(e))}function r(e){w(e);let n=h(e);n&&(o(),t(null),u({type:"deepnote-static-files-app-pick",html:function(e){let t=e.cloneNode(!1);for(let n of e.childNodes){let e=n instanceof Element&&n.childElementCount>0,r=n.cloneNode(!e);e&&(r.textContent="..."),t.append(r)}return t.outerHTML}(n)}),t(n))}function o(){for(let e of(document.removeEventListener("mouseover",n,!0),document.removeEventListener("click",r,!0),g))document.removeEventListener(e,w,!0)}window.addEventListener("message",e=>{if(e.source===window.parent&&e.origin===c){if(e.data?.type==="deepnote-static-files-app-pick-start")return void function(){for(let e of(document.addEventListener("mouseover",n,!0),document.addEventListener("click",r,!0),g))document.addEventListener(e,w,!0)}();e.data?.type==="deepnote-static-files-app-pick-stop"&&(o(),t(null))}})}()})(); \ No newline at end of file diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts index 6615a331a0..0273e8f8c9 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts @@ -14,7 +14,10 @@ import { generateUuid } from '../../../platform/common/uuid'; import type { DeepnoteNotebook } from '../../../platform/deepnote/deepnoteTypes'; import { logger } from '../../../platform/logging'; import type { AppPreviewRunFiles } from './appPreviewRunFiles.node'; +import type { AppPreviewProject } from './appPreviewSession.node'; import { blocksInNotebookOrder, toNotebookInputs, type WorkspaceNotebook } from './appPreviewWorkspace.node'; +import { DATAFRAME_NAME_PATTERN, DATAFRAME_NOT_FOUND_MESSAGE, DataframePageError } from './dataframePage'; +import { readStoredDataframePage } from './storedDataframePage.node'; import type { AppPreviewApi, AppPreviewInputValue, @@ -25,12 +28,11 @@ import type { SnapshotBlock } from './types'; -export type AppPreviewUnsupportedOperation = 'dataframe()'; - export interface AppPreviewApiOptions { token: string; findNotebook(notebookId: string): Promise; - onUnsupported(operation: AppPreviewUnsupportedOperation): void; + /** The project the previewed app belongs to, read again on every dataframe request. */ + getProject(): AppPreviewProject | undefined; runFiles: AppPreviewRunFiles; runner: IAppPreviewRunner; } @@ -47,15 +49,22 @@ export const INTERNAL_ERROR_MESSAGE = 'Internal server error'; type AppViewerNotebook = operations['getNotebook']['responses'][200]['content']['application/json']['notebook']; +const MAX_DATAFRAME_PAGE_SIZE = 1000; + const createRunBodySchema = z.strictObject({ notebookId: z.string().min(1), inputs: z.record(z.string().min(1), z.union([z.string(), z.boolean(), z.array(z.string())])).optional(), detachedRunStorageMode: z.enum(['read_write', 'readonly']).optional() }); - -export function notSupportedMessage(operation: AppPreviewUnsupportedOperation): string { - return `${operation} is not supported in the local preview yet.`; -} +// Deepnote also requires a UUID `projectId`, but a `.deepnote` file's project id can be any string. +const dataframeParamsSchema = z.object({ + projectId: z.string(), + name: z.string().regex(DATAFRAME_NAME_PATTERN) +}); +const dataframeQuerySchema = z.strictObject({ + pageIndex: z.coerce.number().int().min(0).default(0), + pageSize: z.coerce.number().int().min(1).max(MAX_DATAFRAME_PAGE_SIZE).default(10) +}); /** The 4xx status of an error body-parser raises for the request itself, such as malformed JSON. */ function clientErrorStatus(error: unknown): number | undefined { @@ -182,26 +191,13 @@ function toAppViewerNotebook({ file, notebook }: WorkspaceNotebook): AppViewerNo }; } -/** - * The local stand-in for Deepnote's app viewer API, mounted at `/v2` on the preview server. - * Requests without the preview's bearer token get 401. `GET /notebooks/:notebookId` answers from the workspace's - * notebooks, and `POST /runs` runs one with `runner`, which `GET /runs/:runId` then reports on. - * `GET /notebooks/:notebookId/app-data` answers from the notebook's latest successful run that `runFiles` saved. The - * dataframe route, which the version of Deepnote's client that adds `dataframe()` calls, gets 501, and every other - * route gets 403, as Deepnote answers app viewer tokens. A body that cannot be read, such as malformed JSON, gets its - * 4xx; any other failure is logged and gets a JSON 500. - */ +/** The local stand-in for Deepnote's app viewer API, mounted at `/v2` on the preview server. */ export function createAppPreviewApi(options: AppPreviewApiOptions): AppPreviewApi { const router = express.Router(); const runs = new Map(); const unfinished = new Set(); let isDisposed = false; - const unsupported = (operation: AppPreviewUnsupportedOperation) => (_req: Request, res: Response) => { - options.onUnsupported(operation); - res.status(501).json({ message: notSupportedMessage(operation) }); - }; - const startRun = (run: PreviewRun, request: AppPreviewRunRequest) => { const cancellation = new CancellationTokenSource(); unfinished.add(cancellation); @@ -343,7 +339,35 @@ export function createAppPreviewApi(options: AppPreviewApiOptions): AppPreviewAp run: { ...run, snapshotBlocks, snapshotExpiresAt: null, snapshotContent: null, snapshotDownloadUrl: null } }); }); - router.get('/projects/:projectId/dataframes/:name', unsupported('dataframe()')); + router.get('/projects/:projectId/dataframes/:name', async (req: Request, res: Response) => { + const params = dataframeParamsSchema.safeParse(req.params); + if (!params.success) { + res.status(400).json({ message: readableErrors(params.error) }); + + return; + } + const query = dataframeQuerySchema.safeParse(req.query); + if (!query.success) { + res.status(400).json({ message: readableErrors(query.error) }); + + return; + } + const project = options.getProject(); + if (!project || project.id !== params.data.projectId) { + res.status(404).json({ message: DATAFRAME_NOT_FOUND_MESSAGE }); + + return; + } + + try { + res.json(await readStoredDataframePage(project.folder, params.data.name, query.data)); + } catch (error) { + if (!(error instanceof DataframePageError)) { + throw error; + } + res.status(error.status).json({ message: error.message }); + } + }); router.use((_req: Request, res: Response) => { res.status(403).json({ message: NOT_AVAILABLE_MESSAGE }); diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts index 9f4c9aebfa..d4b3428f5f 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts @@ -2,15 +2,22 @@ import type { DeepnoteBlock, DeepnoteFile } from '@deepnote/blocks'; import type { IDisplayData, IOutput, IStream } from '@deepnote/runtime-core'; import { assert } from 'chai'; import express from 'express'; +import * as fs from 'fs'; import * as http from 'http'; import type { AddressInfo } from 'net'; +import * as os from 'os'; import * as sinon from 'sinon'; import { anything, capture, instance, mock, verify, when } from 'ts-mockito'; import { Uri } from 'vscode'; +import zlib from 'zlib'; import { createDeferred, type Deferred } from '../../../platform/common/utils/async'; +import { DeepnoteAppPreview } from '../../../platform/common/utils/localize'; +import { platformUtils } from '../../../platform/common/utils/platform.node'; import { isUUID } from '../../../platform/common/uuid'; import { logger } from '../../../platform/logging'; +import * as path from '../../../platform/vscode-path/path'; +import { EXTENSION_ROOT_DIR_FOR_TESTS } from '../../../test/constants.node'; import { createDeepnoteBlock, createDeepnoteFile, @@ -24,14 +31,14 @@ import { NO_RUN_RESULTS_MESSAGE, NOT_AVAILABLE_MESSAGE, NOTEBOOK_NOT_FOUND_MESSAGE, - notSupportedMessage, PREVIEW_STOPPED_MESSAGE, RUN_NOT_FOUND_MESSAGE, - UNAUTHORIZED_MESSAGE, - type AppPreviewUnsupportedOperation + UNAUTHORIZED_MESSAGE } from './appPreviewApi.node'; import { AppPreviewRunFiles } from './appPreviewRunFiles.node'; +import type { AppPreviewProject } from './appPreviewSession.node'; import type { WorkspaceNotebook } from './appPreviewWorkspace.node'; +import { DATAFRAME_NOT_FOUND_MESSAGE } from './dataframePage'; import type { AppPreviewApi, AppPreviewRunOutcome, IAppPreviewRunner, SnapshotBlock } from './types'; const TOKEN = 'preview-token'; @@ -137,7 +144,7 @@ suite('createAppPreviewApi', () => { let runner: IAppPreviewRunner; let runFiles: AppPreviewRunFiles; let findNotebook: sinon.SinonStub<[string], Promise>; - let onUnsupported: sinon.SinonStub<[AppPreviewUnsupportedOperation], void>; + let getProject: sinon.SinonStub<[], AppPreviewProject | undefined>; setup(async () => { runner = mock(); @@ -151,7 +158,7 @@ suite('createAppPreviewApi', () => { findNotebook = sinon .stub<[string], Promise>() .callsFake(async (notebookId) => notebooks.get(notebookId)); - onUnsupported = sinon.stub<[AppPreviewUnsupportedOperation], void>(); + getProject = sinon.stub<[], AppPreviewProject | undefined>(); runFiles = mock(AppPreviewRunFiles); when(runFiles.write(anything(), anything())).thenResolve(true); when(runFiles.read(anything())).thenResolve(RUN_FILE); @@ -160,7 +167,7 @@ suite('createAppPreviewApi', () => { api = createAppPreviewApi({ token: TOKEN, findNotebook, - onUnsupported, + getProject, runFiles: instance(runFiles), runner: instance(runner) }); @@ -251,7 +258,6 @@ suite('createAppPreviewApi', () => { ] } }); - sinon.assert.notCalled(onUnsupported); }); test('GET /notebooks/:notebookId leaves inputs out for a notebook without any, and marks the init notebook', async () => { @@ -272,7 +278,6 @@ suite('createAppPreviewApi', () => { test('GET /notebooks/:notebookId answers 404 for an ID no workspace notebook has', async () => { await assertJson(await call('GET', '/notebooks/nb-missing'), 404, { message: NOTEBOOK_NOT_FOUND_MESSAGE }); - sinon.assert.notCalled(onUnsupported); }); test('answers a JSON 500 without the stack, and logs the error, when the notebook lookup fails', async () => { @@ -308,7 +313,6 @@ suite('createAppPreviewApi', () => { notebookId: 'nb-1', inputs: { region: 'Asia' } }); - sinon.assert.notCalled(onUnsupported); }); test('POST /runs runs the notebook without inputs when the body has none', async () => { @@ -361,7 +365,6 @@ suite('createAppPreviewApi', () => { }); verify(runFiles.write(runId, RUN_FILE)).once(); verify(runFiles.updateLatest('nb-1', runId, NOW)).once(); - sinon.assert.notCalled(onUnsupported); }); const outcomes: [AppPreviewRunOutcome, string, SnapshotBlock[] | null, number][] = [ @@ -606,7 +609,6 @@ suite('createAppPreviewApi', () => { agentBlockSummary: null, runCreatedAt: LATEST_STARTED_AT }); - sinon.assert.notCalled(onUnsupported); }); test('answers the first JSON object across blocks and their outputs, skipping a JSON array and null', async () => { @@ -704,15 +706,144 @@ suite('createAppPreviewApi', () => { }); }); - const stubs: [string, string, AppPreviewUnsupportedOperation][] = [ - ['GET', '/projects/p-1/dataframes/sales%20by%20month', 'dataframe()'] - ]; - for (const [method, path, operation] of stubs) { - test(`${method} ${path} answers 501 for ${operation}`, async () => { - await assertJson(await call(method, path), 501, { message: notSupportedMessage(operation) }); - sinon.assert.calledOnceWithExactly(onUnsupported, operation); + suite('GET /projects/:projectId/dataframes/:name', () => { + const PROJECT_ID = '5b0d4a8e-2f1c-4e3b-9a6d-7c8e9f0a1b2c'; + const NOT_FOUND = { message: DATAFRAME_NOT_FOUND_MESSAGE }; + // Holds deepnote_dataframes/toolkit_frame, three rows that deepnote-toolkit 2.9.1 stored. + const FRAMES_PROJECT: AppPreviewProject = { + id: PROJECT_ID, + folder: Uri.joinPath( + Uri.file(EXTENSION_ROOT_DIR_FOR_TESTS), + 'src', + 'test', + 'testFiles', + 'appPreview', + 'frames' + ) + }; + let emptyFolder: string; + + setup(() => { + emptyFolder = fs.mkdtempSync(path.join(os.tmpdir(), 'deepnote-app-preview-api-')); + getProject.returns(FRAMES_PROJECT); + // The reader falls back to $HOME/work, which must not hold the developer's own frames here. + sinon.stub(platformUtils, 'getEnvironmentVariable').callThrough().withArgs('HOME').returns(emptyFolder); }); - } + + teardown(() => { + fs.rmSync(emptyFolder, { recursive: true, force: true }); + }); + + function getDataframe(query = '', projectId = PROJECT_ID): Promise { + return call('GET', `/projects/${projectId}/dataframes/toolkit_frame${query}`); + } + + test("answers a page of the frame stored in the project's folder, in Deepnote's shape and key order", async () => { + const response = await getDataframe('?pageIndex=1&pageSize=2'); + + assert.strictEqual(response.status, 200); + const body = await response.json(); + assert.deepStrictEqual(Object.keys(body), [ + 'referenceId', + 'rowCount', + 'columnCount', + 'pageIndex', + 'pageSize', + 'pageCount', + 'columns', + 'rows' + ]); + assert.deepStrictEqual(body, { + referenceId: '4f988928-3050-43ab-ab95-15554633d002', + rowCount: 3, + columnCount: 4, + pageIndex: 1, + pageSize: 2, + pageCount: 2, + columns: [ + { name: 'id', type: 'int64', timezone: null }, + { name: 'score', type: 'float', timezone: null }, + { name: 'seen_at', type: 'timestamp', timezone: 'Europe/Prague' }, + { name: 'label', type: 'string', timezone: null } + ], + rows: [['0', -0.25, null, 'café']] + }); + }); + + test('answers page 0 of 10 rows without a query', async () => { + const body = await (await getDataframe()).json(); + + assert.deepStrictEqual([body.pageIndex, body.pageSize, body.pageCount, body.rows.length], [0, 10, 1, 3]); + }); + + const invalidRequests: [string, string, string][] = [ + ['a pageSize above 1000', '?pageSize=1001', 'pageSize too big: expected number to be <=1000'], + [ + 'a pageSize that is not a number', + '?pageSize=ten', + 'pageSize invalid input: expected number, received nan' + ], + ['a fractional pageIndex', '?pageIndex=0.5', 'pageIndex invalid input: expected int, received number'], + ['a fractional pageSize', '?pageSize=2.5', 'pageSize invalid input: expected int, received number'], + ['a query key Deepnote does not know', '?pageIndex=0&limit=5', 'Unrecognized key: "limit"'], + [ + 'several invalid values', + '?pageIndex=-1&pageSize=0', + 'pageIndex too small: expected number to be >=0; pageSize too small: expected number to be >=1' + ], + [ + 'a pageIndex past the last page', + '?pageIndex=1', + 'pageIndex 1 is out of range: the dataframe has 1 page(s) of 10 rows.' + ] + ]; + for (const [condition, query, message] of invalidRequests) { + test(`answers 400 to ${condition}`, async () => { + await assertJson(await getDataframe(query), 400, { message }); + }); + } + + test('answers 400 to a name outside [A-Za-z0-9_-]', async () => { + await assertJson(await call('GET', `/projects/${PROJECT_ID}/dataframes/sales%20by%20month`), 400, { + message: 'name invalid string: must match pattern /^[a-za-z0-9_-]{1,128}$/' + }); + }); + + test('reads the frames of a project whose ID is not a UUID, as .deepnote files allow', async () => { + getProject.returns({ ...FRAMES_PROJECT, id: 'e2e-hello-world-project' }); + + assert.strictEqual((await getDataframe('', 'e2e-hello-world-project')).status, 200); + }); + + test("answers 404 for a project ID other than the previewed app's project", async () => { + await assertJson(await getDataframe('', 'a7c3e1f0-9b8d-4c6e-8f2a-1b3c5d7e9f00'), 404, NOT_FOUND); + }); + + test('answers 404 when the previewed app belongs to no project', async () => { + getProject.returns(undefined); + + await assertJson(await getDataframe(), 404, NOT_FOUND); + }); + + test('asks for the project again on every request', async () => { + getProject.returns(undefined); + await assertJson(await getDataframe(), 404, NOT_FOUND); + + getProject.returns(FRAMES_PROJECT); + assert.strictEqual((await getDataframe()).status, 200); + + getProject.returns({ id: PROJECT_ID, folder: Uri.file(emptyFolder) }); + await assertJson(await getDataframe(), 404, NOT_FOUND); + }); + + test("answers the reader's 422 with its message, without logging an error", async () => { + const logError = sinon.stub(logger, 'error'); + sinon.stub(zlib, 'zstdDecompressSync').value(undefined); + + await assertJson(await getDataframe(), 422, { message: DeepnoteAppPreview.zstdUnavailable }); + sinon.assert.notCalled(logError); + }); + }); const rejectedAuthorizations: [string, string | null][] = [ ['no authorization header', null], @@ -727,7 +858,6 @@ suite('createAppPreviewApi', () => { }); await assertJson(await call('POST', '/runs', authorization), 401, { message: UNAUTHORIZED_MESSAGE }); sinon.assert.notCalled(findNotebook); - sinon.assert.notCalled(onUnsupported); }); } @@ -736,6 +866,5 @@ suite('createAppPreviewApi', () => { await assertJson(await call('GET', '/projects/p-1'), 403, notAvailable); await assertJson(await call('DELETE', '/runs/run-1'), 403, notAvailable); await assertJson(await call('POST', '/notebooks/nb-1'), 403, notAvailable); - sinon.assert.notCalled(onUnsupported); }); }); diff --git a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.ts b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.ts index c013ddf8c7..5d51efac5e 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.ts @@ -6,8 +6,6 @@ import { Commands } from '../../../platform/common/constants'; import { IDisposableRegistry, IExtensionContext } from '../../../platform/common/types'; import { DeepnoteAppPreview } from '../../../platform/common/utils/localize'; import { logger } from '../../../platform/logging'; -import { basename } from '../../../platform/vscode-path/resources'; -import type { AppPreviewUnsupportedOperation } from './appPreviewApi.node'; import { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import { AppPreviewSession } from './appPreviewSession.node'; import { resolvePreviewProject } from './appPreviewWorkspace.node'; @@ -136,7 +134,6 @@ export class AppPreviewCommandHandler implements IExtensionSyncActivationService } private async startSession(folder: Uri): Promise { - const warned = new Set(); this.runFiles ??= new AppPreviewRunFiles( this.extensionContext.storageUri ?? this.extensionContext.globalStorageUri ); @@ -148,13 +145,6 @@ export class AppPreviewCommandHandler implements IExtensionSyncActivationService // A copy of https://deepnote.com/static/app-client/v1.js, so that previews work offline. scripts: { appClient: Uri.joinPath(this.extensionContext.extensionUri, 'resources', 'appPreview', 'v1.js') - }, - onUnsupported: (operation) => { - if (warned.has(operation)) { - return; - } - warned.add(operation); - void window.showWarningMessage(DeepnoteAppPreview.operationNotSupported(operation, basename(folder))); } }); diff --git a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts index 1f3cdf8382..55c4a1e71f 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts @@ -309,18 +309,4 @@ suite('AppPreviewCommandHandler', () => { verify(commands().executeCommand(SIMPLE_BROWSER_OPEN, anything(), anything())).once(); assert.include(await page(), '

app

'); }); - - test('warns once per unsupported operation, naming the operation and the folder', async () => { - await previewApp(Uri.file(appFolder)); - const { token } = await requestToken(); - const api = (urlPath: string) => - fetch(`${serverUrl()}v2${urlPath}`, { headers: { authorization: `Bearer ${token}` } }); - const dataframe = () => api('/projects/project-1/dataframes/sales'); - - assert.strictEqual((await dataframe()).status, 501); - // A repeated call must not warn again. - assert.strictEqual((await dataframe()).status, 501); - - verify(win().showWarningMessage(DeepnoteAppPreview.operationNotSupported('dataframe()', 'app'))).once(); - }); }); diff --git a/src/notebooks/deepnote/appPreview/appPreviewSession.node.ts b/src/notebooks/deepnote/appPreview/appPreviewSession.node.ts index 64d5b42811..47f5c648f5 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewSession.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewSession.node.ts @@ -7,7 +7,7 @@ import { IDisposable } from '../../../platform/common/types'; import { generateUuid } from '../../../platform/common/uuid'; import { logger } from '../../../platform/logging'; import { extname, extUri } from '../../../platform/vscode-path/resources'; -import { createAppPreviewApi, type AppPreviewUnsupportedOperation } from './appPreviewApi.node'; +import { createAppPreviewApi } from './appPreviewApi.node'; import type { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import { findNotebookById } from './appPreviewWorkspace.node'; import type { AppPreviewApi, IAppPreviewRunner } from './types'; @@ -23,7 +23,6 @@ export interface AppPreviewSessionOptions { runFiles: AppPreviewRunFiles; runner: IAppPreviewRunner; scripts: { appClient: Uri }; - onUnsupported(operation: AppPreviewUnsupportedOperation): void; } const LOOPBACK_HOSTNAMES = ['127.0.0.1', 'localhost', '[::1]']; @@ -251,7 +250,7 @@ export class AppPreviewSession implements IDisposable { this.api = createAppPreviewApi({ token: this.token, findNotebook: (notebookId) => findNotebookById(notebookId, this.project?.folder), - onUnsupported: (operation) => this.options.onUnsupported(operation), + getProject: () => this.project, runFiles: this.options.runFiles, runner: this.options.runner }); @@ -294,7 +293,7 @@ export class AppPreviewSession implements IDisposable { token: this.token, apiOrigin: pageOrigin, expiresAtSeconds: Math.floor(Date.now() / 1000) + TOKEN_LIFETIME_SECONDS, - // The bundled client ignores this; the version that adds `dataframe()` will read the project from here. + // The client's `dataframe()` reads the project from here. ...(this.project ? { projectId: this.project.id } : {}) }); } diff --git a/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts index bc68e42bea..3848b96975 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts @@ -8,11 +8,13 @@ import { anything, capture, instance, mock, verify, when } from 'ts-mockito'; import { Uri } from 'vscode'; import { createDeferred } from '../../../platform/common/utils/async'; +import { platformUtils } from '../../../platform/common/utils/platform.node'; import * as path from '../../../platform/vscode-path/path'; +import { EXTENSION_ROOT_DIR_FOR_TESTS } from '../../../test/constants.node'; import { stubWorkspaceFsOnDisk } from '../../../test/mocks/vscodeFs'; import { mockedVSCodeNamespaces, resetVSCodeMocks } from '../../../test/vscode-mock'; import { createDeepnoteFile, createDeepnoteNotebook, createDeepnoteProject } from '../deepnoteTestHelpers'; -import { notSupportedMessage, type AppPreviewUnsupportedOperation } from './appPreviewApi.node'; +import { RUN_NOT_FOUND_MESSAGE } from './appPreviewApi.node'; import { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import { AppPreviewSession, type AppPreviewProject } from './appPreviewSession.node'; import type { AppPreviewRunOutcome, IAppPreviewRunner } from './types'; @@ -94,7 +96,6 @@ suite('AppPreviewSession', () => { let appFolder: string; let clientScript: string; let sessions: AppPreviewSession[]; - let onUnsupported: sinon.SinonStub<[AppPreviewUnsupportedOperation], void>; let runner: IAppPreviewRunner; async function startSession( @@ -106,8 +107,7 @@ suite('AppPreviewSession', () => { project: project ?? undefined, runFiles: instance(mock(AppPreviewRunFiles)), runner: instance(runner), - scripts: { appClient: Uri.file(clientScript) }, - onUnsupported + scripts: { appClient: Uri.file(clientScript) } }); sessions.push(session); await session.start(); @@ -123,7 +123,6 @@ suite('AppPreviewSession', () => { setup(() => { resetVSCodeMocks(); - onUnsupported = sinon.stub<[AppPreviewUnsupportedOperation], void>(); runner = mock(); sessions = []; tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'deepnote-app-preview-')); @@ -138,6 +137,7 @@ suite('AppPreviewSession', () => { }); teardown(() => { + sinon.restore(); sessions.forEach((session) => session.dispose()); fs.rmSync(tmp, { recursive: true, force: true }); }); @@ -368,14 +368,41 @@ suite('AppPreviewSession', () => { const session = await startSession(); const { token } = await requestToken(session); - const stub = await request(session, '/v2/projects/project-1/dataframes/sales', { + const missingRun = await request(session, '/v2/runs/run-1', { headers: { authorization: `Bearer ${token}` } }); - assert.strictEqual(stub.status, 501); - assert.deepStrictEqual(JSON.parse(stub.body.toString()), { message: notSupportedMessage('dataframe()') }); - sinon.assert.calledOnceWithExactly(onUnsupported, 'dataframe()'); + assert.strictEqual(missingRun.status, 404); + assert.deepStrictEqual(JSON.parse(missingRun.body.toString()), { message: RUN_NOT_FOUND_MESSAGE }); - assert.strictEqual((await request(session, '/v2/projects/project-1/dataframes/sales')).status, 401); + assert.strictEqual((await request(session, '/v2/runs/run-1')).status, 401); + }); + + test("answers dataframes from the session's current project folder", async () => { + const projectId = '5b0d4a8e-2f1c-4e3b-9a6d-7c8e9f0a1b2c'; + const framesFolder = Uri.joinPath( + Uri.file(EXTENSION_ROOT_DIR_FOR_TESTS), + 'src', + 'test', + 'testFiles', + 'appPreview', + 'frames' + ); + // The reader falls back to $HOME/work, which must not hold the developer's own frames here. + sinon.stub(platformUtils, 'getEnvironmentVariable').callThrough().withArgs('HOME').returns(tmp); + const session = await startSession({ project: { id: projectId, folder: framesFolder } }); + const { token } = await requestToken(session); + const dataframeStatus = async () => + ( + await request(session, `/v2/projects/${projectId}/dataframes/toolkit_frame`, { + headers: { authorization: `Bearer ${token}` } + }) + ).status; + + assert.strictEqual(await dataframeStatus(), 200); + + session.setProject({ id: projectId, folder: Uri.file(tmp) }); + + assert.strictEqual(await dataframeStatus(), 404); }); test("answers a notebook that two files share from the session's current project folder", async () => { diff --git a/src/notebooks/deepnote/appPreview/dataframeEncoding.node.ts b/src/notebooks/deepnote/appPreview/dataframeEncoding.node.ts new file mode 100644 index 0000000000..d4453f3085 --- /dev/null +++ b/src/notebooks/deepnote/appPreview/dataframeEncoding.node.ts @@ -0,0 +1,294 @@ +import { + DataType, + DateUnit, + Int64, + TimeUnit, + Type, + Vector, + type Data, + type Decimal, + type Field, + type FixedSizeList, + type LargeList, + type List, + type MapRow, + type RecordBatch, + type StructRow, + type Timestamp +} from 'apache-arrow'; + +import { + DATE_OUT_OF_RANGE_MESSAGE, + DataframePageError, + type DataframeColumn, + type DataframeColumnType +} from './dataframePage'; + +const UUID_EXTENSION_KEY = 'ARROW:extension:name'; +const UUID_EXTENSION = 'arrow.uuid'; +const UUID_BYTES = 16; +// Past these years toISOString switches to signed six-digit years. +const MIN_FORMATTED_YEAR = 0; +const MAX_FORMATTED_YEAR = 9999; +const MILLISECONDS_PER_HOUR = 3_600_000; +const NANOSECONDS_PER_MILLISECOND = 1_000_000n; +const NANOSECONDS_PER_SECOND = 1_000_000_000n; +const NANOSECONDS_PER_UNIT: Record = { + [TimeUnit.SECOND]: NANOSECONDS_PER_SECOND, + [TimeUnit.MILLISECOND]: NANOSECONDS_PER_MILLISECOND, + [TimeUnit.MICROSECOND]: 1_000n, + [TimeUnit.NANOSECOND]: 1n +}; +const TEXT_TYPES = new Set([Type.Utf8, Type.LargeUtf8, Type.Utf8View]); +const BINARY_TYPES = new Set([Type.Binary, Type.LargeBinary, Type.BinaryView, Type.FixedSizeBinary]); +const LIST_TYPES = new Set([Type.List, Type.LargeList, Type.FixedSizeList]); + +function columnType(field: Field): DataframeColumnType { + // The Arrow format allows 64-bit dictionary indices, which apache-arrow decodes as bigints that its value getters + // throw on, although its TKeys type leaves them out. + if (DataType.isDictionary(field.type) && field.type.indices.bitWidth > 32) { + throw new DataframePageError(422, `The dataframe has an unsupported column type ${String(field.type)}.`); + } + const type = valueType(field.type); + // `children` is declared as an array, yet it is null on a type that has none. + (type.children ?? []).forEach(columnType); + + if (DataType.isNull(type)) { + return 'null'; + } + if (DataType.isInt(type)) { + return type.bitWidth === 64 ? 'int64' : 'integer'; + } + if (DataType.isFloat(type)) { + return 'float'; + } + if (DataType.isBool(type)) { + return 'boolean'; + } + if (isText(type) || isUuid(field)) { + return 'string'; + } + if (isBinary(type)) { + return 'binary'; + } + if (DataType.isDecimal(type)) { + return 'decimal'; + } + if (DataType.isDate(type)) { + return 'date'; + } + if (DataType.isTimestamp(type)) { + return 'timestamp'; + } + if (DataType.isTime(type)) { + return 'time'; + } + if (DataType.isDuration(type)) { + return 'duration'; + } + if (isList(type)) { + return 'list'; + } + if (DataType.isStruct(type)) { + if (new Set(type.children.map(({ name }) => name)).size < type.children.length) { + throw new DataframePageError( + 422, + `The dataframe has a struct with two fields of the same name, ${String(type)}.` + ); + } + return 'struct'; + } + if (DataType.isMap(type)) { + return 'map'; + } + throw new DataframePageError(422, `The dataframe has an unsupported column type ${String(type)}.`); +} + +function encodeValue(value: unknown, field: Field): unknown { + if (value === null || value === undefined) { + return null; + } + + const type = valueType(field.type); + if (DataType.isInt(type)) { + return type.bitWidth === 64 ? String(value) : value; + } + if (DataType.isFloat(type)) { + return Number.isFinite(value) ? value : null; + } + if (isUuid(field)) { + return formatUuid(value as Uint8Array); + } + if (isBinary(type)) { + return Buffer.from(value as Uint8Array).toString('base64'); + } + if (DataType.isDecimal(type)) { + return formatDecimal(value as Uint32Array, type); + } + if (DataType.isDate(type)) { + return isoString(Number(value)).slice(0, 10); + } + if (DataType.isTimestamp(type)) { + return formatTimestamp(value as bigint, type); + } + if (DataType.isTime(type)) { + const nanoseconds = BigInt(value as number | bigint) * NANOSECONDS_PER_UNIT[type.unit]; + + return formatTime(Number(nanoseconds / NANOSECONDS_PER_MILLISECOND)); + } + if (DataType.isDuration(type)) { + return Number(value) / Number(NANOSECONDS_PER_SECOND / NANOSECONDS_PER_UNIT[type.unit]); + } + if (isList(type)) { + return Array.from(value as Vector, (item) => encodeValue(item, type.children[0])); + } + if (DataType.isStruct(type)) { + return Object.fromEntries( + Array.from(value as StructRow, ([name, child], index) => [name, encodeValue(child, type.children[index])]) + ); + } + if (DataType.isMap(type)) { + const [keyField, valueField] = type.children[0].type.children; + + return Array.from(value as MapRow, ([key, item]) => [ + encodeValue(key, keyField), + encodeValue(item, valueField) + ]); + } + + return value; +} + +function floorDivide(dividend: bigint, divisor: bigint): bigint { + const quotient = dividend / divisor; + + return dividend % divisor < 0n ? quotient - 1n : quotient; +} + +/** apache-arrow hands a decimal over as the 32-bit words, least significant first, of its unscaled two's complement. */ +function formatDecimal(words: Uint32Array, type: Decimal): string { + let bits = 0n; + for (let index = words.length - 1; index >= 0; index--) { + bits = (bits << 32n) + BigInt(words[index]); + } + const unscaled = BigInt.asIntN(type.bitWidth, bits); + const sign = unscaled < 0n ? '-' : ''; + const magnitude = (unscaled < 0n ? -unscaled : unscaled).toString(); + if (type.scale <= 0) { + return sign + magnitude + (unscaled === 0n ? '' : '0'.repeat(-type.scale)); + } + const whole = magnitude.length > type.scale ? magnitude.slice(0, magnitude.length - type.scale) : '0'; + const fraction = magnitude.slice(-type.scale).padStart(type.scale, '0'); + + return `${sign}${whole}.${fraction}`; +} + +function formatTime(milliseconds: number): string { + const hours = Math.floor(milliseconds / MILLISECONDS_PER_HOUR); + // A time of day can pass 24 hours, so a Date formats only what follows the hours: `MM:SS.sss`. + const rest = new Date(milliseconds % MILLISECONDS_PER_HOUR).toISOString().slice(14, 23); + + return `${String(hours).padStart(2, '0')}:${rest}`; +} + +function formatTimestamp(value: bigint, type: Timestamp): string { + const milliseconds = floorDivide(value * NANOSECONDS_PER_UNIT[type.unit], NANOSECONDS_PER_MILLISECOND); + const iso = isoString(Number(milliseconds)); + + return type.timezone ? iso : iso.slice(0, -1); +} + +function formatUuid(bytes: Uint8Array): string { + return Buffer.from(bytes) + .toString('hex') + .replace(/^(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})$/, '$1-$2-$3-$4-$5'); +} + +function isBinary(type: DataType): boolean { + return BINARY_TYPES.has(type.typeId); +} + +function isList(type: DataType): type is List | LargeList | FixedSizeList { + return LIST_TYPES.has(type.typeId); +} + +function isoString(milliseconds: number): string { + const date = new Date(milliseconds); + const year = date.getUTCFullYear(); + if (!(year >= MIN_FORMATTED_YEAR && year <= MAX_FORMATTED_YEAR)) { + throw new DataframePageError(422, DATE_OUT_OF_RANGE_MESSAGE); + } + + return date.toISOString(); +} + +function isText(type: DataType): boolean { + return TEXT_TYPES.has(type.typeId); +} + +function isUuid(field: Field): boolean { + const type = valueType(field.type); + + return ( + field.metadata.get(UUID_EXTENSION_KEY) === UUID_EXTENSION && + DataType.isFixedSizeBinary(type) && + type.byteWidth === UUID_BYTES + ); +} + +function valueType(type: DataType): DataType { + return DataType.isDictionary(type) ? type.dictionary : type; +} + +/** + * apache-arrow reads a timestamp or a Date64 as float milliseconds, which rounds sub-millisecond units and throws past + * 2^53. Viewed as Int64, the same buffers read as the exact count of units. + */ +function withInt64Times(data: Data): Data { + const isInt64Time = + DataType.isTimestamp(data.type) || (DataType.isDate(data.type) && data.type.unit === DateUnit.MILLISECOND); + const copy = data.clone( + isInt64Time ? new Int64() : data.type, + undefined, + undefined, + undefined, + undefined, + data.children.map(withInt64Times) + ); + if (data.dictionary) { + copy.dictionary = new Vector(data.dictionary.data.map(withInt64Times)); + } + + return copy; +} + +/** + * Describes a column as Deepnote's dataframe API lists it. Throws a 422 {@link DataframePageError} for a column, or a + * type nested in it, that {@link encodeRows} cannot encode. + */ +export function describeColumn(field: Field): DataframeColumn { + const type = valueType(field.type); + + return { + name: field.name, + type: columnType(field), + timezone: DataType.isTimestamp(type) && type.timezone ? type.timezone : null + }; +} + +/** + * Encodes the rows `begin` to `end` (exclusive) of `batch` the way Deepnote's dataframe API serves values. `fields` are + * the batch's columns, each already accepted by {@link describeColumn}, since encodeRows does not check types. For a + * batch read from a file they are the reader's schema fields: apache-arrow rebuilds `batch.schema` by field name, which + * gives the first of two same-named columns the other's type. Throws a 422 {@link DataframePageError} for a date or + * timestamp outside the years 0 to 9999. + */ +export function encodeRows(batch: RecordBatch, fields: Field[], begin: number, end: number): unknown[][] { + const columns = batch.data.children.map((data) => new Vector([withInt64Times(data)])); + const rows: unknown[][] = []; + for (let row = begin; row < end; row++) { + rows.push(fields.map((field, column) => encodeValue(columns[column].get(row), field))); + } + + return rows; +} diff --git a/src/notebooks/deepnote/appPreview/dataframeEncoding.node.unit.test.ts b/src/notebooks/deepnote/appPreview/dataframeEncoding.node.unit.test.ts new file mode 100644 index 0000000000..d7feee3717 --- /dev/null +++ b/src/notebooks/deepnote/appPreview/dataframeEncoding.node.unit.test.ts @@ -0,0 +1,504 @@ +import { + Binary, + Bool, + DateDay, + DateMillisecond, + Decimal, + Dictionary, + Duration, + Field, + FixedSizeBinary, + FixedSizeList, + Float16, + Float64, + Int32, + Int64, + Int8, + IntervalDayTime, + LargeBinary, + LargeList, + LargeUtf8, + List, + makeData, + Map_, + Null, + RecordBatch, + Schema, + Struct, + TimeMillisecond, + TimeNanosecond, + TimeSecond, + TimestampMicrosecond, + TimestampNanosecond, + TimestampSecond, + TimeUnit, + Uint64, + Utf8, + Vector, + vectorFromArray, + type Data, + type DataType +} from 'apache-arrow'; +import { assert } from 'chai'; + +import { describeColumn, encodeRows } from './dataframeEncoding.node'; +import { DataframePageError, DATE_OUT_OF_RANGE_MESSAGE } from './dataframePage'; + +function column(name: string, data: Data, metadata: Record = {}): [Field, Data] { + return [new Field(name, data.type, true, new Map(Object.entries(metadata))), data]; +} + +function vector(values: unknown[], type: DataType): Data { + return vectorFromArray(values, type).data[0]; +} + +function recordBatch(...columns: [Field, Data][]): RecordBatch { + const schema = new Schema(columns.map(([field]) => field)); + + return new RecordBatch( + schema, + makeData({ + type: new Struct(schema.fields), + length: columns[0][1].length, + children: columns.map(([, data]) => data) + }) + ); +} + +/** The little-endian 32-bit words of each value's two's complement, as Arrow stores a decimal. */ +function decimalWords(values: bigint[], bitWidth: number): Uint32Array { + const words = new Uint32Array((values.length * bitWidth) / 32); + values.forEach((value, index) => { + let bits = BigInt.asUintN(bitWidth, value); + for (let word = 0; word < bitWidth / 32; word++) { + words[(index * bitWidth) / 32 + word] = Number(bits & 0xffffffffn); + bits >>= 32n; + } + }); + + return words; +} + +function describeColumns(batch: RecordBatch): unknown { + return batch.schema.fields.map(describeColumn); +} + +function encode(batch: RecordBatch): { columns: unknown; rows: unknown } { + return { + columns: describeColumns(batch), + rows: encodeRows(batch, batch.schema.fields, 0, batch.numRows) + }; +} + +function failure(call: () => unknown): { status: number; message: string } { + try { + call(); + } catch (error) { + assert.instanceOf(error, DataframePageError); + + return { status: error.status, message: error.message }; + } + + return assert.fail('the call did not throw'); +} + +suite('describeColumn and encodeRows', () => { + test('encodes 8- to 32-bit integers as numbers, 64-bit integers as decimal strings, and NaN and infinities as null', () => { + const batch = recordBatch( + column('int8', vector([-128, 7, null], new Int8())), + column('int64', vector([9007199254740993n, -1n, null], new Int64())), + column( + 'uint64', + makeData({ type: new Uint64(), length: 3, data: BigUint64Array.of(2n ** 64n - 1n, 0n, 1n) }) + ), + column('float64', vector([1.5, NaN, null], new Float64())), + column('float16', vector([0.5, Infinity, -Infinity], new Float16())) + ); + + assert.deepStrictEqual(encode(batch), { + columns: [ + { name: 'int8', type: 'integer', timezone: null }, + { name: 'int64', type: 'int64', timezone: null }, + { name: 'uint64', type: 'int64', timezone: null }, + { name: 'float64', type: 'float', timezone: null }, + { name: 'float16', type: 'float', timezone: null } + ], + rows: [ + [-128, '9007199254740993', '18446744073709551615', 1.5, 0.5], + [7, '-1', '0', null, null], + [null, null, '1', null, null] + ] + }); + }); + + test('encodes booleans, strings, null columns, and dictionary columns by their values', () => { + const batch = recordBatch( + column('bool', vector([true, false, null], new Bool())), + column('utf8', vector(['a', null, 'ž'], new Utf8())), + column('large_utf8', vector(['x', 'y', null], new LargeUtf8())), + column('null', makeData({ type: new Null(), length: 3 })), + column('dictionary', vector(['b', 'b', null], new Dictionary(new Utf8(), new Int32()))), + column( + 'dictionary_timestamp', + makeData({ + type: new Dictionary(new TimestampNanosecond(), new Int32()), + length: 3, + data: Int32Array.of(1, 0, 1), + dictionary: new Vector([ + makeData({ type: new TimestampNanosecond(), length: 2, data: BigInt64Array.of(-500n, 0n) }) + ]) + }) + ) + ); + + assert.deepStrictEqual(encode(batch), { + columns: [ + { name: 'bool', type: 'boolean', timezone: null }, + { name: 'utf8', type: 'string', timezone: null }, + { name: 'large_utf8', type: 'string', timezone: null }, + { name: 'null', type: 'null', timezone: null }, + { name: 'dictionary', type: 'string', timezone: null }, + { name: 'dictionary_timestamp', type: 'timestamp', timezone: null } + ], + rows: [ + [true, 'a', 'x', null, 'b', '1970-01-01T00:00:00.000'], + [false, null, 'y', null, 'b', '1969-12-31T23:59:59.999'], + [null, 'ž', null, null, null, '1970-01-01T00:00:00.000'] + ] + }); + }); + + test('encodes an arrow.uuid as a lowercase UUID, and other binary values as padded base64', () => { + const sixteenBytes = makeData({ + type: new FixedSizeBinary(16), + length: 1, + data: Uint8Array.from(Buffer.from('0B5C1F2E3D4A4B6C8D7E9F0A1B2C3D4E', 'hex')) + }); + const batch = recordBatch( + column('uuid', sixteenBytes, { 'ARROW:extension:name': 'arrow.uuid' }), + column('fixed', sixteenBytes), + column('binary', vector([Uint8Array.of(0xfb, 0xff)], new Binary())), + column('large_binary', vector([Uint8Array.of(1)], new LargeBinary())) + ); + + assert.deepStrictEqual(encode(batch), { + columns: [ + { name: 'uuid', type: 'string', timezone: null }, + { name: 'fixed', type: 'binary', timezone: null }, + { name: 'binary', type: 'binary', timezone: null }, + { name: 'large_binary', type: 'binary', timezone: null } + ], + rows: [['0b5c1f2e-3d4a-4b6c-8d7e-9f0a1b2c3d4e', 'C1wfLj1KS2yNfp8KGyw9Tg==', '+/8=', 'AQ==']] + }); + }); + + test('encodes decimals as plain strings with exactly the scale of fraction digits', () => { + const decimal = (scale: number, precision: number, bitWidth: number, values: bigint[]) => + makeData({ + type: new Decimal(scale, precision, bitWidth), + length: values.length, + data: decimalWords(values, bitWidth) + }); + const batch = recordBatch( + column('scale_2', decimal(2, 38, 128, [12345n, 0n, -1n])), + column('scale_7', decimal(7, 18, 64, [-5n, 10_000_000n, 1n])), + column('scale_minus_2', decimal(-2, 9, 32, [12n, 0n, -3n])), + column('wide', decimal(0, 76, 256, [2n ** 200n, -(2n ** 200n), 7n])) + ); + + assert.deepStrictEqual(encode(batch), { + columns: [ + { name: 'scale_2', type: 'decimal', timezone: null }, + { name: 'scale_7', type: 'decimal', timezone: null }, + { name: 'scale_minus_2', type: 'decimal', timezone: null }, + { name: 'wide', type: 'decimal', timezone: null } + ], + rows: [ + ['123.45', '-0.0000005', '1200', '1606938044258990275541962092341162602522202993782792835301376'], + ['0.00', '1.0000000', '0', '-1606938044258990275541962092341162602522202993782792835301376'], + ['-0.01', '0.0000001', '-300', '7'] + ] + }); + }); + + test('encodes dates as UTC days, and timestamps floored to milliseconds, with Z only when zoned', () => { + const batch = recordBatch( + column('date32', makeData({ type: new DateDay(), length: 2, data: Int32Array.of(0, 19_723) })), + column( + 'date64', + makeData({ type: new DateMillisecond(), length: 2, data: BigInt64Array.of(-1n, 86_400_000n) }) + ), + column( + 'nanoseconds', + makeData({ + type: new TimestampNanosecond(), + length: 2, + data: BigInt64Array.of(-500n, 1_735_689_604_123_999_999n) + }) + ), + column( + 'microseconds_zoned', + makeData({ + type: new TimestampMicrosecond('America/New_York'), + length: 2, + data: BigInt64Array.of(0n, 253_402_300_799_999_999n) + }) + ), + column( + 'seconds', + makeData({ + type: new TimestampSecond(), + length: 2, + data: BigInt64Array.of(1_700_000_000n, -62_167_219_200n) + }) + ) + ); + + assert.deepStrictEqual(encode(batch), { + columns: [ + { name: 'date32', type: 'date', timezone: null }, + { name: 'date64', type: 'date', timezone: null }, + { name: 'nanoseconds', type: 'timestamp', timezone: null }, + { name: 'microseconds_zoned', type: 'timestamp', timezone: 'America/New_York' }, + { name: 'seconds', type: 'timestamp', timezone: null } + ], + rows: [ + [ + '1970-01-01', + '1969-12-31', + '1969-12-31T23:59:59.999', + '1970-01-01T00:00:00.000Z', + '2023-11-14T22:13:20.000' + ], + [ + '2024-01-01', + '1970-01-02', + '2025-01-01T00:00:04.123', + '9999-12-31T23:59:59.999Z', + '0000-01-01T00:00:00.000' + ] + ] + }); + }); + + test('encodes times truncated to milliseconds without wrapping the hours, and durations as seconds', () => { + const batch = recordBatch( + column('time_seconds', makeData({ type: new TimeSecond(), length: 2, data: Int32Array.of(90_061, 0) })), + column( + 'time_milliseconds', + makeData({ type: new TimeMillisecond(), length: 2, data: Int32Array.of(45_296_789, 1) }) + ), + column( + 'time_nanoseconds', + makeData({ type: new TimeNanosecond(), length: 2, data: BigInt64Array.of(1_999_999n, 999_999n) }) + ), + column( + 'duration_milliseconds', + makeData({ + type: new Duration(TimeUnit.MILLISECOND), + length: 2, + data: BigInt64Array.of(1500n, -1n) + }) + ), + column( + 'duration_nanoseconds', + makeData({ type: new Duration(TimeUnit.NANOSECOND), length: 2, data: BigInt64Array.of(3n, 0n) }) + ) + ); + + assert.deepStrictEqual(encode(batch), { + columns: [ + { name: 'time_seconds', type: 'time', timezone: null }, + { name: 'time_milliseconds', type: 'time', timezone: null }, + { name: 'time_nanoseconds', type: 'time', timezone: null }, + { name: 'duration_milliseconds', type: 'duration', timezone: null }, + { name: 'duration_nanoseconds', type: 'duration', timezone: null } + ], + rows: [ + ['25:01:01.000', '12:34:56.789', '00:00:00.001', 1.5, 3e-9], + ['00:00:00.000', '00:00:00.001', '00:00:00.000', -0.001, 0] + ] + }); + }); + + test('encodes lists as arrays, structs as objects in field order, and maps as key-value pairs, with each value by its type', () => { + const timestamps = new Field('item', new TimestampNanosecond('UTC'), true); + const structFields = [new Field('z', new Int64(), true), new Field('a', new List(timestamps), true)]; + const batch = recordBatch( + column('list', vector([[1, null], [], null], new List(new Field('item', new Int32(), true)))), + column('large_list', vector([['a'], ['b', 'c'], []], new LargeList(new Field('item', new Utf8(), true)))), + column( + 'fixed_list', + vector([[1.5, NaN], null, [0, 2]], new FixedSizeList(2, new Field('item', new Float64(), true))) + ), + column( + 'struct', + makeData({ + type: new Struct(structFields), + length: 3, + nullCount: 1, + nullBitmap: Uint8Array.of(0b011), + children: [ + vector([1n, null, 0n], new Int64()), + makeData({ + type: new List(timestamps), + length: 3, + valueOffsets: Int32Array.of(0, 1, 1, 1), + child: makeData({ + type: timestamps.type, + length: 1, + data: BigInt64Array.of(-500n) + }) + }) + ] + }) + ), + column( + 'map', + vector( + [ + new Map([ + [2n, 1.5], + [1n, NaN] + ]), + new Map(), + null + ], + new Map_( + new Field( + 'entries', + new Struct<{ key: Int64; value: Float64 }>([ + new Field('key', new Int64(), false), + new Field('value', new Float64(), true) + ]), + false + ) + ) + ) + ) + ); + + assert.deepStrictEqual(encode(batch), { + columns: [ + { name: 'list', type: 'list', timezone: null }, + { name: 'large_list', type: 'list', timezone: null }, + { name: 'fixed_list', type: 'list', timezone: null }, + { name: 'struct', type: 'struct', timezone: null }, + { name: 'map', type: 'map', timezone: null } + ], + rows: [ + [ + [1, null], + ['a'], + [1.5, null], + { z: '1', a: ['1969-12-31T23:59:59.999Z'] }, + [ + ['2', 1.5], + ['1', null] + ] + ], + [[], ['b', 'c'], null, { z: null, a: [] }, []], + [null, [], [0, 2], null, null] + ] + }); + }); + + test('throws a 422 for a column type it has no encoding for, also nested in another type', () => { + const top = recordBatch(column('interval', vector([], new IntervalDayTime()))); + const nested = recordBatch( + column('list', vector([], new List(new Field('item', new IntervalDayTime(), true)))), + column('ok', vector([], new Int32())) + ); + + assert.deepStrictEqual( + failure(() => describeColumns(top)), + { + status: 422, + message: 'The dataframe has an unsupported column type Interval.' + } + ); + assert.deepStrictEqual( + failure(() => describeColumns(nested)), + { + status: 422, + message: 'The dataframe has an unsupported column type Interval.' + } + ); + }); + + test('throws a 422 for a struct with two fields of the same name, also nested in another type', () => { + const duplicates = new Struct([new Field('a', new Int64(), true), new Field('a', new Int64(), true)]); + const top = recordBatch(column('struct', vector([], duplicates))); + const nested = recordBatch(column('list', vector([], new List(new Field('item', duplicates, true))))); + + assert.deepStrictEqual( + failure(() => describeColumns(top)), + { + status: 422, + message: 'The dataframe has a struct with two fields of the same name, Struct<{a:Int64, a:Int64}>.' + } + ); + assert.deepStrictEqual( + failure(() => describeColumns(nested)), + { + status: 422, + message: 'The dataframe has a struct with two fields of the same name, Struct<{a:Int64, a:Int64}>.' + } + ); + }); + + test('throws a 422 for a dictionary with 64-bit indices, also nested in another type', () => { + // apache-arrow's TKeys leaves out the 64-bit indices the Arrow format allows and its reader decodes. + const signed = new Dictionary(new Utf8(), new Int64()); + const unsigned = new Dictionary(new Utf8(), new Uint64()); + + assert.deepStrictEqual( + failure(() => describeColumns(recordBatch(column('dictionary', vector([], signed))))), + { + status: 422, + message: 'The dataframe has an unsupported column type Dictionary.' + } + ); + assert.deepStrictEqual( + failure(() => describeColumns(recordBatch(column('dictionary', vector([], unsigned))))), + { + status: 422, + message: 'The dataframe has an unsupported column type Dictionary.' + } + ); + assert.deepStrictEqual( + failure(() => + describeColumns(recordBatch(column('list', vector([], new List(new Field('item', signed, true)))))) + ), + { + status: 422, + message: 'The dataframe has an unsupported column type Dictionary.' + } + ); + }); + + const outOfRange: [string, Data, unknown[][]][] = [ + [ + 'a date in the year 10000', + makeData({ type: new DateDay(), length: 2, data: Int32Array.of(0, 2_932_897) }), + [['1970-01-01']] + ], + [ + 'a timestamp before the year 0', + makeData({ type: new TimestampSecond(), length: 2, data: BigInt64Array.of(0n, -62_167_219_201n) }), + [['1970-01-01T00:00:00.000']] + ] + ]; + for (const [condition, data, firstRows] of outOfRange) { + test(`throws a 422 for rows that hold ${condition}, and encodes the rows without it`, () => { + const batch = recordBatch(column('when', data)); + const fields = batch.schema.fields; + + assert.deepStrictEqual(encodeRows(batch, fields, 0, 1), firstRows); + assert.deepStrictEqual( + failure(() => encodeRows(batch, fields, 1, 2)), + { status: 422, message: DATE_OUT_OF_RANGE_MESSAGE } + ); + }); + } +}); diff --git a/src/notebooks/deepnote/appPreview/dataframePage.ts b/src/notebooks/deepnote/appPreview/dataframePage.ts new file mode 100644 index 0000000000..b9465a98ed --- /dev/null +++ b/src/notebooks/deepnote/appPreview/dataframePage.ts @@ -0,0 +1,53 @@ +export type DataframeColumnType = + | 'null' + | 'integer' + | 'int64' + | 'float' + | 'boolean' + | 'string' + | 'binary' + | 'decimal' + | 'date' + | 'timestamp' + | 'time' + | 'duration' + | 'list' + | 'struct' + | 'map'; + +export interface DataframeColumn { + name: string; + timezone: string | null; + type: DataframeColumnType; +} + +/** A page of a stored dataframe, as Deepnote's `GET /v2/projects/:projectId/dataframes/:name` answers it. */ +export interface DataframePage { + columnCount: number; + columns: DataframeColumn[]; + pageCount: number; + pageIndex: number; + pageSize: number; + referenceId: string; + rowCount: number; + rows: unknown[][]; +} + +/** A page that cannot be read, with the HTTP status Deepnote answers for it. */ +export class DataframePageError extends Error { + constructor( + public readonly status: 400 | 404 | 422, + message: string + ) { + super(message); + } +} + +/** The names deepnote-toolkit's `store_dataframe` accepts, so each is a single path segment. */ +export const DATAFRAME_NAME_PATTERN = /^[A-Za-z0-9_-]{1,128}$/; + +// Protocol strings: app code receives them, so they stay English like Deepnote's API messages. +export const DATAFRAME_NOT_FOUND_MESSAGE = 'Dataframe not found'; +export const DATE_OUT_OF_RANGE_MESSAGE = + 'The page holds a date or timestamp outside the years 0 to 9999, which the server cannot format.'; +export const LZ4_MESSAGE = 'The stored dataframe is compressed with lz4, which the server cannot decode.'; diff --git a/src/notebooks/deepnote/appPreview/storedDataframePage.node.ts b/src/notebooks/deepnote/appPreview/storedDataframePage.node.ts new file mode 100644 index 0000000000..ae51ea1ea7 --- /dev/null +++ b/src/notebooks/deepnote/appPreview/storedDataframePage.node.ts @@ -0,0 +1,203 @@ +import { CompressionType, compressionRegistry, RecordBatchReader } from 'apache-arrow'; +import fs, { type FileHandle } from 'fs/promises'; +import { homedir } from 'os'; +import { Uri } from 'vscode'; +import zlib from 'zlib'; +import { z } from 'zod'; + +import { isFileNotFoundError } from '../../../platform/common/platform/errors'; +import { DeepnoteAppPreview } from '../../../platform/common/utils/localize'; +import { getEnvironmentVariable } from '../../../platform/common/utils/platform.node'; +import { describeColumn, encodeRows } from './dataframeEncoding.node'; +import { + DATAFRAME_NAME_PATTERN, + DATAFRAME_NOT_FOUND_MESSAGE, + DataframePageError, + LZ4_MESSAGE, + type DataframePage +} from './dataframePage'; + +// deepnote-toolkit's FRAMES_DIR, relative to the folder it stores frames under. +const DATAFRAMES_DIRECTORY = 'deepnote_dataframes'; +const MANIFEST_FILE = 'manifest.json'; +const FRAME_EXTENSION = '.arrow'; +const FRAME_FILE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.arrow$/; + +const manifestSchema = z + .object({ + file: z.string().regex(FRAME_FILE), + rows: z.int().nonnegative(), + batch_rows: z.array(z.int().nonnegative()) + }) + .refine((manifest) => manifest.batch_rows.reduce((sum, rows) => sum + rows, 0) === manifest.rows); + +type Manifest = z.infer; + +interface PageRequest { + pageIndex: number; + pageSize: number; +} + +function decompressZstd(bytes: Uint8Array): Uint8Array { + // zlib has zstd from Node.js 22.15 on, and older editors run an older Node.js. + if (typeof zlib.zstdDecompressSync !== 'function') { + throw new DataframePageError(422, DeepnoteAppPreview.zstdUnavailable); + } + + return zlib.zstdDecompressSync(bytes); +} + +/** + * Falls back to `$HOME/work` because deepnote-toolkit 2.9.1 stores frames there when nothing sets its notebook root, + * and the extension's servers set none. Drop the fallback once the toolkit reads a storage root the extension sets. + * HOME comes first, as in the toolkit, because Node's homedir() reads USERPROFILE on Windows. + */ +async function frameDirectory(projectFolder: Uri, name: string): Promise { + const inProject = Uri.joinPath(projectFolder, DATAFRAMES_DIRECTORY, name); + try { + await fs.stat(Uri.joinPath(inProject, MANIFEST_FILE).fsPath); + + return inProject; + } catch (error) { + if (!isFileNotFoundError(error)) { + throw error; + } + } + + return Uri.joinPath(Uri.file(getEnvironmentVariable('HOME') || homedir()), 'work', DATAFRAMES_DIRECTORY, name); +} + +function notFound(): DataframePageError { + return new DataframePageError(404, DATAFRAME_NOT_FOUND_MESSAGE); +} + +async function readCurrentFrame(directory: Uri, page: PageRequest): Promise { + const manifest = await readManifest(directory); + if (!manifest) { + throw notFound(); + } + const pageCount = Math.max(1, Math.ceil(manifest.rows / page.pageSize)); + if (page.pageIndex >= pageCount) { + throw new DataframePageError( + 400, + `pageIndex ${page.pageIndex} is out of range: the dataframe has ${pageCount} page(s) of ${page.pageSize} rows.` + ); + } + + let handle: FileHandle; + try { + handle = await fs.open(Uri.joinPath(directory, manifest.file).fsPath, 'r'); + } catch (error) { + if (isFileNotFoundError(error)) { + return undefined; + } + throw error; + } + try { + return await readFramePage(handle, manifest, page, pageCount); + } finally { + await handle.close(); + } +} + +async function readFramePage( + handle: FileHandle, + manifest: Manifest, + { pageIndex, pageSize }: PageRequest, + pageCount: number +): Promise { + const reader = await RecordBatchReader.from(handle); + if (!reader.isFile()) { + throw notFound(); + } + await reader.open(); + if (reader.numRecordBatches !== manifest.batch_rows.length) { + throw notFound(); + } + const fields = reader.schema.fields; + const columns = fields.map(describeColumn); + + const firstRow = pageIndex * pageSize; + const endRow = Math.min(firstRow + pageSize, manifest.rows); + const rows: unknown[][] = []; + let batchStart = 0; + for (const [index, batchRows] of manifest.batch_rows.entries()) { + const batchEnd = batchStart + batchRows; + if (batchRows > 0 && batchStart < endRow && batchEnd > firstRow) { + const batch = await reader.readRecordBatch(index); + if (batch?.numRows !== batchRows) { + throw notFound(); + } + const begin = Math.max(firstRow, batchStart) - batchStart; + rows.push(...encodeRows(batch, fields, begin, Math.min(endRow, batchEnd) - batchStart)); + } + batchStart = batchEnd; + } + + return { + referenceId: manifest.file.slice(0, -FRAME_EXTENSION.length), + rowCount: manifest.rows, + columnCount: fields.length, + pageIndex, + pageSize, + pageCount, + columns, + rows + }; +} + +async function readManifest(directory: Uri): Promise { + let text: string; + try { + text = await fs.readFile(Uri.joinPath(directory, MANIFEST_FILE).fsPath, 'utf8'); + } catch (error) { + if (isFileNotFoundError(error)) { + return undefined; + } + throw error; + } + + let json: unknown; + try { + json = JSON.parse(text); + } catch { + return undefined; + } + const parsed = manifestSchema.safeParse(json); + + return parsed.success ? parsed.data : undefined; +} + +function refuseLz4(): never { + throw new DataframePageError(422, LZ4_MESSAGE); +} + +/** + * Reads one page of the dataframe that deepnote-toolkit's `store_dataframe` stored under `name` in `projectFolder`, or, + * when that folder holds no manifest for `name`, in `$HOME/work`, where the toolkit stores frames by default: + * `deepnote_dataframes//manifest.json` names an Arrow IPC file beside it, of which only the record batches the + * page overlaps are decoded. Throws a {@link DataframePageError}: 400 for a `pageIndex` past the last page, 404 for a + * `name` outside {@link DATAFRAME_NAME_PATTERN} or a missing or invalid manifest or frame file, and 422 for a frame or + * page that cannot be decompressed or encoded. Any other error, such as a corrupt record batch, propagates as it is. + */ +export async function readStoredDataframePage( + projectFolder: Uri, + name: string, + page: PageRequest +): Promise { + if (!DATAFRAME_NAME_PATTERN.test(name)) { + throw notFound(); + } + // The registry is process-wide and `set` replaces a whole codec, so one registered elsewhere could stand in. + compressionRegistry.set(CompressionType.ZSTD, { decode: decompressZstd }); + compressionRegistry.set(CompressionType.LZ4_FRAME, { decode: refuseLz4 }); + + const directory = await frameDirectory(projectFolder, name); + // A newer store may have replaced the frame, deleting its file, between reading the manifest and opening the file. + const found = (await readCurrentFrame(directory, page)) ?? (await readCurrentFrame(directory, page)); + if (!found) { + throw notFound(); + } + + return found; +} diff --git a/src/notebooks/deepnote/appPreview/storedDataframePage.node.unit.test.ts b/src/notebooks/deepnote/appPreview/storedDataframePage.node.unit.test.ts new file mode 100644 index 0000000000..f954a716b7 --- /dev/null +++ b/src/notebooks/deepnote/appPreview/storedDataframePage.node.unit.test.ts @@ -0,0 +1,441 @@ +import { + CompressionType, + compressionRegistry, + DateDay, + Dictionary, + Field, + FixedSizeBinary, + Int32, + Int64, + makeData, + RecordBatch, + RecordBatchFileWriter, + Schema, + Struct, + Utf8, + vectorFromArray +} from 'apache-arrow'; +import { assert } from 'chai'; +import * as fs from 'fs'; +import fsPromises from 'fs/promises'; +import { syncBuiltinESMExports } from 'module'; +import os from 'os'; +import * as sinon from 'sinon'; +import { Uri } from 'vscode'; +import zlib from 'zlib'; + +import { DeepnoteAppPreview } from '../../../platform/common/utils/localize'; +import { platformUtils } from '../../../platform/common/utils/platform.node'; +import * as path from '../../../platform/vscode-path/path'; +import { EXTENSION_ROOT_DIR_FOR_TESTS } from '../../../test/constants.node'; +import { + DATAFRAME_NOT_FOUND_MESSAGE, + DataframePageError, + DATE_OUT_OF_RANGE_MESSAGE, + LZ4_MESSAGE +} from './dataframePage'; +import { readStoredDataframePage } from './storedDataframePage.node'; + +const REFERENCE_ID = '0b5c1f2e-3d4a-4b6c-8d7e-9f0a1b2c3d4e'; +const LZ4_FRAME_HEADER = Uint8Array.of(0x04, 0x22, 0x4d, 0x18, 0x40, 0x40, 0xc0); +const OTHER_REFERENCE_ID = '7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d'; +const FIXTURE_PROJECT = Uri.joinPath( + Uri.file(EXTENSION_ROOT_DIR_FOR_TESTS), + 'src', + 'test', + 'testFiles', + 'appPreview', + 'frames' +); + +function numbers(...values: number[]): RecordBatch { + return new RecordBatch({ n: vectorFromArray(values, new Int32()).data[0] }); +} + +async function rejection(promise: Promise): Promise<{ status: number; message: string }> { + const error = await promise.then( + () => assert.fail('the read did not reject'), + (reason: unknown) => reason + ); + assert.instanceOf(error, DataframePageError); + + return { status: error.status, message: error.message }; +} + +suite('readStoredDataframePage', () => { + let projectFolder: string; + let home: string; + let getEnvironmentVariable: sinon.SinonStub; + + setup(() => { + projectFolder = fs.mkdtempSync(path.join(os.tmpdir(), 'deepnote-stored-dataframe-')); + home = fs.mkdtempSync(path.join(os.tmpdir(), 'deepnote-stored-dataframe-home-')); + getEnvironmentVariable = sinon.stub(platformUtils, 'getEnvironmentVariable').callThrough(); + getEnvironmentVariable.withArgs('HOME').returns(home); + }); + + teardown(() => { + sinon.restore(); + syncBuiltinESMExports(); + fs.rmSync(projectFolder, { recursive: true, force: true }); + fs.rmSync(home, { recursive: true, force: true }); + }); + + function frameDirectory(name: string): string { + return path.join(projectFolder, 'deepnote_dataframes', name); + } + + function moveFramesToHome(): void { + fs.mkdirSync(path.join(home, 'work')); + fs.renameSync(path.join(projectFolder, 'deepnote_dataframes'), path.join(home, 'work', 'deepnote_dataframes')); + } + + function writeManifest(name: string, manifest: unknown): void { + fs.mkdirSync(frameDirectory(name), { recursive: true }); + const text = typeof manifest === 'string' ? manifest : JSON.stringify(manifest); + fs.writeFileSync(path.join(frameDirectory(name), 'manifest.json'), text); + } + + function writeFrame( + name: string, + batches: RecordBatch[], + options: { compression?: CompressionType; manifest?: unknown; referenceId?: string } = {} + ): void { + const referenceId = options.referenceId ?? REFERENCE_ID; + if (options.compression === CompressionType.ZSTD) { + compressionRegistry.set(CompressionType.ZSTD, { encode: (bytes) => zlib.zstdCompressSync(bytes) }); + } + // The reader refuses lz4 before decoding, so a buffer need not be real lz4: only start like an lz4 frame, as + // apache-arrow checks, and be shorter than the data, or the writer stores the data uncompressed. + if (options.compression === CompressionType.LZ4_FRAME) { + compressionRegistry.set(CompressionType.LZ4_FRAME, { encode: () => LZ4_FRAME_HEADER }); + } + const writer = RecordBatchFileWriter.writeAll(batches, { compressionType: options.compression ?? null }); + fs.mkdirSync(frameDirectory(name), { recursive: true }); + fs.writeFileSync(path.join(frameDirectory(name), `${referenceId}.arrow`), writer.toUint8Array(true)); + writeManifest( + name, + options.manifest ?? { + file: `${referenceId}.arrow`, + rows: batches.reduce((rows, batch) => rows + batch.numRows, 0), + batch_rows: batches.map((batch) => batch.numRows) + } + ); + } + + function read(name: string, pageIndex = 0, pageSize = 10, folder = Uri.file(projectFolder)) { + return readStoredDataframePage(folder, name, { pageIndex, pageSize }); + } + + suite('encoding', () => { + test('answers 422 for a page that holds a date outside the years 0 to 9999, and serves the pages without it', async () => { + const dates = makeData({ type: new DateDay(), length: 2, data: Int32Array.of(0, 2_932_897) }); + writeFrame('frame', [new RecordBatch({ when: dates })]); + + assert.deepStrictEqual((await read('frame', 0, 1)).rows, [['1970-01-01']]); + assert.deepStrictEqual(await rejection(read('frame', 1, 1)), { + status: 422, + message: DATE_OUT_OF_RANGE_MESSAGE + }); + }); + + test('answers 422 for a column it cannot encode, before it encodes any value', async () => { + // apache-arrow's TKeys leaves out 64-bit indices, and its getters throw a TypeError on them, so only a reader + // that describes the columns before it encodes a value answers 422. + const dictionary = makeData({ + type: new Dictionary(new Utf8(), new Int64()), + length: 1, + data: BigInt64Array.of(0n), + dictionary: vectorFromArray(['a'], new Utf8()) + }); + writeFrame('frame', [new RecordBatch({ dictionary })]); + + assert.deepStrictEqual(await rejection(read('frame')), { + status: 422, + message: 'The dataframe has an unsupported column type Dictionary.' + }); + }); + + test('answers an arrow.uuid column as UUIDs, by the extension name the frame file keeps on the column', async () => { + const field = new Field( + 'id', + new FixedSizeBinary(16), + true, + new Map([['ARROW:extension:name', 'arrow.uuid']]) + ); + const ids = makeData({ + type: field.type, + length: 1, + data: Uint8Array.from(Buffer.from('6F1D2C3B4A594E8D9C7B0A1B2C3D4E5F', 'hex')) + }); + writeFrame('frame', [ + new RecordBatch( + new Schema([field]), + makeData({ type: new Struct([field]), length: 1, children: [ids] }) + ) + ]); + const { columns, rows } = await read('frame'); + + assert.deepStrictEqual( + { columns, rows }, + { + columns: [{ name: 'id', type: 'string', timezone: null }], + rows: [['6f1d2c3b-4a59-4e8d-9c7b-0a1b2c3d4e5f']] + } + ); + }); + }); + + suite('paging', () => { + const FRAME = [numbers(0, 1, 2), numbers(), numbers(3, 4), numbers(5, 6, 7)]; + + test('answers the page in the response key order, reading across a record batch boundary', async () => { + writeFrame('frame', FRAME); + + const page = await read('frame', 1, 2); + + assert.deepStrictEqual(Object.keys(page), [ + 'referenceId', + 'rowCount', + 'columnCount', + 'pageIndex', + 'pageSize', + 'pageCount', + 'columns', + 'rows' + ]); + assert.deepStrictEqual(page, { + referenceId: REFERENCE_ID, + rowCount: 8, + columnCount: 1, + pageIndex: 1, + pageSize: 2, + pageCount: 4, + columns: [{ name: 'n', type: 'integer', timezone: null }], + rows: [[2], [3]] + }); + }); + + test('answers pages that end exactly on a record batch boundary, and a short last page', async () => { + writeFrame('frame', FRAME); + + assert.deepStrictEqual((await read('frame', 0, 3)).rows, [[0], [1], [2]]); + assert.deepStrictEqual((await read('frame', 1, 3)).rows, [[3], [4], [5]]); + assert.deepStrictEqual((await read('frame', 2, 3)).rows, [[6], [7]]); + assert.deepStrictEqual((await read('frame', 0, 1000)).rows, [[0], [1], [2], [3], [4], [5], [6], [7]]); + }); + + test('answers 400 for a pageIndex past the last page', async () => { + writeFrame('frame', FRAME); + + assert.deepStrictEqual(await rejection(read('frame', 2, 5)), { + status: 400, + message: 'pageIndex 2 is out of range: the dataframe has 2 page(s) of 5 rows.' + }); + }); + + test('answers an empty frame as one empty page', async () => { + writeFrame('empty', [numbers(), numbers()]); + + const page = await read('empty'); + + assert.deepStrictEqual(page, { + referenceId: REFERENCE_ID, + rowCount: 0, + columnCount: 1, + pageIndex: 0, + pageSize: 10, + pageCount: 1, + columns: [{ name: 'n', type: 'integer', timezone: null }], + rows: [] + }); + assert.deepStrictEqual(await rejection(read('empty', 1)), { + status: 400, + message: 'pageIndex 1 is out of range: the dataframe has 1 page(s) of 10 rows.' + }); + }); + + test('reads only the record batches the page overlaps', async () => { + writeFrame('frame', [numbers(0, 1, 2), numbers(3, 4), numbers(5)], { + manifest: { file: `${REFERENCE_ID}.arrow`, rows: 6, batch_rows: [2, 2, 2] } + }); + + assert.deepStrictEqual((await read('frame', 1, 2)).rows, [[3], [4]]); + assert.deepStrictEqual(await rejection(read('frame', 0, 2)), { + status: 404, + message: DATAFRAME_NOT_FOUND_MESSAGE + }); + }); + }); + + suite('storage', () => { + // apache-arrow's writer stores a buffer uncompressed unless compressing makes it smaller. + const COMPRESSIBLE = new Array(1000).fill(7); + + test('reads a zstd frame written by deepnote-toolkit 2.9.1, ignoring the extra manifest keys', async () => { + const page = await read('toolkit_frame', 0, 10, FIXTURE_PROJECT); + + assert.deepStrictEqual(page, { + referenceId: '4f988928-3050-43ab-ab95-15554633d002', + rowCount: 3, + columnCount: 4, + pageIndex: 0, + pageSize: 10, + pageCount: 1, + columns: [ + { name: 'id', type: 'int64', timezone: null }, + { name: 'score', type: 'float', timezone: null }, + { name: 'seen_at', type: 'timestamp', timezone: 'Europe/Prague' }, + { name: 'label', type: 'string', timezone: null } + ], + rows: [ + ['9007199254740993', 1.5, '2024-01-02T03:04:05.678Z', 'alpha'], + ['-7', null, '1969-12-31T23:59:59.999Z', null], + ['0', -0.25, null, 'café'] + ] + }); + }); + + const missing: [string, () => void][] = [ + ['nothing is stored under the name', () => undefined], + ['the manifest is not JSON', () => writeManifest('frame', '{"file":')], + [ + "the manifest's file is not a lowercase UUID with .arrow", + () => writeFrame('frame', [numbers(1)], { referenceId: REFERENCE_ID.toUpperCase() }) + ], + [ + "the manifest's file is a path out of the frame's folder", + () => { + writeFrame('other', [numbers(1)]); + writeManifest('frame', { file: `../other/${REFERENCE_ID}.arrow`, rows: 1, batch_rows: [1] }); + } + ], + [ + 'the manifest has no batch_rows', + () => writeFrame('frame', [numbers(1)], { manifest: { file: `${REFERENCE_ID}.arrow`, rows: 1 } }) + ], + [ + "the manifest's batch_rows do not add up to its rows", + () => + writeFrame('frame', [numbers(1)], { + manifest: { file: `${REFERENCE_ID}.arrow`, rows: 2, batch_rows: [1] } + }) + ], + [ + 'the file the manifest names is missing', + () => writeManifest('frame', { file: `${OTHER_REFERENCE_ID}.arrow`, rows: 1, batch_rows: [1] }) + ], + [ + 'the frame holds more record batches than batch_rows lists', + () => + writeFrame('frame', [numbers(1), numbers(2)], { + manifest: { file: `${REFERENCE_ID}.arrow`, rows: 1, batch_rows: [1] } + }) + ], + [ + 'a record batch holds another row count than its batch_rows entry', + () => + writeFrame('frame', [numbers(1)], { + manifest: { file: `${REFERENCE_ID}.arrow`, rows: 2, batch_rows: [2] } + }) + ] + ]; + for (const [condition, store] of missing) { + test(`answers 404 when ${condition}`, async () => { + store(); + + assert.deepStrictEqual(await rejection(read('frame')), { + status: 404, + message: DATAFRAME_NOT_FOUND_MESSAGE + }); + }); + } + + test('reads a frame stored under $HOME/work when the project folder has none under its name', async () => { + writeFrame('frame', [numbers(1, 2)]); + moveFramesToHome(); + + const page = await read('frame'); + + assert.deepStrictEqual([page.referenceId, page.rows], [REFERENCE_ID, [[1], [2]]]); + }); + + test('reads a frame stored under the home folder Node reports when HOME is unset, as it usually is on Windows', async () => { + getEnvironmentVariable.withArgs('HOME').returns(undefined); + sinon.stub(os, 'homedir').returns(home); + // The reader's named import of homedir follows os.homedir only once synced, here and after the restore. + syncBuiltinESMExports(); + writeFrame('frame', [numbers(1, 2)]); + moveFramesToHome(); + + const page = await read('frame'); + + assert.deepStrictEqual([page.referenceId, page.rows], [REFERENCE_ID, [[1], [2]]]); + }); + + test("reads the project folder's frame over one of the same name under $HOME/work", async () => { + writeFrame('frame', [numbers(1)], { referenceId: OTHER_REFERENCE_ID }); + moveFramesToHome(); + writeFrame('frame', [numbers(2)]); + + const page = await read('frame'); + + assert.deepStrictEqual([page.referenceId, page.rows], [REFERENCE_ID, [[2]]]); + }); + + test('answers 404 for an invalid manifest in the project folder, even when $HOME/work has the frame', async () => { + writeFrame('frame', [numbers(1)]); + moveFramesToHome(); + writeManifest('frame', '{"file":'); + + assert.deepStrictEqual(await rejection(read('frame')), { + status: 404, + message: DATAFRAME_NOT_FOUND_MESSAGE + }); + }); + + test('answers 404 for a name that is not a single safe path segment', async () => { + writeFrame('frame', [numbers(1)]); + + assert.deepStrictEqual(await rejection(read('../deepnote_dataframes/frame')), { + status: 404, + message: DATAFRAME_NOT_FOUND_MESSAGE + }); + }); + + test('reads the manifest again when the frame it named was replaced before the file was opened', async () => { + writeFrame('frame', [numbers(1, 2)], { referenceId: OTHER_REFERENCE_ID }); + writeManifest('frame', { file: `${REFERENCE_ID}.arrow`, rows: 1, batch_rows: [1] }); + const realOpen = fsPromises.open; + const open = sinon.stub(fsPromises, 'open').callThrough(); + open.onFirstCall().callsFake(async (...args: Parameters) => { + writeManifest('frame', { file: `${OTHER_REFERENCE_ID}.arrow`, rows: 2, batch_rows: [2] }); + + return realOpen(...args); + }); + + const page = await read('frame'); + + assert.deepStrictEqual([page.referenceId, page.rows], [OTHER_REFERENCE_ID, [[1], [2]]]); + }); + + test('answers 422 for a frame compressed with lz4', async () => { + writeFrame('frame', [numbers(...COMPRESSIBLE)], { compression: CompressionType.LZ4_FRAME }); + + assert.deepStrictEqual(await rejection(read('frame')), { + status: 422, + message: LZ4_MESSAGE + }); + }); + + test("answers 422 for a zstd frame when the editor's Node.js has no zstd", async () => { + writeFrame('frame', [numbers(...COMPRESSIBLE)], { compression: CompressionType.ZSTD }); + sinon.stub(zlib, 'zstdDecompressSync').value(undefined); + + assert.deepStrictEqual(await rejection(read('frame')), { + status: 422, + message: DeepnoteAppPreview.zstdUnavailable + }); + }); + }); +}); diff --git a/src/platform/common/utils/localize.ts b/src/platform/common/utils/localize.ts index 5307216a68..a176816f3d 100644 --- a/src/platform/common/utils/localize.ts +++ b/src/platform/common/utils/localize.ts @@ -1417,8 +1417,6 @@ export namespace DeepnoteAppPreview { export const chooseFolderTitle = l10n.t('Choose the app folder to preview'); export const preview = l10n.t('Preview'); export const startFailed = (message: string) => l10n.t('Could not start the app preview: {0}', message); - export const operationNotSupported = (operation: string, folderName: string) => - l10n.t('The app in {1} called {0}, which the local preview does not support yet.', operation, folderName); export const noInterpreter = l10n.t( 'No Python interpreter is selected for the notebook. Select one in VS Code, then run the app again.' ); @@ -1431,6 +1429,9 @@ export namespace DeepnoteAppPreview { export const blockFailed = (blockId: string) => l10n.t('Block {0} failed.', blockId); export const notebookNotInFile = (notebookId: string) => l10n.t('The notebook {0} is no longer in its .deepnote file.', notebookId); + export const zstdUnavailable = l10n.t( + "The editor's Node.js cannot decompress the stored dataframe, which is compressed with zstd. Update the editor to read it." + ); } export namespace SelectInputSettings { diff --git a/src/test/testFiles/appPreview/frames/deepnote_dataframes/toolkit_frame/4f988928-3050-43ab-ab95-15554633d002.arrow b/src/test/testFiles/appPreview/frames/deepnote_dataframes/toolkit_frame/4f988928-3050-43ab-ab95-15554633d002.arrow new file mode 100644 index 0000000000..e1e8031fd1 Binary files /dev/null and b/src/test/testFiles/appPreview/frames/deepnote_dataframes/toolkit_frame/4f988928-3050-43ab-ab95-15554633d002.arrow differ diff --git a/src/test/testFiles/appPreview/frames/deepnote_dataframes/toolkit_frame/manifest.json b/src/test/testFiles/appPreview/frames/deepnote_dataframes/toolkit_frame/manifest.json new file mode 100644 index 0000000000..e41f080edd --- /dev/null +++ b/src/test/testFiles/appPreview/frames/deepnote_dataframes/toolkit_frame/manifest.json @@ -0,0 +1 @@ +{"version": 1, "file": "4f988928-3050-43ab-ab95-15554633d002.arrow", "written_at": "2026-11-25T14:22:21Z", "rows": 3, "batch_rows": [3], "toolkit_version": "2.9.1"} \ No newline at end of file diff --git a/test/e2e/fixtures/app-preview-app-data/index.html b/test/e2e/fixtures/app-preview-app-data/index.html index aca35e9537..f00bd514d6 100644 --- a/test/e2e/fixtures/app-preview-app-data/index.html +++ b/test/e2e/fixtures/app-preview-app-data/index.html @@ -6,7 +6,7 @@ -

Sales results

+

Sales results

  • run({ region: 'Asia' }): pending
  • appData() after the run: pending
  • diff --git a/test/e2e/fixtures/app-preview-dataframes/3f2b8c1e-6d4a-4e9b-9a7c-0d5e1f2a3b4c.arrow b/test/e2e/fixtures/app-preview-dataframes/3f2b8c1e-6d4a-4e9b-9a7c-0d5e1f2a3b4c.arrow new file mode 100644 index 0000000000..ee0d0cf35c Binary files /dev/null and b/test/e2e/fixtures/app-preview-dataframes/3f2b8c1e-6d4a-4e9b-9a7c-0d5e1f2a3b4c.arrow differ diff --git a/test/e2e/fixtures/app-preview-dataframes/index.html b/test/e2e/fixtures/app-preview-dataframes/index.html new file mode 100644 index 0000000000..05faa7f5a1 --- /dev/null +++ b/test/e2e/fixtures/app-preview-dataframes/index.html @@ -0,0 +1,241 @@ + + + + + + Customers + + + + +
    +

    Customers

    +

    Loading the stored dataframe…

    +
    + + + + + +
    + +
    + +
    + + + diff --git a/test/e2e/fixtures/app-preview-dataframes/store_frame.py b/test/e2e/fixtures/app-preview-dataframes/store_frame.py new file mode 100644 index 0000000000..219abe7832 --- /dev/null +++ b/test/e2e/fixtures/app-preview-dataframes/store_frame.py @@ -0,0 +1,7 @@ +import sys + +import pyarrow as pa +from deepnote_toolkit.artifacts import store_dataframe + +frame_file, name = sys.argv[1:] +store_dataframe(pa.ipc.open_file(frame_file).read_all().to_pandas(), name) diff --git a/test/e2e/fixtures/app-preview-runs/index.html b/test/e2e/fixtures/app-preview-runs/index.html index a5fd2b5e94..ecaa29eda2 100644 --- a/test/e2e/fixtures/app-preview-runs/index.html +++ b/test/e2e/fixtures/app-preview-runs/index.html @@ -9,9 +9,9 @@

    Sales runs

    idle

    diff --git a/test/e2e/fixtures/app-preview/app.js b/test/e2e/fixtures/app-preview/app.js index 8073ba9ce6..979bf176bb 100644 --- a/test/e2e/fixtures/app-preview/app.js +++ b/test/e2e/fixtures/app-preview/app.js @@ -69,6 +69,7 @@ const notebook = connection.notebook('e2e-preview-notebook'); connection.notebook('e2e-missing-notebook').inputs() ); await call('app-data', 'appData()', () => notebook.appData()); + await call('dataframe', 'dataframe()', () => connection.dataframe('sales')); const deepnoteRequests = performance .getEntriesByType('resource') .filter((entry) => new URL(entry.name).hostname.endsWith('deepnote.com')); diff --git a/test/e2e/fixtures/app-preview/index.html b/test/e2e/fixtures/app-preview/index.html index 3037d9f1ec..c3f013155c 100644 --- a/test/e2e/fixtures/app-preview/index.html +++ b/test/e2e/fixtures/app-preview/index.html @@ -16,6 +16,7 @@

    Sales dashboard

  • inputs(): pending
  • inputs() of an unknown notebook: pending
  • appData(): pending
  • +
  • dataframe(): pending
  • requests to deepnote.com: pending
diff --git a/test/e2e/helpers/venv.ts b/test/e2e/helpers/venv.ts index b1d234d8c1..1edb76b6ae 100644 --- a/test/e2e/helpers/venv.ts +++ b/test/e2e/helpers/venv.ts @@ -19,7 +19,7 @@ const SETTINGS_SOURCE = path.join(REPO_ROOT, 'test', 'e2e', 'settings.json'); const SETTINGS_TARGET = path.join(REPO_ROOT, 'test', 'e2e', 'settings.generated.json'); /** The interpreter inside the pre-baked venv. Suites run against it as the active interpreter. */ -function venvPython(): string { +export function venvPython(): string { return process.platform === 'win32' ? path.join(VENV_DIR, 'Scripts', 'python.exe') : path.join(VENV_DIR, 'bin', 'python'); diff --git a/test/e2e/suite/appPreview/previewApp.e2e.test.ts b/test/e2e/suite/appPreview/previewApp.e2e.test.ts index 984c30e0cb..c6f2e39bfb 100644 --- a/test/e2e/suite/appPreview/previewApp.e2e.test.ts +++ b/test/e2e/suite/appPreview/previewApp.e2e.test.ts @@ -6,10 +6,20 @@ */ import { expect } from 'chai'; +import { execFileSync } from 'child_process'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { By, EditorView, InputBox, SideBarView, VSBrowser, Workbench, type ViewItem } from 'vscode-extension-tester'; +import { + By, + EditorView, + InputBox, + SideBarView, + VSBrowser, + Workbench, + type TreeItem, + type ViewItem +} from 'vscode-extension-tester'; import { KERNEL_CONNECT_TIMEOUT, @@ -23,12 +33,15 @@ import { openFolderViaDialog, selectDeepnoteContextMenu } from '../../helpers'; +import { venvPython } from '../../helpers/venv'; const FIXTURE_APP = path.resolve(process.cwd(), 'test', 'e2e', 'fixtures', 'app-preview'); const RUNS_FIXTURE_APP = path.resolve(process.cwd(), 'test', 'e2e', 'fixtures', 'app-preview-runs'); const APP_DATA_FIXTURE_APP = path.resolve(process.cwd(), 'test', 'e2e', 'fixtures', 'app-preview-app-data'); +const DATAFRAMES_FIXTURE = path.resolve(process.cwd(), 'test', 'e2e', 'fixtures', 'app-preview-dataframes'); const INPUTS_NOTEBOOK_FIXTURE = 'app-preview-inputs.deepnote'; const RUNS_NOTEBOOK_FIXTURES = ['app-preview-runs.deepnote', 'app-preview-runs-init.deepnote']; +const PROJECT_FIXTURE = 'hello-world.deepnote'; const SYNCED_APP = path.join('Sales', '.files', '_deepnote_static'); const SYNCED_TITLE = 'Synced fixture'; const RELOAD_TITLE = 'Reload fixture'; @@ -36,11 +49,26 @@ const REUSE_TITLE = 'Reuse fixture'; const INPUTS_TITLE = 'Inputs fixture'; const RUNS_TITLE = 'Runs fixture'; const APP_DATA_TITLE = 'App data fixture'; +const DATAFRAMES_APP = 'app'; +const DATAFRAMES_TITLE = 'Customers'; const PREVIEW_URL = /^http:\/\/127\.0\.0\.1:\d+\//; const INPUTS_RESOLVED = 'inputs() resolved: '; const APP_DATA_AFTER_RUN = 'appData() after the run: '; +const PREVIEW_REPORT_IDS = [ + 'title', + 'client', + 'styles', + 'logo-status', + 'inputs', + 'missing-inputs', + 'app-data', + 'dataframe', + 'network' +]; +const APP_DATA_REPORT_IDS = ['title', 'run', 'after-run']; const NO_RUN_RESULTS = 'You have no run results for this notebook yet. Run the notebook to load them.'; +const NO_PROJECT_DATAFRAME = 'Reload the page to read dataframes.'; const NOTEBOOK_INPUTS = [ { blockId: 'e2e-region-input', name: 'region', type: 'input-text', value: 'Europe', label: 'Region' }, @@ -65,6 +93,38 @@ const NOTEBOOK_INPUTS = [ } ]; +// The frame is stored in the developer's own home folder on a local run, so under a name no notebook of theirs uses. +const FRAME_NAME = 'app_preview_e2e_customers'; +const FRAME_FILE = '3f2b8c1e-6d4a-4e9b-9a7c-0d5e1f2a3b4c.arrow'; +const STORE_FRAME_SCRIPT = path.join(DATAFRAMES_FIXTURE, 'store_frame.py'); +const STORE_FRAME_TIMEOUT = 60_000; +const FIRST_ROW = [ + '0', + 'customer-000039', + '58.88', + 'silver', + 'false', + '2025-01-01T00:00:04.000', + 'left voicemail (ticket 34)' +]; +const LAST_ROW = [ + '199999', + 'customer-000167', + '68.8', + 'diamond', + 'true', + '2025-01-06T19:13:25.000', + 'called back (ticket 33)' +]; + +interface DataframeSitePage { + error: string; + indicator: string; + isNextDisabled: boolean; + rows: string[][]; + summary: string; +} + function expectedReport(title: string): unknown[] { return [ title, @@ -74,6 +134,7 @@ function expectedReport(title: string): unknown[] { NOTEBOOK_INPUTS, 'inputs() of an unknown notebook rejected: Notebook not found', `appData() rejected: ${NO_RUN_RESULTS}`, + `dataframe() rejected: ${NO_PROJECT_DATAFRAME}`, 'requests to deepnote.com: 0' ]; } @@ -84,7 +145,7 @@ function withParsedInputs(report: string[]): unknown[] { ); } -async function readReport(timeout = WORKBENCH_TIMEOUT): Promise { +async function readReport(ids = PREVIEW_REPORT_IDS, timeout = WORKBENCH_TIMEOUT): Promise { const driver = VSBrowser.instance.driver; let report: string[] = []; try { @@ -92,7 +153,8 @@ async function readReport(timeout = WORKBENCH_TIMEOUT): Promise { async () => { report = await driver .executeScript( - "return Array.from(document.querySelectorAll('h1, li'), (element) => element.textContent)" + 'return arguments[0].map((id) => document.getElementById(id).textContent)', + ids ) .catch(() => []); @@ -108,6 +170,42 @@ async function readReport(timeout = WORKBENCH_TIMEOUT): Promise { return withParsedInputs(report); } +function consecutiveIds(first: number, count: number): string[] { + return Array.from({ length: count }, (_, offset) => String(first + offset)); +} + +async function readDataframePage(indicator: string): Promise { + const driver = VSBrowser.instance.driver; + let page: DataframeSitePage | undefined; + try { + await driver.wait( + async () => { + page = await driver + .executeScript( + `return { + error: document.getElementById('error').textContent, + indicator: document.getElementById('indicator').textContent, + isNextDisabled: document.getElementById('next').disabled, + rows: Array.from(document.getElementById('rows').rows, (row) => + Array.from(row.cells, (cell) => cell.textContent) + ), + summary: document.getElementById('summary').textContent + };` + ) + .catch(() => undefined); + + return page?.indicator === indicator; + }, + WORKBENCH_TIMEOUT, + `the dataframe site did not show "${indicator}"` + ); + } catch (error) { + throw new Error(`${(error as Error).message}. Last read: ${JSON.stringify(page)}`); + } + + return page!; +} + async function onIntegratedBrowserPage(title: string, read: () => Promise): Promise { const driver = VSBrowser.instance.driver; const workbench = await driver.getWindowHandle(); @@ -139,11 +237,11 @@ async function onIntegratedBrowserPage(title: string, read: () => Promise) } async function runWithRegion( - region: string, + regionOptionId: string, timeout = WORKBENCH_TIMEOUT ): Promise<{ status: string; result: unknown }> { const driver = VSBrowser.instance.driver; - await driver.findElement(By.css(`#region option[value="${region}"]`)).click(); + await driver.findElement(By.id(regionOptionId)).click(); await driver.findElement(By.id('run')).click(); let status = ''; await driver.wait( @@ -153,7 +251,7 @@ async function runWithRegion( return status !== 'running'; }, timeout, - `the run with region "${region}" did not finish` + `the run with ${regionOptionId} chosen did not finish` ); const result = await driver.findElement(By.id('result')).getText(); @@ -177,6 +275,23 @@ async function findRootExplorerItem(label: string): Promise { return found!; } +/** Looks the parent up again on every try, so a row the Explorer has re-rendered is not held stale. */ +async function findExplorerChildItem(parentLabel: string, label: string): Promise { + let found: TreeItem | undefined; + await VSBrowser.instance.driver.wait( + async () => { + const parent = (await findRootExplorerItem(parentLabel)) as TreeItem; + found = await parent.findChildItem(label).catch(() => undefined); + + return found !== undefined; + }, + WORKBENCH_TIMEOUT, + `"${label}" did not appear under "${parentLabel}" in the file explorer` + ); + + return found!; +} + /** In the simple folder dialog, OK first navigates toward the typed path, so it is clicked until the dialog closes. */ async function previewFromCommandPalette(folder: string): Promise { const driver = VSBrowser.instance.driver; @@ -241,6 +356,37 @@ async function closeAllEditors(): Promise { ); } +/** + * Stores the fixture frame with the venv's deepnote-toolkit, which puts it under `$HOME/work`, as it does for a + * notebook on the extension's servers. Returns the function that removes the frame and the folders the store created. + */ +function storeFrameWithToolkit(): () => void { + const work = path.join(process.env.HOME || os.homedir(), 'work'); + const frames = path.join(work, 'deepnote_dataframes'); + const created = [frames, work].filter((folder) => !fs.existsSync(folder)); + const removeFrame = () => { + fs.rmSync(path.join(frames, FRAME_NAME), { recursive: true, force: true }); + // Only while empty: a kernel of another test may have written to them since. + for (const folder of created.filter((candidate) => fs.existsSync(candidate))) { + try { + fs.rmdirSync(folder); + } catch (error) { + console.warn(`[deepnote-e2e] kept ${folder}:`, error); + } + } + }; + try { + execFileSync(venvPython(), ['-I', STORE_FRAME_SCRIPT, path.join(DATAFRAMES_FIXTURE, FRAME_FILE), FRAME_NAME], { + timeout: STORE_FRAME_TIMEOUT + }); + } catch (error) { + removeFrame(); + throw error; + } + + return removeFrame; +} + describe('Deepnote: Preview App — serve a data app folder in the built-in browser', function () { this.timeout(SUITE_TIMEOUT); @@ -259,6 +405,15 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow return appDir; } + function addDataframesProject(): string { + const project = fs.mkdtempSync(path.join(workspaceDir, 'dataframes-')); + fs.mkdirSync(path.join(project, DATAFRAMES_APP)); + fs.copyFileSync(path.join(DATAFRAMES_FIXTURE, 'index.html'), path.join(project, DATAFRAMES_APP, 'index.html')); + copyFixtureIntoDir(project, PROJECT_FIXTURE); + + return path.basename(project); + } + before(async function () { workspaceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'deepnote-e2e-preview-')); fs.mkdirSync(path.join(workspaceDir, '.vscode')); @@ -370,9 +525,9 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow // The first run starts the notebook file's toolkit server and a kernel. const runs = await onIntegratedBrowserPage(RUNS_TITLE, async () => { - const asia = await runWithRegion('Asia', KERNEL_CONNECT_TIMEOUT); - const americas = await runWithRegion('Americas'); - const noRegion = await runWithRegion(''); + const asia = await runWithRegion('region-asia', KERNEL_CONNECT_TIMEOUT); + const americas = await runWithRegion('region-americas'); + const noRegion = await runWithRegion('region-none'); await screenshot('run-results'); return [asia, americas, noRegion]; @@ -394,7 +549,7 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow await selectDeepnoteContextMenu(await findRootExplorerItem(path.basename(appDir)), 'Preview App'); const report = await onIntegratedBrowserPage(APP_DATA_TITLE, async () => { - const read = await readReport(KERNEL_CONNECT_TIMEOUT); + const read = await readReport(APP_DATA_REPORT_IDS, KERNEL_CONNECT_TIMEOUT); await screenshot('app-data-after-run'); return read; @@ -413,6 +568,47 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow expect(Date.parse(createdAt ?? ''), `the run's createdAt, ${createdAt}`).to.be.within(startedAt, Date.now()); }); + it('pages through a dataframe deepnote-toolkit stored under $HOME/work, its default, across its record batches', async function () { + const screenshot = createScreenshotter(this); + const removeFrame = storeFrameWithToolkit(); + try { + const folder = addDataframesProject(); + await selectDeepnoteContextMenu(await findExplorerChildItem(folder, DATAFRAMES_APP), 'Preview App'); + + await onIntegratedBrowserPage(DATAFRAMES_TITLE, async () => { + const driver = VSBrowser.instance.driver; + const clickButton = (id: string) => driver.findElement(By.id(id)).click(); + const ids = (page: DataframeSitePage) => page.rows.map(([id]) => id); + + const first = await readDataframePage('Page 1 of 20,000'); + expect(first.summary).to.include('200,000 rows · 7 columns'); + expect(first.rows[0]).to.deep.equal(FIRST_ROW); + expect(ids(first)).to.deep.equal(consecutiveIds(0, 10)); + await screenshot('first-page'); + + await clickButton('next'); + expect(ids(await readDataframePage('Page 2 of 20,000'))).to.deep.equal(consecutiveIds(10, 10)); + await screenshot('next-page'); + + // deepnote-toolkit caps a record batch at 65,536 rows, so rows 65,530 to 65,539 straddle two batches. + const pageNumber = driver.findElement(By.id('page-number')); + await pageNumber.clear(); + await pageNumber.sendKeys('6554'); + await clickButton('go'); + expect(ids(await readDataframePage('Page 6,554 of 20,000'))).to.deep.equal(consecutiveIds(65_530, 10)); + await screenshot('across-record-batches'); + + await clickButton('last'); + const last = await readDataframePage('Page 20,000 of 20,000'); + expect(last.rows.at(-1)).to.deep.equal(LAST_ROW); + expect(last.isNextDisabled).to.equal(true); + await screenshot('last-page'); + }); + } finally { + removeFrame(); + } + }); + it('switches to the open tab and reloads it when the same folder is previewed again', async function () { const screenshot = createScreenshotter(this); const driver = VSBrowser.instance.driver; @@ -436,7 +632,7 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow driver.wait( async () => (await driver - .executeScript("return document.querySelector('h1')?.textContent") + .executeScript("return document.getElementById('title')?.textContent") .catch(() => '')) === 'Sales dashboard, edited', WORKBENCH_TIMEOUT, 'the reused tab did not reload'